Fix minor problem in stack probing
[official-gcc.git] / gcc / genmatch.cc
blobe9d7afa7728f5a0d1dce7a3f13cb3f0bbeabc560
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"
32 #include "ordered-hash-map.h"
35 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
36 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
37 size_t, size_t MEM_STAT_DECL)
39 return NULL;
41 void ggc_free (void *)
46 /* Global state. */
48 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
49 unsigned verbose;
52 /* libccp helpers. */
54 static class line_maps *line_table;
56 /* The rich_location class within libcpp requires a way to expand
57 location_t instances, and relies on the client code
58 providing a symbol named
59 linemap_client_expand_location_to_spelling_point
60 to do this.
62 This is the implementation for genmatch. */
64 expanded_location
65 linemap_client_expand_location_to_spelling_point (location_t loc,
66 enum location_aspect)
68 const struct line_map_ordinary *map;
69 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
70 return linemap_expand_location (line_table, map, loc);
73 static bool
74 #if GCC_VERSION >= 4001
75 __attribute__((format (printf, 5, 0)))
76 #endif
77 diagnostic_cb (cpp_reader *, enum cpp_diagnostic_level errtype,
78 enum cpp_warning_reason, rich_location *richloc,
79 const char *msg, va_list *ap)
81 const line_map_ordinary *map;
82 location_t location = richloc->get_loc ();
83 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
84 expanded_location loc = linemap_expand_location (line_table, map, location);
85 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
86 (errtype == CPP_DL_WARNING) ? "warning" : "error");
87 vfprintf (stderr, msg, *ap);
88 fprintf (stderr, "\n");
89 FILE *f = fopen (loc.file, "r");
90 if (f)
92 char buf[128];
93 while (loc.line > 0)
95 if (!fgets (buf, 128, f))
96 goto notfound;
97 if (buf[strlen (buf) - 1] != '\n')
99 if (loc.line > 1)
100 loc.line++;
102 loc.line--;
104 fprintf (stderr, "%s", buf);
105 for (int i = 0; i < loc.column - 1; ++i)
106 fputc (' ', stderr);
107 fputc ('^', stderr);
108 fputc ('\n', stderr);
109 notfound:
110 fclose (f);
113 if (errtype == CPP_DL_FATAL)
114 exit (1);
115 return false;
118 static void
119 #if GCC_VERSION >= 4001
120 __attribute__((format (printf, 2, 3)))
121 #endif
122 fatal_at (const cpp_token *tk, const char *msg, ...)
124 rich_location richloc (line_table, tk->src_loc);
125 va_list ap;
126 va_start (ap, msg);
127 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
128 va_end (ap);
131 static void
132 #if GCC_VERSION >= 4001
133 __attribute__((format (printf, 2, 3)))
134 #endif
135 fatal_at (location_t loc, const char *msg, ...)
137 rich_location richloc (line_table, loc);
138 va_list ap;
139 va_start (ap, msg);
140 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
141 va_end (ap);
144 static void
145 #if GCC_VERSION >= 4001
146 __attribute__((format (printf, 2, 3)))
147 #endif
148 warning_at (const cpp_token *tk, const char *msg, ...)
150 rich_location richloc (line_table, tk->src_loc);
151 va_list ap;
152 va_start (ap, msg);
153 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
154 va_end (ap);
157 static void
158 #if GCC_VERSION >= 4001
159 __attribute__((format (printf, 2, 3)))
160 #endif
161 warning_at (location_t loc, const char *msg, ...)
163 rich_location richloc (line_table, loc);
164 va_list ap;
165 va_start (ap, msg);
166 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
167 va_end (ap);
170 /* Like fprintf, but print INDENT spaces at the beginning. */
172 static void
173 #if GCC_VERSION >= 4001
174 __attribute__((format (printf, 3, 4)))
175 #endif
176 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
178 va_list ap;
179 for (; indent >= 8; indent -= 8)
180 fputc ('\t', f);
181 fprintf (f, "%*s", indent, "");
182 va_start (ap, format);
183 vfprintf (f, format, ap);
184 va_end (ap);
187 /* Secondary stream for fp_decl. */
188 static FILE *header_file;
190 /* Start or continue emitting a declaration in fprintf-like manner,
191 printing both to F and global header_file, if non-null. */
192 static void
193 #if GCC_VERSION >= 4001
194 __attribute__((format (printf, 2, 3)))
195 #endif
196 fp_decl (FILE *f, const char *format, ...)
198 va_list ap;
199 va_start (ap, format);
200 vfprintf (f, format, ap);
201 va_end (ap);
203 if (!header_file)
204 return;
206 va_start (ap, format);
207 vfprintf (header_file, format, ap);
208 va_end (ap);
211 /* Finish a declaration being emitted by fp_decl. */
212 static void
213 fp_decl_done (FILE *f, const char *trailer)
215 fprintf (f, "%s\n", trailer);
216 if (header_file)
217 fprintf (header_file, "%s;", trailer);
220 /* Line numbers for use by indirect line directives. */
221 static vec<int> dbg_line_numbers;
223 static void
224 write_header_declarations (bool gimple, FILE *f)
226 fprintf (f, "\nextern void\n%s_dump_logs (const char *file1, int line1_id, "
227 "const char *file2, int line2, bool simplify);\n",
228 gimple ? "gimple" : "generic");
231 static void
232 define_dump_logs (bool gimple, FILE *f)
234 if (dbg_line_numbers.is_empty ())
235 return;
237 fprintf (f , "void\n%s_dump_logs (const char *file1, int line1_id, "
238 "const char *file2, int line2, bool simplify)\n{\n",
239 gimple ? "gimple" : "generic");
241 fprintf_indent (f, 2, "static int dbg_line_numbers[%d] = {",
242 dbg_line_numbers.length ());
244 for (unsigned i = 0; i < dbg_line_numbers.length () - 1; i++)
246 if (i % 20 == 0)
247 fprintf (f, "\n\t");
249 fprintf (f, "%d, ", dbg_line_numbers[i]);
251 fprintf (f, "%d\n };\n\n", dbg_line_numbers.last ());
254 fprintf_indent (f, 2, "fprintf (dump_file, \"%%s "
255 "%%s:%%d, %%s:%%d\\n\",\n");
256 fprintf_indent (f, 10, "simplify ? \"Applying pattern\" : "
257 "\"Matching expression\", file1, "
258 "dbg_line_numbers[line1_id], file2, line2);");
260 fprintf (f, "\n}\n\n");
263 static void
264 output_line_directive (FILE *f, location_t location,
265 bool dumpfile = false, bool fnargs = false,
266 bool indirect_line_numbers = false)
268 typedef pair_hash<nofree_string_hash, int_hash<int, -1>> location_hash;
269 static hash_map<location_hash, int> loc_id_map;
270 const line_map_ordinary *map;
271 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
272 expanded_location loc = linemap_expand_location (line_table, map, location);
273 if (dumpfile)
275 /* When writing to a dumpfile only dump the filename. */
276 const char *file = strrchr (loc.file, DIR_SEPARATOR);
277 #if defined(DIR_SEPARATOR_2)
278 const char *pos2 = strrchr (loc.file, DIR_SEPARATOR_2);
279 if (pos2 && (!file || (pos2 > file)))
280 file = pos2;
281 #endif
282 if (!file)
283 file = loc.file;
284 else
285 ++file;
287 if (fnargs)
289 if (indirect_line_numbers)
291 bool existed;
292 int &loc_id = loc_id_map.get_or_insert (
293 std::make_pair (file, loc.line), &existed);
294 if (!existed)
296 loc_id = dbg_line_numbers.length ();
297 dbg_line_numbers.safe_push (loc.line);
300 fprintf (f, "\"%s\", %d", file, loc_id);
302 else
303 fprintf (f, "\"%s\", %d", file, loc.line);
305 else
306 fprintf (f, "%s:%d", file, loc.line);
308 else if (verbose >= 2)
309 /* Other gen programs really output line directives here, at least for
310 development it's right now more convenient to have line information
311 from the generated file. Still keep the directives as comment for now
312 to easily back-point to the meta-description. */
313 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
316 /* Find the file to write into next. We try to evenly distribute the contents
317 over the different files. */
319 #define SIZED_BASED_CHUNKS 1
321 static FILE *
322 choose_output (const vec<FILE *> &parts)
324 #ifdef SIZED_BASED_CHUNKS
325 FILE *shortest = NULL;
326 long min = 0;
327 for (FILE *part : parts)
329 long len = ftell (part);
330 if (!shortest || min > len)
331 shortest = part, min = len;
333 return shortest;
334 #else
335 static int current_file;
336 return parts[current_file++ % parts.length ()];
337 #endif
341 /* Pull in tree codes and builtin function codes from their
342 definition files. */
344 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
345 enum tree_code {
346 #include "tree.def"
347 MAX_TREE_CODES
349 #undef DEFTREECODE
351 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
352 enum built_in_function {
353 #include "builtins.def"
354 END_BUILTINS
357 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
358 enum internal_fn {
359 #include "internal-fn.def"
360 IFN_LAST
363 enum combined_fn {
364 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
365 CFN_##ENUM = int (ENUM),
366 #include "builtins.def"
368 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) \
369 CFN_##CODE = int (END_BUILTINS) + int (IFN_##CODE),
370 #include "internal-fn.def"
372 CFN_LAST
375 #include "case-cfn-macros.h"
377 /* Return true if CODE represents a commutative tree code. Otherwise
378 return false. */
379 bool
380 commutative_tree_code (enum tree_code code)
382 switch (code)
384 case PLUS_EXPR:
385 case MULT_EXPR:
386 case MULT_HIGHPART_EXPR:
387 case MIN_EXPR:
388 case MAX_EXPR:
389 case BIT_IOR_EXPR:
390 case BIT_XOR_EXPR:
391 case BIT_AND_EXPR:
392 case NE_EXPR:
393 case EQ_EXPR:
394 case UNORDERED_EXPR:
395 case ORDERED_EXPR:
396 case UNEQ_EXPR:
397 case LTGT_EXPR:
398 case TRUTH_AND_EXPR:
399 case TRUTH_XOR_EXPR:
400 case TRUTH_OR_EXPR:
401 case WIDEN_MULT_EXPR:
402 case VEC_WIDEN_MULT_HI_EXPR:
403 case VEC_WIDEN_MULT_LO_EXPR:
404 case VEC_WIDEN_MULT_EVEN_EXPR:
405 case VEC_WIDEN_MULT_ODD_EXPR:
406 return true;
408 default:
409 break;
411 return false;
414 /* Return true if CODE represents a ternary tree code for which the
415 first two operands are commutative. Otherwise return false. */
416 bool
417 commutative_ternary_tree_code (enum tree_code code)
419 switch (code)
421 case WIDEN_MULT_PLUS_EXPR:
422 case WIDEN_MULT_MINUS_EXPR:
423 case DOT_PROD_EXPR:
424 return true;
426 default:
427 break;
429 return false;
432 /* Return true if CODE is a comparison. */
434 bool
435 comparison_code_p (enum tree_code code)
437 switch (code)
439 case EQ_EXPR:
440 case NE_EXPR:
441 case ORDERED_EXPR:
442 case UNORDERED_EXPR:
443 case LTGT_EXPR:
444 case UNEQ_EXPR:
445 case GT_EXPR:
446 case GE_EXPR:
447 case LT_EXPR:
448 case LE_EXPR:
449 case UNGT_EXPR:
450 case UNGE_EXPR:
451 case UNLT_EXPR:
452 case UNLE_EXPR:
453 return true;
455 default:
456 break;
458 return false;
462 /* Base class for all identifiers the parser knows. */
464 class id_base : public nofree_ptr_hash<id_base>
466 public:
467 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
469 id_base (id_kind, const char *, int = -1);
471 hashval_t hashval;
472 int nargs;
473 const char *id;
475 /* hash_table support. */
476 static inline hashval_t hash (const id_base *);
477 static inline int equal (const id_base *, const id_base *);
480 inline hashval_t
481 id_base::hash (const id_base *op)
483 return op->hashval;
486 inline int
487 id_base::equal (const id_base *op1,
488 const id_base *op2)
490 return (op1->hashval == op2->hashval
491 && strcmp (op1->id, op2->id) == 0);
494 /* The special id "null", which matches nothing. */
495 static id_base *null_id;
497 /* Hashtable of known pattern operators. This is pre-seeded from
498 all known tree codes and all known builtin function ids. */
499 static hash_table<id_base> *operators;
501 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
503 kind = kind_;
504 id = id_;
505 nargs = nargs_;
506 hashval = htab_hash_string (id);
509 /* Identifier that maps to a tree code. */
511 class operator_id : public id_base
513 public:
514 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
515 const char *tcc_)
516 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
517 enum tree_code code;
518 const char *tcc;
521 /* Identifier that maps to a builtin or internal function code. */
523 class fn_id : public id_base
525 public:
526 fn_id (enum built_in_function fn_, const char *id_)
527 : id_base (id_base::FN, id_), fn (fn_) {}
528 fn_id (enum internal_fn fn_, const char *id_)
529 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
530 unsigned int fn;
533 class simplify;
535 /* Identifier that maps to a user-defined predicate. */
537 class predicate_id : public id_base
539 public:
540 predicate_id (const char *id_)
541 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
542 vec<simplify *> matchers;
545 /* Identifier that maps to a operator defined by a 'for' directive. */
547 class user_id : public id_base
549 public:
550 user_id (const char *id_, bool is_oper_list_ = false)
551 : id_base (id_base::USER, id_), substitutes (vNULL),
552 used (false), is_oper_list (is_oper_list_) {}
553 vec<id_base *> substitutes;
554 bool used;
555 bool is_oper_list;
558 template<>
559 template<>
560 inline bool
561 is_a_helper <fn_id *>::test (id_base *id)
563 return id->kind == id_base::FN;
566 template<>
567 template<>
568 inline bool
569 is_a_helper <operator_id *>::test (id_base *id)
571 return id->kind == id_base::CODE;
574 template<>
575 template<>
576 inline bool
577 is_a_helper <predicate_id *>::test (id_base *id)
579 return id->kind == id_base::PREDICATE;
582 template<>
583 template<>
584 inline bool
585 is_a_helper <user_id *>::test (id_base *id)
587 return id->kind == id_base::USER;
590 /* If ID has a pair of consecutive, commutative operands, return the
591 index of the first, otherwise return -1. */
593 static int
594 commutative_op (id_base *id)
596 if (operator_id *code = dyn_cast <operator_id *> (id))
598 if (commutative_tree_code (code->code)
599 || commutative_ternary_tree_code (code->code))
600 return 0;
601 return -1;
603 if (fn_id *fn = dyn_cast <fn_id *> (id))
604 switch (fn->fn)
606 CASE_CFN_FMA:
607 case CFN_FMS:
608 case CFN_FNMA:
609 case CFN_FNMS:
610 return 0;
612 case CFN_COND_ADD:
613 case CFN_COND_MUL:
614 case CFN_COND_MIN:
615 case CFN_COND_MAX:
616 case CFN_COND_FMIN:
617 case CFN_COND_FMAX:
618 case CFN_COND_AND:
619 case CFN_COND_IOR:
620 case CFN_COND_XOR:
621 case CFN_COND_FMA:
622 case CFN_COND_FMS:
623 case CFN_COND_FNMA:
624 case CFN_COND_FNMS:
625 case CFN_COND_LEN_ADD:
626 case CFN_COND_LEN_MUL:
627 case CFN_COND_LEN_MIN:
628 case CFN_COND_LEN_MAX:
629 case CFN_COND_LEN_FMIN:
630 case CFN_COND_LEN_FMAX:
631 case CFN_COND_LEN_AND:
632 case CFN_COND_LEN_IOR:
633 case CFN_COND_LEN_XOR:
634 case CFN_COND_LEN_FMA:
635 case CFN_COND_LEN_FMS:
636 case CFN_COND_LEN_FNMA:
637 case CFN_COND_LEN_FNMS:
638 return 1;
640 default:
641 return -1;
643 if (user_id *uid = dyn_cast<user_id *> (id))
645 int res = commutative_op (uid->substitutes[0]);
646 if (res < 0)
647 return -1;
648 for (unsigned i = 1; i < uid->substitutes.length (); ++i)
649 if (res != commutative_op (uid->substitutes[i]))
650 return -1;
651 return res;
653 return -1;
656 /* Add a predicate identifier to the hash. */
658 static predicate_id *
659 add_predicate (const char *id)
661 predicate_id *p = new predicate_id (id);
662 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
663 if (*slot)
664 fatal ("duplicate id definition");
665 *slot = p;
666 return p;
669 /* Add a tree code identifier to the hash. */
671 static void
672 add_operator (enum tree_code code, const char *id,
673 const char *tcc, unsigned nargs)
675 if (strcmp (tcc, "tcc_unary") != 0
676 && strcmp (tcc, "tcc_binary") != 0
677 && strcmp (tcc, "tcc_comparison") != 0
678 && strcmp (tcc, "tcc_expression") != 0
679 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
680 && strcmp (tcc, "tcc_reference") != 0
681 /* To have INTEGER_CST and friends as "predicate operators". */
682 && strcmp (tcc, "tcc_constant") != 0
683 /* And allow CONSTRUCTOR for vector initializers. */
684 && !(code == CONSTRUCTOR)
685 /* Allow SSA_NAME as predicate operator. */
686 && !(code == SSA_NAME))
687 return;
688 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
689 if (code == ADDR_EXPR)
690 nargs = 0;
691 operator_id *op = new operator_id (code, id, nargs, tcc);
692 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
693 if (*slot)
694 fatal ("duplicate id definition");
695 *slot = op;
698 /* Add a built-in or internal function identifier to the hash. ID is
699 the name of its CFN_* enumeration value. */
701 template <typename T>
702 static void
703 add_function (T code, const char *id)
705 fn_id *fn = new fn_id (code, id);
706 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
707 if (*slot)
708 fatal ("duplicate id definition");
709 *slot = fn;
712 /* Helper for easy comparing ID with tree code CODE. */
714 static bool
715 operator==(id_base &id, enum tree_code code)
717 if (operator_id *oid = dyn_cast <operator_id *> (&id))
718 return oid->code == code;
719 return false;
722 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
724 id_base *
725 get_operator (const char *id, bool allow_null = false)
727 if (allow_null && strcmp (id, "null") == 0)
728 return null_id;
730 id_base tem (id_base::CODE, id);
732 id_base *op = operators->find_with_hash (&tem, tem.hashval);
733 if (op)
735 /* If this is a user-defined identifier track whether it was used. */
736 if (user_id *uid = dyn_cast<user_id *> (op))
737 uid->used = true;
738 return op;
741 char *id2;
742 bool all_upper = true;
743 bool all_lower = true;
744 for (unsigned int i = 0; id[i]; ++i)
745 if (ISUPPER (id[i]))
746 all_lower = false;
747 else if (ISLOWER (id[i]))
748 all_upper = false;
749 if (all_lower)
751 /* Try in caps with _EXPR appended. */
752 id2 = ACONCAT ((id, "_EXPR", NULL));
753 for (unsigned int i = 0; id2[i]; ++i)
754 id2[i] = TOUPPER (id2[i]);
756 else if (all_upper && startswith (id, "IFN_"))
757 /* Try CFN_ instead of IFN_. */
758 id2 = ACONCAT (("CFN_", id + 4, NULL));
759 else if (all_upper && startswith (id, "BUILT_IN_"))
760 /* Try prepending CFN_. */
761 id2 = ACONCAT (("CFN_", id, NULL));
762 else
763 return NULL;
765 new (&tem) id_base (id_base::CODE, id2);
766 return operators->find_with_hash (&tem, tem.hashval);
769 /* Return the comparison operators that results if the operands are
770 swapped. This is safe for floating-point. */
772 id_base *
773 swap_tree_comparison (operator_id *p)
775 switch (p->code)
777 case EQ_EXPR:
778 case NE_EXPR:
779 case ORDERED_EXPR:
780 case UNORDERED_EXPR:
781 case LTGT_EXPR:
782 case UNEQ_EXPR:
783 return p;
784 case GT_EXPR:
785 return get_operator ("LT_EXPR");
786 case GE_EXPR:
787 return get_operator ("LE_EXPR");
788 case LT_EXPR:
789 return get_operator ("GT_EXPR");
790 case LE_EXPR:
791 return get_operator ("GE_EXPR");
792 case UNGT_EXPR:
793 return get_operator ("UNLT_EXPR");
794 case UNGE_EXPR:
795 return get_operator ("UNLE_EXPR");
796 case UNLT_EXPR:
797 return get_operator ("UNGT_EXPR");
798 case UNLE_EXPR:
799 return get_operator ("UNGE_EXPR");
800 default:
801 gcc_unreachable ();
805 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
808 /* The AST produced by parsing of the pattern definitions. */
810 class dt_operand;
811 class capture_info;
813 /* The base class for operands. */
815 class operand {
816 public:
817 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
818 operand (enum op_type type_, location_t loc_)
819 : type (type_), location (loc_) {}
820 enum op_type type;
821 location_t location;
822 virtual void gen_transform (FILE *, int, const char *, bool, int,
823 const char *, capture_info *,
824 dt_operand ** = 0,
825 int = 0)
826 { gcc_unreachable (); }
829 /* A predicate operand. Predicates are leafs in the AST. */
831 class predicate : public operand
833 public:
834 predicate (predicate_id *p_, location_t loc)
835 : operand (OP_PREDICATE, loc), p (p_) {}
836 predicate_id *p;
839 /* An operand that constitutes an expression. Expressions include
840 function calls and user-defined predicate invocations. */
842 class expr : public operand
844 public:
845 expr (id_base *operation_, location_t loc, bool is_commutative_ = false)
846 : operand (OP_EXPR, loc), operation (operation_),
847 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
848 is_generic (false), force_single_use (false), force_leaf (false),
849 opt_grp (0) {}
850 expr (expr *e)
851 : operand (OP_EXPR, e->location), operation (e->operation),
852 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
853 is_generic (e->is_generic), force_single_use (e->force_single_use),
854 force_leaf (e->force_leaf), opt_grp (e->opt_grp) {}
855 void append_op (operand *op) { ops.safe_push (op); }
856 /* The operator and its operands. */
857 id_base *operation;
858 vec<operand *> ops;
859 /* An explicitely specified type - used exclusively for conversions. */
860 const char *expr_type;
861 /* Whether the operation is to be applied commutatively. This is
862 later lowered to two separate patterns. */
863 bool is_commutative;
864 /* Whether the expression is expected to be in GENERIC form. */
865 bool is_generic;
866 /* Whether pushing any stmt to the sequence should be conditional
867 on this expression having a single-use. */
868 bool force_single_use;
869 /* Whether in the result expression this should be a leaf node
870 with any children simplified down to simple operands. */
871 bool force_leaf;
872 /* If non-zero, the group for optional handling. */
873 unsigned char opt_grp;
874 void gen_transform (FILE *f, int, const char *, bool, int,
875 const char *, capture_info *,
876 dt_operand ** = 0, int = 0) override;
879 /* An operator that is represented by native C code. This is always
880 a leaf operand in the AST. This class is also used to represent
881 the code to be generated for 'if' and 'with' expressions. */
883 class c_expr : public operand
885 public:
886 /* A mapping of an identifier and its replacement. Used to apply
887 'for' lowering. */
888 class id_tab {
889 public:
890 const char *id;
891 const char *oper;
892 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
895 c_expr (cpp_reader *r_, location_t loc,
896 vec<cpp_token> code_, unsigned nr_stmts_,
897 vec<id_tab> ids_, cid_map_t *capture_ids_)
898 : operand (OP_C_EXPR, loc), r (r_), code (code_),
899 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
900 /* cpplib tokens and state to transform this back to source. */
901 cpp_reader *r;
902 vec<cpp_token> code;
903 cid_map_t *capture_ids;
904 /* The number of statements parsed (well, the number of ';'s). */
905 unsigned nr_stmts;
906 /* The identifier replacement vector. */
907 vec<id_tab> ids;
908 void gen_transform (FILE *f, int, const char *, bool, int,
909 const char *, capture_info *,
910 dt_operand ** = 0, int = 0) final override;
913 /* A wrapper around another operand that captures its value. */
915 class capture : public operand
917 public:
918 capture (location_t loc, unsigned where_, operand *what_, bool value_)
919 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
920 what (what_) {}
921 /* Identifier index for the value. */
922 unsigned where;
923 /* Whether in a match of two operands the compare should be for
924 equal values rather than equal atoms (boils down to a type
925 check or not). */
926 bool value_match;
927 /* The captured value. */
928 operand *what;
929 void gen_transform (FILE *f, int, const char *, bool, int,
930 const char *, capture_info *,
931 dt_operand ** = 0, int = 0) final override;
934 /* if expression. */
936 class if_expr : public operand
938 public:
939 if_expr (location_t loc)
940 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
941 c_expr *cond;
942 operand *trueexpr;
943 operand *falseexpr;
946 /* with expression. */
948 class with_expr : public operand
950 public:
951 with_expr (location_t loc)
952 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
953 c_expr *with;
954 operand *subexpr;
957 template<>
958 template<>
959 inline bool
960 is_a_helper <capture *>::test (operand *op)
962 return op->type == operand::OP_CAPTURE;
965 template<>
966 template<>
967 inline bool
968 is_a_helper <predicate *>::test (operand *op)
970 return op->type == operand::OP_PREDICATE;
973 template<>
974 template<>
975 inline bool
976 is_a_helper <c_expr *>::test (operand *op)
978 return op->type == operand::OP_C_EXPR;
981 template<>
982 template<>
983 inline bool
984 is_a_helper <expr *>::test (operand *op)
986 return op->type == operand::OP_EXPR;
989 template<>
990 template<>
991 inline bool
992 is_a_helper <if_expr *>::test (operand *op)
994 return op->type == operand::OP_IF;
997 template<>
998 template<>
999 inline bool
1000 is_a_helper <with_expr *>::test (operand *op)
1002 return op->type == operand::OP_WITH;
1005 /* The main class of a pattern and its transform. This is used to
1006 represent both (simplify ...) and (match ...) kinds. The AST
1007 duplicates all outer 'if' and 'for' expressions here so each
1008 simplify can exist in isolation. */
1010 class simplify
1012 public:
1013 enum simplify_kind { SIMPLIFY, MATCH };
1015 simplify (simplify_kind kind_, unsigned id_, operand *match_,
1016 operand *result_, vec<vec<user_id *> > for_vec_,
1017 cid_map_t *capture_ids_)
1018 : kind (kind_), id (id_), match (match_), result (result_),
1019 for_vec (for_vec_), for_subst_vec (vNULL),
1020 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
1022 simplify_kind kind;
1023 /* ID. This is kept to easily associate related simplifies expanded
1024 from the same original one. */
1025 unsigned id;
1026 /* The expression that is matched against the GENERIC or GIMPLE IL. */
1027 operand *match;
1028 /* For a (simplify ...) an expression with ifs and withs with the expression
1029 produced when the pattern applies in the leafs.
1030 For a (match ...) the leafs are either empty if it is a simple predicate
1031 or the single expression specifying the matched operands. */
1032 class operand *result;
1033 /* Collected 'for' expression operators that have to be replaced
1034 in the lowering phase. */
1035 vec<vec<user_id *> > for_vec;
1036 vec<std::pair<user_id *, id_base *> > for_subst_vec;
1037 /* A map of capture identifiers to indexes. */
1038 cid_map_t *capture_ids;
1039 int capture_max;
1042 /* Debugging routines for dumping the AST. */
1044 DEBUG_FUNCTION void
1045 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
1047 if (capture *c = dyn_cast<capture *> (o))
1049 if (c->what && flattened == false)
1050 print_operand (c->what, f, flattened);
1051 fprintf (f, "@%u", c->where);
1054 else if (predicate *p = dyn_cast<predicate *> (o))
1055 fprintf (f, "%s", p->p->id);
1057 else if (is_a<c_expr *> (o))
1058 fprintf (f, "c_expr");
1060 else if (expr *e = dyn_cast<expr *> (o))
1062 if (e->ops.length () == 0)
1063 fprintf (f, "%s", e->operation->id);
1064 else
1066 fprintf (f, "(%s", e->operation->id);
1068 if (flattened == false)
1070 for (unsigned i = 0; i < e->ops.length (); ++i)
1072 putc (' ', f);
1073 print_operand (e->ops[i], f, flattened);
1076 putc (')', f);
1080 else
1081 gcc_unreachable ();
1084 DEBUG_FUNCTION void
1085 print_matches (class simplify *s, FILE *f = stderr)
1087 fprintf (f, "for expression: ");
1088 print_operand (s->match, f);
1089 putc ('\n', f);
1093 /* AST lowering. */
1095 /* Lowering of commutative operators. */
1097 static void
1098 cartesian_product (const vec< vec<operand *> >& ops_vector,
1099 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
1101 if (n == ops_vector.length ())
1103 vec<operand *> xv = v.copy ();
1104 result.safe_push (xv);
1105 return;
1108 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
1110 v[n] = ops_vector[n][i];
1111 cartesian_product (ops_vector, result, v, n + 1);
1115 /* Lower OP to two operands in case it is marked as commutative. */
1117 static vec<operand *>
1118 commutate (operand *op, vec<vec<user_id *> > &for_vec)
1120 vec<operand *> ret = vNULL;
1122 if (capture *c = dyn_cast <capture *> (op))
1124 if (!c->what)
1126 ret.safe_push (op);
1127 return ret;
1129 vec<operand *> v = commutate (c->what, for_vec);
1130 for (unsigned i = 0; i < v.length (); ++i)
1132 capture *nc = new capture (c->location, c->where, v[i],
1133 c->value_match);
1134 ret.safe_push (nc);
1136 return ret;
1139 expr *e = dyn_cast <expr *> (op);
1140 if (!e || e->ops.length () == 0)
1142 ret.safe_push (op);
1143 return ret;
1146 vec< vec<operand *> > ops_vector = vNULL;
1147 for (unsigned i = 0; i < e->ops.length (); ++i)
1148 ops_vector.safe_push (commutate (e->ops[i], for_vec));
1150 auto_vec< vec<operand *> > result;
1151 auto_vec<operand *> v (e->ops.length ());
1152 v.quick_grow_cleared (e->ops.length ());
1153 cartesian_product (ops_vector, result, v, 0);
1156 for (unsigned i = 0; i < result.length (); ++i)
1158 expr *ne = new expr (e);
1159 ne->is_commutative = false;
1160 for (unsigned j = 0; j < result[i].length (); ++j)
1161 ne->append_op (result[i][j]);
1162 ret.safe_push (ne);
1165 if (!e->is_commutative)
1166 return ret;
1168 /* The operation is always binary if it isn't inherently commutative. */
1169 int natural_opno = commutative_op (e->operation);
1170 unsigned int opno = natural_opno >= 0 ? natural_opno : 0;
1171 for (unsigned i = 0; i < result.length (); ++i)
1173 expr *ne = new expr (e);
1174 if (operator_id *r = dyn_cast <operator_id *> (ne->operation))
1176 if (comparison_code_p (r->code))
1177 ne->operation = swap_tree_comparison (r);
1179 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
1181 bool found_compare = false;
1182 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1183 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
1185 if (comparison_code_p (q->code)
1186 && swap_tree_comparison (q) != q)
1188 found_compare = true;
1189 break;
1192 if (found_compare)
1194 user_id *newop = new user_id ("<internal>");
1195 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1197 id_base *subst = p->substitutes[j];
1198 if (operator_id *q = dyn_cast <operator_id *> (subst))
1200 if (comparison_code_p (q->code))
1201 subst = swap_tree_comparison (q);
1203 newop->substitutes.safe_push (subst);
1205 ne->operation = newop;
1206 /* Search for 'p' inside the for vector and push 'newop'
1207 to the same level. */
1208 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
1209 for (unsigned k = 0; k < for_vec[j].length (); ++k)
1210 if (for_vec[j][k] == p)
1212 for_vec[j].safe_push (newop);
1213 newop = NULL;
1214 break;
1218 ne->is_commutative = false;
1219 for (unsigned j = 0; j < result[i].length (); ++j)
1221 int old_j = (j == opno ? opno + 1 : j == opno + 1 ? opno : j);
1222 ne->append_op (result[i][old_j]);
1224 ret.safe_push (ne);
1227 return ret;
1230 /* Lower operations marked as commutative in the AST of S and push
1231 the resulting patterns to SIMPLIFIERS. */
1233 static void
1234 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1236 vec<operand *> matchers = commutate (s->match, s->for_vec);
1237 for (unsigned i = 0; i < matchers.length (); ++i)
1239 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1240 s->for_vec, s->capture_ids);
1241 simplifiers.safe_push (ns);
1245 /* Strip conditional operations using group GRP from O and its
1246 children if STRIP, else replace them with an unconditional operation. */
1248 operand *
1249 lower_opt (operand *o, unsigned char grp, bool strip)
1251 if (capture *c = dyn_cast<capture *> (o))
1253 if (c->what)
1254 return new capture (c->location, c->where,
1255 lower_opt (c->what, grp, strip),
1256 c->value_match);
1257 else
1258 return c;
1261 expr *e = dyn_cast<expr *> (o);
1262 if (!e)
1263 return o;
1265 if (e->opt_grp == grp)
1267 if (strip)
1268 return lower_opt (e->ops[0], grp, strip);
1270 expr *ne = new expr (e);
1271 ne->opt_grp = 0;
1272 ne->append_op (lower_opt (e->ops[0], grp, strip));
1273 return ne;
1276 expr *ne = new expr (e);
1277 for (unsigned i = 0; i < e->ops.length (); ++i)
1278 ne->append_op (lower_opt (e->ops[i], grp, strip));
1280 return ne;
1283 /* Determine whether O or its children uses the conditional operation
1284 group GRP. */
1286 static bool
1287 has_opt (operand *o, unsigned char grp)
1289 if (capture *c = dyn_cast<capture *> (o))
1291 if (c->what)
1292 return has_opt (c->what, grp);
1293 else
1294 return false;
1297 expr *e = dyn_cast<expr *> (o);
1298 if (!e)
1299 return false;
1301 if (e->opt_grp == grp)
1302 return true;
1304 for (unsigned i = 0; i < e->ops.length (); ++i)
1305 if (has_opt (e->ops[i], grp))
1306 return true;
1308 return false;
1311 /* Lower conditional convert operators in O, expanding it to a vector
1312 if required. */
1314 static vec<operand *>
1315 lower_opt (operand *o)
1317 vec<operand *> v1 = vNULL, v2;
1319 v1.safe_push (o);
1321 /* Conditional operations are lowered to a pattern with the
1322 operation and one without. All different conditional operation
1323 groups are lowered separately. */
1325 for (unsigned i = 1; i <= 10; ++i)
1327 v2 = vNULL;
1328 for (unsigned j = 0; j < v1.length (); ++j)
1329 if (has_opt (v1[j], i))
1331 v2.safe_push (lower_opt (v1[j], i, false));
1332 v2.safe_push (lower_opt (v1[j], i, true));
1335 if (v2 != vNULL)
1337 v1 = vNULL;
1338 for (unsigned j = 0; j < v2.length (); ++j)
1339 v1.safe_push (v2[j]);
1343 return v1;
1346 /* Lower conditional convert operators in the AST of S and push
1347 the resulting multiple patterns to SIMPLIFIERS. */
1349 static void
1350 lower_opt (simplify *s, vec<simplify *>& simplifiers)
1352 vec<operand *> matchers = lower_opt (s->match);
1353 for (unsigned i = 0; i < matchers.length (); ++i)
1355 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1356 s->for_vec, s->capture_ids);
1357 simplifiers.safe_push (ns);
1361 /* Lower the compare operand of COND_EXPRs to a
1362 GENERIC and a GIMPLE variant. */
1364 static vec<operand *>
1365 lower_cond (operand *o)
1367 vec<operand *> ro = vNULL;
1369 if (capture *c = dyn_cast<capture *> (o))
1371 if (c->what)
1373 vec<operand *> lop = vNULL;
1374 lop = lower_cond (c->what);
1376 for (unsigned i = 0; i < lop.length (); ++i)
1377 ro.safe_push (new capture (c->location, c->where, lop[i],
1378 c->value_match));
1379 return ro;
1383 expr *e = dyn_cast<expr *> (o);
1384 if (!e || e->ops.length () == 0)
1386 ro.safe_push (o);
1387 return ro;
1390 vec< vec<operand *> > ops_vector = vNULL;
1391 for (unsigned i = 0; i < e->ops.length (); ++i)
1392 ops_vector.safe_push (lower_cond (e->ops[i]));
1394 auto_vec< vec<operand *> > result;
1395 auto_vec<operand *> v (e->ops.length ());
1396 v.quick_grow_cleared (e->ops.length ());
1397 cartesian_product (ops_vector, result, v, 0);
1399 for (unsigned i = 0; i < result.length (); ++i)
1401 expr *ne = new expr (e);
1402 for (unsigned j = 0; j < result[i].length (); ++j)
1403 ne->append_op (result[i][j]);
1404 ro.safe_push (ne);
1405 /* If this is a COND with a captured expression or an
1406 expression with two operands then also match a GENERIC
1407 form on the compare. */
1408 if (*e->operation == COND_EXPR
1409 && ((is_a <capture *> (e->ops[0])
1410 && as_a <capture *> (e->ops[0])->what
1411 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1412 && as_a <expr *>
1413 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1414 || (is_a <expr *> (e->ops[0])
1415 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1417 ne = new expr (e);
1418 for (unsigned j = 0; j < result[i].length (); ++j)
1419 ne->append_op (result[i][j]);
1420 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1422 expr *ocmp = as_a <expr *> (c->what);
1423 expr *cmp = new expr (ocmp);
1424 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1425 cmp->append_op (ocmp->ops[j]);
1426 cmp->is_generic = true;
1427 ne->ops[0] = new capture (c->location, c->where, cmp,
1428 c->value_match);
1430 else
1432 expr *ocmp = as_a <expr *> (ne->ops[0]);
1433 expr *cmp = new expr (ocmp);
1434 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1435 cmp->append_op (ocmp->ops[j]);
1436 cmp->is_generic = true;
1437 ne->ops[0] = cmp;
1439 ro.safe_push (ne);
1443 return ro;
1446 /* Lower the compare operand of COND_EXPRs to a
1447 GENERIC and a GIMPLE variant. */
1449 static void
1450 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1452 vec<operand *> matchers = lower_cond (s->match);
1453 for (unsigned i = 0; i < matchers.length (); ++i)
1455 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1456 s->for_vec, s->capture_ids);
1457 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1458 simplifiers.safe_push (ns);
1462 /* Return true if O refers to ID. */
1464 bool
1465 contains_id (operand *o, user_id *id)
1467 if (capture *c = dyn_cast<capture *> (o))
1468 return c->what && contains_id (c->what, id);
1470 if (expr *e = dyn_cast<expr *> (o))
1472 if (e->operation == id)
1473 return true;
1474 for (unsigned i = 0; i < e->ops.length (); ++i)
1475 if (contains_id (e->ops[i], id))
1476 return true;
1477 return false;
1480 if (with_expr *w = dyn_cast <with_expr *> (o))
1481 return (contains_id (w->with, id)
1482 || contains_id (w->subexpr, id));
1484 if (if_expr *ife = dyn_cast <if_expr *> (o))
1485 return (contains_id (ife->cond, id)
1486 || contains_id (ife->trueexpr, id)
1487 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1489 if (c_expr *ce = dyn_cast<c_expr *> (o))
1490 return ce->capture_ids && ce->capture_ids->get (id->id);
1492 return false;
1496 /* In AST operand O replace operator ID with operator WITH. */
1498 operand *
1499 replace_id (operand *o, user_id *id, id_base *with)
1501 /* Deep-copy captures and expressions, replacing operations as
1502 needed. */
1503 if (capture *c = dyn_cast<capture *> (o))
1505 if (!c->what)
1506 return c;
1507 return new capture (c->location, c->where,
1508 replace_id (c->what, id, with), c->value_match);
1510 else if (expr *e = dyn_cast<expr *> (o))
1512 expr *ne = new expr (e);
1513 if (e->operation == id)
1514 ne->operation = with;
1515 for (unsigned i = 0; i < e->ops.length (); ++i)
1516 ne->append_op (replace_id (e->ops[i], id, with));
1517 return ne;
1519 else if (with_expr *w = dyn_cast <with_expr *> (o))
1521 with_expr *nw = new with_expr (w->location);
1522 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1523 nw->subexpr = replace_id (w->subexpr, id, with);
1524 return nw;
1526 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1528 if_expr *nife = new if_expr (ife->location);
1529 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1530 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1531 if (ife->falseexpr)
1532 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1533 return nife;
1536 /* For c_expr we simply record a string replacement table which is
1537 applied at code-generation time. */
1538 if (c_expr *ce = dyn_cast<c_expr *> (o))
1540 vec<c_expr::id_tab> ids = ce->ids.copy ();
1541 ids.safe_push (c_expr::id_tab (id->id, with->id));
1542 return new c_expr (ce->r, ce->location,
1543 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1546 return o;
1549 /* Return true if the binary operator OP is ok for delayed substitution
1550 during for lowering. */
1552 static bool
1553 binary_ok (operator_id *op)
1555 switch (op->code)
1557 case PLUS_EXPR:
1558 case MINUS_EXPR:
1559 case MULT_EXPR:
1560 case TRUNC_DIV_EXPR:
1561 case CEIL_DIV_EXPR:
1562 case FLOOR_DIV_EXPR:
1563 case ROUND_DIV_EXPR:
1564 case TRUNC_MOD_EXPR:
1565 case CEIL_MOD_EXPR:
1566 case FLOOR_MOD_EXPR:
1567 case ROUND_MOD_EXPR:
1568 case RDIV_EXPR:
1569 case EXACT_DIV_EXPR:
1570 case MIN_EXPR:
1571 case MAX_EXPR:
1572 case BIT_IOR_EXPR:
1573 case BIT_XOR_EXPR:
1574 case BIT_AND_EXPR:
1575 return true;
1576 default:
1577 return false;
1581 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1583 static void
1584 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1586 vec<vec<user_id *> >& for_vec = sin->for_vec;
1587 unsigned worklist_start = 0;
1588 auto_vec<simplify *> worklist;
1589 worklist.safe_push (sin);
1591 /* Lower each recorded for separately, operating on the
1592 set of simplifiers created by the previous one.
1593 Lower inner-to-outer so inner for substitutes can refer
1594 to operators replaced by outer fors. */
1595 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1597 vec<user_id *>& ids = for_vec[fi];
1598 unsigned n_ids = ids.length ();
1599 unsigned max_n_opers = 0;
1600 bool can_delay_subst = true;
1601 for (unsigned i = 0; i < n_ids; ++i)
1603 if (ids[i]->substitutes.length () > max_n_opers)
1604 max_n_opers = ids[i]->substitutes.length ();
1605 /* Require that all substitutes are of the same kind so that
1606 if we delay substitution to the result op code generation
1607 can look at the first substitute for deciding things like
1608 types of operands. */
1609 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1610 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1611 if (ids[i]->substitutes[j]->kind != kind)
1612 can_delay_subst = false;
1613 else if (operator_id *op
1614 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1616 operator_id *op0
1617 = as_a <operator_id *> (ids[i]->substitutes[0]);
1618 if (strcmp (op->tcc, "tcc_comparison") == 0
1619 && strcmp (op0->tcc, "tcc_comparison") == 0)
1621 /* Unfortunately we can't just allow all tcc_binary. */
1622 else if (strcmp (op->tcc, "tcc_binary") == 0
1623 && strcmp (op0->tcc, "tcc_binary") == 0
1624 && binary_ok (op)
1625 && binary_ok (op0))
1627 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1628 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1629 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1630 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1632 else
1633 can_delay_subst = false;
1635 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1637 else
1638 can_delay_subst = false;
1640 if (sin->kind == simplify::MATCH
1641 && can_delay_subst)
1642 continue;
1644 unsigned worklist_end = worklist.length ();
1645 for (unsigned si = worklist_start; si < worklist_end; ++si)
1647 simplify *s = worklist[si];
1648 for (unsigned j = 0; j < max_n_opers; ++j)
1650 operand *match_op = s->match;
1651 operand *result_op = s->result;
1652 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1653 bool skip = false;
1654 for (unsigned i = 0; i < n_ids; ++i)
1656 user_id *id = ids[i];
1657 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1658 if (oper == null_id
1659 && (contains_id (match_op, id)
1660 || contains_id (result_op, id)))
1662 skip = true;
1663 break;
1665 subst.quick_push (std::make_pair (id, oper));
1666 if (sin->kind == simplify::SIMPLIFY
1667 || !can_delay_subst)
1668 match_op = replace_id (match_op, id, oper);
1669 if (result_op
1670 && !can_delay_subst)
1671 result_op = replace_id (result_op, id, oper);
1673 if (skip)
1674 continue;
1676 simplify *ns = new simplify (s->kind, s->id, match_op, result_op,
1677 vNULL, s->capture_ids);
1678 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1679 if (result_op
1680 && can_delay_subst)
1681 ns->for_subst_vec.safe_splice (subst);
1683 worklist.safe_push (ns);
1686 worklist_start = worklist_end;
1689 /* Copy out the result from the last for lowering. */
1690 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1691 simplifiers.safe_push (worklist[i]);
1694 /* Lower the AST for everything in SIMPLIFIERS. */
1696 static void
1697 lower (vec<simplify *>& simplifiers, bool gimple)
1699 auto_vec<simplify *> out_simplifiers;
1700 for (auto s: simplifiers)
1701 lower_opt (s, out_simplifiers);
1703 simplifiers.truncate (0);
1704 for (auto s: out_simplifiers)
1705 lower_commutative (s, simplifiers);
1707 /* Lower for needs to happen before lowering cond
1708 to support (for cnd (cond vec_cond)). This is
1709 safe as substitution delay does not happen for
1710 cond or vec_cond. */
1711 out_simplifiers.truncate (0);
1712 for (auto s: simplifiers)
1713 lower_for (s, out_simplifiers);
1715 simplifiers.truncate (0);
1716 if (gimple)
1717 for (auto s: out_simplifiers)
1718 lower_cond (s, simplifiers);
1719 else
1720 simplifiers.safe_splice (out_simplifiers);
1726 /* The decision tree built for generating GIMPLE and GENERIC pattern
1727 matching code. It represents the 'match' expression of all
1728 simplifies and has those as its leafs. */
1730 class dt_simplify;
1732 /* A hash-map collecting semantically equivalent leafs in the decision
1733 tree for splitting out to separate functions. */
1734 struct sinfo
1736 dt_simplify *s;
1738 const char *fname;
1739 unsigned cnt;
1742 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1743 sinfo *>
1745 static inline hashval_t hash (const key_type &);
1746 static inline bool equal_keys (const key_type &, const key_type &);
1747 template <typename T> static inline void remove (T &) {}
1750 typedef ordered_hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1751 sinfo_map_t;
1753 /* Current simplifier ID we are processing during insertion into the
1754 decision tree. */
1755 static unsigned current_id;
1757 /* Decision tree base class, used for DT_NODE. */
1759 class dt_node
1761 public:
1762 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1764 enum dt_type type;
1765 unsigned level;
1766 dt_node *parent;
1767 vec<dt_node *> kids;
1769 /* Statistics. */
1770 unsigned num_leafs;
1771 unsigned total_size;
1772 unsigned max_level;
1774 dt_node (enum dt_type type_, dt_node *parent_)
1775 : type (type_), level (0), parent (parent_), kids (vNULL) {}
1777 dt_node *append_node (dt_node *);
1778 dt_node *append_op (operand *, dt_node *parent, unsigned pos);
1779 dt_node *append_true_op (operand *, dt_node *parent, unsigned pos);
1780 dt_node *append_match_op (operand *, dt_operand *, dt_node *parent,
1781 unsigned pos);
1782 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1784 virtual void gen (FILE *, int, bool, int) {}
1786 void gen_kids (FILE *, int, bool, int);
1787 void gen_kids_1 (FILE *, int, bool, int,
1788 const vec<dt_operand *> &, const vec<dt_operand *> &,
1789 const vec<dt_operand *> &, const vec<dt_operand *> &,
1790 const vec<dt_operand *> &, const vec<dt_node *> &);
1792 void analyze (sinfo_map_t &);
1795 /* Generic decision tree node used for DT_OPERAND, DT_MATCH and DT_TRUE. */
1797 class dt_operand : public dt_node
1799 public:
1800 operand *op;
1801 dt_operand *match_dop;
1802 unsigned pos;
1803 bool value_match;
1804 unsigned for_id;
1806 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1807 dt_operand *parent_, unsigned pos_)
1808 : dt_node (type, parent_), op (op_), match_dop (match_dop_),
1809 pos (pos_), value_match (false), for_id (current_id) {}
1811 void gen (FILE *, int, bool, int) final override;
1812 unsigned gen_predicate (FILE *, int, const char *, bool);
1813 unsigned gen_match_op (FILE *, int, const char *, bool);
1815 unsigned gen_gimple_expr (FILE *, int, int);
1816 unsigned gen_generic_expr (FILE *, int, const char *);
1818 char *get_name (char *);
1819 void gen_opname (char *, unsigned);
1822 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1824 class dt_simplify : public dt_node
1826 public:
1827 simplify *s;
1828 unsigned pattern_no;
1829 dt_operand **indexes;
1830 sinfo *info;
1832 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1833 : dt_node (DT_SIMPLIFY, NULL), s (s_), pattern_no (pattern_no_),
1834 indexes (indexes_), info (NULL) {}
1836 void gen_1 (FILE *, int, bool, operand *);
1837 void gen (FILE *f, int, bool, int) final override;
1840 template<>
1841 template<>
1842 inline bool
1843 is_a_helper <dt_operand *>::test (dt_node *n)
1845 return (n->type == dt_node::DT_OPERAND
1846 || n->type == dt_node::DT_MATCH
1847 || n->type == dt_node::DT_TRUE);
1850 template<>
1851 template<>
1852 inline bool
1853 is_a_helper <dt_simplify *>::test (dt_node *n)
1855 return n->type == dt_node::DT_SIMPLIFY;
1860 /* A container for the actual decision tree. */
1862 class decision_tree
1864 public:
1865 dt_node *root;
1867 void insert (class simplify *, unsigned);
1868 void gen (vec <FILE *> &f, bool gimple);
1869 void print (FILE *f = stderr);
1871 decision_tree () { root = new dt_node (dt_node::DT_NODE, NULL); }
1873 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1874 unsigned pos = 0, dt_node *parent = 0);
1875 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1876 static bool cmp_node (dt_node *, dt_node *);
1877 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1880 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1882 bool
1883 cmp_operand (operand *o1, operand *o2)
1885 if (!o1 || !o2 || o1->type != o2->type)
1886 return false;
1888 if (o1->type == operand::OP_PREDICATE)
1890 predicate *p1 = as_a<predicate *>(o1);
1891 predicate *p2 = as_a<predicate *>(o2);
1892 return p1->p == p2->p;
1894 else if (o1->type == operand::OP_EXPR)
1896 expr *e1 = static_cast<expr *>(o1);
1897 expr *e2 = static_cast<expr *>(o2);
1898 return (e1->operation == e2->operation
1899 && e1->is_generic == e2->is_generic);
1901 else
1902 return false;
1905 /* Compare two decision tree nodes N1 and N2 and return true if they
1906 are equal. */
1908 bool
1909 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1911 if (!n1 || !n2 || n1->type != n2->type)
1912 return false;
1914 if (n1 == n2)
1915 return true;
1917 if (n1->type == dt_node::DT_TRUE)
1918 return false;
1920 if (n1->type == dt_node::DT_OPERAND)
1921 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1922 (as_a<dt_operand *> (n2))->op);
1923 else if (n1->type == dt_node::DT_MATCH)
1924 return (((as_a<dt_operand *> (n1))->match_dop
1925 == (as_a<dt_operand *> (n2))->match_dop)
1926 && ((as_a<dt_operand *> (n1))->value_match
1927 == (as_a<dt_operand *> (n2))->value_match));
1928 return false;
1931 /* Search OPS for a decision tree node like P and return it if found. */
1933 dt_node *
1934 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1936 /* We can merge adjacent DT_TRUE. */
1937 if (p->type == dt_node::DT_TRUE
1938 && !ops.is_empty ()
1939 && ops.last ()->type == dt_node::DT_TRUE)
1940 return ops.last ();
1941 dt_operand *true_node = NULL;
1942 for (int i = ops.length () - 1; i >= 0; --i)
1944 /* But we can't merge across DT_TRUE nodes as they serve as
1945 pattern order barriers to make sure that patterns apply
1946 in order of appearance in case multiple matches are possible. */
1947 if (ops[i]->type == dt_node::DT_TRUE)
1949 if (! true_node
1950 || as_a <dt_operand *> (ops[i])->for_id > true_node->for_id)
1951 true_node = as_a <dt_operand *> (ops[i]);
1953 if (decision_tree::cmp_node (ops[i], p))
1955 /* Unless we are processing the same pattern or the blocking
1956 pattern is before the one we are going to merge with. */
1957 if (true_node
1958 && true_node->for_id != current_id
1959 && true_node->for_id > as_a <dt_operand *> (ops[i])->for_id)
1961 if (verbose >= 1)
1963 location_t p_loc = 0;
1964 if (p->type == dt_node::DT_OPERAND)
1965 p_loc = as_a <dt_operand *> (p)->op->location;
1966 location_t op_loc = 0;
1967 if (ops[i]->type == dt_node::DT_OPERAND)
1968 op_loc = as_a <dt_operand *> (ops[i])->op->location;
1969 location_t true_loc = 0;
1970 true_loc = true_node->op->location;
1971 warning_at (p_loc,
1972 "failed to merge decision tree node");
1973 warning_at (op_loc,
1974 "with the following");
1975 warning_at (true_loc,
1976 "because of the following which serves as ordering "
1977 "barrier");
1979 return NULL;
1981 return ops[i];
1984 return NULL;
1987 /* Append N to the decision tree if it there is not already an existing
1988 identical child. */
1990 dt_node *
1991 dt_node::append_node (dt_node *n)
1993 dt_node *kid;
1995 kid = decision_tree::find_node (kids, n);
1996 if (kid)
1997 return kid;
1999 kids.safe_push (n);
2000 n->level = this->level + 1;
2002 return n;
2005 /* Append OP to the decision tree. */
2007 dt_node *
2008 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
2010 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
2011 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
2012 return append_node (n);
2015 /* Append a DT_TRUE decision tree node. */
2017 dt_node *
2018 dt_node::append_true_op (operand *op, dt_node *parent, unsigned pos)
2020 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
2021 dt_operand *n = new dt_operand (DT_TRUE, op, 0, parent_, pos);
2022 return append_node (n);
2025 /* Append a DT_MATCH decision tree node. */
2027 dt_node *
2028 dt_node::append_match_op (operand *op, dt_operand *match_dop,
2029 dt_node *parent, unsigned pos)
2031 dt_operand *parent_ = as_a<dt_operand *> (parent);
2032 dt_operand *n = new dt_operand (DT_MATCH, op, match_dop, parent_, pos);
2033 return append_node (n);
2036 /* Append S to the decision tree. */
2038 dt_node *
2039 dt_node::append_simplify (simplify *s, unsigned pattern_no,
2040 dt_operand **indexes)
2042 dt_simplify *s2;
2043 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
2044 for (unsigned i = 0; i < kids.length (); ++i)
2045 if ((s2 = dyn_cast <dt_simplify *> (kids[i]))
2046 && (verbose >= 1
2047 || s->match->location != s2->s->match->location))
2049 /* With a nested patters, it's hard to avoid these in order
2050 to keep match.pd rules relatively small. */
2051 warning_at (s->match->location, "duplicate pattern");
2052 warning_at (s2->s->match->location, "previous pattern defined here");
2053 print_operand (s->match, stderr);
2054 fprintf (stderr, "\n");
2056 return append_node (n);
2059 /* Analyze the node and its children. */
2061 void
2062 dt_node::analyze (sinfo_map_t &map)
2064 num_leafs = 0;
2065 total_size = 1;
2066 max_level = level;
2068 if (type == DT_SIMPLIFY)
2070 /* Populate the map of equivalent simplifies. */
2071 dt_simplify *s = as_a <dt_simplify *> (this);
2072 bool existed;
2073 sinfo *&si = map.get_or_insert (s, &existed);
2074 if (!existed)
2076 si = new sinfo;
2077 si->s = s;
2078 si->cnt = 1;
2079 si->fname = NULL;
2081 else
2082 si->cnt++;
2083 s->info = si;
2084 num_leafs = 1;
2085 return;
2088 for (unsigned i = 0; i < kids.length (); ++i)
2090 kids[i]->analyze (map);
2091 num_leafs += kids[i]->num_leafs;
2092 total_size += kids[i]->total_size;
2093 max_level = MAX (max_level, kids[i]->max_level);
2097 /* Insert O into the decision tree and return the decision tree node found
2098 or created. */
2100 dt_node *
2101 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
2102 unsigned pos, dt_node *parent)
2104 dt_node *q, *elm = 0;
2106 if (capture *c = dyn_cast<capture *> (o))
2108 unsigned capt_index = c->where;
2110 if (indexes[capt_index] == 0)
2112 if (c->what)
2113 q = insert_operand (p, c->what, indexes, pos, parent);
2114 else
2116 q = elm = p->append_true_op (o, parent, pos);
2117 goto at_assert_elm;
2119 // get to the last capture
2120 for (operand *what = c->what;
2121 what && is_a<capture *> (what);
2122 c = as_a<capture *> (what), what = c->what)
2125 if (!c->what)
2127 unsigned cc_index = c->where;
2128 dt_operand *match_op = indexes[cc_index];
2130 dt_operand temp (dt_node::DT_TRUE, 0, 0, 0, 0);
2131 elm = decision_tree::find_node (p->kids, &temp);
2133 if (elm == 0)
2135 dt_operand match (dt_node::DT_MATCH, 0, match_op, 0, 0);
2136 match.value_match = c->value_match;
2137 elm = decision_tree::find_node (p->kids, &match);
2140 else
2142 dt_operand temp (dt_node::DT_OPERAND, c->what, 0, 0, 0);
2143 elm = decision_tree::find_node (p->kids, &temp);
2146 at_assert_elm:
2147 gcc_assert (elm->type == dt_node::DT_TRUE
2148 || elm->type == dt_node::DT_OPERAND
2149 || elm->type == dt_node::DT_MATCH);
2150 indexes[capt_index] = static_cast<dt_operand *> (elm);
2151 return q;
2153 else
2155 p = p->append_match_op (o, indexes[capt_index], parent, pos);
2156 as_a <dt_operand *>(p)->value_match = c->value_match;
2157 if (c->what)
2158 return insert_operand (p, c->what, indexes, 0, p);
2159 else
2160 return p;
2163 p = p->append_op (o, parent, pos);
2164 q = p;
2166 if (expr *e = dyn_cast <expr *>(o))
2168 for (unsigned i = 0; i < e->ops.length (); ++i)
2169 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
2172 return q;
2175 /* Insert S into the decision tree. */
2177 void
2178 decision_tree::insert (class simplify *s, unsigned pattern_no)
2180 current_id = s->id;
2181 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
2182 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
2183 p->append_simplify (s, pattern_no, indexes);
2186 /* Debug functions to dump the decision tree. */
2188 DEBUG_FUNCTION void
2189 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
2191 if (p->type == dt_node::DT_NODE)
2192 fprintf (f, "root");
2193 else
2195 fprintf (f, "|");
2196 for (unsigned i = 0; i < indent; i++)
2197 fprintf (f, "-");
2199 if (p->type == dt_node::DT_OPERAND)
2201 dt_operand *dop = static_cast<dt_operand *>(p);
2202 print_operand (dop->op, f, true);
2204 else if (p->type == dt_node::DT_TRUE)
2205 fprintf (f, "true");
2206 else if (p->type == dt_node::DT_MATCH)
2207 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
2208 else if (p->type == dt_node::DT_SIMPLIFY)
2210 dt_simplify *s = static_cast<dt_simplify *> (p);
2211 fprintf (f, "simplify_%u { ", s->pattern_no);
2212 for (int i = 0; i <= s->s->capture_max; ++i)
2213 fprintf (f, "%p, ", (void *) s->indexes[i]);
2214 fprintf (f, " } ");
2216 if (is_a <dt_operand *> (p))
2217 fprintf (f, " [%u]", as_a <dt_operand *> (p)->for_id);
2220 fprintf (stderr, " (%p, %p), %u, %u\n",
2221 (void *) p, (void *) p->parent, p->level, p->kids.length ());
2223 for (unsigned i = 0; i < p->kids.length (); ++i)
2224 decision_tree::print_node (p->kids[i], f, indent + 2);
2227 DEBUG_FUNCTION void
2228 decision_tree::print (FILE *f)
2230 return decision_tree::print_node (root, f);
2234 /* For GENERIC we have to take care of wrapping multiple-used
2235 expressions with side-effects in save_expr and preserve side-effects
2236 of expressions with omit_one_operand. Analyze captures in
2237 match, result and with expressions and perform early-outs
2238 on the outermost match expression operands for cases we cannot
2239 handle. */
2241 class capture_info
2243 public:
2244 capture_info (simplify *s, operand *, bool);
2245 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
2246 bool walk_result (operand *o, bool, operand *);
2247 void walk_c_expr (c_expr *);
2249 struct cinfo
2251 bool expr_p;
2252 bool cse_p;
2253 bool force_no_side_effects_p;
2254 bool force_single_use;
2255 bool cond_expr_cond_p;
2256 unsigned long toplevel_msk;
2257 unsigned match_use_count;
2258 unsigned result_use_count;
2259 unsigned same_as;
2260 capture *c;
2263 auto_vec<cinfo> info;
2264 unsigned long force_no_side_effects;
2265 bool gimple;
2268 /* Analyze captures in S. */
2270 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
2272 gimple = gimple_;
2274 expr *e;
2275 if (s->kind == simplify::MATCH)
2277 force_no_side_effects = -1;
2278 return;
2281 force_no_side_effects = 0;
2282 info.safe_grow_cleared (s->capture_max + 1, true);
2283 for (int i = 0; i <= s->capture_max; ++i)
2284 info[i].same_as = i;
2286 e = as_a <expr *> (s->match);
2287 for (unsigned i = 0; i < e->ops.length (); ++i)
2288 walk_match (e->ops[i], i,
2289 (i != 0 && *e->operation == COND_EXPR)
2290 || *e->operation == TRUTH_ANDIF_EXPR
2291 || *e->operation == TRUTH_ORIF_EXPR,
2292 i == 0 && *e->operation == COND_EXPR);
2294 walk_result (s->result, false, result);
2297 /* Analyze captures in the match expression piece O. */
2299 void
2300 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2301 bool conditional_p, bool cond_expr_cond_p)
2303 if (capture *c = dyn_cast <capture *> (o))
2305 unsigned where = c->where;
2306 info[where].match_use_count++;
2307 info[where].toplevel_msk |= 1 << toplevel_arg;
2308 info[where].force_no_side_effects_p |= conditional_p;
2309 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2310 if (!info[where].c)
2311 info[where].c = c;
2312 if (!c->what)
2313 return;
2314 /* Recurse to exprs and captures. */
2315 if (is_a <capture *> (c->what)
2316 || is_a <expr *> (c->what))
2317 walk_match (c->what, toplevel_arg, conditional_p, false);
2318 /* We need to look past multiple captures to find a captured
2319 expression as with conditional converts two captures
2320 can be collapsed onto the same expression. Also collect
2321 what captures capture the same thing. */
2322 while (c->what && is_a <capture *> (c->what))
2324 c = as_a <capture *> (c->what);
2325 if (info[c->where].same_as != c->where
2326 && info[c->where].same_as != info[where].same_as)
2327 fatal_at (c->location, "cannot handle this collapsed capture");
2328 info[c->where].same_as = info[where].same_as;
2330 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2331 expr *e;
2332 if (c->what
2333 && (e = dyn_cast <expr *> (c->what)))
2335 /* Zero-operand expression captures like ADDR_EXPR@0 are
2336 similar as predicates -- if they are not mentioned in
2337 the result we have to force them to have no side-effects. */
2338 if (e->ops.length () != 0)
2339 info[where].expr_p = true;
2340 info[where].force_single_use |= e->force_single_use;
2343 else if (expr *e = dyn_cast <expr *> (o))
2345 for (unsigned i = 0; i < e->ops.length (); ++i)
2347 bool cond_p = conditional_p;
2348 bool expr_cond_p = false;
2349 if (i != 0 && *e->operation == COND_EXPR)
2350 cond_p = true;
2351 else if (*e->operation == TRUTH_ANDIF_EXPR
2352 || *e->operation == TRUTH_ORIF_EXPR)
2353 cond_p = true;
2354 if (i == 0
2355 && *e->operation == COND_EXPR)
2356 expr_cond_p = true;
2357 walk_match (e->ops[i], toplevel_arg, cond_p, expr_cond_p);
2360 else if (is_a <predicate *> (o))
2362 /* Mark non-captured leafs toplevel arg for checking. */
2363 force_no_side_effects |= 1 << toplevel_arg;
2364 if (verbose >= 1
2365 && !gimple)
2366 warning_at (o->location,
2367 "forcing no side-effects on possibly lost leaf");
2369 else
2370 gcc_unreachable ();
2373 /* Analyze captures in the result expression piece O. Return true
2374 if RESULT was visited in one of the children. Only visit
2375 non-if/with children if they are rooted on RESULT. */
2377 bool
2378 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2380 if (capture *c = dyn_cast <capture *> (o))
2382 unsigned where = info[c->where].same_as;
2383 info[where].result_use_count++;
2384 /* If we substitute an expression capture we don't know
2385 which captures this will end up using (well, we don't
2386 compute that). Force the uses to be side-effect free
2387 which means forcing the toplevels that reach the
2388 expression side-effect free. */
2389 if (info[where].expr_p)
2390 force_no_side_effects |= info[where].toplevel_msk;
2391 /* Mark CSE capture uses as forced to have no side-effects. */
2392 if (c->what
2393 && is_a <expr *> (c->what))
2395 info[where].cse_p = true;
2396 walk_result (c->what, true, result);
2399 else if (expr *e = dyn_cast <expr *> (o))
2401 id_base *opr = e->operation;
2402 if (user_id *uid = dyn_cast <user_id *> (opr))
2403 opr = uid->substitutes[0];
2404 for (unsigned i = 0; i < e->ops.length (); ++i)
2406 bool cond_p = conditional_p;
2407 if (i != 0 && *e->operation == COND_EXPR)
2408 cond_p = true;
2409 else if (*e->operation == TRUTH_ANDIF_EXPR
2410 || *e->operation == TRUTH_ORIF_EXPR)
2411 cond_p = true;
2412 walk_result (e->ops[i], cond_p, result);
2415 else if (if_expr *ie = dyn_cast <if_expr *> (o))
2417 /* 'if' conditions should be all fine. */
2418 if (ie->trueexpr == result)
2420 walk_result (ie->trueexpr, false, result);
2421 return true;
2423 if (ie->falseexpr == result)
2425 walk_result (ie->falseexpr, false, result);
2426 return true;
2428 bool res = false;
2429 if (is_a <if_expr *> (ie->trueexpr)
2430 || is_a <with_expr *> (ie->trueexpr))
2431 res |= walk_result (ie->trueexpr, false, result);
2432 if (ie->falseexpr
2433 && (is_a <if_expr *> (ie->falseexpr)
2434 || is_a <with_expr *> (ie->falseexpr)))
2435 res |= walk_result (ie->falseexpr, false, result);
2436 return res;
2438 else if (with_expr *we = dyn_cast <with_expr *> (o))
2440 bool res = (we->subexpr == result);
2441 if (res
2442 || is_a <if_expr *> (we->subexpr)
2443 || is_a <with_expr *> (we->subexpr))
2444 res |= walk_result (we->subexpr, false, result);
2445 if (res)
2446 walk_c_expr (we->with);
2447 return res;
2449 else if (c_expr *ce = dyn_cast <c_expr *> (o))
2450 walk_c_expr (ce);
2451 else
2452 gcc_unreachable ();
2454 return false;
2457 /* Look for captures in the C expr E. */
2459 void
2460 capture_info::walk_c_expr (c_expr *e)
2462 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2463 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2464 really escape through. */
2465 unsigned p_depth = 0;
2466 for (unsigned i = 0; i < e->code.length (); ++i)
2468 const cpp_token *t = &e->code[i];
2469 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2470 id_base *id;
2471 if (t->type == CPP_NAME
2472 && (strcmp ((const char *)CPP_HASHNODE
2473 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2474 || strcmp ((const char *)CPP_HASHNODE
2475 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2476 || strcmp ((const char *)CPP_HASHNODE
2477 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2478 || ((id = get_operator ((const char *)CPP_HASHNODE
2479 (t->val.node.node)->ident.str))
2480 && is_a <predicate_id *> (id)))
2481 && n->type == CPP_OPEN_PAREN)
2482 p_depth++;
2483 else if (t->type == CPP_CLOSE_PAREN
2484 && p_depth > 0)
2485 p_depth--;
2486 else if (p_depth == 0
2487 && t->type == CPP_ATSIGN
2488 && (n->type == CPP_NUMBER
2489 || n->type == CPP_NAME)
2490 && !(n->flags & PREV_WHITE))
2492 const char *id1;
2493 if (n->type == CPP_NUMBER)
2494 id1 = (const char *)n->val.str.text;
2495 else
2496 id1 = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2497 unsigned *where = e->capture_ids->get(id1);
2498 if (! where)
2499 fatal_at (n, "unknown capture id '%s'", id1);
2500 info[info[*where].same_as].force_no_side_effects_p = true;
2501 if (verbose >= 1
2502 && !gimple)
2503 warning_at (t, "capture escapes");
2509 /* The current label failing the current matched pattern during
2510 code generation. */
2511 static char *fail_label;
2513 /* Code generation off the decision tree and the refered AST nodes. */
2515 bool
2516 is_conversion (id_base *op)
2518 return (*op == CONVERT_EXPR
2519 || *op == NOP_EXPR
2520 || *op == FLOAT_EXPR
2521 || *op == FIX_TRUNC_EXPR
2522 || *op == VIEW_CONVERT_EXPR);
2525 /* Get the type to be used for generating operand POS of OP from the
2526 various sources. */
2528 static const char *
2529 get_operand_type (id_base *op, unsigned pos,
2530 const char *in_type,
2531 const char *expr_type,
2532 const char *other_oprnd_type)
2534 /* Generally operands whose type does not match the type of the
2535 expression generated need to know their types but match and
2536 thus can fall back to 'other_oprnd_type'. */
2537 if (is_conversion (op))
2538 return other_oprnd_type;
2539 else if (*op == REALPART_EXPR
2540 || *op == IMAGPART_EXPR)
2541 return other_oprnd_type;
2542 else if (is_a <operator_id *> (op)
2543 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2544 return other_oprnd_type;
2545 else if (*op == COND_EXPR
2546 && pos == 0)
2547 return "boolean_type_node";
2548 else if (startswith (op->id, "CFN_COND_"))
2550 /* IFN_COND_* operands 1 and later by default have the same type
2551 as the result. The type of operand 0 needs to be specified
2552 explicitly. */
2553 if (pos > 0 && expr_type)
2554 return expr_type;
2555 else if (pos > 0 && in_type)
2556 return in_type;
2557 else
2558 return NULL;
2560 else
2562 /* Otherwise all types should match - choose one in order of
2563 preference. */
2564 if (expr_type)
2565 return expr_type;
2566 else if (in_type)
2567 return in_type;
2568 else
2569 return other_oprnd_type;
2573 /* Generate transform code for an expression. */
2575 void
2576 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2577 int depth, const char *in_type, capture_info *cinfo,
2578 dt_operand **indexes, int)
2580 id_base *opr = operation;
2581 /* When we delay operator substituting during lowering of fors we
2582 make sure that for code-gen purposes the effects of each substitute
2583 are the same. Thus just look at that. */
2584 if (user_id *uid = dyn_cast <user_id *> (opr))
2585 opr = uid->substitutes[0];
2587 bool conversion_p = is_conversion (opr);
2588 const char *type = expr_type;
2589 char optype[64];
2590 if (type)
2591 /* If there was a type specification in the pattern use it. */
2593 else if (conversion_p)
2594 /* For conversions we need to build the expression using the
2595 outer type passed in. */
2596 type = in_type;
2597 else if (*opr == REALPART_EXPR
2598 || *opr == IMAGPART_EXPR)
2600 /* __real and __imag use the component type of its operand. */
2601 snprintf (optype, sizeof (optype), "TREE_TYPE (TREE_TYPE (_o%d[0]))",
2602 depth);
2603 type = optype;
2605 else if (is_a <operator_id *> (opr)
2606 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2608 /* comparisons use boolean_type_node (or what gets in), but
2609 their operands need to figure out the types themselves. */
2610 if (in_type)
2611 type = in_type;
2612 else
2614 snprintf (optype, sizeof (optype), "boolean_type_node");
2615 type = optype;
2617 in_type = NULL;
2619 else if (*opr == COND_EXPR
2620 || *opr == VEC_COND_EXPR
2621 || startswith (opr->id, "CFN_COND_"))
2623 /* Conditions are of the same type as their first alternative. */
2624 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[1])", depth);
2625 type = optype;
2627 else
2629 /* Other operations are of the same type as their first operand. */
2630 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[0])", depth);
2631 type = optype;
2633 if (!type)
2634 fatal_at (location, "cannot determine type of operand");
2636 fprintf_indent (f, indent, "{\n");
2637 indent += 2;
2638 fprintf_indent (f, indent,
2639 "tree _o%d[%u], _r%d;\n", depth, ops.length (), depth);
2640 char op0type[64];
2641 snprintf (op0type, sizeof (op0type), "TREE_TYPE (_o%d[0])", depth);
2642 for (unsigned i = 0; i < ops.length (); ++i)
2644 char dest1[32];
2645 snprintf (dest1, sizeof (dest1), "_o%d[%u]", depth, i);
2646 const char *optype1
2647 = get_operand_type (opr, i, in_type, expr_type,
2648 i == 0 ? NULL : op0type);
2649 ops[i]->gen_transform (f, indent, dest1, gimple, depth + 1, optype1,
2650 cinfo, indexes,
2651 *opr == COND_EXPR && i == 0 ? 1 : 2);
2654 const char *opr_name;
2655 if (*operation == CONVERT_EXPR)
2656 opr_name = "NOP_EXPR";
2657 else
2658 opr_name = operation->id;
2660 if (gimple)
2662 if (*opr == CONVERT_EXPR)
2664 fprintf_indent (f, indent,
2665 "if (%s != TREE_TYPE (_o%d[0])\n",
2666 type, depth);
2667 fprintf_indent (f, indent,
2668 " && !useless_type_conversion_p (%s, TREE_TYPE "
2669 "(_o%d[0])))\n",
2670 type, depth);
2671 fprintf_indent (f, indent + 2, "{\n");
2672 indent += 4;
2674 /* ??? Building a stmt can fail for various reasons here, seq being
2675 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2676 So if we fail here we should continue matching other patterns. */
2677 fprintf_indent (f, indent, "gimple_match_op tem_op "
2678 "(res_op->cond.any_else (), %s, %s", opr_name, type);
2679 for (unsigned i = 0; i < ops.length (); ++i)
2680 fprintf (f, ", _o%d[%u]", depth, i);
2681 fprintf (f, ");\n");
2682 fprintf_indent (f, indent, "tem_op.resimplify (%s, valueize);\n",
2683 !force_leaf ? "lseq" : "NULL");
2684 fprintf_indent (f, indent,
2685 "_r%d = maybe_push_res_to_seq (&tem_op, %s);\n", depth,
2686 !force_leaf ? "lseq" : "NULL");
2687 fprintf_indent (f, indent,
2688 "if (!_r%d) goto %s;\n",
2689 depth, fail_label);
2690 if (*opr == CONVERT_EXPR)
2692 indent -= 4;
2693 fprintf_indent (f, indent, " }\n");
2694 fprintf_indent (f, indent, "else\n");
2695 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2698 else
2700 if (*opr == CONVERT_EXPR)
2702 fprintf_indent (f, indent, "if (TREE_TYPE (_o%d[0]) != %s)\n",
2703 depth, type);
2704 fprintf_indent (f, indent + 2, "{\n");
2705 indent += 4;
2707 if (opr->kind == id_base::CODE)
2708 fprintf_indent (f, indent, "_r%d = fold_build%d_loc (loc, %s, %s",
2709 depth, ops.length(), opr_name, type);
2710 else
2711 fprintf_indent (f, indent, "_r%d = maybe_build_call_expr_loc (loc, "
2712 "%s, %s, %d", depth, opr_name, type, ops.length());
2713 for (unsigned i = 0; i < ops.length (); ++i)
2714 fprintf (f, ", _o%d[%u]", depth, i);
2715 fprintf (f, ");\n");
2716 if (opr->kind != id_base::CODE)
2718 fprintf_indent (f, indent, "if (!_r%d)\n", depth);
2719 fprintf_indent (f, indent, " goto %s;\n", fail_label);
2721 if (force_leaf)
2723 fprintf_indent (f, indent, "if (EXPR_P (_r%d))\n", depth);
2724 fprintf_indent (f, indent, " goto %s;\n", fail_label);
2726 if (*opr == CONVERT_EXPR)
2728 fprintf_indent (f, indent - 2, "}\n");
2729 indent -= 4;
2730 fprintf_indent (f, indent, "else\n");
2731 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2734 fprintf_indent (f, indent, "%s = _r%d;\n", dest, depth);
2735 indent -= 2;
2736 fprintf_indent (f, indent, "}\n");
2739 /* Generate code for a c_expr which is either the expression inside
2740 an if statement or a sequence of statements which computes a
2741 result to be stored to DEST. */
2743 void
2744 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2745 bool, int, const char *, capture_info *,
2746 dt_operand **, int)
2748 if (dest && nr_stmts == 1)
2749 fprintf_indent (f, indent, "%s = ", dest);
2751 unsigned stmt_nr = 1;
2752 int prev_line = -1;
2753 for (unsigned i = 0; i < code.length (); ++i)
2755 const cpp_token *token = &code[i];
2757 /* We can't recover from all lexing losses but we can roughly restore line
2758 breaks from location info. */
2759 const line_map_ordinary *map;
2760 linemap_resolve_location (line_table, token->src_loc,
2761 LRK_SPELLING_LOCATION, &map);
2762 expanded_location loc = linemap_expand_location (line_table, map,
2763 token->src_loc);
2764 if (prev_line != -1 && loc.line != prev_line)
2765 fputc ('\n', f);
2766 prev_line = loc.line;
2768 /* Replace captures for code-gen. */
2769 if (token->type == CPP_ATSIGN)
2771 const cpp_token *n = &code[i+1];
2772 if ((n->type == CPP_NUMBER
2773 || n->type == CPP_NAME)
2774 && !(n->flags & PREV_WHITE))
2776 if (token->flags & PREV_WHITE)
2777 fputc (' ', f);
2778 const char *id;
2779 if (n->type == CPP_NUMBER)
2780 id = (const char *)n->val.str.text;
2781 else
2782 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2783 unsigned *cid = capture_ids->get (id);
2784 if (!cid)
2785 fatal_at (token, "unknown capture id");
2786 fprintf (f, "captures[%u]", *cid);
2787 ++i;
2788 continue;
2792 if (token->flags & PREV_WHITE)
2793 fputc (' ', f);
2795 if (token->type == CPP_NAME)
2797 const char *id = (const char *) NODE_NAME (token->val.node.node);
2798 unsigned j;
2799 for (j = 0; j < ids.length (); ++j)
2801 if (strcmp (id, ids[j].id) == 0)
2803 fprintf (f, "%s", ids[j].oper);
2804 break;
2807 if (j < ids.length ())
2808 continue;
2811 /* Output the token as string. */
2812 char *tk = (char *)cpp_token_as_text (r, token);
2813 fputs (tk, f);
2815 if (token->type == CPP_SEMICOLON)
2817 stmt_nr++;
2818 if (dest && stmt_nr == nr_stmts)
2819 fprintf_indent (f, indent, "%s = ", dest);
2822 fputc ('\n', f);
2825 /* Generate transform code for a capture. */
2827 void
2828 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2829 int depth, const char *in_type, capture_info *cinfo,
2830 dt_operand **indexes, int cond_handling)
2832 if (what && is_a<expr *> (what))
2834 if (indexes[where] == 0)
2836 char buf[20];
2837 snprintf (buf, sizeof (buf), "captures[%u]", where);
2838 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2839 cinfo, NULL);
2843 /* If in GENERIC some capture is used multiple times, unshare it except
2844 when emitting the last use. */
2845 if (!gimple
2846 && cinfo->info.exists ()
2847 && cinfo->info[cinfo->info[where].same_as].result_use_count > 1)
2849 fprintf_indent (f, indent, "%s = unshare_expr (captures[%u]);\n",
2850 dest, where);
2851 cinfo->info[cinfo->info[where].same_as].result_use_count--;
2853 else
2854 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2856 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2857 with substituting a capture of that. */
2858 if (gimple
2859 && cond_handling != 0
2860 && cinfo->info[where].cond_expr_cond_p)
2862 /* If substituting into a cond_expr condition, unshare. */
2863 if (cond_handling == 1)
2864 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2865 /* If substituting elsewhere we might need to decompose it. */
2866 else if (cond_handling == 2)
2868 /* ??? Returning false here will also not allow any other patterns
2869 to match unless this generator was split out. */
2870 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2871 fprintf_indent (f, indent, " {\n");
2872 fprintf_indent (f, indent, " if (!seq) return false;\n");
2873 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2874 " TREE_CODE (%s),"
2875 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2876 " TREE_OPERAND (%s, 1));\n",
2877 dest, dest, dest, dest, dest);
2878 fprintf_indent (f, indent, " }\n");
2883 /* Return the name of the operand representing the decision tree node.
2884 Use NAME as space to generate it. */
2886 char *
2887 dt_operand::get_name (char *name)
2889 if (! parent)
2890 sprintf (name, "t");
2891 else if (parent->level == 1)
2892 sprintf (name, "_p%u", pos);
2893 else if (parent->type == dt_node::DT_MATCH)
2894 return as_a <dt_operand *> (parent)->get_name (name);
2895 else
2896 sprintf (name, "_q%u%u", parent->level, pos);
2897 return name;
2900 /* Fill NAME with the operand name at position POS. */
2902 void
2903 dt_operand::gen_opname (char *name, unsigned pos)
2905 if (! parent)
2906 sprintf (name, "_p%u", pos);
2907 else
2908 sprintf (name, "_q%u%u", level, pos);
2911 /* Generate matching code for the decision tree operand which is
2912 a predicate. */
2914 unsigned
2915 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2917 predicate *p = as_a <predicate *> (op);
2919 if (p->p->matchers.exists ())
2921 /* If this is a predicate generated from a pattern mangle its
2922 name and pass on the valueize hook. */
2923 if (gimple)
2924 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2925 p->p->id, opname);
2926 else
2927 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2929 else
2930 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2931 fprintf_indent (f, indent + 2, "{\n");
2932 return 1;
2935 /* Generate matching code for the decision tree operand which is
2936 a capture-match. */
2938 unsigned
2939 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2941 char match_opname[20];
2942 match_dop->get_name (match_opname);
2943 if (value_match)
2944 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2945 "|| operand_equal_p (%s, %s, 0))\n",
2946 opname, match_opname, opname, opname, match_opname);
2947 else
2948 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2949 "|| (operand_equal_p (%s, %s, 0) "
2950 "&& types_match (%s, %s)))\n",
2951 opname, match_opname, opname, opname, match_opname,
2952 opname, match_opname);
2953 fprintf_indent (f, indent + 2, "{\n");
2954 return 1;
2957 /* Generate GIMPLE matching code for the decision tree operand. */
2959 unsigned
2960 dt_operand::gen_gimple_expr (FILE *f, int indent, int depth)
2962 expr *e = static_cast<expr *> (op);
2963 id_base *id = e->operation;
2964 unsigned n_ops = e->ops.length ();
2965 unsigned n_braces = 0;
2967 if (user_id *u = dyn_cast <user_id *> (id))
2968 id = u->substitutes[0];
2970 for (unsigned i = 0; i < n_ops; ++i)
2972 char child_opname[20];
2973 gen_opname (child_opname, i);
2975 if (id->kind == id_base::CODE)
2977 if (e->is_generic
2978 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2979 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2981 /* ??? If this is a memory operation we can't (and should not)
2982 match this. The only sensible operand types are
2983 SSA names and invariants. */
2984 if (e->is_generic)
2986 char opname[20];
2987 get_name (opname);
2988 fprintf_indent (f, indent,
2989 "tree %s = TREE_OPERAND (%s, %i);\n",
2990 child_opname, opname, i);
2992 else
2993 fprintf_indent (f, indent,
2994 "tree %s = TREE_OPERAND "
2995 "(gimple_assign_rhs1 (_a%d), %i);\n",
2996 child_opname, depth, i);
2997 fprintf_indent (f, indent,
2998 "if ((TREE_CODE (%s) == SSA_NAME\n",
2999 child_opname);
3000 fprintf_indent (f, indent,
3001 " || is_gimple_min_invariant (%s)))\n",
3002 child_opname);
3003 fprintf_indent (f, indent,
3004 " {\n");
3005 indent += 4;
3006 n_braces++;
3007 fprintf_indent (f, indent,
3008 "%s = do_valueize (valueize, %s);\n",
3009 child_opname, child_opname);
3010 continue;
3012 else
3013 fprintf_indent (f, indent,
3014 "tree %s = gimple_assign_rhs%u (_a%d);\n",
3015 child_opname, i + 1, depth);
3017 else
3018 fprintf_indent (f, indent,
3019 "tree %s = gimple_call_arg (_c%d, %u);\n",
3020 child_opname, depth, i);
3021 fprintf_indent (f, indent,
3022 "%s = do_valueize (valueize, %s);\n",
3023 child_opname, child_opname);
3025 /* While the toplevel operands are canonicalized by the caller
3026 after valueizing operands of sub-expressions we have to
3027 re-canonicalize operand order. */
3028 int opno = commutative_op (id);
3029 if (opno >= 0)
3031 char child_opname0[20], child_opname1[20];
3032 gen_opname (child_opname0, opno);
3033 gen_opname (child_opname1, opno + 1);
3034 fprintf_indent (f, indent,
3035 "if (tree_swap_operands_p (%s, %s))\n",
3036 child_opname0, child_opname1);
3037 fprintf_indent (f, indent,
3038 " std::swap (%s, %s);\n",
3039 child_opname0, child_opname1);
3042 return n_braces;
3045 /* Generate GENERIC matching code for the decision tree operand. */
3047 unsigned
3048 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
3050 expr *e = static_cast<expr *> (op);
3051 id_base *id = e->operation;
3052 unsigned n_ops = e->ops.length ();
3054 if (user_id *u = dyn_cast <user_id *> (id))
3055 id = u->substitutes[0];
3057 for (unsigned i = 0; i < n_ops; ++i)
3059 char child_opname[20];
3060 gen_opname (child_opname, i);
3062 if (id->kind == id_base::CODE)
3063 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
3064 child_opname, opname, i);
3065 else
3066 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
3067 child_opname, opname, i);
3070 return 0;
3073 /* Generate matching code for the children of the decision tree node. */
3075 void
3076 dt_node::gen_kids (FILE *f, int indent, bool gimple, int depth)
3078 auto_vec<dt_operand *> gimple_exprs;
3079 auto_vec<dt_operand *> generic_exprs;
3080 auto_vec<dt_operand *> fns;
3081 auto_vec<dt_operand *> generic_fns;
3082 auto_vec<dt_operand *> preds;
3083 auto_vec<dt_node *> others;
3085 for (unsigned i = 0; i < kids.length (); ++i)
3087 if (kids[i]->type == dt_node::DT_OPERAND)
3089 dt_operand *op = as_a<dt_operand *> (kids[i]);
3090 if (expr *e = dyn_cast <expr *> (op->op))
3092 if (e->ops.length () == 0
3093 /* In GIMPLE a CONSTRUCTOR always appears in a
3094 separate definition. */
3095 && (!gimple || !(*e->operation == CONSTRUCTOR)))
3097 generic_exprs.safe_push (op);
3098 /* But ADDR_EXPRs can appear directly when invariant
3099 and in a separate definition when not. */
3100 if (gimple && *e->operation == ADDR_EXPR)
3101 gimple_exprs.safe_push (op);
3103 else if (e->operation->kind == id_base::FN)
3105 if (gimple)
3106 fns.safe_push (op);
3107 else
3108 generic_fns.safe_push (op);
3110 else if (e->operation->kind == id_base::PREDICATE)
3111 preds.safe_push (op);
3112 else
3114 user_id *u = dyn_cast <user_id *> (e->operation);
3115 if (u && u->substitutes[0]->kind == id_base::FN)
3117 if (gimple)
3118 fns.safe_push (op);
3119 else
3120 generic_fns.safe_push (op);
3122 else
3124 if (gimple && !e->is_generic)
3125 gimple_exprs.safe_push (op);
3126 else
3127 generic_exprs.safe_push (op);
3131 else if (op->op->type == operand::OP_PREDICATE)
3132 others.safe_push (kids[i]);
3133 else
3134 gcc_unreachable ();
3136 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
3137 others.safe_push (kids[i]);
3138 else if (kids[i]->type == dt_node::DT_MATCH
3139 || kids[i]->type == dt_node::DT_TRUE)
3141 /* A DT_TRUE operand serves as a barrier - generate code now
3142 for what we have collected sofar.
3143 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
3144 dependent matches to get out-of-order. Generate code now
3145 for what we have collected sofar. */
3146 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
3147 fns, generic_fns, preds, others);
3148 /* And output the true operand itself. */
3149 kids[i]->gen (f, indent, gimple, depth);
3150 gimple_exprs.truncate (0);
3151 generic_exprs.truncate (0);
3152 fns.truncate (0);
3153 generic_fns.truncate (0);
3154 preds.truncate (0);
3155 others.truncate (0);
3157 else
3158 gcc_unreachable ();
3161 /* Generate code for the remains. */
3162 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
3163 fns, generic_fns, preds, others);
3166 /* Generate matching code for the children of the decision tree node. */
3168 void
3169 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple, int depth,
3170 const vec<dt_operand *> &gimple_exprs,
3171 const vec<dt_operand *> &generic_exprs,
3172 const vec<dt_operand *> &fns,
3173 const vec<dt_operand *> &generic_fns,
3174 const vec<dt_operand *> &preds,
3175 const vec<dt_node *> &others)
3177 char buf[128];
3178 char *kid_opname = buf;
3180 unsigned exprs_len = gimple_exprs.length ();
3181 unsigned gexprs_len = generic_exprs.length ();
3182 unsigned fns_len = fns.length ();
3183 unsigned gfns_len = generic_fns.length ();
3185 if (exprs_len || fns_len || gexprs_len || gfns_len)
3187 if (exprs_len)
3188 gimple_exprs[0]->get_name (kid_opname);
3189 else if (fns_len)
3190 fns[0]->get_name (kid_opname);
3191 else if (gfns_len)
3192 generic_fns[0]->get_name (kid_opname);
3193 else
3194 generic_exprs[0]->get_name (kid_opname);
3196 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
3197 fprintf_indent (f, indent, " {\n");
3198 indent += 2;
3201 if (exprs_len || fns_len)
3203 depth++;
3204 fprintf_indent (f, indent,
3205 "case SSA_NAME:\n");
3206 fprintf_indent (f, indent,
3207 " if (gimple *_d%d = get_def (valueize, %s))\n",
3208 depth, kid_opname);
3209 fprintf_indent (f, indent,
3210 " {\n");
3211 indent += 6;
3212 if (exprs_len)
3214 fprintf_indent (f, indent,
3215 "if (gassign *_a%d = dyn_cast <gassign *> (_d%d))\n",
3216 depth, depth);
3217 fprintf_indent (f, indent,
3218 " switch (gimple_assign_rhs_code (_a%d))\n",
3219 depth);
3220 indent += 4;
3221 fprintf_indent (f, indent, "{\n");
3222 for (unsigned i = 0; i < exprs_len; ++i)
3224 expr *e = as_a <expr *> (gimple_exprs[i]->op);
3225 if (user_id *u = dyn_cast <user_id *> (e->operation))
3227 for (auto id : u->substitutes)
3228 fprintf_indent (f, indent, "case %s:\n", id->id);
3230 else
3232 id_base *op = e->operation;
3233 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3234 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3235 else
3236 fprintf_indent (f, indent, "case %s:\n", op->id);
3238 fprintf_indent (f, indent, " {\n");
3239 gimple_exprs[i]->gen (f, indent + 4, true, depth);
3240 fprintf_indent (f, indent, " break;\n");
3241 fprintf_indent (f, indent, " }\n");
3243 fprintf_indent (f, indent, "default:;\n");
3244 fprintf_indent (f, indent, "}\n");
3245 indent -= 4;
3248 if (fns_len)
3250 fprintf_indent (f, indent,
3251 "%sif (gcall *_c%d = dyn_cast <gcall *> (_d%d))\n",
3252 exprs_len ? "else " : "", depth, depth);
3253 fprintf_indent (f, indent,
3254 " switch (gimple_call_combined_fn (_c%d))\n",
3255 depth);
3257 indent += 4;
3258 fprintf_indent (f, indent, "{\n");
3259 for (unsigned i = 0; i < fns_len; ++i)
3261 expr *e = as_a <expr *>(fns[i]->op);
3262 if (user_id *u = dyn_cast <user_id *> (e->operation))
3263 for (auto id : u->substitutes)
3264 fprintf_indent (f, indent, "case %s:\n", id->id);
3265 else
3266 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3267 /* We need to be defensive against bogus prototypes allowing
3268 calls with not enough arguments. */
3269 fprintf_indent (f, indent,
3270 " if (gimple_call_num_args (_c%d) == %d)\n",
3271 depth, e->ops.length ());
3272 fprintf_indent (f, indent, " {\n");
3273 fns[i]->gen (f, indent + 6, true, depth);
3274 fprintf_indent (f, indent, " }\n");
3275 fprintf_indent (f, indent, " break;\n");
3278 fprintf_indent (f, indent, "default:;\n");
3279 fprintf_indent (f, indent, "}\n");
3280 indent -= 4;
3283 indent -= 6;
3284 depth--;
3285 fprintf_indent (f, indent, " }\n");
3286 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
3287 here rather than in the next loop. */
3288 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3290 expr *e = as_a <expr *>(generic_exprs[i]->op);
3291 id_base *op = e->operation;
3292 if (*op == SSA_NAME && (exprs_len || fns_len))
3294 fprintf_indent (f, indent + 4, "{\n");
3295 generic_exprs[i]->gen (f, indent + 6, gimple, depth);
3296 fprintf_indent (f, indent + 4, "}\n");
3300 fprintf_indent (f, indent, " break;\n");
3303 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3305 expr *e = as_a <expr *>(generic_exprs[i]->op);
3306 id_base *op = e->operation;
3307 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3308 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3309 else if (*op == SSA_NAME && (exprs_len || fns_len))
3310 /* Already handled above. */
3311 continue;
3312 else
3314 if (user_id *u = dyn_cast <user_id *> (op))
3315 for (auto id : u->substitutes)
3316 fprintf_indent (f, indent, "case %s:\n", id->id);
3317 else
3318 fprintf_indent (f, indent, "case %s:\n", op->id);
3320 fprintf_indent (f, indent, " {\n");
3321 generic_exprs[i]->gen (f, indent + 4, gimple, depth);
3322 fprintf_indent (f, indent, " break;\n");
3323 fprintf_indent (f, indent, " }\n");
3326 if (gfns_len)
3328 fprintf_indent (f, indent,
3329 "case CALL_EXPR:\n");
3330 fprintf_indent (f, indent,
3331 " switch (get_call_combined_fn (%s))\n",
3332 kid_opname);
3333 fprintf_indent (f, indent,
3334 " {\n");
3335 indent += 4;
3337 for (unsigned j = 0; j < generic_fns.length (); ++j)
3339 expr *e = as_a <expr *>(generic_fns[j]->op);
3340 gcc_assert (e->operation->kind == id_base::FN);
3342 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3343 fprintf_indent (f, indent, " if (call_expr_nargs (%s) == %d)\n"
3344 " {\n", kid_opname, e->ops.length ());
3345 generic_fns[j]->gen (f, indent + 6, false, depth);
3346 fprintf_indent (f, indent, " }\n"
3347 " break;\n");
3349 fprintf_indent (f, indent, "default:;\n");
3351 indent -= 4;
3352 fprintf_indent (f, indent, " }\n");
3353 fprintf_indent (f, indent, " break;\n");
3356 /* Close switch (TREE_CODE ()). */
3357 if (exprs_len || fns_len || gexprs_len || gfns_len)
3359 indent -= 4;
3360 fprintf_indent (f, indent, " default:;\n");
3361 fprintf_indent (f, indent, " }\n");
3364 for (unsigned i = 0; i < preds.length (); ++i)
3366 expr *e = as_a <expr *> (preds[i]->op);
3367 predicate_id *p = as_a <predicate_id *> (e->operation);
3368 preds[i]->get_name (kid_opname);
3369 fprintf_indent (f, indent, "{\n");
3370 indent += 2;
3371 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
3372 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
3373 gimple ? "gimple" : "tree",
3374 p->id, kid_opname, kid_opname,
3375 gimple ? ", valueize" : "");
3376 fprintf_indent (f, indent, " {\n");
3377 for (int j = 0; j < p->nargs; ++j)
3379 char child_opname[20];
3380 preds[i]->gen_opname (child_opname, j);
3381 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3382 child_opname, kid_opname, j);
3384 preds[i]->gen_kids (f, indent + 4, gimple, depth);
3385 fprintf (f, "}\n");
3386 indent -= 2;
3387 fprintf_indent (f, indent, "}\n");
3390 for (unsigned i = 0; i < others.length (); ++i)
3391 others[i]->gen (f, indent, gimple, depth);
3394 /* Generate matching code for the decision tree operand. */
3396 void
3397 dt_operand::gen (FILE *f, int indent, bool gimple, int depth)
3399 char opname[20];
3400 get_name (opname);
3402 unsigned n_braces = 0;
3404 if (type == DT_OPERAND)
3405 switch (op->type)
3407 case operand::OP_PREDICATE:
3408 n_braces = gen_predicate (f, indent, opname, gimple);
3409 break;
3411 case operand::OP_EXPR:
3412 if (gimple)
3413 n_braces = gen_gimple_expr (f, indent, depth);
3414 else
3415 n_braces = gen_generic_expr (f, indent, opname);
3416 break;
3418 default:
3419 gcc_unreachable ();
3421 else if (type == DT_TRUE)
3423 else if (type == DT_MATCH)
3424 n_braces = gen_match_op (f, indent, opname, gimple);
3425 else
3426 gcc_unreachable ();
3428 indent += 4 * n_braces;
3429 gen_kids (f, indent, gimple, depth);
3431 for (unsigned i = 0; i < n_braces; ++i)
3433 indent -= 4;
3434 if (indent < 0)
3435 indent = 0;
3436 fprintf_indent (f, indent, " }\n");
3440 /* Emit a logging call to the debug file to the file F, with the INDENT from
3441 either the RESULT location or the S's match location if RESULT is null. */
3442 static void
3443 emit_logging_call (FILE *f, int indent, class simplify *s, operand *result,
3444 bool gimple)
3446 fprintf_indent (f, indent, "if (UNLIKELY (debug_dump)) "
3447 "%s_dump_logs (", gimple ? "gimple" : "generic");
3448 output_line_directive (f,
3449 result ? result->location : s->match->location,
3450 true, true, true);
3451 fprintf (f, ", __FILE__, __LINE__, %s);\n",
3452 s->kind == simplify::SIMPLIFY ? "true" : "false");
3455 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3456 step of a '(simplify ...)' or '(match ...)'. This handles everything
3457 that is not part of the decision tree (simplify->match).
3458 Main recursive worker. */
3460 void
3461 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3463 if (result)
3465 if (with_expr *w = dyn_cast <with_expr *> (result))
3467 fprintf_indent (f, indent, "{\n");
3468 indent += 4;
3469 output_line_directive (f, w->location);
3470 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3471 gen_1 (f, indent, gimple, w->subexpr);
3472 indent -= 4;
3473 fprintf_indent (f, indent, "}\n");
3474 return;
3476 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3478 output_line_directive (f, ife->location);
3479 fprintf_indent (f, indent, "if (");
3480 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3481 fprintf (f, ")\n");
3482 fprintf_indent (f, indent + 2, "{\n");
3483 indent += 4;
3484 gen_1 (f, indent, gimple, ife->trueexpr);
3485 indent -= 4;
3486 fprintf_indent (f, indent + 2, "}\n");
3487 if (ife->falseexpr)
3489 fprintf_indent (f, indent, "else\n");
3490 fprintf_indent (f, indent + 2, "{\n");
3491 indent += 4;
3492 gen_1 (f, indent, gimple, ife->falseexpr);
3493 indent -= 4;
3494 fprintf_indent (f, indent + 2, "}\n");
3496 return;
3500 static unsigned fail_label_cnt;
3501 char local_fail_label[256];
3502 snprintf (local_fail_label, 256, "next_after_fail%u", ++fail_label_cnt);
3503 fail_label = local_fail_label;
3504 bool needs_label = false;
3506 /* Analyze captures and perform early-outs on the incoming arguments
3507 that cover cases we cannot handle. */
3508 capture_info cinfo (s, result, gimple);
3509 if (s->kind == simplify::SIMPLIFY)
3511 if (!gimple)
3513 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3514 if (cinfo.force_no_side_effects & (1 << i))
3516 fprintf_indent (f, indent,
3517 "if (TREE_SIDE_EFFECTS (_p%d)) goto %s;\n",
3518 i, fail_label);
3519 needs_label = true;
3520 if (verbose >= 1)
3521 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3522 "forcing toplevel operand to have no "
3523 "side-effects");
3525 for (int i = 0; i <= s->capture_max; ++i)
3526 if (cinfo.info[i].cse_p)
3528 else if (cinfo.info[i].force_no_side_effects_p
3529 && (cinfo.info[i].toplevel_msk
3530 & cinfo.force_no_side_effects) == 0)
3532 fprintf_indent (f, indent,
3533 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3534 "goto %s;\n", i, fail_label);
3535 needs_label = true;
3536 if (verbose >= 1)
3537 warning_at (cinfo.info[i].c->location,
3538 "forcing captured operand to have no "
3539 "side-effects");
3541 else if ((cinfo.info[i].toplevel_msk
3542 & cinfo.force_no_side_effects) != 0)
3543 /* Mark capture as having no side-effects if we had to verify
3544 that via forced toplevel operand checks. */
3545 cinfo.info[i].force_no_side_effects_p = true;
3547 if (gimple)
3549 /* Force single-use restriction by only allowing simple
3550 results via setting seq to NULL. */
3551 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3552 bool first_p = true;
3553 for (int i = 0; i <= s->capture_max; ++i)
3554 if (cinfo.info[i].force_single_use)
3556 if (first_p)
3558 fprintf_indent (f, indent, "if (lseq\n");
3559 fprintf_indent (f, indent, " && (");
3560 first_p = false;
3562 else
3564 fprintf (f, "\n");
3565 fprintf_indent (f, indent, " || ");
3567 fprintf (f, "!single_use (captures[%d])", i);
3569 if (!first_p)
3571 fprintf (f, "))\n");
3572 fprintf_indent (f, indent, " lseq = NULL;\n");
3577 if (s->kind == simplify::SIMPLIFY)
3579 fprintf_indent (f, indent, "if (UNLIKELY (!dbg_cnt (match))) goto %s;\n", fail_label);
3580 needs_label = true;
3583 fprintf_indent (f, indent, "{\n");
3584 indent += 2;
3585 if (!result)
3587 /* If there is no result then this is a predicate implementation. */
3588 emit_logging_call (f, indent, s, result, gimple);
3589 fprintf_indent (f, indent, "return true;\n");
3591 else if (gimple)
3593 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3594 in outermost position). */
3595 if (result->type == operand::OP_EXPR
3596 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3597 result = as_a <expr *> (result)->ops[0];
3598 if (result->type == operand::OP_EXPR)
3600 expr *e = as_a <expr *> (result);
3601 id_base *opr = e->operation;
3602 bool is_predicate = false;
3603 /* When we delay operator substituting during lowering of fors we
3604 make sure that for code-gen purposes the effects of each substitute
3605 are the same. Thus just look at that. */
3606 if (user_id *uid = dyn_cast <user_id *> (opr))
3607 opr = uid->substitutes[0];
3608 else if (is_a <predicate_id *> (opr))
3609 is_predicate = true;
3610 if (!is_predicate)
3611 fprintf_indent (f, indent, "res_op->set_op (%s, type, %d);\n",
3612 *e->operation == CONVERT_EXPR
3613 ? "NOP_EXPR" : e->operation->id,
3614 e->ops.length ());
3615 for (unsigned j = 0; j < e->ops.length (); ++j)
3617 char dest[32];
3618 if (is_predicate)
3619 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3620 else
3621 snprintf (dest, sizeof (dest), "res_op->ops[%d]", j);
3622 const char *optype
3623 = get_operand_type (opr, j,
3624 "type", e->expr_type,
3625 j == 0 ? NULL
3626 : "TREE_TYPE (res_op->ops[0])");
3627 /* We need to expand GENERIC conditions we captured from
3628 COND_EXPRs and we need to unshare them when substituting
3629 into COND_EXPRs. */
3630 int cond_handling = 0;
3631 if (!is_predicate)
3632 cond_handling = (*opr == COND_EXPR && j == 0) ? 1 : 2;
3633 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3634 &cinfo, indexes, cond_handling);
3637 /* Re-fold the toplevel result. It's basically an embedded
3638 gimple_build w/o actually building the stmt. */
3639 if (!is_predicate)
3641 fprintf_indent (f, indent,
3642 "res_op->resimplify (%s, valueize);\n",
3643 !e->force_leaf ? "lseq" : "NULL");
3644 if (e->force_leaf)
3646 fprintf_indent (f, indent,
3647 "if (!maybe_push_res_to_seq (res_op, NULL)) "
3648 "goto %s;\n", fail_label);
3649 needs_label = true;
3653 else if (result->type == operand::OP_CAPTURE
3654 || result->type == operand::OP_C_EXPR)
3656 fprintf_indent (f, indent, "tree tem;\n");
3657 result->gen_transform (f, indent, "tem", true, 1, "type",
3658 &cinfo, indexes);
3659 fprintf_indent (f, indent, "res_op->set_value (tem);\n");
3660 if (is_a <capture *> (result)
3661 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3663 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3664 with substituting a capture of that. */
3665 fprintf_indent (f, indent,
3666 "if (COMPARISON_CLASS_P (tem))\n");
3667 fprintf_indent (f, indent,
3668 " {\n");
3669 fprintf_indent (f, indent,
3670 " res_op->ops[0] = TREE_OPERAND (tem, 0);\n");
3671 fprintf_indent (f, indent,
3672 " res_op->ops[1] = TREE_OPERAND (tem, 1);\n");
3673 fprintf_indent (f, indent,
3674 " }\n");
3677 else
3678 gcc_unreachable ();
3679 emit_logging_call (f, indent, s, result, gimple);
3680 fprintf_indent (f, indent, "return true;\n");
3682 else /* GENERIC */
3684 bool is_predicate = false;
3685 if (result->type == operand::OP_EXPR)
3687 expr *e = as_a <expr *> (result);
3688 id_base *opr = e->operation;
3689 /* When we delay operator substituting during lowering of fors we
3690 make sure that for code-gen purposes the effects of each substitute
3691 are the same. Thus just look at that. */
3692 if (user_id *uid = dyn_cast <user_id *> (opr))
3693 opr = uid->substitutes[0];
3694 else if (is_a <predicate_id *> (opr))
3695 is_predicate = true;
3696 /* Search for captures used multiple times in the result expression
3697 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3698 original expression. */
3699 if (!is_predicate)
3700 for (int i = 0; i < s->capture_max + 1; ++i)
3702 if (cinfo.info[i].same_as != (unsigned)i
3703 || cinfo.info[i].cse_p)
3704 continue;
3705 if (cinfo.info[i].result_use_count
3706 > cinfo.info[i].match_use_count)
3708 fprintf_indent (f, indent,
3709 "if (! tree_invariant_p (captures[%d])) "
3710 "goto %s;\n", i, fail_label);
3711 needs_label = true;
3714 for (unsigned j = 0; j < e->ops.length (); ++j)
3716 char dest[32];
3717 if (is_predicate)
3718 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3719 else
3721 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3722 snprintf (dest, sizeof (dest), "res_op%d", j);
3724 const char *optype
3725 = get_operand_type (opr, j,
3726 "type", e->expr_type,
3727 j == 0
3728 ? NULL : "TREE_TYPE (res_op0)");
3729 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3730 &cinfo, indexes);
3732 if (is_predicate)
3734 emit_logging_call (f, indent, s, result, gimple);
3735 fprintf_indent (f, indent, "return true;\n");
3737 else
3739 fprintf_indent (f, indent, "tree _r;\n");
3740 /* Re-fold the toplevel result. Use non_lvalue to
3741 build NON_LVALUE_EXPRs so they get properly
3742 ignored when in GIMPLE form. */
3743 if (*opr == NON_LVALUE_EXPR)
3744 fprintf_indent (f, indent,
3745 "_r = non_lvalue_loc (loc, res_op0);\n");
3746 else
3748 if (is_a <operator_id *> (opr))
3749 fprintf_indent (f, indent,
3750 "_r = fold_build%d_loc (loc, %s, type",
3751 e->ops.length (),
3752 *e->operation == CONVERT_EXPR
3753 ? "NOP_EXPR" : e->operation->id);
3754 else
3755 fprintf_indent (f, indent,
3756 "_r = maybe_build_call_expr_loc (loc, "
3757 "%s, type, %d", e->operation->id,
3758 e->ops.length());
3759 for (unsigned j = 0; j < e->ops.length (); ++j)
3760 fprintf (f, ", res_op%d", j);
3761 fprintf (f, ");\n");
3762 if (!is_a <operator_id *> (opr))
3764 fprintf_indent (f, indent, "if (!_r)\n");
3765 fprintf_indent (f, indent, " goto %s;\n", fail_label);
3766 needs_label = true;
3771 else if (result->type == operand::OP_CAPTURE
3772 || result->type == operand::OP_C_EXPR)
3775 fprintf_indent (f, indent, "tree _r;\n");
3776 result->gen_transform (f, indent, "_r", false, 1, "type",
3777 &cinfo, indexes);
3779 else
3780 gcc_unreachable ();
3781 if (!is_predicate)
3783 /* Search for captures not used in the result expression and dependent
3784 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3785 for (int i = 0; i < s->capture_max + 1; ++i)
3787 if (cinfo.info[i].same_as != (unsigned)i)
3788 continue;
3789 if (!cinfo.info[i].force_no_side_effects_p
3790 && !cinfo.info[i].expr_p
3791 && cinfo.info[i].result_use_count == 0)
3793 fprintf_indent (f, indent,
3794 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3796 fprintf_indent (f, indent + 2,
3797 "_r = build2_loc (loc, COMPOUND_EXPR, type, "
3798 "fold_ignored_result (captures[%d]), _r);\n",
3802 emit_logging_call (f, indent, s, result, gimple);
3803 fprintf_indent (f, indent, "return _r;\n");
3806 indent -= 2;
3807 fprintf_indent (f, indent, "}\n");
3808 if (needs_label)
3809 fprintf (f, "%s:;\n", fail_label);
3810 fail_label = NULL;
3813 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3814 step of a '(simplify ...)' or '(match ...)'. This handles everything
3815 that is not part of the decision tree (simplify->match). */
3817 void
3818 dt_simplify::gen (FILE *f, int indent, bool gimple, int depth ATTRIBUTE_UNUSED)
3820 fprintf_indent (f, indent, "{\n");
3821 indent += 2;
3822 output_line_directive (f,
3823 s->result ? s->result->location : s->match->location);
3824 if (s->capture_max >= 0)
3826 char opname[20];
3827 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3828 s->capture_max + 1, indexes[0]->get_name (opname));
3830 for (int i = 1; i <= s->capture_max; ++i)
3832 if (!indexes[i])
3833 break;
3834 fprintf (f, ", %s", indexes[i]->get_name (opname));
3836 fprintf (f, " };\n");
3839 /* If we have a split-out function for the actual transform, call it. */
3840 if (info && info->fname)
3842 if (gimple)
3844 fprintf_indent (f, indent, "if (%s (res_op, seq, "
3845 "valueize, type, captures", info->fname);
3846 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3847 if (s->for_subst_vec[i].first->used)
3848 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3849 fprintf (f, "))\n");
3850 fprintf_indent (f, indent, " return true;\n");
3852 else
3854 fprintf_indent (f, indent, "tree res = %s (loc, type",
3855 info->fname);
3856 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3857 fprintf (f, ", _p%d", i);
3858 fprintf (f, ", captures");
3859 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3861 if (s->for_subst_vec[i].first->used)
3862 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3864 fprintf (f, ");\n");
3865 fprintf_indent (f, indent, "if (res) return res;\n");
3868 else
3870 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3872 if (! s->for_subst_vec[i].first->used)
3873 continue;
3874 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3875 fprintf_indent (f, indent, "const enum tree_code %s = %s;\n",
3876 s->for_subst_vec[i].first->id,
3877 s->for_subst_vec[i].second->id);
3878 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3879 fprintf_indent (f, indent, "const combined_fn %s = %s;\n",
3880 s->for_subst_vec[i].first->id,
3881 s->for_subst_vec[i].second->id);
3882 else
3883 gcc_unreachable ();
3885 gen_1 (f, indent, gimple, s->result);
3888 indent -= 2;
3889 fprintf_indent (f, indent, "}\n");
3893 /* Hash function for finding equivalent transforms. */
3895 hashval_t
3896 sinfo_hashmap_traits::hash (const key_type &v)
3898 /* Only bother to compare those originating from the same source pattern. */
3899 return v->s->result->location;
3902 /* Compare function for finding equivalent transforms. */
3904 static bool
3905 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3907 if (o1->type != o2->type)
3908 return false;
3910 switch (o1->type)
3912 case operand::OP_IF:
3914 if_expr *if1 = as_a <if_expr *> (o1);
3915 if_expr *if2 = as_a <if_expr *> (o2);
3916 /* ??? Properly compare c-exprs. */
3917 if (if1->cond != if2->cond)
3918 return false;
3919 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3920 return false;
3921 if (if1->falseexpr != if2->falseexpr
3922 || (if1->falseexpr
3923 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3924 return false;
3925 return true;
3927 case operand::OP_WITH:
3929 with_expr *with1 = as_a <with_expr *> (o1);
3930 with_expr *with2 = as_a <with_expr *> (o2);
3931 if (with1->with != with2->with)
3932 return false;
3933 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3935 default:;
3938 /* We've hit a result. Time to compare capture-infos - this is required
3939 in addition to the conservative pointer-equivalency of the result IL. */
3940 capture_info cinfo1 (s1, o1, true);
3941 capture_info cinfo2 (s2, o2, true);
3943 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3944 || cinfo1.info.length () != cinfo2.info.length ())
3945 return false;
3947 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3949 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3950 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3951 || (cinfo1.info[i].force_no_side_effects_p
3952 != cinfo2.info[i].force_no_side_effects_p)
3953 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3954 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3955 /* toplevel_msk is an optimization */
3956 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3957 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3958 /* the pointer back to the capture is for diagnostics only */)
3959 return false;
3962 /* ??? Deep-compare the actual result. */
3963 return o1 == o2;
3966 bool
3967 sinfo_hashmap_traits::equal_keys (const key_type &v,
3968 const key_type &candidate)
3970 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3974 /* Main entry to generate code for matching GIMPLE IL off the decision
3975 tree. */
3977 void
3978 decision_tree::gen (vec <FILE *> &files, bool gimple)
3980 sinfo_map_t si;
3982 root->analyze (si);
3984 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3985 "a total number of %u nodes\n",
3986 gimple ? "GIMPLE" : "GENERIC",
3987 root->num_leafs, root->max_level, root->total_size);
3989 /* First split out the transform part of equal leafs. */
3990 unsigned rcnt = 0;
3991 unsigned fcnt = 1;
3992 for (sinfo_map_t::iterator iter = si.begin ();
3993 iter != si.end (); ++iter)
3995 sinfo *s = (*iter).second;
3996 /* Do not split out single uses. */
3997 if (s->cnt <= 1)
3998 continue;
4000 rcnt += s->cnt - 1;
4001 if (verbose >= 1)
4003 fprintf (stderr, "found %u uses of", s->cnt);
4004 output_line_directive (stderr, s->s->s->result->location);
4007 /* Cycle the file buffers. */
4008 FILE *f = choose_output (files);
4010 /* Generate a split out function with the leaf transform code. */
4011 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
4012 fcnt++);
4013 if (gimple)
4014 fp_decl (f, "\nbool\n"
4015 "%s (gimple_match_op *res_op, gimple_seq *seq,\n"
4016 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
4017 " const tree ARG_UNUSED (type), tree *ARG_UNUSED "
4018 "(captures)",
4019 s->fname);
4020 else
4022 fp_decl (f, "\ntree\n"
4023 "%s (location_t ARG_UNUSED (loc), const tree ARG_UNUSED (type),\n",
4024 (*iter).second->fname);
4025 for (unsigned i = 0;
4026 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
4027 fp_decl (f, " tree ARG_UNUSED (_p%d),", i);
4028 fp_decl (f, " tree *captures");
4030 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
4032 if (! s->s->s->for_subst_vec[i].first->used)
4033 continue;
4034 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
4035 fp_decl (f, ",\n const enum tree_code ARG_UNUSED (%s)",
4036 s->s->s->for_subst_vec[i].first->id);
4037 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
4038 fp_decl (f, ",\n const combined_fn ARG_UNUSED (%s)",
4039 s->s->s->for_subst_vec[i].first->id);
4042 fp_decl_done (f, ")");
4043 fprintf (f, "{\n");
4044 fprintf_indent (f, 2, "const bool debug_dump = "
4045 "dump_file && (dump_flags & TDF_FOLDING);\n");
4046 s->s->gen_1 (f, 2, gimple, s->s->s->result);
4047 if (gimple)
4048 fprintf (f, " return false;\n");
4049 else
4050 fprintf (f, " return NULL_TREE;\n");
4051 fprintf (f, "}\n");
4053 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
4055 for (unsigned n = 1; n <= 7; ++n)
4057 bool has_kids_p = false;
4059 /* First generate split-out functions. */
4060 for (unsigned j = 0; j < root->kids.length (); j++)
4062 dt_operand *dop = static_cast<dt_operand *>(root->kids[j]);
4063 expr *e = static_cast<expr *>(dop->op);
4064 if (e->ops.length () != n
4065 /* Builtin simplifications are somewhat premature on
4066 GENERIC. The following drops patterns with outermost
4067 calls. It's easy to emit overloads for function code
4068 though if necessary. */
4069 || (!gimple
4070 && e->operation->kind != id_base::CODE))
4071 continue;
4074 /* Cycle the file buffers. */
4075 FILE *f = choose_output (files);
4077 if (gimple)
4078 fp_decl (f, "\nbool\n"
4079 "gimple_simplify_%s (gimple_match_op *res_op,"
4080 " gimple_seq *seq,\n"
4081 " tree (*valueize)(tree) "
4082 "ATTRIBUTE_UNUSED,\n"
4083 " code_helper ARG_UNUSED (code), tree "
4084 "ARG_UNUSED (type)",
4085 e->operation->id);
4086 else
4087 fp_decl (f, "\ntree\n"
4088 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
4089 "tree_code ARG_UNUSED (code), const tree ARG_UNUSED (type)",
4090 e->operation->id);
4091 for (unsigned i = 0; i < n; ++i)
4092 fp_decl (f, ", tree _p%d", i);
4093 fp_decl_done (f, ")");
4094 fprintf (f, "{\n");
4095 fprintf_indent (f, 2, "const bool debug_dump = "
4096 "dump_file && (dump_flags & TDF_FOLDING);\n");
4097 dop->gen_kids (f, 2, gimple, 0);
4098 if (gimple)
4099 fprintf (f, " return false;\n");
4100 else
4101 fprintf (f, " return NULL_TREE;\n");
4102 fprintf (f, "}\n");
4103 has_kids_p = true;
4106 /* If this main entry has no children, avoid generating code
4107 with compiler warnings, by generating a simple stub. */
4108 if (! has_kids_p)
4111 /* Cycle the file buffers. */
4112 FILE *f = choose_output (files);
4114 if (gimple)
4115 fp_decl (f, "\nbool\n"
4116 "gimple_simplify (gimple_match_op*, gimple_seq*,\n"
4117 " tree (*)(tree), code_helper,\n"
4118 " const tree");
4119 else
4120 fp_decl (f, "\ntree\n"
4121 "generic_simplify (location_t, enum tree_code,\n"
4122 " const tree");
4123 for (unsigned i = 0; i < n; ++i)
4124 fp_decl (f, ", tree");
4125 fp_decl_done (f, ")");
4126 fprintf (f, "{\n");
4127 if (gimple)
4128 fprintf (f, " return false;\n");
4129 else
4130 fprintf (f, " return NULL_TREE;\n");
4131 fprintf (f, "}\n");
4132 continue;
4136 /* Cycle the file buffers. */
4137 FILE *f = choose_output (files);
4139 /* Then generate the main entry with the outermost switch and
4140 tail-calls to the split-out functions. */
4141 if (gimple)
4142 fp_decl (f, "\nbool\n"
4143 "gimple_simplify (gimple_match_op *res_op, gimple_seq *seq,\n"
4144 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
4145 " code_helper code, const tree type");
4146 else
4147 fp_decl (f, "\ntree\n"
4148 "generic_simplify (location_t loc, enum tree_code code, "
4149 "const tree type ATTRIBUTE_UNUSED");
4150 for (unsigned i = 0; i < n; ++i)
4151 fp_decl (f, ", tree _p%d", i);
4152 fp_decl_done (f, ")");
4153 fprintf (f, "{\n");
4155 if (gimple)
4156 fprintf (f, " switch (code.get_rep())\n"
4157 " {\n");
4158 else
4159 fprintf (f, " switch (code)\n"
4160 " {\n");
4161 for (unsigned i = 0; i < root->kids.length (); i++)
4163 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
4164 expr *e = static_cast<expr *>(dop->op);
4165 if (e->ops.length () != n
4166 /* Builtin simplifications are somewhat premature on
4167 GENERIC. The following drops patterns with outermost
4168 calls. It's easy to emit overloads for function code
4169 though if necessary. */
4170 || (!gimple
4171 && e->operation->kind != id_base::CODE))
4172 continue;
4174 if (*e->operation == CONVERT_EXPR
4175 || *e->operation == NOP_EXPR)
4176 fprintf (f, " CASE_CONVERT:\n");
4177 else
4178 fprintf (f, " case %s%s:\n",
4179 is_a <fn_id *> (e->operation) ? "-" : "",
4180 e->operation->id);
4181 if (gimple)
4182 fprintf (f, " return gimple_simplify_%s (res_op, "
4183 "seq, valueize, code, type", e->operation->id);
4184 else
4185 fprintf (f, " return generic_simplify_%s (loc, code, type",
4186 e->operation->id);
4187 for (unsigned j = 0; j < n; ++j)
4188 fprintf (f, ", _p%d", j);
4189 fprintf (f, ");\n");
4191 fprintf (f, " default:;\n"
4192 " }\n");
4194 if (gimple)
4195 fprintf (f, " return false;\n");
4196 else
4197 fprintf (f, " return NULL_TREE;\n");
4198 fprintf (f, "}\n");
4202 /* Output code to implement the predicate P from the decision tree DT. */
4204 void
4205 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
4207 fp_decl (f, "\nbool\n%s%s (tree t%s%s)",
4208 gimple ? "gimple_" : "tree_", p->id,
4209 p->nargs > 0 ? ", tree *res_ops" : "",
4210 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
4211 fp_decl_done (f, "");
4212 fprintf (f, "{\n");
4213 /* Conveniently make 'type' available. */
4214 fprintf_indent (f, 2, "const tree type = TREE_TYPE (t);\n");
4215 fprintf_indent (f, 2, "const bool debug_dump = "
4216 "dump_file && (dump_flags & TDF_FOLDING);\n");
4218 if (!gimple)
4219 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
4220 dt.root->gen_kids (f, 2, gimple, 0);
4222 fprintf_indent (f, 2, "return false;\n"
4223 "}\n");
4226 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
4228 static void
4229 write_header (FILE *f, const char *head)
4231 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
4232 fprintf (f, " a IL pattern matching and simplification description. */\n");
4233 fprintf (f, "#pragma GCC diagnostic push\n");
4234 fprintf (f, "#pragma GCC diagnostic ignored \"-Wunused-variable\"\n");
4235 fprintf (f, "#pragma GCC diagnostic ignored \"-Wunused-function\"\n");
4237 /* Include the header instead of writing it awkwardly quoted here. */
4238 if (head)
4239 fprintf (f, "\n#include \"%s\"\n", head);
4244 /* AST parsing. */
4246 class parser
4248 public:
4249 parser (cpp_reader *, bool gimple);
4251 private:
4252 const cpp_token *next ();
4253 const cpp_token *peek (unsigned = 1);
4254 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
4255 const cpp_token *expect (enum cpp_ttype);
4256 const cpp_token *eat_token (enum cpp_ttype);
4257 const char *get_string ();
4258 const char *get_ident ();
4259 const cpp_token *eat_ident (const char *);
4260 const char *get_number ();
4262 unsigned get_internal_capture_id ();
4264 id_base *parse_operation (unsigned char &);
4265 operand *parse_capture (operand *, bool);
4266 operand *parse_expr ();
4267 c_expr *parse_c_expr (cpp_ttype);
4268 operand *parse_op ();
4270 void record_operlist (location_t, user_id *);
4272 void parse_pattern ();
4273 operand *parse_result (operand *, predicate_id *);
4274 void push_simplify (simplify::simplify_kind,
4275 vec<simplify *>&, operand *, operand *);
4276 void parse_simplify (simplify::simplify_kind,
4277 vec<simplify *>&, predicate_id *, operand *);
4278 void parse_for (location_t);
4279 void parse_if (location_t);
4280 void parse_predicates (location_t);
4281 void parse_operator_list (location_t);
4283 void finish_match_operand (operand *);
4285 cpp_reader *r;
4286 bool gimple;
4287 vec<c_expr *> active_ifs;
4288 vec<vec<user_id *> > active_fors;
4289 hash_set<user_id *> *oper_lists_set;
4290 vec<user_id *> oper_lists;
4292 cid_map_t *capture_ids;
4293 unsigned last_id;
4295 public:
4296 vec<simplify *> simplifiers;
4297 vec<predicate_id *> user_predicates;
4298 bool parsing_match_operand;
4301 /* Lexing helpers. */
4303 /* Read the next non-whitespace token from R. */
4305 const cpp_token *
4306 parser::next ()
4308 const cpp_token *token;
4311 token = cpp_get_token (r);
4313 while (token->type == CPP_PADDING);
4314 return token;
4317 /* Peek at the next non-whitespace token from R. */
4319 const cpp_token *
4320 parser::peek (unsigned num)
4322 const cpp_token *token;
4323 unsigned i = 0;
4326 token = cpp_peek_token (r, i++);
4328 while (token->type == CPP_PADDING
4329 || (--num > 0));
4330 /* If we peek at EOF this is a fatal error as it leaves the
4331 cpp_reader in unusable state. Assume we really wanted a
4332 token and thus this EOF is unexpected. */
4333 if (token->type == CPP_EOF)
4334 fatal_at (token, "unexpected end of file");
4335 return token;
4338 /* Peek at the next identifier token (or return NULL if the next
4339 token is not an identifier or equal to ID if supplied). */
4341 const cpp_token *
4342 parser::peek_ident (const char *id, unsigned num)
4344 const cpp_token *token = peek (num);
4345 if (token->type != CPP_NAME)
4346 return 0;
4348 if (id == 0)
4349 return token;
4351 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
4352 if (strcmp (id, t) == 0)
4353 return token;
4355 return 0;
4358 /* Read the next token from R and assert it is of type TK. */
4360 const cpp_token *
4361 parser::expect (enum cpp_ttype tk)
4363 const cpp_token *token = next ();
4364 if (token->type != tk)
4365 fatal_at (token, "expected %s, got %s",
4366 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
4368 return token;
4371 /* Consume the next token from R and assert it is of type TK. */
4373 const cpp_token *
4374 parser::eat_token (enum cpp_ttype tk)
4376 return expect (tk);
4379 /* Read the next token from R and assert it is of type CPP_STRING and
4380 return its value. */
4382 const char *
4383 parser::get_string ()
4385 const cpp_token *token = expect (CPP_STRING);
4386 return (const char *)token->val.str.text;
4389 /* Read the next token from R and assert it is of type CPP_NAME and
4390 return its value. */
4392 const char *
4393 parser::get_ident ()
4395 const cpp_token *token = expect (CPP_NAME);
4396 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4399 /* Eat an identifier token with value S from R. */
4401 const cpp_token *
4402 parser::eat_ident (const char *s)
4404 const cpp_token *token = peek ();
4405 const char *t = get_ident ();
4406 if (strcmp (s, t) != 0)
4407 fatal_at (token, "expected '%s' got '%s'\n", s, t);
4408 return token;
4411 /* Read the next token from R and assert it is of type CPP_NUMBER and
4412 return its value. */
4414 const char *
4415 parser::get_number ()
4417 const cpp_token *token = expect (CPP_NUMBER);
4418 return (const char *)token->val.str.text;
4421 /* Return a capture ID that can be used internally. */
4423 unsigned
4424 parser::get_internal_capture_id ()
4426 unsigned newid = capture_ids->elements ();
4427 /* Big enough for a 32-bit UINT_MAX plus prefix. */
4428 char id[13];
4429 bool existed;
4430 snprintf (id, sizeof (id), "__%u", newid);
4431 capture_ids->get_or_insert (xstrdup (id), &existed);
4432 if (existed)
4433 fatal ("reserved capture id '%s' already used", id);
4434 return newid;
4437 /* Record an operator-list use for transparent for handling. */
4439 void
4440 parser::record_operlist (location_t loc, user_id *p)
4442 if (!oper_lists_set->add (p))
4444 if (!oper_lists.is_empty ()
4445 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
4446 fatal_at (loc, "User-defined operator list does not have the "
4447 "same number of entries as others used in the pattern");
4448 oper_lists.safe_push (p);
4452 /* Parse the operator ID, special-casing convert?, convert1? and
4453 convert2? */
4455 id_base *
4456 parser::parse_operation (unsigned char &opt_grp)
4458 const cpp_token *id_tok = peek ();
4459 char *alt_id = NULL;
4460 const char *id = get_ident ();
4461 const cpp_token *token = peek ();
4462 opt_grp = 0;
4463 if (token->type == CPP_QUERY
4464 && !(token->flags & PREV_WHITE))
4466 if (!parsing_match_operand)
4467 fatal_at (id_tok, "conditional convert can only be used in "
4468 "match expression");
4469 if (ISDIGIT (id[strlen (id) - 1]))
4471 opt_grp = id[strlen (id) - 1] - '0' + 1;
4472 alt_id = xstrdup (id);
4473 alt_id[strlen (id) - 1] = '\0';
4474 if (opt_grp == 1)
4475 fatal_at (id_tok, "use '%s?' here", alt_id);
4477 else
4478 opt_grp = 1;
4479 eat_token (CPP_QUERY);
4481 id_base *op = get_operator (alt_id ? alt_id : id);
4482 if (!op)
4483 fatal_at (id_tok, "unknown operator %s", alt_id ? alt_id : id);
4484 if (alt_id)
4485 free (alt_id);
4486 user_id *p = dyn_cast<user_id *> (op);
4487 if (p && p->is_oper_list)
4489 if (active_fors.length() == 0)
4490 record_operlist (id_tok->src_loc, p);
4491 else
4492 fatal_at (id_tok, "operator-list %s cannot be expanded inside 'for'", id);
4494 return op;
4497 /* Parse a capture.
4498 capture = '@'<number> */
4500 class operand *
4501 parser::parse_capture (operand *op, bool require_existing)
4503 location_t src_loc = eat_token (CPP_ATSIGN)->src_loc;
4504 const cpp_token *token = peek ();
4505 const char *id = NULL;
4506 bool value_match = false;
4507 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4508 if (token->type == CPP_ATSIGN
4509 && ! (token->flags & PREV_WHITE)
4510 && parsing_match_operand)
4512 eat_token (CPP_ATSIGN);
4513 token = peek ();
4514 value_match = true;
4516 if (token->type == CPP_NUMBER)
4517 id = get_number ();
4518 else if (token->type == CPP_NAME)
4519 id = get_ident ();
4520 else
4521 fatal_at (token, "expected number or identifier");
4522 unsigned next_id = capture_ids->elements ();
4523 bool existed;
4524 unsigned &num = capture_ids->get_or_insert (id, &existed);
4525 if (!existed)
4527 if (require_existing)
4528 fatal_at (src_loc, "unknown capture id");
4529 num = next_id;
4531 return new capture (src_loc, num, op, value_match);
4534 /* Parse an expression
4535 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4537 class operand *
4538 parser::parse_expr ()
4540 const cpp_token *token = peek ();
4541 unsigned char opt_grp;
4542 expr *e = new expr (parse_operation (opt_grp), token->src_loc);
4543 token = peek ();
4544 operand *op;
4545 bool is_commutative = false;
4546 bool force_capture = false;
4547 const char *expr_type = NULL;
4549 if (!parsing_match_operand
4550 && token->type == CPP_NOT
4551 && !(token->flags & PREV_WHITE))
4553 eat_token (CPP_NOT);
4554 e->force_leaf = true;
4557 if (token->type == CPP_COLON
4558 && !(token->flags & PREV_WHITE))
4560 eat_token (CPP_COLON);
4561 token = peek ();
4562 if (token->type == CPP_NAME
4563 && !(token->flags & PREV_WHITE))
4565 const char *s = get_ident ();
4566 if (!parsing_match_operand)
4567 expr_type = s;
4568 else
4570 const char *sp = s;
4571 while (*sp)
4573 if (*sp == 'c')
4575 if (operator_id *o
4576 = dyn_cast<operator_id *> (e->operation))
4578 if (!commutative_tree_code (o->code)
4579 && !comparison_code_p (o->code))
4580 fatal_at (token, "operation is not commutative");
4582 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4583 for (unsigned i = 0;
4584 i < p->substitutes.length (); ++i)
4586 if (operator_id *q
4587 = dyn_cast<operator_id *> (p->substitutes[i]))
4589 if (!commutative_tree_code (q->code)
4590 && !comparison_code_p (q->code))
4591 fatal_at (token, "operation %s is not "
4592 "commutative", q->id);
4595 is_commutative = true;
4597 else if (*sp == 'C')
4598 is_commutative = true;
4599 else if (*sp == 's')
4601 e->force_single_use = true;
4602 force_capture = true;
4604 else
4605 fatal_at (token, "flag %c not recognized", *sp);
4606 sp++;
4609 token = peek ();
4611 else
4612 fatal_at (token, "expected flag or type specifying identifier");
4615 if (token->type == CPP_ATSIGN
4616 && !(token->flags & PREV_WHITE))
4617 op = parse_capture (e, false);
4618 else if (force_capture)
4620 unsigned num = get_internal_capture_id ();
4621 op = new capture (token->src_loc, num, e, false);
4623 else
4624 op = e;
4627 token = peek ();
4628 if (token->type == CPP_CLOSE_PAREN)
4630 if (e->operation->nargs != -1
4631 && e->operation->nargs != (int) e->ops.length ())
4632 fatal_at (token, "'%s' expects %u operands, not %u",
4633 e->operation->id, e->operation->nargs, e->ops.length ());
4634 if (is_commutative)
4636 if (e->ops.length () == 2
4637 || commutative_op (e->operation) >= 0)
4638 e->is_commutative = true;
4639 else
4640 fatal_at (token, "only binary operators or functions with "
4641 "two arguments can be marked commutative, "
4642 "unless the operation is known to be inherently "
4643 "commutative");
4645 e->expr_type = expr_type;
4646 if (opt_grp != 0)
4648 if (e->ops.length () != 1)
4649 fatal_at (token, "only unary operations can be conditional");
4650 e->opt_grp = opt_grp;
4652 return op;
4654 else if (!(token->flags & PREV_WHITE))
4655 fatal_at (token, "expected expression operand");
4657 e->append_op (parse_op ());
4659 while (1);
4662 /* Lex native C code delimited by START recording the preprocessing tokens
4663 for later processing.
4664 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4666 c_expr *
4667 parser::parse_c_expr (cpp_ttype start)
4669 const cpp_token *token;
4670 cpp_ttype end;
4671 unsigned opencnt;
4672 vec<cpp_token> code = vNULL;
4673 unsigned nr_stmts = 0;
4674 location_t loc = eat_token (start)->src_loc;
4675 if (start == CPP_OPEN_PAREN)
4676 end = CPP_CLOSE_PAREN;
4677 else if (start == CPP_OPEN_BRACE)
4678 end = CPP_CLOSE_BRACE;
4679 else
4680 gcc_unreachable ();
4681 opencnt = 1;
4684 token = next ();
4686 /* Count brace pairs to find the end of the expr to match. */
4687 if (token->type == start)
4688 opencnt++;
4689 else if (token->type == end
4690 && --opencnt == 0)
4691 break;
4692 else if (token->type == CPP_EOF)
4693 fatal_at (token, "unexpected end of file");
4695 /* This is a lame way of counting the number of statements. */
4696 if (token->type == CPP_SEMICOLON)
4697 nr_stmts++;
4699 /* If this is possibly a user-defined identifier mark it used. */
4700 if (token->type == CPP_NAME)
4702 const char *str
4703 = (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4704 if (strcmp (str, "return") == 0)
4705 fatal_at (token, "return statement not allowed in C expression");
4706 id_base *idb = get_operator (str);
4707 user_id *p;
4708 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4709 record_operlist (token->src_loc, p);
4712 /* Record the token. */
4713 code.safe_push (*token);
4715 while (1);
4716 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4719 /* Parse an operand which is either an expression, a predicate or
4720 a standalone capture.
4721 op = predicate | expr | c_expr | capture */
4723 class operand *
4724 parser::parse_op ()
4726 const cpp_token *token = peek ();
4727 class operand *op = NULL;
4728 if (token->type == CPP_OPEN_PAREN)
4730 eat_token (CPP_OPEN_PAREN);
4731 op = parse_expr ();
4732 eat_token (CPP_CLOSE_PAREN);
4734 else if (token->type == CPP_OPEN_BRACE)
4736 op = parse_c_expr (CPP_OPEN_BRACE);
4738 else
4740 /* Remaining ops are either empty or predicates */
4741 if (token->type == CPP_NAME)
4743 const char *id = get_ident ();
4744 id_base *opr = get_operator (id);
4745 if (!opr)
4746 fatal_at (token, "expected predicate name");
4747 if (operator_id *code1 = dyn_cast <operator_id *> (opr))
4749 if (code1->nargs != 0)
4750 fatal_at (token, "using an operator with operands as predicate");
4751 /* Parse the zero-operand operator "predicates" as
4752 expression. */
4753 op = new expr (opr, token->src_loc);
4755 else if (user_id *code2 = dyn_cast <user_id *> (opr))
4757 if (code2->nargs != 0)
4758 fatal_at (token, "using an operator with operands as predicate");
4759 /* Parse the zero-operand operator "predicates" as
4760 expression. */
4761 op = new expr (opr, token->src_loc);
4763 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4764 op = new predicate (p, token->src_loc);
4765 else
4766 fatal_at (token, "using an unsupported operator as predicate");
4767 if (!parsing_match_operand)
4768 fatal_at (token, "predicates are only allowed in match expression");
4769 token = peek ();
4770 if (token->flags & PREV_WHITE)
4771 return op;
4773 else if (token->type != CPP_COLON
4774 && token->type != CPP_ATSIGN)
4775 fatal_at (token, "expected expression or predicate");
4776 /* optionally followed by a capture and a predicate. */
4777 if (token->type == CPP_COLON)
4778 fatal_at (token, "not implemented: predicate on leaf operand");
4779 if (token->type == CPP_ATSIGN)
4780 op = parse_capture (op, !parsing_match_operand);
4783 return op;
4786 /* Create a new simplify from the current parsing state and MATCH,
4787 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4789 void
4790 parser::push_simplify (simplify::simplify_kind kind,
4791 vec<simplify *>& simplifiers,
4792 operand *match, operand *result)
4794 /* Build and push a temporary for operator list uses in expressions. */
4795 if (!oper_lists.is_empty ())
4796 active_fors.safe_push (oper_lists);
4798 simplifiers.safe_push
4799 (new simplify (kind, last_id++, match, result,
4800 active_fors.copy (), capture_ids));
4802 if (!oper_lists.is_empty ())
4803 active_fors.pop ();
4806 /* Parse
4807 <result-op> = <op> | <if> | <with>
4808 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4809 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4810 and return it. */
4812 operand *
4813 parser::parse_result (operand *result, predicate_id *matcher)
4815 const cpp_token *token = peek ();
4816 if (token->type != CPP_OPEN_PAREN)
4817 return parse_op ();
4819 eat_token (CPP_OPEN_PAREN);
4820 if (peek_ident ("if"))
4822 eat_ident ("if");
4823 if_expr *ife = new if_expr (token->src_loc);
4824 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4825 if (peek ()->type == CPP_OPEN_PAREN)
4827 ife->trueexpr = parse_result (result, matcher);
4828 if (peek ()->type == CPP_OPEN_PAREN)
4829 ife->falseexpr = parse_result (result, matcher);
4830 else if (peek ()->type != CPP_CLOSE_PAREN)
4831 ife->falseexpr = parse_op ();
4833 else if (peek ()->type != CPP_CLOSE_PAREN)
4835 ife->trueexpr = parse_op ();
4836 if (peek ()->type == CPP_OPEN_PAREN)
4837 ife->falseexpr = parse_result (result, matcher);
4838 else if (peek ()->type != CPP_CLOSE_PAREN)
4839 ife->falseexpr = parse_op ();
4841 /* If this if is immediately closed then it contains a
4842 manual matcher or is part of a predicate definition. */
4843 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4845 if (!matcher)
4846 fatal_at (peek (), "manual transform not implemented");
4847 ife->trueexpr = result;
4849 eat_token (CPP_CLOSE_PAREN);
4850 return ife;
4852 else if (peek_ident ("with"))
4854 eat_ident ("with");
4855 with_expr *withe = new with_expr (token->src_loc);
4856 /* Parse (with c-expr expr) as (if-with (true) expr). */
4857 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4858 withe->with->nr_stmts = 0;
4859 withe->subexpr = parse_result (result, matcher);
4860 eat_token (CPP_CLOSE_PAREN);
4861 return withe;
4863 else if (peek_ident ("switch"))
4865 token = eat_ident ("switch");
4866 location_t ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4867 eat_ident ("if");
4868 if_expr *ife = new if_expr (ifloc);
4869 operand *res = ife;
4870 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4871 if (peek ()->type == CPP_OPEN_PAREN)
4872 ife->trueexpr = parse_result (result, matcher);
4873 else
4874 ife->trueexpr = parse_op ();
4875 eat_token (CPP_CLOSE_PAREN);
4876 if (peek ()->type != CPP_OPEN_PAREN
4877 || !peek_ident ("if", 2))
4878 fatal_at (token, "switch can be implemented with a single if");
4879 while (peek ()->type != CPP_CLOSE_PAREN)
4881 if (peek ()->type == CPP_OPEN_PAREN)
4883 if (peek_ident ("if", 2))
4885 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4886 eat_ident ("if");
4887 ife->falseexpr = new if_expr (ifloc);
4888 ife = as_a <if_expr *> (ife->falseexpr);
4889 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4890 if (peek ()->type == CPP_OPEN_PAREN)
4891 ife->trueexpr = parse_result (result, matcher);
4892 else
4893 ife->trueexpr = parse_op ();
4894 if (peek ()->type == CPP_OPEN_PAREN)
4895 fatal_at (peek(), "if inside switch cannot have an else");
4896 eat_token (CPP_CLOSE_PAREN);
4898 else
4900 /* switch default clause */
4901 ife->falseexpr = parse_result (result, matcher);
4902 eat_token (CPP_CLOSE_PAREN);
4903 return res;
4906 else
4908 /* switch default clause */
4909 ife->falseexpr = parse_op ();
4910 eat_token (CPP_CLOSE_PAREN);
4911 return res;
4914 eat_token (CPP_CLOSE_PAREN);
4915 return res;
4917 else
4919 operand *op = result;
4920 if (!matcher)
4921 op = parse_expr ();
4922 eat_token (CPP_CLOSE_PAREN);
4923 return op;
4927 /* Parse
4928 simplify = 'simplify' <expr> <result-op>
4930 match = 'match' <ident> <expr> [<result-op>]
4931 and fill SIMPLIFIERS with the results. */
4933 void
4934 parser::parse_simplify (simplify::simplify_kind kind,
4935 vec<simplify *>& simplifiers, predicate_id *matcher,
4936 operand *result)
4938 /* Reset the capture map. */
4939 if (!capture_ids)
4940 capture_ids = new cid_map_t;
4941 /* Reset oper_lists and set. */
4942 hash_set <user_id *> olist;
4943 oper_lists_set = &olist;
4944 oper_lists = vNULL;
4946 const cpp_token *loc = peek ();
4947 parsing_match_operand = true;
4948 class operand *match = parse_op ();
4949 finish_match_operand (match);
4950 parsing_match_operand = false;
4951 if (match->type == operand::OP_CAPTURE && !matcher)
4952 fatal_at (loc, "outermost expression cannot be captured");
4953 if (match->type == operand::OP_EXPR
4954 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4955 fatal_at (loc, "outermost expression cannot be a predicate");
4957 /* Splice active_ifs onto result and continue parsing the
4958 "then" expr. */
4959 if_expr *active_if = NULL;
4960 for (int i = active_ifs.length (); i > 0; --i)
4962 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4963 ifc->cond = active_ifs[i-1];
4964 ifc->trueexpr = active_if;
4965 active_if = ifc;
4967 if_expr *outermost_if = active_if;
4968 while (active_if && active_if->trueexpr)
4969 active_if = as_a <if_expr *> (active_if->trueexpr);
4971 const cpp_token *token = peek ();
4973 /* If this if is immediately closed then it is part of a predicate
4974 definition. Push it. */
4975 if (token->type == CPP_CLOSE_PAREN)
4977 if (!matcher)
4978 fatal_at (token, "expected transform expression");
4979 if (active_if)
4981 active_if->trueexpr = result;
4982 result = outermost_if;
4984 push_simplify (kind, simplifiers, match, result);
4985 return;
4988 operand *tem = parse_result (result, matcher);
4989 if (active_if)
4991 active_if->trueexpr = tem;
4992 result = outermost_if;
4994 else
4995 result = tem;
4997 push_simplify (kind, simplifiers, match, result);
5000 /* Parsing of the outer control structures. */
5002 /* Parse a for expression
5003 for = '(' 'for' <subst>... <pattern> ')'
5004 subst = <ident> '(' <ident>... ')' */
5006 void
5007 parser::parse_for (location_t)
5009 auto_vec<const cpp_token *> user_id_tokens;
5010 vec<user_id *> user_ids = vNULL;
5011 const cpp_token *token;
5012 unsigned min_n_opers = 0, max_n_opers = 0;
5014 while (1)
5016 token = peek ();
5017 if (token->type != CPP_NAME)
5018 break;
5020 /* Insert the user defined operators into the operator hash. */
5021 const char *id = get_ident ();
5022 if (get_operator (id, true) != NULL)
5023 fatal_at (token, "operator already defined");
5024 user_id *op = new user_id (id);
5025 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
5026 *slot = op;
5027 user_ids.safe_push (op);
5028 user_id_tokens.safe_push (token);
5030 eat_token (CPP_OPEN_PAREN);
5032 int arity = -1;
5033 while ((token = peek_ident ()) != 0)
5035 const char *oper = get_ident ();
5036 id_base *idb = get_operator (oper, true);
5037 if (idb == NULL)
5038 fatal_at (token, "no such operator '%s'", oper);
5040 if (arity == -1)
5041 arity = idb->nargs;
5042 else if (idb->nargs == -1)
5044 else if (idb->nargs != arity)
5045 fatal_at (token, "operator '%s' with arity %d does not match "
5046 "others with arity %d", oper, idb->nargs, arity);
5048 user_id *p = dyn_cast<user_id *> (idb);
5049 if (p)
5051 if (p->is_oper_list)
5052 op->substitutes.safe_splice (p->substitutes);
5053 else
5054 fatal_at (token, "iterator cannot be used as operator-list");
5056 else
5057 op->substitutes.safe_push (idb);
5059 op->nargs = arity;
5060 token = expect (CPP_CLOSE_PAREN);
5062 unsigned nsubstitutes = op->substitutes.length ();
5063 if (nsubstitutes == 0)
5064 fatal_at (token, "A user-defined operator must have at least "
5065 "one substitution");
5066 if (max_n_opers == 0)
5068 min_n_opers = nsubstitutes;
5069 max_n_opers = nsubstitutes;
5071 else
5073 if (nsubstitutes % min_n_opers != 0
5074 && min_n_opers % nsubstitutes != 0)
5075 fatal_at (token, "All user-defined identifiers must have a "
5076 "multiple number of operator substitutions of the "
5077 "smallest number of substitutions");
5078 if (nsubstitutes < min_n_opers)
5079 min_n_opers = nsubstitutes;
5080 else if (nsubstitutes > max_n_opers)
5081 max_n_opers = nsubstitutes;
5085 unsigned n_ids = user_ids.length ();
5086 if (n_ids == 0)
5087 fatal_at (token, "for requires at least one user-defined identifier");
5089 token = peek ();
5090 if (token->type == CPP_CLOSE_PAREN)
5091 fatal_at (token, "no pattern defined in for");
5093 active_fors.safe_push (user_ids);
5094 while (1)
5096 token = peek ();
5097 if (token->type == CPP_CLOSE_PAREN)
5098 break;
5099 parse_pattern ();
5101 active_fors.pop ();
5103 /* Remove user-defined operators from the hash again. */
5104 for (unsigned i = 0; i < user_ids.length (); ++i)
5106 if (!user_ids[i]->used)
5107 warning_at (user_id_tokens[i],
5108 "operator %s defined but not used", user_ids[i]->id);
5109 operators->remove_elt (user_ids[i]);
5113 /* Parse an identifier associated with a list of operators.
5114 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
5116 void
5117 parser::parse_operator_list (location_t)
5119 const cpp_token *token = peek ();
5120 const char *id = get_ident ();
5122 if (get_operator (id, true) != 0)
5123 fatal_at (token, "operator %s already defined", id);
5125 user_id *op = new user_id (id, true);
5126 int arity = -1;
5128 while ((token = peek_ident ()) != 0)
5130 token = peek ();
5131 const char *oper = get_ident ();
5132 id_base *idb = get_operator (oper, true);
5134 if (idb == 0)
5135 fatal_at (token, "no such operator '%s'", oper);
5137 if (arity == -1)
5138 arity = idb->nargs;
5139 else if (idb->nargs == -1)
5141 else if (arity != idb->nargs)
5142 fatal_at (token, "operator '%s' with arity %d does not match "
5143 "others with arity %d", oper, idb->nargs, arity);
5145 /* We allow composition of multiple operator lists. */
5146 if (user_id *p = dyn_cast<user_id *> (idb))
5147 op->substitutes.safe_splice (p->substitutes);
5148 else
5149 op->substitutes.safe_push (idb);
5152 // Check that there is no junk after id-list
5153 token = peek();
5154 if (token->type != CPP_CLOSE_PAREN)
5155 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
5157 if (op->substitutes.length () == 0)
5158 fatal_at (token, "operator-list cannot be empty");
5160 op->nargs = arity;
5161 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
5162 *slot = op;
5165 /* Parse an outer if expression.
5166 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
5168 void
5169 parser::parse_if (location_t)
5171 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
5173 const cpp_token *token = peek ();
5174 if (token->type == CPP_CLOSE_PAREN)
5175 fatal_at (token, "no pattern defined in if");
5177 active_ifs.safe_push (ifexpr);
5178 while (1)
5180 token = peek ();
5181 if (token->type == CPP_CLOSE_PAREN)
5182 break;
5184 parse_pattern ();
5186 active_ifs.pop ();
5189 /* Parse a list of predefined predicate identifiers.
5190 preds = '(' 'define_predicates' <ident>... ')' */
5192 void
5193 parser::parse_predicates (location_t)
5197 const cpp_token *token = peek ();
5198 if (token->type != CPP_NAME)
5199 break;
5201 add_predicate (get_ident ());
5203 while (1);
5206 /* Parse outer control structures.
5207 pattern = <preds>|<for>|<if>|<simplify>|<match> */
5209 void
5210 parser::parse_pattern ()
5212 /* All clauses start with '('. */
5213 eat_token (CPP_OPEN_PAREN);
5214 const cpp_token *token = peek ();
5215 const char *id = get_ident ();
5216 if (strcmp (id, "simplify") == 0)
5218 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
5219 capture_ids = NULL;
5221 else if (strcmp (id, "match") == 0)
5223 bool with_args = false;
5224 location_t e_loc = peek ()->src_loc;
5225 if (peek ()->type == CPP_OPEN_PAREN)
5227 eat_token (CPP_OPEN_PAREN);
5228 with_args = true;
5230 const char *name = get_ident ();
5231 id_base *id1 = get_operator (name);
5232 predicate_id *p;
5233 if (!id1)
5235 p = add_predicate (name);
5236 user_predicates.safe_push (p);
5238 else if ((p = dyn_cast <predicate_id *> (id1)))
5240 else
5241 fatal_at (token, "cannot add a match to a non-predicate ID");
5242 /* Parse (match <id> <arg>... (match-expr)) here. */
5243 expr *e = NULL;
5244 if (with_args)
5246 capture_ids = new cid_map_t;
5247 e = new expr (p, e_loc);
5248 while (peek ()->type == CPP_ATSIGN)
5249 e->append_op (parse_capture (NULL, false));
5250 eat_token (CPP_CLOSE_PAREN);
5252 if (p->nargs != -1
5253 && ((e && e->ops.length () != (unsigned)p->nargs)
5254 || (!e && p->nargs != 0)))
5255 fatal_at (token, "non-matching number of match operands");
5256 p->nargs = e ? e->ops.length () : 0;
5257 parse_simplify (simplify::MATCH, p->matchers, p, e);
5258 capture_ids = NULL;
5260 else if (strcmp (id, "for") == 0)
5261 parse_for (token->src_loc);
5262 else if (strcmp (id, "if") == 0)
5263 parse_if (token->src_loc);
5264 else if (strcmp (id, "define_predicates") == 0)
5266 if (active_ifs.length () > 0
5267 || active_fors.length () > 0)
5268 fatal_at (token, "define_predicates inside if or for is not supported");
5269 parse_predicates (token->src_loc);
5271 else if (strcmp (id, "define_operator_list") == 0)
5273 if (active_ifs.length () > 0
5274 || active_fors.length () > 0)
5275 fatal_at (token, "operator-list inside if or for is not supported");
5276 parse_operator_list (token->src_loc);
5278 else
5279 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
5280 active_ifs.length () == 0 && active_fors.length () == 0
5281 ? "'define_predicates', " : "");
5283 eat_token (CPP_CLOSE_PAREN);
5286 /* Helper for finish_match_operand, collecting captures of OP in CPTS
5287 recursively. */
5289 static void
5290 walk_captures (operand *op, vec<vec<capture *> > &cpts)
5292 if (! op)
5293 return;
5295 if (capture *c = dyn_cast <capture *> (op))
5297 cpts[c->where].safe_push (c);
5298 walk_captures (c->what, cpts);
5300 else if (expr *e = dyn_cast <expr *> (op))
5301 for (unsigned i = 0; i < e->ops.length (); ++i)
5302 walk_captures (e->ops[i], cpts);
5305 /* Finish up OP which is a match operand. */
5307 void
5308 parser::finish_match_operand (operand *op)
5310 /* Look for matching captures, diagnose mis-uses of @@ and apply
5311 early lowering and distribution of value_match. */
5312 auto_vec<vec<capture *> > cpts;
5313 cpts.safe_grow_cleared (capture_ids->elements (), true);
5314 walk_captures (op, cpts);
5315 for (unsigned i = 0; i < cpts.length (); ++i)
5317 capture *value_match = NULL;
5318 for (unsigned j = 0; j < cpts[i].length (); ++j)
5320 if (cpts[i][j]->value_match)
5322 if (value_match)
5323 fatal_at (cpts[i][j]->location, "duplicate @@");
5324 value_match = cpts[i][j];
5327 if (cpts[i].length () == 1 && value_match)
5328 fatal_at (value_match->location, "@@ without a matching capture");
5329 if (value_match)
5331 /* Duplicate prevailing capture with the existing ID, create
5332 a fake ID and rewrite all captures to use it. This turns
5333 @@1 into @__<newid>@1 and @1 into @__<newid>. */
5334 value_match->what = new capture (value_match->location,
5335 value_match->where,
5336 value_match->what, false);
5337 /* Create a fake ID and rewrite all captures to use it. */
5338 unsigned newid = get_internal_capture_id ();
5339 for (unsigned j = 0; j < cpts[i].length (); ++j)
5341 cpts[i][j]->where = newid;
5342 cpts[i][j]->value_match = true;
5345 cpts[i].release ();
5349 /* Main entry of the parser. Repeatedly parse outer control structures. */
5351 parser::parser (cpp_reader *r_, bool gimple_)
5353 r = r_;
5354 gimple = gimple_;
5355 active_ifs = vNULL;
5356 active_fors = vNULL;
5357 simplifiers = vNULL;
5358 oper_lists_set = NULL;
5359 oper_lists = vNULL;
5360 capture_ids = NULL;
5361 user_predicates = vNULL;
5362 parsing_match_operand = false;
5363 last_id = 0;
5365 const cpp_token *token = next ();
5366 while (token->type != CPP_EOF)
5368 _cpp_backup_tokens (r, 1);
5369 parse_pattern ();
5370 token = next ();
5375 /* Helper for the linemap code. */
5377 static size_t
5378 round_alloc_size (size_t s)
5380 return s;
5384 /* Construct and display the help menu. */
5386 static void
5387 usage ()
5389 const char *usage = "Usage:\n"
5390 " %s [--gimple|--generic] [-v[v]] <input>\n"
5391 " %s [options] [--include=FILE] --header=FILE <input> <output>...\n";
5392 fprintf (stderr, usage, progname, progname);
5395 /* Write out the correct include to the match-head fle containing the helper
5396 files. */
5398 static void
5399 write_header_includes (bool gimple, FILE *header_file)
5401 if (gimple)
5402 fprintf (header_file, "#include \"gimple-match-head.cc\"\n");
5403 else
5404 fprintf (header_file, "#include \"generic-match-head.cc\"\n");
5407 /* The genmatch generator program. It reads from a pattern description
5408 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
5411 main (int argc, char **argv)
5413 cpp_reader *r;
5415 progname = "genmatch";
5417 bool gimple = true;
5418 char *s_header_file = NULL;
5419 char *s_include_file = NULL;
5420 auto_vec <char *> files;
5421 char *input = NULL;
5422 int last_file = argc - 1;
5423 for (int i = argc - 1; i >= 1; --i)
5425 if (strcmp (argv[i], "--gimple") == 0)
5426 gimple = true;
5427 else if (strcmp (argv[i], "--generic") == 0)
5428 gimple = false;
5429 else if (strncmp (argv[i], "--header=", 9) == 0)
5430 s_header_file = &argv[i][9];
5431 else if (strncmp (argv[i], "--include=", 10) == 0)
5432 s_include_file = &argv[i][10];
5433 else if (strcmp (argv[i], "-v") == 0)
5434 verbose = 1;
5435 else if (strcmp (argv[i], "-vv") == 0)
5436 verbose = 2;
5437 else if (strncmp (argv[i], "--", 2) != 0 && last_file-- == i)
5438 files.safe_push (argv[i]);
5439 else
5441 usage ();
5442 return 1;
5446 /* Validate if the combinations are valid. */
5447 if ((files.length () > 1 && !s_header_file) || files.is_empty ())
5449 usage ();
5450 return 1;
5453 if (!s_include_file)
5454 s_include_file = s_header_file;
5456 /* Input file is the last in the reverse list. */
5457 input = files.pop ();
5459 line_table = XCNEW (class line_maps);
5460 linemap_init (line_table, 0);
5461 line_table->m_reallocator = xrealloc;
5462 line_table->m_round_alloc_size = round_alloc_size;
5464 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
5465 cpp_callbacks *cb = cpp_get_callbacks (r);
5466 cb->diagnostic = diagnostic_cb;
5468 /* Add the build directory to the #include "" search path. */
5469 cpp_dir *dir = XCNEW (cpp_dir);
5470 dir->name = getpwd ();
5471 if (!dir->name)
5472 dir->name = ASTRDUP (".");
5473 cpp_set_include_chains (r, dir, NULL, false);
5475 if (!cpp_read_main_file (r, input))
5476 return 1;
5477 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
5478 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
5480 null_id = new id_base (id_base::NULL_ID, "null");
5482 /* Pre-seed operators. */
5483 operators = new hash_table<id_base> (1024);
5484 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
5485 add_operator (SYM, # SYM, # TYPE, NARGS);
5486 #define END_OF_BASE_TREE_CODES
5487 #include "tree.def"
5488 #undef END_OF_BASE_TREE_CODES
5489 #undef DEFTREECODE
5491 /* Pre-seed builtin functions.
5492 ??? Cannot use N (name) as that is targetm.emultls.get_address
5493 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
5494 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
5495 add_function (ENUM, "CFN_" # ENUM);
5496 #include "builtins.def"
5498 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
5499 add_function (IFN_##CODE, "CFN_" #CODE);
5500 #include "internal-fn.def"
5502 /* Parse ahead! */
5503 parser p (r, gimple);
5505 /* Create file buffers. */
5506 int n_parts = files.is_empty () ? 1 : files.length ();
5507 auto_vec <FILE *> parts (n_parts);
5508 if (files.is_empty ())
5510 parts.quick_push (stdout);
5511 write_header (stdout, s_include_file);
5512 write_header_includes (gimple, stdout);
5513 write_header_declarations (gimple, stdout);
5515 else
5517 for (char *s_file : files)
5519 parts.quick_push (fopen (s_file, "w"));
5520 write_header (parts.last (), s_include_file);
5523 header_file = fopen (s_header_file, "w");
5524 fprintf (header_file, "#ifndef GCC_GIMPLE_MATCH_AUTO_H\n"
5525 "#define GCC_GIMPLE_MATCH_AUTO_H\n");
5526 write_header_includes (gimple, header_file);
5527 write_header_declarations (gimple, header_file);
5530 /* Go over all predicates defined with patterns and perform
5531 lowering and code generation. */
5532 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
5534 predicate_id *pred = p.user_predicates[i];
5535 lower (pred->matchers, gimple);
5537 if (verbose == 2)
5538 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5539 print_matches (pred->matchers[j]);
5541 decision_tree dt;
5542 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5543 dt.insert (pred->matchers[j], j);
5545 if (verbose == 2)
5546 dt.print (stderr);
5548 /* Cycle the file buffers. */
5549 FILE *f = choose_output (parts);
5551 write_predicate (f, pred, dt, gimple);
5554 /* Lower the main simplifiers and generate code for them. */
5555 lower (p.simplifiers, gimple);
5557 if (verbose == 2)
5558 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5559 print_matches (p.simplifiers[i]);
5561 decision_tree dt;
5562 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5563 dt.insert (p.simplifiers[i], i);
5565 if (verbose == 2)
5566 dt.print (stderr);
5568 dt.gen (parts, gimple);
5570 define_dump_logs (gimple, choose_output (parts));
5572 for (FILE *f : parts)
5574 fprintf (f, "#pragma GCC diagnostic pop\n");
5575 fclose (f);
5578 if (header_file)
5580 fprintf (header_file, "\n#endif /* GCC_GIMPLE_MATCH_AUTO_H. */\n");
5581 fclose (header_file);
5584 /* Finalize. */
5585 cpp_finish (r, NULL);
5586 cpp_destroy (r);
5588 delete operators;
5590 return 0;