[PR c++/86374] Name lookup failure in enclosing template
[official-gcc.git] / gcc / genmatch.c
blob5d6cf0b4d3a75ec1d3e64d814df829feff399f29
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2018 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under
11 the terms of the GNU General Public License as published by the Free
12 Software Foundation; either version 3, or (at your option) any later
13 version.
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 #include "bconfig.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include <cpplib.h>
28 #include "errors.h"
29 #include "hash-table.h"
30 #include "hash-set.h"
31 #include "is-a.h"
34 /* Stubs for GGC referenced through instantiations triggered by hash-map. */
35 void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
36 size_t, size_t MEM_STAT_DECL)
38 return NULL;
40 void ggc_free (void *)
45 /* Global state. */
47 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
48 unsigned verbose;
51 /* libccp helpers. */
53 static struct line_maps *line_table;
55 /* The rich_location class within libcpp requires a way to expand
56 source_location instances, and relies on the client code
57 providing a symbol named
58 linemap_client_expand_location_to_spelling_point
59 to do this.
61 This is the implementation for genmatch. */
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (source_location loc,
65 enum location_aspect)
67 const struct line_map_ordinary *map;
68 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
69 return linemap_expand_location (line_table, map, loc);
72 static bool
73 #if GCC_VERSION >= 4001
74 __attribute__((format (printf, 5, 0)))
75 #endif
76 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
77 const char *msg, va_list *ap)
79 const line_map_ordinary *map;
80 source_location location = richloc->get_loc ();
81 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
82 expanded_location loc = linemap_expand_location (line_table, map, location);
83 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
84 (errtype == CPP_DL_WARNING) ? "warning" : "error");
85 vfprintf (stderr, msg, *ap);
86 fprintf (stderr, "\n");
87 FILE *f = fopen (loc.file, "r");
88 if (f)
90 char buf[128];
91 while (loc.line > 0)
93 if (!fgets (buf, 128, f))
94 goto notfound;
95 if (buf[strlen (buf) - 1] != '\n')
97 if (loc.line > 1)
98 loc.line++;
100 loc.line--;
102 fprintf (stderr, "%s", buf);
103 for (int i = 0; i < loc.column - 1; ++i)
104 fputc (' ', stderr);
105 fputc ('^', stderr);
106 fputc ('\n', stderr);
107 notfound:
108 fclose (f);
111 if (errtype == CPP_DL_FATAL)
112 exit (1);
113 return false;
116 static void
117 #if GCC_VERSION >= 4001
118 __attribute__((format (printf, 2, 3)))
119 #endif
120 fatal_at (const cpp_token *tk, const char *msg, ...)
122 rich_location richloc (line_table, tk->src_loc);
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
126 va_end (ap);
129 static void
130 #if GCC_VERSION >= 4001
131 __attribute__((format (printf, 2, 3)))
132 #endif
133 fatal_at (source_location loc, const char *msg, ...)
135 rich_location richloc (line_table, loc);
136 va_list ap;
137 va_start (ap, msg);
138 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
139 va_end (ap);
142 static void
143 #if GCC_VERSION >= 4001
144 __attribute__((format (printf, 2, 3)))
145 #endif
146 warning_at (const cpp_token *tk, const char *msg, ...)
148 rich_location richloc (line_table, tk->src_loc);
149 va_list ap;
150 va_start (ap, msg);
151 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
152 va_end (ap);
155 static void
156 #if GCC_VERSION >= 4001
157 __attribute__((format (printf, 2, 3)))
158 #endif
159 warning_at (source_location loc, const char *msg, ...)
161 rich_location richloc (line_table, loc);
162 va_list ap;
163 va_start (ap, msg);
164 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
165 va_end (ap);
168 /* Like fprintf, but print INDENT spaces at the beginning. */
170 static void
171 #if GCC_VERSION >= 4001
172 __attribute__((format (printf, 3, 4)))
173 #endif
174 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
176 va_list ap;
177 for (; indent >= 8; indent -= 8)
178 fputc ('\t', f);
179 fprintf (f, "%*s", indent, "");
180 va_start (ap, format);
181 vfprintf (f, format, ap);
182 va_end (ap);
185 static void
186 output_line_directive (FILE *f, source_location location,
187 bool dumpfile = false)
189 const line_map_ordinary *map;
190 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
191 expanded_location loc = linemap_expand_location (line_table, map, location);
192 if (dumpfile)
194 /* When writing to a dumpfile only dump the filename. */
195 const char *file = strrchr (loc.file, DIR_SEPARATOR);
196 #if defined(DIR_SEPARATOR_2)
197 const char *pos2 = strrchr (loc.file, DIR_SEPARATOR_2);
198 if (pos2 && (!file || (pos2 > file)))
199 file = pos2;
200 #endif
201 if (!file)
202 file = loc.file;
203 else
204 ++file;
205 fprintf (f, "%s:%d", file, loc.line);
207 else
208 /* Other gen programs really output line directives here, at least for
209 development it's right now more convenient to have line information
210 from the generated file. Still keep the directives as comment for now
211 to easily back-point to the meta-description. */
212 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
216 /* Pull in tree codes and builtin function codes from their
217 definition files. */
219 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
220 enum tree_code {
221 #include "tree.def"
222 CONVERT0,
223 CONVERT1,
224 CONVERT2,
225 VIEW_CONVERT0,
226 VIEW_CONVERT1,
227 VIEW_CONVERT2,
228 MAX_TREE_CODES
230 #undef DEFTREECODE
232 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
233 enum built_in_function {
234 #include "builtins.def"
235 END_BUILTINS
238 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
239 enum internal_fn {
240 #include "internal-fn.def"
241 IFN_LAST
244 enum combined_fn {
245 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
246 CFN_##ENUM = int (ENUM),
247 #include "builtins.def"
249 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) \
250 CFN_##CODE = int (END_BUILTINS) + int (IFN_##CODE),
251 #include "internal-fn.def"
253 CFN_LAST
256 #include "case-cfn-macros.h"
258 /* Return true if CODE represents a commutative tree code. Otherwise
259 return false. */
260 bool
261 commutative_tree_code (enum tree_code code)
263 switch (code)
265 case PLUS_EXPR:
266 case MULT_EXPR:
267 case MULT_HIGHPART_EXPR:
268 case MIN_EXPR:
269 case MAX_EXPR:
270 case BIT_IOR_EXPR:
271 case BIT_XOR_EXPR:
272 case BIT_AND_EXPR:
273 case NE_EXPR:
274 case EQ_EXPR:
275 case UNORDERED_EXPR:
276 case ORDERED_EXPR:
277 case UNEQ_EXPR:
278 case LTGT_EXPR:
279 case TRUTH_AND_EXPR:
280 case TRUTH_XOR_EXPR:
281 case TRUTH_OR_EXPR:
282 case WIDEN_MULT_EXPR:
283 case VEC_WIDEN_MULT_HI_EXPR:
284 case VEC_WIDEN_MULT_LO_EXPR:
285 case VEC_WIDEN_MULT_EVEN_EXPR:
286 case VEC_WIDEN_MULT_ODD_EXPR:
287 return true;
289 default:
290 break;
292 return false;
295 /* Return true if CODE represents a ternary tree code for which the
296 first two operands are commutative. Otherwise return false. */
297 bool
298 commutative_ternary_tree_code (enum tree_code code)
300 switch (code)
302 case WIDEN_MULT_PLUS_EXPR:
303 case WIDEN_MULT_MINUS_EXPR:
304 case DOT_PROD_EXPR:
305 return true;
307 default:
308 break;
310 return false;
313 /* Return true if CODE is a comparison. */
315 bool
316 comparison_code_p (enum tree_code code)
318 switch (code)
320 case EQ_EXPR:
321 case NE_EXPR:
322 case ORDERED_EXPR:
323 case UNORDERED_EXPR:
324 case LTGT_EXPR:
325 case UNEQ_EXPR:
326 case GT_EXPR:
327 case GE_EXPR:
328 case LT_EXPR:
329 case LE_EXPR:
330 case UNGT_EXPR:
331 case UNGE_EXPR:
332 case UNLT_EXPR:
333 case UNLE_EXPR:
334 return true;
336 default:
337 break;
339 return false;
343 /* Base class for all identifiers the parser knows. */
345 struct id_base : nofree_ptr_hash<id_base>
347 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
349 id_base (id_kind, const char *, int = -1);
351 hashval_t hashval;
352 int nargs;
353 const char *id;
355 /* hash_table support. */
356 static inline hashval_t hash (const id_base *);
357 static inline int equal (const id_base *, const id_base *);
360 inline hashval_t
361 id_base::hash (const id_base *op)
363 return op->hashval;
366 inline int
367 id_base::equal (const id_base *op1,
368 const id_base *op2)
370 return (op1->hashval == op2->hashval
371 && strcmp (op1->id, op2->id) == 0);
374 /* The special id "null", which matches nothing. */
375 static id_base *null_id;
377 /* Hashtable of known pattern operators. This is pre-seeded from
378 all known tree codes and all known builtin function ids. */
379 static hash_table<id_base> *operators;
381 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
383 kind = kind_;
384 id = id_;
385 nargs = nargs_;
386 hashval = htab_hash_string (id);
389 /* Identifier that maps to a tree code. */
391 struct operator_id : public id_base
393 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
394 const char *tcc_)
395 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
396 enum tree_code code;
397 const char *tcc;
400 /* Identifier that maps to a builtin or internal function code. */
402 struct fn_id : public id_base
404 fn_id (enum built_in_function fn_, const char *id_)
405 : id_base (id_base::FN, id_), fn (fn_) {}
406 fn_id (enum internal_fn fn_, const char *id_)
407 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
408 unsigned int fn;
411 struct simplify;
413 /* Identifier that maps to a user-defined predicate. */
415 struct predicate_id : public id_base
417 predicate_id (const char *id_)
418 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
419 vec<simplify *> matchers;
422 /* Identifier that maps to a operator defined by a 'for' directive. */
424 struct user_id : public id_base
426 user_id (const char *id_, bool is_oper_list_ = false)
427 : id_base (id_base::USER, id_), substitutes (vNULL),
428 used (false), is_oper_list (is_oper_list_) {}
429 vec<id_base *> substitutes;
430 bool used;
431 bool is_oper_list;
434 template<>
435 template<>
436 inline bool
437 is_a_helper <fn_id *>::test (id_base *id)
439 return id->kind == id_base::FN;
442 template<>
443 template<>
444 inline bool
445 is_a_helper <operator_id *>::test (id_base *id)
447 return id->kind == id_base::CODE;
450 template<>
451 template<>
452 inline bool
453 is_a_helper <predicate_id *>::test (id_base *id)
455 return id->kind == id_base::PREDICATE;
458 template<>
459 template<>
460 inline bool
461 is_a_helper <user_id *>::test (id_base *id)
463 return id->kind == id_base::USER;
466 /* If ID has a pair of consecutive, commutative operands, return the
467 index of the first, otherwise return -1. */
469 static int
470 commutative_op (id_base *id)
472 if (operator_id *code = dyn_cast <operator_id *> (id))
474 if (commutative_tree_code (code->code)
475 || commutative_ternary_tree_code (code->code))
476 return 0;
477 return -1;
479 if (fn_id *fn = dyn_cast <fn_id *> (id))
480 switch (fn->fn)
482 CASE_CFN_FMA:
483 case CFN_FMS:
484 case CFN_FNMA:
485 case CFN_FNMS:
486 return 0;
488 default:
489 return -1;
491 if (user_id *uid = dyn_cast<user_id *> (id))
493 int res = commutative_op (uid->substitutes[0]);
494 if (res < 0)
495 return 0;
496 for (unsigned i = 1; i < uid->substitutes.length (); ++i)
497 if (res != commutative_op (uid->substitutes[i]))
498 return -1;
499 return res;
501 return -1;
504 /* Add a predicate identifier to the hash. */
506 static predicate_id *
507 add_predicate (const char *id)
509 predicate_id *p = new predicate_id (id);
510 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
511 if (*slot)
512 fatal ("duplicate id definition");
513 *slot = p;
514 return p;
517 /* Add a tree code identifier to the hash. */
519 static void
520 add_operator (enum tree_code code, const char *id,
521 const char *tcc, unsigned nargs)
523 if (strcmp (tcc, "tcc_unary") != 0
524 && strcmp (tcc, "tcc_binary") != 0
525 && strcmp (tcc, "tcc_comparison") != 0
526 && strcmp (tcc, "tcc_expression") != 0
527 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
528 && strcmp (tcc, "tcc_reference") != 0
529 /* To have INTEGER_CST and friends as "predicate operators". */
530 && strcmp (tcc, "tcc_constant") != 0
531 /* And allow CONSTRUCTOR for vector initializers. */
532 && !(code == CONSTRUCTOR)
533 /* Allow SSA_NAME as predicate operator. */
534 && !(code == SSA_NAME))
535 return;
536 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
537 if (code == ADDR_EXPR)
538 nargs = 0;
539 operator_id *op = new operator_id (code, id, nargs, tcc);
540 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
541 if (*slot)
542 fatal ("duplicate id definition");
543 *slot = op;
546 /* Add a built-in or internal function identifier to the hash. ID is
547 the name of its CFN_* enumeration value. */
549 template <typename T>
550 static void
551 add_function (T code, const char *id)
553 fn_id *fn = new fn_id (code, id);
554 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
555 if (*slot)
556 fatal ("duplicate id definition");
557 *slot = fn;
560 /* Helper for easy comparing ID with tree code CODE. */
562 static bool
563 operator==(id_base &id, enum tree_code code)
565 if (operator_id *oid = dyn_cast <operator_id *> (&id))
566 return oid->code == code;
567 return false;
570 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
572 id_base *
573 get_operator (const char *id, bool allow_null = false)
575 if (allow_null && strcmp (id, "null") == 0)
576 return null_id;
578 id_base tem (id_base::CODE, id);
580 id_base *op = operators->find_with_hash (&tem, tem.hashval);
581 if (op)
583 /* If this is a user-defined identifier track whether it was used. */
584 if (user_id *uid = dyn_cast<user_id *> (op))
585 uid->used = true;
586 return op;
589 char *id2;
590 bool all_upper = true;
591 bool all_lower = true;
592 for (unsigned int i = 0; id[i]; ++i)
593 if (ISUPPER (id[i]))
594 all_lower = false;
595 else if (ISLOWER (id[i]))
596 all_upper = false;
597 if (all_lower)
599 /* Try in caps with _EXPR appended. */
600 id2 = ACONCAT ((id, "_EXPR", NULL));
601 for (unsigned int i = 0; id2[i]; ++i)
602 id2[i] = TOUPPER (id2[i]);
604 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
605 /* Try CFN_ instead of IFN_. */
606 id2 = ACONCAT (("CFN_", id + 4, NULL));
607 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
608 /* Try prepending CFN_. */
609 id2 = ACONCAT (("CFN_", id, NULL));
610 else
611 return NULL;
613 new (&tem) id_base (id_base::CODE, id2);
614 return operators->find_with_hash (&tem, tem.hashval);
617 /* Return the comparison operators that results if the operands are
618 swapped. This is safe for floating-point. */
620 id_base *
621 swap_tree_comparison (operator_id *p)
623 switch (p->code)
625 case EQ_EXPR:
626 case NE_EXPR:
627 case ORDERED_EXPR:
628 case UNORDERED_EXPR:
629 case LTGT_EXPR:
630 case UNEQ_EXPR:
631 return p;
632 case GT_EXPR:
633 return get_operator ("LT_EXPR");
634 case GE_EXPR:
635 return get_operator ("LE_EXPR");
636 case LT_EXPR:
637 return get_operator ("GT_EXPR");
638 case LE_EXPR:
639 return get_operator ("GE_EXPR");
640 case UNGT_EXPR:
641 return get_operator ("UNLT_EXPR");
642 case UNGE_EXPR:
643 return get_operator ("UNLE_EXPR");
644 case UNLT_EXPR:
645 return get_operator ("UNGT_EXPR");
646 case UNLE_EXPR:
647 return get_operator ("UNGE_EXPR");
648 default:
649 gcc_unreachable ();
653 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
656 /* The AST produced by parsing of the pattern definitions. */
658 struct dt_operand;
659 struct capture_info;
661 /* The base class for operands. */
663 struct operand {
664 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
665 operand (enum op_type type_, source_location loc_)
666 : type (type_), location (loc_) {}
667 enum op_type type;
668 source_location location;
669 virtual void gen_transform (FILE *, int, const char *, bool, int,
670 const char *, capture_info *,
671 dt_operand ** = 0,
672 int = 0)
673 { gcc_unreachable (); }
676 /* A predicate operand. Predicates are leafs in the AST. */
678 struct predicate : public operand
680 predicate (predicate_id *p_, source_location loc)
681 : operand (OP_PREDICATE, loc), p (p_) {}
682 predicate_id *p;
685 /* An operand that constitutes an expression. Expressions include
686 function calls and user-defined predicate invocations. */
688 struct expr : public operand
690 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
691 : operand (OP_EXPR, loc), operation (operation_),
692 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
693 is_generic (false), force_single_use (false) {}
694 expr (expr *e)
695 : operand (OP_EXPR, e->location), operation (e->operation),
696 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
697 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
698 void append_op (operand *op) { ops.safe_push (op); }
699 /* The operator and its operands. */
700 id_base *operation;
701 vec<operand *> ops;
702 /* An explicitely specified type - used exclusively for conversions. */
703 const char *expr_type;
704 /* Whether the operation is to be applied commutatively. This is
705 later lowered to two separate patterns. */
706 bool is_commutative;
707 /* Whether the expression is expected to be in GENERIC form. */
708 bool is_generic;
709 /* Whether pushing any stmt to the sequence should be conditional
710 on this expression having a single-use. */
711 bool force_single_use;
712 virtual void gen_transform (FILE *f, int, const char *, bool, int,
713 const char *, capture_info *,
714 dt_operand ** = 0, int = 0);
717 /* An operator that is represented by native C code. This is always
718 a leaf operand in the AST. This class is also used to represent
719 the code to be generated for 'if' and 'with' expressions. */
721 struct c_expr : public operand
723 /* A mapping of an identifier and its replacement. Used to apply
724 'for' lowering. */
725 struct id_tab {
726 const char *id;
727 const char *oper;
728 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
731 c_expr (cpp_reader *r_, source_location loc,
732 vec<cpp_token> code_, unsigned nr_stmts_,
733 vec<id_tab> ids_, cid_map_t *capture_ids_)
734 : operand (OP_C_EXPR, loc), r (r_), code (code_),
735 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
736 /* cpplib tokens and state to transform this back to source. */
737 cpp_reader *r;
738 vec<cpp_token> code;
739 cid_map_t *capture_ids;
740 /* The number of statements parsed (well, the number of ';'s). */
741 unsigned nr_stmts;
742 /* The identifier replacement vector. */
743 vec<id_tab> ids;
744 virtual void gen_transform (FILE *f, int, const char *, bool, int,
745 const char *, capture_info *,
746 dt_operand ** = 0, int = 0);
749 /* A wrapper around another operand that captures its value. */
751 struct capture : public operand
753 capture (source_location loc, unsigned where_, operand *what_, bool value_)
754 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
755 what (what_) {}
756 /* Identifier index for the value. */
757 unsigned where;
758 /* Whether in a match of two operands the compare should be for
759 equal values rather than equal atoms (boils down to a type
760 check or not). */
761 bool value_match;
762 /* The captured value. */
763 operand *what;
764 virtual void gen_transform (FILE *f, int, const char *, bool, int,
765 const char *, capture_info *,
766 dt_operand ** = 0, int = 0);
769 /* if expression. */
771 struct if_expr : public operand
773 if_expr (source_location loc)
774 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
775 c_expr *cond;
776 operand *trueexpr;
777 operand *falseexpr;
780 /* with expression. */
782 struct with_expr : public operand
784 with_expr (source_location loc)
785 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
786 c_expr *with;
787 operand *subexpr;
790 template<>
791 template<>
792 inline bool
793 is_a_helper <capture *>::test (operand *op)
795 return op->type == operand::OP_CAPTURE;
798 template<>
799 template<>
800 inline bool
801 is_a_helper <predicate *>::test (operand *op)
803 return op->type == operand::OP_PREDICATE;
806 template<>
807 template<>
808 inline bool
809 is_a_helper <c_expr *>::test (operand *op)
811 return op->type == operand::OP_C_EXPR;
814 template<>
815 template<>
816 inline bool
817 is_a_helper <expr *>::test (operand *op)
819 return op->type == operand::OP_EXPR;
822 template<>
823 template<>
824 inline bool
825 is_a_helper <if_expr *>::test (operand *op)
827 return op->type == operand::OP_IF;
830 template<>
831 template<>
832 inline bool
833 is_a_helper <with_expr *>::test (operand *op)
835 return op->type == operand::OP_WITH;
838 /* The main class of a pattern and its transform. This is used to
839 represent both (simplify ...) and (match ...) kinds. The AST
840 duplicates all outer 'if' and 'for' expressions here so each
841 simplify can exist in isolation. */
843 struct simplify
845 enum simplify_kind { SIMPLIFY, MATCH };
847 simplify (simplify_kind kind_, unsigned id_, operand *match_,
848 operand *result_, vec<vec<user_id *> > for_vec_,
849 cid_map_t *capture_ids_)
850 : kind (kind_), id (id_), match (match_), result (result_),
851 for_vec (for_vec_), for_subst_vec (vNULL),
852 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
854 simplify_kind kind;
855 /* ID. This is kept to easily associate related simplifies expanded
856 from the same original one. */
857 unsigned id;
858 /* The expression that is matched against the GENERIC or GIMPLE IL. */
859 operand *match;
860 /* For a (simplify ...) an expression with ifs and withs with the expression
861 produced when the pattern applies in the leafs.
862 For a (match ...) the leafs are either empty if it is a simple predicate
863 or the single expression specifying the matched operands. */
864 struct operand *result;
865 /* Collected 'for' expression operators that have to be replaced
866 in the lowering phase. */
867 vec<vec<user_id *> > for_vec;
868 vec<std::pair<user_id *, id_base *> > for_subst_vec;
869 /* A map of capture identifiers to indexes. */
870 cid_map_t *capture_ids;
871 int capture_max;
874 /* Debugging routines for dumping the AST. */
876 DEBUG_FUNCTION void
877 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
879 if (capture *c = dyn_cast<capture *> (o))
881 if (c->what && flattened == false)
882 print_operand (c->what, f, flattened);
883 fprintf (f, "@%u", c->where);
886 else if (predicate *p = dyn_cast<predicate *> (o))
887 fprintf (f, "%s", p->p->id);
889 else if (is_a<c_expr *> (o))
890 fprintf (f, "c_expr");
892 else if (expr *e = dyn_cast<expr *> (o))
894 if (e->ops.length () == 0)
895 fprintf (f, "%s", e->operation->id);
896 else
898 fprintf (f, "(%s", e->operation->id);
900 if (flattened == false)
902 for (unsigned i = 0; i < e->ops.length (); ++i)
904 putc (' ', f);
905 print_operand (e->ops[i], f, flattened);
908 putc (')', f);
912 else
913 gcc_unreachable ();
916 DEBUG_FUNCTION void
917 print_matches (struct simplify *s, FILE *f = stderr)
919 fprintf (f, "for expression: ");
920 print_operand (s->match, f);
921 putc ('\n', f);
925 /* AST lowering. */
927 /* Lowering of commutative operators. */
929 static void
930 cartesian_product (const vec< vec<operand *> >& ops_vector,
931 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
933 if (n == ops_vector.length ())
935 vec<operand *> xv = v.copy ();
936 result.safe_push (xv);
937 return;
940 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
942 v[n] = ops_vector[n][i];
943 cartesian_product (ops_vector, result, v, n + 1);
947 /* Lower OP to two operands in case it is marked as commutative. */
949 static vec<operand *>
950 commutate (operand *op, vec<vec<user_id *> > &for_vec)
952 vec<operand *> ret = vNULL;
954 if (capture *c = dyn_cast <capture *> (op))
956 if (!c->what)
958 ret.safe_push (op);
959 return ret;
961 vec<operand *> v = commutate (c->what, for_vec);
962 for (unsigned i = 0; i < v.length (); ++i)
964 capture *nc = new capture (c->location, c->where, v[i],
965 c->value_match);
966 ret.safe_push (nc);
968 return ret;
971 expr *e = dyn_cast <expr *> (op);
972 if (!e || e->ops.length () == 0)
974 ret.safe_push (op);
975 return ret;
978 vec< vec<operand *> > ops_vector = vNULL;
979 for (unsigned i = 0; i < e->ops.length (); ++i)
980 ops_vector.safe_push (commutate (e->ops[i], for_vec));
982 auto_vec< vec<operand *> > result;
983 auto_vec<operand *> v (e->ops.length ());
984 v.quick_grow_cleared (e->ops.length ());
985 cartesian_product (ops_vector, result, v, 0);
988 for (unsigned i = 0; i < result.length (); ++i)
990 expr *ne = new expr (e);
991 ne->is_commutative = false;
992 for (unsigned j = 0; j < result[i].length (); ++j)
993 ne->append_op (result[i][j]);
994 ret.safe_push (ne);
997 if (!e->is_commutative)
998 return ret;
1000 /* The operation is always binary if it isn't inherently commutative. */
1001 int natural_opno = commutative_op (e->operation);
1002 unsigned int opno = natural_opno >= 0 ? natural_opno : 0;
1003 for (unsigned i = 0; i < result.length (); ++i)
1005 expr *ne = new expr (e);
1006 if (operator_id *p = dyn_cast <operator_id *> (ne->operation))
1008 if (comparison_code_p (p->code))
1009 ne->operation = swap_tree_comparison (p);
1011 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
1013 bool found_compare = false;
1014 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1015 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
1017 if (comparison_code_p (q->code)
1018 && swap_tree_comparison (q) != q)
1020 found_compare = true;
1021 break;
1024 if (found_compare)
1026 user_id *newop = new user_id ("<internal>");
1027 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1029 id_base *subst = p->substitutes[j];
1030 if (operator_id *q = dyn_cast <operator_id *> (subst))
1032 if (comparison_code_p (q->code))
1033 subst = swap_tree_comparison (q);
1035 newop->substitutes.safe_push (subst);
1037 ne->operation = newop;
1038 /* Search for 'p' inside the for vector and push 'newop'
1039 to the same level. */
1040 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
1041 for (unsigned k = 0; k < for_vec[j].length (); ++k)
1042 if (for_vec[j][k] == p)
1044 for_vec[j].safe_push (newop);
1045 newop = NULL;
1046 break;
1050 ne->is_commutative = false;
1051 for (unsigned j = 0; j < result[i].length (); ++j)
1053 int old_j = (j == opno ? opno + 1 : j == opno + 1 ? opno : j);
1054 ne->append_op (result[i][old_j]);
1056 ret.safe_push (ne);
1059 return ret;
1062 /* Lower operations marked as commutative in the AST of S and push
1063 the resulting patterns to SIMPLIFIERS. */
1065 static void
1066 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1068 vec<operand *> matchers = commutate (s->match, s->for_vec);
1069 for (unsigned i = 0; i < matchers.length (); ++i)
1071 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1072 s->for_vec, s->capture_ids);
1073 simplifiers.safe_push (ns);
1077 /* Strip conditional conversios using operator OPER from O and its
1078 children if STRIP, else replace them with an unconditional convert. */
1080 operand *
1081 lower_opt_convert (operand *o, enum tree_code oper,
1082 enum tree_code to_oper, bool strip)
1084 if (capture *c = dyn_cast<capture *> (o))
1086 if (c->what)
1087 return new capture (c->location, c->where,
1088 lower_opt_convert (c->what, oper, to_oper, strip),
1089 c->value_match);
1090 else
1091 return c;
1094 expr *e = dyn_cast<expr *> (o);
1095 if (!e)
1096 return o;
1098 if (*e->operation == oper)
1100 if (strip)
1101 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
1103 expr *ne = new expr (e);
1104 ne->operation = (to_oper == CONVERT_EXPR
1105 ? get_operator ("CONVERT_EXPR")
1106 : get_operator ("VIEW_CONVERT_EXPR"));
1107 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
1108 return ne;
1111 expr *ne = new expr (e);
1112 for (unsigned i = 0; i < e->ops.length (); ++i)
1113 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
1115 return ne;
1118 /* Determine whether O or its children uses the conditional conversion
1119 operator OPER. */
1121 static bool
1122 has_opt_convert (operand *o, enum tree_code oper)
1124 if (capture *c = dyn_cast<capture *> (o))
1126 if (c->what)
1127 return has_opt_convert (c->what, oper);
1128 else
1129 return false;
1132 expr *e = dyn_cast<expr *> (o);
1133 if (!e)
1134 return false;
1136 if (*e->operation == oper)
1137 return true;
1139 for (unsigned i = 0; i < e->ops.length (); ++i)
1140 if (has_opt_convert (e->ops[i], oper))
1141 return true;
1143 return false;
1146 /* Lower conditional convert operators in O, expanding it to a vector
1147 if required. */
1149 static vec<operand *>
1150 lower_opt_convert (operand *o)
1152 vec<operand *> v1 = vNULL, v2;
1154 v1.safe_push (o);
1156 enum tree_code opers[]
1157 = { CONVERT0, CONVERT_EXPR,
1158 CONVERT1, CONVERT_EXPR,
1159 CONVERT2, CONVERT_EXPR,
1160 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
1161 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
1162 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
1164 /* Conditional converts are lowered to a pattern with the
1165 conversion and one without. The three different conditional
1166 convert codes are lowered separately. */
1168 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
1170 v2 = vNULL;
1171 for (unsigned j = 0; j < v1.length (); ++j)
1172 if (has_opt_convert (v1[j], opers[i]))
1174 v2.safe_push (lower_opt_convert (v1[j],
1175 opers[i], opers[i+1], false));
1176 v2.safe_push (lower_opt_convert (v1[j],
1177 opers[i], opers[i+1], true));
1180 if (v2 != vNULL)
1182 v1 = vNULL;
1183 for (unsigned j = 0; j < v2.length (); ++j)
1184 v1.safe_push (v2[j]);
1188 return v1;
1191 /* Lower conditional convert operators in the AST of S and push
1192 the resulting multiple patterns to SIMPLIFIERS. */
1194 static void
1195 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1197 vec<operand *> matchers = lower_opt_convert (s->match);
1198 for (unsigned i = 0; i < matchers.length (); ++i)
1200 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1201 s->for_vec, s->capture_ids);
1202 simplifiers.safe_push (ns);
1206 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1207 GENERIC and a GIMPLE variant. */
1209 static vec<operand *>
1210 lower_cond (operand *o)
1212 vec<operand *> ro = vNULL;
1214 if (capture *c = dyn_cast<capture *> (o))
1216 if (c->what)
1218 vec<operand *> lop = vNULL;
1219 lop = lower_cond (c->what);
1221 for (unsigned i = 0; i < lop.length (); ++i)
1222 ro.safe_push (new capture (c->location, c->where, lop[i],
1223 c->value_match));
1224 return ro;
1228 expr *e = dyn_cast<expr *> (o);
1229 if (!e || e->ops.length () == 0)
1231 ro.safe_push (o);
1232 return ro;
1235 vec< vec<operand *> > ops_vector = vNULL;
1236 for (unsigned i = 0; i < e->ops.length (); ++i)
1237 ops_vector.safe_push (lower_cond (e->ops[i]));
1239 auto_vec< vec<operand *> > result;
1240 auto_vec<operand *> v (e->ops.length ());
1241 v.quick_grow_cleared (e->ops.length ());
1242 cartesian_product (ops_vector, result, v, 0);
1244 for (unsigned i = 0; i < result.length (); ++i)
1246 expr *ne = new expr (e);
1247 for (unsigned j = 0; j < result[i].length (); ++j)
1248 ne->append_op (result[i][j]);
1249 ro.safe_push (ne);
1250 /* If this is a COND with a captured expression or an
1251 expression with two operands then also match a GENERIC
1252 form on the compare. */
1253 if ((*e->operation == COND_EXPR
1254 || *e->operation == VEC_COND_EXPR)
1255 && ((is_a <capture *> (e->ops[0])
1256 && as_a <capture *> (e->ops[0])->what
1257 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1258 && as_a <expr *>
1259 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1260 || (is_a <expr *> (e->ops[0])
1261 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1263 expr *ne = new expr (e);
1264 for (unsigned j = 0; j < result[i].length (); ++j)
1265 ne->append_op (result[i][j]);
1266 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1268 expr *ocmp = as_a <expr *> (c->what);
1269 expr *cmp = new expr (ocmp);
1270 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1271 cmp->append_op (ocmp->ops[j]);
1272 cmp->is_generic = true;
1273 ne->ops[0] = new capture (c->location, c->where, cmp,
1274 c->value_match);
1276 else
1278 expr *ocmp = as_a <expr *> (ne->ops[0]);
1279 expr *cmp = new expr (ocmp);
1280 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1281 cmp->append_op (ocmp->ops[j]);
1282 cmp->is_generic = true;
1283 ne->ops[0] = cmp;
1285 ro.safe_push (ne);
1289 return ro;
1292 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1293 GENERIC and a GIMPLE variant. */
1295 static void
1296 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1298 vec<operand *> matchers = lower_cond (s->match);
1299 for (unsigned i = 0; i < matchers.length (); ++i)
1301 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1302 s->for_vec, s->capture_ids);
1303 simplifiers.safe_push (ns);
1307 /* Return true if O refers to ID. */
1309 bool
1310 contains_id (operand *o, user_id *id)
1312 if (capture *c = dyn_cast<capture *> (o))
1313 return c->what && contains_id (c->what, id);
1315 if (expr *e = dyn_cast<expr *> (o))
1317 if (e->operation == id)
1318 return true;
1319 for (unsigned i = 0; i < e->ops.length (); ++i)
1320 if (contains_id (e->ops[i], id))
1321 return true;
1322 return false;
1325 if (with_expr *w = dyn_cast <with_expr *> (o))
1326 return (contains_id (w->with, id)
1327 || contains_id (w->subexpr, id));
1329 if (if_expr *ife = dyn_cast <if_expr *> (o))
1330 return (contains_id (ife->cond, id)
1331 || contains_id (ife->trueexpr, id)
1332 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1334 if (c_expr *ce = dyn_cast<c_expr *> (o))
1335 return ce->capture_ids && ce->capture_ids->get (id->id);
1337 return false;
1341 /* In AST operand O replace operator ID with operator WITH. */
1343 operand *
1344 replace_id (operand *o, user_id *id, id_base *with)
1346 /* Deep-copy captures and expressions, replacing operations as
1347 needed. */
1348 if (capture *c = dyn_cast<capture *> (o))
1350 if (!c->what)
1351 return c;
1352 return new capture (c->location, c->where,
1353 replace_id (c->what, id, with), c->value_match);
1355 else if (expr *e = dyn_cast<expr *> (o))
1357 expr *ne = new expr (e);
1358 if (e->operation == id)
1359 ne->operation = with;
1360 for (unsigned i = 0; i < e->ops.length (); ++i)
1361 ne->append_op (replace_id (e->ops[i], id, with));
1362 return ne;
1364 else if (with_expr *w = dyn_cast <with_expr *> (o))
1366 with_expr *nw = new with_expr (w->location);
1367 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1368 nw->subexpr = replace_id (w->subexpr, id, with);
1369 return nw;
1371 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1373 if_expr *nife = new if_expr (ife->location);
1374 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1375 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1376 if (ife->falseexpr)
1377 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1378 return nife;
1381 /* For c_expr we simply record a string replacement table which is
1382 applied at code-generation time. */
1383 if (c_expr *ce = dyn_cast<c_expr *> (o))
1385 vec<c_expr::id_tab> ids = ce->ids.copy ();
1386 ids.safe_push (c_expr::id_tab (id->id, with->id));
1387 return new c_expr (ce->r, ce->location,
1388 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1391 return o;
1394 /* Return true if the binary operator OP is ok for delayed substitution
1395 during for lowering. */
1397 static bool
1398 binary_ok (operator_id *op)
1400 switch (op->code)
1402 case PLUS_EXPR:
1403 case MINUS_EXPR:
1404 case MULT_EXPR:
1405 case TRUNC_DIV_EXPR:
1406 case CEIL_DIV_EXPR:
1407 case FLOOR_DIV_EXPR:
1408 case ROUND_DIV_EXPR:
1409 case TRUNC_MOD_EXPR:
1410 case CEIL_MOD_EXPR:
1411 case FLOOR_MOD_EXPR:
1412 case ROUND_MOD_EXPR:
1413 case RDIV_EXPR:
1414 case EXACT_DIV_EXPR:
1415 case MIN_EXPR:
1416 case MAX_EXPR:
1417 case BIT_IOR_EXPR:
1418 case BIT_XOR_EXPR:
1419 case BIT_AND_EXPR:
1420 return true;
1421 default:
1422 return false;
1426 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1428 static void
1429 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1431 vec<vec<user_id *> >& for_vec = sin->for_vec;
1432 unsigned worklist_start = 0;
1433 auto_vec<simplify *> worklist;
1434 worklist.safe_push (sin);
1436 /* Lower each recorded for separately, operating on the
1437 set of simplifiers created by the previous one.
1438 Lower inner-to-outer so inner for substitutes can refer
1439 to operators replaced by outer fors. */
1440 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1442 vec<user_id *>& ids = for_vec[fi];
1443 unsigned n_ids = ids.length ();
1444 unsigned max_n_opers = 0;
1445 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1446 for (unsigned i = 0; i < n_ids; ++i)
1448 if (ids[i]->substitutes.length () > max_n_opers)
1449 max_n_opers = ids[i]->substitutes.length ();
1450 /* Require that all substitutes are of the same kind so that
1451 if we delay substitution to the result op code generation
1452 can look at the first substitute for deciding things like
1453 types of operands. */
1454 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1455 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1456 if (ids[i]->substitutes[j]->kind != kind)
1457 can_delay_subst = false;
1458 else if (operator_id *op
1459 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1461 operator_id *op0
1462 = as_a <operator_id *> (ids[i]->substitutes[0]);
1463 if (strcmp (op->tcc, "tcc_comparison") == 0
1464 && strcmp (op0->tcc, "tcc_comparison") == 0)
1466 /* Unfortunately we can't just allow all tcc_binary. */
1467 else if (strcmp (op->tcc, "tcc_binary") == 0
1468 && strcmp (op0->tcc, "tcc_binary") == 0
1469 && binary_ok (op)
1470 && binary_ok (op0))
1472 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1473 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1474 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1475 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1477 else
1478 can_delay_subst = false;
1480 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1482 else
1483 can_delay_subst = false;
1486 unsigned worklist_end = worklist.length ();
1487 for (unsigned si = worklist_start; si < worklist_end; ++si)
1489 simplify *s = worklist[si];
1490 for (unsigned j = 0; j < max_n_opers; ++j)
1492 operand *match_op = s->match;
1493 operand *result_op = s->result;
1494 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1495 bool skip = false;
1496 for (unsigned i = 0; i < n_ids; ++i)
1498 user_id *id = ids[i];
1499 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1500 if (oper == null_id
1501 && (contains_id (match_op, id)
1502 || contains_id (result_op, id)))
1504 skip = true;
1505 break;
1507 subst.quick_push (std::make_pair (id, oper));
1508 match_op = replace_id (match_op, id, oper);
1509 if (result_op
1510 && !can_delay_subst)
1511 result_op = replace_id (result_op, id, oper);
1513 if (skip)
1514 continue;
1516 simplify *ns = new simplify (s->kind, s->id, match_op, result_op,
1517 vNULL, s->capture_ids);
1518 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1519 if (result_op
1520 && can_delay_subst)
1521 ns->for_subst_vec.safe_splice (subst);
1523 worklist.safe_push (ns);
1526 worklist_start = worklist_end;
1529 /* Copy out the result from the last for lowering. */
1530 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1531 simplifiers.safe_push (worklist[i]);
1534 /* Lower the AST for everything in SIMPLIFIERS. */
1536 static void
1537 lower (vec<simplify *>& simplifiers, bool gimple)
1539 auto_vec<simplify *> out_simplifiers;
1540 for (unsigned i = 0; i < simplifiers.length (); ++i)
1541 lower_opt_convert (simplifiers[i], out_simplifiers);
1543 simplifiers.truncate (0);
1544 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1545 lower_commutative (out_simplifiers[i], simplifiers);
1547 out_simplifiers.truncate (0);
1548 if (gimple)
1549 for (unsigned i = 0; i < simplifiers.length (); ++i)
1550 lower_cond (simplifiers[i], out_simplifiers);
1551 else
1552 out_simplifiers.safe_splice (simplifiers);
1555 simplifiers.truncate (0);
1556 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1557 lower_for (out_simplifiers[i], simplifiers);
1563 /* The decision tree built for generating GIMPLE and GENERIC pattern
1564 matching code. It represents the 'match' expression of all
1565 simplifies and has those as its leafs. */
1567 struct dt_simplify;
1569 /* A hash-map collecting semantically equivalent leafs in the decision
1570 tree for splitting out to separate functions. */
1571 struct sinfo
1573 dt_simplify *s;
1575 const char *fname;
1576 unsigned cnt;
1579 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1580 sinfo *>
1582 static inline hashval_t hash (const key_type &);
1583 static inline bool equal_keys (const key_type &, const key_type &);
1584 template <typename T> static inline void remove (T &) {}
1587 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1588 sinfo_map_t;
1590 /* Current simplifier ID we are processing during insertion into the
1591 decision tree. */
1592 static unsigned current_id;
1594 /* Decision tree base class, used for DT_NODE. */
1596 struct dt_node
1598 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1600 enum dt_type type;
1601 unsigned level;
1602 dt_node *parent;
1603 vec<dt_node *> kids;
1605 /* Statistics. */
1606 unsigned num_leafs;
1607 unsigned total_size;
1608 unsigned max_level;
1610 dt_node (enum dt_type type_, dt_node *parent_)
1611 : type (type_), level (0), parent (parent_), kids (vNULL) {}
1613 dt_node *append_node (dt_node *);
1614 dt_node *append_op (operand *, dt_node *parent, unsigned pos);
1615 dt_node *append_true_op (operand *, dt_node *parent, unsigned pos);
1616 dt_node *append_match_op (operand *, dt_operand *, dt_node *parent,
1617 unsigned pos);
1618 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1620 virtual void gen (FILE *, int, bool) {}
1622 void gen_kids (FILE *, int, bool);
1623 void gen_kids_1 (FILE *, int, bool,
1624 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1625 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1627 void analyze (sinfo_map_t &);
1630 /* Generic decision tree node used for DT_OPERAND, DT_MATCH and DT_TRUE. */
1632 struct dt_operand : public dt_node
1634 operand *op;
1635 dt_operand *match_dop;
1636 unsigned pos;
1637 bool value_match;
1638 unsigned for_id;
1640 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1641 dt_operand *parent_, unsigned pos_)
1642 : dt_node (type, parent_), op (op_), match_dop (match_dop_),
1643 pos (pos_), value_match (false), for_id (current_id) {}
1645 void gen (FILE *, int, bool);
1646 unsigned gen_predicate (FILE *, int, const char *, bool);
1647 unsigned gen_match_op (FILE *, int, const char *, bool);
1649 unsigned gen_gimple_expr (FILE *, int);
1650 unsigned gen_generic_expr (FILE *, int, const char *);
1652 char *get_name (char *);
1653 void gen_opname (char *, unsigned);
1656 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1658 struct dt_simplify : public dt_node
1660 simplify *s;
1661 unsigned pattern_no;
1662 dt_operand **indexes;
1663 sinfo *info;
1665 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1666 : dt_node (DT_SIMPLIFY, NULL), s (s_), pattern_no (pattern_no_),
1667 indexes (indexes_), info (NULL) {}
1669 void gen_1 (FILE *, int, bool, operand *);
1670 void gen (FILE *f, int, bool);
1673 template<>
1674 template<>
1675 inline bool
1676 is_a_helper <dt_operand *>::test (dt_node *n)
1678 return (n->type == dt_node::DT_OPERAND
1679 || n->type == dt_node::DT_MATCH
1680 || n->type == dt_node::DT_TRUE);
1683 template<>
1684 template<>
1685 inline bool
1686 is_a_helper <dt_simplify *>::test (dt_node *n)
1688 return n->type == dt_node::DT_SIMPLIFY;
1693 /* A container for the actual decision tree. */
1695 struct decision_tree
1697 dt_node *root;
1699 void insert (struct simplify *, unsigned);
1700 void gen (FILE *f, bool gimple);
1701 void print (FILE *f = stderr);
1703 decision_tree () { root = new dt_node (dt_node::DT_NODE, NULL); }
1705 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1706 unsigned pos = 0, dt_node *parent = 0);
1707 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1708 static bool cmp_node (dt_node *, dt_node *);
1709 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1712 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1714 bool
1715 cmp_operand (operand *o1, operand *o2)
1717 if (!o1 || !o2 || o1->type != o2->type)
1718 return false;
1720 if (o1->type == operand::OP_PREDICATE)
1722 predicate *p1 = as_a<predicate *>(o1);
1723 predicate *p2 = as_a<predicate *>(o2);
1724 return p1->p == p2->p;
1726 else if (o1->type == operand::OP_EXPR)
1728 expr *e1 = static_cast<expr *>(o1);
1729 expr *e2 = static_cast<expr *>(o2);
1730 return (e1->operation == e2->operation
1731 && e1->is_generic == e2->is_generic);
1733 else
1734 return false;
1737 /* Compare two decision tree nodes N1 and N2 and return true if they
1738 are equal. */
1740 bool
1741 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1743 if (!n1 || !n2 || n1->type != n2->type)
1744 return false;
1746 if (n1 == n2)
1747 return true;
1749 if (n1->type == dt_node::DT_TRUE)
1750 return false;
1752 if (n1->type == dt_node::DT_OPERAND)
1753 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1754 (as_a<dt_operand *> (n2))->op);
1755 else if (n1->type == dt_node::DT_MATCH)
1756 return (((as_a<dt_operand *> (n1))->match_dop
1757 == (as_a<dt_operand *> (n2))->match_dop)
1758 && ((as_a<dt_operand *> (n1))->value_match
1759 == (as_a<dt_operand *> (n2))->value_match));
1760 return false;
1763 /* Search OPS for a decision tree node like P and return it if found. */
1765 dt_node *
1766 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1768 /* We can merge adjacent DT_TRUE. */
1769 if (p->type == dt_node::DT_TRUE
1770 && !ops.is_empty ()
1771 && ops.last ()->type == dt_node::DT_TRUE)
1772 return ops.last ();
1773 dt_operand *true_node = NULL;
1774 for (int i = ops.length () - 1; i >= 0; --i)
1776 /* But we can't merge across DT_TRUE nodes as they serve as
1777 pattern order barriers to make sure that patterns apply
1778 in order of appearance in case multiple matches are possible. */
1779 if (ops[i]->type == dt_node::DT_TRUE)
1781 if (! true_node
1782 || as_a <dt_operand *> (ops[i])->for_id > true_node->for_id)
1783 true_node = as_a <dt_operand *> (ops[i]);
1785 if (decision_tree::cmp_node (ops[i], p))
1787 /* Unless we are processing the same pattern or the blocking
1788 pattern is before the one we are going to merge with. */
1789 if (true_node
1790 && true_node->for_id != current_id
1791 && true_node->for_id > as_a <dt_operand *> (ops[i])->for_id)
1793 if (verbose >= 1)
1795 source_location p_loc = 0;
1796 if (p->type == dt_node::DT_OPERAND)
1797 p_loc = as_a <dt_operand *> (p)->op->location;
1798 source_location op_loc = 0;
1799 if (ops[i]->type == dt_node::DT_OPERAND)
1800 op_loc = as_a <dt_operand *> (ops[i])->op->location;
1801 source_location true_loc = 0;
1802 true_loc = true_node->op->location;
1803 warning_at (p_loc,
1804 "failed to merge decision tree node");
1805 warning_at (op_loc,
1806 "with the following");
1807 warning_at (true_loc,
1808 "because of the following which serves as ordering "
1809 "barrier");
1811 return NULL;
1813 return ops[i];
1816 return NULL;
1819 /* Append N to the decision tree if it there is not already an existing
1820 identical child. */
1822 dt_node *
1823 dt_node::append_node (dt_node *n)
1825 dt_node *kid;
1827 kid = decision_tree::find_node (kids, n);
1828 if (kid)
1829 return kid;
1831 kids.safe_push (n);
1832 n->level = this->level + 1;
1834 return n;
1837 /* Append OP to the decision tree. */
1839 dt_node *
1840 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1842 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1843 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1844 return append_node (n);
1847 /* Append a DT_TRUE decision tree node. */
1849 dt_node *
1850 dt_node::append_true_op (operand *op, dt_node *parent, unsigned pos)
1852 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1853 dt_operand *n = new dt_operand (DT_TRUE, op, 0, parent_, pos);
1854 return append_node (n);
1857 /* Append a DT_MATCH decision tree node. */
1859 dt_node *
1860 dt_node::append_match_op (operand *op, dt_operand *match_dop,
1861 dt_node *parent, unsigned pos)
1863 dt_operand *parent_ = as_a<dt_operand *> (parent);
1864 dt_operand *n = new dt_operand (DT_MATCH, op, match_dop, parent_, pos);
1865 return append_node (n);
1868 /* Append S to the decision tree. */
1870 dt_node *
1871 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1872 dt_operand **indexes)
1874 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1875 for (unsigned i = 0; i < kids.length (); ++i)
1876 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1878 warning_at (s->match->location, "duplicate pattern");
1879 warning_at (s2->s->match->location, "previous pattern defined here");
1880 print_operand (s->match, stderr);
1881 fprintf (stderr, "\n");
1883 return append_node (n);
1886 /* Analyze the node and its children. */
1888 void
1889 dt_node::analyze (sinfo_map_t &map)
1891 num_leafs = 0;
1892 total_size = 1;
1893 max_level = level;
1895 if (type == DT_SIMPLIFY)
1897 /* Populate the map of equivalent simplifies. */
1898 dt_simplify *s = as_a <dt_simplify *> (this);
1899 bool existed;
1900 sinfo *&si = map.get_or_insert (s, &existed);
1901 if (!existed)
1903 si = new sinfo;
1904 si->s = s;
1905 si->cnt = 1;
1906 si->fname = NULL;
1908 else
1909 si->cnt++;
1910 s->info = si;
1911 num_leafs = 1;
1912 return;
1915 for (unsigned i = 0; i < kids.length (); ++i)
1917 kids[i]->analyze (map);
1918 num_leafs += kids[i]->num_leafs;
1919 total_size += kids[i]->total_size;
1920 max_level = MAX (max_level, kids[i]->max_level);
1924 /* Insert O into the decision tree and return the decision tree node found
1925 or created. */
1927 dt_node *
1928 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1929 unsigned pos, dt_node *parent)
1931 dt_node *q, *elm = 0;
1933 if (capture *c = dyn_cast<capture *> (o))
1935 unsigned capt_index = c->where;
1937 if (indexes[capt_index] == 0)
1939 if (c->what)
1940 q = insert_operand (p, c->what, indexes, pos, parent);
1941 else
1943 q = elm = p->append_true_op (o, parent, pos);
1944 goto at_assert_elm;
1946 // get to the last capture
1947 for (operand *what = c->what;
1948 what && is_a<capture *> (what);
1949 c = as_a<capture *> (what), what = c->what)
1952 if (!c->what)
1954 unsigned cc_index = c->where;
1955 dt_operand *match_op = indexes[cc_index];
1957 dt_operand temp (dt_node::DT_TRUE, 0, 0, 0, 0);
1958 elm = decision_tree::find_node (p->kids, &temp);
1960 if (elm == 0)
1962 dt_operand temp (dt_node::DT_MATCH, 0, match_op, 0, 0);
1963 temp.value_match = c->value_match;
1964 elm = decision_tree::find_node (p->kids, &temp);
1967 else
1969 dt_operand temp (dt_node::DT_OPERAND, c->what, 0, 0, 0);
1970 elm = decision_tree::find_node (p->kids, &temp);
1973 at_assert_elm:
1974 gcc_assert (elm->type == dt_node::DT_TRUE
1975 || elm->type == dt_node::DT_OPERAND
1976 || elm->type == dt_node::DT_MATCH);
1977 indexes[capt_index] = static_cast<dt_operand *> (elm);
1978 return q;
1980 else
1982 p = p->append_match_op (o, indexes[capt_index], parent, pos);
1983 as_a <dt_operand *>(p)->value_match = c->value_match;
1984 if (c->what)
1985 return insert_operand (p, c->what, indexes, 0, p);
1986 else
1987 return p;
1990 p = p->append_op (o, parent, pos);
1991 q = p;
1993 if (expr *e = dyn_cast <expr *>(o))
1995 for (unsigned i = 0; i < e->ops.length (); ++i)
1996 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1999 return q;
2002 /* Insert S into the decision tree. */
2004 void
2005 decision_tree::insert (struct simplify *s, unsigned pattern_no)
2007 current_id = s->id;
2008 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
2009 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
2010 p->append_simplify (s, pattern_no, indexes);
2013 /* Debug functions to dump the decision tree. */
2015 DEBUG_FUNCTION void
2016 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
2018 if (p->type == dt_node::DT_NODE)
2019 fprintf (f, "root");
2020 else
2022 fprintf (f, "|");
2023 for (unsigned i = 0; i < indent; i++)
2024 fprintf (f, "-");
2026 if (p->type == dt_node::DT_OPERAND)
2028 dt_operand *dop = static_cast<dt_operand *>(p);
2029 print_operand (dop->op, f, true);
2031 else if (p->type == dt_node::DT_TRUE)
2032 fprintf (f, "true");
2033 else if (p->type == dt_node::DT_MATCH)
2034 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
2035 else if (p->type == dt_node::DT_SIMPLIFY)
2037 dt_simplify *s = static_cast<dt_simplify *> (p);
2038 fprintf (f, "simplify_%u { ", s->pattern_no);
2039 for (int i = 0; i <= s->s->capture_max; ++i)
2040 fprintf (f, "%p, ", (void *) s->indexes[i]);
2041 fprintf (f, " } ");
2043 if (is_a <dt_operand *> (p))
2044 fprintf (f, " [%u]", as_a <dt_operand *> (p)->for_id);
2047 fprintf (stderr, " (%p, %p), %u, %u\n",
2048 (void *) p, (void *) p->parent, p->level, p->kids.length ());
2050 for (unsigned i = 0; i < p->kids.length (); ++i)
2051 decision_tree::print_node (p->kids[i], f, indent + 2);
2054 DEBUG_FUNCTION void
2055 decision_tree::print (FILE *f)
2057 return decision_tree::print_node (root, f);
2061 /* For GENERIC we have to take care of wrapping multiple-used
2062 expressions with side-effects in save_expr and preserve side-effects
2063 of expressions with omit_one_operand. Analyze captures in
2064 match, result and with expressions and perform early-outs
2065 on the outermost match expression operands for cases we cannot
2066 handle. */
2068 struct capture_info
2070 capture_info (simplify *s, operand *, bool);
2071 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
2072 bool walk_result (operand *o, bool, operand *);
2073 void walk_c_expr (c_expr *);
2075 struct cinfo
2077 bool expr_p;
2078 bool cse_p;
2079 bool force_no_side_effects_p;
2080 bool force_single_use;
2081 bool cond_expr_cond_p;
2082 unsigned long toplevel_msk;
2083 unsigned match_use_count;
2084 unsigned result_use_count;
2085 unsigned same_as;
2086 capture *c;
2089 auto_vec<cinfo> info;
2090 unsigned long force_no_side_effects;
2091 bool gimple;
2094 /* Analyze captures in S. */
2096 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
2098 gimple = gimple_;
2100 expr *e;
2101 if (s->kind == simplify::MATCH)
2103 force_no_side_effects = -1;
2104 return;
2107 force_no_side_effects = 0;
2108 info.safe_grow_cleared (s->capture_max + 1);
2109 for (int i = 0; i <= s->capture_max; ++i)
2110 info[i].same_as = i;
2112 e = as_a <expr *> (s->match);
2113 for (unsigned i = 0; i < e->ops.length (); ++i)
2114 walk_match (e->ops[i], i,
2115 (i != 0 && *e->operation == COND_EXPR)
2116 || *e->operation == TRUTH_ANDIF_EXPR
2117 || *e->operation == TRUTH_ORIF_EXPR,
2118 i == 0
2119 && (*e->operation == COND_EXPR
2120 || *e->operation == VEC_COND_EXPR));
2122 walk_result (s->result, false, result);
2125 /* Analyze captures in the match expression piece O. */
2127 void
2128 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2129 bool conditional_p, bool cond_expr_cond_p)
2131 if (capture *c = dyn_cast <capture *> (o))
2133 unsigned where = c->where;
2134 info[where].match_use_count++;
2135 info[where].toplevel_msk |= 1 << toplevel_arg;
2136 info[where].force_no_side_effects_p |= conditional_p;
2137 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2138 if (!info[where].c)
2139 info[where].c = c;
2140 if (!c->what)
2141 return;
2142 /* Recurse to exprs and captures. */
2143 if (is_a <capture *> (c->what)
2144 || is_a <expr *> (c->what))
2145 walk_match (c->what, toplevel_arg, conditional_p, false);
2146 /* We need to look past multiple captures to find a captured
2147 expression as with conditional converts two captures
2148 can be collapsed onto the same expression. Also collect
2149 what captures capture the same thing. */
2150 while (c->what && is_a <capture *> (c->what))
2152 c = as_a <capture *> (c->what);
2153 if (info[c->where].same_as != c->where
2154 && info[c->where].same_as != info[where].same_as)
2155 fatal_at (c->location, "cannot handle this collapsed capture");
2156 info[c->where].same_as = info[where].same_as;
2158 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2159 expr *e;
2160 if (c->what
2161 && (e = dyn_cast <expr *> (c->what)))
2163 /* Zero-operand expression captures like ADDR_EXPR@0 are
2164 similar as predicates -- if they are not mentioned in
2165 the result we have to force them to have no side-effects. */
2166 if (e->ops.length () != 0)
2167 info[where].expr_p = true;
2168 info[where].force_single_use |= e->force_single_use;
2171 else if (expr *e = dyn_cast <expr *> (o))
2173 for (unsigned i = 0; i < e->ops.length (); ++i)
2175 bool cond_p = conditional_p;
2176 bool cond_expr_cond_p = false;
2177 if (i != 0 && *e->operation == COND_EXPR)
2178 cond_p = true;
2179 else if (*e->operation == TRUTH_ANDIF_EXPR
2180 || *e->operation == TRUTH_ORIF_EXPR)
2181 cond_p = true;
2182 if (i == 0
2183 && (*e->operation == COND_EXPR
2184 || *e->operation == VEC_COND_EXPR))
2185 cond_expr_cond_p = true;
2186 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
2189 else if (is_a <predicate *> (o))
2191 /* Mark non-captured leafs toplevel arg for checking. */
2192 force_no_side_effects |= 1 << toplevel_arg;
2193 if (verbose >= 1
2194 && !gimple)
2195 warning_at (o->location,
2196 "forcing no side-effects on possibly lost leaf");
2198 else
2199 gcc_unreachable ();
2202 /* Analyze captures in the result expression piece O. Return true
2203 if RESULT was visited in one of the children. Only visit
2204 non-if/with children if they are rooted on RESULT. */
2206 bool
2207 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2209 if (capture *c = dyn_cast <capture *> (o))
2211 unsigned where = info[c->where].same_as;
2212 info[where].result_use_count++;
2213 /* If we substitute an expression capture we don't know
2214 which captures this will end up using (well, we don't
2215 compute that). Force the uses to be side-effect free
2216 which means forcing the toplevels that reach the
2217 expression side-effect free. */
2218 if (info[where].expr_p)
2219 force_no_side_effects |= info[where].toplevel_msk;
2220 /* Mark CSE capture uses as forced to have no side-effects. */
2221 if (c->what
2222 && is_a <expr *> (c->what))
2224 info[where].cse_p = true;
2225 walk_result (c->what, true, result);
2228 else if (expr *e = dyn_cast <expr *> (o))
2230 id_base *opr = e->operation;
2231 if (user_id *uid = dyn_cast <user_id *> (opr))
2232 opr = uid->substitutes[0];
2233 for (unsigned i = 0; i < e->ops.length (); ++i)
2235 bool cond_p = conditional_p;
2236 if (i != 0 && *e->operation == COND_EXPR)
2237 cond_p = true;
2238 else if (*e->operation == TRUTH_ANDIF_EXPR
2239 || *e->operation == TRUTH_ORIF_EXPR)
2240 cond_p = true;
2241 walk_result (e->ops[i], cond_p, result);
2244 else if (if_expr *e = dyn_cast <if_expr *> (o))
2246 /* 'if' conditions should be all fine. */
2247 if (e->trueexpr == result)
2249 walk_result (e->trueexpr, false, result);
2250 return true;
2252 if (e->falseexpr == result)
2254 walk_result (e->falseexpr, false, result);
2255 return true;
2257 bool res = false;
2258 if (is_a <if_expr *> (e->trueexpr)
2259 || is_a <with_expr *> (e->trueexpr))
2260 res |= walk_result (e->trueexpr, false, result);
2261 if (e->falseexpr
2262 && (is_a <if_expr *> (e->falseexpr)
2263 || is_a <with_expr *> (e->falseexpr)))
2264 res |= walk_result (e->falseexpr, false, result);
2265 return res;
2267 else if (with_expr *e = dyn_cast <with_expr *> (o))
2269 bool res = (e->subexpr == result);
2270 if (res
2271 || is_a <if_expr *> (e->subexpr)
2272 || is_a <with_expr *> (e->subexpr))
2273 res |= walk_result (e->subexpr, false, result);
2274 if (res)
2275 walk_c_expr (e->with);
2276 return res;
2278 else if (c_expr *e = dyn_cast <c_expr *> (o))
2279 walk_c_expr (e);
2280 else
2281 gcc_unreachable ();
2283 return false;
2286 /* Look for captures in the C expr E. */
2288 void
2289 capture_info::walk_c_expr (c_expr *e)
2291 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2292 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2293 really escape through. */
2294 unsigned p_depth = 0;
2295 for (unsigned i = 0; i < e->code.length (); ++i)
2297 const cpp_token *t = &e->code[i];
2298 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2299 id_base *id;
2300 if (t->type == CPP_NAME
2301 && (strcmp ((const char *)CPP_HASHNODE
2302 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2303 || strcmp ((const char *)CPP_HASHNODE
2304 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2305 || strcmp ((const char *)CPP_HASHNODE
2306 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2307 || ((id = get_operator ((const char *)CPP_HASHNODE
2308 (t->val.node.node)->ident.str))
2309 && is_a <predicate_id *> (id)))
2310 && n->type == CPP_OPEN_PAREN)
2311 p_depth++;
2312 else if (t->type == CPP_CLOSE_PAREN
2313 && p_depth > 0)
2314 p_depth--;
2315 else if (p_depth == 0
2316 && t->type == CPP_ATSIGN
2317 && (n->type == CPP_NUMBER
2318 || n->type == CPP_NAME)
2319 && !(n->flags & PREV_WHITE))
2321 const char *id;
2322 if (n->type == CPP_NUMBER)
2323 id = (const char *)n->val.str.text;
2324 else
2325 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2326 unsigned *where = e->capture_ids->get(id);
2327 if (! where)
2328 fatal_at (n, "unknown capture id '%s'", id);
2329 info[info[*where].same_as].force_no_side_effects_p = true;
2330 if (verbose >= 1
2331 && !gimple)
2332 warning_at (t, "capture escapes");
2338 /* Code generation off the decision tree and the refered AST nodes. */
2340 bool
2341 is_conversion (id_base *op)
2343 return (*op == CONVERT_EXPR
2344 || *op == NOP_EXPR
2345 || *op == FLOAT_EXPR
2346 || *op == FIX_TRUNC_EXPR
2347 || *op == VIEW_CONVERT_EXPR);
2350 /* Get the type to be used for generating operand POS of OP from the
2351 various sources. */
2353 static const char *
2354 get_operand_type (id_base *op, unsigned pos,
2355 const char *in_type,
2356 const char *expr_type,
2357 const char *other_oprnd_type)
2359 /* Generally operands whose type does not match the type of the
2360 expression generated need to know their types but match and
2361 thus can fall back to 'other_oprnd_type'. */
2362 if (is_conversion (op))
2363 return other_oprnd_type;
2364 else if (*op == REALPART_EXPR
2365 || *op == IMAGPART_EXPR)
2366 return other_oprnd_type;
2367 else if (is_a <operator_id *> (op)
2368 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2369 return other_oprnd_type;
2370 else if (*op == COND_EXPR
2371 && pos == 0)
2372 return "boolean_type_node";
2373 else if (strncmp (op->id, "CFN_COND_", 9) == 0)
2375 /* IFN_COND_* operands 1 and later by default have the same type
2376 as the result. The type of operand 0 needs to be specified
2377 explicitly. */
2378 if (pos > 0 && expr_type)
2379 return expr_type;
2380 else if (pos > 0 && in_type)
2381 return in_type;
2382 else
2383 return NULL;
2385 else
2387 /* Otherwise all types should match - choose one in order of
2388 preference. */
2389 if (expr_type)
2390 return expr_type;
2391 else if (in_type)
2392 return in_type;
2393 else
2394 return other_oprnd_type;
2398 /* Generate transform code for an expression. */
2400 void
2401 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2402 int depth, const char *in_type, capture_info *cinfo,
2403 dt_operand **indexes, int)
2405 id_base *opr = operation;
2406 /* When we delay operator substituting during lowering of fors we
2407 make sure that for code-gen purposes the effects of each substitute
2408 are the same. Thus just look at that. */
2409 if (user_id *uid = dyn_cast <user_id *> (opr))
2410 opr = uid->substitutes[0];
2412 bool conversion_p = is_conversion (opr);
2413 const char *type = expr_type;
2414 char optype[64];
2415 if (type)
2416 /* If there was a type specification in the pattern use it. */
2418 else if (conversion_p)
2419 /* For conversions we need to build the expression using the
2420 outer type passed in. */
2421 type = in_type;
2422 else if (*opr == REALPART_EXPR
2423 || *opr == IMAGPART_EXPR)
2425 /* __real and __imag use the component type of its operand. */
2426 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2427 type = optype;
2429 else if (is_a <operator_id *> (opr)
2430 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2432 /* comparisons use boolean_type_node (or what gets in), but
2433 their operands need to figure out the types themselves. */
2434 if (in_type)
2435 type = in_type;
2436 else
2438 sprintf (optype, "boolean_type_node");
2439 type = optype;
2441 in_type = NULL;
2443 else if (*opr == COND_EXPR
2444 || *opr == VEC_COND_EXPR
2445 || strncmp (opr->id, "CFN_COND_", 9) == 0)
2447 /* Conditions are of the same type as their first alternative. */
2448 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2449 type = optype;
2451 else
2453 /* Other operations are of the same type as their first operand. */
2454 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2455 type = optype;
2457 if (!type)
2458 fatal_at (location, "cannot determine type of operand");
2460 fprintf_indent (f, indent, "{\n");
2461 indent += 2;
2462 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2463 char op0type[64];
2464 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2465 for (unsigned i = 0; i < ops.length (); ++i)
2467 char dest[32];
2468 snprintf (dest, 32, "ops%d[%u]", depth, i);
2469 const char *optype
2470 = get_operand_type (opr, i, in_type, expr_type,
2471 i == 0 ? NULL : op0type);
2472 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2473 cinfo, indexes,
2474 (*opr == COND_EXPR
2475 || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2478 const char *opr_name;
2479 if (*operation == CONVERT_EXPR)
2480 opr_name = "NOP_EXPR";
2481 else
2482 opr_name = operation->id;
2484 if (gimple)
2486 if (*opr == CONVERT_EXPR)
2488 fprintf_indent (f, indent,
2489 "if (%s != TREE_TYPE (ops%d[0])\n",
2490 type, depth);
2491 fprintf_indent (f, indent,
2492 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2493 type, depth);
2494 fprintf_indent (f, indent + 2, "{\n");
2495 indent += 4;
2497 /* ??? Building a stmt can fail for various reasons here, seq being
2498 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2499 So if we fail here we should continue matching other patterns. */
2500 fprintf_indent (f, indent, "gimple_match_op tem_op "
2501 "(res_op->cond.any_else (), %s, %s", opr_name, type);
2502 for (unsigned i = 0; i < ops.length (); ++i)
2503 fprintf (f, ", ops%d[%u]", depth, i);
2504 fprintf (f, ");\n");
2505 fprintf_indent (f, indent,
2506 "gimple_resimplify%d (lseq, &tem_op, valueize);\n",
2507 ops.length ());
2508 fprintf_indent (f, indent,
2509 "res = maybe_push_res_to_seq (&tem_op, lseq);\n");
2510 fprintf_indent (f, indent,
2511 "if (!res) return false;\n");
2512 if (*opr == CONVERT_EXPR)
2514 indent -= 4;
2515 fprintf_indent (f, indent, " }\n");
2516 fprintf_indent (f, indent, "else\n");
2517 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2520 else
2522 if (*opr == CONVERT_EXPR)
2524 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2525 depth, type);
2526 indent += 2;
2528 if (opr->kind == id_base::CODE)
2529 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2530 ops.length(), opr_name, type);
2531 else
2533 fprintf_indent (f, indent, "{\n");
2534 fprintf_indent (f, indent, " res = maybe_build_call_expr_loc (loc, "
2535 "%s, %s, %d", opr_name, type, ops.length());
2537 for (unsigned i = 0; i < ops.length (); ++i)
2538 fprintf (f, ", ops%d[%u]", depth, i);
2539 fprintf (f, ");\n");
2540 if (opr->kind != id_base::CODE)
2542 fprintf_indent (f, indent, " if (!res)\n");
2543 fprintf_indent (f, indent, " return NULL_TREE;\n");
2544 fprintf_indent (f, indent, "}\n");
2546 if (*opr == CONVERT_EXPR)
2548 indent -= 2;
2549 fprintf_indent (f, indent, "else\n");
2550 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2553 fprintf_indent (f, indent, "%s = res;\n", dest);
2554 indent -= 2;
2555 fprintf_indent (f, indent, "}\n");
2558 /* Generate code for a c_expr which is either the expression inside
2559 an if statement or a sequence of statements which computes a
2560 result to be stored to DEST. */
2562 void
2563 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2564 bool, int, const char *, capture_info *,
2565 dt_operand **, int)
2567 if (dest && nr_stmts == 1)
2568 fprintf_indent (f, indent, "%s = ", dest);
2570 unsigned stmt_nr = 1;
2571 for (unsigned i = 0; i < code.length (); ++i)
2573 const cpp_token *token = &code[i];
2575 /* Replace captures for code-gen. */
2576 if (token->type == CPP_ATSIGN)
2578 const cpp_token *n = &code[i+1];
2579 if ((n->type == CPP_NUMBER
2580 || n->type == CPP_NAME)
2581 && !(n->flags & PREV_WHITE))
2583 if (token->flags & PREV_WHITE)
2584 fputc (' ', f);
2585 const char *id;
2586 if (n->type == CPP_NUMBER)
2587 id = (const char *)n->val.str.text;
2588 else
2589 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2590 unsigned *cid = capture_ids->get (id);
2591 if (!cid)
2592 fatal_at (token, "unknown capture id");
2593 fprintf (f, "captures[%u]", *cid);
2594 ++i;
2595 continue;
2599 if (token->flags & PREV_WHITE)
2600 fputc (' ', f);
2602 if (token->type == CPP_NAME)
2604 const char *id = (const char *) NODE_NAME (token->val.node.node);
2605 unsigned j;
2606 for (j = 0; j < ids.length (); ++j)
2608 if (strcmp (id, ids[j].id) == 0)
2610 fprintf (f, "%s", ids[j].oper);
2611 break;
2614 if (j < ids.length ())
2615 continue;
2618 /* Output the token as string. */
2619 char *tk = (char *)cpp_token_as_text (r, token);
2620 fputs (tk, f);
2622 if (token->type == CPP_SEMICOLON)
2624 stmt_nr++;
2625 fputc ('\n', f);
2626 if (dest && stmt_nr == nr_stmts)
2627 fprintf_indent (f, indent, "%s = ", dest);
2632 /* Generate transform code for a capture. */
2634 void
2635 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2636 int depth, const char *in_type, capture_info *cinfo,
2637 dt_operand **indexes, int cond_handling)
2639 if (what && is_a<expr *> (what))
2641 if (indexes[where] == 0)
2643 char buf[20];
2644 sprintf (buf, "captures[%u]", where);
2645 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2646 cinfo, NULL);
2650 /* If in GENERIC some capture is used multiple times, unshare it except
2651 when emitting the last use. */
2652 if (!gimple
2653 && cinfo->info.exists ()
2654 && cinfo->info[cinfo->info[where].same_as].result_use_count > 1)
2656 fprintf_indent (f, indent, "%s = unshare_expr (captures[%u]);\n",
2657 dest, where);
2658 cinfo->info[cinfo->info[where].same_as].result_use_count--;
2660 else
2661 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2663 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2664 with substituting a capture of that. */
2665 if (gimple
2666 && cond_handling != 0
2667 && cinfo->info[where].cond_expr_cond_p)
2669 /* If substituting into a cond_expr condition, unshare. */
2670 if (cond_handling == 1)
2671 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2672 /* If substituting elsewhere we might need to decompose it. */
2673 else if (cond_handling == 2)
2675 /* ??? Returning false here will also not allow any other patterns
2676 to match unless this generator was split out. */
2677 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2678 fprintf_indent (f, indent, " {\n");
2679 fprintf_indent (f, indent, " if (!seq) return false;\n");
2680 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2681 " TREE_CODE (%s),"
2682 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2683 " TREE_OPERAND (%s, 1));\n",
2684 dest, dest, dest, dest, dest);
2685 fprintf_indent (f, indent, " }\n");
2690 /* Return the name of the operand representing the decision tree node.
2691 Use NAME as space to generate it. */
2693 char *
2694 dt_operand::get_name (char *name)
2696 if (! parent)
2697 sprintf (name, "t");
2698 else if (parent->level == 1)
2699 sprintf (name, "op%u", pos);
2700 else if (parent->type == dt_node::DT_MATCH)
2701 return as_a <dt_operand *> (parent)->get_name (name);
2702 else
2703 sprintf (name, "o%u%u", parent->level, pos);
2704 return name;
2707 /* Fill NAME with the operand name at position POS. */
2709 void
2710 dt_operand::gen_opname (char *name, unsigned pos)
2712 if (! parent)
2713 sprintf (name, "op%u", pos);
2714 else
2715 sprintf (name, "o%u%u", level, pos);
2718 /* Generate matching code for the decision tree operand which is
2719 a predicate. */
2721 unsigned
2722 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2724 predicate *p = as_a <predicate *> (op);
2726 if (p->p->matchers.exists ())
2728 /* If this is a predicate generated from a pattern mangle its
2729 name and pass on the valueize hook. */
2730 if (gimple)
2731 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2732 p->p->id, opname);
2733 else
2734 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2736 else
2737 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2738 fprintf_indent (f, indent + 2, "{\n");
2739 return 1;
2742 /* Generate matching code for the decision tree operand which is
2743 a capture-match. */
2745 unsigned
2746 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2748 char match_opname[20];
2749 match_dop->get_name (match_opname);
2750 if (value_match)
2751 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2752 opname, match_opname, opname, match_opname);
2753 else
2754 fprintf_indent (f, indent, "if (%s == %s || (operand_equal_p (%s, %s, 0) "
2755 "&& types_match (%s, %s)))\n",
2756 opname, match_opname, opname, match_opname,
2757 opname, match_opname);
2758 fprintf_indent (f, indent + 2, "{\n");
2759 return 1;
2762 /* Generate GIMPLE matching code for the decision tree operand. */
2764 unsigned
2765 dt_operand::gen_gimple_expr (FILE *f, int indent)
2767 expr *e = static_cast<expr *> (op);
2768 id_base *id = e->operation;
2769 unsigned n_ops = e->ops.length ();
2770 unsigned n_braces = 0;
2772 for (unsigned i = 0; i < n_ops; ++i)
2774 char child_opname[20];
2775 gen_opname (child_opname, i);
2777 if (id->kind == id_base::CODE)
2779 if (e->is_generic
2780 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2781 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2783 /* ??? If this is a memory operation we can't (and should not)
2784 match this. The only sensible operand types are
2785 SSA names and invariants. */
2786 if (e->is_generic)
2788 char opname[20];
2789 get_name (opname);
2790 fprintf_indent (f, indent,
2791 "tree %s = TREE_OPERAND (%s, %i);\n",
2792 child_opname, opname, i);
2794 else
2795 fprintf_indent (f, indent,
2796 "tree %s = TREE_OPERAND "
2797 "(gimple_assign_rhs1 (def), %i);\n",
2798 child_opname, i);
2799 fprintf_indent (f, indent,
2800 "if ((TREE_CODE (%s) == SSA_NAME\n",
2801 child_opname);
2802 fprintf_indent (f, indent,
2803 " || is_gimple_min_invariant (%s)))\n",
2804 child_opname);
2805 fprintf_indent (f, indent,
2806 " {\n");
2807 indent += 4;
2808 n_braces++;
2809 fprintf_indent (f, indent,
2810 "%s = do_valueize (valueize, %s);\n",
2811 child_opname, child_opname);
2812 continue;
2814 else
2815 fprintf_indent (f, indent,
2816 "tree %s = gimple_assign_rhs%u (def);\n",
2817 child_opname, i + 1);
2819 else
2820 fprintf_indent (f, indent,
2821 "tree %s = gimple_call_arg (def, %u);\n",
2822 child_opname, i);
2823 fprintf_indent (f, indent,
2824 "%s = do_valueize (valueize, %s);\n",
2825 child_opname, child_opname);
2827 /* While the toplevel operands are canonicalized by the caller
2828 after valueizing operands of sub-expressions we have to
2829 re-canonicalize operand order. */
2830 int opno = commutative_op (id);
2831 if (opno >= 0)
2833 char child_opname0[20], child_opname1[20];
2834 gen_opname (child_opname0, opno);
2835 gen_opname (child_opname1, opno + 1);
2836 fprintf_indent (f, indent,
2837 "if (tree_swap_operands_p (%s, %s))\n",
2838 child_opname0, child_opname1);
2839 fprintf_indent (f, indent,
2840 " std::swap (%s, %s);\n",
2841 child_opname0, child_opname1);
2844 return n_braces;
2847 /* Generate GENERIC matching code for the decision tree operand. */
2849 unsigned
2850 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2852 expr *e = static_cast<expr *> (op);
2853 unsigned n_ops = e->ops.length ();
2855 for (unsigned i = 0; i < n_ops; ++i)
2857 char child_opname[20];
2858 gen_opname (child_opname, i);
2860 if (e->operation->kind == id_base::CODE)
2861 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2862 child_opname, opname, i);
2863 else
2864 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2865 child_opname, opname, i);
2868 return 0;
2871 /* Generate matching code for the children of the decision tree node. */
2873 void
2874 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2876 auto_vec<dt_operand *> gimple_exprs;
2877 auto_vec<dt_operand *> generic_exprs;
2878 auto_vec<dt_operand *> fns;
2879 auto_vec<dt_operand *> generic_fns;
2880 auto_vec<dt_operand *> preds;
2881 auto_vec<dt_node *> others;
2883 for (unsigned i = 0; i < kids.length (); ++i)
2885 if (kids[i]->type == dt_node::DT_OPERAND)
2887 dt_operand *op = as_a<dt_operand *> (kids[i]);
2888 if (expr *e = dyn_cast <expr *> (op->op))
2890 if (e->ops.length () == 0
2891 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2892 generic_exprs.safe_push (op);
2893 else if (e->operation->kind == id_base::FN)
2895 if (gimple)
2896 fns.safe_push (op);
2897 else
2898 generic_fns.safe_push (op);
2900 else if (e->operation->kind == id_base::PREDICATE)
2901 preds.safe_push (op);
2902 else
2904 if (gimple && !e->is_generic)
2905 gimple_exprs.safe_push (op);
2906 else
2907 generic_exprs.safe_push (op);
2910 else if (op->op->type == operand::OP_PREDICATE)
2911 others.safe_push (kids[i]);
2912 else
2913 gcc_unreachable ();
2915 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2916 others.safe_push (kids[i]);
2917 else if (kids[i]->type == dt_node::DT_MATCH
2918 || kids[i]->type == dt_node::DT_TRUE)
2920 /* A DT_TRUE operand serves as a barrier - generate code now
2921 for what we have collected sofar.
2922 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2923 dependent matches to get out-of-order. Generate code now
2924 for what we have collected sofar. */
2925 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2926 fns, generic_fns, preds, others);
2927 /* And output the true operand itself. */
2928 kids[i]->gen (f, indent, gimple);
2929 gimple_exprs.truncate (0);
2930 generic_exprs.truncate (0);
2931 fns.truncate (0);
2932 generic_fns.truncate (0);
2933 preds.truncate (0);
2934 others.truncate (0);
2936 else
2937 gcc_unreachable ();
2940 /* Generate code for the remains. */
2941 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2942 fns, generic_fns, preds, others);
2945 /* Generate matching code for the children of the decision tree node. */
2947 void
2948 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2949 vec<dt_operand *> gimple_exprs,
2950 vec<dt_operand *> generic_exprs,
2951 vec<dt_operand *> fns,
2952 vec<dt_operand *> generic_fns,
2953 vec<dt_operand *> preds,
2954 vec<dt_node *> others)
2956 char buf[128];
2957 char *kid_opname = buf;
2959 unsigned exprs_len = gimple_exprs.length ();
2960 unsigned gexprs_len = generic_exprs.length ();
2961 unsigned fns_len = fns.length ();
2962 unsigned gfns_len = generic_fns.length ();
2964 if (exprs_len || fns_len || gexprs_len || gfns_len)
2966 if (exprs_len)
2967 gimple_exprs[0]->get_name (kid_opname);
2968 else if (fns_len)
2969 fns[0]->get_name (kid_opname);
2970 else if (gfns_len)
2971 generic_fns[0]->get_name (kid_opname);
2972 else
2973 generic_exprs[0]->get_name (kid_opname);
2975 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2976 fprintf_indent (f, indent, " {\n");
2977 indent += 2;
2980 if (exprs_len || fns_len)
2982 fprintf_indent (f, indent,
2983 "case SSA_NAME:\n");
2984 fprintf_indent (f, indent,
2985 " if (gimple *def_stmt = get_def (valueize, %s))\n",
2986 kid_opname);
2987 fprintf_indent (f, indent,
2988 " {\n");
2989 indent += 6;
2990 if (exprs_len)
2992 fprintf_indent (f, indent,
2993 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2994 fprintf_indent (f, indent,
2995 " switch (gimple_assign_rhs_code (def))\n");
2996 indent += 4;
2997 fprintf_indent (f, indent, "{\n");
2998 for (unsigned i = 0; i < exprs_len; ++i)
3000 expr *e = as_a <expr *> (gimple_exprs[i]->op);
3001 id_base *op = e->operation;
3002 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3003 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3004 else
3005 fprintf_indent (f, indent, "case %s:\n", op->id);
3006 fprintf_indent (f, indent, " {\n");
3007 gimple_exprs[i]->gen (f, indent + 4, true);
3008 fprintf_indent (f, indent, " break;\n");
3009 fprintf_indent (f, indent, " }\n");
3011 fprintf_indent (f, indent, "default:;\n");
3012 fprintf_indent (f, indent, "}\n");
3013 indent -= 4;
3016 if (fns_len)
3018 fprintf_indent (f, indent,
3019 "%sif (gcall *def = dyn_cast <gcall *>"
3020 " (def_stmt))\n",
3021 exprs_len ? "else " : "");
3022 fprintf_indent (f, indent,
3023 " switch (gimple_call_combined_fn (def))\n");
3025 indent += 4;
3026 fprintf_indent (f, indent, "{\n");
3027 for (unsigned i = 0; i < fns_len; ++i)
3029 expr *e = as_a <expr *>(fns[i]->op);
3030 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3031 fprintf_indent (f, indent, " {\n");
3032 fns[i]->gen (f, indent + 4, true);
3033 fprintf_indent (f, indent, " break;\n");
3034 fprintf_indent (f, indent, " }\n");
3037 fprintf_indent (f, indent, "default:;\n");
3038 fprintf_indent (f, indent, "}\n");
3039 indent -= 4;
3042 indent -= 6;
3043 fprintf_indent (f, indent, " }\n");
3044 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
3045 here rather than in the next loop. */
3046 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3048 expr *e = as_a <expr *>(generic_exprs[i]->op);
3049 id_base *op = e->operation;
3050 if (*op == SSA_NAME && (exprs_len || fns_len))
3052 fprintf_indent (f, indent + 4, "{\n");
3053 generic_exprs[i]->gen (f, indent + 6, gimple);
3054 fprintf_indent (f, indent + 4, "}\n");
3058 fprintf_indent (f, indent, " break;\n");
3061 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3063 expr *e = as_a <expr *>(generic_exprs[i]->op);
3064 id_base *op = e->operation;
3065 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3066 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3067 else if (*op == SSA_NAME && (exprs_len || fns_len))
3068 /* Already handled above. */
3069 continue;
3070 else
3071 fprintf_indent (f, indent, "case %s:\n", op->id);
3072 fprintf_indent (f, indent, " {\n");
3073 generic_exprs[i]->gen (f, indent + 4, gimple);
3074 fprintf_indent (f, indent, " break;\n");
3075 fprintf_indent (f, indent, " }\n");
3078 if (gfns_len)
3080 fprintf_indent (f, indent,
3081 "case CALL_EXPR:\n");
3082 fprintf_indent (f, indent,
3083 " switch (get_call_combined_fn (%s))\n",
3084 kid_opname);
3085 fprintf_indent (f, indent,
3086 " {\n");
3087 indent += 4;
3089 for (unsigned j = 0; j < generic_fns.length (); ++j)
3091 expr *e = as_a <expr *>(generic_fns[j]->op);
3092 gcc_assert (e->operation->kind == id_base::FN);
3094 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3095 fprintf_indent (f, indent, " {\n");
3096 generic_fns[j]->gen (f, indent + 4, false);
3097 fprintf_indent (f, indent, " break;\n");
3098 fprintf_indent (f, indent, " }\n");
3100 fprintf_indent (f, indent, "default:;\n");
3102 indent -= 4;
3103 fprintf_indent (f, indent, " }\n");
3104 fprintf_indent (f, indent, " break;\n");
3107 /* Close switch (TREE_CODE ()). */
3108 if (exprs_len || fns_len || gexprs_len || gfns_len)
3110 indent -= 4;
3111 fprintf_indent (f, indent, " default:;\n");
3112 fprintf_indent (f, indent, " }\n");
3115 for (unsigned i = 0; i < preds.length (); ++i)
3117 expr *e = as_a <expr *> (preds[i]->op);
3118 predicate_id *p = as_a <predicate_id *> (e->operation);
3119 preds[i]->get_name (kid_opname);
3120 fprintf_indent (f, indent, "{\n");
3121 indent += 2;
3122 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
3123 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
3124 gimple ? "gimple" : "tree",
3125 p->id, kid_opname, kid_opname,
3126 gimple ? ", valueize" : "");
3127 fprintf_indent (f, indent, " {\n");
3128 for (int j = 0; j < p->nargs; ++j)
3130 char child_opname[20];
3131 preds[i]->gen_opname (child_opname, j);
3132 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3133 child_opname, kid_opname, j);
3135 preds[i]->gen_kids (f, indent + 4, gimple);
3136 fprintf (f, "}\n");
3137 indent -= 2;
3138 fprintf_indent (f, indent, "}\n");
3141 for (unsigned i = 0; i < others.length (); ++i)
3142 others[i]->gen (f, indent, gimple);
3145 /* Generate matching code for the decision tree operand. */
3147 void
3148 dt_operand::gen (FILE *f, int indent, bool gimple)
3150 char opname[20];
3151 get_name (opname);
3153 unsigned n_braces = 0;
3155 if (type == DT_OPERAND)
3156 switch (op->type)
3158 case operand::OP_PREDICATE:
3159 n_braces = gen_predicate (f, indent, opname, gimple);
3160 break;
3162 case operand::OP_EXPR:
3163 if (gimple)
3164 n_braces = gen_gimple_expr (f, indent);
3165 else
3166 n_braces = gen_generic_expr (f, indent, opname);
3167 break;
3169 default:
3170 gcc_unreachable ();
3172 else if (type == DT_TRUE)
3174 else if (type == DT_MATCH)
3175 n_braces = gen_match_op (f, indent, opname, gimple);
3176 else
3177 gcc_unreachable ();
3179 indent += 4 * n_braces;
3180 gen_kids (f, indent, gimple);
3182 for (unsigned i = 0; i < n_braces; ++i)
3184 indent -= 4;
3185 if (indent < 0)
3186 indent = 0;
3187 fprintf_indent (f, indent, " }\n");
3192 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3193 step of a '(simplify ...)' or '(match ...)'. This handles everything
3194 that is not part of the decision tree (simplify->match).
3195 Main recursive worker. */
3197 void
3198 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3200 if (result)
3202 if (with_expr *w = dyn_cast <with_expr *> (result))
3204 fprintf_indent (f, indent, "{\n");
3205 indent += 4;
3206 output_line_directive (f, w->location);
3207 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3208 gen_1 (f, indent, gimple, w->subexpr);
3209 indent -= 4;
3210 fprintf_indent (f, indent, "}\n");
3211 return;
3213 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3215 output_line_directive (f, ife->location);
3216 fprintf_indent (f, indent, "if (");
3217 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3218 fprintf (f, ")\n");
3219 fprintf_indent (f, indent + 2, "{\n");
3220 indent += 4;
3221 gen_1 (f, indent, gimple, ife->trueexpr);
3222 indent -= 4;
3223 fprintf_indent (f, indent + 2, "}\n");
3224 if (ife->falseexpr)
3226 fprintf_indent (f, indent, "else\n");
3227 fprintf_indent (f, indent + 2, "{\n");
3228 indent += 4;
3229 gen_1 (f, indent, gimple, ife->falseexpr);
3230 indent -= 4;
3231 fprintf_indent (f, indent + 2, "}\n");
3233 return;
3237 /* Analyze captures and perform early-outs on the incoming arguments
3238 that cover cases we cannot handle. */
3239 capture_info cinfo (s, result, gimple);
3240 if (s->kind == simplify::SIMPLIFY)
3242 if (!gimple)
3244 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3245 if (cinfo.force_no_side_effects & (1 << i))
3247 fprintf_indent (f, indent,
3248 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
3250 if (verbose >= 1)
3251 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3252 "forcing toplevel operand to have no "
3253 "side-effects");
3255 for (int i = 0; i <= s->capture_max; ++i)
3256 if (cinfo.info[i].cse_p)
3258 else if (cinfo.info[i].force_no_side_effects_p
3259 && (cinfo.info[i].toplevel_msk
3260 & cinfo.force_no_side_effects) == 0)
3262 fprintf_indent (f, indent,
3263 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3264 "return NULL_TREE;\n", i);
3265 if (verbose >= 1)
3266 warning_at (cinfo.info[i].c->location,
3267 "forcing captured operand to have no "
3268 "side-effects");
3270 else if ((cinfo.info[i].toplevel_msk
3271 & cinfo.force_no_side_effects) != 0)
3272 /* Mark capture as having no side-effects if we had to verify
3273 that via forced toplevel operand checks. */
3274 cinfo.info[i].force_no_side_effects_p = true;
3276 if (gimple)
3278 /* Force single-use restriction by only allowing simple
3279 results via setting seq to NULL. */
3280 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3281 bool first_p = true;
3282 for (int i = 0; i <= s->capture_max; ++i)
3283 if (cinfo.info[i].force_single_use)
3285 if (first_p)
3287 fprintf_indent (f, indent, "if (lseq\n");
3288 fprintf_indent (f, indent, " && (");
3289 first_p = false;
3291 else
3293 fprintf (f, "\n");
3294 fprintf_indent (f, indent, " || ");
3296 fprintf (f, "!single_use (captures[%d])", i);
3298 if (!first_p)
3300 fprintf (f, "))\n");
3301 fprintf_indent (f, indent, " lseq = NULL;\n");
3306 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_FOLDING)) "
3307 "fprintf (dump_file, \"Applying pattern ");
3308 output_line_directive (f,
3309 result ? result->location : s->match->location, true);
3310 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3312 if (!result)
3314 /* If there is no result then this is a predicate implementation. */
3315 fprintf_indent (f, indent, "return true;\n");
3317 else if (gimple)
3319 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3320 in outermost position). */
3321 if (result->type == operand::OP_EXPR
3322 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3323 result = as_a <expr *> (result)->ops[0];
3324 if (result->type == operand::OP_EXPR)
3326 expr *e = as_a <expr *> (result);
3327 id_base *opr = e->operation;
3328 bool is_predicate = false;
3329 /* When we delay operator substituting during lowering of fors we
3330 make sure that for code-gen purposes the effects of each substitute
3331 are the same. Thus just look at that. */
3332 if (user_id *uid = dyn_cast <user_id *> (opr))
3333 opr = uid->substitutes[0];
3334 else if (is_a <predicate_id *> (opr))
3335 is_predicate = true;
3336 if (!is_predicate)
3337 fprintf_indent (f, indent, "res_op->set_op (%s, type, %d);\n",
3338 *e->operation == CONVERT_EXPR
3339 ? "NOP_EXPR" : e->operation->id,
3340 e->ops.length ());
3341 for (unsigned j = 0; j < e->ops.length (); ++j)
3343 char dest[32];
3344 if (is_predicate)
3345 snprintf (dest, 32, "res_ops[%d]", j);
3346 else
3347 snprintf (dest, 32, "res_op->ops[%d]", j);
3348 const char *optype
3349 = get_operand_type (opr, j,
3350 "type", e->expr_type,
3351 j == 0 ? NULL
3352 : "TREE_TYPE (res_op->ops[0])");
3353 /* We need to expand GENERIC conditions we captured from
3354 COND_EXPRs and we need to unshare them when substituting
3355 into COND_EXPRs. */
3356 int cond_handling = 0;
3357 if (!is_predicate)
3358 cond_handling = ((*opr == COND_EXPR
3359 || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3360 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3361 &cinfo, indexes, cond_handling);
3364 /* Re-fold the toplevel result. It's basically an embedded
3365 gimple_build w/o actually building the stmt. */
3366 if (!is_predicate)
3367 fprintf_indent (f, indent,
3368 "gimple_resimplify%d (lseq, res_op,"
3369 " valueize);\n", e->ops.length ());
3371 else if (result->type == operand::OP_CAPTURE
3372 || result->type == operand::OP_C_EXPR)
3374 fprintf_indent (f, indent, "tree tem;\n");
3375 result->gen_transform (f, indent, "tem", true, 1, "type",
3376 &cinfo, indexes);
3377 fprintf_indent (f, indent, "res_op->set_value (tem);\n");
3378 if (is_a <capture *> (result)
3379 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3381 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3382 with substituting a capture of that. */
3383 fprintf_indent (f, indent,
3384 "if (COMPARISON_CLASS_P (tem))\n");
3385 fprintf_indent (f, indent,
3386 " {\n");
3387 fprintf_indent (f, indent,
3388 " res_op->ops[0] = TREE_OPERAND (tem, 0);\n");
3389 fprintf_indent (f, indent,
3390 " res_op->ops[1] = TREE_OPERAND (tem, 1);\n");
3391 fprintf_indent (f, indent,
3392 " }\n");
3395 else
3396 gcc_unreachable ();
3397 fprintf_indent (f, indent, "return true;\n");
3399 else /* GENERIC */
3401 bool is_predicate = false;
3402 if (result->type == operand::OP_EXPR)
3404 expr *e = as_a <expr *> (result);
3405 id_base *opr = e->operation;
3406 /* When we delay operator substituting during lowering of fors we
3407 make sure that for code-gen purposes the effects of each substitute
3408 are the same. Thus just look at that. */
3409 if (user_id *uid = dyn_cast <user_id *> (opr))
3410 opr = uid->substitutes[0];
3411 else if (is_a <predicate_id *> (opr))
3412 is_predicate = true;
3413 /* Search for captures used multiple times in the result expression
3414 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3415 original expression. */
3416 if (!is_predicate)
3417 for (int i = 0; i < s->capture_max + 1; ++i)
3419 if (cinfo.info[i].same_as != (unsigned)i
3420 || cinfo.info[i].cse_p)
3421 continue;
3422 if (cinfo.info[i].result_use_count
3423 > cinfo.info[i].match_use_count)
3424 fprintf_indent (f, indent,
3425 "if (! tree_invariant_p (captures[%d])) "
3426 "return NULL_TREE;\n", i);
3428 for (unsigned j = 0; j < e->ops.length (); ++j)
3430 char dest[32];
3431 if (is_predicate)
3432 snprintf (dest, 32, "res_ops[%d]", j);
3433 else
3435 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3436 snprintf (dest, 32, "res_op%d", j);
3438 const char *optype
3439 = get_operand_type (opr, j,
3440 "type", e->expr_type,
3441 j == 0
3442 ? NULL : "TREE_TYPE (res_op0)");
3443 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3444 &cinfo, indexes);
3446 if (is_predicate)
3447 fprintf_indent (f, indent, "return true;\n");
3448 else
3450 fprintf_indent (f, indent, "tree res;\n");
3451 /* Re-fold the toplevel result. Use non_lvalue to
3452 build NON_LVALUE_EXPRs so they get properly
3453 ignored when in GIMPLE form. */
3454 if (*opr == NON_LVALUE_EXPR)
3455 fprintf_indent (f, indent,
3456 "res = non_lvalue_loc (loc, res_op0);\n");
3457 else
3459 if (is_a <operator_id *> (opr))
3460 fprintf_indent (f, indent,
3461 "res = fold_build%d_loc (loc, %s, type",
3462 e->ops.length (),
3463 *e->operation == CONVERT_EXPR
3464 ? "NOP_EXPR" : e->operation->id);
3465 else
3466 fprintf_indent (f, indent,
3467 "res = maybe_build_call_expr_loc (loc, "
3468 "%s, type, %d", e->operation->id,
3469 e->ops.length());
3470 for (unsigned j = 0; j < e->ops.length (); ++j)
3471 fprintf (f, ", res_op%d", j);
3472 fprintf (f, ");\n");
3473 if (!is_a <operator_id *> (opr))
3475 fprintf_indent (f, indent, "if (!res)\n");
3476 fprintf_indent (f, indent, " return NULL_TREE;\n");
3481 else if (result->type == operand::OP_CAPTURE
3482 || result->type == operand::OP_C_EXPR)
3485 fprintf_indent (f, indent, "tree res;\n");
3486 result->gen_transform (f, indent, "res", false, 1, "type",
3487 &cinfo, indexes);
3489 else
3490 gcc_unreachable ();
3491 if (!is_predicate)
3493 /* Search for captures not used in the result expression and dependent
3494 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3495 for (int i = 0; i < s->capture_max + 1; ++i)
3497 if (cinfo.info[i].same_as != (unsigned)i)
3498 continue;
3499 if (!cinfo.info[i].force_no_side_effects_p
3500 && !cinfo.info[i].expr_p
3501 && cinfo.info[i].result_use_count == 0)
3503 fprintf_indent (f, indent,
3504 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3506 fprintf_indent (f, indent + 2,
3507 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3508 "fold_ignored_result (captures[%d]), res);\n",
3512 fprintf_indent (f, indent, "return res;\n");
3517 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3518 step of a '(simplify ...)' or '(match ...)'. This handles everything
3519 that is not part of the decision tree (simplify->match). */
3521 void
3522 dt_simplify::gen (FILE *f, int indent, bool gimple)
3524 fprintf_indent (f, indent, "{\n");
3525 indent += 2;
3526 output_line_directive (f,
3527 s->result ? s->result->location : s->match->location);
3528 if (s->capture_max >= 0)
3530 char opname[20];
3531 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3532 s->capture_max + 1, indexes[0]->get_name (opname));
3534 for (int i = 1; i <= s->capture_max; ++i)
3536 if (!indexes[i])
3537 break;
3538 fprintf (f, ", %s", indexes[i]->get_name (opname));
3540 fprintf (f, " };\n");
3543 /* If we have a split-out function for the actual transform, call it. */
3544 if (info && info->fname)
3546 if (gimple)
3548 fprintf_indent (f, indent, "if (%s (res_op, seq, "
3549 "valueize, type, captures", info->fname);
3550 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3551 if (s->for_subst_vec[i].first->used)
3552 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3553 fprintf (f, "))\n");
3554 fprintf_indent (f, indent, " return true;\n");
3556 else
3558 fprintf_indent (f, indent, "tree res = %s (loc, type",
3559 info->fname);
3560 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3561 fprintf (f, ", op%d", i);
3562 fprintf (f, ", captures");
3563 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3565 if (s->for_subst_vec[i].first->used)
3566 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3568 fprintf (f, ");\n");
3569 fprintf_indent (f, indent, "if (res) return res;\n");
3572 else
3574 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3576 if (! s->for_subst_vec[i].first->used)
3577 continue;
3578 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3579 fprintf_indent (f, indent, "const enum tree_code %s = %s;\n",
3580 s->for_subst_vec[i].first->id,
3581 s->for_subst_vec[i].second->id);
3582 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3583 fprintf_indent (f, indent, "const combined_fn %s = %s;\n",
3584 s->for_subst_vec[i].first->id,
3585 s->for_subst_vec[i].second->id);
3586 else
3587 gcc_unreachable ();
3589 gen_1 (f, indent, gimple, s->result);
3592 indent -= 2;
3593 fprintf_indent (f, indent, "}\n");
3597 /* Hash function for finding equivalent transforms. */
3599 hashval_t
3600 sinfo_hashmap_traits::hash (const key_type &v)
3602 /* Only bother to compare those originating from the same source pattern. */
3603 return v->s->result->location;
3606 /* Compare function for finding equivalent transforms. */
3608 static bool
3609 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3611 if (o1->type != o2->type)
3612 return false;
3614 switch (o1->type)
3616 case operand::OP_IF:
3618 if_expr *if1 = as_a <if_expr *> (o1);
3619 if_expr *if2 = as_a <if_expr *> (o2);
3620 /* ??? Properly compare c-exprs. */
3621 if (if1->cond != if2->cond)
3622 return false;
3623 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3624 return false;
3625 if (if1->falseexpr != if2->falseexpr
3626 || (if1->falseexpr
3627 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3628 return false;
3629 return true;
3631 case operand::OP_WITH:
3633 with_expr *with1 = as_a <with_expr *> (o1);
3634 with_expr *with2 = as_a <with_expr *> (o2);
3635 if (with1->with != with2->with)
3636 return false;
3637 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3639 default:;
3642 /* We've hit a result. Time to compare capture-infos - this is required
3643 in addition to the conservative pointer-equivalency of the result IL. */
3644 capture_info cinfo1 (s1, o1, true);
3645 capture_info cinfo2 (s2, o2, true);
3647 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3648 || cinfo1.info.length () != cinfo2.info.length ())
3649 return false;
3651 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3653 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3654 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3655 || (cinfo1.info[i].force_no_side_effects_p
3656 != cinfo2.info[i].force_no_side_effects_p)
3657 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3658 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3659 /* toplevel_msk is an optimization */
3660 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3661 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3662 /* the pointer back to the capture is for diagnostics only */)
3663 return false;
3666 /* ??? Deep-compare the actual result. */
3667 return o1 == o2;
3670 bool
3671 sinfo_hashmap_traits::equal_keys (const key_type &v,
3672 const key_type &candidate)
3674 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3678 /* Main entry to generate code for matching GIMPLE IL off the decision
3679 tree. */
3681 void
3682 decision_tree::gen (FILE *f, bool gimple)
3684 sinfo_map_t si;
3686 root->analyze (si);
3688 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3689 "a total number of %u nodes\n",
3690 gimple ? "GIMPLE" : "GENERIC",
3691 root->num_leafs, root->max_level, root->total_size);
3693 /* First split out the transform part of equal leafs. */
3694 unsigned rcnt = 0;
3695 unsigned fcnt = 1;
3696 for (sinfo_map_t::iterator iter = si.begin ();
3697 iter != si.end (); ++iter)
3699 sinfo *s = (*iter).second;
3700 /* Do not split out single uses. */
3701 if (s->cnt <= 1)
3702 continue;
3704 rcnt += s->cnt - 1;
3705 if (verbose >= 1)
3707 fprintf (stderr, "found %u uses of", s->cnt);
3708 output_line_directive (stderr, s->s->s->result->location);
3711 /* Generate a split out function with the leaf transform code. */
3712 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3713 fcnt++);
3714 if (gimple)
3715 fprintf (f, "\nstatic bool\n"
3716 "%s (gimple_match_op *res_op, gimple_seq *seq,\n"
3717 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
3718 " const tree ARG_UNUSED (type), tree *ARG_UNUSED "
3719 "(captures)\n",
3720 s->fname);
3721 else
3723 fprintf (f, "\nstatic tree\n"
3724 "%s (location_t ARG_UNUSED (loc), const tree ARG_UNUSED (type),\n",
3725 (*iter).second->fname);
3726 for (unsigned i = 0;
3727 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3728 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3729 fprintf (f, " tree *captures\n");
3731 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3733 if (! s->s->s->for_subst_vec[i].first->used)
3734 continue;
3735 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3736 fprintf (f, ", const enum tree_code ARG_UNUSED (%s)",
3737 s->s->s->for_subst_vec[i].first->id);
3738 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3739 fprintf (f, ", const combined_fn ARG_UNUSED (%s)",
3740 s->s->s->for_subst_vec[i].first->id);
3743 fprintf (f, ")\n{\n");
3744 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3745 if (gimple)
3746 fprintf (f, " return false;\n");
3747 else
3748 fprintf (f, " return NULL_TREE;\n");
3749 fprintf (f, "}\n");
3751 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3753 for (unsigned n = 1; n <= 5; ++n)
3755 /* First generate split-out functions. */
3756 for (unsigned i = 0; i < root->kids.length (); i++)
3758 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3759 expr *e = static_cast<expr *>(dop->op);
3760 if (e->ops.length () != n
3761 /* Builtin simplifications are somewhat premature on
3762 GENERIC. The following drops patterns with outermost
3763 calls. It's easy to emit overloads for function code
3764 though if necessary. */
3765 || (!gimple
3766 && e->operation->kind != id_base::CODE))
3767 continue;
3769 if (gimple)
3770 fprintf (f, "\nstatic bool\n"
3771 "gimple_simplify_%s (gimple_match_op *res_op,"
3772 " gimple_seq *seq,\n"
3773 " tree (*valueize)(tree) "
3774 "ATTRIBUTE_UNUSED,\n"
3775 " code_helper ARG_UNUSED (code), tree "
3776 "ARG_UNUSED (type)\n",
3777 e->operation->id);
3778 else
3779 fprintf (f, "\nstatic tree\n"
3780 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3781 "tree_code ARG_UNUSED (code), const tree ARG_UNUSED (type)",
3782 e->operation->id);
3783 for (unsigned i = 0; i < n; ++i)
3784 fprintf (f, ", tree op%d", i);
3785 fprintf (f, ")\n");
3786 fprintf (f, "{\n");
3787 dop->gen_kids (f, 2, gimple);
3788 if (gimple)
3789 fprintf (f, " return false;\n");
3790 else
3791 fprintf (f, " return NULL_TREE;\n");
3792 fprintf (f, "}\n");
3795 /* Then generate the main entry with the outermost switch and
3796 tail-calls to the split-out functions. */
3797 if (gimple)
3798 fprintf (f, "\nstatic bool\n"
3799 "gimple_simplify (gimple_match_op *res_op, gimple_seq *seq,\n"
3800 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
3801 " code_helper code, const tree type");
3802 else
3803 fprintf (f, "\ntree\n"
3804 "generic_simplify (location_t loc, enum tree_code code, "
3805 "const tree type ATTRIBUTE_UNUSED");
3806 for (unsigned i = 0; i < n; ++i)
3807 fprintf (f, ", tree op%d", i);
3808 fprintf (f, ")\n");
3809 fprintf (f, "{\n");
3811 if (gimple)
3812 fprintf (f, " switch (code.get_rep())\n"
3813 " {\n");
3814 else
3815 fprintf (f, " switch (code)\n"
3816 " {\n");
3817 for (unsigned i = 0; i < root->kids.length (); i++)
3819 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3820 expr *e = static_cast<expr *>(dop->op);
3821 if (e->ops.length () != n
3822 /* Builtin simplifications are somewhat premature on
3823 GENERIC. The following drops patterns with outermost
3824 calls. It's easy to emit overloads for function code
3825 though if necessary. */
3826 || (!gimple
3827 && e->operation->kind != id_base::CODE))
3828 continue;
3830 if (*e->operation == CONVERT_EXPR
3831 || *e->operation == NOP_EXPR)
3832 fprintf (f, " CASE_CONVERT:\n");
3833 else
3834 fprintf (f, " case %s%s:\n",
3835 is_a <fn_id *> (e->operation) ? "-" : "",
3836 e->operation->id);
3837 if (gimple)
3838 fprintf (f, " return gimple_simplify_%s (res_op, "
3839 "seq, valueize, code, type", e->operation->id);
3840 else
3841 fprintf (f, " return generic_simplify_%s (loc, code, type",
3842 e->operation->id);
3843 for (unsigned i = 0; i < n; ++i)
3844 fprintf (f, ", op%d", i);
3845 fprintf (f, ");\n");
3847 fprintf (f, " default:;\n"
3848 " }\n");
3850 if (gimple)
3851 fprintf (f, " return false;\n");
3852 else
3853 fprintf (f, " return NULL_TREE;\n");
3854 fprintf (f, "}\n");
3858 /* Output code to implement the predicate P from the decision tree DT. */
3860 void
3861 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3863 fprintf (f, "\nbool\n"
3864 "%s%s (tree t%s%s)\n"
3865 "{\n", gimple ? "gimple_" : "tree_", p->id,
3866 p->nargs > 0 ? ", tree *res_ops" : "",
3867 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3868 /* Conveniently make 'type' available. */
3869 fprintf_indent (f, 2, "const tree type = TREE_TYPE (t);\n");
3871 if (!gimple)
3872 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3873 dt.root->gen_kids (f, 2, gimple);
3875 fprintf_indent (f, 2, "return false;\n"
3876 "}\n");
3879 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3881 static void
3882 write_header (FILE *f, const char *head)
3884 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3885 fprintf (f, " a IL pattern matching and simplification description. */\n");
3887 /* Include the header instead of writing it awkwardly quoted here. */
3888 fprintf (f, "\n#include \"%s\"\n", head);
3893 /* AST parsing. */
3895 class parser
3897 public:
3898 parser (cpp_reader *);
3900 private:
3901 const cpp_token *next ();
3902 const cpp_token *peek (unsigned = 1);
3903 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3904 const cpp_token *expect (enum cpp_ttype);
3905 const cpp_token *eat_token (enum cpp_ttype);
3906 const char *get_string ();
3907 const char *get_ident ();
3908 const cpp_token *eat_ident (const char *);
3909 const char *get_number ();
3911 unsigned get_internal_capture_id ();
3913 id_base *parse_operation ();
3914 operand *parse_capture (operand *, bool);
3915 operand *parse_expr ();
3916 c_expr *parse_c_expr (cpp_ttype);
3917 operand *parse_op ();
3919 void record_operlist (source_location, user_id *);
3921 void parse_pattern ();
3922 operand *parse_result (operand *, predicate_id *);
3923 void push_simplify (simplify::simplify_kind,
3924 vec<simplify *>&, operand *, operand *);
3925 void parse_simplify (simplify::simplify_kind,
3926 vec<simplify *>&, predicate_id *, operand *);
3927 void parse_for (source_location);
3928 void parse_if (source_location);
3929 void parse_predicates (source_location);
3930 void parse_operator_list (source_location);
3932 void finish_match_operand (operand *);
3934 cpp_reader *r;
3935 vec<c_expr *> active_ifs;
3936 vec<vec<user_id *> > active_fors;
3937 hash_set<user_id *> *oper_lists_set;
3938 vec<user_id *> oper_lists;
3940 cid_map_t *capture_ids;
3941 unsigned last_id;
3943 public:
3944 vec<simplify *> simplifiers;
3945 vec<predicate_id *> user_predicates;
3946 bool parsing_match_operand;
3949 /* Lexing helpers. */
3951 /* Read the next non-whitespace token from R. */
3953 const cpp_token *
3954 parser::next ()
3956 const cpp_token *token;
3959 token = cpp_get_token (r);
3961 while (token->type == CPP_PADDING);
3962 return token;
3965 /* Peek at the next non-whitespace token from R. */
3967 const cpp_token *
3968 parser::peek (unsigned num)
3970 const cpp_token *token;
3971 unsigned i = 0;
3974 token = cpp_peek_token (r, i++);
3976 while (token->type == CPP_PADDING
3977 || (--num > 0));
3978 /* If we peek at EOF this is a fatal error as it leaves the
3979 cpp_reader in unusable state. Assume we really wanted a
3980 token and thus this EOF is unexpected. */
3981 if (token->type == CPP_EOF)
3982 fatal_at (token, "unexpected end of file");
3983 return token;
3986 /* Peek at the next identifier token (or return NULL if the next
3987 token is not an identifier or equal to ID if supplied). */
3989 const cpp_token *
3990 parser::peek_ident (const char *id, unsigned num)
3992 const cpp_token *token = peek (num);
3993 if (token->type != CPP_NAME)
3994 return 0;
3996 if (id == 0)
3997 return token;
3999 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
4000 if (strcmp (id, t) == 0)
4001 return token;
4003 return 0;
4006 /* Read the next token from R and assert it is of type TK. */
4008 const cpp_token *
4009 parser::expect (enum cpp_ttype tk)
4011 const cpp_token *token = next ();
4012 if (token->type != tk)
4013 fatal_at (token, "expected %s, got %s",
4014 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
4016 return token;
4019 /* Consume the next token from R and assert it is of type TK. */
4021 const cpp_token *
4022 parser::eat_token (enum cpp_ttype tk)
4024 return expect (tk);
4027 /* Read the next token from R and assert it is of type CPP_STRING and
4028 return its value. */
4030 const char *
4031 parser::get_string ()
4033 const cpp_token *token = expect (CPP_STRING);
4034 return (const char *)token->val.str.text;
4037 /* Read the next token from R and assert it is of type CPP_NAME and
4038 return its value. */
4040 const char *
4041 parser::get_ident ()
4043 const cpp_token *token = expect (CPP_NAME);
4044 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4047 /* Eat an identifier token with value S from R. */
4049 const cpp_token *
4050 parser::eat_ident (const char *s)
4052 const cpp_token *token = peek ();
4053 const char *t = get_ident ();
4054 if (strcmp (s, t) != 0)
4055 fatal_at (token, "expected '%s' got '%s'\n", s, t);
4056 return token;
4059 /* Read the next token from R and assert it is of type CPP_NUMBER and
4060 return its value. */
4062 const char *
4063 parser::get_number ()
4065 const cpp_token *token = expect (CPP_NUMBER);
4066 return (const char *)token->val.str.text;
4069 /* Return a capture ID that can be used internally. */
4071 unsigned
4072 parser::get_internal_capture_id ()
4074 unsigned newid = capture_ids->elements ();
4075 /* Big enough for a 32-bit UINT_MAX plus prefix. */
4076 char id[13];
4077 bool existed;
4078 sprintf (id, "__%u", newid);
4079 capture_ids->get_or_insert (xstrdup (id), &existed);
4080 if (existed)
4081 fatal ("reserved capture id '%s' already used", id);
4082 return newid;
4085 /* Record an operator-list use for transparent for handling. */
4087 void
4088 parser::record_operlist (source_location loc, user_id *p)
4090 if (!oper_lists_set->add (p))
4092 if (!oper_lists.is_empty ()
4093 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
4094 fatal_at (loc, "User-defined operator list does not have the "
4095 "same number of entries as others used in the pattern");
4096 oper_lists.safe_push (p);
4100 /* Parse the operator ID, special-casing convert?, convert1? and
4101 convert2? */
4103 id_base *
4104 parser::parse_operation ()
4106 const cpp_token *id_tok = peek ();
4107 const char *id = get_ident ();
4108 const cpp_token *token = peek ();
4109 if (strcmp (id, "convert0") == 0)
4110 fatal_at (id_tok, "use 'convert?' here");
4111 else if (strcmp (id, "view_convert0") == 0)
4112 fatal_at (id_tok, "use 'view_convert?' here");
4113 if (token->type == CPP_QUERY
4114 && !(token->flags & PREV_WHITE))
4116 if (strcmp (id, "convert") == 0)
4117 id = "convert0";
4118 else if (strcmp (id, "convert1") == 0)
4120 else if (strcmp (id, "convert2") == 0)
4122 else if (strcmp (id, "view_convert") == 0)
4123 id = "view_convert0";
4124 else if (strcmp (id, "view_convert1") == 0)
4126 else if (strcmp (id, "view_convert2") == 0)
4128 else
4129 fatal_at (id_tok, "non-convert operator conditionalized");
4131 if (!parsing_match_operand)
4132 fatal_at (id_tok, "conditional convert can only be used in "
4133 "match expression");
4134 eat_token (CPP_QUERY);
4136 else if (strcmp (id, "convert1") == 0
4137 || strcmp (id, "convert2") == 0
4138 || strcmp (id, "view_convert1") == 0
4139 || strcmp (id, "view_convert2") == 0)
4140 fatal_at (id_tok, "expected '?' after conditional operator");
4141 id_base *op = get_operator (id);
4142 if (!op)
4143 fatal_at (id_tok, "unknown operator %s", id);
4145 user_id *p = dyn_cast<user_id *> (op);
4146 if (p && p->is_oper_list)
4148 if (active_fors.length() == 0)
4149 record_operlist (id_tok->src_loc, p);
4150 else
4151 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
4153 return op;
4156 /* Parse a capture.
4157 capture = '@'<number> */
4159 struct operand *
4160 parser::parse_capture (operand *op, bool require_existing)
4162 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
4163 const cpp_token *token = peek ();
4164 const char *id = NULL;
4165 bool value_match = false;
4166 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4167 if (token->type == CPP_ATSIGN
4168 && ! (token->flags & PREV_WHITE)
4169 && parsing_match_operand)
4171 eat_token (CPP_ATSIGN);
4172 token = peek ();
4173 value_match = true;
4175 if (token->type == CPP_NUMBER)
4176 id = get_number ();
4177 else if (token->type == CPP_NAME)
4178 id = get_ident ();
4179 else
4180 fatal_at (token, "expected number or identifier");
4181 unsigned next_id = capture_ids->elements ();
4182 bool existed;
4183 unsigned &num = capture_ids->get_or_insert (id, &existed);
4184 if (!existed)
4186 if (require_existing)
4187 fatal_at (src_loc, "unknown capture id");
4188 num = next_id;
4190 return new capture (src_loc, num, op, value_match);
4193 /* Parse an expression
4194 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4196 struct operand *
4197 parser::parse_expr ()
4199 const cpp_token *token = peek ();
4200 expr *e = new expr (parse_operation (), token->src_loc);
4201 token = peek ();
4202 operand *op;
4203 bool is_commutative = false;
4204 bool force_capture = false;
4205 const char *expr_type = NULL;
4207 if (token->type == CPP_COLON
4208 && !(token->flags & PREV_WHITE))
4210 eat_token (CPP_COLON);
4211 token = peek ();
4212 if (token->type == CPP_NAME
4213 && !(token->flags & PREV_WHITE))
4215 const char *s = get_ident ();
4216 if (!parsing_match_operand)
4217 expr_type = s;
4218 else
4220 const char *sp = s;
4221 while (*sp)
4223 if (*sp == 'c')
4225 if (operator_id *p
4226 = dyn_cast<operator_id *> (e->operation))
4228 if (!commutative_tree_code (p->code)
4229 && !comparison_code_p (p->code))
4230 fatal_at (token, "operation is not commutative");
4232 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4233 for (unsigned i = 0;
4234 i < p->substitutes.length (); ++i)
4236 if (operator_id *q
4237 = dyn_cast<operator_id *> (p->substitutes[i]))
4239 if (!commutative_tree_code (q->code)
4240 && !comparison_code_p (q->code))
4241 fatal_at (token, "operation %s is not "
4242 "commutative", q->id);
4245 is_commutative = true;
4247 else if (*sp == 'C')
4248 is_commutative = true;
4249 else if (*sp == 's')
4251 e->force_single_use = true;
4252 force_capture = true;
4254 else
4255 fatal_at (token, "flag %c not recognized", *sp);
4256 sp++;
4259 token = peek ();
4261 else
4262 fatal_at (token, "expected flag or type specifying identifier");
4265 if (token->type == CPP_ATSIGN
4266 && !(token->flags & PREV_WHITE))
4267 op = parse_capture (e, false);
4268 else if (force_capture)
4270 unsigned num = get_internal_capture_id ();
4271 op = new capture (token->src_loc, num, e, false);
4273 else
4274 op = e;
4277 const cpp_token *token = peek ();
4278 if (token->type == CPP_CLOSE_PAREN)
4280 if (e->operation->nargs != -1
4281 && e->operation->nargs != (int) e->ops.length ())
4282 fatal_at (token, "'%s' expects %u operands, not %u",
4283 e->operation->id, e->operation->nargs, e->ops.length ());
4284 if (is_commutative)
4286 if (e->ops.length () == 2
4287 || commutative_op (e->operation) >= 0)
4288 e->is_commutative = true;
4289 else
4290 fatal_at (token, "only binary operators or functions with "
4291 "two arguments can be marked commutative, "
4292 "unless the operation is known to be inherently "
4293 "commutative");
4295 e->expr_type = expr_type;
4296 return op;
4298 else if (!(token->flags & PREV_WHITE))
4299 fatal_at (token, "expected expression operand");
4301 e->append_op (parse_op ());
4303 while (1);
4306 /* Lex native C code delimited by START recording the preprocessing tokens
4307 for later processing.
4308 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4310 c_expr *
4311 parser::parse_c_expr (cpp_ttype start)
4313 const cpp_token *token;
4314 cpp_ttype end;
4315 unsigned opencnt;
4316 vec<cpp_token> code = vNULL;
4317 unsigned nr_stmts = 0;
4318 source_location loc = eat_token (start)->src_loc;
4319 if (start == CPP_OPEN_PAREN)
4320 end = CPP_CLOSE_PAREN;
4321 else if (start == CPP_OPEN_BRACE)
4322 end = CPP_CLOSE_BRACE;
4323 else
4324 gcc_unreachable ();
4325 opencnt = 1;
4328 token = next ();
4330 /* Count brace pairs to find the end of the expr to match. */
4331 if (token->type == start)
4332 opencnt++;
4333 else if (token->type == end
4334 && --opencnt == 0)
4335 break;
4336 else if (token->type == CPP_EOF)
4337 fatal_at (token, "unexpected end of file");
4339 /* This is a lame way of counting the number of statements. */
4340 if (token->type == CPP_SEMICOLON)
4341 nr_stmts++;
4343 /* If this is possibly a user-defined identifier mark it used. */
4344 if (token->type == CPP_NAME)
4346 id_base *idb = get_operator ((const char *)CPP_HASHNODE
4347 (token->val.node.node)->ident.str);
4348 user_id *p;
4349 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4350 record_operlist (token->src_loc, p);
4353 /* Record the token. */
4354 code.safe_push (*token);
4356 while (1);
4357 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4360 /* Parse an operand which is either an expression, a predicate or
4361 a standalone capture.
4362 op = predicate | expr | c_expr | capture */
4364 struct operand *
4365 parser::parse_op ()
4367 const cpp_token *token = peek ();
4368 struct operand *op = NULL;
4369 if (token->type == CPP_OPEN_PAREN)
4371 eat_token (CPP_OPEN_PAREN);
4372 op = parse_expr ();
4373 eat_token (CPP_CLOSE_PAREN);
4375 else if (token->type == CPP_OPEN_BRACE)
4377 op = parse_c_expr (CPP_OPEN_BRACE);
4379 else
4381 /* Remaining ops are either empty or predicates */
4382 if (token->type == CPP_NAME)
4384 const char *id = get_ident ();
4385 id_base *opr = get_operator (id);
4386 if (!opr)
4387 fatal_at (token, "expected predicate name");
4388 if (operator_id *code = dyn_cast <operator_id *> (opr))
4390 if (code->nargs != 0)
4391 fatal_at (token, "using an operator with operands as predicate");
4392 /* Parse the zero-operand operator "predicates" as
4393 expression. */
4394 op = new expr (opr, token->src_loc);
4396 else if (user_id *code = dyn_cast <user_id *> (opr))
4398 if (code->nargs != 0)
4399 fatal_at (token, "using an operator with operands as predicate");
4400 /* Parse the zero-operand operator "predicates" as
4401 expression. */
4402 op = new expr (opr, token->src_loc);
4404 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4405 op = new predicate (p, token->src_loc);
4406 else
4407 fatal_at (token, "using an unsupported operator as predicate");
4408 if (!parsing_match_operand)
4409 fatal_at (token, "predicates are only allowed in match expression");
4410 token = peek ();
4411 if (token->flags & PREV_WHITE)
4412 return op;
4414 else if (token->type != CPP_COLON
4415 && token->type != CPP_ATSIGN)
4416 fatal_at (token, "expected expression or predicate");
4417 /* optionally followed by a capture and a predicate. */
4418 if (token->type == CPP_COLON)
4419 fatal_at (token, "not implemented: predicate on leaf operand");
4420 if (token->type == CPP_ATSIGN)
4421 op = parse_capture (op, !parsing_match_operand);
4424 return op;
4427 /* Create a new simplify from the current parsing state and MATCH,
4428 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4430 void
4431 parser::push_simplify (simplify::simplify_kind kind,
4432 vec<simplify *>& simplifiers,
4433 operand *match, operand *result)
4435 /* Build and push a temporary for operator list uses in expressions. */
4436 if (!oper_lists.is_empty ())
4437 active_fors.safe_push (oper_lists);
4439 simplifiers.safe_push
4440 (new simplify (kind, last_id++, match, result,
4441 active_fors.copy (), capture_ids));
4443 if (!oper_lists.is_empty ())
4444 active_fors.pop ();
4447 /* Parse
4448 <result-op> = <op> | <if> | <with>
4449 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4450 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4451 and return it. */
4453 operand *
4454 parser::parse_result (operand *result, predicate_id *matcher)
4456 const cpp_token *token = peek ();
4457 if (token->type != CPP_OPEN_PAREN)
4458 return parse_op ();
4460 eat_token (CPP_OPEN_PAREN);
4461 if (peek_ident ("if"))
4463 eat_ident ("if");
4464 if_expr *ife = new if_expr (token->src_loc);
4465 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4466 if (peek ()->type == CPP_OPEN_PAREN)
4468 ife->trueexpr = parse_result (result, matcher);
4469 if (peek ()->type == CPP_OPEN_PAREN)
4470 ife->falseexpr = parse_result (result, matcher);
4471 else if (peek ()->type != CPP_CLOSE_PAREN)
4472 ife->falseexpr = parse_op ();
4474 else if (peek ()->type != CPP_CLOSE_PAREN)
4476 ife->trueexpr = parse_op ();
4477 if (peek ()->type == CPP_OPEN_PAREN)
4478 ife->falseexpr = parse_result (result, matcher);
4479 else if (peek ()->type != CPP_CLOSE_PAREN)
4480 ife->falseexpr = parse_op ();
4482 /* If this if is immediately closed then it contains a
4483 manual matcher or is part of a predicate definition. */
4484 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4486 if (!matcher)
4487 fatal_at (peek (), "manual transform not implemented");
4488 ife->trueexpr = result;
4490 eat_token (CPP_CLOSE_PAREN);
4491 return ife;
4493 else if (peek_ident ("with"))
4495 eat_ident ("with");
4496 with_expr *withe = new with_expr (token->src_loc);
4497 /* Parse (with c-expr expr) as (if-with (true) expr). */
4498 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4499 withe->with->nr_stmts = 0;
4500 withe->subexpr = parse_result (result, matcher);
4501 eat_token (CPP_CLOSE_PAREN);
4502 return withe;
4504 else if (peek_ident ("switch"))
4506 token = eat_ident ("switch");
4507 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4508 eat_ident ("if");
4509 if_expr *ife = new if_expr (ifloc);
4510 operand *res = ife;
4511 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4512 if (peek ()->type == CPP_OPEN_PAREN)
4513 ife->trueexpr = parse_result (result, matcher);
4514 else
4515 ife->trueexpr = parse_op ();
4516 eat_token (CPP_CLOSE_PAREN);
4517 if (peek ()->type != CPP_OPEN_PAREN
4518 || !peek_ident ("if", 2))
4519 fatal_at (token, "switch can be implemented with a single if");
4520 while (peek ()->type != CPP_CLOSE_PAREN)
4522 if (peek ()->type == CPP_OPEN_PAREN)
4524 if (peek_ident ("if", 2))
4526 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4527 eat_ident ("if");
4528 ife->falseexpr = new if_expr (ifloc);
4529 ife = as_a <if_expr *> (ife->falseexpr);
4530 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4531 if (peek ()->type == CPP_OPEN_PAREN)
4532 ife->trueexpr = parse_result (result, matcher);
4533 else
4534 ife->trueexpr = parse_op ();
4535 eat_token (CPP_CLOSE_PAREN);
4537 else
4539 /* switch default clause */
4540 ife->falseexpr = parse_result (result, matcher);
4541 eat_token (CPP_CLOSE_PAREN);
4542 return res;
4545 else
4547 /* switch default clause */
4548 ife->falseexpr = parse_op ();
4549 eat_token (CPP_CLOSE_PAREN);
4550 return res;
4553 eat_token (CPP_CLOSE_PAREN);
4554 return res;
4556 else
4558 operand *op = result;
4559 if (!matcher)
4560 op = parse_expr ();
4561 eat_token (CPP_CLOSE_PAREN);
4562 return op;
4566 /* Parse
4567 simplify = 'simplify' <expr> <result-op>
4569 match = 'match' <ident> <expr> [<result-op>]
4570 and fill SIMPLIFIERS with the results. */
4572 void
4573 parser::parse_simplify (simplify::simplify_kind kind,
4574 vec<simplify *>& simplifiers, predicate_id *matcher,
4575 operand *result)
4577 /* Reset the capture map. */
4578 if (!capture_ids)
4579 capture_ids = new cid_map_t;
4580 /* Reset oper_lists and set. */
4581 hash_set <user_id *> olist;
4582 oper_lists_set = &olist;
4583 oper_lists = vNULL;
4585 const cpp_token *loc = peek ();
4586 parsing_match_operand = true;
4587 struct operand *match = parse_op ();
4588 finish_match_operand (match);
4589 parsing_match_operand = false;
4590 if (match->type == operand::OP_CAPTURE && !matcher)
4591 fatal_at (loc, "outermost expression cannot be captured");
4592 if (match->type == operand::OP_EXPR
4593 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4594 fatal_at (loc, "outermost expression cannot be a predicate");
4596 /* Splice active_ifs onto result and continue parsing the
4597 "then" expr. */
4598 if_expr *active_if = NULL;
4599 for (int i = active_ifs.length (); i > 0; --i)
4601 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4602 ifc->cond = active_ifs[i-1];
4603 ifc->trueexpr = active_if;
4604 active_if = ifc;
4606 if_expr *outermost_if = active_if;
4607 while (active_if && active_if->trueexpr)
4608 active_if = as_a <if_expr *> (active_if->trueexpr);
4610 const cpp_token *token = peek ();
4612 /* If this if is immediately closed then it is part of a predicate
4613 definition. Push it. */
4614 if (token->type == CPP_CLOSE_PAREN)
4616 if (!matcher)
4617 fatal_at (token, "expected transform expression");
4618 if (active_if)
4620 active_if->trueexpr = result;
4621 result = outermost_if;
4623 push_simplify (kind, simplifiers, match, result);
4624 return;
4627 operand *tem = parse_result (result, matcher);
4628 if (active_if)
4630 active_if->trueexpr = tem;
4631 result = outermost_if;
4633 else
4634 result = tem;
4636 push_simplify (kind, simplifiers, match, result);
4639 /* Parsing of the outer control structures. */
4641 /* Parse a for expression
4642 for = '(' 'for' <subst>... <pattern> ')'
4643 subst = <ident> '(' <ident>... ')' */
4645 void
4646 parser::parse_for (source_location)
4648 auto_vec<const cpp_token *> user_id_tokens;
4649 vec<user_id *> user_ids = vNULL;
4650 const cpp_token *token;
4651 unsigned min_n_opers = 0, max_n_opers = 0;
4653 while (1)
4655 token = peek ();
4656 if (token->type != CPP_NAME)
4657 break;
4659 /* Insert the user defined operators into the operator hash. */
4660 const char *id = get_ident ();
4661 if (get_operator (id, true) != NULL)
4662 fatal_at (token, "operator already defined");
4663 user_id *op = new user_id (id);
4664 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4665 *slot = op;
4666 user_ids.safe_push (op);
4667 user_id_tokens.safe_push (token);
4669 eat_token (CPP_OPEN_PAREN);
4671 int arity = -1;
4672 while ((token = peek_ident ()) != 0)
4674 const char *oper = get_ident ();
4675 id_base *idb = get_operator (oper, true);
4676 if (idb == NULL)
4677 fatal_at (token, "no such operator '%s'", oper);
4678 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4679 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4680 || *idb == VIEW_CONVERT2)
4681 fatal_at (token, "conditional operators cannot be used inside for");
4683 if (arity == -1)
4684 arity = idb->nargs;
4685 else if (idb->nargs == -1)
4687 else if (idb->nargs != arity)
4688 fatal_at (token, "operator '%s' with arity %d does not match "
4689 "others with arity %d", oper, idb->nargs, arity);
4691 user_id *p = dyn_cast<user_id *> (idb);
4692 if (p)
4694 if (p->is_oper_list)
4695 op->substitutes.safe_splice (p->substitutes);
4696 else
4697 fatal_at (token, "iterator cannot be used as operator-list");
4699 else
4700 op->substitutes.safe_push (idb);
4702 op->nargs = arity;
4703 token = expect (CPP_CLOSE_PAREN);
4705 unsigned nsubstitutes = op->substitutes.length ();
4706 if (nsubstitutes == 0)
4707 fatal_at (token, "A user-defined operator must have at least "
4708 "one substitution");
4709 if (max_n_opers == 0)
4711 min_n_opers = nsubstitutes;
4712 max_n_opers = nsubstitutes;
4714 else
4716 if (nsubstitutes % min_n_opers != 0
4717 && min_n_opers % nsubstitutes != 0)
4718 fatal_at (token, "All user-defined identifiers must have a "
4719 "multiple number of operator substitutions of the "
4720 "smallest number of substitutions");
4721 if (nsubstitutes < min_n_opers)
4722 min_n_opers = nsubstitutes;
4723 else if (nsubstitutes > max_n_opers)
4724 max_n_opers = nsubstitutes;
4728 unsigned n_ids = user_ids.length ();
4729 if (n_ids == 0)
4730 fatal_at (token, "for requires at least one user-defined identifier");
4732 token = peek ();
4733 if (token->type == CPP_CLOSE_PAREN)
4734 fatal_at (token, "no pattern defined in for");
4736 active_fors.safe_push (user_ids);
4737 while (1)
4739 token = peek ();
4740 if (token->type == CPP_CLOSE_PAREN)
4741 break;
4742 parse_pattern ();
4744 active_fors.pop ();
4746 /* Remove user-defined operators from the hash again. */
4747 for (unsigned i = 0; i < user_ids.length (); ++i)
4749 if (!user_ids[i]->used)
4750 warning_at (user_id_tokens[i],
4751 "operator %s defined but not used", user_ids[i]->id);
4752 operators->remove_elt (user_ids[i]);
4756 /* Parse an identifier associated with a list of operators.
4757 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4759 void
4760 parser::parse_operator_list (source_location)
4762 const cpp_token *token = peek ();
4763 const char *id = get_ident ();
4765 if (get_operator (id, true) != 0)
4766 fatal_at (token, "operator %s already defined", id);
4768 user_id *op = new user_id (id, true);
4769 int arity = -1;
4771 while ((token = peek_ident ()) != 0)
4773 token = peek ();
4774 const char *oper = get_ident ();
4775 id_base *idb = get_operator (oper, true);
4777 if (idb == 0)
4778 fatal_at (token, "no such operator '%s'", oper);
4780 if (arity == -1)
4781 arity = idb->nargs;
4782 else if (idb->nargs == -1)
4784 else if (arity != idb->nargs)
4785 fatal_at (token, "operator '%s' with arity %d does not match "
4786 "others with arity %d", oper, idb->nargs, arity);
4788 /* We allow composition of multiple operator lists. */
4789 if (user_id *p = dyn_cast<user_id *> (idb))
4790 op->substitutes.safe_splice (p->substitutes);
4791 else
4792 op->substitutes.safe_push (idb);
4795 // Check that there is no junk after id-list
4796 token = peek();
4797 if (token->type != CPP_CLOSE_PAREN)
4798 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4800 if (op->substitutes.length () == 0)
4801 fatal_at (token, "operator-list cannot be empty");
4803 op->nargs = arity;
4804 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4805 *slot = op;
4808 /* Parse an outer if expression.
4809 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4811 void
4812 parser::parse_if (source_location)
4814 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4816 const cpp_token *token = peek ();
4817 if (token->type == CPP_CLOSE_PAREN)
4818 fatal_at (token, "no pattern defined in if");
4820 active_ifs.safe_push (ifexpr);
4821 while (1)
4823 const cpp_token *token = peek ();
4824 if (token->type == CPP_CLOSE_PAREN)
4825 break;
4827 parse_pattern ();
4829 active_ifs.pop ();
4832 /* Parse a list of predefined predicate identifiers.
4833 preds = '(' 'define_predicates' <ident>... ')' */
4835 void
4836 parser::parse_predicates (source_location)
4840 const cpp_token *token = peek ();
4841 if (token->type != CPP_NAME)
4842 break;
4844 add_predicate (get_ident ());
4846 while (1);
4849 /* Parse outer control structures.
4850 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4852 void
4853 parser::parse_pattern ()
4855 /* All clauses start with '('. */
4856 eat_token (CPP_OPEN_PAREN);
4857 const cpp_token *token = peek ();
4858 const char *id = get_ident ();
4859 if (strcmp (id, "simplify") == 0)
4861 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4862 capture_ids = NULL;
4864 else if (strcmp (id, "match") == 0)
4866 bool with_args = false;
4867 source_location e_loc = peek ()->src_loc;
4868 if (peek ()->type == CPP_OPEN_PAREN)
4870 eat_token (CPP_OPEN_PAREN);
4871 with_args = true;
4873 const char *name = get_ident ();
4874 id_base *id = get_operator (name);
4875 predicate_id *p;
4876 if (!id)
4878 p = add_predicate (name);
4879 user_predicates.safe_push (p);
4881 else if ((p = dyn_cast <predicate_id *> (id)))
4883 else
4884 fatal_at (token, "cannot add a match to a non-predicate ID");
4885 /* Parse (match <id> <arg>... (match-expr)) here. */
4886 expr *e = NULL;
4887 if (with_args)
4889 capture_ids = new cid_map_t;
4890 e = new expr (p, e_loc);
4891 while (peek ()->type == CPP_ATSIGN)
4892 e->append_op (parse_capture (NULL, false));
4893 eat_token (CPP_CLOSE_PAREN);
4895 if (p->nargs != -1
4896 && ((e && e->ops.length () != (unsigned)p->nargs)
4897 || (!e && p->nargs != 0)))
4898 fatal_at (token, "non-matching number of match operands");
4899 p->nargs = e ? e->ops.length () : 0;
4900 parse_simplify (simplify::MATCH, p->matchers, p, e);
4901 capture_ids = NULL;
4903 else if (strcmp (id, "for") == 0)
4904 parse_for (token->src_loc);
4905 else if (strcmp (id, "if") == 0)
4906 parse_if (token->src_loc);
4907 else if (strcmp (id, "define_predicates") == 0)
4909 if (active_ifs.length () > 0
4910 || active_fors.length () > 0)
4911 fatal_at (token, "define_predicates inside if or for is not supported");
4912 parse_predicates (token->src_loc);
4914 else if (strcmp (id, "define_operator_list") == 0)
4916 if (active_ifs.length () > 0
4917 || active_fors.length () > 0)
4918 fatal_at (token, "operator-list inside if or for is not supported");
4919 parse_operator_list (token->src_loc);
4921 else
4922 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4923 active_ifs.length () == 0 && active_fors.length () == 0
4924 ? "'define_predicates', " : "");
4926 eat_token (CPP_CLOSE_PAREN);
4929 /* Helper for finish_match_operand, collecting captures of OP in CPTS
4930 recursively. */
4932 static void
4933 walk_captures (operand *op, vec<vec<capture *> > cpts)
4935 if (! op)
4936 return;
4938 if (capture *c = dyn_cast <capture *> (op))
4940 cpts[c->where].safe_push (c);
4941 walk_captures (c->what, cpts);
4943 else if (expr *e = dyn_cast <expr *> (op))
4944 for (unsigned i = 0; i < e->ops.length (); ++i)
4945 walk_captures (e->ops[i], cpts);
4948 /* Finish up OP which is a match operand. */
4950 void
4951 parser::finish_match_operand (operand *op)
4953 /* Look for matching captures, diagnose mis-uses of @@ and apply
4954 early lowering and distribution of value_match. */
4955 auto_vec<vec<capture *> > cpts;
4956 cpts.safe_grow_cleared (capture_ids->elements ());
4957 walk_captures (op, cpts);
4958 for (unsigned i = 0; i < cpts.length (); ++i)
4960 capture *value_match = NULL;
4961 for (unsigned j = 0; j < cpts[i].length (); ++j)
4963 if (cpts[i][j]->value_match)
4965 if (value_match)
4966 fatal_at (cpts[i][j]->location, "duplicate @@");
4967 value_match = cpts[i][j];
4970 if (cpts[i].length () == 1 && value_match)
4971 fatal_at (value_match->location, "@@ without a matching capture");
4972 if (value_match)
4974 /* Duplicate prevailing capture with the existing ID, create
4975 a fake ID and rewrite all captures to use it. This turns
4976 @@1 into @__<newid>@1 and @1 into @__<newid>. */
4977 value_match->what = new capture (value_match->location,
4978 value_match->where,
4979 value_match->what, false);
4980 /* Create a fake ID and rewrite all captures to use it. */
4981 unsigned newid = get_internal_capture_id ();
4982 for (unsigned j = 0; j < cpts[i].length (); ++j)
4984 cpts[i][j]->where = newid;
4985 cpts[i][j]->value_match = true;
4988 cpts[i].release ();
4992 /* Main entry of the parser. Repeatedly parse outer control structures. */
4994 parser::parser (cpp_reader *r_)
4996 r = r_;
4997 active_ifs = vNULL;
4998 active_fors = vNULL;
4999 simplifiers = vNULL;
5000 oper_lists_set = NULL;
5001 oper_lists = vNULL;
5002 capture_ids = NULL;
5003 user_predicates = vNULL;
5004 parsing_match_operand = false;
5005 last_id = 0;
5007 const cpp_token *token = next ();
5008 while (token->type != CPP_EOF)
5010 _cpp_backup_tokens (r, 1);
5011 parse_pattern ();
5012 token = next ();
5017 /* Helper for the linemap code. */
5019 static size_t
5020 round_alloc_size (size_t s)
5022 return s;
5026 /* The genmatch generator progam. It reads from a pattern description
5027 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
5030 main (int argc, char **argv)
5032 cpp_reader *r;
5034 progname = "genmatch";
5036 if (argc < 2)
5037 return 1;
5039 bool gimple = true;
5040 char *input = argv[argc-1];
5041 for (int i = 1; i < argc - 1; ++i)
5043 if (strcmp (argv[i], "--gimple") == 0)
5044 gimple = true;
5045 else if (strcmp (argv[i], "--generic") == 0)
5046 gimple = false;
5047 else if (strcmp (argv[i], "-v") == 0)
5048 verbose = 1;
5049 else if (strcmp (argv[i], "-vv") == 0)
5050 verbose = 2;
5051 else
5053 fprintf (stderr, "Usage: genmatch "
5054 "[--gimple] [--generic] [-v[v]] input\n");
5055 return 1;
5059 line_table = XCNEW (struct line_maps);
5060 linemap_init (line_table, 0);
5061 line_table->reallocator = xrealloc;
5062 line_table->round_alloc_size = round_alloc_size;
5064 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
5065 cpp_callbacks *cb = cpp_get_callbacks (r);
5066 cb->error = error_cb;
5068 /* Add the build directory to the #include "" search path. */
5069 cpp_dir *dir = XCNEW (cpp_dir);
5070 dir->name = getpwd ();
5071 if (!dir->name)
5072 dir->name = ASTRDUP (".");
5073 cpp_set_include_chains (r, dir, NULL, false);
5075 if (!cpp_read_main_file (r, input))
5076 return 1;
5077 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
5078 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
5080 null_id = new id_base (id_base::NULL_ID, "null");
5082 /* Pre-seed operators. */
5083 operators = new hash_table<id_base> (1024);
5084 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
5085 add_operator (SYM, # SYM, # TYPE, NARGS);
5086 #define END_OF_BASE_TREE_CODES
5087 #include "tree.def"
5088 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
5089 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
5090 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
5091 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
5092 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
5093 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
5094 #undef END_OF_BASE_TREE_CODES
5095 #undef DEFTREECODE
5097 /* Pre-seed builtin functions.
5098 ??? Cannot use N (name) as that is targetm.emultls.get_address
5099 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
5100 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
5101 add_function (ENUM, "CFN_" # ENUM);
5102 #include "builtins.def"
5104 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
5105 add_function (IFN_##CODE, "CFN_" #CODE);
5106 #include "internal-fn.def"
5108 /* Parse ahead! */
5109 parser p (r);
5111 if (gimple)
5112 write_header (stdout, "gimple-match-head.c");
5113 else
5114 write_header (stdout, "generic-match-head.c");
5116 /* Go over all predicates defined with patterns and perform
5117 lowering and code generation. */
5118 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
5120 predicate_id *pred = p.user_predicates[i];
5121 lower (pred->matchers, gimple);
5123 if (verbose == 2)
5124 for (unsigned i = 0; i < pred->matchers.length (); ++i)
5125 print_matches (pred->matchers[i]);
5127 decision_tree dt;
5128 for (unsigned i = 0; i < pred->matchers.length (); ++i)
5129 dt.insert (pred->matchers[i], i);
5131 if (verbose == 2)
5132 dt.print (stderr);
5134 write_predicate (stdout, pred, dt, gimple);
5137 /* Lower the main simplifiers and generate code for them. */
5138 lower (p.simplifiers, gimple);
5140 if (verbose == 2)
5141 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5142 print_matches (p.simplifiers[i]);
5144 decision_tree dt;
5145 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5146 dt.insert (p.simplifiers[i], i);
5148 if (verbose == 2)
5149 dt.print (stderr);
5151 dt.gen (stdout, gimple);
5153 /* Finalize. */
5154 cpp_finish (r, NULL);
5155 cpp_destroy (r);
5157 delete operators;
5159 return 0;