[ARM] Fix assembly comment syntax in -mprint-tune-info
[official-gcc.git] / gcc / genmatch.c
blobc163ded68764a4a0e6623774c0a22f2523673683
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
4 Copyright (C) 2014-2017 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)
66 const struct line_map_ordinary *map;
67 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
68 return linemap_expand_location (line_table, map, loc);
71 static bool
72 #if GCC_VERSION >= 4001
73 __attribute__((format (printf, 5, 0)))
74 #endif
75 error_cb (cpp_reader *, int errtype, int, rich_location *richloc,
76 const char *msg, va_list *ap)
78 const line_map_ordinary *map;
79 source_location location = richloc->get_loc ();
80 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
81 expanded_location loc = linemap_expand_location (line_table, map, location);
82 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
83 (errtype == CPP_DL_WARNING) ? "warning" : "error");
84 vfprintf (stderr, msg, *ap);
85 fprintf (stderr, "\n");
86 FILE *f = fopen (loc.file, "r");
87 if (f)
89 char buf[128];
90 while (loc.line > 0)
92 if (!fgets (buf, 128, f))
93 goto notfound;
94 if (buf[strlen (buf) - 1] != '\n')
96 if (loc.line > 1)
97 loc.line++;
99 loc.line--;
101 fprintf (stderr, "%s", buf);
102 for (int i = 0; i < loc.column - 1; ++i)
103 fputc (' ', stderr);
104 fputc ('^', stderr);
105 fputc ('\n', stderr);
106 notfound:
107 fclose (f);
110 if (errtype == CPP_DL_FATAL)
111 exit (1);
112 return false;
115 static void
116 #if GCC_VERSION >= 4001
117 __attribute__((format (printf, 2, 3)))
118 #endif
119 fatal_at (const cpp_token *tk, const char *msg, ...)
121 rich_location richloc (line_table, tk->src_loc);
122 va_list ap;
123 va_start (ap, msg);
124 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
125 va_end (ap);
128 static void
129 #if GCC_VERSION >= 4001
130 __attribute__((format (printf, 2, 3)))
131 #endif
132 fatal_at (source_location loc, const char *msg, ...)
134 rich_location richloc (line_table, loc);
135 va_list ap;
136 va_start (ap, msg);
137 error_cb (NULL, CPP_DL_FATAL, 0, &richloc, msg, &ap);
138 va_end (ap);
141 static void
142 #if GCC_VERSION >= 4001
143 __attribute__((format (printf, 2, 3)))
144 #endif
145 warning_at (const cpp_token *tk, const char *msg, ...)
147 rich_location richloc (line_table, tk->src_loc);
148 va_list ap;
149 va_start (ap, msg);
150 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
151 va_end (ap);
154 static void
155 #if GCC_VERSION >= 4001
156 __attribute__((format (printf, 2, 3)))
157 #endif
158 warning_at (source_location loc, const char *msg, ...)
160 rich_location richloc (line_table, loc);
161 va_list ap;
162 va_start (ap, msg);
163 error_cb (NULL, CPP_DL_WARNING, 0, &richloc, msg, &ap);
164 va_end (ap);
167 /* Like fprintf, but print INDENT spaces at the beginning. */
169 static void
170 #if GCC_VERSION >= 4001
171 __attribute__((format (printf, 3, 4)))
172 #endif
173 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
175 va_list ap;
176 for (; indent >= 8; indent -= 8)
177 fputc ('\t', f);
178 fprintf (f, "%*s", indent, "");
179 va_start (ap, format);
180 vfprintf (f, format, ap);
181 va_end (ap);
184 static void
185 output_line_directive (FILE *f, source_location location,
186 bool dumpfile = false)
188 const line_map_ordinary *map;
189 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
190 expanded_location loc = linemap_expand_location (line_table, map, location);
191 if (dumpfile)
193 /* When writing to a dumpfile only dump the filename. */
194 const char *file = strrchr (loc.file, DIR_SEPARATOR);
195 if (!file)
196 file = loc.file;
197 else
198 ++file;
199 fprintf (f, "%s:%d", file, loc.line);
201 else
202 /* Other gen programs really output line directives here, at least for
203 development it's right now more convenient to have line information
204 from the generated file. Still keep the directives as comment for now
205 to easily back-point to the meta-description. */
206 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
210 /* Pull in tree codes and builtin function codes from their
211 definition files. */
213 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
214 enum tree_code {
215 #include "tree.def"
216 CONVERT0,
217 CONVERT1,
218 CONVERT2,
219 VIEW_CONVERT0,
220 VIEW_CONVERT1,
221 VIEW_CONVERT2,
222 MAX_TREE_CODES
224 #undef DEFTREECODE
226 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
227 enum built_in_function {
228 #include "builtins.def"
229 END_BUILTINS
232 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
233 enum internal_fn {
234 #include "internal-fn.def"
235 IFN_LAST
238 /* Return true if CODE represents a commutative tree code. Otherwise
239 return false. */
240 bool
241 commutative_tree_code (enum tree_code code)
243 switch (code)
245 case PLUS_EXPR:
246 case MULT_EXPR:
247 case MULT_HIGHPART_EXPR:
248 case MIN_EXPR:
249 case MAX_EXPR:
250 case BIT_IOR_EXPR:
251 case BIT_XOR_EXPR:
252 case BIT_AND_EXPR:
253 case NE_EXPR:
254 case EQ_EXPR:
255 case UNORDERED_EXPR:
256 case ORDERED_EXPR:
257 case UNEQ_EXPR:
258 case LTGT_EXPR:
259 case TRUTH_AND_EXPR:
260 case TRUTH_XOR_EXPR:
261 case TRUTH_OR_EXPR:
262 case WIDEN_MULT_EXPR:
263 case VEC_WIDEN_MULT_HI_EXPR:
264 case VEC_WIDEN_MULT_LO_EXPR:
265 case VEC_WIDEN_MULT_EVEN_EXPR:
266 case VEC_WIDEN_MULT_ODD_EXPR:
267 return true;
269 default:
270 break;
272 return false;
275 /* Return true if CODE represents a ternary tree code for which the
276 first two operands are commutative. Otherwise return false. */
277 bool
278 commutative_ternary_tree_code (enum tree_code code)
280 switch (code)
282 case WIDEN_MULT_PLUS_EXPR:
283 case WIDEN_MULT_MINUS_EXPR:
284 case DOT_PROD_EXPR:
285 case FMA_EXPR:
286 return true;
288 default:
289 break;
291 return false;
294 /* Return true if CODE is a comparison. */
296 bool
297 comparison_code_p (enum tree_code code)
299 switch (code)
301 case EQ_EXPR:
302 case NE_EXPR:
303 case ORDERED_EXPR:
304 case UNORDERED_EXPR:
305 case LTGT_EXPR:
306 case UNEQ_EXPR:
307 case GT_EXPR:
308 case GE_EXPR:
309 case LT_EXPR:
310 case LE_EXPR:
311 case UNGT_EXPR:
312 case UNGE_EXPR:
313 case UNLT_EXPR:
314 case UNLE_EXPR:
315 return true;
317 default:
318 break;
320 return false;
324 /* Base class for all identifiers the parser knows. */
326 struct id_base : nofree_ptr_hash<id_base>
328 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
330 id_base (id_kind, const char *, int = -1);
332 hashval_t hashval;
333 int nargs;
334 const char *id;
336 /* hash_table support. */
337 static inline hashval_t hash (const id_base *);
338 static inline int equal (const id_base *, const id_base *);
341 inline hashval_t
342 id_base::hash (const id_base *op)
344 return op->hashval;
347 inline int
348 id_base::equal (const id_base *op1,
349 const id_base *op2)
351 return (op1->hashval == op2->hashval
352 && strcmp (op1->id, op2->id) == 0);
355 /* The special id "null", which matches nothing. */
356 static id_base *null_id;
358 /* Hashtable of known pattern operators. This is pre-seeded from
359 all known tree codes and all known builtin function ids. */
360 static hash_table<id_base> *operators;
362 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
364 kind = kind_;
365 id = id_;
366 nargs = nargs_;
367 hashval = htab_hash_string (id);
370 /* Identifier that maps to a tree code. */
372 struct operator_id : public id_base
374 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
375 const char *tcc_)
376 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
377 enum tree_code code;
378 const char *tcc;
381 /* Identifier that maps to a builtin or internal function code. */
383 struct fn_id : public id_base
385 fn_id (enum built_in_function fn_, const char *id_)
386 : id_base (id_base::FN, id_), fn (fn_) {}
387 fn_id (enum internal_fn fn_, const char *id_)
388 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
389 unsigned int fn;
392 struct simplify;
394 /* Identifier that maps to a user-defined predicate. */
396 struct predicate_id : public id_base
398 predicate_id (const char *id_)
399 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
400 vec<simplify *> matchers;
403 /* Identifier that maps to a operator defined by a 'for' directive. */
405 struct user_id : public id_base
407 user_id (const char *id_, bool is_oper_list_ = false)
408 : id_base (id_base::USER, id_), substitutes (vNULL),
409 used (false), is_oper_list (is_oper_list_) {}
410 vec<id_base *> substitutes;
411 bool used;
412 bool is_oper_list;
415 template<>
416 template<>
417 inline bool
418 is_a_helper <fn_id *>::test (id_base *id)
420 return id->kind == id_base::FN;
423 template<>
424 template<>
425 inline bool
426 is_a_helper <operator_id *>::test (id_base *id)
428 return id->kind == id_base::CODE;
431 template<>
432 template<>
433 inline bool
434 is_a_helper <predicate_id *>::test (id_base *id)
436 return id->kind == id_base::PREDICATE;
439 template<>
440 template<>
441 inline bool
442 is_a_helper <user_id *>::test (id_base *id)
444 return id->kind == id_base::USER;
447 /* Add a predicate identifier to the hash. */
449 static predicate_id *
450 add_predicate (const char *id)
452 predicate_id *p = new predicate_id (id);
453 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
454 if (*slot)
455 fatal ("duplicate id definition");
456 *slot = p;
457 return p;
460 /* Add a tree code identifier to the hash. */
462 static void
463 add_operator (enum tree_code code, const char *id,
464 const char *tcc, unsigned nargs)
466 if (strcmp (tcc, "tcc_unary") != 0
467 && strcmp (tcc, "tcc_binary") != 0
468 && strcmp (tcc, "tcc_comparison") != 0
469 && strcmp (tcc, "tcc_expression") != 0
470 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
471 && strcmp (tcc, "tcc_reference") != 0
472 /* To have INTEGER_CST and friends as "predicate operators". */
473 && strcmp (tcc, "tcc_constant") != 0
474 /* And allow CONSTRUCTOR for vector initializers. */
475 && !(code == CONSTRUCTOR)
476 /* Allow SSA_NAME as predicate operator. */
477 && !(code == SSA_NAME))
478 return;
479 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
480 if (code == ADDR_EXPR)
481 nargs = 0;
482 operator_id *op = new operator_id (code, id, nargs, tcc);
483 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
484 if (*slot)
485 fatal ("duplicate id definition");
486 *slot = op;
489 /* Add a built-in or internal function identifier to the hash. ID is
490 the name of its CFN_* enumeration value. */
492 template <typename T>
493 static void
494 add_function (T code, const char *id)
496 fn_id *fn = new fn_id (code, id);
497 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
498 if (*slot)
499 fatal ("duplicate id definition");
500 *slot = fn;
503 /* Helper for easy comparing ID with tree code CODE. */
505 static bool
506 operator==(id_base &id, enum tree_code code)
508 if (operator_id *oid = dyn_cast <operator_id *> (&id))
509 return oid->code == code;
510 return false;
513 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
515 id_base *
516 get_operator (const char *id, bool allow_null = false)
518 if (allow_null && strcmp (id, "null") == 0)
519 return null_id;
521 id_base tem (id_base::CODE, id);
523 id_base *op = operators->find_with_hash (&tem, tem.hashval);
524 if (op)
526 /* If this is a user-defined identifier track whether it was used. */
527 if (user_id *uid = dyn_cast<user_id *> (op))
528 uid->used = true;
529 return op;
532 char *id2;
533 bool all_upper = true;
534 bool all_lower = true;
535 for (unsigned int i = 0; id[i]; ++i)
536 if (ISUPPER (id[i]))
537 all_lower = false;
538 else if (ISLOWER (id[i]))
539 all_upper = false;
540 if (all_lower)
542 /* Try in caps with _EXPR appended. */
543 id2 = ACONCAT ((id, "_EXPR", NULL));
544 for (unsigned int i = 0; id2[i]; ++i)
545 id2[i] = TOUPPER (id2[i]);
547 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
548 /* Try CFN_ instead of IFN_. */
549 id2 = ACONCAT (("CFN_", id + 4, NULL));
550 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
551 /* Try prepending CFN_. */
552 id2 = ACONCAT (("CFN_", id, NULL));
553 else
554 return NULL;
556 new (&tem) id_base (id_base::CODE, id2);
557 return operators->find_with_hash (&tem, tem.hashval);
560 /* Return the comparison operators that results if the operands are
561 swapped. This is safe for floating-point. */
563 id_base *
564 swap_tree_comparison (operator_id *p)
566 switch (p->code)
568 case EQ_EXPR:
569 case NE_EXPR:
570 case ORDERED_EXPR:
571 case UNORDERED_EXPR:
572 case LTGT_EXPR:
573 case UNEQ_EXPR:
574 return p;
575 case GT_EXPR:
576 return get_operator ("LT_EXPR");
577 case GE_EXPR:
578 return get_operator ("LE_EXPR");
579 case LT_EXPR:
580 return get_operator ("GT_EXPR");
581 case LE_EXPR:
582 return get_operator ("GE_EXPR");
583 case UNGT_EXPR:
584 return get_operator ("UNLT_EXPR");
585 case UNGE_EXPR:
586 return get_operator ("UNLE_EXPR");
587 case UNLT_EXPR:
588 return get_operator ("UNGT_EXPR");
589 case UNLE_EXPR:
590 return get_operator ("UNGE_EXPR");
591 default:
592 gcc_unreachable ();
596 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
599 /* The AST produced by parsing of the pattern definitions. */
601 struct dt_operand;
602 struct capture_info;
604 /* The base class for operands. */
606 struct operand {
607 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
608 operand (enum op_type type_, source_location loc_)
609 : type (type_), location (loc_) {}
610 enum op_type type;
611 source_location location;
612 virtual void gen_transform (FILE *, int, const char *, bool, int,
613 const char *, capture_info *,
614 dt_operand ** = 0,
615 int = 0)
616 { gcc_unreachable (); }
619 /* A predicate operand. Predicates are leafs in the AST. */
621 struct predicate : public operand
623 predicate (predicate_id *p_, source_location loc)
624 : operand (OP_PREDICATE, loc), p (p_) {}
625 predicate_id *p;
628 /* An operand that constitutes an expression. Expressions include
629 function calls and user-defined predicate invocations. */
631 struct expr : public operand
633 expr (id_base *operation_, source_location loc, bool is_commutative_ = false)
634 : operand (OP_EXPR, loc), operation (operation_),
635 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
636 is_generic (false), force_single_use (false) {}
637 expr (expr *e)
638 : operand (OP_EXPR, e->location), operation (e->operation),
639 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
640 is_generic (e->is_generic), force_single_use (e->force_single_use) {}
641 void append_op (operand *op) { ops.safe_push (op); }
642 /* The operator and its operands. */
643 id_base *operation;
644 vec<operand *> ops;
645 /* An explicitely specified type - used exclusively for conversions. */
646 const char *expr_type;
647 /* Whether the operation is to be applied commutatively. This is
648 later lowered to two separate patterns. */
649 bool is_commutative;
650 /* Whether the expression is expected to be in GENERIC form. */
651 bool is_generic;
652 /* Whether pushing any stmt to the sequence should be conditional
653 on this expression having a single-use. */
654 bool force_single_use;
655 virtual void gen_transform (FILE *f, int, const char *, bool, int,
656 const char *, capture_info *,
657 dt_operand ** = 0, int = 0);
660 /* An operator that is represented by native C code. This is always
661 a leaf operand in the AST. This class is also used to represent
662 the code to be generated for 'if' and 'with' expressions. */
664 struct c_expr : public operand
666 /* A mapping of an identifier and its replacement. Used to apply
667 'for' lowering. */
668 struct id_tab {
669 const char *id;
670 const char *oper;
671 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
674 c_expr (cpp_reader *r_, source_location loc,
675 vec<cpp_token> code_, unsigned nr_stmts_,
676 vec<id_tab> ids_, cid_map_t *capture_ids_)
677 : operand (OP_C_EXPR, loc), r (r_), code (code_),
678 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
679 /* cpplib tokens and state to transform this back to source. */
680 cpp_reader *r;
681 vec<cpp_token> code;
682 cid_map_t *capture_ids;
683 /* The number of statements parsed (well, the number of ';'s). */
684 unsigned nr_stmts;
685 /* The identifier replacement vector. */
686 vec<id_tab> ids;
687 virtual void gen_transform (FILE *f, int, const char *, bool, int,
688 const char *, capture_info *,
689 dt_operand ** = 0, int = 0);
692 /* A wrapper around another operand that captures its value. */
694 struct capture : public operand
696 capture (source_location loc, unsigned where_, operand *what_, bool value_)
697 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
698 what (what_) {}
699 /* Identifier index for the value. */
700 unsigned where;
701 /* Whether in a match of two operands the compare should be for
702 equal values rather than equal atoms (boils down to a type
703 check or not). */
704 bool value_match;
705 /* The captured value. */
706 operand *what;
707 virtual void gen_transform (FILE *f, int, const char *, bool, int,
708 const char *, capture_info *,
709 dt_operand ** = 0, int = 0);
712 /* if expression. */
714 struct if_expr : public operand
716 if_expr (source_location loc)
717 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
718 c_expr *cond;
719 operand *trueexpr;
720 operand *falseexpr;
723 /* with expression. */
725 struct with_expr : public operand
727 with_expr (source_location loc)
728 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
729 c_expr *with;
730 operand *subexpr;
733 template<>
734 template<>
735 inline bool
736 is_a_helper <capture *>::test (operand *op)
738 return op->type == operand::OP_CAPTURE;
741 template<>
742 template<>
743 inline bool
744 is_a_helper <predicate *>::test (operand *op)
746 return op->type == operand::OP_PREDICATE;
749 template<>
750 template<>
751 inline bool
752 is_a_helper <c_expr *>::test (operand *op)
754 return op->type == operand::OP_C_EXPR;
757 template<>
758 template<>
759 inline bool
760 is_a_helper <expr *>::test (operand *op)
762 return op->type == operand::OP_EXPR;
765 template<>
766 template<>
767 inline bool
768 is_a_helper <if_expr *>::test (operand *op)
770 return op->type == operand::OP_IF;
773 template<>
774 template<>
775 inline bool
776 is_a_helper <with_expr *>::test (operand *op)
778 return op->type == operand::OP_WITH;
781 /* The main class of a pattern and its transform. This is used to
782 represent both (simplify ...) and (match ...) kinds. The AST
783 duplicates all outer 'if' and 'for' expressions here so each
784 simplify can exist in isolation. */
786 struct simplify
788 enum simplify_kind { SIMPLIFY, MATCH };
790 simplify (simplify_kind kind_, operand *match_, operand *result_,
791 vec<vec<user_id *> > for_vec_, cid_map_t *capture_ids_)
792 : kind (kind_), match (match_), result (result_),
793 for_vec (for_vec_), for_subst_vec (vNULL),
794 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
796 simplify_kind kind;
797 /* The expression that is matched against the GENERIC or GIMPLE IL. */
798 operand *match;
799 /* For a (simplify ...) an expression with ifs and withs with the expression
800 produced when the pattern applies in the leafs.
801 For a (match ...) the leafs are either empty if it is a simple predicate
802 or the single expression specifying the matched operands. */
803 struct operand *result;
804 /* Collected 'for' expression operators that have to be replaced
805 in the lowering phase. */
806 vec<vec<user_id *> > for_vec;
807 vec<std::pair<user_id *, id_base *> > for_subst_vec;
808 /* A map of capture identifiers to indexes. */
809 cid_map_t *capture_ids;
810 int capture_max;
813 /* Debugging routines for dumping the AST. */
815 DEBUG_FUNCTION void
816 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
818 if (capture *c = dyn_cast<capture *> (o))
820 if (c->what && flattened == false)
821 print_operand (c->what, f, flattened);
822 fprintf (f, "@%u", c->where);
825 else if (predicate *p = dyn_cast<predicate *> (o))
826 fprintf (f, "%s", p->p->id);
828 else if (is_a<c_expr *> (o))
829 fprintf (f, "c_expr");
831 else if (expr *e = dyn_cast<expr *> (o))
833 if (e->ops.length () == 0)
834 fprintf (f, "%s", e->operation->id);
835 else
837 fprintf (f, "(%s", e->operation->id);
839 if (flattened == false)
841 for (unsigned i = 0; i < e->ops.length (); ++i)
843 putc (' ', f);
844 print_operand (e->ops[i], f, flattened);
847 putc (')', f);
851 else
852 gcc_unreachable ();
855 DEBUG_FUNCTION void
856 print_matches (struct simplify *s, FILE *f = stderr)
858 fprintf (f, "for expression: ");
859 print_operand (s->match, f);
860 putc ('\n', f);
864 /* AST lowering. */
866 /* Lowering of commutative operators. */
868 static void
869 cartesian_product (const vec< vec<operand *> >& ops_vector,
870 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
872 if (n == ops_vector.length ())
874 vec<operand *> xv = v.copy ();
875 result.safe_push (xv);
876 return;
879 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
881 v[n] = ops_vector[n][i];
882 cartesian_product (ops_vector, result, v, n + 1);
886 /* Lower OP to two operands in case it is marked as commutative. */
888 static vec<operand *>
889 commutate (operand *op, vec<vec<user_id *> > &for_vec)
891 vec<operand *> ret = vNULL;
893 if (capture *c = dyn_cast <capture *> (op))
895 if (!c->what)
897 ret.safe_push (op);
898 return ret;
900 vec<operand *> v = commutate (c->what, for_vec);
901 for (unsigned i = 0; i < v.length (); ++i)
903 capture *nc = new capture (c->location, c->where, v[i],
904 c->value_match);
905 ret.safe_push (nc);
907 return ret;
910 expr *e = dyn_cast <expr *> (op);
911 if (!e || e->ops.length () == 0)
913 ret.safe_push (op);
914 return ret;
917 vec< vec<operand *> > ops_vector = vNULL;
918 for (unsigned i = 0; i < e->ops.length (); ++i)
919 ops_vector.safe_push (commutate (e->ops[i], for_vec));
921 auto_vec< vec<operand *> > result;
922 auto_vec<operand *> v (e->ops.length ());
923 v.quick_grow_cleared (e->ops.length ());
924 cartesian_product (ops_vector, result, v, 0);
927 for (unsigned i = 0; i < result.length (); ++i)
929 expr *ne = new expr (e);
930 ne->is_commutative = false;
931 for (unsigned j = 0; j < result[i].length (); ++j)
932 ne->append_op (result[i][j]);
933 ret.safe_push (ne);
936 if (!e->is_commutative)
937 return ret;
939 for (unsigned i = 0; i < result.length (); ++i)
941 expr *ne = new expr (e);
942 if (operator_id *p = dyn_cast <operator_id *> (ne->operation))
944 if (comparison_code_p (p->code))
945 ne->operation = swap_tree_comparison (p);
947 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
949 bool found_compare = false;
950 for (unsigned j = 0; j < p->substitutes.length (); ++j)
951 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
953 if (comparison_code_p (q->code)
954 && swap_tree_comparison (q) != q)
956 found_compare = true;
957 break;
960 if (found_compare)
962 user_id *newop = new user_id ("<internal>");
963 for (unsigned j = 0; j < p->substitutes.length (); ++j)
965 id_base *subst = p->substitutes[j];
966 if (operator_id *q = dyn_cast <operator_id *> (subst))
968 if (comparison_code_p (q->code))
969 subst = swap_tree_comparison (q);
971 newop->substitutes.safe_push (subst);
973 ne->operation = newop;
974 /* Search for 'p' inside the for vector and push 'newop'
975 to the same level. */
976 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
977 for (unsigned k = 0; k < for_vec[j].length (); ++k)
978 if (for_vec[j][k] == p)
980 for_vec[j].safe_push (newop);
981 newop = NULL;
982 break;
986 ne->is_commutative = false;
987 // result[i].length () is 2 since e->operation is binary
988 for (unsigned j = result[i].length (); j; --j)
989 ne->append_op (result[i][j-1]);
990 ret.safe_push (ne);
993 return ret;
996 /* Lower operations marked as commutative in the AST of S and push
997 the resulting patterns to SIMPLIFIERS. */
999 static void
1000 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1002 vec<operand *> matchers = commutate (s->match, s->for_vec);
1003 for (unsigned i = 0; i < matchers.length (); ++i)
1005 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1006 s->for_vec, s->capture_ids);
1007 simplifiers.safe_push (ns);
1011 /* Strip conditional conversios using operator OPER from O and its
1012 children if STRIP, else replace them with an unconditional convert. */
1014 operand *
1015 lower_opt_convert (operand *o, enum tree_code oper,
1016 enum tree_code to_oper, bool strip)
1018 if (capture *c = dyn_cast<capture *> (o))
1020 if (c->what)
1021 return new capture (c->location, c->where,
1022 lower_opt_convert (c->what, oper, to_oper, strip),
1023 c->value_match);
1024 else
1025 return c;
1028 expr *e = dyn_cast<expr *> (o);
1029 if (!e)
1030 return o;
1032 if (*e->operation == oper)
1034 if (strip)
1035 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
1037 expr *ne = new expr (e);
1038 ne->operation = (to_oper == CONVERT_EXPR
1039 ? get_operator ("CONVERT_EXPR")
1040 : get_operator ("VIEW_CONVERT_EXPR"));
1041 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
1042 return ne;
1045 expr *ne = new expr (e);
1046 for (unsigned i = 0; i < e->ops.length (); ++i)
1047 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
1049 return ne;
1052 /* Determine whether O or its children uses the conditional conversion
1053 operator OPER. */
1055 static bool
1056 has_opt_convert (operand *o, enum tree_code oper)
1058 if (capture *c = dyn_cast<capture *> (o))
1060 if (c->what)
1061 return has_opt_convert (c->what, oper);
1062 else
1063 return false;
1066 expr *e = dyn_cast<expr *> (o);
1067 if (!e)
1068 return false;
1070 if (*e->operation == oper)
1071 return true;
1073 for (unsigned i = 0; i < e->ops.length (); ++i)
1074 if (has_opt_convert (e->ops[i], oper))
1075 return true;
1077 return false;
1080 /* Lower conditional convert operators in O, expanding it to a vector
1081 if required. */
1083 static vec<operand *>
1084 lower_opt_convert (operand *o)
1086 vec<operand *> v1 = vNULL, v2;
1088 v1.safe_push (o);
1090 enum tree_code opers[]
1091 = { CONVERT0, CONVERT_EXPR,
1092 CONVERT1, CONVERT_EXPR,
1093 CONVERT2, CONVERT_EXPR,
1094 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
1095 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
1096 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
1098 /* Conditional converts are lowered to a pattern with the
1099 conversion and one without. The three different conditional
1100 convert codes are lowered separately. */
1102 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
1104 v2 = vNULL;
1105 for (unsigned j = 0; j < v1.length (); ++j)
1106 if (has_opt_convert (v1[j], opers[i]))
1108 v2.safe_push (lower_opt_convert (v1[j],
1109 opers[i], opers[i+1], false));
1110 v2.safe_push (lower_opt_convert (v1[j],
1111 opers[i], opers[i+1], true));
1114 if (v2 != vNULL)
1116 v1 = vNULL;
1117 for (unsigned j = 0; j < v2.length (); ++j)
1118 v1.safe_push (v2[j]);
1122 return v1;
1125 /* Lower conditional convert operators in the AST of S and push
1126 the resulting multiple patterns to SIMPLIFIERS. */
1128 static void
1129 lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
1131 vec<operand *> matchers = lower_opt_convert (s->match);
1132 for (unsigned i = 0; i < matchers.length (); ++i)
1134 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1135 s->for_vec, s->capture_ids);
1136 simplifiers.safe_push (ns);
1140 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1141 GENERIC and a GIMPLE variant. */
1143 static vec<operand *>
1144 lower_cond (operand *o)
1146 vec<operand *> ro = vNULL;
1148 if (capture *c = dyn_cast<capture *> (o))
1150 if (c->what)
1152 vec<operand *> lop = vNULL;
1153 lop = lower_cond (c->what);
1155 for (unsigned i = 0; i < lop.length (); ++i)
1156 ro.safe_push (new capture (c->location, c->where, lop[i],
1157 c->value_match));
1158 return ro;
1162 expr *e = dyn_cast<expr *> (o);
1163 if (!e || e->ops.length () == 0)
1165 ro.safe_push (o);
1166 return ro;
1169 vec< vec<operand *> > ops_vector = vNULL;
1170 for (unsigned i = 0; i < e->ops.length (); ++i)
1171 ops_vector.safe_push (lower_cond (e->ops[i]));
1173 auto_vec< vec<operand *> > result;
1174 auto_vec<operand *> v (e->ops.length ());
1175 v.quick_grow_cleared (e->ops.length ());
1176 cartesian_product (ops_vector, result, v, 0);
1178 for (unsigned i = 0; i < result.length (); ++i)
1180 expr *ne = new expr (e);
1181 for (unsigned j = 0; j < result[i].length (); ++j)
1182 ne->append_op (result[i][j]);
1183 ro.safe_push (ne);
1184 /* If this is a COND with a captured expression or an
1185 expression with two operands then also match a GENERIC
1186 form on the compare. */
1187 if ((*e->operation == COND_EXPR
1188 || *e->operation == VEC_COND_EXPR)
1189 && ((is_a <capture *> (e->ops[0])
1190 && as_a <capture *> (e->ops[0])->what
1191 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1192 && as_a <expr *>
1193 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1194 || (is_a <expr *> (e->ops[0])
1195 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1197 expr *ne = new expr (e);
1198 for (unsigned j = 0; j < result[i].length (); ++j)
1199 ne->append_op (result[i][j]);
1200 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1202 expr *ocmp = as_a <expr *> (c->what);
1203 expr *cmp = new expr (ocmp);
1204 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1205 cmp->append_op (ocmp->ops[j]);
1206 cmp->is_generic = true;
1207 ne->ops[0] = new capture (c->location, c->where, cmp,
1208 c->value_match);
1210 else
1212 expr *ocmp = as_a <expr *> (ne->ops[0]);
1213 expr *cmp = new expr (ocmp);
1214 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1215 cmp->append_op (ocmp->ops[j]);
1216 cmp->is_generic = true;
1217 ne->ops[0] = cmp;
1219 ro.safe_push (ne);
1223 return ro;
1226 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1227 GENERIC and a GIMPLE variant. */
1229 static void
1230 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1232 vec<operand *> matchers = lower_cond (s->match);
1233 for (unsigned i = 0; i < matchers.length (); ++i)
1235 simplify *ns = new simplify (s->kind, matchers[i], s->result,
1236 s->for_vec, s->capture_ids);
1237 simplifiers.safe_push (ns);
1241 /* Return true if O refers to ID. */
1243 bool
1244 contains_id (operand *o, user_id *id)
1246 if (capture *c = dyn_cast<capture *> (o))
1247 return c->what && contains_id (c->what, id);
1249 if (expr *e = dyn_cast<expr *> (o))
1251 if (e->operation == id)
1252 return true;
1253 for (unsigned i = 0; i < e->ops.length (); ++i)
1254 if (contains_id (e->ops[i], id))
1255 return true;
1256 return false;
1259 if (with_expr *w = dyn_cast <with_expr *> (o))
1260 return (contains_id (w->with, id)
1261 || contains_id (w->subexpr, id));
1263 if (if_expr *ife = dyn_cast <if_expr *> (o))
1264 return (contains_id (ife->cond, id)
1265 || contains_id (ife->trueexpr, id)
1266 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1268 if (c_expr *ce = dyn_cast<c_expr *> (o))
1269 return ce->capture_ids && ce->capture_ids->get (id->id);
1271 return false;
1275 /* In AST operand O replace operator ID with operator WITH. */
1277 operand *
1278 replace_id (operand *o, user_id *id, id_base *with)
1280 /* Deep-copy captures and expressions, replacing operations as
1281 needed. */
1282 if (capture *c = dyn_cast<capture *> (o))
1284 if (!c->what)
1285 return c;
1286 return new capture (c->location, c->where,
1287 replace_id (c->what, id, with), c->value_match);
1289 else if (expr *e = dyn_cast<expr *> (o))
1291 expr *ne = new expr (e);
1292 if (e->operation == id)
1293 ne->operation = with;
1294 for (unsigned i = 0; i < e->ops.length (); ++i)
1295 ne->append_op (replace_id (e->ops[i], id, with));
1296 return ne;
1298 else if (with_expr *w = dyn_cast <with_expr *> (o))
1300 with_expr *nw = new with_expr (w->location);
1301 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1302 nw->subexpr = replace_id (w->subexpr, id, with);
1303 return nw;
1305 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1307 if_expr *nife = new if_expr (ife->location);
1308 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1309 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1310 if (ife->falseexpr)
1311 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1312 return nife;
1315 /* For c_expr we simply record a string replacement table which is
1316 applied at code-generation time. */
1317 if (c_expr *ce = dyn_cast<c_expr *> (o))
1319 vec<c_expr::id_tab> ids = ce->ids.copy ();
1320 ids.safe_push (c_expr::id_tab (id->id, with->id));
1321 return new c_expr (ce->r, ce->location,
1322 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1325 return o;
1328 /* Return true if the binary operator OP is ok for delayed substitution
1329 during for lowering. */
1331 static bool
1332 binary_ok (operator_id *op)
1334 switch (op->code)
1336 case PLUS_EXPR:
1337 case MINUS_EXPR:
1338 case MULT_EXPR:
1339 case TRUNC_DIV_EXPR:
1340 case CEIL_DIV_EXPR:
1341 case FLOOR_DIV_EXPR:
1342 case ROUND_DIV_EXPR:
1343 case TRUNC_MOD_EXPR:
1344 case CEIL_MOD_EXPR:
1345 case FLOOR_MOD_EXPR:
1346 case ROUND_MOD_EXPR:
1347 case RDIV_EXPR:
1348 case EXACT_DIV_EXPR:
1349 case MIN_EXPR:
1350 case MAX_EXPR:
1351 case BIT_IOR_EXPR:
1352 case BIT_XOR_EXPR:
1353 case BIT_AND_EXPR:
1354 return true;
1355 default:
1356 return false;
1360 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1362 static void
1363 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1365 vec<vec<user_id *> >& for_vec = sin->for_vec;
1366 unsigned worklist_start = 0;
1367 auto_vec<simplify *> worklist;
1368 worklist.safe_push (sin);
1370 /* Lower each recorded for separately, operating on the
1371 set of simplifiers created by the previous one.
1372 Lower inner-to-outer so inner for substitutes can refer
1373 to operators replaced by outer fors. */
1374 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1376 vec<user_id *>& ids = for_vec[fi];
1377 unsigned n_ids = ids.length ();
1378 unsigned max_n_opers = 0;
1379 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1380 for (unsigned i = 0; i < n_ids; ++i)
1382 if (ids[i]->substitutes.length () > max_n_opers)
1383 max_n_opers = ids[i]->substitutes.length ();
1384 /* Require that all substitutes are of the same kind so that
1385 if we delay substitution to the result op code generation
1386 can look at the first substitute for deciding things like
1387 types of operands. */
1388 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1389 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1390 if (ids[i]->substitutes[j]->kind != kind)
1391 can_delay_subst = false;
1392 else if (operator_id *op
1393 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1395 operator_id *op0
1396 = as_a <operator_id *> (ids[i]->substitutes[0]);
1397 if (strcmp (op->tcc, "tcc_comparison") == 0
1398 && strcmp (op0->tcc, "tcc_comparison") == 0)
1400 /* Unfortunately we can't just allow all tcc_binary. */
1401 else if (strcmp (op->tcc, "tcc_binary") == 0
1402 && strcmp (op0->tcc, "tcc_binary") == 0
1403 && binary_ok (op)
1404 && binary_ok (op0))
1406 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1407 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1408 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1409 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1411 else
1412 can_delay_subst = false;
1414 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1416 else
1417 can_delay_subst = false;
1420 unsigned worklist_end = worklist.length ();
1421 for (unsigned si = worklist_start; si < worklist_end; ++si)
1423 simplify *s = worklist[si];
1424 for (unsigned j = 0; j < max_n_opers; ++j)
1426 operand *match_op = s->match;
1427 operand *result_op = s->result;
1428 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1429 bool skip = false;
1430 for (unsigned i = 0; i < n_ids; ++i)
1432 user_id *id = ids[i];
1433 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1434 if (oper == null_id
1435 && (contains_id (match_op, id)
1436 || contains_id (result_op, id)))
1438 skip = true;
1439 break;
1441 subst.quick_push (std::make_pair (id, oper));
1442 match_op = replace_id (match_op, id, oper);
1443 if (result_op
1444 && !can_delay_subst)
1445 result_op = replace_id (result_op, id, oper);
1447 if (skip)
1448 continue;
1450 simplify *ns = new simplify (s->kind, match_op, result_op,
1451 vNULL, s->capture_ids);
1452 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1453 if (result_op
1454 && can_delay_subst)
1455 ns->for_subst_vec.safe_splice (subst);
1457 worklist.safe_push (ns);
1460 worklist_start = worklist_end;
1463 /* Copy out the result from the last for lowering. */
1464 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1465 simplifiers.safe_push (worklist[i]);
1468 /* Lower the AST for everything in SIMPLIFIERS. */
1470 static void
1471 lower (vec<simplify *>& simplifiers, bool gimple)
1473 auto_vec<simplify *> out_simplifiers;
1474 for (unsigned i = 0; i < simplifiers.length (); ++i)
1475 lower_opt_convert (simplifiers[i], out_simplifiers);
1477 simplifiers.truncate (0);
1478 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1479 lower_commutative (out_simplifiers[i], simplifiers);
1481 out_simplifiers.truncate (0);
1482 if (gimple)
1483 for (unsigned i = 0; i < simplifiers.length (); ++i)
1484 lower_cond (simplifiers[i], out_simplifiers);
1485 else
1486 out_simplifiers.safe_splice (simplifiers);
1489 simplifiers.truncate (0);
1490 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1491 lower_for (out_simplifiers[i], simplifiers);
1497 /* The decision tree built for generating GIMPLE and GENERIC pattern
1498 matching code. It represents the 'match' expression of all
1499 simplifies and has those as its leafs. */
1501 struct dt_simplify;
1503 /* A hash-map collecting semantically equivalent leafs in the decision
1504 tree for splitting out to separate functions. */
1505 struct sinfo
1507 dt_simplify *s;
1509 const char *fname;
1510 unsigned cnt;
1513 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1514 sinfo *>
1516 static inline hashval_t hash (const key_type &);
1517 static inline bool equal_keys (const key_type &, const key_type &);
1518 template <typename T> static inline void remove (T &) {}
1521 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1522 sinfo_map_t;
1525 /* Decision tree base class, used for DT_TRUE and DT_NODE. */
1527 struct dt_node
1529 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1531 enum dt_type type;
1532 unsigned level;
1533 vec<dt_node *> kids;
1535 /* Statistics. */
1536 unsigned num_leafs;
1537 unsigned total_size;
1538 unsigned max_level;
1540 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1542 dt_node *append_node (dt_node *);
1543 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1544 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1545 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1546 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1548 virtual void gen (FILE *, int, bool) {}
1550 void gen_kids (FILE *, int, bool);
1551 void gen_kids_1 (FILE *, int, bool,
1552 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1553 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1555 void analyze (sinfo_map_t &);
1558 /* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1560 struct dt_operand : public dt_node
1562 operand *op;
1563 dt_operand *match_dop;
1564 dt_operand *parent;
1565 unsigned pos;
1566 bool value_match;
1568 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1569 dt_operand *parent_ = 0, unsigned pos_ = 0)
1570 : dt_node (type), op (op_), match_dop (match_dop_),
1571 parent (parent_), pos (pos_), value_match (false) {}
1573 void gen (FILE *, int, bool);
1574 unsigned gen_predicate (FILE *, int, const char *, bool);
1575 unsigned gen_match_op (FILE *, int, const char *, bool);
1577 unsigned gen_gimple_expr (FILE *, int);
1578 unsigned gen_generic_expr (FILE *, int, const char *);
1580 char *get_name (char *);
1581 void gen_opname (char *, unsigned);
1584 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1586 struct dt_simplify : public dt_node
1588 simplify *s;
1589 unsigned pattern_no;
1590 dt_operand **indexes;
1591 sinfo *info;
1593 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1594 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1595 indexes (indexes_), info (NULL) {}
1597 void gen_1 (FILE *, int, bool, operand *);
1598 void gen (FILE *f, int, bool);
1601 template<>
1602 template<>
1603 inline bool
1604 is_a_helper <dt_operand *>::test (dt_node *n)
1606 return (n->type == dt_node::DT_OPERAND
1607 || n->type == dt_node::DT_MATCH);
1610 template<>
1611 template<>
1612 inline bool
1613 is_a_helper <dt_simplify *>::test (dt_node *n)
1615 return n->type == dt_node::DT_SIMPLIFY;
1620 /* A container for the actual decision tree. */
1622 struct decision_tree
1624 dt_node *root;
1626 void insert (struct simplify *, unsigned);
1627 void gen (FILE *f, bool gimple);
1628 void print (FILE *f = stderr);
1630 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1632 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1633 unsigned pos = 0, dt_node *parent = 0);
1634 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1635 static bool cmp_node (dt_node *, dt_node *);
1636 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1639 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1641 bool
1642 cmp_operand (operand *o1, operand *o2)
1644 if (!o1 || !o2 || o1->type != o2->type)
1645 return false;
1647 if (o1->type == operand::OP_PREDICATE)
1649 predicate *p1 = as_a<predicate *>(o1);
1650 predicate *p2 = as_a<predicate *>(o2);
1651 return p1->p == p2->p;
1653 else if (o1->type == operand::OP_EXPR)
1655 expr *e1 = static_cast<expr *>(o1);
1656 expr *e2 = static_cast<expr *>(o2);
1657 return (e1->operation == e2->operation
1658 && e1->is_generic == e2->is_generic);
1660 else
1661 return false;
1664 /* Compare two decision tree nodes N1 and N2 and return true if they
1665 are equal. */
1667 bool
1668 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1670 if (!n1 || !n2 || n1->type != n2->type)
1671 return false;
1673 if (n1 == n2)
1674 return true;
1676 if (n1->type == dt_node::DT_TRUE)
1677 return false;
1679 if (n1->type == dt_node::DT_OPERAND)
1680 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1681 (as_a<dt_operand *> (n2))->op);
1682 else if (n1->type == dt_node::DT_MATCH)
1683 return (((as_a<dt_operand *> (n1))->match_dop
1684 == (as_a<dt_operand *> (n2))->match_dop)
1685 && ((as_a<dt_operand *> (n1))->value_match
1686 == (as_a<dt_operand *> (n2))->value_match));
1687 return false;
1690 /* Search OPS for a decision tree node like P and return it if found. */
1692 dt_node *
1693 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1695 /* We can merge adjacent DT_TRUE. */
1696 if (p->type == dt_node::DT_TRUE
1697 && !ops.is_empty ()
1698 && ops.last ()->type == dt_node::DT_TRUE)
1699 return ops.last ();
1700 for (int i = ops.length () - 1; i >= 0; --i)
1702 /* But we can't merge across DT_TRUE nodes as they serve as
1703 pattern order barriers to make sure that patterns apply
1704 in order of appearance in case multiple matches are possible. */
1705 if (ops[i]->type == dt_node::DT_TRUE)
1706 return NULL;
1707 if (decision_tree::cmp_node (ops[i], p))
1708 return ops[i];
1710 return NULL;
1713 /* Append N to the decision tree if it there is not already an existing
1714 identical child. */
1716 dt_node *
1717 dt_node::append_node (dt_node *n)
1719 dt_node *kid;
1721 kid = decision_tree::find_node (kids, n);
1722 if (kid)
1723 return kid;
1725 kids.safe_push (n);
1726 n->level = this->level + 1;
1728 return n;
1731 /* Append OP to the decision tree. */
1733 dt_node *
1734 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1736 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1737 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1738 return append_node (n);
1741 /* Append a DT_TRUE decision tree node. */
1743 dt_node *
1744 dt_node::append_true_op (dt_node *parent, unsigned pos)
1746 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1747 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1748 return append_node (n);
1751 /* Append a DT_MATCH decision tree node. */
1753 dt_node *
1754 dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1756 dt_operand *parent_ = as_a<dt_operand *> (parent);
1757 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1758 return append_node (n);
1761 /* Append S to the decision tree. */
1763 dt_node *
1764 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1765 dt_operand **indexes)
1767 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1768 for (unsigned i = 0; i < kids.length (); ++i)
1769 if (dt_simplify *s2 = dyn_cast <dt_simplify *> (kids[i]))
1771 warning_at (s->match->location, "duplicate pattern");
1772 warning_at (s2->s->match->location, "previous pattern defined here");
1773 print_operand (s->match, stderr);
1774 fprintf (stderr, "\n");
1776 return append_node (n);
1779 /* Analyze the node and its children. */
1781 void
1782 dt_node::analyze (sinfo_map_t &map)
1784 num_leafs = 0;
1785 total_size = 1;
1786 max_level = level;
1788 if (type == DT_SIMPLIFY)
1790 /* Populate the map of equivalent simplifies. */
1791 dt_simplify *s = as_a <dt_simplify *> (this);
1792 bool existed;
1793 sinfo *&si = map.get_or_insert (s, &existed);
1794 if (!existed)
1796 si = new sinfo;
1797 si->s = s;
1798 si->cnt = 1;
1799 si->fname = NULL;
1801 else
1802 si->cnt++;
1803 s->info = si;
1804 num_leafs = 1;
1805 return;
1808 for (unsigned i = 0; i < kids.length (); ++i)
1810 kids[i]->analyze (map);
1811 num_leafs += kids[i]->num_leafs;
1812 total_size += kids[i]->total_size;
1813 max_level = MAX (max_level, kids[i]->max_level);
1817 /* Insert O into the decision tree and return the decision tree node found
1818 or created. */
1820 dt_node *
1821 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1822 unsigned pos, dt_node *parent)
1824 dt_node *q, *elm = 0;
1826 if (capture *c = dyn_cast<capture *> (o))
1828 unsigned capt_index = c->where;
1830 if (indexes[capt_index] == 0)
1832 if (c->what)
1833 q = insert_operand (p, c->what, indexes, pos, parent);
1834 else
1836 q = elm = p->append_true_op (parent, pos);
1837 goto at_assert_elm;
1839 // get to the last capture
1840 for (operand *what = c->what;
1841 what && is_a<capture *> (what);
1842 c = as_a<capture *> (what), what = c->what)
1845 if (!c->what)
1847 unsigned cc_index = c->where;
1848 dt_operand *match_op = indexes[cc_index];
1850 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1851 elm = decision_tree::find_node (p->kids, &temp);
1853 if (elm == 0)
1855 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1856 temp.value_match = c->value_match;
1857 elm = decision_tree::find_node (p->kids, &temp);
1860 else
1862 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1863 elm = decision_tree::find_node (p->kids, &temp);
1866 at_assert_elm:
1867 gcc_assert (elm->type == dt_node::DT_TRUE
1868 || elm->type == dt_node::DT_OPERAND
1869 || elm->type == dt_node::DT_MATCH);
1870 indexes[capt_index] = static_cast<dt_operand *> (elm);
1871 return q;
1873 else
1875 p = p->append_match_op (indexes[capt_index], parent, pos);
1876 as_a <dt_operand *>(p)->value_match = c->value_match;
1877 if (c->what)
1878 return insert_operand (p, c->what, indexes, 0, p);
1879 else
1880 return p;
1883 p = p->append_op (o, parent, pos);
1884 q = p;
1886 if (expr *e = dyn_cast <expr *>(o))
1888 for (unsigned i = 0; i < e->ops.length (); ++i)
1889 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1892 return q;
1895 /* Insert S into the decision tree. */
1897 void
1898 decision_tree::insert (struct simplify *s, unsigned pattern_no)
1900 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1901 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1902 p->append_simplify (s, pattern_no, indexes);
1905 /* Debug functions to dump the decision tree. */
1907 DEBUG_FUNCTION void
1908 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1910 if (p->type == dt_node::DT_NODE)
1911 fprintf (f, "root");
1912 else
1914 fprintf (f, "|");
1915 for (unsigned i = 0; i < indent; i++)
1916 fprintf (f, "-");
1918 if (p->type == dt_node::DT_OPERAND)
1920 dt_operand *dop = static_cast<dt_operand *>(p);
1921 print_operand (dop->op, f, true);
1923 else if (p->type == dt_node::DT_TRUE)
1924 fprintf (f, "true");
1925 else if (p->type == dt_node::DT_MATCH)
1926 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1927 else if (p->type == dt_node::DT_SIMPLIFY)
1929 dt_simplify *s = static_cast<dt_simplify *> (p);
1930 fprintf (f, "simplify_%u { ", s->pattern_no);
1931 for (int i = 0; i <= s->s->capture_max; ++i)
1932 fprintf (f, "%p, ", (void *) s->indexes[i]);
1933 fprintf (f, " } ");
1937 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1939 for (unsigned i = 0; i < p->kids.length (); ++i)
1940 decision_tree::print_node (p->kids[i], f, indent + 2);
1943 DEBUG_FUNCTION void
1944 decision_tree::print (FILE *f)
1946 return decision_tree::print_node (root, f);
1950 /* For GENERIC we have to take care of wrapping multiple-used
1951 expressions with side-effects in save_expr and preserve side-effects
1952 of expressions with omit_one_operand. Analyze captures in
1953 match, result and with expressions and perform early-outs
1954 on the outermost match expression operands for cases we cannot
1955 handle. */
1957 struct capture_info
1959 capture_info (simplify *s, operand *, bool);
1960 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1961 bool walk_result (operand *o, bool, operand *);
1962 void walk_c_expr (c_expr *);
1964 struct cinfo
1966 bool expr_p;
1967 bool cse_p;
1968 bool force_no_side_effects_p;
1969 bool force_single_use;
1970 bool cond_expr_cond_p;
1971 unsigned long toplevel_msk;
1972 unsigned match_use_count;
1973 unsigned result_use_count;
1974 unsigned same_as;
1975 capture *c;
1978 auto_vec<cinfo> info;
1979 unsigned long force_no_side_effects;
1980 bool gimple;
1983 /* Analyze captures in S. */
1985 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
1987 gimple = gimple_;
1989 expr *e;
1990 if (s->kind == simplify::MATCH)
1992 force_no_side_effects = -1;
1993 return;
1996 force_no_side_effects = 0;
1997 info.safe_grow_cleared (s->capture_max + 1);
1998 for (int i = 0; i <= s->capture_max; ++i)
1999 info[i].same_as = i;
2001 e = as_a <expr *> (s->match);
2002 for (unsigned i = 0; i < e->ops.length (); ++i)
2003 walk_match (e->ops[i], i,
2004 (i != 0 && *e->operation == COND_EXPR)
2005 || *e->operation == TRUTH_ANDIF_EXPR
2006 || *e->operation == TRUTH_ORIF_EXPR,
2007 i == 0
2008 && (*e->operation == COND_EXPR
2009 || *e->operation == VEC_COND_EXPR));
2011 walk_result (s->result, false, result);
2014 /* Analyze captures in the match expression piece O. */
2016 void
2017 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2018 bool conditional_p, bool cond_expr_cond_p)
2020 if (capture *c = dyn_cast <capture *> (o))
2022 unsigned where = c->where;
2023 info[where].match_use_count++;
2024 info[where].toplevel_msk |= 1 << toplevel_arg;
2025 info[where].force_no_side_effects_p |= conditional_p;
2026 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2027 if (!info[where].c)
2028 info[where].c = c;
2029 if (!c->what)
2030 return;
2031 /* Recurse to exprs and captures. */
2032 if (is_a <capture *> (c->what)
2033 || is_a <expr *> (c->what))
2034 walk_match (c->what, toplevel_arg, conditional_p, false);
2035 /* We need to look past multiple captures to find a captured
2036 expression as with conditional converts two captures
2037 can be collapsed onto the same expression. Also collect
2038 what captures capture the same thing. */
2039 while (c->what && is_a <capture *> (c->what))
2041 c = as_a <capture *> (c->what);
2042 if (info[c->where].same_as != c->where
2043 && info[c->where].same_as != info[where].same_as)
2044 fatal_at (c->location, "cannot handle this collapsed capture");
2045 info[c->where].same_as = info[where].same_as;
2047 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2048 expr *e;
2049 if (c->what
2050 && (e = dyn_cast <expr *> (c->what)))
2052 info[where].expr_p = true;
2053 info[where].force_single_use |= e->force_single_use;
2056 else if (expr *e = dyn_cast <expr *> (o))
2058 for (unsigned i = 0; i < e->ops.length (); ++i)
2060 bool cond_p = conditional_p;
2061 bool cond_expr_cond_p = false;
2062 if (i != 0 && *e->operation == COND_EXPR)
2063 cond_p = true;
2064 else if (*e->operation == TRUTH_ANDIF_EXPR
2065 || *e->operation == TRUTH_ORIF_EXPR)
2066 cond_p = true;
2067 if (i == 0
2068 && (*e->operation == COND_EXPR
2069 || *e->operation == VEC_COND_EXPR))
2070 cond_expr_cond_p = true;
2071 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
2074 else if (is_a <predicate *> (o))
2076 /* Mark non-captured leafs toplevel arg for checking. */
2077 force_no_side_effects |= 1 << toplevel_arg;
2078 if (verbose >= 1
2079 && !gimple)
2080 warning_at (o->location,
2081 "forcing no side-effects on possibly lost leaf");
2083 else
2084 gcc_unreachable ();
2087 /* Analyze captures in the result expression piece O. Return true
2088 if RESULT was visited in one of the children. Only visit
2089 non-if/with children if they are rooted on RESULT. */
2091 bool
2092 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2094 if (capture *c = dyn_cast <capture *> (o))
2096 unsigned where = info[c->where].same_as;
2097 info[where].result_use_count++;
2098 /* If we substitute an expression capture we don't know
2099 which captures this will end up using (well, we don't
2100 compute that). Force the uses to be side-effect free
2101 which means forcing the toplevels that reach the
2102 expression side-effect free. */
2103 if (info[where].expr_p)
2104 force_no_side_effects |= info[where].toplevel_msk;
2105 /* Mark CSE capture uses as forced to have no side-effects. */
2106 if (c->what
2107 && is_a <expr *> (c->what))
2109 info[where].cse_p = true;
2110 walk_result (c->what, true, result);
2113 else if (expr *e = dyn_cast <expr *> (o))
2115 id_base *opr = e->operation;
2116 if (user_id *uid = dyn_cast <user_id *> (opr))
2117 opr = uid->substitutes[0];
2118 for (unsigned i = 0; i < e->ops.length (); ++i)
2120 bool cond_p = conditional_p;
2121 if (i != 0 && *e->operation == COND_EXPR)
2122 cond_p = true;
2123 else if (*e->operation == TRUTH_ANDIF_EXPR
2124 || *e->operation == TRUTH_ORIF_EXPR)
2125 cond_p = true;
2126 walk_result (e->ops[i], cond_p, result);
2129 else if (if_expr *e = dyn_cast <if_expr *> (o))
2131 /* 'if' conditions should be all fine. */
2132 if (e->trueexpr == result)
2134 walk_result (e->trueexpr, false, result);
2135 return true;
2137 if (e->falseexpr == result)
2139 walk_result (e->falseexpr, false, result);
2140 return true;
2142 bool res = false;
2143 if (is_a <if_expr *> (e->trueexpr)
2144 || is_a <with_expr *> (e->trueexpr))
2145 res |= walk_result (e->trueexpr, false, result);
2146 if (e->falseexpr
2147 && (is_a <if_expr *> (e->falseexpr)
2148 || is_a <with_expr *> (e->falseexpr)))
2149 res |= walk_result (e->falseexpr, false, result);
2150 return res;
2152 else if (with_expr *e = dyn_cast <with_expr *> (o))
2154 bool res = (e->subexpr == result);
2155 if (res
2156 || is_a <if_expr *> (e->subexpr)
2157 || is_a <with_expr *> (e->subexpr))
2158 res |= walk_result (e->subexpr, false, result);
2159 if (res)
2160 walk_c_expr (e->with);
2161 return res;
2163 else if (c_expr *e = dyn_cast <c_expr *> (o))
2164 walk_c_expr (e);
2165 else
2166 gcc_unreachable ();
2168 return false;
2171 /* Look for captures in the C expr E. */
2173 void
2174 capture_info::walk_c_expr (c_expr *e)
2176 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2177 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2178 really escape through. */
2179 unsigned p_depth = 0;
2180 for (unsigned i = 0; i < e->code.length (); ++i)
2182 const cpp_token *t = &e->code[i];
2183 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2184 id_base *id;
2185 if (t->type == CPP_NAME
2186 && (strcmp ((const char *)CPP_HASHNODE
2187 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2188 || strcmp ((const char *)CPP_HASHNODE
2189 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2190 || strcmp ((const char *)CPP_HASHNODE
2191 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2192 || ((id = get_operator ((const char *)CPP_HASHNODE
2193 (t->val.node.node)->ident.str))
2194 && is_a <predicate_id *> (id)))
2195 && n->type == CPP_OPEN_PAREN)
2196 p_depth++;
2197 else if (t->type == CPP_CLOSE_PAREN
2198 && p_depth > 0)
2199 p_depth--;
2200 else if (p_depth == 0
2201 && t->type == CPP_ATSIGN
2202 && (n->type == CPP_NUMBER
2203 || n->type == CPP_NAME)
2204 && !(n->flags & PREV_WHITE))
2206 const char *id;
2207 if (n->type == CPP_NUMBER)
2208 id = (const char *)n->val.str.text;
2209 else
2210 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2211 unsigned *where = e->capture_ids->get(id);
2212 if (! where)
2213 fatal_at (n, "unknown capture id '%s'", id);
2214 info[info[*where].same_as].force_no_side_effects_p = true;
2215 if (verbose >= 1
2216 && !gimple)
2217 warning_at (t, "capture escapes");
2223 /* Code generation off the decision tree and the refered AST nodes. */
2225 bool
2226 is_conversion (id_base *op)
2228 return (*op == CONVERT_EXPR
2229 || *op == NOP_EXPR
2230 || *op == FLOAT_EXPR
2231 || *op == FIX_TRUNC_EXPR
2232 || *op == VIEW_CONVERT_EXPR);
2235 /* Get the type to be used for generating operand POS of OP from the
2236 various sources. */
2238 static const char *
2239 get_operand_type (id_base *op, unsigned pos,
2240 const char *in_type,
2241 const char *expr_type,
2242 const char *other_oprnd_type)
2244 /* Generally operands whose type does not match the type of the
2245 expression generated need to know their types but match and
2246 thus can fall back to 'other_oprnd_type'. */
2247 if (is_conversion (op))
2248 return other_oprnd_type;
2249 else if (*op == REALPART_EXPR
2250 || *op == IMAGPART_EXPR)
2251 return other_oprnd_type;
2252 else if (is_a <operator_id *> (op)
2253 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2254 return other_oprnd_type;
2255 else if (*op == COND_EXPR
2256 && pos == 0)
2257 return "boolean_type_node";
2258 else
2260 /* Otherwise all types should match - choose one in order of
2261 preference. */
2262 if (expr_type)
2263 return expr_type;
2264 else if (in_type)
2265 return in_type;
2266 else
2267 return other_oprnd_type;
2271 /* Generate transform code for an expression. */
2273 void
2274 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2275 int depth, const char *in_type, capture_info *cinfo,
2276 dt_operand **indexes, int)
2278 id_base *opr = operation;
2279 /* When we delay operator substituting during lowering of fors we
2280 make sure that for code-gen purposes the effects of each substitute
2281 are the same. Thus just look at that. */
2282 if (user_id *uid = dyn_cast <user_id *> (opr))
2283 opr = uid->substitutes[0];
2285 bool conversion_p = is_conversion (opr);
2286 const char *type = expr_type;
2287 char optype[64];
2288 if (type)
2289 /* If there was a type specification in the pattern use it. */
2291 else if (conversion_p)
2292 /* For conversions we need to build the expression using the
2293 outer type passed in. */
2294 type = in_type;
2295 else if (*opr == REALPART_EXPR
2296 || *opr == IMAGPART_EXPR)
2298 /* __real and __imag use the component type of its operand. */
2299 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
2300 type = optype;
2302 else if (is_a <operator_id *> (opr)
2303 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2305 /* comparisons use boolean_type_node (or what gets in), but
2306 their operands need to figure out the types themselves. */
2307 if (in_type)
2308 type = in_type;
2309 else
2311 sprintf (optype, "boolean_type_node");
2312 type = optype;
2314 in_type = NULL;
2316 else if (*opr == COND_EXPR
2317 || *opr == VEC_COND_EXPR)
2319 /* Conditions are of the same type as their first alternative. */
2320 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
2321 type = optype;
2323 else
2325 /* Other operations are of the same type as their first operand. */
2326 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
2327 type = optype;
2329 if (!type)
2330 fatal_at (location, "cannot determine type of operand");
2332 fprintf_indent (f, indent, "{\n");
2333 indent += 2;
2334 fprintf_indent (f, indent, "tree ops%d[%u], res;\n", depth, ops.length ());
2335 char op0type[64];
2336 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
2337 for (unsigned i = 0; i < ops.length (); ++i)
2339 char dest[32];
2340 snprintf (dest, 32, "ops%d[%u]", depth, i);
2341 const char *optype
2342 = get_operand_type (opr, i, in_type, expr_type,
2343 i == 0 ? NULL : op0type);
2344 ops[i]->gen_transform (f, indent, dest, gimple, depth + 1, optype,
2345 cinfo, indexes,
2346 (*opr == COND_EXPR
2347 || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2350 const char *opr_name;
2351 if (*operation == CONVERT_EXPR)
2352 opr_name = "NOP_EXPR";
2353 else
2354 opr_name = operation->id;
2356 if (gimple)
2358 if (*opr == CONVERT_EXPR)
2360 fprintf_indent (f, indent,
2361 "if (%s != TREE_TYPE (ops%d[0])\n",
2362 type, depth);
2363 fprintf_indent (f, indent,
2364 " && !useless_type_conversion_p (%s, TREE_TYPE (ops%d[0])))\n",
2365 type, depth);
2366 fprintf_indent (f, indent + 2, "{\n");
2367 indent += 4;
2369 /* ??? Building a stmt can fail for various reasons here, seq being
2370 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2371 So if we fail here we should continue matching other patterns. */
2372 fprintf_indent (f, indent, "code_helper tem_code = %s;\n", opr_name);
2373 fprintf_indent (f, indent, "tree tem_ops[3] = { ");
2374 for (unsigned i = 0; i < ops.length (); ++i)
2375 fprintf (f, "ops%d[%u]%s", depth, i,
2376 i == ops.length () - 1 ? " };\n" : ", ");
2377 fprintf_indent (f, indent,
2378 "gimple_resimplify%d (lseq, &tem_code, %s, tem_ops, valueize);\n",
2379 ops.length (), type);
2380 fprintf_indent (f, indent,
2381 "res = maybe_push_res_to_seq (tem_code, %s, tem_ops, lseq);\n",
2382 type);
2383 fprintf_indent (f, indent,
2384 "if (!res) return false;\n");
2385 if (*opr == CONVERT_EXPR)
2387 indent -= 4;
2388 fprintf_indent (f, indent, " }\n");
2389 fprintf_indent (f, indent, "else\n");
2390 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2393 else
2395 if (*opr == CONVERT_EXPR)
2397 fprintf_indent (f, indent, "if (TREE_TYPE (ops%d[0]) != %s)\n",
2398 depth, type);
2399 indent += 2;
2401 if (opr->kind == id_base::CODE)
2402 fprintf_indent (f, indent, "res = fold_build%d_loc (loc, %s, %s",
2403 ops.length(), opr_name, type);
2404 else
2406 fprintf_indent (f, indent, "{\n");
2407 fprintf_indent (f, indent, " res = maybe_build_call_expr_loc (loc, "
2408 "%s, %s, %d", opr_name, type, ops.length());
2410 for (unsigned i = 0; i < ops.length (); ++i)
2411 fprintf (f, ", ops%d[%u]", depth, i);
2412 fprintf (f, ");\n");
2413 if (opr->kind != id_base::CODE)
2415 fprintf_indent (f, indent, " if (!res)\n");
2416 fprintf_indent (f, indent, " return NULL_TREE;\n");
2417 fprintf_indent (f, indent, "}\n");
2419 if (*opr == CONVERT_EXPR)
2421 indent -= 2;
2422 fprintf_indent (f, indent, "else\n");
2423 fprintf_indent (f, indent, " res = ops%d[0];\n", depth);
2426 fprintf_indent (f, indent, "%s = res;\n", dest);
2427 indent -= 2;
2428 fprintf_indent (f, indent, "}\n");
2431 /* Generate code for a c_expr which is either the expression inside
2432 an if statement or a sequence of statements which computes a
2433 result to be stored to DEST. */
2435 void
2436 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2437 bool, int, const char *, capture_info *,
2438 dt_operand **, int)
2440 if (dest && nr_stmts == 1)
2441 fprintf_indent (f, indent, "%s = ", dest);
2443 unsigned stmt_nr = 1;
2444 for (unsigned i = 0; i < code.length (); ++i)
2446 const cpp_token *token = &code[i];
2448 /* Replace captures for code-gen. */
2449 if (token->type == CPP_ATSIGN)
2451 const cpp_token *n = &code[i+1];
2452 if ((n->type == CPP_NUMBER
2453 || n->type == CPP_NAME)
2454 && !(n->flags & PREV_WHITE))
2456 if (token->flags & PREV_WHITE)
2457 fputc (' ', f);
2458 const char *id;
2459 if (n->type == CPP_NUMBER)
2460 id = (const char *)n->val.str.text;
2461 else
2462 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2463 unsigned *cid = capture_ids->get (id);
2464 if (!cid)
2465 fatal_at (token, "unknown capture id");
2466 fprintf (f, "captures[%u]", *cid);
2467 ++i;
2468 continue;
2472 if (token->flags & PREV_WHITE)
2473 fputc (' ', f);
2475 if (token->type == CPP_NAME)
2477 const char *id = (const char *) NODE_NAME (token->val.node.node);
2478 unsigned j;
2479 for (j = 0; j < ids.length (); ++j)
2481 if (strcmp (id, ids[j].id) == 0)
2483 fprintf (f, "%s", ids[j].oper);
2484 break;
2487 if (j < ids.length ())
2488 continue;
2491 /* Output the token as string. */
2492 char *tk = (char *)cpp_token_as_text (r, token);
2493 fputs (tk, f);
2495 if (token->type == CPP_SEMICOLON)
2497 stmt_nr++;
2498 fputc ('\n', f);
2499 if (dest && stmt_nr == nr_stmts)
2500 fprintf_indent (f, indent, "%s = ", dest);
2505 /* Generate transform code for a capture. */
2507 void
2508 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2509 int depth, const char *in_type, capture_info *cinfo,
2510 dt_operand **indexes, int cond_handling)
2512 if (what && is_a<expr *> (what))
2514 if (indexes[where] == 0)
2516 char buf[20];
2517 sprintf (buf, "captures[%u]", where);
2518 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2519 cinfo, NULL);
2523 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2525 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2526 with substituting a capture of that. */
2527 if (gimple
2528 && cond_handling != 0
2529 && cinfo->info[where].cond_expr_cond_p)
2531 /* If substituting into a cond_expr condition, unshare. */
2532 if (cond_handling == 1)
2533 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2534 /* If substituting elsewhere we might need to decompose it. */
2535 else if (cond_handling == 2)
2537 /* ??? Returning false here will also not allow any other patterns
2538 to match unless this generator was split out. */
2539 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2540 fprintf_indent (f, indent, " {\n");
2541 fprintf_indent (f, indent, " if (!seq) return false;\n");
2542 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2543 " TREE_CODE (%s),"
2544 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2545 " TREE_OPERAND (%s, 1));\n",
2546 dest, dest, dest, dest, dest);
2547 fprintf_indent (f, indent, " }\n");
2552 /* Return the name of the operand representing the decision tree node.
2553 Use NAME as space to generate it. */
2555 char *
2556 dt_operand::get_name (char *name)
2558 if (!parent)
2559 sprintf (name, "t");
2560 else if (parent->level == 1)
2561 sprintf (name, "op%u", pos);
2562 else if (parent->type == dt_node::DT_MATCH)
2563 return parent->get_name (name);
2564 else
2565 sprintf (name, "o%u%u", parent->level, pos);
2566 return name;
2569 /* Fill NAME with the operand name at position POS. */
2571 void
2572 dt_operand::gen_opname (char *name, unsigned pos)
2574 if (!parent)
2575 sprintf (name, "op%u", pos);
2576 else
2577 sprintf (name, "o%u%u", level, pos);
2580 /* Generate matching code for the decision tree operand which is
2581 a predicate. */
2583 unsigned
2584 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2586 predicate *p = as_a <predicate *> (op);
2588 if (p->p->matchers.exists ())
2590 /* If this is a predicate generated from a pattern mangle its
2591 name and pass on the valueize hook. */
2592 if (gimple)
2593 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2594 p->p->id, opname);
2595 else
2596 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2598 else
2599 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2600 fprintf_indent (f, indent + 2, "{\n");
2601 return 1;
2604 /* Generate matching code for the decision tree operand which is
2605 a capture-match. */
2607 unsigned
2608 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2610 char match_opname[20];
2611 match_dop->get_name (match_opname);
2612 if (value_match)
2613 fprintf_indent (f, indent, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
2614 opname, match_opname, opname, match_opname);
2615 else
2616 fprintf_indent (f, indent, "if (%s == %s || (operand_equal_p (%s, %s, 0) "
2617 "&& types_match (%s, %s)))\n",
2618 opname, match_opname, opname, match_opname,
2619 opname, match_opname);
2620 fprintf_indent (f, indent + 2, "{\n");
2621 return 1;
2624 /* Generate GIMPLE matching code for the decision tree operand. */
2626 unsigned
2627 dt_operand::gen_gimple_expr (FILE *f, int indent)
2629 expr *e = static_cast<expr *> (op);
2630 id_base *id = e->operation;
2631 unsigned n_ops = e->ops.length ();
2633 for (unsigned i = 0; i < n_ops; ++i)
2635 char child_opname[20];
2636 gen_opname (child_opname, i);
2638 if (id->kind == id_base::CODE)
2640 if (e->is_generic
2641 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2642 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2644 /* ??? If this is a memory operation we can't (and should not)
2645 match this. The only sensible operand types are
2646 SSA names and invariants. */
2647 if (e->is_generic)
2649 char opname[20];
2650 get_name (opname);
2651 fprintf_indent (f, indent,
2652 "tree %s = TREE_OPERAND (%s, %i);\n",
2653 child_opname, opname, i);
2655 else
2656 fprintf_indent (f, indent,
2657 "tree %s = TREE_OPERAND "
2658 "(gimple_assign_rhs1 (def), %i);\n",
2659 child_opname, i);
2660 fprintf_indent (f, indent,
2661 "if ((TREE_CODE (%s) == SSA_NAME\n",
2662 child_opname);
2663 fprintf_indent (f, indent,
2664 " || is_gimple_min_invariant (%s))\n",
2665 child_opname);
2666 fprintf_indent (f, indent,
2667 " && (%s = do_valueize (valueize, %s)))\n",
2668 child_opname, child_opname);
2669 fprintf_indent (f, indent,
2670 " {\n");
2671 indent += 4;
2672 continue;
2674 else
2675 fprintf_indent (f, indent,
2676 "tree %s = gimple_assign_rhs%u (def);\n",
2677 child_opname, i + 1);
2679 else
2680 fprintf_indent (f, indent,
2681 "tree %s = gimple_call_arg (def, %u);\n",
2682 child_opname, i);
2683 fprintf_indent (f, indent,
2684 "if ((%s = do_valueize (valueize, %s)))\n",
2685 child_opname, child_opname);
2686 fprintf_indent (f, indent, " {\n");
2687 indent += 4;
2689 /* While the toplevel operands are canonicalized by the caller
2690 after valueizing operands of sub-expressions we have to
2691 re-canonicalize operand order. */
2692 if (operator_id *code = dyn_cast <operator_id *> (id))
2694 /* ??? We can't canonicalize tcc_comparison operands here
2695 because that requires changing the comparison code which
2696 we already matched... */
2697 if (commutative_tree_code (code->code)
2698 || commutative_ternary_tree_code (code->code))
2700 char child_opname0[20], child_opname1[20];
2701 gen_opname (child_opname0, 0);
2702 gen_opname (child_opname1, 1);
2703 fprintf_indent (f, indent,
2704 "if (tree_swap_operands_p (%s, %s))\n",
2705 child_opname0, child_opname1);
2706 fprintf_indent (f, indent,
2707 " std::swap (%s, %s);\n",
2708 child_opname0, child_opname1);
2712 return n_ops;
2715 /* Generate GENERIC matching code for the decision tree operand. */
2717 unsigned
2718 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2720 expr *e = static_cast<expr *> (op);
2721 unsigned n_ops = e->ops.length ();
2723 for (unsigned i = 0; i < n_ops; ++i)
2725 char child_opname[20];
2726 gen_opname (child_opname, i);
2728 if (e->operation->kind == id_base::CODE)
2729 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2730 child_opname, opname, i);
2731 else
2732 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2733 child_opname, opname, i);
2736 return 0;
2739 /* Generate matching code for the children of the decision tree node. */
2741 void
2742 dt_node::gen_kids (FILE *f, int indent, bool gimple)
2744 auto_vec<dt_operand *> gimple_exprs;
2745 auto_vec<dt_operand *> generic_exprs;
2746 auto_vec<dt_operand *> fns;
2747 auto_vec<dt_operand *> generic_fns;
2748 auto_vec<dt_operand *> preds;
2749 auto_vec<dt_node *> others;
2751 for (unsigned i = 0; i < kids.length (); ++i)
2753 if (kids[i]->type == dt_node::DT_OPERAND)
2755 dt_operand *op = as_a<dt_operand *> (kids[i]);
2756 if (expr *e = dyn_cast <expr *> (op->op))
2758 if (e->ops.length () == 0
2759 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2760 generic_exprs.safe_push (op);
2761 else if (e->operation->kind == id_base::FN)
2763 if (gimple)
2764 fns.safe_push (op);
2765 else
2766 generic_fns.safe_push (op);
2768 else if (e->operation->kind == id_base::PREDICATE)
2769 preds.safe_push (op);
2770 else
2772 if (gimple && !e->is_generic)
2773 gimple_exprs.safe_push (op);
2774 else
2775 generic_exprs.safe_push (op);
2778 else if (op->op->type == operand::OP_PREDICATE)
2779 others.safe_push (kids[i]);
2780 else
2781 gcc_unreachable ();
2783 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2784 others.safe_push (kids[i]);
2785 else if (kids[i]->type == dt_node::DT_MATCH
2786 || kids[i]->type == dt_node::DT_TRUE)
2788 /* A DT_TRUE operand serves as a barrier - generate code now
2789 for what we have collected sofar.
2790 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2791 dependent matches to get out-of-order. Generate code now
2792 for what we have collected sofar. */
2793 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2794 fns, generic_fns, preds, others);
2795 /* And output the true operand itself. */
2796 kids[i]->gen (f, indent, gimple);
2797 gimple_exprs.truncate (0);
2798 generic_exprs.truncate (0);
2799 fns.truncate (0);
2800 generic_fns.truncate (0);
2801 preds.truncate (0);
2802 others.truncate (0);
2804 else
2805 gcc_unreachable ();
2808 /* Generate code for the remains. */
2809 gen_kids_1 (f, indent, gimple, gimple_exprs, generic_exprs,
2810 fns, generic_fns, preds, others);
2813 /* Generate matching code for the children of the decision tree node. */
2815 void
2816 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple,
2817 vec<dt_operand *> gimple_exprs,
2818 vec<dt_operand *> generic_exprs,
2819 vec<dt_operand *> fns,
2820 vec<dt_operand *> generic_fns,
2821 vec<dt_operand *> preds,
2822 vec<dt_node *> others)
2824 char buf[128];
2825 char *kid_opname = buf;
2827 unsigned exprs_len = gimple_exprs.length ();
2828 unsigned gexprs_len = generic_exprs.length ();
2829 unsigned fns_len = fns.length ();
2830 unsigned gfns_len = generic_fns.length ();
2832 if (exprs_len || fns_len || gexprs_len || gfns_len)
2834 if (exprs_len)
2835 gimple_exprs[0]->get_name (kid_opname);
2836 else if (fns_len)
2837 fns[0]->get_name (kid_opname);
2838 else if (gfns_len)
2839 generic_fns[0]->get_name (kid_opname);
2840 else
2841 generic_exprs[0]->get_name (kid_opname);
2843 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
2844 fprintf_indent (f, indent, " {\n");
2845 indent += 2;
2848 if (exprs_len || fns_len)
2850 fprintf_indent (f, indent,
2851 "case SSA_NAME:\n");
2852 fprintf_indent (f, indent,
2853 " if (do_valueize (valueize, %s) != NULL_TREE)\n",
2854 kid_opname);
2855 fprintf_indent (f, indent,
2856 " {\n");
2857 fprintf_indent (f, indent,
2858 " gimple *def_stmt = SSA_NAME_DEF_STMT (%s);\n",
2859 kid_opname);
2861 indent += 6;
2862 if (exprs_len)
2864 fprintf_indent (f, indent,
2865 "if (gassign *def = dyn_cast <gassign *> (def_stmt))\n");
2866 fprintf_indent (f, indent,
2867 " switch (gimple_assign_rhs_code (def))\n");
2868 indent += 4;
2869 fprintf_indent (f, indent, "{\n");
2870 for (unsigned i = 0; i < exprs_len; ++i)
2872 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2873 id_base *op = e->operation;
2874 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2875 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2876 else
2877 fprintf_indent (f, indent, "case %s:\n", op->id);
2878 fprintf_indent (f, indent, " {\n");
2879 gimple_exprs[i]->gen (f, indent + 4, true);
2880 fprintf_indent (f, indent, " break;\n");
2881 fprintf_indent (f, indent, " }\n");
2883 fprintf_indent (f, indent, "default:;\n");
2884 fprintf_indent (f, indent, "}\n");
2885 indent -= 4;
2888 if (fns_len)
2890 fprintf_indent (f, indent,
2891 "%sif (gcall *def = dyn_cast <gcall *>"
2892 " (def_stmt))\n",
2893 exprs_len ? "else " : "");
2894 fprintf_indent (f, indent,
2895 " switch (gimple_call_combined_fn (def))\n");
2897 indent += 4;
2898 fprintf_indent (f, indent, "{\n");
2899 for (unsigned i = 0; i < fns_len; ++i)
2901 expr *e = as_a <expr *>(fns[i]->op);
2902 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2903 fprintf_indent (f, indent, " {\n");
2904 fns[i]->gen (f, indent + 4, true);
2905 fprintf_indent (f, indent, " break;\n");
2906 fprintf_indent (f, indent, " }\n");
2909 fprintf_indent (f, indent, "default:;\n");
2910 fprintf_indent (f, indent, "}\n");
2911 indent -= 4;
2914 indent -= 6;
2915 fprintf_indent (f, indent, " }\n");
2916 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
2917 here rather than in the next loop. */
2918 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2920 expr *e = as_a <expr *>(generic_exprs[i]->op);
2921 id_base *op = e->operation;
2922 if (*op == SSA_NAME && (exprs_len || fns_len))
2924 fprintf_indent (f, indent + 4, "{\n");
2925 generic_exprs[i]->gen (f, indent + 6, gimple);
2926 fprintf_indent (f, indent + 4, "}\n");
2930 fprintf_indent (f, indent, " break;\n");
2933 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2935 expr *e = as_a <expr *>(generic_exprs[i]->op);
2936 id_base *op = e->operation;
2937 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2938 fprintf_indent (f, indent, "CASE_CONVERT:\n");
2939 else if (*op == SSA_NAME && (exprs_len || fns_len))
2940 /* Already handled above. */
2941 continue;
2942 else
2943 fprintf_indent (f, indent, "case %s:\n", op->id);
2944 fprintf_indent (f, indent, " {\n");
2945 generic_exprs[i]->gen (f, indent + 4, gimple);
2946 fprintf_indent (f, indent, " break;\n");
2947 fprintf_indent (f, indent, " }\n");
2950 if (gfns_len)
2952 fprintf_indent (f, indent,
2953 "case CALL_EXPR:\n");
2954 fprintf_indent (f, indent,
2955 " switch (get_call_combined_fn (%s))\n",
2956 kid_opname);
2957 fprintf_indent (f, indent,
2958 " {\n");
2959 indent += 4;
2961 for (unsigned j = 0; j < generic_fns.length (); ++j)
2963 expr *e = as_a <expr *>(generic_fns[j]->op);
2964 gcc_assert (e->operation->kind == id_base::FN);
2966 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
2967 fprintf_indent (f, indent, " {\n");
2968 generic_fns[j]->gen (f, indent + 4, false);
2969 fprintf_indent (f, indent, " break;\n");
2970 fprintf_indent (f, indent, " }\n");
2972 fprintf_indent (f, indent, "default:;\n");
2974 indent -= 4;
2975 fprintf_indent (f, indent, " }\n");
2976 fprintf_indent (f, indent, " break;\n");
2979 /* Close switch (TREE_CODE ()). */
2980 if (exprs_len || fns_len || gexprs_len || gfns_len)
2982 indent -= 4;
2983 fprintf_indent (f, indent, " default:;\n");
2984 fprintf_indent (f, indent, " }\n");
2987 for (unsigned i = 0; i < preds.length (); ++i)
2989 expr *e = as_a <expr *> (preds[i]->op);
2990 predicate_id *p = as_a <predicate_id *> (e->operation);
2991 preds[i]->get_name (kid_opname);
2992 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2993 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
2994 gimple ? "gimple" : "tree",
2995 p->id, kid_opname, kid_opname,
2996 gimple ? ", valueize" : "");
2997 fprintf_indent (f, indent, " {\n");
2998 for (int j = 0; j < p->nargs; ++j)
3000 char child_opname[20];
3001 preds[i]->gen_opname (child_opname, j);
3002 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3003 child_opname, kid_opname, j);
3005 preds[i]->gen_kids (f, indent + 4, gimple);
3006 fprintf (f, "}\n");
3009 for (unsigned i = 0; i < others.length (); ++i)
3010 others[i]->gen (f, indent, gimple);
3013 /* Generate matching code for the decision tree operand. */
3015 void
3016 dt_operand::gen (FILE *f, int indent, bool gimple)
3018 char opname[20];
3019 get_name (opname);
3021 unsigned n_braces = 0;
3023 if (type == DT_OPERAND)
3024 switch (op->type)
3026 case operand::OP_PREDICATE:
3027 n_braces = gen_predicate (f, indent, opname, gimple);
3028 break;
3030 case operand::OP_EXPR:
3031 if (gimple)
3032 n_braces = gen_gimple_expr (f, indent);
3033 else
3034 n_braces = gen_generic_expr (f, indent, opname);
3035 break;
3037 default:
3038 gcc_unreachable ();
3040 else if (type == DT_TRUE)
3042 else if (type == DT_MATCH)
3043 n_braces = gen_match_op (f, indent, opname, gimple);
3044 else
3045 gcc_unreachable ();
3047 indent += 4 * n_braces;
3048 gen_kids (f, indent, gimple);
3050 for (unsigned i = 0; i < n_braces; ++i)
3052 indent -= 4;
3053 if (indent < 0)
3054 indent = 0;
3055 fprintf_indent (f, indent, " }\n");
3060 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3061 step of a '(simplify ...)' or '(match ...)'. This handles everything
3062 that is not part of the decision tree (simplify->match).
3063 Main recursive worker. */
3065 void
3066 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3068 if (result)
3070 if (with_expr *w = dyn_cast <with_expr *> (result))
3072 fprintf_indent (f, indent, "{\n");
3073 indent += 4;
3074 output_line_directive (f, w->location);
3075 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3076 gen_1 (f, indent, gimple, w->subexpr);
3077 indent -= 4;
3078 fprintf_indent (f, indent, "}\n");
3079 return;
3081 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3083 output_line_directive (f, ife->location);
3084 fprintf_indent (f, indent, "if (");
3085 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3086 fprintf (f, ")\n");
3087 fprintf_indent (f, indent + 2, "{\n");
3088 indent += 4;
3089 gen_1 (f, indent, gimple, ife->trueexpr);
3090 indent -= 4;
3091 fprintf_indent (f, indent + 2, "}\n");
3092 if (ife->falseexpr)
3094 fprintf_indent (f, indent, "else\n");
3095 fprintf_indent (f, indent + 2, "{\n");
3096 indent += 4;
3097 gen_1 (f, indent, gimple, ife->falseexpr);
3098 indent -= 4;
3099 fprintf_indent (f, indent + 2, "}\n");
3101 return;
3105 /* Analyze captures and perform early-outs on the incoming arguments
3106 that cover cases we cannot handle. */
3107 capture_info cinfo (s, result, gimple);
3108 if (s->kind == simplify::SIMPLIFY)
3110 if (!gimple)
3112 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3113 if (cinfo.force_no_side_effects & (1 << i))
3115 fprintf_indent (f, indent,
3116 "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n",
3118 if (verbose >= 1)
3119 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3120 "forcing toplevel operand to have no "
3121 "side-effects");
3123 for (int i = 0; i <= s->capture_max; ++i)
3124 if (cinfo.info[i].cse_p)
3126 else if (cinfo.info[i].force_no_side_effects_p
3127 && (cinfo.info[i].toplevel_msk
3128 & cinfo.force_no_side_effects) == 0)
3130 fprintf_indent (f, indent,
3131 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3132 "return NULL_TREE;\n", i);
3133 if (verbose >= 1)
3134 warning_at (cinfo.info[i].c->location,
3135 "forcing captured operand to have no "
3136 "side-effects");
3138 else if ((cinfo.info[i].toplevel_msk
3139 & cinfo.force_no_side_effects) != 0)
3140 /* Mark capture as having no side-effects if we had to verify
3141 that via forced toplevel operand checks. */
3142 cinfo.info[i].force_no_side_effects_p = true;
3144 if (gimple)
3146 /* Force single-use restriction by only allowing simple
3147 results via setting seq to NULL. */
3148 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3149 bool first_p = true;
3150 for (int i = 0; i <= s->capture_max; ++i)
3151 if (cinfo.info[i].force_single_use)
3153 if (first_p)
3155 fprintf_indent (f, indent, "if (lseq\n");
3156 fprintf_indent (f, indent, " && (");
3157 first_p = false;
3159 else
3161 fprintf (f, "\n");
3162 fprintf_indent (f, indent, " || ");
3164 fprintf (f, "!single_use (captures[%d])", i);
3166 if (!first_p)
3168 fprintf (f, "))\n");
3169 fprintf_indent (f, indent, " lseq = NULL;\n");
3174 fprintf_indent (f, indent, "if (dump_file && (dump_flags & TDF_DETAILS)) "
3175 "fprintf (dump_file, \"Applying pattern ");
3176 output_line_directive (f,
3177 result ? result->location : s->match->location, true);
3178 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
3180 if (!result)
3182 /* If there is no result then this is a predicate implementation. */
3183 fprintf_indent (f, indent, "return true;\n");
3185 else if (gimple)
3187 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3188 in outermost position). */
3189 if (result->type == operand::OP_EXPR
3190 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3191 result = as_a <expr *> (result)->ops[0];
3192 if (result->type == operand::OP_EXPR)
3194 expr *e = as_a <expr *> (result);
3195 id_base *opr = e->operation;
3196 bool is_predicate = false;
3197 /* When we delay operator substituting during lowering of fors we
3198 make sure that for code-gen purposes the effects of each substitute
3199 are the same. Thus just look at that. */
3200 if (user_id *uid = dyn_cast <user_id *> (opr))
3201 opr = uid->substitutes[0];
3202 else if (is_a <predicate_id *> (opr))
3203 is_predicate = true;
3204 if (!is_predicate)
3205 fprintf_indent (f, indent, "*res_code = %s;\n",
3206 *e->operation == CONVERT_EXPR
3207 ? "NOP_EXPR" : e->operation->id);
3208 for (unsigned j = 0; j < e->ops.length (); ++j)
3210 char dest[32];
3211 snprintf (dest, 32, "res_ops[%d]", j);
3212 const char *optype
3213 = get_operand_type (opr, j,
3214 "type", e->expr_type,
3215 j == 0 ? NULL : "TREE_TYPE (res_ops[0])");
3216 /* We need to expand GENERIC conditions we captured from
3217 COND_EXPRs and we need to unshare them when substituting
3218 into COND_EXPRs. */
3219 int cond_handling = 0;
3220 if (!is_predicate)
3221 cond_handling = ((*opr == COND_EXPR
3222 || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3223 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3224 &cinfo, indexes, cond_handling);
3227 /* Re-fold the toplevel result. It's basically an embedded
3228 gimple_build w/o actually building the stmt. */
3229 if (!is_predicate)
3230 fprintf_indent (f, indent,
3231 "gimple_resimplify%d (lseq, res_code, type, "
3232 "res_ops, valueize);\n", e->ops.length ());
3234 else if (result->type == operand::OP_CAPTURE
3235 || result->type == operand::OP_C_EXPR)
3237 result->gen_transform (f, indent, "res_ops[0]", true, 1, "type",
3238 &cinfo, indexes);
3239 fprintf_indent (f, indent, "*res_code = TREE_CODE (res_ops[0]);\n");
3240 if (is_a <capture *> (result)
3241 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3243 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3244 with substituting a capture of that. */
3245 fprintf_indent (f, indent,
3246 "if (COMPARISON_CLASS_P (res_ops[0]))\n");
3247 fprintf_indent (f, indent,
3248 " {\n");
3249 fprintf_indent (f, indent,
3250 " tree tem = res_ops[0];\n");
3251 fprintf_indent (f, indent,
3252 " res_ops[0] = TREE_OPERAND (tem, 0);\n");
3253 fprintf_indent (f, indent,
3254 " res_ops[1] = TREE_OPERAND (tem, 1);\n");
3255 fprintf_indent (f, indent,
3256 " }\n");
3259 else
3260 gcc_unreachable ();
3261 fprintf_indent (f, indent, "return true;\n");
3263 else /* GENERIC */
3265 bool is_predicate = false;
3266 if (result->type == operand::OP_EXPR)
3268 expr *e = as_a <expr *> (result);
3269 id_base *opr = e->operation;
3270 /* When we delay operator substituting during lowering of fors we
3271 make sure that for code-gen purposes the effects of each substitute
3272 are the same. Thus just look at that. */
3273 if (user_id *uid = dyn_cast <user_id *> (opr))
3274 opr = uid->substitutes[0];
3275 else if (is_a <predicate_id *> (opr))
3276 is_predicate = true;
3277 /* Search for captures used multiple times in the result expression
3278 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3279 original expression. */
3280 if (!is_predicate)
3281 for (int i = 0; i < s->capture_max + 1; ++i)
3283 if (cinfo.info[i].same_as != (unsigned)i
3284 || cinfo.info[i].cse_p)
3285 continue;
3286 if (cinfo.info[i].result_use_count
3287 > cinfo.info[i].match_use_count)
3288 fprintf_indent (f, indent,
3289 "if (! tree_invariant_p (captures[%d])) "
3290 "return NULL_TREE;\n", i);
3292 for (unsigned j = 0; j < e->ops.length (); ++j)
3294 char dest[32];
3295 if (is_predicate)
3296 snprintf (dest, 32, "res_ops[%d]", j);
3297 else
3299 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3300 snprintf (dest, 32, "res_op%d", j);
3302 const char *optype
3303 = get_operand_type (opr, j,
3304 "type", e->expr_type,
3305 j == 0
3306 ? NULL : "TREE_TYPE (res_op0)");
3307 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3308 &cinfo, indexes);
3310 if (is_predicate)
3311 fprintf_indent (f, indent, "return true;\n");
3312 else
3314 fprintf_indent (f, indent, "tree res;\n");
3315 /* Re-fold the toplevel result. Use non_lvalue to
3316 build NON_LVALUE_EXPRs so they get properly
3317 ignored when in GIMPLE form. */
3318 if (*opr == NON_LVALUE_EXPR)
3319 fprintf_indent (f, indent,
3320 "res = non_lvalue_loc (loc, res_op0);\n");
3321 else
3323 if (is_a <operator_id *> (opr))
3324 fprintf_indent (f, indent,
3325 "res = fold_build%d_loc (loc, %s, type",
3326 e->ops.length (),
3327 *e->operation == CONVERT_EXPR
3328 ? "NOP_EXPR" : e->operation->id);
3329 else
3330 fprintf_indent (f, indent,
3331 "res = maybe_build_call_expr_loc (loc, "
3332 "%s, type, %d", e->operation->id,
3333 e->ops.length());
3334 for (unsigned j = 0; j < e->ops.length (); ++j)
3335 fprintf (f, ", res_op%d", j);
3336 fprintf (f, ");\n");
3337 if (!is_a <operator_id *> (opr))
3339 fprintf_indent (f, indent, "if (!res)\n");
3340 fprintf_indent (f, indent, " return NULL_TREE;\n");
3345 else if (result->type == operand::OP_CAPTURE
3346 || result->type == operand::OP_C_EXPR)
3349 fprintf_indent (f, indent, "tree res;\n");
3350 result->gen_transform (f, indent, "res", false, 1, "type",
3351 &cinfo, indexes);
3353 else
3354 gcc_unreachable ();
3355 if (!is_predicate)
3357 /* Search for captures not used in the result expression and dependent
3358 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3359 for (int i = 0; i < s->capture_max + 1; ++i)
3361 if (cinfo.info[i].same_as != (unsigned)i)
3362 continue;
3363 if (!cinfo.info[i].force_no_side_effects_p
3364 && !cinfo.info[i].expr_p
3365 && cinfo.info[i].result_use_count == 0)
3367 fprintf_indent (f, indent,
3368 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3370 fprintf_indent (f, indent + 2,
3371 "res = build2_loc (loc, COMPOUND_EXPR, type, "
3372 "fold_ignored_result (captures[%d]), res);\n",
3376 fprintf_indent (f, indent, "return res;\n");
3381 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3382 step of a '(simplify ...)' or '(match ...)'. This handles everything
3383 that is not part of the decision tree (simplify->match). */
3385 void
3386 dt_simplify::gen (FILE *f, int indent, bool gimple)
3388 fprintf_indent (f, indent, "{\n");
3389 indent += 2;
3390 output_line_directive (f,
3391 s->result ? s->result->location : s->match->location);
3392 if (s->capture_max >= 0)
3394 char opname[20];
3395 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3396 s->capture_max + 1, indexes[0]->get_name (opname));
3398 for (int i = 1; i <= s->capture_max; ++i)
3400 if (!indexes[i])
3401 break;
3402 fprintf (f, ", %s", indexes[i]->get_name (opname));
3404 fprintf (f, " };\n");
3407 /* If we have a split-out function for the actual transform, call it. */
3408 if (info && info->fname)
3410 if (gimple)
3412 fprintf_indent (f, indent, "if (%s (res_code, res_ops, seq, "
3413 "valueize, type, captures", info->fname);
3414 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3415 if (s->for_subst_vec[i].first->used)
3416 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3417 fprintf (f, "))\n");
3418 fprintf_indent (f, indent, " return true;\n");
3420 else
3422 fprintf_indent (f, indent, "tree res = %s (loc, type",
3423 info->fname);
3424 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3425 fprintf (f, ", op%d", i);
3426 fprintf (f, ", captures");
3427 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3429 if (s->for_subst_vec[i].first->used)
3430 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3432 fprintf (f, ");\n");
3433 fprintf_indent (f, indent, "if (res) return res;\n");
3436 else
3438 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3440 if (! s->for_subst_vec[i].first->used)
3441 continue;
3442 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3443 fprintf_indent (f, indent, "enum tree_code %s = %s;\n",
3444 s->for_subst_vec[i].first->id,
3445 s->for_subst_vec[i].second->id);
3446 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3447 fprintf_indent (f, indent, "combined_fn %s = %s;\n",
3448 s->for_subst_vec[i].first->id,
3449 s->for_subst_vec[i].second->id);
3450 else
3451 gcc_unreachable ();
3453 gen_1 (f, indent, gimple, s->result);
3456 indent -= 2;
3457 fprintf_indent (f, indent, "}\n");
3461 /* Hash function for finding equivalent transforms. */
3463 hashval_t
3464 sinfo_hashmap_traits::hash (const key_type &v)
3466 /* Only bother to compare those originating from the same source pattern. */
3467 return v->s->result->location;
3470 /* Compare function for finding equivalent transforms. */
3472 static bool
3473 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3475 if (o1->type != o2->type)
3476 return false;
3478 switch (o1->type)
3480 case operand::OP_IF:
3482 if_expr *if1 = as_a <if_expr *> (o1);
3483 if_expr *if2 = as_a <if_expr *> (o2);
3484 /* ??? Properly compare c-exprs. */
3485 if (if1->cond != if2->cond)
3486 return false;
3487 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3488 return false;
3489 if (if1->falseexpr != if2->falseexpr
3490 || (if1->falseexpr
3491 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3492 return false;
3493 return true;
3495 case operand::OP_WITH:
3497 with_expr *with1 = as_a <with_expr *> (o1);
3498 with_expr *with2 = as_a <with_expr *> (o2);
3499 if (with1->with != with2->with)
3500 return false;
3501 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3503 default:;
3506 /* We've hit a result. Time to compare capture-infos - this is required
3507 in addition to the conservative pointer-equivalency of the result IL. */
3508 capture_info cinfo1 (s1, o1, true);
3509 capture_info cinfo2 (s2, o2, true);
3511 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3512 || cinfo1.info.length () != cinfo2.info.length ())
3513 return false;
3515 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3517 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3518 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3519 || (cinfo1.info[i].force_no_side_effects_p
3520 != cinfo2.info[i].force_no_side_effects_p)
3521 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3522 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3523 /* toplevel_msk is an optimization */
3524 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3525 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3526 /* the pointer back to the capture is for diagnostics only */)
3527 return false;
3530 /* ??? Deep-compare the actual result. */
3531 return o1 == o2;
3534 bool
3535 sinfo_hashmap_traits::equal_keys (const key_type &v,
3536 const key_type &candidate)
3538 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3542 /* Main entry to generate code for matching GIMPLE IL off the decision
3543 tree. */
3545 void
3546 decision_tree::gen (FILE *f, bool gimple)
3548 sinfo_map_t si;
3550 root->analyze (si);
3552 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3553 "a total number of %u nodes\n",
3554 gimple ? "GIMPLE" : "GENERIC",
3555 root->num_leafs, root->max_level, root->total_size);
3557 /* First split out the transform part of equal leafs. */
3558 unsigned rcnt = 0;
3559 unsigned fcnt = 1;
3560 for (sinfo_map_t::iterator iter = si.begin ();
3561 iter != si.end (); ++iter)
3563 sinfo *s = (*iter).second;
3564 /* Do not split out single uses. */
3565 if (s->cnt <= 1)
3566 continue;
3568 rcnt += s->cnt - 1;
3569 if (verbose >= 1)
3571 fprintf (stderr, "found %u uses of", s->cnt);
3572 output_line_directive (stderr, s->s->s->result->location);
3575 /* Generate a split out function with the leaf transform code. */
3576 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3577 fcnt++);
3578 if (gimple)
3579 fprintf (f, "\nstatic bool\n"
3580 "%s (code_helper *res_code, tree *res_ops,\n"
3581 " gimple_seq *seq, tree (*valueize)(tree) "
3582 "ATTRIBUTE_UNUSED,\n"
3583 " tree ARG_UNUSED (type), tree *ARG_UNUSED "
3584 "(captures)\n",
3585 s->fname);
3586 else
3588 fprintf (f, "\nstatic tree\n"
3589 "%s (location_t ARG_UNUSED (loc), tree ARG_UNUSED (type),\n",
3590 (*iter).second->fname);
3591 for (unsigned i = 0;
3592 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3593 fprintf (f, " tree ARG_UNUSED (op%d),", i);
3594 fprintf (f, " tree *captures\n");
3596 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3598 if (! s->s->s->for_subst_vec[i].first->used)
3599 continue;
3600 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3601 fprintf (f, ", enum tree_code ARG_UNUSED (%s)",
3602 s->s->s->for_subst_vec[i].first->id);
3603 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3604 fprintf (f, ", combined_fn ARG_UNUSED (%s)",
3605 s->s->s->for_subst_vec[i].first->id);
3608 fprintf (f, ")\n{\n");
3609 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3610 if (gimple)
3611 fprintf (f, " return false;\n");
3612 else
3613 fprintf (f, " return NULL_TREE;\n");
3614 fprintf (f, "}\n");
3616 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3618 for (unsigned n = 1; n <= 3; ++n)
3620 /* First generate split-out functions. */
3621 for (unsigned i = 0; i < root->kids.length (); i++)
3623 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3624 expr *e = static_cast<expr *>(dop->op);
3625 if (e->ops.length () != n
3626 /* Builtin simplifications are somewhat premature on
3627 GENERIC. The following drops patterns with outermost
3628 calls. It's easy to emit overloads for function code
3629 though if necessary. */
3630 || (!gimple
3631 && e->operation->kind != id_base::CODE))
3632 continue;
3634 if (gimple)
3635 fprintf (f, "\nstatic bool\n"
3636 "gimple_simplify_%s (code_helper *res_code, tree *res_ops,\n"
3637 " gimple_seq *seq, tree (*valueize)(tree) "
3638 "ATTRIBUTE_UNUSED,\n"
3639 " code_helper ARG_UNUSED (code), tree "
3640 "ARG_UNUSED (type)\n",
3641 e->operation->id);
3642 else
3643 fprintf (f, "\nstatic tree\n"
3644 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3645 "tree_code ARG_UNUSED (code), tree ARG_UNUSED (type)",
3646 e->operation->id);
3647 for (unsigned i = 0; i < n; ++i)
3648 fprintf (f, ", tree op%d", i);
3649 fprintf (f, ")\n");
3650 fprintf (f, "{\n");
3651 dop->gen_kids (f, 2, gimple);
3652 if (gimple)
3653 fprintf (f, " return false;\n");
3654 else
3655 fprintf (f, " return NULL_TREE;\n");
3656 fprintf (f, "}\n");
3659 /* Then generate the main entry with the outermost switch and
3660 tail-calls to the split-out functions. */
3661 if (gimple)
3662 fprintf (f, "\nstatic bool\n"
3663 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
3664 " gimple_seq *seq, tree (*valueize)(tree),\n"
3665 " code_helper code, tree type");
3666 else
3667 fprintf (f, "\ntree\n"
3668 "generic_simplify (location_t loc, enum tree_code code, "
3669 "tree type ATTRIBUTE_UNUSED");
3670 for (unsigned i = 0; i < n; ++i)
3671 fprintf (f, ", tree op%d", i);
3672 fprintf (f, ")\n");
3673 fprintf (f, "{\n");
3675 if (gimple)
3676 fprintf (f, " switch (code.get_rep())\n"
3677 " {\n");
3678 else
3679 fprintf (f, " switch (code)\n"
3680 " {\n");
3681 for (unsigned i = 0; i < root->kids.length (); i++)
3683 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3684 expr *e = static_cast<expr *>(dop->op);
3685 if (e->ops.length () != n
3686 /* Builtin simplifications are somewhat premature on
3687 GENERIC. The following drops patterns with outermost
3688 calls. It's easy to emit overloads for function code
3689 though if necessary. */
3690 || (!gimple
3691 && e->operation->kind != id_base::CODE))
3692 continue;
3694 if (*e->operation == CONVERT_EXPR
3695 || *e->operation == NOP_EXPR)
3696 fprintf (f, " CASE_CONVERT:\n");
3697 else
3698 fprintf (f, " case %s%s:\n",
3699 is_a <fn_id *> (e->operation) ? "-" : "",
3700 e->operation->id);
3701 if (gimple)
3702 fprintf (f, " return gimple_simplify_%s (res_code, res_ops, "
3703 "seq, valueize, code, type", e->operation->id);
3704 else
3705 fprintf (f, " return generic_simplify_%s (loc, code, type",
3706 e->operation->id);
3707 for (unsigned i = 0; i < n; ++i)
3708 fprintf (f, ", op%d", i);
3709 fprintf (f, ");\n");
3711 fprintf (f, " default:;\n"
3712 " }\n");
3714 if (gimple)
3715 fprintf (f, " return false;\n");
3716 else
3717 fprintf (f, " return NULL_TREE;\n");
3718 fprintf (f, "}\n");
3722 /* Output code to implement the predicate P from the decision tree DT. */
3724 void
3725 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3727 fprintf (f, "\nbool\n"
3728 "%s%s (tree t%s%s)\n"
3729 "{\n", gimple ? "gimple_" : "tree_", p->id,
3730 p->nargs > 0 ? ", tree *res_ops" : "",
3731 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3732 /* Conveniently make 'type' available. */
3733 fprintf_indent (f, 2, "tree type = TREE_TYPE (t);\n");
3735 if (!gimple)
3736 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3737 dt.root->gen_kids (f, 2, gimple);
3739 fprintf_indent (f, 2, "return false;\n"
3740 "}\n");
3743 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3745 static void
3746 write_header (FILE *f, const char *head)
3748 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3749 fprintf (f, " a IL pattern matching and simplification description. */\n");
3751 /* Include the header instead of writing it awkwardly quoted here. */
3752 fprintf (f, "\n#include \"%s\"\n", head);
3757 /* AST parsing. */
3759 class parser
3761 public:
3762 parser (cpp_reader *);
3764 private:
3765 const cpp_token *next ();
3766 const cpp_token *peek (unsigned = 1);
3767 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3768 const cpp_token *expect (enum cpp_ttype);
3769 const cpp_token *eat_token (enum cpp_ttype);
3770 const char *get_string ();
3771 const char *get_ident ();
3772 const cpp_token *eat_ident (const char *);
3773 const char *get_number ();
3775 unsigned get_internal_capture_id ();
3777 id_base *parse_operation ();
3778 operand *parse_capture (operand *, bool);
3779 operand *parse_expr ();
3780 c_expr *parse_c_expr (cpp_ttype);
3781 operand *parse_op ();
3783 void record_operlist (source_location, user_id *);
3785 void parse_pattern ();
3786 operand *parse_result (operand *, predicate_id *);
3787 void push_simplify (simplify::simplify_kind,
3788 vec<simplify *>&, operand *, operand *);
3789 void parse_simplify (simplify::simplify_kind,
3790 vec<simplify *>&, predicate_id *, operand *);
3791 void parse_for (source_location);
3792 void parse_if (source_location);
3793 void parse_predicates (source_location);
3794 void parse_operator_list (source_location);
3796 void finish_match_operand (operand *);
3798 cpp_reader *r;
3799 vec<c_expr *> active_ifs;
3800 vec<vec<user_id *> > active_fors;
3801 hash_set<user_id *> *oper_lists_set;
3802 vec<user_id *> oper_lists;
3804 cid_map_t *capture_ids;
3806 public:
3807 vec<simplify *> simplifiers;
3808 vec<predicate_id *> user_predicates;
3809 bool parsing_match_operand;
3812 /* Lexing helpers. */
3814 /* Read the next non-whitespace token from R. */
3816 const cpp_token *
3817 parser::next ()
3819 const cpp_token *token;
3822 token = cpp_get_token (r);
3824 while (token->type == CPP_PADDING
3825 && token->type != CPP_EOF);
3826 return token;
3829 /* Peek at the next non-whitespace token from R. */
3831 const cpp_token *
3832 parser::peek (unsigned num)
3834 const cpp_token *token;
3835 unsigned i = 0;
3838 token = cpp_peek_token (r, i++);
3840 while ((token->type == CPP_PADDING
3841 && token->type != CPP_EOF)
3842 || (--num > 0));
3843 /* If we peek at EOF this is a fatal error as it leaves the
3844 cpp_reader in unusable state. Assume we really wanted a
3845 token and thus this EOF is unexpected. */
3846 if (token->type == CPP_EOF)
3847 fatal_at (token, "unexpected end of file");
3848 return token;
3851 /* Peek at the next identifier token (or return NULL if the next
3852 token is not an identifier or equal to ID if supplied). */
3854 const cpp_token *
3855 parser::peek_ident (const char *id, unsigned num)
3857 const cpp_token *token = peek (num);
3858 if (token->type != CPP_NAME)
3859 return 0;
3861 if (id == 0)
3862 return token;
3864 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
3865 if (strcmp (id, t) == 0)
3866 return token;
3868 return 0;
3871 /* Read the next token from R and assert it is of type TK. */
3873 const cpp_token *
3874 parser::expect (enum cpp_ttype tk)
3876 const cpp_token *token = next ();
3877 if (token->type != tk)
3878 fatal_at (token, "expected %s, got %s",
3879 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
3881 return token;
3884 /* Consume the next token from R and assert it is of type TK. */
3886 const cpp_token *
3887 parser::eat_token (enum cpp_ttype tk)
3889 return expect (tk);
3892 /* Read the next token from R and assert it is of type CPP_STRING and
3893 return its value. */
3895 const char *
3896 parser::get_string ()
3898 const cpp_token *token = expect (CPP_STRING);
3899 return (const char *)token->val.str.text;
3902 /* Read the next token from R and assert it is of type CPP_NAME and
3903 return its value. */
3905 const char *
3906 parser::get_ident ()
3908 const cpp_token *token = expect (CPP_NAME);
3909 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
3912 /* Eat an identifier token with value S from R. */
3914 const cpp_token *
3915 parser::eat_ident (const char *s)
3917 const cpp_token *token = peek ();
3918 const char *t = get_ident ();
3919 if (strcmp (s, t) != 0)
3920 fatal_at (token, "expected '%s' got '%s'\n", s, t);
3921 return token;
3924 /* Read the next token from R and assert it is of type CPP_NUMBER and
3925 return its value. */
3927 const char *
3928 parser::get_number ()
3930 const cpp_token *token = expect (CPP_NUMBER);
3931 return (const char *)token->val.str.text;
3934 /* Return a capture ID that can be used internally. */
3936 unsigned
3937 parser::get_internal_capture_id ()
3939 unsigned newid = capture_ids->elements ();
3940 /* Big enough for a 32-bit UINT_MAX plus prefix. */
3941 char id[13];
3942 bool existed;
3943 sprintf (id, "__%u", newid);
3944 capture_ids->get_or_insert (xstrdup (id), &existed);
3945 if (existed)
3946 fatal ("reserved capture id '%s' already used", id);
3947 return newid;
3950 /* Record an operator-list use for transparent for handling. */
3952 void
3953 parser::record_operlist (source_location loc, user_id *p)
3955 if (!oper_lists_set->add (p))
3957 if (!oper_lists.is_empty ()
3958 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
3959 fatal_at (loc, "User-defined operator list does not have the "
3960 "same number of entries as others used in the pattern");
3961 oper_lists.safe_push (p);
3965 /* Parse the operator ID, special-casing convert?, convert1? and
3966 convert2? */
3968 id_base *
3969 parser::parse_operation ()
3971 const cpp_token *id_tok = peek ();
3972 const char *id = get_ident ();
3973 const cpp_token *token = peek ();
3974 if (strcmp (id, "convert0") == 0)
3975 fatal_at (id_tok, "use 'convert?' here");
3976 else if (strcmp (id, "view_convert0") == 0)
3977 fatal_at (id_tok, "use 'view_convert?' here");
3978 if (token->type == CPP_QUERY
3979 && !(token->flags & PREV_WHITE))
3981 if (strcmp (id, "convert") == 0)
3982 id = "convert0";
3983 else if (strcmp (id, "convert1") == 0)
3985 else if (strcmp (id, "convert2") == 0)
3987 else if (strcmp (id, "view_convert") == 0)
3988 id = "view_convert0";
3989 else if (strcmp (id, "view_convert1") == 0)
3991 else if (strcmp (id, "view_convert2") == 0)
3993 else
3994 fatal_at (id_tok, "non-convert operator conditionalized");
3996 if (!parsing_match_operand)
3997 fatal_at (id_tok, "conditional convert can only be used in "
3998 "match expression");
3999 eat_token (CPP_QUERY);
4001 else if (strcmp (id, "convert1") == 0
4002 || strcmp (id, "convert2") == 0
4003 || strcmp (id, "view_convert1") == 0
4004 || strcmp (id, "view_convert2") == 0)
4005 fatal_at (id_tok, "expected '?' after conditional operator");
4006 id_base *op = get_operator (id);
4007 if (!op)
4008 fatal_at (id_tok, "unknown operator %s", id);
4010 user_id *p = dyn_cast<user_id *> (op);
4011 if (p && p->is_oper_list)
4013 if (active_fors.length() == 0)
4014 record_operlist (id_tok->src_loc, p);
4015 else
4016 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
4018 return op;
4021 /* Parse a capture.
4022 capture = '@'<number> */
4024 struct operand *
4025 parser::parse_capture (operand *op, bool require_existing)
4027 source_location src_loc = eat_token (CPP_ATSIGN)->src_loc;
4028 const cpp_token *token = peek ();
4029 const char *id = NULL;
4030 bool value_match = false;
4031 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4032 if (token->type == CPP_ATSIGN
4033 && ! (token->flags & PREV_WHITE)
4034 && parsing_match_operand)
4036 eat_token (CPP_ATSIGN);
4037 token = peek ();
4038 value_match = true;
4040 if (token->type == CPP_NUMBER)
4041 id = get_number ();
4042 else if (token->type == CPP_NAME)
4043 id = get_ident ();
4044 else
4045 fatal_at (token, "expected number or identifier");
4046 unsigned next_id = capture_ids->elements ();
4047 bool existed;
4048 unsigned &num = capture_ids->get_or_insert (id, &existed);
4049 if (!existed)
4051 if (require_existing)
4052 fatal_at (src_loc, "unknown capture id");
4053 num = next_id;
4055 return new capture (src_loc, num, op, value_match);
4058 /* Parse an expression
4059 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4061 struct operand *
4062 parser::parse_expr ()
4064 const cpp_token *token = peek ();
4065 expr *e = new expr (parse_operation (), token->src_loc);
4066 token = peek ();
4067 operand *op;
4068 bool is_commutative = false;
4069 bool force_capture = false;
4070 const char *expr_type = NULL;
4072 if (token->type == CPP_COLON
4073 && !(token->flags & PREV_WHITE))
4075 eat_token (CPP_COLON);
4076 token = peek ();
4077 if (token->type == CPP_NAME
4078 && !(token->flags & PREV_WHITE))
4080 const char *s = get_ident ();
4081 if (!parsing_match_operand)
4082 expr_type = s;
4083 else
4085 const char *sp = s;
4086 while (*sp)
4088 if (*sp == 'c')
4090 if (operator_id *p
4091 = dyn_cast<operator_id *> (e->operation))
4093 if (!commutative_tree_code (p->code)
4094 && !comparison_code_p (p->code))
4095 fatal_at (token, "operation is not commutative");
4097 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4098 for (unsigned i = 0;
4099 i < p->substitutes.length (); ++i)
4101 if (operator_id *q
4102 = dyn_cast<operator_id *> (p->substitutes[i]))
4104 if (!commutative_tree_code (q->code)
4105 && !comparison_code_p (q->code))
4106 fatal_at (token, "operation %s is not "
4107 "commutative", q->id);
4110 is_commutative = true;
4112 else if (*sp == 'C')
4113 is_commutative = true;
4114 else if (*sp == 's')
4116 e->force_single_use = true;
4117 force_capture = true;
4119 else
4120 fatal_at (token, "flag %c not recognized", *sp);
4121 sp++;
4124 token = peek ();
4126 else
4127 fatal_at (token, "expected flag or type specifying identifier");
4130 if (token->type == CPP_ATSIGN
4131 && !(token->flags & PREV_WHITE))
4132 op = parse_capture (e, false);
4133 else if (force_capture)
4135 unsigned num = get_internal_capture_id ();
4136 op = new capture (token->src_loc, num, e, false);
4138 else
4139 op = e;
4142 const cpp_token *token = peek ();
4143 if (token->type == CPP_CLOSE_PAREN)
4145 if (e->operation->nargs != -1
4146 && e->operation->nargs != (int) e->ops.length ())
4147 fatal_at (token, "'%s' expects %u operands, not %u",
4148 e->operation->id, e->operation->nargs, e->ops.length ());
4149 if (is_commutative)
4151 if (e->ops.length () == 2)
4152 e->is_commutative = true;
4153 else
4154 fatal_at (token, "only binary operators or function with "
4155 "two arguments can be marked commutative");
4157 e->expr_type = expr_type;
4158 return op;
4160 else if (!(token->flags & PREV_WHITE))
4161 fatal_at (token, "expected expression operand");
4163 e->append_op (parse_op ());
4165 while (1);
4168 /* Lex native C code delimited by START recording the preprocessing tokens
4169 for later processing.
4170 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4172 c_expr *
4173 parser::parse_c_expr (cpp_ttype start)
4175 const cpp_token *token;
4176 cpp_ttype end;
4177 unsigned opencnt;
4178 vec<cpp_token> code = vNULL;
4179 unsigned nr_stmts = 0;
4180 source_location loc = eat_token (start)->src_loc;
4181 if (start == CPP_OPEN_PAREN)
4182 end = CPP_CLOSE_PAREN;
4183 else if (start == CPP_OPEN_BRACE)
4184 end = CPP_CLOSE_BRACE;
4185 else
4186 gcc_unreachable ();
4187 opencnt = 1;
4190 token = next ();
4192 /* Count brace pairs to find the end of the expr to match. */
4193 if (token->type == start)
4194 opencnt++;
4195 else if (token->type == end
4196 && --opencnt == 0)
4197 break;
4198 else if (token->type == CPP_EOF)
4199 fatal_at (token, "unexpected end of file");
4201 /* This is a lame way of counting the number of statements. */
4202 if (token->type == CPP_SEMICOLON)
4203 nr_stmts++;
4205 /* If this is possibly a user-defined identifier mark it used. */
4206 if (token->type == CPP_NAME)
4208 id_base *idb = get_operator ((const char *)CPP_HASHNODE
4209 (token->val.node.node)->ident.str);
4210 user_id *p;
4211 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4212 record_operlist (token->src_loc, p);
4215 /* Record the token. */
4216 code.safe_push (*token);
4218 while (1);
4219 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4222 /* Parse an operand which is either an expression, a predicate or
4223 a standalone capture.
4224 op = predicate | expr | c_expr | capture */
4226 struct operand *
4227 parser::parse_op ()
4229 const cpp_token *token = peek ();
4230 struct operand *op = NULL;
4231 if (token->type == CPP_OPEN_PAREN)
4233 eat_token (CPP_OPEN_PAREN);
4234 op = parse_expr ();
4235 eat_token (CPP_CLOSE_PAREN);
4237 else if (token->type == CPP_OPEN_BRACE)
4239 op = parse_c_expr (CPP_OPEN_BRACE);
4241 else
4243 /* Remaining ops are either empty or predicates */
4244 if (token->type == CPP_NAME)
4246 const char *id = get_ident ();
4247 id_base *opr = get_operator (id);
4248 if (!opr)
4249 fatal_at (token, "expected predicate name");
4250 if (operator_id *code = dyn_cast <operator_id *> (opr))
4252 if (code->nargs != 0)
4253 fatal_at (token, "using an operator with operands as predicate");
4254 /* Parse the zero-operand operator "predicates" as
4255 expression. */
4256 op = new expr (opr, token->src_loc);
4258 else if (user_id *code = dyn_cast <user_id *> (opr))
4260 if (code->nargs != 0)
4261 fatal_at (token, "using an operator with operands as predicate");
4262 /* Parse the zero-operand operator "predicates" as
4263 expression. */
4264 op = new expr (opr, token->src_loc);
4266 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4267 op = new predicate (p, token->src_loc);
4268 else
4269 fatal_at (token, "using an unsupported operator as predicate");
4270 if (!parsing_match_operand)
4271 fatal_at (token, "predicates are only allowed in match expression");
4272 token = peek ();
4273 if (token->flags & PREV_WHITE)
4274 return op;
4276 else if (token->type != CPP_COLON
4277 && token->type != CPP_ATSIGN)
4278 fatal_at (token, "expected expression or predicate");
4279 /* optionally followed by a capture and a predicate. */
4280 if (token->type == CPP_COLON)
4281 fatal_at (token, "not implemented: predicate on leaf operand");
4282 if (token->type == CPP_ATSIGN)
4283 op = parse_capture (op, !parsing_match_operand);
4286 return op;
4289 /* Create a new simplify from the current parsing state and MATCH,
4290 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4292 void
4293 parser::push_simplify (simplify::simplify_kind kind,
4294 vec<simplify *>& simplifiers,
4295 operand *match, operand *result)
4297 /* Build and push a temporary for operator list uses in expressions. */
4298 if (!oper_lists.is_empty ())
4299 active_fors.safe_push (oper_lists);
4301 simplifiers.safe_push
4302 (new simplify (kind, match, result,
4303 active_fors.copy (), capture_ids));
4305 if (!oper_lists.is_empty ())
4306 active_fors.pop ();
4309 /* Parse
4310 <result-op> = <op> | <if> | <with>
4311 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4312 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4313 and return it. */
4315 operand *
4316 parser::parse_result (operand *result, predicate_id *matcher)
4318 const cpp_token *token = peek ();
4319 if (token->type != CPP_OPEN_PAREN)
4320 return parse_op ();
4322 eat_token (CPP_OPEN_PAREN);
4323 if (peek_ident ("if"))
4325 eat_ident ("if");
4326 if_expr *ife = new if_expr (token->src_loc);
4327 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4328 if (peek ()->type == CPP_OPEN_PAREN)
4330 ife->trueexpr = parse_result (result, matcher);
4331 if (peek ()->type == CPP_OPEN_PAREN)
4332 ife->falseexpr = parse_result (result, matcher);
4333 else if (peek ()->type != CPP_CLOSE_PAREN)
4334 ife->falseexpr = parse_op ();
4336 else if (peek ()->type != CPP_CLOSE_PAREN)
4338 ife->trueexpr = parse_op ();
4339 if (peek ()->type == CPP_OPEN_PAREN)
4340 ife->falseexpr = parse_result (result, matcher);
4341 else if (peek ()->type != CPP_CLOSE_PAREN)
4342 ife->falseexpr = parse_op ();
4344 /* If this if is immediately closed then it contains a
4345 manual matcher or is part of a predicate definition. */
4346 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4348 if (!matcher)
4349 fatal_at (peek (), "manual transform not implemented");
4350 ife->trueexpr = result;
4352 eat_token (CPP_CLOSE_PAREN);
4353 return ife;
4355 else if (peek_ident ("with"))
4357 eat_ident ("with");
4358 with_expr *withe = new with_expr (token->src_loc);
4359 /* Parse (with c-expr expr) as (if-with (true) expr). */
4360 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4361 withe->with->nr_stmts = 0;
4362 withe->subexpr = parse_result (result, matcher);
4363 eat_token (CPP_CLOSE_PAREN);
4364 return withe;
4366 else if (peek_ident ("switch"))
4368 token = eat_ident ("switch");
4369 source_location ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4370 eat_ident ("if");
4371 if_expr *ife = new if_expr (ifloc);
4372 operand *res = ife;
4373 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4374 if (peek ()->type == CPP_OPEN_PAREN)
4375 ife->trueexpr = parse_result (result, matcher);
4376 else
4377 ife->trueexpr = parse_op ();
4378 eat_token (CPP_CLOSE_PAREN);
4379 if (peek ()->type != CPP_OPEN_PAREN
4380 || !peek_ident ("if", 2))
4381 fatal_at (token, "switch can be implemented with a single if");
4382 while (peek ()->type != CPP_CLOSE_PAREN)
4384 if (peek ()->type == CPP_OPEN_PAREN)
4386 if (peek_ident ("if", 2))
4388 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4389 eat_ident ("if");
4390 ife->falseexpr = new if_expr (ifloc);
4391 ife = as_a <if_expr *> (ife->falseexpr);
4392 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4393 if (peek ()->type == CPP_OPEN_PAREN)
4394 ife->trueexpr = parse_result (result, matcher);
4395 else
4396 ife->trueexpr = parse_op ();
4397 eat_token (CPP_CLOSE_PAREN);
4399 else
4401 /* switch default clause */
4402 ife->falseexpr = parse_result (result, matcher);
4403 eat_token (CPP_CLOSE_PAREN);
4404 return res;
4407 else
4409 /* switch default clause */
4410 ife->falseexpr = parse_op ();
4411 eat_token (CPP_CLOSE_PAREN);
4412 return res;
4415 eat_token (CPP_CLOSE_PAREN);
4416 return res;
4418 else
4420 operand *op = result;
4421 if (!matcher)
4422 op = parse_expr ();
4423 eat_token (CPP_CLOSE_PAREN);
4424 return op;
4428 /* Parse
4429 simplify = 'simplify' <expr> <result-op>
4431 match = 'match' <ident> <expr> [<result-op>]
4432 and fill SIMPLIFIERS with the results. */
4434 void
4435 parser::parse_simplify (simplify::simplify_kind kind,
4436 vec<simplify *>& simplifiers, predicate_id *matcher,
4437 operand *result)
4439 /* Reset the capture map. */
4440 if (!capture_ids)
4441 capture_ids = new cid_map_t;
4442 /* Reset oper_lists and set. */
4443 hash_set <user_id *> olist;
4444 oper_lists_set = &olist;
4445 oper_lists = vNULL;
4447 const cpp_token *loc = peek ();
4448 parsing_match_operand = true;
4449 struct operand *match = parse_op ();
4450 finish_match_operand (match);
4451 parsing_match_operand = false;
4452 if (match->type == operand::OP_CAPTURE && !matcher)
4453 fatal_at (loc, "outermost expression cannot be captured");
4454 if (match->type == operand::OP_EXPR
4455 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4456 fatal_at (loc, "outermost expression cannot be a predicate");
4458 /* Splice active_ifs onto result and continue parsing the
4459 "then" expr. */
4460 if_expr *active_if = NULL;
4461 for (int i = active_ifs.length (); i > 0; --i)
4463 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4464 ifc->cond = active_ifs[i-1];
4465 ifc->trueexpr = active_if;
4466 active_if = ifc;
4468 if_expr *outermost_if = active_if;
4469 while (active_if && active_if->trueexpr)
4470 active_if = as_a <if_expr *> (active_if->trueexpr);
4472 const cpp_token *token = peek ();
4474 /* If this if is immediately closed then it is part of a predicate
4475 definition. Push it. */
4476 if (token->type == CPP_CLOSE_PAREN)
4478 if (!matcher)
4479 fatal_at (token, "expected transform expression");
4480 if (active_if)
4482 active_if->trueexpr = result;
4483 result = outermost_if;
4485 push_simplify (kind, simplifiers, match, result);
4486 return;
4489 operand *tem = parse_result (result, matcher);
4490 if (active_if)
4492 active_if->trueexpr = tem;
4493 result = outermost_if;
4495 else
4496 result = tem;
4498 push_simplify (kind, simplifiers, match, result);
4501 /* Parsing of the outer control structures. */
4503 /* Parse a for expression
4504 for = '(' 'for' <subst>... <pattern> ')'
4505 subst = <ident> '(' <ident>... ')' */
4507 void
4508 parser::parse_for (source_location)
4510 auto_vec<const cpp_token *> user_id_tokens;
4511 vec<user_id *> user_ids = vNULL;
4512 const cpp_token *token;
4513 unsigned min_n_opers = 0, max_n_opers = 0;
4515 while (1)
4517 token = peek ();
4518 if (token->type != CPP_NAME)
4519 break;
4521 /* Insert the user defined operators into the operator hash. */
4522 const char *id = get_ident ();
4523 if (get_operator (id, true) != NULL)
4524 fatal_at (token, "operator already defined");
4525 user_id *op = new user_id (id);
4526 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4527 *slot = op;
4528 user_ids.safe_push (op);
4529 user_id_tokens.safe_push (token);
4531 eat_token (CPP_OPEN_PAREN);
4533 int arity = -1;
4534 while ((token = peek_ident ()) != 0)
4536 const char *oper = get_ident ();
4537 id_base *idb = get_operator (oper, true);
4538 if (idb == NULL)
4539 fatal_at (token, "no such operator '%s'", oper);
4540 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
4541 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
4542 || *idb == VIEW_CONVERT2)
4543 fatal_at (token, "conditional operators cannot be used inside for");
4545 if (arity == -1)
4546 arity = idb->nargs;
4547 else if (idb->nargs == -1)
4549 else if (idb->nargs != arity)
4550 fatal_at (token, "operator '%s' with arity %d does not match "
4551 "others with arity %d", oper, idb->nargs, arity);
4553 user_id *p = dyn_cast<user_id *> (idb);
4554 if (p)
4556 if (p->is_oper_list)
4557 op->substitutes.safe_splice (p->substitutes);
4558 else
4559 fatal_at (token, "iterator cannot be used as operator-list");
4561 else
4562 op->substitutes.safe_push (idb);
4564 op->nargs = arity;
4565 token = expect (CPP_CLOSE_PAREN);
4567 unsigned nsubstitutes = op->substitutes.length ();
4568 if (nsubstitutes == 0)
4569 fatal_at (token, "A user-defined operator must have at least "
4570 "one substitution");
4571 if (max_n_opers == 0)
4573 min_n_opers = nsubstitutes;
4574 max_n_opers = nsubstitutes;
4576 else
4578 if (nsubstitutes % min_n_opers != 0
4579 && min_n_opers % nsubstitutes != 0)
4580 fatal_at (token, "All user-defined identifiers must have a "
4581 "multiple number of operator substitutions of the "
4582 "smallest number of substitutions");
4583 if (nsubstitutes < min_n_opers)
4584 min_n_opers = nsubstitutes;
4585 else if (nsubstitutes > max_n_opers)
4586 max_n_opers = nsubstitutes;
4590 unsigned n_ids = user_ids.length ();
4591 if (n_ids == 0)
4592 fatal_at (token, "for requires at least one user-defined identifier");
4594 token = peek ();
4595 if (token->type == CPP_CLOSE_PAREN)
4596 fatal_at (token, "no pattern defined in for");
4598 active_fors.safe_push (user_ids);
4599 while (1)
4601 token = peek ();
4602 if (token->type == CPP_CLOSE_PAREN)
4603 break;
4604 parse_pattern ();
4606 active_fors.pop ();
4608 /* Remove user-defined operators from the hash again. */
4609 for (unsigned i = 0; i < user_ids.length (); ++i)
4611 if (!user_ids[i]->used)
4612 warning_at (user_id_tokens[i],
4613 "operator %s defined but not used", user_ids[i]->id);
4614 operators->remove_elt (user_ids[i]);
4618 /* Parse an identifier associated with a list of operators.
4619 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4621 void
4622 parser::parse_operator_list (source_location)
4624 const cpp_token *token = peek ();
4625 const char *id = get_ident ();
4627 if (get_operator (id, true) != 0)
4628 fatal_at (token, "operator %s already defined", id);
4630 user_id *op = new user_id (id, true);
4631 int arity = -1;
4633 while ((token = peek_ident ()) != 0)
4635 token = peek ();
4636 const char *oper = get_ident ();
4637 id_base *idb = get_operator (oper, true);
4639 if (idb == 0)
4640 fatal_at (token, "no such operator '%s'", oper);
4642 if (arity == -1)
4643 arity = idb->nargs;
4644 else if (idb->nargs == -1)
4646 else if (arity != idb->nargs)
4647 fatal_at (token, "operator '%s' with arity %d does not match "
4648 "others with arity %d", oper, idb->nargs, arity);
4650 /* We allow composition of multiple operator lists. */
4651 if (user_id *p = dyn_cast<user_id *> (idb))
4652 op->substitutes.safe_splice (p->substitutes);
4653 else
4654 op->substitutes.safe_push (idb);
4657 // Check that there is no junk after id-list
4658 token = peek();
4659 if (token->type != CPP_CLOSE_PAREN)
4660 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4662 if (op->substitutes.length () == 0)
4663 fatal_at (token, "operator-list cannot be empty");
4665 op->nargs = arity;
4666 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4667 *slot = op;
4670 /* Parse an outer if expression.
4671 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4673 void
4674 parser::parse_if (source_location)
4676 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4678 const cpp_token *token = peek ();
4679 if (token->type == CPP_CLOSE_PAREN)
4680 fatal_at (token, "no pattern defined in if");
4682 active_ifs.safe_push (ifexpr);
4683 while (1)
4685 const cpp_token *token = peek ();
4686 if (token->type == CPP_CLOSE_PAREN)
4687 break;
4689 parse_pattern ();
4691 active_ifs.pop ();
4694 /* Parse a list of predefined predicate identifiers.
4695 preds = '(' 'define_predicates' <ident>... ')' */
4697 void
4698 parser::parse_predicates (source_location)
4702 const cpp_token *token = peek ();
4703 if (token->type != CPP_NAME)
4704 break;
4706 add_predicate (get_ident ());
4708 while (1);
4711 /* Parse outer control structures.
4712 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4714 void
4715 parser::parse_pattern ()
4717 /* All clauses start with '('. */
4718 eat_token (CPP_OPEN_PAREN);
4719 const cpp_token *token = peek ();
4720 const char *id = get_ident ();
4721 if (strcmp (id, "simplify") == 0)
4723 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4724 capture_ids = NULL;
4726 else if (strcmp (id, "match") == 0)
4728 bool with_args = false;
4729 source_location e_loc = peek ()->src_loc;
4730 if (peek ()->type == CPP_OPEN_PAREN)
4732 eat_token (CPP_OPEN_PAREN);
4733 with_args = true;
4735 const char *name = get_ident ();
4736 id_base *id = get_operator (name);
4737 predicate_id *p;
4738 if (!id)
4740 p = add_predicate (name);
4741 user_predicates.safe_push (p);
4743 else if ((p = dyn_cast <predicate_id *> (id)))
4745 else
4746 fatal_at (token, "cannot add a match to a non-predicate ID");
4747 /* Parse (match <id> <arg>... (match-expr)) here. */
4748 expr *e = NULL;
4749 if (with_args)
4751 capture_ids = new cid_map_t;
4752 e = new expr (p, e_loc);
4753 while (peek ()->type == CPP_ATSIGN)
4754 e->append_op (parse_capture (NULL, false));
4755 eat_token (CPP_CLOSE_PAREN);
4757 if (p->nargs != -1
4758 && ((e && e->ops.length () != (unsigned)p->nargs)
4759 || (!e && p->nargs != 0)))
4760 fatal_at (token, "non-matching number of match operands");
4761 p->nargs = e ? e->ops.length () : 0;
4762 parse_simplify (simplify::MATCH, p->matchers, p, e);
4763 capture_ids = NULL;
4765 else if (strcmp (id, "for") == 0)
4766 parse_for (token->src_loc);
4767 else if (strcmp (id, "if") == 0)
4768 parse_if (token->src_loc);
4769 else if (strcmp (id, "define_predicates") == 0)
4771 if (active_ifs.length () > 0
4772 || active_fors.length () > 0)
4773 fatal_at (token, "define_predicates inside if or for is not supported");
4774 parse_predicates (token->src_loc);
4776 else if (strcmp (id, "define_operator_list") == 0)
4778 if (active_ifs.length () > 0
4779 || active_fors.length () > 0)
4780 fatal_at (token, "operator-list inside if or for is not supported");
4781 parse_operator_list (token->src_loc);
4783 else
4784 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4785 active_ifs.length () == 0 && active_fors.length () == 0
4786 ? "'define_predicates', " : "");
4788 eat_token (CPP_CLOSE_PAREN);
4791 /* Helper for finish_match_operand, collecting captures of OP in CPTS
4792 recursively. */
4794 static void
4795 walk_captures (operand *op, vec<vec<capture *> > cpts)
4797 if (! op)
4798 return;
4800 if (capture *c = dyn_cast <capture *> (op))
4802 cpts[c->where].safe_push (c);
4803 walk_captures (c->what, cpts);
4805 else if (expr *e = dyn_cast <expr *> (op))
4806 for (unsigned i = 0; i < e->ops.length (); ++i)
4807 walk_captures (e->ops[i], cpts);
4810 /* Finish up OP which is a match operand. */
4812 void
4813 parser::finish_match_operand (operand *op)
4815 /* Look for matching captures, diagnose mis-uses of @@ and apply
4816 early lowering and distribution of value_match. */
4817 auto_vec<vec<capture *> > cpts;
4818 cpts.safe_grow_cleared (capture_ids->elements ());
4819 walk_captures (op, cpts);
4820 for (unsigned i = 0; i < cpts.length (); ++i)
4822 capture *value_match = NULL;
4823 for (unsigned j = 0; j < cpts[i].length (); ++j)
4825 if (cpts[i][j]->value_match)
4827 if (value_match)
4828 fatal_at (cpts[i][j]->location, "duplicate @@");
4829 value_match = cpts[i][j];
4832 if (cpts[i].length () == 1 && value_match)
4833 fatal_at (value_match->location, "@@ without a matching capture");
4834 if (value_match)
4836 /* Duplicate prevailing capture with the existing ID, create
4837 a fake ID and rewrite all captures to use it. This turns
4838 @@1 into @__<newid>@1 and @1 into @__<newid>. */
4839 value_match->what = new capture (value_match->location,
4840 value_match->where,
4841 value_match->what, false);
4842 /* Create a fake ID and rewrite all captures to use it. */
4843 unsigned newid = get_internal_capture_id ();
4844 for (unsigned j = 0; j < cpts[i].length (); ++j)
4846 cpts[i][j]->where = newid;
4847 cpts[i][j]->value_match = true;
4850 cpts[i].release ();
4854 /* Main entry of the parser. Repeatedly parse outer control structures. */
4856 parser::parser (cpp_reader *r_)
4858 r = r_;
4859 active_ifs = vNULL;
4860 active_fors = vNULL;
4861 simplifiers = vNULL;
4862 oper_lists_set = NULL;
4863 oper_lists = vNULL;
4864 capture_ids = NULL;
4865 user_predicates = vNULL;
4866 parsing_match_operand = false;
4868 const cpp_token *token = next ();
4869 while (token->type != CPP_EOF)
4871 _cpp_backup_tokens (r, 1);
4872 parse_pattern ();
4873 token = next ();
4878 /* Helper for the linemap code. */
4880 static size_t
4881 round_alloc_size (size_t s)
4883 return s;
4887 /* The genmatch generator progam. It reads from a pattern description
4888 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
4891 main (int argc, char **argv)
4893 cpp_reader *r;
4895 progname = "genmatch";
4897 if (argc < 2)
4898 return 1;
4900 bool gimple = true;
4901 char *input = argv[argc-1];
4902 for (int i = 1; i < argc - 1; ++i)
4904 if (strcmp (argv[i], "--gimple") == 0)
4905 gimple = true;
4906 else if (strcmp (argv[i], "--generic") == 0)
4907 gimple = false;
4908 else if (strcmp (argv[i], "-v") == 0)
4909 verbose = 1;
4910 else if (strcmp (argv[i], "-vv") == 0)
4911 verbose = 2;
4912 else
4914 fprintf (stderr, "Usage: genmatch "
4915 "[--gimple] [--generic] [-v[v]] input\n");
4916 return 1;
4920 line_table = XCNEW (struct line_maps);
4921 linemap_init (line_table, 0);
4922 line_table->reallocator = xrealloc;
4923 line_table->round_alloc_size = round_alloc_size;
4925 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
4926 cpp_callbacks *cb = cpp_get_callbacks (r);
4927 cb->error = error_cb;
4929 /* Add the build directory to the #include "" search path. */
4930 cpp_dir *dir = XCNEW (cpp_dir);
4931 dir->name = getpwd ();
4932 if (!dir->name)
4933 dir->name = ASTRDUP (".");
4934 cpp_set_include_chains (r, dir, NULL, false);
4936 if (!cpp_read_main_file (r, input))
4937 return 1;
4938 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
4939 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
4941 null_id = new id_base (id_base::NULL_ID, "null");
4943 /* Pre-seed operators. */
4944 operators = new hash_table<id_base> (1024);
4945 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
4946 add_operator (SYM, # SYM, # TYPE, NARGS);
4947 #define END_OF_BASE_TREE_CODES
4948 #include "tree.def"
4949 add_operator (CONVERT0, "convert0", "tcc_unary", 1);
4950 add_operator (CONVERT1, "convert1", "tcc_unary", 1);
4951 add_operator (CONVERT2, "convert2", "tcc_unary", 1);
4952 add_operator (VIEW_CONVERT0, "view_convert0", "tcc_unary", 1);
4953 add_operator (VIEW_CONVERT1, "view_convert1", "tcc_unary", 1);
4954 add_operator (VIEW_CONVERT2, "view_convert2", "tcc_unary", 1);
4955 #undef END_OF_BASE_TREE_CODES
4956 #undef DEFTREECODE
4958 /* Pre-seed builtin functions.
4959 ??? Cannot use N (name) as that is targetm.emultls.get_address
4960 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
4961 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
4962 add_function (ENUM, "CFN_" # ENUM);
4963 #include "builtins.def"
4965 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
4966 add_function (IFN_##CODE, "CFN_" #CODE);
4967 #include "internal-fn.def"
4969 /* Parse ahead! */
4970 parser p (r);
4972 if (gimple)
4973 write_header (stdout, "gimple-match-head.c");
4974 else
4975 write_header (stdout, "generic-match-head.c");
4977 /* Go over all predicates defined with patterns and perform
4978 lowering and code generation. */
4979 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
4981 predicate_id *pred = p.user_predicates[i];
4982 lower (pred->matchers, gimple);
4984 if (verbose == 2)
4985 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4986 print_matches (pred->matchers[i]);
4988 decision_tree dt;
4989 for (unsigned i = 0; i < pred->matchers.length (); ++i)
4990 dt.insert (pred->matchers[i], i);
4992 if (verbose == 2)
4993 dt.print (stderr);
4995 write_predicate (stdout, pred, dt, gimple);
4998 /* Lower the main simplifiers and generate code for them. */
4999 lower (p.simplifiers, gimple);
5001 if (verbose == 2)
5002 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5003 print_matches (p.simplifiers[i]);
5005 decision_tree dt;
5006 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5007 dt.insert (p.simplifiers[i], i);
5009 if (verbose == 2)
5010 dt.print (stderr);
5012 dt.gen (stdout, gimple);
5014 /* Finalize. */
5015 cpp_finish (r, NULL);
5016 cpp_destroy (r);
5018 delete operators;
5020 return 0;