[Fortran] gfortran.texi - minor style cleanup
[gcc.git] / gcc / genmatch.c
1 /* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
3
4 Copyright (C) 2014-2020 Free Software Foundation, Inc.
5 Contributed by Richard Biener <rguenther@suse.de>
6 and Prathamesh Kulkarni <bilbotheelffriend@gmail.com>
7
8 This file is part of GCC.
9
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.
14
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.
19
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/>. */
23
24 #include "bconfig.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include <cpplib.h>
28 #include "errors.h"
29 #include "hash-table.h"
30 #include "hash-set.h"
31 #include "is-a.h"
32
33
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)
37 {
38 return NULL;
39 }
40 void ggc_free (void *)
41 {
42 }
43
44
45 /* Global state. */
46
47 /* Verboseness. 0 is quiet, 1 adds some warnings, 2 is for debugging. */
48 unsigned verbose;
49
50
51 /* libccp helpers. */
52
53 static class line_maps *line_table;
54
55 /* The rich_location class within libcpp requires a way to expand
56 location_t instances, and relies on the client code
57 providing a symbol named
58 linemap_client_expand_location_to_spelling_point
59 to do this.
60
61 This is the implementation for genmatch. */
62
63 expanded_location
64 linemap_client_expand_location_to_spelling_point (location_t loc,
65 enum location_aspect)
66 {
67 const struct line_map_ordinary *map;
68 loc = linemap_resolve_location (line_table, loc, LRK_SPELLING_LOCATION, &map);
69 return linemap_expand_location (line_table, map, loc);
70 }
71
72 static bool
73 #if GCC_VERSION >= 4001
74 __attribute__((format (printf, 5, 0)))
75 #endif
76 diagnostic_cb (cpp_reader *, enum cpp_diagnostic_level errtype,
77 enum cpp_warning_reason, rich_location *richloc,
78 const char *msg, va_list *ap)
79 {
80 const line_map_ordinary *map;
81 location_t location = richloc->get_loc ();
82 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
83 expanded_location loc = linemap_expand_location (line_table, map, location);
84 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
85 (errtype == CPP_DL_WARNING) ? "warning" : "error");
86 vfprintf (stderr, msg, *ap);
87 fprintf (stderr, "\n");
88 FILE *f = fopen (loc.file, "r");
89 if (f)
90 {
91 char buf[128];
92 while (loc.line > 0)
93 {
94 if (!fgets (buf, 128, f))
95 goto notfound;
96 if (buf[strlen (buf) - 1] != '\n')
97 {
98 if (loc.line > 1)
99 loc.line++;
100 }
101 loc.line--;
102 }
103 fprintf (stderr, "%s", buf);
104 for (int i = 0; i < loc.column - 1; ++i)
105 fputc (' ', stderr);
106 fputc ('^', stderr);
107 fputc ('\n', stderr);
108 notfound:
109 fclose (f);
110 }
111
112 if (errtype == CPP_DL_FATAL)
113 exit (1);
114 return false;
115 }
116
117 static void
118 #if GCC_VERSION >= 4001
119 __attribute__((format (printf, 2, 3)))
120 #endif
121 fatal_at (const cpp_token *tk, const char *msg, ...)
122 {
123 rich_location richloc (line_table, tk->src_loc);
124 va_list ap;
125 va_start (ap, msg);
126 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
127 va_end (ap);
128 }
129
130 static void
131 #if GCC_VERSION >= 4001
132 __attribute__((format (printf, 2, 3)))
133 #endif
134 fatal_at (location_t loc, const char *msg, ...)
135 {
136 rich_location richloc (line_table, loc);
137 va_list ap;
138 va_start (ap, msg);
139 diagnostic_cb (NULL, CPP_DL_FATAL, CPP_W_NONE, &richloc, msg, &ap);
140 va_end (ap);
141 }
142
143 static void
144 #if GCC_VERSION >= 4001
145 __attribute__((format (printf, 2, 3)))
146 #endif
147 warning_at (const cpp_token *tk, const char *msg, ...)
148 {
149 rich_location richloc (line_table, tk->src_loc);
150 va_list ap;
151 va_start (ap, msg);
152 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
153 va_end (ap);
154 }
155
156 static void
157 #if GCC_VERSION >= 4001
158 __attribute__((format (printf, 2, 3)))
159 #endif
160 warning_at (location_t loc, const char *msg, ...)
161 {
162 rich_location richloc (line_table, loc);
163 va_list ap;
164 va_start (ap, msg);
165 diagnostic_cb (NULL, CPP_DL_WARNING, CPP_W_NONE, &richloc, msg, &ap);
166 va_end (ap);
167 }
168
169 /* Like fprintf, but print INDENT spaces at the beginning. */
170
171 static void
172 #if GCC_VERSION >= 4001
173 __attribute__((format (printf, 3, 4)))
174 #endif
175 fprintf_indent (FILE *f, unsigned int indent, const char *format, ...)
176 {
177 va_list ap;
178 for (; indent >= 8; indent -= 8)
179 fputc ('\t', f);
180 fprintf (f, "%*s", indent, "");
181 va_start (ap, format);
182 vfprintf (f, format, ap);
183 va_end (ap);
184 }
185
186 static void
187 output_line_directive (FILE *f, location_t location,
188 bool dumpfile = false, bool fnargs = false)
189 {
190 const line_map_ordinary *map;
191 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
192 expanded_location loc = linemap_expand_location (line_table, map, location);
193 if (dumpfile)
194 {
195 /* When writing to a dumpfile only dump the filename. */
196 const char *file = strrchr (loc.file, DIR_SEPARATOR);
197 #if defined(DIR_SEPARATOR_2)
198 const char *pos2 = strrchr (loc.file, DIR_SEPARATOR_2);
199 if (pos2 && (!file || (pos2 > file)))
200 file = pos2;
201 #endif
202 if (!file)
203 file = loc.file;
204 else
205 ++file;
206
207 if (fnargs)
208 fprintf (f, "\"%s\", %d", file, loc.line);
209 else
210 fprintf (f, "%s:%d", file, loc.line);
211 }
212 else
213 /* Other gen programs really output line directives here, at least for
214 development it's right now more convenient to have line information
215 from the generated file. Still keep the directives as comment for now
216 to easily back-point to the meta-description. */
217 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
218 }
219
220
221 /* Pull in tree codes and builtin function codes from their
222 definition files. */
223
224 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
225 enum tree_code {
226 #include "tree.def"
227 MAX_TREE_CODES
228 };
229 #undef DEFTREECODE
230
231 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
232 enum built_in_function {
233 #include "builtins.def"
234 END_BUILTINS
235 };
236
237 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) IFN_##CODE,
238 enum internal_fn {
239 #include "internal-fn.def"
240 IFN_LAST
241 };
242
243 enum combined_fn {
244 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
245 CFN_##ENUM = int (ENUM),
246 #include "builtins.def"
247
248 #define DEF_INTERNAL_FN(CODE, FLAGS, FNSPEC) \
249 CFN_##CODE = int (END_BUILTINS) + int (IFN_##CODE),
250 #include "internal-fn.def"
251
252 CFN_LAST
253 };
254
255 #include "case-cfn-macros.h"
256
257 /* Return true if CODE represents a commutative tree code. Otherwise
258 return false. */
259 bool
260 commutative_tree_code (enum tree_code code)
261 {
262 switch (code)
263 {
264 case PLUS_EXPR:
265 case MULT_EXPR:
266 case MULT_HIGHPART_EXPR:
267 case MIN_EXPR:
268 case MAX_EXPR:
269 case BIT_IOR_EXPR:
270 case BIT_XOR_EXPR:
271 case BIT_AND_EXPR:
272 case NE_EXPR:
273 case EQ_EXPR:
274 case UNORDERED_EXPR:
275 case ORDERED_EXPR:
276 case UNEQ_EXPR:
277 case LTGT_EXPR:
278 case TRUTH_AND_EXPR:
279 case TRUTH_XOR_EXPR:
280 case TRUTH_OR_EXPR:
281 case WIDEN_MULT_EXPR:
282 case VEC_WIDEN_MULT_HI_EXPR:
283 case VEC_WIDEN_MULT_LO_EXPR:
284 case VEC_WIDEN_MULT_EVEN_EXPR:
285 case VEC_WIDEN_MULT_ODD_EXPR:
286 return true;
287
288 default:
289 break;
290 }
291 return false;
292 }
293
294 /* Return true if CODE represents a ternary tree code for which the
295 first two operands are commutative. Otherwise return false. */
296 bool
297 commutative_ternary_tree_code (enum tree_code code)
298 {
299 switch (code)
300 {
301 case WIDEN_MULT_PLUS_EXPR:
302 case WIDEN_MULT_MINUS_EXPR:
303 case DOT_PROD_EXPR:
304 return true;
305
306 default:
307 break;
308 }
309 return false;
310 }
311
312 /* Return true if CODE is a comparison. */
313
314 bool
315 comparison_code_p (enum tree_code code)
316 {
317 switch (code)
318 {
319 case EQ_EXPR:
320 case NE_EXPR:
321 case ORDERED_EXPR:
322 case UNORDERED_EXPR:
323 case LTGT_EXPR:
324 case UNEQ_EXPR:
325 case GT_EXPR:
326 case GE_EXPR:
327 case LT_EXPR:
328 case LE_EXPR:
329 case UNGT_EXPR:
330 case UNGE_EXPR:
331 case UNLT_EXPR:
332 case UNLE_EXPR:
333 return true;
334
335 default:
336 break;
337 }
338 return false;
339 }
340
341
342 /* Base class for all identifiers the parser knows. */
343
344 class id_base : public nofree_ptr_hash<id_base>
345 {
346 public:
347 enum id_kind { CODE, FN, PREDICATE, USER, NULL_ID } kind;
348
349 id_base (id_kind, const char *, int = -1);
350
351 hashval_t hashval;
352 int nargs;
353 const char *id;
354
355 /* hash_table support. */
356 static inline hashval_t hash (const id_base *);
357 static inline int equal (const id_base *, const id_base *);
358 };
359
360 inline hashval_t
361 id_base::hash (const id_base *op)
362 {
363 return op->hashval;
364 }
365
366 inline int
367 id_base::equal (const id_base *op1,
368 const id_base *op2)
369 {
370 return (op1->hashval == op2->hashval
371 && strcmp (op1->id, op2->id) == 0);
372 }
373
374 /* The special id "null", which matches nothing. */
375 static id_base *null_id;
376
377 /* Hashtable of known pattern operators. This is pre-seeded from
378 all known tree codes and all known builtin function ids. */
379 static hash_table<id_base> *operators;
380
381 id_base::id_base (id_kind kind_, const char *id_, int nargs_)
382 {
383 kind = kind_;
384 id = id_;
385 nargs = nargs_;
386 hashval = htab_hash_string (id);
387 }
388
389 /* Identifier that maps to a tree code. */
390
391 class operator_id : public id_base
392 {
393 public:
394 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
395 const char *tcc_)
396 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
397 enum tree_code code;
398 const char *tcc;
399 };
400
401 /* Identifier that maps to a builtin or internal function code. */
402
403 class fn_id : public id_base
404 {
405 public:
406 fn_id (enum built_in_function fn_, const char *id_)
407 : id_base (id_base::FN, id_), fn (fn_) {}
408 fn_id (enum internal_fn fn_, const char *id_)
409 : id_base (id_base::FN, id_), fn (int (END_BUILTINS) + int (fn_)) {}
410 unsigned int fn;
411 };
412
413 class simplify;
414
415 /* Identifier that maps to a user-defined predicate. */
416
417 class predicate_id : public id_base
418 {
419 public:
420 predicate_id (const char *id_)
421 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
422 vec<simplify *> matchers;
423 };
424
425 /* Identifier that maps to a operator defined by a 'for' directive. */
426
427 class user_id : public id_base
428 {
429 public:
430 user_id (const char *id_, bool is_oper_list_ = false)
431 : id_base (id_base::USER, id_), substitutes (vNULL),
432 used (false), is_oper_list (is_oper_list_) {}
433 vec<id_base *> substitutes;
434 bool used;
435 bool is_oper_list;
436 };
437
438 template<>
439 template<>
440 inline bool
441 is_a_helper <fn_id *>::test (id_base *id)
442 {
443 return id->kind == id_base::FN;
444 }
445
446 template<>
447 template<>
448 inline bool
449 is_a_helper <operator_id *>::test (id_base *id)
450 {
451 return id->kind == id_base::CODE;
452 }
453
454 template<>
455 template<>
456 inline bool
457 is_a_helper <predicate_id *>::test (id_base *id)
458 {
459 return id->kind == id_base::PREDICATE;
460 }
461
462 template<>
463 template<>
464 inline bool
465 is_a_helper <user_id *>::test (id_base *id)
466 {
467 return id->kind == id_base::USER;
468 }
469
470 /* If ID has a pair of consecutive, commutative operands, return the
471 index of the first, otherwise return -1. */
472
473 static int
474 commutative_op (id_base *id)
475 {
476 if (operator_id *code = dyn_cast <operator_id *> (id))
477 {
478 if (commutative_tree_code (code->code)
479 || commutative_ternary_tree_code (code->code))
480 return 0;
481 return -1;
482 }
483 if (fn_id *fn = dyn_cast <fn_id *> (id))
484 switch (fn->fn)
485 {
486 CASE_CFN_FMA:
487 case CFN_FMS:
488 case CFN_FNMA:
489 case CFN_FNMS:
490 return 0;
491
492 default:
493 return -1;
494 }
495 if (user_id *uid = dyn_cast<user_id *> (id))
496 {
497 int res = commutative_op (uid->substitutes[0]);
498 if (res < 0)
499 return 0;
500 for (unsigned i = 1; i < uid->substitutes.length (); ++i)
501 if (res != commutative_op (uid->substitutes[i]))
502 return -1;
503 return res;
504 }
505 return -1;
506 }
507
508 /* Add a predicate identifier to the hash. */
509
510 static predicate_id *
511 add_predicate (const char *id)
512 {
513 predicate_id *p = new predicate_id (id);
514 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
515 if (*slot)
516 fatal ("duplicate id definition");
517 *slot = p;
518 return p;
519 }
520
521 /* Add a tree code identifier to the hash. */
522
523 static void
524 add_operator (enum tree_code code, const char *id,
525 const char *tcc, unsigned nargs)
526 {
527 if (strcmp (tcc, "tcc_unary") != 0
528 && strcmp (tcc, "tcc_binary") != 0
529 && strcmp (tcc, "tcc_comparison") != 0
530 && strcmp (tcc, "tcc_expression") != 0
531 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
532 && strcmp (tcc, "tcc_reference") != 0
533 /* To have INTEGER_CST and friends as "predicate operators". */
534 && strcmp (tcc, "tcc_constant") != 0
535 /* And allow CONSTRUCTOR for vector initializers. */
536 && !(code == CONSTRUCTOR)
537 /* Allow SSA_NAME as predicate operator. */
538 && !(code == SSA_NAME))
539 return;
540 /* Treat ADDR_EXPR as atom, thus don't allow matching its operand. */
541 if (code == ADDR_EXPR)
542 nargs = 0;
543 operator_id *op = new operator_id (code, id, nargs, tcc);
544 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
545 if (*slot)
546 fatal ("duplicate id definition");
547 *slot = op;
548 }
549
550 /* Add a built-in or internal function identifier to the hash. ID is
551 the name of its CFN_* enumeration value. */
552
553 template <typename T>
554 static void
555 add_function (T code, const char *id)
556 {
557 fn_id *fn = new fn_id (code, id);
558 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
559 if (*slot)
560 fatal ("duplicate id definition");
561 *slot = fn;
562 }
563
564 /* Helper for easy comparing ID with tree code CODE. */
565
566 static bool
567 operator==(id_base &id, enum tree_code code)
568 {
569 if (operator_id *oid = dyn_cast <operator_id *> (&id))
570 return oid->code == code;
571 return false;
572 }
573
574 /* Lookup the identifier ID. Allow "null" if ALLOW_NULL. */
575
576 id_base *
577 get_operator (const char *id, bool allow_null = false)
578 {
579 if (allow_null && strcmp (id, "null") == 0)
580 return null_id;
581
582 id_base tem (id_base::CODE, id);
583
584 id_base *op = operators->find_with_hash (&tem, tem.hashval);
585 if (op)
586 {
587 /* If this is a user-defined identifier track whether it was used. */
588 if (user_id *uid = dyn_cast<user_id *> (op))
589 uid->used = true;
590 return op;
591 }
592
593 char *id2;
594 bool all_upper = true;
595 bool all_lower = true;
596 for (unsigned int i = 0; id[i]; ++i)
597 if (ISUPPER (id[i]))
598 all_lower = false;
599 else if (ISLOWER (id[i]))
600 all_upper = false;
601 if (all_lower)
602 {
603 /* Try in caps with _EXPR appended. */
604 id2 = ACONCAT ((id, "_EXPR", NULL));
605 for (unsigned int i = 0; id2[i]; ++i)
606 id2[i] = TOUPPER (id2[i]);
607 }
608 else if (all_upper && strncmp (id, "IFN_", 4) == 0)
609 /* Try CFN_ instead of IFN_. */
610 id2 = ACONCAT (("CFN_", id + 4, NULL));
611 else if (all_upper && strncmp (id, "BUILT_IN_", 9) == 0)
612 /* Try prepending CFN_. */
613 id2 = ACONCAT (("CFN_", id, NULL));
614 else
615 return NULL;
616
617 new (&tem) id_base (id_base::CODE, id2);
618 return operators->find_with_hash (&tem, tem.hashval);
619 }
620
621 /* Return the comparison operators that results if the operands are
622 swapped. This is safe for floating-point. */
623
624 id_base *
625 swap_tree_comparison (operator_id *p)
626 {
627 switch (p->code)
628 {
629 case EQ_EXPR:
630 case NE_EXPR:
631 case ORDERED_EXPR:
632 case UNORDERED_EXPR:
633 case LTGT_EXPR:
634 case UNEQ_EXPR:
635 return p;
636 case GT_EXPR:
637 return get_operator ("LT_EXPR");
638 case GE_EXPR:
639 return get_operator ("LE_EXPR");
640 case LT_EXPR:
641 return get_operator ("GT_EXPR");
642 case LE_EXPR:
643 return get_operator ("GE_EXPR");
644 case UNGT_EXPR:
645 return get_operator ("UNLT_EXPR");
646 case UNGE_EXPR:
647 return get_operator ("UNLE_EXPR");
648 case UNLT_EXPR:
649 return get_operator ("UNGT_EXPR");
650 case UNLE_EXPR:
651 return get_operator ("UNGE_EXPR");
652 default:
653 gcc_unreachable ();
654 }
655 }
656
657 typedef hash_map<nofree_string_hash, unsigned> cid_map_t;
658
659
660 /* The AST produced by parsing of the pattern definitions. */
661
662 class dt_operand;
663 class capture_info;
664
665 /* The base class for operands. */
666
667 class operand {
668 public:
669 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR, OP_IF, OP_WITH };
670 operand (enum op_type type_, location_t loc_)
671 : type (type_), location (loc_) {}
672 enum op_type type;
673 location_t location;
674 virtual void gen_transform (FILE *, int, const char *, bool, int,
675 const char *, capture_info *,
676 dt_operand ** = 0,
677 int = 0)
678 { gcc_unreachable (); }
679 };
680
681 /* A predicate operand. Predicates are leafs in the AST. */
682
683 class predicate : public operand
684 {
685 public:
686 predicate (predicate_id *p_, location_t loc)
687 : operand (OP_PREDICATE, loc), p (p_) {}
688 predicate_id *p;
689 };
690
691 /* An operand that constitutes an expression. Expressions include
692 function calls and user-defined predicate invocations. */
693
694 class expr : public operand
695 {
696 public:
697 expr (id_base *operation_, location_t loc, bool is_commutative_ = false)
698 : operand (OP_EXPR, loc), operation (operation_),
699 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
700 is_generic (false), force_single_use (false), opt_grp (0) {}
701 expr (expr *e)
702 : operand (OP_EXPR, e->location), operation (e->operation),
703 ops (vNULL), expr_type (e->expr_type), is_commutative (e->is_commutative),
704 is_generic (e->is_generic), force_single_use (e->force_single_use),
705 opt_grp (e->opt_grp) {}
706 void append_op (operand *op) { ops.safe_push (op); }
707 /* The operator and its operands. */
708 id_base *operation;
709 vec<operand *> ops;
710 /* An explicitely specified type - used exclusively for conversions. */
711 const char *expr_type;
712 /* Whether the operation is to be applied commutatively. This is
713 later lowered to two separate patterns. */
714 bool is_commutative;
715 /* Whether the expression is expected to be in GENERIC form. */
716 bool is_generic;
717 /* Whether pushing any stmt to the sequence should be conditional
718 on this expression having a single-use. */
719 bool force_single_use;
720 /* If non-zero, the group for optional handling. */
721 unsigned char opt_grp;
722 virtual void gen_transform (FILE *f, int, const char *, bool, int,
723 const char *, capture_info *,
724 dt_operand ** = 0, int = 0);
725 };
726
727 /* An operator that is represented by native C code. This is always
728 a leaf operand in the AST. This class is also used to represent
729 the code to be generated for 'if' and 'with' expressions. */
730
731 class c_expr : public operand
732 {
733 public:
734 /* A mapping of an identifier and its replacement. Used to apply
735 'for' lowering. */
736 class id_tab {
737 public:
738 const char *id;
739 const char *oper;
740 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
741 };
742
743 c_expr (cpp_reader *r_, location_t loc,
744 vec<cpp_token> code_, unsigned nr_stmts_,
745 vec<id_tab> ids_, cid_map_t *capture_ids_)
746 : operand (OP_C_EXPR, loc), r (r_), code (code_),
747 capture_ids (capture_ids_), nr_stmts (nr_stmts_), ids (ids_) {}
748 /* cpplib tokens and state to transform this back to source. */
749 cpp_reader *r;
750 vec<cpp_token> code;
751 cid_map_t *capture_ids;
752 /* The number of statements parsed (well, the number of ';'s). */
753 unsigned nr_stmts;
754 /* The identifier replacement vector. */
755 vec<id_tab> ids;
756 virtual void gen_transform (FILE *f, int, const char *, bool, int,
757 const char *, capture_info *,
758 dt_operand ** = 0, int = 0);
759 };
760
761 /* A wrapper around another operand that captures its value. */
762
763 class capture : public operand
764 {
765 public:
766 capture (location_t loc, unsigned where_, operand *what_, bool value_)
767 : operand (OP_CAPTURE, loc), where (where_), value_match (value_),
768 what (what_) {}
769 /* Identifier index for the value. */
770 unsigned where;
771 /* Whether in a match of two operands the compare should be for
772 equal values rather than equal atoms (boils down to a type
773 check or not). */
774 bool value_match;
775 /* The captured value. */
776 operand *what;
777 virtual void gen_transform (FILE *f, int, const char *, bool, int,
778 const char *, capture_info *,
779 dt_operand ** = 0, int = 0);
780 };
781
782 /* if expression. */
783
784 class if_expr : public operand
785 {
786 public:
787 if_expr (location_t loc)
788 : operand (OP_IF, loc), cond (NULL), trueexpr (NULL), falseexpr (NULL) {}
789 c_expr *cond;
790 operand *trueexpr;
791 operand *falseexpr;
792 };
793
794 /* with expression. */
795
796 class with_expr : public operand
797 {
798 public:
799 with_expr (location_t loc)
800 : operand (OP_WITH, loc), with (NULL), subexpr (NULL) {}
801 c_expr *with;
802 operand *subexpr;
803 };
804
805 template<>
806 template<>
807 inline bool
808 is_a_helper <capture *>::test (operand *op)
809 {
810 return op->type == operand::OP_CAPTURE;
811 }
812
813 template<>
814 template<>
815 inline bool
816 is_a_helper <predicate *>::test (operand *op)
817 {
818 return op->type == operand::OP_PREDICATE;
819 }
820
821 template<>
822 template<>
823 inline bool
824 is_a_helper <c_expr *>::test (operand *op)
825 {
826 return op->type == operand::OP_C_EXPR;
827 }
828
829 template<>
830 template<>
831 inline bool
832 is_a_helper <expr *>::test (operand *op)
833 {
834 return op->type == operand::OP_EXPR;
835 }
836
837 template<>
838 template<>
839 inline bool
840 is_a_helper <if_expr *>::test (operand *op)
841 {
842 return op->type == operand::OP_IF;
843 }
844
845 template<>
846 template<>
847 inline bool
848 is_a_helper <with_expr *>::test (operand *op)
849 {
850 return op->type == operand::OP_WITH;
851 }
852
853 /* The main class of a pattern and its transform. This is used to
854 represent both (simplify ...) and (match ...) kinds. The AST
855 duplicates all outer 'if' and 'for' expressions here so each
856 simplify can exist in isolation. */
857
858 class simplify
859 {
860 public:
861 enum simplify_kind { SIMPLIFY, MATCH };
862
863 simplify (simplify_kind kind_, unsigned id_, operand *match_,
864 operand *result_, vec<vec<user_id *> > for_vec_,
865 cid_map_t *capture_ids_)
866 : kind (kind_), id (id_), match (match_), result (result_),
867 for_vec (for_vec_), for_subst_vec (vNULL),
868 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
869
870 simplify_kind kind;
871 /* ID. This is kept to easily associate related simplifies expanded
872 from the same original one. */
873 unsigned id;
874 /* The expression that is matched against the GENERIC or GIMPLE IL. */
875 operand *match;
876 /* For a (simplify ...) an expression with ifs and withs with the expression
877 produced when the pattern applies in the leafs.
878 For a (match ...) the leafs are either empty if it is a simple predicate
879 or the single expression specifying the matched operands. */
880 class operand *result;
881 /* Collected 'for' expression operators that have to be replaced
882 in the lowering phase. */
883 vec<vec<user_id *> > for_vec;
884 vec<std::pair<user_id *, id_base *> > for_subst_vec;
885 /* A map of capture identifiers to indexes. */
886 cid_map_t *capture_ids;
887 int capture_max;
888 };
889
890 /* Debugging routines for dumping the AST. */
891
892 DEBUG_FUNCTION void
893 print_operand (operand *o, FILE *f = stderr, bool flattened = false)
894 {
895 if (capture *c = dyn_cast<capture *> (o))
896 {
897 if (c->what && flattened == false)
898 print_operand (c->what, f, flattened);
899 fprintf (f, "@%u", c->where);
900 }
901
902 else if (predicate *p = dyn_cast<predicate *> (o))
903 fprintf (f, "%s", p->p->id);
904
905 else if (is_a<c_expr *> (o))
906 fprintf (f, "c_expr");
907
908 else if (expr *e = dyn_cast<expr *> (o))
909 {
910 if (e->ops.length () == 0)
911 fprintf (f, "%s", e->operation->id);
912 else
913 {
914 fprintf (f, "(%s", e->operation->id);
915
916 if (flattened == false)
917 {
918 for (unsigned i = 0; i < e->ops.length (); ++i)
919 {
920 putc (' ', f);
921 print_operand (e->ops[i], f, flattened);
922 }
923 }
924 putc (')', f);
925 }
926 }
927
928 else
929 gcc_unreachable ();
930 }
931
932 DEBUG_FUNCTION void
933 print_matches (class simplify *s, FILE *f = stderr)
934 {
935 fprintf (f, "for expression: ");
936 print_operand (s->match, f);
937 putc ('\n', f);
938 }
939
940
941 /* AST lowering. */
942
943 /* Lowering of commutative operators. */
944
945 static void
946 cartesian_product (const vec< vec<operand *> >& ops_vector,
947 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
948 {
949 if (n == ops_vector.length ())
950 {
951 vec<operand *> xv = v.copy ();
952 result.safe_push (xv);
953 return;
954 }
955
956 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
957 {
958 v[n] = ops_vector[n][i];
959 cartesian_product (ops_vector, result, v, n + 1);
960 }
961 }
962
963 /* Lower OP to two operands in case it is marked as commutative. */
964
965 static vec<operand *>
966 commutate (operand *op, vec<vec<user_id *> > &for_vec)
967 {
968 vec<operand *> ret = vNULL;
969
970 if (capture *c = dyn_cast <capture *> (op))
971 {
972 if (!c->what)
973 {
974 ret.safe_push (op);
975 return ret;
976 }
977 vec<operand *> v = commutate (c->what, for_vec);
978 for (unsigned i = 0; i < v.length (); ++i)
979 {
980 capture *nc = new capture (c->location, c->where, v[i],
981 c->value_match);
982 ret.safe_push (nc);
983 }
984 return ret;
985 }
986
987 expr *e = dyn_cast <expr *> (op);
988 if (!e || e->ops.length () == 0)
989 {
990 ret.safe_push (op);
991 return ret;
992 }
993
994 vec< vec<operand *> > ops_vector = vNULL;
995 for (unsigned i = 0; i < e->ops.length (); ++i)
996 ops_vector.safe_push (commutate (e->ops[i], for_vec));
997
998 auto_vec< vec<operand *> > result;
999 auto_vec<operand *> v (e->ops.length ());
1000 v.quick_grow_cleared (e->ops.length ());
1001 cartesian_product (ops_vector, result, v, 0);
1002
1003
1004 for (unsigned i = 0; i < result.length (); ++i)
1005 {
1006 expr *ne = new expr (e);
1007 ne->is_commutative = false;
1008 for (unsigned j = 0; j < result[i].length (); ++j)
1009 ne->append_op (result[i][j]);
1010 ret.safe_push (ne);
1011 }
1012
1013 if (!e->is_commutative)
1014 return ret;
1015
1016 /* The operation is always binary if it isn't inherently commutative. */
1017 int natural_opno = commutative_op (e->operation);
1018 unsigned int opno = natural_opno >= 0 ? natural_opno : 0;
1019 for (unsigned i = 0; i < result.length (); ++i)
1020 {
1021 expr *ne = new expr (e);
1022 if (operator_id *r = dyn_cast <operator_id *> (ne->operation))
1023 {
1024 if (comparison_code_p (r->code))
1025 ne->operation = swap_tree_comparison (r);
1026 }
1027 else if (user_id *p = dyn_cast <user_id *> (ne->operation))
1028 {
1029 bool found_compare = false;
1030 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1031 if (operator_id *q = dyn_cast <operator_id *> (p->substitutes[j]))
1032 {
1033 if (comparison_code_p (q->code)
1034 && swap_tree_comparison (q) != q)
1035 {
1036 found_compare = true;
1037 break;
1038 }
1039 }
1040 if (found_compare)
1041 {
1042 user_id *newop = new user_id ("<internal>");
1043 for (unsigned j = 0; j < p->substitutes.length (); ++j)
1044 {
1045 id_base *subst = p->substitutes[j];
1046 if (operator_id *q = dyn_cast <operator_id *> (subst))
1047 {
1048 if (comparison_code_p (q->code))
1049 subst = swap_tree_comparison (q);
1050 }
1051 newop->substitutes.safe_push (subst);
1052 }
1053 ne->operation = newop;
1054 /* Search for 'p' inside the for vector and push 'newop'
1055 to the same level. */
1056 for (unsigned j = 0; newop && j < for_vec.length (); ++j)
1057 for (unsigned k = 0; k < for_vec[j].length (); ++k)
1058 if (for_vec[j][k] == p)
1059 {
1060 for_vec[j].safe_push (newop);
1061 newop = NULL;
1062 break;
1063 }
1064 }
1065 }
1066 ne->is_commutative = false;
1067 for (unsigned j = 0; j < result[i].length (); ++j)
1068 {
1069 int old_j = (j == opno ? opno + 1 : j == opno + 1 ? opno : j);
1070 ne->append_op (result[i][old_j]);
1071 }
1072 ret.safe_push (ne);
1073 }
1074
1075 return ret;
1076 }
1077
1078 /* Lower operations marked as commutative in the AST of S and push
1079 the resulting patterns to SIMPLIFIERS. */
1080
1081 static void
1082 lower_commutative (simplify *s, vec<simplify *>& simplifiers)
1083 {
1084 vec<operand *> matchers = commutate (s->match, s->for_vec);
1085 for (unsigned i = 0; i < matchers.length (); ++i)
1086 {
1087 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1088 s->for_vec, s->capture_ids);
1089 simplifiers.safe_push (ns);
1090 }
1091 }
1092
1093 /* Strip conditional operations using group GRP from O and its
1094 children if STRIP, else replace them with an unconditional operation. */
1095
1096 operand *
1097 lower_opt (operand *o, unsigned char grp, bool strip)
1098 {
1099 if (capture *c = dyn_cast<capture *> (o))
1100 {
1101 if (c->what)
1102 return new capture (c->location, c->where,
1103 lower_opt (c->what, grp, strip),
1104 c->value_match);
1105 else
1106 return c;
1107 }
1108
1109 expr *e = dyn_cast<expr *> (o);
1110 if (!e)
1111 return o;
1112
1113 if (e->opt_grp == grp)
1114 {
1115 if (strip)
1116 return lower_opt (e->ops[0], grp, strip);
1117
1118 expr *ne = new expr (e);
1119 ne->opt_grp = 0;
1120 ne->append_op (lower_opt (e->ops[0], grp, strip));
1121 return ne;
1122 }
1123
1124 expr *ne = new expr (e);
1125 for (unsigned i = 0; i < e->ops.length (); ++i)
1126 ne->append_op (lower_opt (e->ops[i], grp, strip));
1127
1128 return ne;
1129 }
1130
1131 /* Determine whether O or its children uses the conditional operation
1132 group GRP. */
1133
1134 static bool
1135 has_opt (operand *o, unsigned char grp)
1136 {
1137 if (capture *c = dyn_cast<capture *> (o))
1138 {
1139 if (c->what)
1140 return has_opt (c->what, grp);
1141 else
1142 return false;
1143 }
1144
1145 expr *e = dyn_cast<expr *> (o);
1146 if (!e)
1147 return false;
1148
1149 if (e->opt_grp == grp)
1150 return true;
1151
1152 for (unsigned i = 0; i < e->ops.length (); ++i)
1153 if (has_opt (e->ops[i], grp))
1154 return true;
1155
1156 return false;
1157 }
1158
1159 /* Lower conditional convert operators in O, expanding it to a vector
1160 if required. */
1161
1162 static vec<operand *>
1163 lower_opt (operand *o)
1164 {
1165 vec<operand *> v1 = vNULL, v2;
1166
1167 v1.safe_push (o);
1168
1169 /* Conditional operations are lowered to a pattern with the
1170 operation and one without. All different conditional operation
1171 groups are lowered separately. */
1172
1173 for (unsigned i = 1; i <= 10; ++i)
1174 {
1175 v2 = vNULL;
1176 for (unsigned j = 0; j < v1.length (); ++j)
1177 if (has_opt (v1[j], i))
1178 {
1179 v2.safe_push (lower_opt (v1[j], i, false));
1180 v2.safe_push (lower_opt (v1[j], i, true));
1181 }
1182
1183 if (v2 != vNULL)
1184 {
1185 v1 = vNULL;
1186 for (unsigned j = 0; j < v2.length (); ++j)
1187 v1.safe_push (v2[j]);
1188 }
1189 }
1190
1191 return v1;
1192 }
1193
1194 /* Lower conditional convert operators in the AST of S and push
1195 the resulting multiple patterns to SIMPLIFIERS. */
1196
1197 static void
1198 lower_opt (simplify *s, vec<simplify *>& simplifiers)
1199 {
1200 vec<operand *> matchers = lower_opt (s->match);
1201 for (unsigned i = 0; i < matchers.length (); ++i)
1202 {
1203 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1204 s->for_vec, s->capture_ids);
1205 simplifiers.safe_push (ns);
1206 }
1207 }
1208
1209 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1210 GENERIC and a GIMPLE variant. */
1211
1212 static vec<operand *>
1213 lower_cond (operand *o)
1214 {
1215 vec<operand *> ro = vNULL;
1216
1217 if (capture *c = dyn_cast<capture *> (o))
1218 {
1219 if (c->what)
1220 {
1221 vec<operand *> lop = vNULL;
1222 lop = lower_cond (c->what);
1223
1224 for (unsigned i = 0; i < lop.length (); ++i)
1225 ro.safe_push (new capture (c->location, c->where, lop[i],
1226 c->value_match));
1227 return ro;
1228 }
1229 }
1230
1231 expr *e = dyn_cast<expr *> (o);
1232 if (!e || e->ops.length () == 0)
1233 {
1234 ro.safe_push (o);
1235 return ro;
1236 }
1237
1238 vec< vec<operand *> > ops_vector = vNULL;
1239 for (unsigned i = 0; i < e->ops.length (); ++i)
1240 ops_vector.safe_push (lower_cond (e->ops[i]));
1241
1242 auto_vec< vec<operand *> > result;
1243 auto_vec<operand *> v (e->ops.length ());
1244 v.quick_grow_cleared (e->ops.length ());
1245 cartesian_product (ops_vector, result, v, 0);
1246
1247 for (unsigned i = 0; i < result.length (); ++i)
1248 {
1249 expr *ne = new expr (e);
1250 for (unsigned j = 0; j < result[i].length (); ++j)
1251 ne->append_op (result[i][j]);
1252 ro.safe_push (ne);
1253 /* If this is a COND with a captured expression or an
1254 expression with two operands then also match a GENERIC
1255 form on the compare. */
1256 if ((*e->operation == COND_EXPR
1257 || *e->operation == VEC_COND_EXPR)
1258 && ((is_a <capture *> (e->ops[0])
1259 && as_a <capture *> (e->ops[0])->what
1260 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
1261 && as_a <expr *>
1262 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
1263 || (is_a <expr *> (e->ops[0])
1264 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
1265 {
1266 ne = new expr (e);
1267 for (unsigned j = 0; j < result[i].length (); ++j)
1268 ne->append_op (result[i][j]);
1269 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
1270 {
1271 expr *ocmp = as_a <expr *> (c->what);
1272 expr *cmp = new expr (ocmp);
1273 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1274 cmp->append_op (ocmp->ops[j]);
1275 cmp->is_generic = true;
1276 ne->ops[0] = new capture (c->location, c->where, cmp,
1277 c->value_match);
1278 }
1279 else
1280 {
1281 expr *ocmp = as_a <expr *> (ne->ops[0]);
1282 expr *cmp = new expr (ocmp);
1283 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
1284 cmp->append_op (ocmp->ops[j]);
1285 cmp->is_generic = true;
1286 ne->ops[0] = cmp;
1287 }
1288 ro.safe_push (ne);
1289 }
1290 }
1291
1292 return ro;
1293 }
1294
1295 /* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
1296 GENERIC and a GIMPLE variant. */
1297
1298 static void
1299 lower_cond (simplify *s, vec<simplify *>& simplifiers)
1300 {
1301 vec<operand *> matchers = lower_cond (s->match);
1302 for (unsigned i = 0; i < matchers.length (); ++i)
1303 {
1304 simplify *ns = new simplify (s->kind, s->id, matchers[i], s->result,
1305 s->for_vec, s->capture_ids);
1306 simplifiers.safe_push (ns);
1307 }
1308 }
1309
1310 /* Return true if O refers to ID. */
1311
1312 bool
1313 contains_id (operand *o, user_id *id)
1314 {
1315 if (capture *c = dyn_cast<capture *> (o))
1316 return c->what && contains_id (c->what, id);
1317
1318 if (expr *e = dyn_cast<expr *> (o))
1319 {
1320 if (e->operation == id)
1321 return true;
1322 for (unsigned i = 0; i < e->ops.length (); ++i)
1323 if (contains_id (e->ops[i], id))
1324 return true;
1325 return false;
1326 }
1327
1328 if (with_expr *w = dyn_cast <with_expr *> (o))
1329 return (contains_id (w->with, id)
1330 || contains_id (w->subexpr, id));
1331
1332 if (if_expr *ife = dyn_cast <if_expr *> (o))
1333 return (contains_id (ife->cond, id)
1334 || contains_id (ife->trueexpr, id)
1335 || (ife->falseexpr && contains_id (ife->falseexpr, id)));
1336
1337 if (c_expr *ce = dyn_cast<c_expr *> (o))
1338 return ce->capture_ids && ce->capture_ids->get (id->id);
1339
1340 return false;
1341 }
1342
1343
1344 /* In AST operand O replace operator ID with operator WITH. */
1345
1346 operand *
1347 replace_id (operand *o, user_id *id, id_base *with)
1348 {
1349 /* Deep-copy captures and expressions, replacing operations as
1350 needed. */
1351 if (capture *c = dyn_cast<capture *> (o))
1352 {
1353 if (!c->what)
1354 return c;
1355 return new capture (c->location, c->where,
1356 replace_id (c->what, id, with), c->value_match);
1357 }
1358 else if (expr *e = dyn_cast<expr *> (o))
1359 {
1360 expr *ne = new expr (e);
1361 if (e->operation == id)
1362 ne->operation = with;
1363 for (unsigned i = 0; i < e->ops.length (); ++i)
1364 ne->append_op (replace_id (e->ops[i], id, with));
1365 return ne;
1366 }
1367 else if (with_expr *w = dyn_cast <with_expr *> (o))
1368 {
1369 with_expr *nw = new with_expr (w->location);
1370 nw->with = as_a <c_expr *> (replace_id (w->with, id, with));
1371 nw->subexpr = replace_id (w->subexpr, id, with);
1372 return nw;
1373 }
1374 else if (if_expr *ife = dyn_cast <if_expr *> (o))
1375 {
1376 if_expr *nife = new if_expr (ife->location);
1377 nife->cond = as_a <c_expr *> (replace_id (ife->cond, id, with));
1378 nife->trueexpr = replace_id (ife->trueexpr, id, with);
1379 if (ife->falseexpr)
1380 nife->falseexpr = replace_id (ife->falseexpr, id, with);
1381 return nife;
1382 }
1383
1384 /* For c_expr we simply record a string replacement table which is
1385 applied at code-generation time. */
1386 if (c_expr *ce = dyn_cast<c_expr *> (o))
1387 {
1388 vec<c_expr::id_tab> ids = ce->ids.copy ();
1389 ids.safe_push (c_expr::id_tab (id->id, with->id));
1390 return new c_expr (ce->r, ce->location,
1391 ce->code, ce->nr_stmts, ids, ce->capture_ids);
1392 }
1393
1394 return o;
1395 }
1396
1397 /* Return true if the binary operator OP is ok for delayed substitution
1398 during for lowering. */
1399
1400 static bool
1401 binary_ok (operator_id *op)
1402 {
1403 switch (op->code)
1404 {
1405 case PLUS_EXPR:
1406 case MINUS_EXPR:
1407 case MULT_EXPR:
1408 case TRUNC_DIV_EXPR:
1409 case CEIL_DIV_EXPR:
1410 case FLOOR_DIV_EXPR:
1411 case ROUND_DIV_EXPR:
1412 case TRUNC_MOD_EXPR:
1413 case CEIL_MOD_EXPR:
1414 case FLOOR_MOD_EXPR:
1415 case ROUND_MOD_EXPR:
1416 case RDIV_EXPR:
1417 case EXACT_DIV_EXPR:
1418 case MIN_EXPR:
1419 case MAX_EXPR:
1420 case BIT_IOR_EXPR:
1421 case BIT_XOR_EXPR:
1422 case BIT_AND_EXPR:
1423 return true;
1424 default:
1425 return false;
1426 }
1427 }
1428
1429 /* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1430
1431 static void
1432 lower_for (simplify *sin, vec<simplify *>& simplifiers)
1433 {
1434 vec<vec<user_id *> >& for_vec = sin->for_vec;
1435 unsigned worklist_start = 0;
1436 auto_vec<simplify *> worklist;
1437 worklist.safe_push (sin);
1438
1439 /* Lower each recorded for separately, operating on the
1440 set of simplifiers created by the previous one.
1441 Lower inner-to-outer so inner for substitutes can refer
1442 to operators replaced by outer fors. */
1443 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1444 {
1445 vec<user_id *>& ids = for_vec[fi];
1446 unsigned n_ids = ids.length ();
1447 unsigned max_n_opers = 0;
1448 bool can_delay_subst = (sin->kind == simplify::SIMPLIFY);
1449 for (unsigned i = 0; i < n_ids; ++i)
1450 {
1451 if (ids[i]->substitutes.length () > max_n_opers)
1452 max_n_opers = ids[i]->substitutes.length ();
1453 /* Require that all substitutes are of the same kind so that
1454 if we delay substitution to the result op code generation
1455 can look at the first substitute for deciding things like
1456 types of operands. */
1457 enum id_base::id_kind kind = ids[i]->substitutes[0]->kind;
1458 for (unsigned j = 0; j < ids[i]->substitutes.length (); ++j)
1459 if (ids[i]->substitutes[j]->kind != kind)
1460 can_delay_subst = false;
1461 else if (operator_id *op
1462 = dyn_cast <operator_id *> (ids[i]->substitutes[j]))
1463 {
1464 operator_id *op0
1465 = as_a <operator_id *> (ids[i]->substitutes[0]);
1466 if (strcmp (op->tcc, "tcc_comparison") == 0
1467 && strcmp (op0->tcc, "tcc_comparison") == 0)
1468 ;
1469 /* Unfortunately we can't just allow all tcc_binary. */
1470 else if (strcmp (op->tcc, "tcc_binary") == 0
1471 && strcmp (op0->tcc, "tcc_binary") == 0
1472 && binary_ok (op)
1473 && binary_ok (op0))
1474 ;
1475 else if ((strcmp (op->id + 1, "SHIFT_EXPR") == 0
1476 || strcmp (op->id + 1, "ROTATE_EXPR") == 0)
1477 && (strcmp (op0->id + 1, "SHIFT_EXPR") == 0
1478 || strcmp (op0->id + 1, "ROTATE_EXPR") == 0))
1479 ;
1480 else
1481 can_delay_subst = false;
1482 }
1483 else if (is_a <fn_id *> (ids[i]->substitutes[j]))
1484 ;
1485 else
1486 can_delay_subst = false;
1487 }
1488
1489 unsigned worklist_end = worklist.length ();
1490 for (unsigned si = worklist_start; si < worklist_end; ++si)
1491 {
1492 simplify *s = worklist[si];
1493 for (unsigned j = 0; j < max_n_opers; ++j)
1494 {
1495 operand *match_op = s->match;
1496 operand *result_op = s->result;
1497 auto_vec<std::pair<user_id *, id_base *> > subst (n_ids);
1498 bool skip = false;
1499 for (unsigned i = 0; i < n_ids; ++i)
1500 {
1501 user_id *id = ids[i];
1502 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1503 if (oper == null_id
1504 && (contains_id (match_op, id)
1505 || contains_id (result_op, id)))
1506 {
1507 skip = true;
1508 break;
1509 }
1510 subst.quick_push (std::make_pair (id, oper));
1511 match_op = replace_id (match_op, id, oper);
1512 if (result_op
1513 && !can_delay_subst)
1514 result_op = replace_id (result_op, id, oper);
1515 }
1516 if (skip)
1517 continue;
1518
1519 simplify *ns = new simplify (s->kind, s->id, match_op, result_op,
1520 vNULL, s->capture_ids);
1521 ns->for_subst_vec.safe_splice (s->for_subst_vec);
1522 if (result_op
1523 && can_delay_subst)
1524 ns->for_subst_vec.safe_splice (subst);
1525
1526 worklist.safe_push (ns);
1527 }
1528 }
1529 worklist_start = worklist_end;
1530 }
1531
1532 /* Copy out the result from the last for lowering. */
1533 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1534 simplifiers.safe_push (worklist[i]);
1535 }
1536
1537 /* Lower the AST for everything in SIMPLIFIERS. */
1538
1539 static void
1540 lower (vec<simplify *>& simplifiers, bool gimple)
1541 {
1542 auto_vec<simplify *> out_simplifiers;
1543 for (unsigned i = 0; i < simplifiers.length (); ++i)
1544 lower_opt (simplifiers[i], out_simplifiers);
1545
1546 simplifiers.truncate (0);
1547 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1548 lower_commutative (out_simplifiers[i], simplifiers);
1549
1550 out_simplifiers.truncate (0);
1551 if (gimple)
1552 for (unsigned i = 0; i < simplifiers.length (); ++i)
1553 lower_cond (simplifiers[i], out_simplifiers);
1554 else
1555 out_simplifiers.safe_splice (simplifiers);
1556
1557
1558 simplifiers.truncate (0);
1559 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1560 lower_for (out_simplifiers[i], simplifiers);
1561 }
1562
1563
1564
1565
1566 /* The decision tree built for generating GIMPLE and GENERIC pattern
1567 matching code. It represents the 'match' expression of all
1568 simplifies and has those as its leafs. */
1569
1570 class dt_simplify;
1571
1572 /* A hash-map collecting semantically equivalent leafs in the decision
1573 tree for splitting out to separate functions. */
1574 struct sinfo
1575 {
1576 dt_simplify *s;
1577
1578 const char *fname;
1579 unsigned cnt;
1580 };
1581
1582 struct sinfo_hashmap_traits : simple_hashmap_traits<pointer_hash<dt_simplify>,
1583 sinfo *>
1584 {
1585 static inline hashval_t hash (const key_type &);
1586 static inline bool equal_keys (const key_type &, const key_type &);
1587 template <typename T> static inline void remove (T &) {}
1588 };
1589
1590 typedef hash_map<void * /* unused */, sinfo *, sinfo_hashmap_traits>
1591 sinfo_map_t;
1592
1593 /* Current simplifier ID we are processing during insertion into the
1594 decision tree. */
1595 static unsigned current_id;
1596
1597 /* Decision tree base class, used for DT_NODE. */
1598
1599 class dt_node
1600 {
1601 public:
1602 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1603
1604 enum dt_type type;
1605 unsigned level;
1606 dt_node *parent;
1607 vec<dt_node *> kids;
1608
1609 /* Statistics. */
1610 unsigned num_leafs;
1611 unsigned total_size;
1612 unsigned max_level;
1613
1614 dt_node (enum dt_type type_, dt_node *parent_)
1615 : type (type_), level (0), parent (parent_), kids (vNULL) {}
1616
1617 dt_node *append_node (dt_node *);
1618 dt_node *append_op (operand *, dt_node *parent, unsigned pos);
1619 dt_node *append_true_op (operand *, dt_node *parent, unsigned pos);
1620 dt_node *append_match_op (operand *, dt_operand *, dt_node *parent,
1621 unsigned pos);
1622 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1623
1624 virtual void gen (FILE *, int, bool, int) {}
1625
1626 void gen_kids (FILE *, int, bool, int);
1627 void gen_kids_1 (FILE *, int, bool, int,
1628 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1629 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
1630
1631 void analyze (sinfo_map_t &);
1632 };
1633
1634 /* Generic decision tree node used for DT_OPERAND, DT_MATCH and DT_TRUE. */
1635
1636 class dt_operand : public dt_node
1637 {
1638 public:
1639 operand *op;
1640 dt_operand *match_dop;
1641 unsigned pos;
1642 bool value_match;
1643 unsigned for_id;
1644
1645 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1646 dt_operand *parent_, unsigned pos_)
1647 : dt_node (type, parent_), op (op_), match_dop (match_dop_),
1648 pos (pos_), value_match (false), for_id (current_id) {}
1649
1650 void gen (FILE *, int, bool, int);
1651 unsigned gen_predicate (FILE *, int, const char *, bool);
1652 unsigned gen_match_op (FILE *, int, const char *, bool);
1653
1654 unsigned gen_gimple_expr (FILE *, int, int);
1655 unsigned gen_generic_expr (FILE *, int, const char *);
1656
1657 char *get_name (char *);
1658 void gen_opname (char *, unsigned);
1659 };
1660
1661 /* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1662
1663 class dt_simplify : public dt_node
1664 {
1665 public:
1666 simplify *s;
1667 unsigned pattern_no;
1668 dt_operand **indexes;
1669 sinfo *info;
1670
1671 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1672 : dt_node (DT_SIMPLIFY, NULL), s (s_), pattern_no (pattern_no_),
1673 indexes (indexes_), info (NULL) {}
1674
1675 void gen_1 (FILE *, int, bool, operand *);
1676 void gen (FILE *f, int, bool, int);
1677 };
1678
1679 template<>
1680 template<>
1681 inline bool
1682 is_a_helper <dt_operand *>::test (dt_node *n)
1683 {
1684 return (n->type == dt_node::DT_OPERAND
1685 || n->type == dt_node::DT_MATCH
1686 || n->type == dt_node::DT_TRUE);
1687 }
1688
1689 template<>
1690 template<>
1691 inline bool
1692 is_a_helper <dt_simplify *>::test (dt_node *n)
1693 {
1694 return n->type == dt_node::DT_SIMPLIFY;
1695 }
1696
1697
1698
1699 /* A container for the actual decision tree. */
1700
1701 class decision_tree
1702 {
1703 public:
1704 dt_node *root;
1705
1706 void insert (class simplify *, unsigned);
1707 void gen (FILE *f, bool gimple);
1708 void print (FILE *f = stderr);
1709
1710 decision_tree () { root = new dt_node (dt_node::DT_NODE, NULL); }
1711
1712 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1713 unsigned pos = 0, dt_node *parent = 0);
1714 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1715 static bool cmp_node (dt_node *, dt_node *);
1716 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1717 };
1718
1719 /* Compare two AST operands O1 and O2 and return true if they are equal. */
1720
1721 bool
1722 cmp_operand (operand *o1, operand *o2)
1723 {
1724 if (!o1 || !o2 || o1->type != o2->type)
1725 return false;
1726
1727 if (o1->type == operand::OP_PREDICATE)
1728 {
1729 predicate *p1 = as_a<predicate *>(o1);
1730 predicate *p2 = as_a<predicate *>(o2);
1731 return p1->p == p2->p;
1732 }
1733 else if (o1->type == operand::OP_EXPR)
1734 {
1735 expr *e1 = static_cast<expr *>(o1);
1736 expr *e2 = static_cast<expr *>(o2);
1737 return (e1->operation == e2->operation
1738 && e1->is_generic == e2->is_generic);
1739 }
1740 else
1741 return false;
1742 }
1743
1744 /* Compare two decision tree nodes N1 and N2 and return true if they
1745 are equal. */
1746
1747 bool
1748 decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1749 {
1750 if (!n1 || !n2 || n1->type != n2->type)
1751 return false;
1752
1753 if (n1 == n2)
1754 return true;
1755
1756 if (n1->type == dt_node::DT_TRUE)
1757 return false;
1758
1759 if (n1->type == dt_node::DT_OPERAND)
1760 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1761 (as_a<dt_operand *> (n2))->op);
1762 else if (n1->type == dt_node::DT_MATCH)
1763 return (((as_a<dt_operand *> (n1))->match_dop
1764 == (as_a<dt_operand *> (n2))->match_dop)
1765 && ((as_a<dt_operand *> (n1))->value_match
1766 == (as_a<dt_operand *> (n2))->value_match));
1767 return false;
1768 }
1769
1770 /* Search OPS for a decision tree node like P and return it if found. */
1771
1772 dt_node *
1773 decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1774 {
1775 /* We can merge adjacent DT_TRUE. */
1776 if (p->type == dt_node::DT_TRUE
1777 && !ops.is_empty ()
1778 && ops.last ()->type == dt_node::DT_TRUE)
1779 return ops.last ();
1780 dt_operand *true_node = NULL;
1781 for (int i = ops.length () - 1; i >= 0; --i)
1782 {
1783 /* But we can't merge across DT_TRUE nodes as they serve as
1784 pattern order barriers to make sure that patterns apply
1785 in order of appearance in case multiple matches are possible. */
1786 if (ops[i]->type == dt_node::DT_TRUE)
1787 {
1788 if (! true_node
1789 || as_a <dt_operand *> (ops[i])->for_id > true_node->for_id)
1790 true_node = as_a <dt_operand *> (ops[i]);
1791 }
1792 if (decision_tree::cmp_node (ops[i], p))
1793 {
1794 /* Unless we are processing the same pattern or the blocking
1795 pattern is before the one we are going to merge with. */
1796 if (true_node
1797 && true_node->for_id != current_id
1798 && true_node->for_id > as_a <dt_operand *> (ops[i])->for_id)
1799 {
1800 if (verbose >= 1)
1801 {
1802 location_t p_loc = 0;
1803 if (p->type == dt_node::DT_OPERAND)
1804 p_loc = as_a <dt_operand *> (p)->op->location;
1805 location_t op_loc = 0;
1806 if (ops[i]->type == dt_node::DT_OPERAND)
1807 op_loc = as_a <dt_operand *> (ops[i])->op->location;
1808 location_t true_loc = 0;
1809 true_loc = true_node->op->location;
1810 warning_at (p_loc,
1811 "failed to merge decision tree node");
1812 warning_at (op_loc,
1813 "with the following");
1814 warning_at (true_loc,
1815 "because of the following which serves as ordering "
1816 "barrier");
1817 }
1818 return NULL;
1819 }
1820 return ops[i];
1821 }
1822 }
1823 return NULL;
1824 }
1825
1826 /* Append N to the decision tree if it there is not already an existing
1827 identical child. */
1828
1829 dt_node *
1830 dt_node::append_node (dt_node *n)
1831 {
1832 dt_node *kid;
1833
1834 kid = decision_tree::find_node (kids, n);
1835 if (kid)
1836 return kid;
1837
1838 kids.safe_push (n);
1839 n->level = this->level + 1;
1840
1841 return n;
1842 }
1843
1844 /* Append OP to the decision tree. */
1845
1846 dt_node *
1847 dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1848 {
1849 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1850 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1851 return append_node (n);
1852 }
1853
1854 /* Append a DT_TRUE decision tree node. */
1855
1856 dt_node *
1857 dt_node::append_true_op (operand *op, dt_node *parent, unsigned pos)
1858 {
1859 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1860 dt_operand *n = new dt_operand (DT_TRUE, op, 0, parent_, pos);
1861 return append_node (n);
1862 }
1863
1864 /* Append a DT_MATCH decision tree node. */
1865
1866 dt_node *
1867 dt_node::append_match_op (operand *op, dt_operand *match_dop,
1868 dt_node *parent, unsigned pos)
1869 {
1870 dt_operand *parent_ = as_a<dt_operand *> (parent);
1871 dt_operand *n = new dt_operand (DT_MATCH, op, match_dop, parent_, pos);
1872 return append_node (n);
1873 }
1874
1875 /* Append S to the decision tree. */
1876
1877 dt_node *
1878 dt_node::append_simplify (simplify *s, unsigned pattern_no,
1879 dt_operand **indexes)
1880 {
1881 dt_simplify *s2;
1882 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1883 for (unsigned i = 0; i < kids.length (); ++i)
1884 if ((s2 = dyn_cast <dt_simplify *> (kids[i]))
1885 && (verbose >= 1
1886 || s->match->location != s2->s->match->location))
1887 {
1888 /* With a nested patters, it's hard to avoid these in order
1889 to keep match.pd rules relatively small. */
1890 warning_at (s->match->location, "duplicate pattern");
1891 warning_at (s2->s->match->location, "previous pattern defined here");
1892 print_operand (s->match, stderr);
1893 fprintf (stderr, "\n");
1894 }
1895 return append_node (n);
1896 }
1897
1898 /* Analyze the node and its children. */
1899
1900 void
1901 dt_node::analyze (sinfo_map_t &map)
1902 {
1903 num_leafs = 0;
1904 total_size = 1;
1905 max_level = level;
1906
1907 if (type == DT_SIMPLIFY)
1908 {
1909 /* Populate the map of equivalent simplifies. */
1910 dt_simplify *s = as_a <dt_simplify *> (this);
1911 bool existed;
1912 sinfo *&si = map.get_or_insert (s, &existed);
1913 if (!existed)
1914 {
1915 si = new sinfo;
1916 si->s = s;
1917 si->cnt = 1;
1918 si->fname = NULL;
1919 }
1920 else
1921 si->cnt++;
1922 s->info = si;
1923 num_leafs = 1;
1924 return;
1925 }
1926
1927 for (unsigned i = 0; i < kids.length (); ++i)
1928 {
1929 kids[i]->analyze (map);
1930 num_leafs += kids[i]->num_leafs;
1931 total_size += kids[i]->total_size;
1932 max_level = MAX (max_level, kids[i]->max_level);
1933 }
1934 }
1935
1936 /* Insert O into the decision tree and return the decision tree node found
1937 or created. */
1938
1939 dt_node *
1940 decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1941 unsigned pos, dt_node *parent)
1942 {
1943 dt_node *q, *elm = 0;
1944
1945 if (capture *c = dyn_cast<capture *> (o))
1946 {
1947 unsigned capt_index = c->where;
1948
1949 if (indexes[capt_index] == 0)
1950 {
1951 if (c->what)
1952 q = insert_operand (p, c->what, indexes, pos, parent);
1953 else
1954 {
1955 q = elm = p->append_true_op (o, parent, pos);
1956 goto at_assert_elm;
1957 }
1958 // get to the last capture
1959 for (operand *what = c->what;
1960 what && is_a<capture *> (what);
1961 c = as_a<capture *> (what), what = c->what)
1962 ;
1963
1964 if (!c->what)
1965 {
1966 unsigned cc_index = c->where;
1967 dt_operand *match_op = indexes[cc_index];
1968
1969 dt_operand temp (dt_node::DT_TRUE, 0, 0, 0, 0);
1970 elm = decision_tree::find_node (p->kids, &temp);
1971
1972 if (elm == 0)
1973 {
1974 dt_operand match (dt_node::DT_MATCH, 0, match_op, 0, 0);
1975 match.value_match = c->value_match;
1976 elm = decision_tree::find_node (p->kids, &match);
1977 }
1978 }
1979 else
1980 {
1981 dt_operand temp (dt_node::DT_OPERAND, c->what, 0, 0, 0);
1982 elm = decision_tree::find_node (p->kids, &temp);
1983 }
1984
1985 at_assert_elm:
1986 gcc_assert (elm->type == dt_node::DT_TRUE
1987 || elm->type == dt_node::DT_OPERAND
1988 || elm->type == dt_node::DT_MATCH);
1989 indexes[capt_index] = static_cast<dt_operand *> (elm);
1990 return q;
1991 }
1992 else
1993 {
1994 p = p->append_match_op (o, indexes[capt_index], parent, pos);
1995 as_a <dt_operand *>(p)->value_match = c->value_match;
1996 if (c->what)
1997 return insert_operand (p, c->what, indexes, 0, p);
1998 else
1999 return p;
2000 }
2001 }
2002 p = p->append_op (o, parent, pos);
2003 q = p;
2004
2005 if (expr *e = dyn_cast <expr *>(o))
2006 {
2007 for (unsigned i = 0; i < e->ops.length (); ++i)
2008 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
2009 }
2010
2011 return q;
2012 }
2013
2014 /* Insert S into the decision tree. */
2015
2016 void
2017 decision_tree::insert (class simplify *s, unsigned pattern_no)
2018 {
2019 current_id = s->id;
2020 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
2021 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
2022 p->append_simplify (s, pattern_no, indexes);
2023 }
2024
2025 /* Debug functions to dump the decision tree. */
2026
2027 DEBUG_FUNCTION void
2028 decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
2029 {
2030 if (p->type == dt_node::DT_NODE)
2031 fprintf (f, "root");
2032 else
2033 {
2034 fprintf (f, "|");
2035 for (unsigned i = 0; i < indent; i++)
2036 fprintf (f, "-");
2037
2038 if (p->type == dt_node::DT_OPERAND)
2039 {
2040 dt_operand *dop = static_cast<dt_operand *>(p);
2041 print_operand (dop->op, f, true);
2042 }
2043 else if (p->type == dt_node::DT_TRUE)
2044 fprintf (f, "true");
2045 else if (p->type == dt_node::DT_MATCH)
2046 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
2047 else if (p->type == dt_node::DT_SIMPLIFY)
2048 {
2049 dt_simplify *s = static_cast<dt_simplify *> (p);
2050 fprintf (f, "simplify_%u { ", s->pattern_no);
2051 for (int i = 0; i <= s->s->capture_max; ++i)
2052 fprintf (f, "%p, ", (void *) s->indexes[i]);
2053 fprintf (f, " } ");
2054 }
2055 if (is_a <dt_operand *> (p))
2056 fprintf (f, " [%u]", as_a <dt_operand *> (p)->for_id);
2057 }
2058
2059 fprintf (stderr, " (%p, %p), %u, %u\n",
2060 (void *) p, (void *) p->parent, p->level, p->kids.length ());
2061
2062 for (unsigned i = 0; i < p->kids.length (); ++i)
2063 decision_tree::print_node (p->kids[i], f, indent + 2);
2064 }
2065
2066 DEBUG_FUNCTION void
2067 decision_tree::print (FILE *f)
2068 {
2069 return decision_tree::print_node (root, f);
2070 }
2071
2072
2073 /* For GENERIC we have to take care of wrapping multiple-used
2074 expressions with side-effects in save_expr and preserve side-effects
2075 of expressions with omit_one_operand. Analyze captures in
2076 match, result and with expressions and perform early-outs
2077 on the outermost match expression operands for cases we cannot
2078 handle. */
2079
2080 class capture_info
2081 {
2082 public:
2083 capture_info (simplify *s, operand *, bool);
2084 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
2085 bool walk_result (operand *o, bool, operand *);
2086 void walk_c_expr (c_expr *);
2087
2088 struct cinfo
2089 {
2090 bool expr_p;
2091 bool cse_p;
2092 bool force_no_side_effects_p;
2093 bool force_single_use;
2094 bool cond_expr_cond_p;
2095 unsigned long toplevel_msk;
2096 unsigned match_use_count;
2097 unsigned result_use_count;
2098 unsigned same_as;
2099 capture *c;
2100 };
2101
2102 auto_vec<cinfo> info;
2103 unsigned long force_no_side_effects;
2104 bool gimple;
2105 };
2106
2107 /* Analyze captures in S. */
2108
2109 capture_info::capture_info (simplify *s, operand *result, bool gimple_)
2110 {
2111 gimple = gimple_;
2112
2113 expr *e;
2114 if (s->kind == simplify::MATCH)
2115 {
2116 force_no_side_effects = -1;
2117 return;
2118 }
2119
2120 force_no_side_effects = 0;
2121 info.safe_grow_cleared (s->capture_max + 1);
2122 for (int i = 0; i <= s->capture_max; ++i)
2123 info[i].same_as = i;
2124
2125 e = as_a <expr *> (s->match);
2126 for (unsigned i = 0; i < e->ops.length (); ++i)
2127 walk_match (e->ops[i], i,
2128 (i != 0 && *e->operation == COND_EXPR)
2129 || *e->operation == TRUTH_ANDIF_EXPR
2130 || *e->operation == TRUTH_ORIF_EXPR,
2131 i == 0
2132 && (*e->operation == COND_EXPR
2133 || *e->operation == VEC_COND_EXPR));
2134
2135 walk_result (s->result, false, result);
2136 }
2137
2138 /* Analyze captures in the match expression piece O. */
2139
2140 void
2141 capture_info::walk_match (operand *o, unsigned toplevel_arg,
2142 bool conditional_p, bool cond_expr_cond_p)
2143 {
2144 if (capture *c = dyn_cast <capture *> (o))
2145 {
2146 unsigned where = c->where;
2147 info[where].match_use_count++;
2148 info[where].toplevel_msk |= 1 << toplevel_arg;
2149 info[where].force_no_side_effects_p |= conditional_p;
2150 info[where].cond_expr_cond_p |= cond_expr_cond_p;
2151 if (!info[where].c)
2152 info[where].c = c;
2153 if (!c->what)
2154 return;
2155 /* Recurse to exprs and captures. */
2156 if (is_a <capture *> (c->what)
2157 || is_a <expr *> (c->what))
2158 walk_match (c->what, toplevel_arg, conditional_p, false);
2159 /* We need to look past multiple captures to find a captured
2160 expression as with conditional converts two captures
2161 can be collapsed onto the same expression. Also collect
2162 what captures capture the same thing. */
2163 while (c->what && is_a <capture *> (c->what))
2164 {
2165 c = as_a <capture *> (c->what);
2166 if (info[c->where].same_as != c->where
2167 && info[c->where].same_as != info[where].same_as)
2168 fatal_at (c->location, "cannot handle this collapsed capture");
2169 info[c->where].same_as = info[where].same_as;
2170 }
2171 /* Mark expr (non-leaf) captures and forced single-use exprs. */
2172 expr *e;
2173 if (c->what
2174 && (e = dyn_cast <expr *> (c->what)))
2175 {
2176 /* Zero-operand expression captures like ADDR_EXPR@0 are
2177 similar as predicates -- if they are not mentioned in
2178 the result we have to force them to have no side-effects. */
2179 if (e->ops.length () != 0)
2180 info[where].expr_p = true;
2181 info[where].force_single_use |= e->force_single_use;
2182 }
2183 }
2184 else if (expr *e = dyn_cast <expr *> (o))
2185 {
2186 for (unsigned i = 0; i < e->ops.length (); ++i)
2187 {
2188 bool cond_p = conditional_p;
2189 bool expr_cond_p = false;
2190 if (i != 0 && *e->operation == COND_EXPR)
2191 cond_p = true;
2192 else if (*e->operation == TRUTH_ANDIF_EXPR
2193 || *e->operation == TRUTH_ORIF_EXPR)
2194 cond_p = true;
2195 if (i == 0
2196 && (*e->operation == COND_EXPR
2197 || *e->operation == VEC_COND_EXPR))
2198 expr_cond_p = true;
2199 walk_match (e->ops[i], toplevel_arg, cond_p, expr_cond_p);
2200 }
2201 }
2202 else if (is_a <predicate *> (o))
2203 {
2204 /* Mark non-captured leafs toplevel arg for checking. */
2205 force_no_side_effects |= 1 << toplevel_arg;
2206 if (verbose >= 1
2207 && !gimple)
2208 warning_at (o->location,
2209 "forcing no side-effects on possibly lost leaf");
2210 }
2211 else
2212 gcc_unreachable ();
2213 }
2214
2215 /* Analyze captures in the result expression piece O. Return true
2216 if RESULT was visited in one of the children. Only visit
2217 non-if/with children if they are rooted on RESULT. */
2218
2219 bool
2220 capture_info::walk_result (operand *o, bool conditional_p, operand *result)
2221 {
2222 if (capture *c = dyn_cast <capture *> (o))
2223 {
2224 unsigned where = info[c->where].same_as;
2225 info[where].result_use_count++;
2226 /* If we substitute an expression capture we don't know
2227 which captures this will end up using (well, we don't
2228 compute that). Force the uses to be side-effect free
2229 which means forcing the toplevels that reach the
2230 expression side-effect free. */
2231 if (info[where].expr_p)
2232 force_no_side_effects |= info[where].toplevel_msk;
2233 /* Mark CSE capture uses as forced to have no side-effects. */
2234 if (c->what
2235 && is_a <expr *> (c->what))
2236 {
2237 info[where].cse_p = true;
2238 walk_result (c->what, true, result);
2239 }
2240 }
2241 else if (expr *e = dyn_cast <expr *> (o))
2242 {
2243 id_base *opr = e->operation;
2244 if (user_id *uid = dyn_cast <user_id *> (opr))
2245 opr = uid->substitutes[0];
2246 for (unsigned i = 0; i < e->ops.length (); ++i)
2247 {
2248 bool cond_p = conditional_p;
2249 if (i != 0 && *e->operation == COND_EXPR)
2250 cond_p = true;
2251 else if (*e->operation == TRUTH_ANDIF_EXPR
2252 || *e->operation == TRUTH_ORIF_EXPR)
2253 cond_p = true;
2254 walk_result (e->ops[i], cond_p, result);
2255 }
2256 }
2257 else if (if_expr *ie = dyn_cast <if_expr *> (o))
2258 {
2259 /* 'if' conditions should be all fine. */
2260 if (ie->trueexpr == result)
2261 {
2262 walk_result (ie->trueexpr, false, result);
2263 return true;
2264 }
2265 if (ie->falseexpr == result)
2266 {
2267 walk_result (ie->falseexpr, false, result);
2268 return true;
2269 }
2270 bool res = false;
2271 if (is_a <if_expr *> (ie->trueexpr)
2272 || is_a <with_expr *> (ie->trueexpr))
2273 res |= walk_result (ie->trueexpr, false, result);
2274 if (ie->falseexpr
2275 && (is_a <if_expr *> (ie->falseexpr)
2276 || is_a <with_expr *> (ie->falseexpr)))
2277 res |= walk_result (ie->falseexpr, false, result);
2278 return res;
2279 }
2280 else if (with_expr *we = dyn_cast <with_expr *> (o))
2281 {
2282 bool res = (we->subexpr == result);
2283 if (res
2284 || is_a <if_expr *> (we->subexpr)
2285 || is_a <with_expr *> (we->subexpr))
2286 res |= walk_result (we->subexpr, false, result);
2287 if (res)
2288 walk_c_expr (we->with);
2289 return res;
2290 }
2291 else if (c_expr *ce = dyn_cast <c_expr *> (o))
2292 walk_c_expr (ce);
2293 else
2294 gcc_unreachable ();
2295
2296 return false;
2297 }
2298
2299 /* Look for captures in the C expr E. */
2300
2301 void
2302 capture_info::walk_c_expr (c_expr *e)
2303 {
2304 /* Give up for C exprs mentioning captures not inside TREE_TYPE,
2305 TREE_REAL_CST, TREE_CODE or a predicate where they cannot
2306 really escape through. */
2307 unsigned p_depth = 0;
2308 for (unsigned i = 0; i < e->code.length (); ++i)
2309 {
2310 const cpp_token *t = &e->code[i];
2311 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
2312 id_base *id;
2313 if (t->type == CPP_NAME
2314 && (strcmp ((const char *)CPP_HASHNODE
2315 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
2316 || strcmp ((const char *)CPP_HASHNODE
2317 (t->val.node.node)->ident.str, "TREE_CODE") == 0
2318 || strcmp ((const char *)CPP_HASHNODE
2319 (t->val.node.node)->ident.str, "TREE_REAL_CST") == 0
2320 || ((id = get_operator ((const char *)CPP_HASHNODE
2321 (t->val.node.node)->ident.str))
2322 && is_a <predicate_id *> (id)))
2323 && n->type == CPP_OPEN_PAREN)
2324 p_depth++;
2325 else if (t->type == CPP_CLOSE_PAREN
2326 && p_depth > 0)
2327 p_depth--;
2328 else if (p_depth == 0
2329 && t->type == CPP_ATSIGN
2330 && (n->type == CPP_NUMBER
2331 || n->type == CPP_NAME)
2332 && !(n->flags & PREV_WHITE))
2333 {
2334 const char *id1;
2335 if (n->type == CPP_NUMBER)
2336 id1 = (const char *)n->val.str.text;
2337 else
2338 id1 = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2339 unsigned *where = e->capture_ids->get(id1);
2340 if (! where)
2341 fatal_at (n, "unknown capture id '%s'", id1);
2342 info[info[*where].same_as].force_no_side_effects_p = true;
2343 if (verbose >= 1
2344 && !gimple)
2345 warning_at (t, "capture escapes");
2346 }
2347 }
2348 }
2349
2350
2351 /* Code generation off the decision tree and the refered AST nodes. */
2352
2353 bool
2354 is_conversion (id_base *op)
2355 {
2356 return (*op == CONVERT_EXPR
2357 || *op == NOP_EXPR
2358 || *op == FLOAT_EXPR
2359 || *op == FIX_TRUNC_EXPR
2360 || *op == VIEW_CONVERT_EXPR);
2361 }
2362
2363 /* Get the type to be used for generating operand POS of OP from the
2364 various sources. */
2365
2366 static const char *
2367 get_operand_type (id_base *op, unsigned pos,
2368 const char *in_type,
2369 const char *expr_type,
2370 const char *other_oprnd_type)
2371 {
2372 /* Generally operands whose type does not match the type of the
2373 expression generated need to know their types but match and
2374 thus can fall back to 'other_oprnd_type'. */
2375 if (is_conversion (op))
2376 return other_oprnd_type;
2377 else if (*op == REALPART_EXPR
2378 || *op == IMAGPART_EXPR)
2379 return other_oprnd_type;
2380 else if (is_a <operator_id *> (op)
2381 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
2382 return other_oprnd_type;
2383 else if (*op == COND_EXPR
2384 && pos == 0)
2385 return "boolean_type_node";
2386 else if (strncmp (op->id, "CFN_COND_", 9) == 0)
2387 {
2388 /* IFN_COND_* operands 1 and later by default have the same type
2389 as the result. The type of operand 0 needs to be specified
2390 explicitly. */
2391 if (pos > 0 && expr_type)
2392 return expr_type;
2393 else if (pos > 0 && in_type)
2394 return in_type;
2395 else
2396 return NULL;
2397 }
2398 else
2399 {
2400 /* Otherwise all types should match - choose one in order of
2401 preference. */
2402 if (expr_type)
2403 return expr_type;
2404 else if (in_type)
2405 return in_type;
2406 else
2407 return other_oprnd_type;
2408 }
2409 }
2410
2411 /* Generate transform code for an expression. */
2412
2413 void
2414 expr::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2415 int depth, const char *in_type, capture_info *cinfo,
2416 dt_operand **indexes, int)
2417 {
2418 id_base *opr = operation;
2419 /* When we delay operator substituting during lowering of fors we
2420 make sure that for code-gen purposes the effects of each substitute
2421 are the same. Thus just look at that. */
2422 if (user_id *uid = dyn_cast <user_id *> (opr))
2423 opr = uid->substitutes[0];
2424
2425 bool conversion_p = is_conversion (opr);
2426 const char *type = expr_type;
2427 char optype[64];
2428 if (type)
2429 /* If there was a type specification in the pattern use it. */
2430 ;
2431 else if (conversion_p)
2432 /* For conversions we need to build the expression using the
2433 outer type passed in. */
2434 type = in_type;
2435 else if (*opr == REALPART_EXPR
2436 || *opr == IMAGPART_EXPR)
2437 {
2438 /* __real and __imag use the component type of its operand. */
2439 snprintf (optype, sizeof (optype), "TREE_TYPE (TREE_TYPE (_o%d[0]))",
2440 depth);
2441 type = optype;
2442 }
2443 else if (is_a <operator_id *> (opr)
2444 && !strcmp (as_a <operator_id *> (opr)->tcc, "tcc_comparison"))
2445 {
2446 /* comparisons use boolean_type_node (or what gets in), but
2447 their operands need to figure out the types themselves. */
2448 if (in_type)
2449 type = in_type;
2450 else
2451 {
2452 snprintf (optype, sizeof (optype), "boolean_type_node");
2453 type = optype;
2454 }
2455 in_type = NULL;
2456 }
2457 else if (*opr == COND_EXPR
2458 || *opr == VEC_COND_EXPR
2459 || strncmp (opr->id, "CFN_COND_", 9) == 0)
2460 {
2461 /* Conditions are of the same type as their first alternative. */
2462 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[1])", depth);
2463 type = optype;
2464 }
2465 else
2466 {
2467 /* Other operations are of the same type as their first operand. */
2468 snprintf (optype, sizeof (optype), "TREE_TYPE (_o%d[0])", depth);
2469 type = optype;
2470 }
2471 if (!type)
2472 fatal_at (location, "cannot determine type of operand");
2473
2474 fprintf_indent (f, indent, "{\n");
2475 indent += 2;
2476 fprintf_indent (f, indent,
2477 "tree _o%d[%u], _r%d;\n", depth, ops.length (), depth);
2478 char op0type[64];
2479 snprintf (op0type, sizeof (op0type), "TREE_TYPE (_o%d[0])", depth);
2480 for (unsigned i = 0; i < ops.length (); ++i)
2481 {
2482 char dest1[32];
2483 snprintf (dest1, sizeof (dest1), "_o%d[%u]", depth, i);
2484 const char *optype1
2485 = get_operand_type (opr, i, in_type, expr_type,
2486 i == 0 ? NULL : op0type);
2487 ops[i]->gen_transform (f, indent, dest1, gimple, depth + 1, optype1,
2488 cinfo, indexes,
2489 (*opr == COND_EXPR
2490 || *opr == VEC_COND_EXPR) && i == 0 ? 1 : 2);
2491 }
2492
2493 const char *opr_name;
2494 if (*operation == CONVERT_EXPR)
2495 opr_name = "NOP_EXPR";
2496 else
2497 opr_name = operation->id;
2498
2499 if (gimple)
2500 {
2501 if (*opr == CONVERT_EXPR)
2502 {
2503 fprintf_indent (f, indent,
2504 "if (%s != TREE_TYPE (_o%d[0])\n",
2505 type, depth);
2506 fprintf_indent (f, indent,
2507 " && !useless_type_conversion_p (%s, TREE_TYPE "
2508 "(_o%d[0])))\n",
2509 type, depth);
2510 fprintf_indent (f, indent + 2, "{\n");
2511 indent += 4;
2512 }
2513 /* ??? Building a stmt can fail for various reasons here, seq being
2514 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
2515 So if we fail here we should continue matching other patterns. */
2516 fprintf_indent (f, indent, "gimple_match_op tem_op "
2517 "(res_op->cond.any_else (), %s, %s", opr_name, type);
2518 for (unsigned i = 0; i < ops.length (); ++i)
2519 fprintf (f, ", _o%d[%u]", depth, i);
2520 fprintf (f, ");\n");
2521 fprintf_indent (f, indent, "tem_op.resimplify (lseq, valueize);\n");
2522 fprintf_indent (f, indent,
2523 "_r%d = maybe_push_res_to_seq (&tem_op, lseq);\n", depth);
2524 fprintf_indent (f, indent,
2525 "if (!_r%d) return false;\n",
2526 depth);
2527 if (*opr == CONVERT_EXPR)
2528 {
2529 indent -= 4;
2530 fprintf_indent (f, indent, " }\n");
2531 fprintf_indent (f, indent, "else\n");
2532 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2533 }
2534 }
2535 else
2536 {
2537 if (*opr == CONVERT_EXPR)
2538 {
2539 fprintf_indent (f, indent, "if (TREE_TYPE (_o%d[0]) != %s)\n",
2540 depth, type);
2541 indent += 2;
2542 }
2543 if (opr->kind == id_base::CODE)
2544 fprintf_indent (f, indent, "_r%d = fold_build%d_loc (loc, %s, %s",
2545 depth, ops.length(), opr_name, type);
2546 else
2547 {
2548 fprintf_indent (f, indent, "{\n");
2549 fprintf_indent (f, indent, " _r%d = maybe_build_call_expr_loc (loc, "
2550 "%s, %s, %d", depth, opr_name, type, ops.length());
2551 }
2552 for (unsigned i = 0; i < ops.length (); ++i)
2553 fprintf (f, ", _o%d[%u]", depth, i);
2554 fprintf (f, ");\n");
2555 if (opr->kind != id_base::CODE)
2556 {
2557 fprintf_indent (f, indent, " if (!_r%d)\n", depth);
2558 fprintf_indent (f, indent, " return NULL_TREE;\n");
2559 fprintf_indent (f, indent, "}\n");
2560 }
2561 if (*opr == CONVERT_EXPR)
2562 {
2563 indent -= 2;
2564 fprintf_indent (f, indent, "else\n");
2565 fprintf_indent (f, indent, " _r%d = _o%d[0];\n", depth, depth);
2566 }
2567 }
2568 fprintf_indent (f, indent, "%s = _r%d;\n", dest, depth);
2569 indent -= 2;
2570 fprintf_indent (f, indent, "}\n");
2571 }
2572
2573 /* Generate code for a c_expr which is either the expression inside
2574 an if statement or a sequence of statements which computes a
2575 result to be stored to DEST. */
2576
2577 void
2578 c_expr::gen_transform (FILE *f, int indent, const char *dest,
2579 bool, int, const char *, capture_info *,
2580 dt_operand **, int)
2581 {
2582 if (dest && nr_stmts == 1)
2583 fprintf_indent (f, indent, "%s = ", dest);
2584
2585 unsigned stmt_nr = 1;
2586 int prev_line = -1;
2587 for (unsigned i = 0; i < code.length (); ++i)
2588 {
2589 const cpp_token *token = &code[i];
2590
2591 /* We can't recover from all lexing losses but we can roughly restore line
2592 breaks from location info. */
2593 const line_map_ordinary *map;
2594 linemap_resolve_location (line_table, token->src_loc,
2595 LRK_SPELLING_LOCATION, &map);
2596 expanded_location loc = linemap_expand_location (line_table, map,
2597 token->src_loc);
2598 if (prev_line != -1 && loc.line != prev_line)
2599 fputc ('\n', f);
2600 prev_line = loc.line;
2601
2602 /* Replace captures for code-gen. */
2603 if (token->type == CPP_ATSIGN)
2604 {
2605 const cpp_token *n = &code[i+1];
2606 if ((n->type == CPP_NUMBER
2607 || n->type == CPP_NAME)
2608 && !(n->flags & PREV_WHITE))
2609 {
2610 if (token->flags & PREV_WHITE)
2611 fputc (' ', f);
2612 const char *id;
2613 if (n->type == CPP_NUMBER)
2614 id = (const char *)n->val.str.text;
2615 else
2616 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
2617 unsigned *cid = capture_ids->get (id);
2618 if (!cid)
2619 fatal_at (token, "unknown capture id");
2620 fprintf (f, "captures[%u]", *cid);
2621 ++i;
2622 continue;
2623 }
2624 }
2625
2626 if (token->flags & PREV_WHITE)
2627 fputc (' ', f);
2628
2629 if (token->type == CPP_NAME)
2630 {
2631 const char *id = (const char *) NODE_NAME (token->val.node.node);
2632 unsigned j;
2633 for (j = 0; j < ids.length (); ++j)
2634 {
2635 if (strcmp (id, ids[j].id) == 0)
2636 {
2637 fprintf (f, "%s", ids[j].oper);
2638 break;
2639 }
2640 }
2641 if (j < ids.length ())
2642 continue;
2643 }
2644
2645 /* Output the token as string. */
2646 char *tk = (char *)cpp_token_as_text (r, token);
2647 fputs (tk, f);
2648
2649 if (token->type == CPP_SEMICOLON)
2650 {
2651 stmt_nr++;
2652 if (dest && stmt_nr == nr_stmts)
2653 fprintf_indent (f, indent, "%s = ", dest);
2654 }
2655 }
2656 fputc ('\n', f);
2657 }
2658
2659 /* Generate transform code for a capture. */
2660
2661 void
2662 capture::gen_transform (FILE *f, int indent, const char *dest, bool gimple,
2663 int depth, const char *in_type, capture_info *cinfo,
2664 dt_operand **indexes, int cond_handling)
2665 {
2666 if (what && is_a<expr *> (what))
2667 {
2668 if (indexes[where] == 0)
2669 {
2670 char buf[20];
2671 snprintf (buf, sizeof (buf), "captures[%u]", where);
2672 what->gen_transform (f, indent, buf, gimple, depth, in_type,
2673 cinfo, NULL);
2674 }
2675 }
2676
2677 /* If in GENERIC some capture is used multiple times, unshare it except
2678 when emitting the last use. */
2679 if (!gimple
2680 && cinfo->info.exists ()
2681 && cinfo->info[cinfo->info[where].same_as].result_use_count > 1)
2682 {
2683 fprintf_indent (f, indent, "%s = unshare_expr (captures[%u]);\n",
2684 dest, where);
2685 cinfo->info[cinfo->info[where].same_as].result_use_count--;
2686 }
2687 else
2688 fprintf_indent (f, indent, "%s = captures[%u];\n", dest, where);
2689
2690 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2691 with substituting a capture of that. */
2692 if (gimple
2693 && cond_handling != 0
2694 && cinfo->info[where].cond_expr_cond_p)
2695 {
2696 /* If substituting into a cond_expr condition, unshare. */
2697 if (cond_handling == 1)
2698 fprintf_indent (f, indent, "%s = unshare_expr (%s);\n", dest, dest);
2699 /* If substituting elsewhere we might need to decompose it. */
2700 else if (cond_handling == 2)
2701 {
2702 /* ??? Returning false here will also not allow any other patterns
2703 to match unless this generator was split out. */
2704 fprintf_indent (f, indent, "if (COMPARISON_CLASS_P (%s))\n", dest);
2705 fprintf_indent (f, indent, " {\n");
2706 fprintf_indent (f, indent, " if (!seq) return false;\n");
2707 fprintf_indent (f, indent, " %s = gimple_build (seq,"
2708 " TREE_CODE (%s),"
2709 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
2710 " TREE_OPERAND (%s, 1));\n",
2711 dest, dest, dest, dest, dest);
2712 fprintf_indent (f, indent, " }\n");
2713 }
2714 }
2715 }
2716
2717 /* Return the name of the operand representing the decision tree node.
2718 Use NAME as space to generate it. */
2719
2720 char *
2721 dt_operand::get_name (char *name)
2722 {
2723 if (! parent)
2724 sprintf (name, "t");
2725 else if (parent->level == 1)
2726 sprintf (name, "_p%u", pos);
2727 else if (parent->type == dt_node::DT_MATCH)
2728 return as_a <dt_operand *> (parent)->get_name (name);
2729 else
2730 sprintf (name, "_q%u%u", parent->level, pos);
2731 return name;
2732 }
2733
2734 /* Fill NAME with the operand name at position POS. */
2735
2736 void
2737 dt_operand::gen_opname (char *name, unsigned pos)
2738 {
2739 if (! parent)
2740 sprintf (name, "_p%u", pos);
2741 else
2742 sprintf (name, "_q%u%u", level, pos);
2743 }
2744
2745 /* Generate matching code for the decision tree operand which is
2746 a predicate. */
2747
2748 unsigned
2749 dt_operand::gen_predicate (FILE *f, int indent, const char *opname, bool gimple)
2750 {
2751 predicate *p = as_a <predicate *> (op);
2752
2753 if (p->p->matchers.exists ())
2754 {
2755 /* If this is a predicate generated from a pattern mangle its
2756 name and pass on the valueize hook. */
2757 if (gimple)
2758 fprintf_indent (f, indent, "if (gimple_%s (%s, valueize))\n",
2759 p->p->id, opname);
2760 else
2761 fprintf_indent (f, indent, "if (tree_%s (%s))\n", p->p->id, opname);
2762 }
2763 else
2764 fprintf_indent (f, indent, "if (%s (%s))\n", p->p->id, opname);
2765 fprintf_indent (f, indent + 2, "{\n");
2766 return 1;
2767 }
2768
2769 /* Generate matching code for the decision tree operand which is
2770 a capture-match. */
2771
2772 unsigned
2773 dt_operand::gen_match_op (FILE *f, int indent, const char *opname, bool)
2774 {
2775 char match_opname[20];
2776 match_dop->get_name (match_opname);
2777 if (value_match)
2778 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2779 "|| operand_equal_p (%s, %s, 0))\n",
2780 opname, match_opname, opname, opname, match_opname);
2781 else
2782 fprintf_indent (f, indent, "if ((%s == %s && ! TREE_SIDE_EFFECTS (%s)) "
2783 "|| (operand_equal_p (%s, %s, 0) "
2784 "&& types_match (%s, %s)))\n",
2785 opname, match_opname, opname, opname, match_opname,
2786 opname, match_opname);
2787 fprintf_indent (f, indent + 2, "{\n");
2788 return 1;
2789 }
2790
2791 /* Generate GIMPLE matching code for the decision tree operand. */
2792
2793 unsigned
2794 dt_operand::gen_gimple_expr (FILE *f, int indent, int depth)
2795 {
2796 expr *e = static_cast<expr *> (op);
2797 id_base *id = e->operation;
2798 unsigned n_ops = e->ops.length ();
2799 unsigned n_braces = 0;
2800
2801 for (unsigned i = 0; i < n_ops; ++i)
2802 {
2803 char child_opname[20];
2804 gen_opname (child_opname, i);
2805
2806 if (id->kind == id_base::CODE)
2807 {
2808 if (e->is_generic
2809 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2810 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
2811 {
2812 /* ??? If this is a memory operation we can't (and should not)
2813 match this. The only sensible operand types are
2814 SSA names and invariants. */
2815 if (e->is_generic)
2816 {
2817 char opname[20];
2818 get_name (opname);
2819 fprintf_indent (f, indent,
2820 "tree %s = TREE_OPERAND (%s, %i);\n",
2821 child_opname, opname, i);
2822 }
2823 else
2824 fprintf_indent (f, indent,
2825 "tree %s = TREE_OPERAND "
2826 "(gimple_assign_rhs1 (_a%d), %i);\n",
2827 child_opname, depth, i);
2828 fprintf_indent (f, indent,
2829 "if ((TREE_CODE (%s) == SSA_NAME\n",
2830 child_opname);
2831 fprintf_indent (f, indent,
2832 " || is_gimple_min_invariant (%s)))\n",
2833 child_opname);
2834 fprintf_indent (f, indent,
2835 " {\n");
2836 indent += 4;
2837 n_braces++;
2838 fprintf_indent (f, indent,
2839 "%s = do_valueize (valueize, %s);\n",
2840 child_opname, child_opname);
2841 continue;
2842 }
2843 else
2844 fprintf_indent (f, indent,
2845 "tree %s = gimple_assign_rhs%u (_a%d);\n",
2846 child_opname, i + 1, depth);
2847 }
2848 else
2849 fprintf_indent (f, indent,
2850 "tree %s = gimple_call_arg (_c%d, %u);\n",
2851 child_opname, depth, i);
2852 fprintf_indent (f, indent,
2853 "%s = do_valueize (valueize, %s);\n",
2854 child_opname, child_opname);
2855 }
2856 /* While the toplevel operands are canonicalized by the caller
2857 after valueizing operands of sub-expressions we have to
2858 re-canonicalize operand order. */
2859 int opno = commutative_op (id);
2860 if (opno >= 0)
2861 {
2862 char child_opname0[20], child_opname1[20];
2863 gen_opname (child_opname0, opno);
2864 gen_opname (child_opname1, opno + 1);
2865 fprintf_indent (f, indent,
2866 "if (tree_swap_operands_p (%s, %s))\n",
2867 child_opname0, child_opname1);
2868 fprintf_indent (f, indent,
2869 " std::swap (%s, %s);\n",
2870 child_opname0, child_opname1);
2871 }
2872
2873 return n_braces;
2874 }
2875
2876 /* Generate GENERIC matching code for the decision tree operand. */
2877
2878 unsigned
2879 dt_operand::gen_generic_expr (FILE *f, int indent, const char *opname)
2880 {
2881 expr *e = static_cast<expr *> (op);
2882 unsigned n_ops = e->ops.length ();
2883
2884 for (unsigned i = 0; i < n_ops; ++i)
2885 {
2886 char child_opname[20];
2887 gen_opname (child_opname, i);
2888
2889 if (e->operation->kind == id_base::CODE)
2890 fprintf_indent (f, indent, "tree %s = TREE_OPERAND (%s, %u);\n",
2891 child_opname, opname, i);
2892 else
2893 fprintf_indent (f, indent, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2894 child_opname, opname, i);
2895 }
2896
2897 return 0;
2898 }
2899
2900 /* Generate matching code for the children of the decision tree node. */
2901
2902 void
2903 dt_node::gen_kids (FILE *f, int indent, bool gimple, int depth)
2904 {
2905 auto_vec<dt_operand *> gimple_exprs;
2906 auto_vec<dt_operand *> generic_exprs;
2907 auto_vec<dt_operand *> fns;
2908 auto_vec<dt_operand *> generic_fns;
2909 auto_vec<dt_operand *> preds;
2910 auto_vec<dt_node *> others;
2911
2912 for (unsigned i = 0; i < kids.length (); ++i)
2913 {
2914 if (kids[i]->type == dt_node::DT_OPERAND)
2915 {
2916 dt_operand *op = as_a<dt_operand *> (kids[i]);
2917 if (expr *e = dyn_cast <expr *> (op->op))
2918 {
2919 if (e->ops.length () == 0
2920 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2921 generic_exprs.safe_push (op);
2922 else if (e->operation->kind == id_base::FN)
2923 {
2924 if (gimple)
2925 fns.safe_push (op);
2926 else
2927 generic_fns.safe_push (op);
2928 }
2929 else if (e->operation->kind == id_base::PREDICATE)
2930 preds.safe_push (op);
2931 else
2932 {
2933 if (gimple && !e->is_generic)
2934 gimple_exprs.safe_push (op);
2935 else
2936 generic_exprs.safe_push (op);
2937 }
2938 }
2939 else if (op->op->type == operand::OP_PREDICATE)
2940 others.safe_push (kids[i]);
2941 else
2942 gcc_unreachable ();
2943 }
2944 else if (kids[i]->type == dt_node::DT_SIMPLIFY)
2945 others.safe_push (kids[i]);
2946 else if (kids[i]->type == dt_node::DT_MATCH
2947 || kids[i]->type == dt_node::DT_TRUE)
2948 {
2949 /* A DT_TRUE operand serves as a barrier - generate code now
2950 for what we have collected sofar.
2951 Like DT_TRUE, DT_MATCH serves as a barrier as it can cause
2952 dependent matches to get out-of-order. Generate code now
2953 for what we have collected sofar. */
2954 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
2955 fns, generic_fns, preds, others);
2956 /* And output the true operand itself. */
2957 kids[i]->gen (f, indent, gimple, depth);
2958 gimple_exprs.truncate (0);
2959 generic_exprs.truncate (0);
2960 fns.truncate (0);
2961 generic_fns.truncate (0);
2962 preds.truncate (0);
2963 others.truncate (0);
2964 }
2965 else
2966 gcc_unreachable ();
2967 }
2968
2969 /* Generate code for the remains. */
2970 gen_kids_1 (f, indent, gimple, depth, gimple_exprs, generic_exprs,
2971 fns, generic_fns, preds, others);
2972 }
2973
2974 /* Generate matching code for the children of the decision tree node. */
2975
2976 void
2977 dt_node::gen_kids_1 (FILE *f, int indent, bool gimple, int depth,
2978 vec<dt_operand *> gimple_exprs,
2979 vec<dt_operand *> generic_exprs,
2980 vec<dt_operand *> fns,
2981 vec<dt_operand *> generic_fns,
2982 vec<dt_operand *> preds,
2983 vec<dt_node *> others)
2984 {
2985 char buf[128];
2986 char *kid_opname = buf;
2987
2988 unsigned exprs_len = gimple_exprs.length ();
2989 unsigned gexprs_len = generic_exprs.length ();
2990 unsigned fns_len = fns.length ();
2991 unsigned gfns_len = generic_fns.length ();
2992
2993 if (exprs_len || fns_len || gexprs_len || gfns_len)
2994 {
2995 if (exprs_len)
2996 gimple_exprs[0]->get_name (kid_opname);
2997 else if (fns_len)
2998 fns[0]->get_name (kid_opname);
2999 else if (gfns_len)
3000 generic_fns[0]->get_name (kid_opname);
3001 else
3002 generic_exprs[0]->get_name (kid_opname);
3003
3004 fprintf_indent (f, indent, "switch (TREE_CODE (%s))\n", kid_opname);
3005 fprintf_indent (f, indent, " {\n");
3006 indent += 2;
3007 }
3008
3009 if (exprs_len || fns_len)
3010 {
3011 depth++;
3012 fprintf_indent (f, indent,
3013 "case SSA_NAME:\n");
3014 fprintf_indent (f, indent,
3015 " if (gimple *_d%d = get_def (valueize, %s))\n",
3016 depth, kid_opname);
3017 fprintf_indent (f, indent,
3018 " {\n");
3019 indent += 6;
3020 if (exprs_len)
3021 {
3022 fprintf_indent (f, indent,
3023 "if (gassign *_a%d = dyn_cast <gassign *> (_d%d))\n",
3024 depth, depth);
3025 fprintf_indent (f, indent,
3026 " switch (gimple_assign_rhs_code (_a%d))\n",
3027 depth);
3028 indent += 4;
3029 fprintf_indent (f, indent, "{\n");
3030 for (unsigned i = 0; i < exprs_len; ++i)
3031 {
3032 expr *e = as_a <expr *> (gimple_exprs[i]->op);
3033 id_base *op = e->operation;
3034 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3035 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3036 else
3037 fprintf_indent (f, indent, "case %s:\n", op->id);
3038 fprintf_indent (f, indent, " {\n");
3039 gimple_exprs[i]->gen (f, indent + 4, true, depth);
3040 fprintf_indent (f, indent, " break;\n");
3041 fprintf_indent (f, indent, " }\n");
3042 }
3043 fprintf_indent (f, indent, "default:;\n");
3044 fprintf_indent (f, indent, "}\n");
3045 indent -= 4;
3046 }
3047
3048 if (fns_len)
3049 {
3050 fprintf_indent (f, indent,
3051 "%sif (gcall *_c%d = dyn_cast <gcall *> (_d%d))\n",
3052 exprs_len ? "else " : "", depth, depth);
3053 fprintf_indent (f, indent,
3054 " switch (gimple_call_combined_fn (_c%d))\n",
3055 depth);
3056
3057 indent += 4;
3058 fprintf_indent (f, indent, "{\n");
3059 for (unsigned i = 0; i < fns_len; ++i)
3060 {
3061 expr *e = as_a <expr *>(fns[i]->op);
3062 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3063 fprintf_indent (f, indent, " {\n");
3064 fns[i]->gen (f, indent + 4, true, depth);
3065 fprintf_indent (f, indent, " break;\n");
3066 fprintf_indent (f, indent, " }\n");
3067 }
3068
3069 fprintf_indent (f, indent, "default:;\n");
3070 fprintf_indent (f, indent, "}\n");
3071 indent -= 4;
3072 }
3073
3074 indent -= 6;
3075 depth--;
3076 fprintf_indent (f, indent, " }\n");
3077 /* See if there is SSA_NAME among generic_exprs and if yes, emit it
3078 here rather than in the next loop. */
3079 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3080 {
3081 expr *e = as_a <expr *>(generic_exprs[i]->op);
3082 id_base *op = e->operation;
3083 if (*op == SSA_NAME && (exprs_len || fns_len))
3084 {
3085 fprintf_indent (f, indent + 4, "{\n");
3086 generic_exprs[i]->gen (f, indent + 6, gimple, depth);
3087 fprintf_indent (f, indent + 4, "}\n");
3088 }
3089 }
3090
3091 fprintf_indent (f, indent, " break;\n");
3092 }
3093
3094 for (unsigned i = 0; i < generic_exprs.length (); ++i)
3095 {
3096 expr *e = as_a <expr *>(generic_exprs[i]->op);
3097 id_base *op = e->operation;
3098 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
3099 fprintf_indent (f, indent, "CASE_CONVERT:\n");
3100 else if (*op == SSA_NAME && (exprs_len || fns_len))
3101 /* Already handled above. */
3102 continue;
3103 else
3104 fprintf_indent (f, indent, "case %s:\n", op->id);
3105 fprintf_indent (f, indent, " {\n");
3106 generic_exprs[i]->gen (f, indent + 4, gimple, depth);
3107 fprintf_indent (f, indent, " break;\n");
3108 fprintf_indent (f, indent, " }\n");
3109 }
3110
3111 if (gfns_len)
3112 {
3113 fprintf_indent (f, indent,
3114 "case CALL_EXPR:\n");
3115 fprintf_indent (f, indent,
3116 " switch (get_call_combined_fn (%s))\n",
3117 kid_opname);
3118 fprintf_indent (f, indent,
3119 " {\n");
3120 indent += 4;
3121
3122 for (unsigned j = 0; j < generic_fns.length (); ++j)
3123 {
3124 expr *e = as_a <expr *>(generic_fns[j]->op);
3125 gcc_assert (e->operation->kind == id_base::FN);
3126
3127 fprintf_indent (f, indent, "case %s:\n", e->operation->id);
3128 fprintf_indent (f, indent, " {\n");
3129 generic_fns[j]->gen (f, indent + 4, false, depth);
3130 fprintf_indent (f, indent, " break;\n");
3131 fprintf_indent (f, indent, " }\n");
3132 }
3133 fprintf_indent (f, indent, "default:;\n");
3134
3135 indent -= 4;
3136 fprintf_indent (f, indent, " }\n");
3137 fprintf_indent (f, indent, " break;\n");
3138 }
3139
3140 /* Close switch (TREE_CODE ()). */
3141 if (exprs_len || fns_len || gexprs_len || gfns_len)
3142 {
3143 indent -= 4;
3144 fprintf_indent (f, indent, " default:;\n");
3145 fprintf_indent (f, indent, " }\n");
3146 }
3147
3148 for (unsigned i = 0; i < preds.length (); ++i)
3149 {
3150 expr *e = as_a <expr *> (preds[i]->op);
3151 predicate_id *p = as_a <predicate_id *> (e->operation);
3152 preds[i]->get_name (kid_opname);
3153 fprintf_indent (f, indent, "{\n");
3154 indent += 2;
3155 fprintf_indent (f, indent, "tree %s_pops[%d];\n", kid_opname, p->nargs);
3156 fprintf_indent (f, indent, "if (%s_%s (%s, %s_pops%s))\n",
3157 gimple ? "gimple" : "tree",
3158 p->id, kid_opname, kid_opname,
3159 gimple ? ", valueize" : "");
3160 fprintf_indent (f, indent, " {\n");
3161 for (int j = 0; j < p->nargs; ++j)
3162 {
3163 char child_opname[20];
3164 preds[i]->gen_opname (child_opname, j);
3165 fprintf_indent (f, indent + 4, "tree %s = %s_pops[%d];\n",
3166 child_opname, kid_opname, j);
3167 }
3168 preds[i]->gen_kids (f, indent + 4, gimple, depth);
3169 fprintf (f, "}\n");
3170 indent -= 2;
3171 fprintf_indent (f, indent, "}\n");
3172 }
3173
3174 for (unsigned i = 0; i < others.length (); ++i)
3175 others[i]->gen (f, indent, gimple, depth);
3176 }
3177
3178 /* Generate matching code for the decision tree operand. */
3179
3180 void
3181 dt_operand::gen (FILE *f, int indent, bool gimple, int depth)
3182 {
3183 char opname[20];
3184 get_name (opname);
3185
3186 unsigned n_braces = 0;
3187
3188 if (type == DT_OPERAND)
3189 switch (op->type)
3190 {
3191 case operand::OP_PREDICATE:
3192 n_braces = gen_predicate (f, indent, opname, gimple);
3193 break;
3194
3195 case operand::OP_EXPR:
3196 if (gimple)
3197 n_braces = gen_gimple_expr (f, indent, depth);
3198 else
3199 n_braces = gen_generic_expr (f, indent, opname);
3200 break;
3201
3202 default:
3203 gcc_unreachable ();
3204 }
3205 else if (type == DT_TRUE)
3206 ;
3207 else if (type == DT_MATCH)
3208 n_braces = gen_match_op (f, indent, opname, gimple);
3209 else
3210 gcc_unreachable ();
3211
3212 indent += 4 * n_braces;
3213 gen_kids (f, indent, gimple, depth);
3214
3215 for (unsigned i = 0; i < n_braces; ++i)
3216 {
3217 indent -= 4;
3218 if (indent < 0)
3219 indent = 0;
3220 fprintf_indent (f, indent, " }\n");
3221 }
3222 }
3223
3224
3225 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3226 step of a '(simplify ...)' or '(match ...)'. This handles everything
3227 that is not part of the decision tree (simplify->match).
3228 Main recursive worker. */
3229
3230 void
3231 dt_simplify::gen_1 (FILE *f, int indent, bool gimple, operand *result)
3232 {
3233 if (result)
3234 {
3235 if (with_expr *w = dyn_cast <with_expr *> (result))
3236 {
3237 fprintf_indent (f, indent, "{\n");
3238 indent += 4;
3239 output_line_directive (f, w->location);
3240 w->with->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3241 gen_1 (f, indent, gimple, w->subexpr);
3242 indent -= 4;
3243 fprintf_indent (f, indent, "}\n");
3244 return;
3245 }
3246 else if (if_expr *ife = dyn_cast <if_expr *> (result))
3247 {
3248 output_line_directive (f, ife->location);
3249 fprintf_indent (f, indent, "if (");
3250 ife->cond->gen_transform (f, indent, NULL, true, 1, "type", NULL);
3251 fprintf (f, ")\n");
3252 fprintf_indent (f, indent + 2, "{\n");
3253 indent += 4;
3254 gen_1 (f, indent, gimple, ife->trueexpr);
3255 indent -= 4;
3256 fprintf_indent (f, indent + 2, "}\n");
3257 if (ife->falseexpr)
3258 {
3259 fprintf_indent (f, indent, "else\n");
3260 fprintf_indent (f, indent + 2, "{\n");
3261 indent += 4;
3262 gen_1 (f, indent, gimple, ife->falseexpr);
3263 indent -= 4;
3264 fprintf_indent (f, indent + 2, "}\n");
3265 }
3266 return;
3267 }
3268 }
3269
3270 /* Analyze captures and perform early-outs on the incoming arguments
3271 that cover cases we cannot handle. */
3272 capture_info cinfo (s, result, gimple);
3273 if (s->kind == simplify::SIMPLIFY)
3274 {
3275 if (!gimple)
3276 {
3277 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3278 if (cinfo.force_no_side_effects & (1 << i))
3279 {
3280 fprintf_indent (f, indent,
3281 "if (TREE_SIDE_EFFECTS (_p%d)) return NULL_TREE;\n",
3282 i);
3283 if (verbose >= 1)
3284 warning_at (as_a <expr *> (s->match)->ops[i]->location,
3285 "forcing toplevel operand to have no "
3286 "side-effects");
3287 }
3288 for (int i = 0; i <= s->capture_max; ++i)
3289 if (cinfo.info[i].cse_p)
3290 ;
3291 else if (cinfo.info[i].force_no_side_effects_p
3292 && (cinfo.info[i].toplevel_msk
3293 & cinfo.force_no_side_effects) == 0)
3294 {
3295 fprintf_indent (f, indent,
3296 "if (TREE_SIDE_EFFECTS (captures[%d])) "
3297 "return NULL_TREE;\n", i);
3298 if (verbose >= 1)
3299 warning_at (cinfo.info[i].c->location,
3300 "forcing captured operand to have no "
3301 "side-effects");
3302 }
3303 else if ((cinfo.info[i].toplevel_msk
3304 & cinfo.force_no_side_effects) != 0)
3305 /* Mark capture as having no side-effects if we had to verify
3306 that via forced toplevel operand checks. */
3307 cinfo.info[i].force_no_side_effects_p = true;
3308 }
3309 if (gimple)
3310 {
3311 /* Force single-use restriction by only allowing simple
3312 results via setting seq to NULL. */
3313 fprintf_indent (f, indent, "gimple_seq *lseq = seq;\n");
3314 bool first_p = true;
3315 for (int i = 0; i <= s->capture_max; ++i)
3316 if (cinfo.info[i].force_single_use)
3317 {
3318 if (first_p)
3319 {
3320 fprintf_indent (f, indent, "if (lseq\n");
3321 fprintf_indent (f, indent, " && (");
3322 first_p = false;
3323 }
3324 else
3325 {
3326 fprintf (f, "\n");
3327 fprintf_indent (f, indent, " || ");
3328 }
3329 fprintf (f, "!single_use (captures[%d])", i);
3330 }
3331 if (!first_p)
3332 {
3333 fprintf (f, "))\n");
3334 fprintf_indent (f, indent, " lseq = NULL;\n");
3335 }
3336 }
3337 }
3338
3339 if (s->kind == simplify::SIMPLIFY)
3340 fprintf_indent (f, indent, "if (__builtin_expect (!dbg_cnt (match), 0)) return %s;\n",
3341 gimple ? "false" : "NULL_TREE");
3342
3343 fprintf_indent (f, indent, "if (__builtin_expect (dump_file && (dump_flags & TDF_FOLDING), 0)) "
3344 "fprintf (dump_file, \"%s ",
3345 s->kind == simplify::SIMPLIFY
3346 ? "Applying pattern" : "Matching expression");
3347 fprintf (f, "%%s:%%d, %%s:%%d\\n\", ");
3348 output_line_directive (f,
3349 result ? result->location : s->match->location, true,
3350 true);
3351 fprintf (f, ", __FILE__, __LINE__);\n");
3352
3353 if (!result)
3354 {
3355 /* If there is no result then this is a predicate implementation. */
3356 fprintf_indent (f, indent, "return true;\n");
3357 }
3358 else if (gimple)
3359 {
3360 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
3361 in outermost position). */
3362 if (result->type == operand::OP_EXPR
3363 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
3364 result = as_a <expr *> (result)->ops[0];
3365 if (result->type == operand::OP_EXPR)
3366 {
3367 expr *e = as_a <expr *> (result);
3368 id_base *opr = e->operation;
3369 bool is_predicate = false;
3370 /* When we delay operator substituting during lowering of fors we
3371 make sure that for code-gen purposes the effects of each substitute
3372 are the same. Thus just look at that. */
3373 if (user_id *uid = dyn_cast <user_id *> (opr))
3374 opr = uid->substitutes[0];
3375 else if (is_a <predicate_id *> (opr))
3376 is_predicate = true;
3377 if (!is_predicate)
3378 fprintf_indent (f, indent, "res_op->set_op (%s, type, %d);\n",
3379 *e->operation == CONVERT_EXPR
3380 ? "NOP_EXPR" : e->operation->id,
3381 e->ops.length ());
3382 for (unsigned j = 0; j < e->ops.length (); ++j)
3383 {
3384 char dest[32];
3385 if (is_predicate)
3386 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3387 else
3388 snprintf (dest, sizeof (dest), "res_op->ops[%d]", j);
3389 const char *optype
3390 = get_operand_type (opr, j,
3391 "type", e->expr_type,
3392 j == 0 ? NULL
3393 : "TREE_TYPE (res_op->ops[0])");
3394 /* We need to expand GENERIC conditions we captured from
3395 COND_EXPRs and we need to unshare them when substituting
3396 into COND_EXPRs. */
3397 int cond_handling = 0;
3398 if (!is_predicate)
3399 cond_handling = ((*opr == COND_EXPR
3400 || *opr == VEC_COND_EXPR) && j == 0) ? 1 : 2;
3401 e->ops[j]->gen_transform (f, indent, dest, true, 1, optype,
3402 &cinfo, indexes, cond_handling);
3403 }
3404
3405 /* Re-fold the toplevel result. It's basically an embedded
3406 gimple_build w/o actually building the stmt. */
3407 if (!is_predicate)
3408 fprintf_indent (f, indent,
3409 "res_op->resimplify (lseq, valueize);\n");
3410 }
3411 else if (result->type == operand::OP_CAPTURE
3412 || result->type == operand::OP_C_EXPR)
3413 {
3414 fprintf_indent (f, indent, "tree tem;\n");
3415 result->gen_transform (f, indent, "tem", true, 1, "type",
3416 &cinfo, indexes);
3417 fprintf_indent (f, indent, "res_op->set_value (tem);\n");
3418 if (is_a <capture *> (result)
3419 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
3420 {
3421 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
3422 with substituting a capture of that. */
3423 fprintf_indent (f, indent,
3424 "if (COMPARISON_CLASS_P (tem))\n");
3425 fprintf_indent (f, indent,
3426 " {\n");
3427 fprintf_indent (f, indent,
3428 " res_op->ops[0] = TREE_OPERAND (tem, 0);\n");
3429 fprintf_indent (f, indent,
3430 " res_op->ops[1] = TREE_OPERAND (tem, 1);\n");
3431 fprintf_indent (f, indent,
3432 " }\n");
3433 }
3434 }
3435 else
3436 gcc_unreachable ();
3437 fprintf_indent (f, indent, "return true;\n");
3438 }
3439 else /* GENERIC */
3440 {
3441 bool is_predicate = false;
3442 if (result->type == operand::OP_EXPR)
3443 {
3444 expr *e = as_a <expr *> (result);
3445 id_base *opr = e->operation;
3446 /* When we delay operator substituting during lowering of fors we
3447 make sure that for code-gen purposes the effects of each substitute
3448 are the same. Thus just look at that. */
3449 if (user_id *uid = dyn_cast <user_id *> (opr))
3450 opr = uid->substitutes[0];
3451 else if (is_a <predicate_id *> (opr))
3452 is_predicate = true;
3453 /* Search for captures used multiple times in the result expression
3454 and wrap them in a SAVE_EXPR. Allow as many uses as in the
3455 original expression. */
3456 if (!is_predicate)
3457 for (int i = 0; i < s->capture_max + 1; ++i)
3458 {
3459 if (cinfo.info[i].same_as != (unsigned)i
3460 || cinfo.info[i].cse_p)
3461 continue;
3462 if (cinfo.info[i].result_use_count
3463 > cinfo.info[i].match_use_count)
3464 fprintf_indent (f, indent,
3465 "if (! tree_invariant_p (captures[%d])) "
3466 "return NULL_TREE;\n", i);
3467 }
3468 for (unsigned j = 0; j < e->ops.length (); ++j)
3469 {
3470 char dest[32];
3471 if (is_predicate)
3472 snprintf (dest, sizeof (dest), "res_ops[%d]", j);
3473 else
3474 {
3475 fprintf_indent (f, indent, "tree res_op%d;\n", j);
3476 snprintf (dest, sizeof (dest), "res_op%d", j);
3477 }
3478 const char *optype
3479 = get_operand_type (opr, j,
3480 "type", e->expr_type,
3481 j == 0
3482 ? NULL : "TREE_TYPE (res_op0)");
3483 e->ops[j]->gen_transform (f, indent, dest, false, 1, optype,
3484 &cinfo, indexes);
3485 }
3486 if (is_predicate)
3487 fprintf_indent (f, indent, "return true;\n");
3488 else
3489 {
3490 fprintf_indent (f, indent, "tree _r;\n");
3491 /* Re-fold the toplevel result. Use non_lvalue to
3492 build NON_LVALUE_EXPRs so they get properly
3493 ignored when in GIMPLE form. */
3494 if (*opr == NON_LVALUE_EXPR)
3495 fprintf_indent (f, indent,
3496 "_r = non_lvalue_loc (loc, res_op0);\n");
3497 else
3498 {
3499 if (is_a <operator_id *> (opr))
3500 fprintf_indent (f, indent,
3501 "_r = fold_build%d_loc (loc, %s, type",
3502 e->ops.length (),
3503 *e->operation == CONVERT_EXPR
3504 ? "NOP_EXPR" : e->operation->id);
3505 else
3506 fprintf_indent (f, indent,
3507 "_r = maybe_build_call_expr_loc (loc, "
3508 "%s, type, %d", e->operation->id,
3509 e->ops.length());
3510 for (unsigned j = 0; j < e->ops.length (); ++j)
3511 fprintf (f, ", res_op%d", j);
3512 fprintf (f, ");\n");
3513 if (!is_a <operator_id *> (opr))
3514 {
3515 fprintf_indent (f, indent, "if (!_r)\n");
3516 fprintf_indent (f, indent, " return NULL_TREE;\n");
3517 }
3518 }
3519 }
3520 }
3521 else if (result->type == operand::OP_CAPTURE
3522 || result->type == operand::OP_C_EXPR)
3523
3524 {
3525 fprintf_indent (f, indent, "tree _r;\n");
3526 result->gen_transform (f, indent, "_r", false, 1, "type",
3527 &cinfo, indexes);
3528 }
3529 else
3530 gcc_unreachable ();
3531 if (!is_predicate)
3532 {
3533 /* Search for captures not used in the result expression and dependent
3534 on TREE_SIDE_EFFECTS emit omit_one_operand. */
3535 for (int i = 0; i < s->capture_max + 1; ++i)
3536 {
3537 if (cinfo.info[i].same_as != (unsigned)i)
3538 continue;
3539 if (!cinfo.info[i].force_no_side_effects_p
3540 && !cinfo.info[i].expr_p
3541 && cinfo.info[i].result_use_count == 0)
3542 {
3543 fprintf_indent (f, indent,
3544 "if (TREE_SIDE_EFFECTS (captures[%d]))\n",
3545 i);
3546 fprintf_indent (f, indent + 2,
3547 "_r = build2_loc (loc, COMPOUND_EXPR, type, "
3548 "fold_ignored_result (captures[%d]), _r);\n",
3549 i);
3550 }
3551 }
3552 fprintf_indent (f, indent, "return _r;\n");
3553 }
3554 }
3555 }
3556
3557 /* Generate code for the '(if ...)', '(with ..)' and actual transform
3558 step of a '(simplify ...)' or '(match ...)'. This handles everything
3559 that is not part of the decision tree (simplify->match). */
3560
3561 void
3562 dt_simplify::gen (FILE *f, int indent, bool gimple, int depth ATTRIBUTE_UNUSED)
3563 {
3564 fprintf_indent (f, indent, "{\n");
3565 indent += 2;
3566 output_line_directive (f,
3567 s->result ? s->result->location : s->match->location);
3568 if (s->capture_max >= 0)
3569 {
3570 char opname[20];
3571 fprintf_indent (f, indent, "tree captures[%u] ATTRIBUTE_UNUSED = { %s",
3572 s->capture_max + 1, indexes[0]->get_name (opname));
3573
3574 for (int i = 1; i <= s->capture_max; ++i)
3575 {
3576 if (!indexes[i])
3577 break;
3578 fprintf (f, ", %s", indexes[i]->get_name (opname));
3579 }
3580 fprintf (f, " };\n");
3581 }
3582
3583 /* If we have a split-out function for the actual transform, call it. */
3584 if (info && info->fname)
3585 {
3586 if (gimple)
3587 {
3588 fprintf_indent (f, indent, "if (%s (res_op, seq, "
3589 "valueize, type, captures", info->fname);
3590 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3591 if (s->for_subst_vec[i].first->used)
3592 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3593 fprintf (f, "))\n");
3594 fprintf_indent (f, indent, " return true;\n");
3595 }
3596 else
3597 {
3598 fprintf_indent (f, indent, "tree res = %s (loc, type",
3599 info->fname);
3600 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
3601 fprintf (f, ", _p%d", i);
3602 fprintf (f, ", captures");
3603 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3604 {
3605 if (s->for_subst_vec[i].first->used)
3606 fprintf (f, ", %s", s->for_subst_vec[i].second->id);
3607 }
3608 fprintf (f, ");\n");
3609 fprintf_indent (f, indent, "if (res) return res;\n");
3610 }
3611 }
3612 else
3613 {
3614 for (unsigned i = 0; i < s->for_subst_vec.length (); ++i)
3615 {
3616 if (! s->for_subst_vec[i].first->used)
3617 continue;
3618 if (is_a <operator_id *> (s->for_subst_vec[i].second))
3619 fprintf_indent (f, indent, "const enum tree_code %s = %s;\n",
3620 s->for_subst_vec[i].first->id,
3621 s->for_subst_vec[i].second->id);
3622 else if (is_a <fn_id *> (s->for_subst_vec[i].second))
3623 fprintf_indent (f, indent, "const combined_fn %s = %s;\n",
3624 s->for_subst_vec[i].first->id,
3625 s->for_subst_vec[i].second->id);
3626 else
3627 gcc_unreachable ();
3628 }
3629 gen_1 (f, indent, gimple, s->result);
3630 }
3631
3632 indent -= 2;
3633 fprintf_indent (f, indent, "}\n");
3634 }
3635
3636
3637 /* Hash function for finding equivalent transforms. */
3638
3639 hashval_t
3640 sinfo_hashmap_traits::hash (const key_type &v)
3641 {
3642 /* Only bother to compare those originating from the same source pattern. */
3643 return v->s->result->location;
3644 }
3645
3646 /* Compare function for finding equivalent transforms. */
3647
3648 static bool
3649 compare_op (operand *o1, simplify *s1, operand *o2, simplify *s2)
3650 {
3651 if (o1->type != o2->type)
3652 return false;
3653
3654 switch (o1->type)
3655 {
3656 case operand::OP_IF:
3657 {
3658 if_expr *if1 = as_a <if_expr *> (o1);
3659 if_expr *if2 = as_a <if_expr *> (o2);
3660 /* ??? Properly compare c-exprs. */
3661 if (if1->cond != if2->cond)
3662 return false;
3663 if (!compare_op (if1->trueexpr, s1, if2->trueexpr, s2))
3664 return false;
3665 if (if1->falseexpr != if2->falseexpr
3666 || (if1->falseexpr
3667 && !compare_op (if1->falseexpr, s1, if2->falseexpr, s2)))
3668 return false;
3669 return true;
3670 }
3671 case operand::OP_WITH:
3672 {
3673 with_expr *with1 = as_a <with_expr *> (o1);
3674 with_expr *with2 = as_a <with_expr *> (o2);
3675 if (with1->with != with2->with)
3676 return false;
3677 return compare_op (with1->subexpr, s1, with2->subexpr, s2);
3678 }
3679 default:;
3680 }
3681
3682 /* We've hit a result. Time to compare capture-infos - this is required
3683 in addition to the conservative pointer-equivalency of the result IL. */
3684 capture_info cinfo1 (s1, o1, true);
3685 capture_info cinfo2 (s2, o2, true);
3686
3687 if (cinfo1.force_no_side_effects != cinfo2.force_no_side_effects
3688 || cinfo1.info.length () != cinfo2.info.length ())
3689 return false;
3690
3691 for (unsigned i = 0; i < cinfo1.info.length (); ++i)
3692 {
3693 if (cinfo1.info[i].expr_p != cinfo2.info[i].expr_p
3694 || cinfo1.info[i].cse_p != cinfo2.info[i].cse_p
3695 || (cinfo1.info[i].force_no_side_effects_p
3696 != cinfo2.info[i].force_no_side_effects_p)
3697 || cinfo1.info[i].force_single_use != cinfo2.info[i].force_single_use
3698 || cinfo1.info[i].cond_expr_cond_p != cinfo2.info[i].cond_expr_cond_p
3699 /* toplevel_msk is an optimization */
3700 || cinfo1.info[i].result_use_count != cinfo2.info[i].result_use_count
3701 || cinfo1.info[i].same_as != cinfo2.info[i].same_as
3702 /* the pointer back to the capture is for diagnostics only */)
3703 return false;
3704 }
3705
3706 /* ??? Deep-compare the actual result. */
3707 return o1 == o2;
3708 }
3709
3710 bool
3711 sinfo_hashmap_traits::equal_keys (const key_type &v,
3712 const key_type &candidate)
3713 {
3714 return compare_op (v->s->result, v->s, candidate->s->result, candidate->s);
3715 }
3716
3717
3718 /* Main entry to generate code for matching GIMPLE IL off the decision
3719 tree. */
3720
3721 void
3722 decision_tree::gen (FILE *f, bool gimple)
3723 {
3724 sinfo_map_t si;
3725
3726 root->analyze (si);
3727
3728 fprintf (stderr, "%s decision tree has %u leafs, maximum depth %u and "
3729 "a total number of %u nodes\n",
3730 gimple ? "GIMPLE" : "GENERIC",
3731 root->num_leafs, root->max_level, root->total_size);
3732
3733 /* First split out the transform part of equal leafs. */
3734 unsigned rcnt = 0;
3735 unsigned fcnt = 1;
3736 for (sinfo_map_t::iterator iter = si.begin ();
3737 iter != si.end (); ++iter)
3738 {
3739 sinfo *s = (*iter).second;
3740 /* Do not split out single uses. */
3741 if (s->cnt <= 1)
3742 continue;
3743
3744 rcnt += s->cnt - 1;
3745 if (verbose >= 1)
3746 {
3747 fprintf (stderr, "found %u uses of", s->cnt);
3748 output_line_directive (stderr, s->s->s->result->location);
3749 }
3750
3751 /* Generate a split out function with the leaf transform code. */
3752 s->fname = xasprintf ("%s_simplify_%u", gimple ? "gimple" : "generic",
3753 fcnt++);
3754 if (gimple)
3755 fprintf (f, "\nstatic bool\n"
3756 "%s (gimple_match_op *res_op, gimple_seq *seq,\n"
3757 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
3758 " const tree ARG_UNUSED (type), tree *ARG_UNUSED "
3759 "(captures)\n",
3760 s->fname);
3761 else
3762 {
3763 fprintf (f, "\nstatic tree\n"
3764 "%s (location_t ARG_UNUSED (loc), const tree ARG_UNUSED (type),\n",
3765 (*iter).second->fname);
3766 for (unsigned i = 0;
3767 i < as_a <expr *>(s->s->s->match)->ops.length (); ++i)
3768 fprintf (f, " tree ARG_UNUSED (_p%d),", i);
3769 fprintf (f, " tree *captures\n");
3770 }
3771 for (unsigned i = 0; i < s->s->s->for_subst_vec.length (); ++i)
3772 {
3773 if (! s->s->s->for_subst_vec[i].first->used)
3774 continue;
3775 if (is_a <operator_id *> (s->s->s->for_subst_vec[i].second))
3776 fprintf (f, ", const enum tree_code ARG_UNUSED (%s)",
3777 s->s->s->for_subst_vec[i].first->id);
3778 else if (is_a <fn_id *> (s->s->s->for_subst_vec[i].second))
3779 fprintf (f, ", const combined_fn ARG_UNUSED (%s)",
3780 s->s->s->for_subst_vec[i].first->id);
3781 }
3782
3783 fprintf (f, ")\n{\n");
3784 s->s->gen_1 (f, 2, gimple, s->s->s->result);
3785 if (gimple)
3786 fprintf (f, " return false;\n");
3787 else
3788 fprintf (f, " return NULL_TREE;\n");
3789 fprintf (f, "}\n");
3790 }
3791 fprintf (stderr, "removed %u duplicate tails\n", rcnt);
3792
3793 for (unsigned n = 1; n <= 5; ++n)
3794 {
3795 /* First generate split-out functions. */
3796 for (unsigned j = 0; j < root->kids.length (); j++)
3797 {
3798 dt_operand *dop = static_cast<dt_operand *>(root->kids[j]);
3799 expr *e = static_cast<expr *>(dop->op);
3800 if (e->ops.length () != n
3801 /* Builtin simplifications are somewhat premature on
3802 GENERIC. The following drops patterns with outermost
3803 calls. It's easy to emit overloads for function code
3804 though if necessary. */
3805 || (!gimple
3806 && e->operation->kind != id_base::CODE))
3807 continue;
3808
3809 if (gimple)
3810 fprintf (f, "\nstatic bool\n"
3811 "gimple_simplify_%s (gimple_match_op *res_op,"
3812 " gimple_seq *seq,\n"
3813 " tree (*valueize)(tree) "
3814 "ATTRIBUTE_UNUSED,\n"
3815 " code_helper ARG_UNUSED (code), tree "
3816 "ARG_UNUSED (type)\n",
3817 e->operation->id);
3818 else
3819 fprintf (f, "\nstatic tree\n"
3820 "generic_simplify_%s (location_t ARG_UNUSED (loc), enum "
3821 "tree_code ARG_UNUSED (code), const tree ARG_UNUSED (type)",
3822 e->operation->id);
3823 for (unsigned i = 0; i < n; ++i)
3824 fprintf (f, ", tree _p%d", i);
3825 fprintf (f, ")\n");
3826 fprintf (f, "{\n");
3827 dop->gen_kids (f, 2, gimple, 0);
3828 if (gimple)
3829 fprintf (f, " return false;\n");
3830 else
3831 fprintf (f, " return NULL_TREE;\n");
3832 fprintf (f, "}\n");
3833 }
3834
3835 /* Then generate the main entry with the outermost switch and
3836 tail-calls to the split-out functions. */
3837 if (gimple)
3838 fprintf (f, "\nstatic bool\n"
3839 "gimple_simplify (gimple_match_op *res_op, gimple_seq *seq,\n"
3840 " tree (*valueize)(tree) ATTRIBUTE_UNUSED,\n"
3841 " code_helper code, const tree type");
3842 else
3843 fprintf (f, "\ntree\n"
3844 "generic_simplify (location_t loc, enum tree_code code, "
3845 "const tree type ATTRIBUTE_UNUSED");
3846 for (unsigned i = 0; i < n; ++i)
3847 fprintf (f, ", tree _p%d", i);
3848 fprintf (f, ")\n");
3849 fprintf (f, "{\n");
3850
3851 if (gimple)
3852 fprintf (f, " switch (code.get_rep())\n"
3853 " {\n");
3854 else
3855 fprintf (f, " switch (code)\n"
3856 " {\n");
3857 for (unsigned i = 0; i < root->kids.length (); i++)
3858 {
3859 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
3860 expr *e = static_cast<expr *>(dop->op);
3861 if (e->ops.length () != n
3862 /* Builtin simplifications are somewhat premature on
3863 GENERIC. The following drops patterns with outermost
3864 calls. It's easy to emit overloads for function code
3865 though if necessary. */
3866 || (!gimple
3867 && e->operation->kind != id_base::CODE))
3868 continue;
3869
3870 if (*e->operation == CONVERT_EXPR
3871 || *e->operation == NOP_EXPR)
3872 fprintf (f, " CASE_CONVERT:\n");
3873 else
3874 fprintf (f, " case %s%s:\n",
3875 is_a <fn_id *> (e->operation) ? "-" : "",
3876 e->operation->id);
3877 if (gimple)
3878 fprintf (f, " return gimple_simplify_%s (res_op, "
3879 "seq, valueize, code, type", e->operation->id);
3880 else
3881 fprintf (f, " return generic_simplify_%s (loc, code, type",
3882 e->operation->id);
3883 for (unsigned j = 0; j < n; ++j)
3884 fprintf (f, ", _p%d", j);
3885 fprintf (f, ");\n");
3886 }
3887 fprintf (f, " default:;\n"
3888 " }\n");
3889
3890 if (gimple)
3891 fprintf (f, " return false;\n");
3892 else
3893 fprintf (f, " return NULL_TREE;\n");
3894 fprintf (f, "}\n");
3895 }
3896 }
3897
3898 /* Output code to implement the predicate P from the decision tree DT. */
3899
3900 void
3901 write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
3902 {
3903 fprintf (f, "\nbool\n"
3904 "%s%s (tree t%s%s)\n"
3905 "{\n", gimple ? "gimple_" : "tree_", p->id,
3906 p->nargs > 0 ? ", tree *res_ops" : "",
3907 gimple ? ", tree (*valueize)(tree) ATTRIBUTE_UNUSED" : "");
3908 /* Conveniently make 'type' available. */
3909 fprintf_indent (f, 2, "const tree type = TREE_TYPE (t);\n");
3910
3911 if (!gimple)
3912 fprintf_indent (f, 2, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
3913 dt.root->gen_kids (f, 2, gimple, 0);
3914
3915 fprintf_indent (f, 2, "return false;\n"
3916 "}\n");
3917 }
3918
3919 /* Write the common header for the GIMPLE/GENERIC IL matching routines. */
3920
3921 static void
3922 write_header (FILE *f, const char *head)
3923 {
3924 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
3925 fprintf (f, " a IL pattern matching and simplification description. */\n");
3926
3927 /* Include the header instead of writing it awkwardly quoted here. */
3928 fprintf (f, "\n#include \"%s\"\n", head);
3929 }
3930
3931
3932
3933 /* AST parsing. */
3934
3935 class parser
3936 {
3937 public:
3938 parser (cpp_reader *);
3939
3940 private:
3941 const cpp_token *next ();
3942 const cpp_token *peek (unsigned = 1);
3943 const cpp_token *peek_ident (const char * = NULL, unsigned = 1);
3944 const cpp_token *expect (enum cpp_ttype);
3945 const cpp_token *eat_token (enum cpp_ttype);
3946 const char *get_string ();
3947 const char *get_ident ();
3948 const cpp_token *eat_ident (const char *);
3949 const char *get_number ();
3950
3951 unsigned get_internal_capture_id ();
3952
3953 id_base *parse_operation (unsigned char &);
3954 operand *parse_capture (operand *, bool);
3955 operand *parse_expr ();
3956 c_expr *parse_c_expr (cpp_ttype);
3957 operand *parse_op ();
3958
3959 void record_operlist (location_t, user_id *);
3960
3961 void parse_pattern ();
3962 operand *parse_result (operand *, predicate_id *);
3963 void push_simplify (simplify::simplify_kind,
3964 vec<simplify *>&, operand *, operand *);
3965 void parse_simplify (simplify::simplify_kind,
3966 vec<simplify *>&, predicate_id *, operand *);
3967 void parse_for (location_t);
3968 void parse_if (location_t);
3969 void parse_predicates (location_t);
3970 void parse_operator_list (location_t);
3971
3972 void finish_match_operand (operand *);
3973
3974 cpp_reader *r;
3975 vec<c_expr *> active_ifs;
3976 vec<vec<user_id *> > active_fors;
3977 hash_set<user_id *> *oper_lists_set;
3978 vec<user_id *> oper_lists;
3979
3980 cid_map_t *capture_ids;
3981 unsigned last_id;
3982
3983 public:
3984 vec<simplify *> simplifiers;
3985 vec<predicate_id *> user_predicates;
3986 bool parsing_match_operand;
3987 };
3988
3989 /* Lexing helpers. */
3990
3991 /* Read the next non-whitespace token from R. */
3992
3993 const cpp_token *
3994 parser::next ()
3995 {
3996 const cpp_token *token;
3997 do
3998 {
3999 token = cpp_get_token (r);
4000 }
4001 while (token->type == CPP_PADDING);
4002 return token;
4003 }
4004
4005 /* Peek at the next non-whitespace token from R. */
4006
4007 const cpp_token *
4008 parser::peek (unsigned num)
4009 {
4010 const cpp_token *token;
4011 unsigned i = 0;
4012 do
4013 {
4014 token = cpp_peek_token (r, i++);
4015 }
4016 while (token->type == CPP_PADDING
4017 || (--num > 0));
4018 /* If we peek at EOF this is a fatal error as it leaves the
4019 cpp_reader in unusable state. Assume we really wanted a
4020 token and thus this EOF is unexpected. */
4021 if (token->type == CPP_EOF)
4022 fatal_at (token, "unexpected end of file");
4023 return token;
4024 }
4025
4026 /* Peek at the next identifier token (or return NULL if the next
4027 token is not an identifier or equal to ID if supplied). */
4028
4029 const cpp_token *
4030 parser::peek_ident (const char *id, unsigned num)
4031 {
4032 const cpp_token *token = peek (num);
4033 if (token->type != CPP_NAME)
4034 return 0;
4035
4036 if (id == 0)
4037 return token;
4038
4039 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
4040 if (strcmp (id, t) == 0)
4041 return token;
4042
4043 return 0;
4044 }
4045
4046 /* Read the next token from R and assert it is of type TK. */
4047
4048 const cpp_token *
4049 parser::expect (enum cpp_ttype tk)
4050 {
4051 const cpp_token *token = next ();
4052 if (token->type != tk)
4053 fatal_at (token, "expected %s, got %s",
4054 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
4055
4056 return token;
4057 }
4058
4059 /* Consume the next token from R and assert it is of type TK. */
4060
4061 const cpp_token *
4062 parser::eat_token (enum cpp_ttype tk)
4063 {
4064 return expect (tk);
4065 }
4066
4067 /* Read the next token from R and assert it is of type CPP_STRING and
4068 return its value. */
4069
4070 const char *
4071 parser::get_string ()
4072 {
4073 const cpp_token *token = expect (CPP_STRING);
4074 return (const char *)token->val.str.text;
4075 }
4076
4077 /* Read the next token from R and assert it is of type CPP_NAME and
4078 return its value. */
4079
4080 const char *
4081 parser::get_ident ()
4082 {
4083 const cpp_token *token = expect (CPP_NAME);
4084 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
4085 }
4086
4087 /* Eat an identifier token with value S from R. */
4088
4089 const cpp_token *
4090 parser::eat_ident (const char *s)
4091 {
4092 const cpp_token *token = peek ();
4093 const char *t = get_ident ();
4094 if (strcmp (s, t) != 0)
4095 fatal_at (token, "expected '%s' got '%s'\n", s, t);
4096 return token;
4097 }
4098
4099 /* Read the next token from R and assert it is of type CPP_NUMBER and
4100 return its value. */
4101
4102 const char *
4103 parser::get_number ()
4104 {
4105 const cpp_token *token = expect (CPP_NUMBER);
4106 return (const char *)token->val.str.text;
4107 }
4108
4109 /* Return a capture ID that can be used internally. */
4110
4111 unsigned
4112 parser::get_internal_capture_id ()
4113 {
4114 unsigned newid = capture_ids->elements ();
4115 /* Big enough for a 32-bit UINT_MAX plus prefix. */
4116 char id[13];
4117 bool existed;
4118 snprintf (id, sizeof (id), "__%u", newid);
4119 capture_ids->get_or_insert (xstrdup (id), &existed);
4120 if (existed)
4121 fatal ("reserved capture id '%s' already used", id);
4122 return newid;
4123 }
4124
4125 /* Record an operator-list use for transparent for handling. */
4126
4127 void
4128 parser::record_operlist (location_t loc, user_id *p)
4129 {
4130 if (!oper_lists_set->add (p))
4131 {
4132 if (!oper_lists.is_empty ()
4133 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
4134 fatal_at (loc, "User-defined operator list does not have the "
4135 "same number of entries as others used in the pattern");
4136 oper_lists.safe_push (p);
4137 }
4138 }
4139
4140 /* Parse the operator ID, special-casing convert?, convert1? and
4141 convert2? */
4142
4143 id_base *
4144 parser::parse_operation (unsigned char &opt_grp)
4145 {
4146 const cpp_token *id_tok = peek ();
4147 char *alt_id = NULL;
4148 const char *id = get_ident ();
4149 const cpp_token *token = peek ();
4150 opt_grp = 0;
4151 if (token->type == CPP_QUERY
4152 && !(token->flags & PREV_WHITE))
4153 {
4154 if (!parsing_match_operand)
4155 fatal_at (id_tok, "conditional convert can only be used in "
4156 "match expression");
4157 if (ISDIGIT (id[strlen (id) - 1]))
4158 {
4159 opt_grp = id[strlen (id) - 1] - '0' + 1;
4160 alt_id = xstrdup (id);
4161 alt_id[strlen (id) - 1] = '\0';
4162 if (opt_grp == 1)
4163 fatal_at (id_tok, "use '%s?' here", alt_id);
4164 }
4165 else
4166 opt_grp = 1;
4167 eat_token (CPP_QUERY);
4168 }
4169 id_base *op = get_operator (alt_id ? alt_id : id);
4170 if (!op)
4171 fatal_at (id_tok, "unknown operator %s", alt_id ? alt_id : id);
4172 if (alt_id)
4173 free (alt_id);
4174 user_id *p = dyn_cast<user_id *> (op);
4175 if (p && p->is_oper_list)
4176 {
4177 if (active_fors.length() == 0)
4178 record_operlist (id_tok->src_loc, p);
4179 else
4180 fatal_at (id_tok, "operator-list %s cannot be expanded inside 'for'", id);
4181 }
4182 return op;
4183 }
4184
4185 /* Parse a capture.
4186 capture = '@'<number> */
4187
4188 class operand *
4189 parser::parse_capture (operand *op, bool require_existing)
4190 {
4191 location_t src_loc = eat_token (CPP_ATSIGN)->src_loc;
4192 const cpp_token *token = peek ();
4193 const char *id = NULL;
4194 bool value_match = false;
4195 /* For matches parse @@ as a value-match denoting the prevailing operand. */
4196 if (token->type == CPP_ATSIGN
4197 && ! (token->flags & PREV_WHITE)
4198 && parsing_match_operand)
4199 {
4200 eat_token (CPP_ATSIGN);
4201 token = peek ();
4202 value_match = true;
4203 }
4204 if (token->type == CPP_NUMBER)
4205 id = get_number ();
4206 else if (token->type == CPP_NAME)
4207 id = get_ident ();
4208 else
4209 fatal_at (token, "expected number or identifier");
4210 unsigned next_id = capture_ids->elements ();
4211 bool existed;
4212 unsigned &num = capture_ids->get_or_insert (id, &existed);
4213 if (!existed)
4214 {
4215 if (require_existing)
4216 fatal_at (src_loc, "unknown capture id");
4217 num = next_id;
4218 }
4219 return new capture (src_loc, num, op, value_match);
4220 }
4221
4222 /* Parse an expression
4223 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
4224
4225 class operand *
4226 parser::parse_expr ()
4227 {
4228 const cpp_token *token = peek ();
4229 unsigned char opt_grp;
4230 expr *e = new expr (parse_operation (opt_grp), token->src_loc);
4231 token = peek ();
4232 operand *op;
4233 bool is_commutative = false;
4234 bool force_capture = false;
4235 const char *expr_type = NULL;
4236
4237 if (token->type == CPP_COLON
4238 && !(token->flags & PREV_WHITE))
4239 {
4240 eat_token (CPP_COLON);
4241 token = peek ();
4242 if (token->type == CPP_NAME
4243 && !(token->flags & PREV_WHITE))
4244 {
4245 const char *s = get_ident ();
4246 if (!parsing_match_operand)
4247 expr_type = s;
4248 else
4249 {
4250 const char *sp = s;
4251 while (*sp)
4252 {
4253 if (*sp == 'c')
4254 {
4255 if (operator_id *o
4256 = dyn_cast<operator_id *> (e->operation))
4257 {
4258 if (!commutative_tree_code (o->code)
4259 && !comparison_code_p (o->code))
4260 fatal_at (token, "operation is not commutative");
4261 }
4262 else if (user_id *p = dyn_cast<user_id *> (e->operation))
4263 for (unsigned i = 0;
4264 i < p->substitutes.length (); ++i)
4265 {
4266 if (operator_id *q
4267 = dyn_cast<operator_id *> (p->substitutes[i]))
4268 {
4269 if (!commutative_tree_code (q->code)
4270 && !comparison_code_p (q->code))
4271 fatal_at (token, "operation %s is not "
4272 "commutative", q->id);
4273 }
4274 }
4275 is_commutative = true;
4276 }
4277 else if (*sp == 'C')
4278 is_commutative = true;
4279 else if (*sp == 's')
4280 {
4281 e->force_single_use = true;
4282 force_capture = true;
4283 }
4284 else
4285 fatal_at (token, "flag %c not recognized", *sp);
4286 sp++;
4287 }
4288 }
4289 token = peek ();
4290 }
4291 else
4292 fatal_at (token, "expected flag or type specifying identifier");
4293 }
4294
4295 if (token->type == CPP_ATSIGN
4296 && !(token->flags & PREV_WHITE))
4297 op = parse_capture (e, false);
4298 else if (force_capture)
4299 {
4300 unsigned num = get_internal_capture_id ();
4301 op = new capture (token->src_loc, num, e, false);
4302 }
4303 else
4304 op = e;
4305 do
4306 {
4307 token = peek ();
4308 if (token->type == CPP_CLOSE_PAREN)
4309 {
4310 if (e->operation->nargs != -1
4311 && e->operation->nargs != (int) e->ops.length ())
4312 fatal_at (token, "'%s' expects %u operands, not %u",
4313 e->operation->id, e->operation->nargs, e->ops.length ());
4314 if (is_commutative)
4315 {
4316 if (e->ops.length () == 2
4317 || commutative_op (e->operation) >= 0)
4318 e->is_commutative = true;
4319 else
4320 fatal_at (token, "only binary operators or functions with "
4321 "two arguments can be marked commutative, "
4322 "unless the operation is known to be inherently "
4323 "commutative");
4324 }
4325 e->expr_type = expr_type;
4326 if (opt_grp != 0)
4327 {
4328 if (e->ops.length () != 1)
4329 fatal_at (token, "only unary operations can be conditional");
4330 e->opt_grp = opt_grp;
4331 }
4332 return op;
4333 }
4334 else if (!(token->flags & PREV_WHITE))
4335 fatal_at (token, "expected expression operand");
4336
4337 e->append_op (parse_op ());
4338 }
4339 while (1);
4340 }
4341
4342 /* Lex native C code delimited by START recording the preprocessing tokens
4343 for later processing.
4344 c_expr = ('{'|'(') <pp token>... ('}'|')') */
4345
4346 c_expr *
4347 parser::parse_c_expr (cpp_ttype start)
4348 {
4349 const cpp_token *token;
4350 cpp_ttype end;
4351 unsigned opencnt;
4352 vec<cpp_token> code = vNULL;
4353 unsigned nr_stmts = 0;
4354 location_t loc = eat_token (start)->src_loc;
4355 if (start == CPP_OPEN_PAREN)
4356 end = CPP_CLOSE_PAREN;
4357 else if (start == CPP_OPEN_BRACE)
4358 end = CPP_CLOSE_BRACE;
4359 else
4360 gcc_unreachable ();
4361 opencnt = 1;
4362 do
4363 {
4364 token = next ();
4365
4366 /* Count brace pairs to find the end of the expr to match. */
4367 if (token->type == start)
4368 opencnt++;
4369 else if (token->type == end
4370 && --opencnt == 0)
4371 break;
4372 else if (token->type == CPP_EOF)
4373 fatal_at (token, "unexpected end of file");
4374
4375 /* This is a lame way of counting the number of statements. */
4376 if (token->type == CPP_SEMICOLON)
4377 nr_stmts++;
4378
4379 /* If this is possibly a user-defined identifier mark it used. */
4380 if (token->type == CPP_NAME)
4381 {
4382 id_base *idb = get_operator ((const char *)CPP_HASHNODE
4383 (token->val.node.node)->ident.str);
4384 user_id *p;
4385 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
4386 record_operlist (token->src_loc, p);
4387 }
4388
4389 /* Record the token. */
4390 code.safe_push (*token);
4391 }
4392 while (1);
4393 return new c_expr (r, loc, code, nr_stmts, vNULL, capture_ids);
4394 }
4395
4396 /* Parse an operand which is either an expression, a predicate or
4397 a standalone capture.
4398 op = predicate | expr | c_expr | capture */
4399
4400 class operand *
4401 parser::parse_op ()
4402 {
4403 const cpp_token *token = peek ();
4404 class operand *op = NULL;
4405 if (token->type == CPP_OPEN_PAREN)
4406 {
4407 eat_token (CPP_OPEN_PAREN);
4408 op = parse_expr ();
4409 eat_token (CPP_CLOSE_PAREN);
4410 }
4411 else if (token->type == CPP_OPEN_BRACE)
4412 {
4413 op = parse_c_expr (CPP_OPEN_BRACE);
4414 }
4415 else
4416 {
4417 /* Remaining ops are either empty or predicates */
4418 if (token->type == CPP_NAME)
4419 {
4420 const char *id = get_ident ();
4421 id_base *opr = get_operator (id);
4422 if (!opr)
4423 fatal_at (token, "expected predicate name");
4424 if (operator_id *code1 = dyn_cast <operator_id *> (opr))
4425 {
4426 if (code1->nargs != 0)
4427 fatal_at (token, "using an operator with operands as predicate");
4428 /* Parse the zero-operand operator "predicates" as
4429 expression. */
4430 op = new expr (opr, token->src_loc);
4431 }
4432 else if (user_id *code2 = dyn_cast <user_id *> (opr))
4433 {
4434 if (code2->nargs != 0)
4435 fatal_at (token, "using an operator with operands as predicate");
4436 /* Parse the zero-operand operator "predicates" as
4437 expression. */
4438 op = new expr (opr, token->src_loc);
4439 }
4440 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
4441 op = new predicate (p, token->src_loc);
4442 else
4443 fatal_at (token, "using an unsupported operator as predicate");
4444 if (!parsing_match_operand)
4445 fatal_at (token, "predicates are only allowed in match expression");
4446 token = peek ();
4447 if (token->flags & PREV_WHITE)
4448 return op;
4449 }
4450 else if (token->type != CPP_COLON
4451 && token->type != CPP_ATSIGN)
4452 fatal_at (token, "expected expression or predicate");
4453 /* optionally followed by a capture and a predicate. */
4454 if (token->type == CPP_COLON)
4455 fatal_at (token, "not implemented: predicate on leaf operand");
4456 if (token->type == CPP_ATSIGN)
4457 op = parse_capture (op, !parsing_match_operand);
4458 }
4459
4460 return op;
4461 }
4462
4463 /* Create a new simplify from the current parsing state and MATCH,
4464 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
4465
4466 void
4467 parser::push_simplify (simplify::simplify_kind kind,
4468 vec<simplify *>& simplifiers,
4469 operand *match, operand *result)
4470 {
4471 /* Build and push a temporary for operator list uses in expressions. */
4472 if (!oper_lists.is_empty ())
4473 active_fors.safe_push (oper_lists);
4474
4475 simplifiers.safe_push
4476 (new simplify (kind, last_id++, match, result,
4477 active_fors.copy (), capture_ids));
4478
4479 if (!oper_lists.is_empty ())
4480 active_fors.pop ();
4481 }
4482
4483 /* Parse
4484 <result-op> = <op> | <if> | <with>
4485 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
4486 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
4487 and return it. */
4488
4489 operand *
4490 parser::parse_result (operand *result, predicate_id *matcher)
4491 {
4492 const cpp_token *token = peek ();
4493 if (token->type != CPP_OPEN_PAREN)
4494 return parse_op ();
4495
4496 eat_token (CPP_OPEN_PAREN);
4497 if (peek_ident ("if"))
4498 {
4499 eat_ident ("if");
4500 if_expr *ife = new if_expr (token->src_loc);
4501 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4502 if (peek ()->type == CPP_OPEN_PAREN)
4503 {
4504 ife->trueexpr = parse_result (result, matcher);
4505 if (peek ()->type == CPP_OPEN_PAREN)
4506 ife->falseexpr = parse_result (result, matcher);
4507 else if (peek ()->type != CPP_CLOSE_PAREN)
4508 ife->falseexpr = parse_op ();
4509 }
4510 else if (peek ()->type != CPP_CLOSE_PAREN)
4511 {
4512 ife->trueexpr = parse_op ();
4513 if (peek ()->type == CPP_OPEN_PAREN)
4514 ife->falseexpr = parse_result (result, matcher);
4515 else if (peek ()->type != CPP_CLOSE_PAREN)
4516 ife->falseexpr = parse_op ();
4517 }
4518 /* If this if is immediately closed then it contains a
4519 manual matcher or is part of a predicate definition. */
4520 else /* if (peek ()->type == CPP_CLOSE_PAREN) */
4521 {
4522 if (!matcher)
4523 fatal_at (peek (), "manual transform not implemented");
4524 ife->trueexpr = result;
4525 }
4526 eat_token (CPP_CLOSE_PAREN);
4527 return ife;
4528 }
4529 else if (peek_ident ("with"))
4530 {
4531 eat_ident ("with");
4532 with_expr *withe = new with_expr (token->src_loc);
4533 /* Parse (with c-expr expr) as (if-with (true) expr). */
4534 withe->with = parse_c_expr (CPP_OPEN_BRACE);
4535 withe->with->nr_stmts = 0;
4536 withe->subexpr = parse_result (result, matcher);
4537 eat_token (CPP_CLOSE_PAREN);
4538 return withe;
4539 }
4540 else if (peek_ident ("switch"))
4541 {
4542 token = eat_ident ("switch");
4543 location_t ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4544 eat_ident ("if");
4545 if_expr *ife = new if_expr (ifloc);
4546 operand *res = ife;
4547 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4548 if (peek ()->type == CPP_OPEN_PAREN)
4549 ife->trueexpr = parse_result (result, matcher);
4550 else
4551 ife->trueexpr = parse_op ();
4552 eat_token (CPP_CLOSE_PAREN);
4553 if (peek ()->type != CPP_OPEN_PAREN
4554 || !peek_ident ("if", 2))
4555 fatal_at (token, "switch can be implemented with a single if");
4556 while (peek ()->type != CPP_CLOSE_PAREN)
4557 {
4558 if (peek ()->type == CPP_OPEN_PAREN)
4559 {
4560 if (peek_ident ("if", 2))
4561 {
4562 ifloc = eat_token (CPP_OPEN_PAREN)->src_loc;
4563 eat_ident ("if");
4564 ife->falseexpr = new if_expr (ifloc);
4565 ife = as_a <if_expr *> (ife->falseexpr);
4566 ife->cond = parse_c_expr (CPP_OPEN_PAREN);
4567 if (peek ()->type == CPP_OPEN_PAREN)
4568 ife->trueexpr = parse_result (result, matcher);
4569 else
4570 ife->trueexpr = parse_op ();
4571 eat_token (CPP_CLOSE_PAREN);
4572 }
4573 else
4574 {
4575 /* switch default clause */
4576 ife->falseexpr = parse_result (result, matcher);
4577 eat_token (CPP_CLOSE_PAREN);
4578 return res;
4579 }
4580 }
4581 else
4582 {
4583 /* switch default clause */
4584 ife->falseexpr = parse_op ();
4585 eat_token (CPP_CLOSE_PAREN);
4586 return res;
4587 }
4588 }
4589 eat_token (CPP_CLOSE_PAREN);
4590 return res;
4591 }
4592 else
4593 {
4594 operand *op = result;
4595 if (!matcher)
4596 op = parse_expr ();
4597 eat_token (CPP_CLOSE_PAREN);
4598 return op;
4599 }
4600 }
4601
4602 /* Parse
4603 simplify = 'simplify' <expr> <result-op>
4604 or
4605 match = 'match' <ident> <expr> [<result-op>]
4606 and fill SIMPLIFIERS with the results. */
4607
4608 void
4609 parser::parse_simplify (simplify::simplify_kind kind,
4610 vec<simplify *>& simplifiers, predicate_id *matcher,
4611 operand *result)
4612 {
4613 /* Reset the capture map. */
4614 if (!capture_ids)
4615 capture_ids = new cid_map_t;
4616 /* Reset oper_lists and set. */
4617 hash_set <user_id *> olist;
4618 oper_lists_set = &olist;
4619 oper_lists = vNULL;
4620
4621 const cpp_token *loc = peek ();
4622 parsing_match_operand = true;
4623 class operand *match = parse_op ();
4624 finish_match_operand (match);
4625 parsing_match_operand = false;
4626 if (match->type == operand::OP_CAPTURE && !matcher)
4627 fatal_at (loc, "outermost expression cannot be captured");
4628 if (match->type == operand::OP_EXPR
4629 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
4630 fatal_at (loc, "outermost expression cannot be a predicate");
4631
4632 /* Splice active_ifs onto result and continue parsing the
4633 "then" expr. */
4634 if_expr *active_if = NULL;
4635 for (int i = active_ifs.length (); i > 0; --i)
4636 {
4637 if_expr *ifc = new if_expr (active_ifs[i-1]->location);
4638 ifc->cond = active_ifs[i-1];
4639 ifc->trueexpr = active_if;
4640 active_if = ifc;
4641 }
4642 if_expr *outermost_if = active_if;
4643 while (active_if && active_if->trueexpr)
4644 active_if = as_a <if_expr *> (active_if->trueexpr);
4645
4646 const cpp_token *token = peek ();
4647
4648 /* If this if is immediately closed then it is part of a predicate
4649 definition. Push it. */
4650 if (token->type == CPP_CLOSE_PAREN)
4651 {
4652 if (!matcher)
4653 fatal_at (token, "expected transform expression");
4654 if (active_if)
4655 {
4656 active_if->trueexpr = result;
4657 result = outermost_if;
4658 }
4659 push_simplify (kind, simplifiers, match, result);
4660 return;
4661 }
4662
4663 operand *tem = parse_result (result, matcher);
4664 if (active_if)
4665 {
4666 active_if->trueexpr = tem;
4667 result = outermost_if;
4668 }
4669 else
4670 result = tem;
4671
4672 push_simplify (kind, simplifiers, match, result);
4673 }
4674
4675 /* Parsing of the outer control structures. */
4676
4677 /* Parse a for expression
4678 for = '(' 'for' <subst>... <pattern> ')'
4679 subst = <ident> '(' <ident>... ')' */
4680
4681 void
4682 parser::parse_for (location_t)
4683 {
4684 auto_vec<const cpp_token *> user_id_tokens;
4685 vec<user_id *> user_ids = vNULL;
4686 const cpp_token *token;
4687 unsigned min_n_opers = 0, max_n_opers = 0;
4688
4689 while (1)
4690 {
4691 token = peek ();
4692 if (token->type != CPP_NAME)
4693 break;
4694
4695 /* Insert the user defined operators into the operator hash. */
4696 const char *id = get_ident ();
4697 if (get_operator (id, true) != NULL)
4698 fatal_at (token, "operator already defined");
4699 user_id *op = new user_id (id);
4700 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4701 *slot = op;
4702 user_ids.safe_push (op);
4703 user_id_tokens.safe_push (token);
4704
4705 eat_token (CPP_OPEN_PAREN);
4706
4707 int arity = -1;
4708 while ((token = peek_ident ()) != 0)
4709 {
4710 const char *oper = get_ident ();
4711 id_base *idb = get_operator (oper, true);
4712 if (idb == NULL)
4713 fatal_at (token, "no such operator '%s'", oper);
4714
4715 if (arity == -1)
4716 arity = idb->nargs;
4717 else if (idb->nargs == -1)
4718 ;
4719 else if (idb->nargs != arity)
4720 fatal_at (token, "operator '%s' with arity %d does not match "
4721 "others with arity %d", oper, idb->nargs, arity);
4722
4723 user_id *p = dyn_cast<user_id *> (idb);
4724 if (p)
4725 {
4726 if (p->is_oper_list)
4727 op->substitutes.safe_splice (p->substitutes);
4728 else
4729 fatal_at (token, "iterator cannot be used as operator-list");
4730 }
4731 else
4732 op->substitutes.safe_push (idb);
4733 }
4734 op->nargs = arity;
4735 token = expect (CPP_CLOSE_PAREN);
4736
4737 unsigned nsubstitutes = op->substitutes.length ();
4738 if (nsubstitutes == 0)
4739 fatal_at (token, "A user-defined operator must have at least "
4740 "one substitution");
4741 if (max_n_opers == 0)
4742 {
4743 min_n_opers = nsubstitutes;
4744 max_n_opers = nsubstitutes;
4745 }
4746 else
4747 {
4748 if (nsubstitutes % min_n_opers != 0
4749 && min_n_opers % nsubstitutes != 0)
4750 fatal_at (token, "All user-defined identifiers must have a "
4751 "multiple number of operator substitutions of the "
4752 "smallest number of substitutions");
4753 if (nsubstitutes < min_n_opers)
4754 min_n_opers = nsubstitutes;
4755 else if (nsubstitutes > max_n_opers)
4756 max_n_opers = nsubstitutes;
4757 }
4758 }
4759
4760 unsigned n_ids = user_ids.length ();
4761 if (n_ids == 0)
4762 fatal_at (token, "for requires at least one user-defined identifier");
4763
4764 token = peek ();
4765 if (token->type == CPP_CLOSE_PAREN)
4766 fatal_at (token, "no pattern defined in for");
4767
4768 active_fors.safe_push (user_ids);
4769 while (1)
4770 {
4771 token = peek ();
4772 if (token->type == CPP_CLOSE_PAREN)
4773 break;
4774 parse_pattern ();
4775 }
4776 active_fors.pop ();
4777
4778 /* Remove user-defined operators from the hash again. */
4779 for (unsigned i = 0; i < user_ids.length (); ++i)
4780 {
4781 if (!user_ids[i]->used)
4782 warning_at (user_id_tokens[i],
4783 "operator %s defined but not used", user_ids[i]->id);
4784 operators->remove_elt (user_ids[i]);
4785 }
4786 }
4787
4788 /* Parse an identifier associated with a list of operators.
4789 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
4790
4791 void
4792 parser::parse_operator_list (location_t)
4793 {
4794 const cpp_token *token = peek ();
4795 const char *id = get_ident ();
4796
4797 if (get_operator (id, true) != 0)
4798 fatal_at (token, "operator %s already defined", id);
4799
4800 user_id *op = new user_id (id, true);
4801 int arity = -1;
4802
4803 while ((token = peek_ident ()) != 0)
4804 {
4805 token = peek ();
4806 const char *oper = get_ident ();
4807 id_base *idb = get_operator (oper, true);
4808
4809 if (idb == 0)
4810 fatal_at (token, "no such operator '%s'", oper);
4811
4812 if (arity == -1)
4813 arity = idb->nargs;
4814 else if (idb->nargs == -1)
4815 ;
4816 else if (arity != idb->nargs)
4817 fatal_at (token, "operator '%s' with arity %d does not match "
4818 "others with arity %d", oper, idb->nargs, arity);
4819
4820 /* We allow composition of multiple operator lists. */
4821 if (user_id *p = dyn_cast<user_id *> (idb))
4822 op->substitutes.safe_splice (p->substitutes);
4823 else
4824 op->substitutes.safe_push (idb);
4825 }
4826
4827 // Check that there is no junk after id-list
4828 token = peek();
4829 if (token->type != CPP_CLOSE_PAREN)
4830 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
4831
4832 if (op->substitutes.length () == 0)
4833 fatal_at (token, "operator-list cannot be empty");
4834
4835 op->nargs = arity;
4836 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
4837 *slot = op;
4838 }
4839
4840 /* Parse an outer if expression.
4841 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
4842
4843 void
4844 parser::parse_if (location_t)
4845 {
4846 c_expr *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
4847
4848 const cpp_token *token = peek ();
4849 if (token->type == CPP_CLOSE_PAREN)
4850 fatal_at (token, "no pattern defined in if");
4851
4852 active_ifs.safe_push (ifexpr);
4853 while (1)
4854 {
4855 token = peek ();
4856 if (token->type == CPP_CLOSE_PAREN)
4857 break;
4858
4859 parse_pattern ();
4860 }
4861 active_ifs.pop ();
4862 }
4863
4864 /* Parse a list of predefined predicate identifiers.
4865 preds = '(' 'define_predicates' <ident>... ')' */
4866
4867 void
4868 parser::parse_predicates (location_t)
4869 {
4870 do
4871 {
4872 const cpp_token *token = peek ();
4873 if (token->type != CPP_NAME)
4874 break;
4875
4876 add_predicate (get_ident ());
4877 }
4878 while (1);
4879 }
4880
4881 /* Parse outer control structures.
4882 pattern = <preds>|<for>|<if>|<simplify>|<match> */
4883
4884 void
4885 parser::parse_pattern ()
4886 {
4887 /* All clauses start with '('. */
4888 eat_token (CPP_OPEN_PAREN);
4889 const cpp_token *token = peek ();
4890 const char *id = get_ident ();
4891 if (strcmp (id, "simplify") == 0)
4892 {
4893 parse_simplify (simplify::SIMPLIFY, simplifiers, NULL, NULL);
4894 capture_ids = NULL;
4895 }
4896 else if (strcmp (id, "match") == 0)
4897 {
4898 bool with_args = false;
4899 location_t e_loc = peek ()->src_loc;
4900 if (peek ()->type == CPP_OPEN_PAREN)
4901 {
4902 eat_token (CPP_OPEN_PAREN);
4903 with_args = true;
4904 }
4905 const char *name = get_ident ();
4906 id_base *id1 = get_operator (name);
4907 predicate_id *p;
4908 if (!id1)
4909 {
4910 p = add_predicate (name);
4911 user_predicates.safe_push (p);
4912 }
4913 else if ((p = dyn_cast <predicate_id *> (id1)))
4914 ;
4915 else
4916 fatal_at (token, "cannot add a match to a non-predicate ID");
4917 /* Parse (match <id> <arg>... (match-expr)) here. */
4918 expr *e = NULL;
4919 if (with_args)
4920 {
4921 capture_ids = new cid_map_t;
4922 e = new expr (p, e_loc);
4923 while (peek ()->type == CPP_ATSIGN)
4924 e->append_op (parse_capture (NULL, false));
4925 eat_token (CPP_CLOSE_PAREN);
4926 }
4927 if (p->nargs != -1
4928 && ((e && e->ops.length () != (unsigned)p->nargs)
4929 || (!e && p->nargs != 0)))
4930 fatal_at (token, "non-matching number of match operands");
4931 p->nargs = e ? e->ops.length () : 0;
4932 parse_simplify (simplify::MATCH, p->matchers, p, e);
4933 capture_ids = NULL;
4934 }
4935 else if (strcmp (id, "for") == 0)
4936 parse_for (token->src_loc);
4937 else if (strcmp (id, "if") == 0)
4938 parse_if (token->src_loc);
4939 else if (strcmp (id, "define_predicates") == 0)
4940 {
4941 if (active_ifs.length () > 0
4942 || active_fors.length () > 0)
4943 fatal_at (token, "define_predicates inside if or for is not supported");
4944 parse_predicates (token->src_loc);
4945 }
4946 else if (strcmp (id, "define_operator_list") == 0)
4947 {
4948 if (active_ifs.length () > 0
4949 || active_fors.length () > 0)
4950 fatal_at (token, "operator-list inside if or for is not supported");
4951 parse_operator_list (token->src_loc);
4952 }
4953 else
4954 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
4955 active_ifs.length () == 0 && active_fors.length () == 0
4956 ? "'define_predicates', " : "");
4957
4958 eat_token (CPP_CLOSE_PAREN);
4959 }
4960
4961 /* Helper for finish_match_operand, collecting captures of OP in CPTS
4962 recursively. */
4963
4964 static void
4965 walk_captures (operand *op, vec<vec<capture *> > cpts)
4966 {
4967 if (! op)
4968 return;
4969
4970 if (capture *c = dyn_cast <capture *> (op))
4971 {
4972 cpts[c->where].safe_push (c);
4973 walk_captures (c->what, cpts);
4974 }
4975 else if (expr *e = dyn_cast <expr *> (op))
4976 for (unsigned i = 0; i < e->ops.length (); ++i)
4977 walk_captures (e->ops[i], cpts);
4978 }
4979
4980 /* Finish up OP which is a match operand. */
4981
4982 void
4983 parser::finish_match_operand (operand *op)
4984 {
4985 /* Look for matching captures, diagnose mis-uses of @@ and apply
4986 early lowering and distribution of value_match. */
4987 auto_vec<vec<capture *> > cpts;
4988 cpts.safe_grow_cleared (capture_ids->elements ());
4989 walk_captures (op, cpts);
4990 for (unsigned i = 0; i < cpts.length (); ++i)
4991 {
4992 capture *value_match = NULL;
4993 for (unsigned j = 0; j < cpts[i].length (); ++j)
4994 {
4995 if (cpts[i][j]->value_match)
4996 {
4997 if (value_match)
4998 fatal_at (cpts[i][j]->location, "duplicate @@");
4999 value_match = cpts[i][j];
5000 }
5001 }
5002 if (cpts[i].length () == 1 && value_match)
5003 fatal_at (value_match->location, "@@ without a matching capture");
5004 if (value_match)
5005 {
5006 /* Duplicate prevailing capture with the existing ID, create
5007 a fake ID and rewrite all captures to use it. This turns
5008 @@1 into @__<newid>@1 and @1 into @__<newid>. */
5009 value_match->what = new capture (value_match->location,
5010 value_match->where,
5011 value_match->what, false);
5012 /* Create a fake ID and rewrite all captures to use it. */
5013 unsigned newid = get_internal_capture_id ();
5014 for (unsigned j = 0; j < cpts[i].length (); ++j)
5015 {
5016 cpts[i][j]->where = newid;
5017 cpts[i][j]->value_match = true;
5018 }
5019 }
5020 cpts[i].release ();
5021 }
5022 }
5023
5024 /* Main entry of the parser. Repeatedly parse outer control structures. */
5025
5026 parser::parser (cpp_reader *r_)
5027 {
5028 r = r_;
5029 active_ifs = vNULL;
5030 active_fors = vNULL;
5031 simplifiers = vNULL;
5032 oper_lists_set = NULL;
5033 oper_lists = vNULL;
5034 capture_ids = NULL;
5035 user_predicates = vNULL;
5036 parsing_match_operand = false;
5037 last_id = 0;
5038
5039 const cpp_token *token = next ();
5040 while (token->type != CPP_EOF)
5041 {
5042 _cpp_backup_tokens (r, 1);
5043 parse_pattern ();
5044 token = next ();
5045 }
5046 }
5047
5048
5049 /* Helper for the linemap code. */
5050
5051 static size_t
5052 round_alloc_size (size_t s)
5053 {
5054 return s;
5055 }
5056
5057
5058 /* The genmatch generator progam. It reads from a pattern description
5059 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
5060
5061 int
5062 main (int argc, char **argv)
5063 {
5064 cpp_reader *r;
5065
5066 progname = "genmatch";
5067
5068 if (argc < 2)
5069 return 1;
5070
5071 bool gimple = true;
5072 char *input = argv[argc-1];
5073 for (int i = 1; i < argc - 1; ++i)
5074 {
5075 if (strcmp (argv[i], "--gimple") == 0)
5076 gimple = true;
5077 else if (strcmp (argv[i], "--generic") == 0)
5078 gimple = false;
5079 else if (strcmp (argv[i], "-v") == 0)
5080 verbose = 1;
5081 else if (strcmp (argv[i], "-vv") == 0)
5082 verbose = 2;
5083 else
5084 {
5085 fprintf (stderr, "Usage: genmatch "
5086 "[--gimple] [--generic] [-v[v]] input\n");
5087 return 1;
5088 }
5089 }
5090
5091 line_table = XCNEW (class line_maps);
5092 linemap_init (line_table, 0);
5093 line_table->reallocator = xrealloc;
5094 line_table->round_alloc_size = round_alloc_size;
5095
5096 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
5097 cpp_callbacks *cb = cpp_get_callbacks (r);
5098 cb->diagnostic = diagnostic_cb;
5099
5100 /* Add the build directory to the #include "" search path. */
5101 cpp_dir *dir = XCNEW (cpp_dir);
5102 dir->name = getpwd ();
5103 if (!dir->name)
5104 dir->name = ASTRDUP (".");
5105 cpp_set_include_chains (r, dir, NULL, false);
5106
5107 if (!cpp_read_main_file (r, input))
5108 return 1;
5109 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
5110 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
5111
5112 null_id = new id_base (id_base::NULL_ID, "null");
5113
5114 /* Pre-seed operators. */
5115 operators = new hash_table<id_base> (1024);
5116 #define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
5117 add_operator (SYM, # SYM, # TYPE, NARGS);
5118 #define END_OF_BASE_TREE_CODES
5119 #include "tree.def"
5120 #undef END_OF_BASE_TREE_CODES
5121 #undef DEFTREECODE
5122
5123 /* Pre-seed builtin functions.
5124 ??? Cannot use N (name) as that is targetm.emultls.get_address
5125 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
5126 #define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
5127 add_function (ENUM, "CFN_" # ENUM);
5128 #include "builtins.def"
5129
5130 #define DEF_INTERNAL_FN(CODE, NAME, FNSPEC) \
5131 add_function (IFN_##CODE, "CFN_" #CODE);
5132 #include "internal-fn.def"
5133
5134 /* Parse ahead! */
5135 parser p (r);
5136
5137 if (gimple)
5138 write_header (stdout, "gimple-match-head.c");
5139 else
5140 write_header (stdout, "generic-match-head.c");
5141
5142 /* Go over all predicates defined with patterns and perform
5143 lowering and code generation. */
5144 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
5145 {
5146 predicate_id *pred = p.user_predicates[i];
5147 lower (pred->matchers, gimple);
5148
5149 if (verbose == 2)
5150 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5151 print_matches (pred->matchers[j]);
5152
5153 decision_tree dt;
5154 for (unsigned j = 0; j < pred->matchers.length (); ++j)
5155 dt.insert (pred->matchers[j], j);
5156
5157 if (verbose == 2)
5158 dt.print (stderr);
5159
5160 write_predicate (stdout, pred, dt, gimple);
5161 }
5162
5163 /* Lower the main simplifiers and generate code for them. */
5164 lower (p.simplifiers, gimple);
5165
5166 if (verbose == 2)
5167 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5168 print_matches (p.simplifiers[i]);
5169
5170 decision_tree dt;
5171 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
5172 dt.insert (p.simplifiers[i], i);
5173
5174 if (verbose == 2)
5175 dt.print (stderr);
5176
5177 dt.gen (stdout, gimple);
5178
5179 /* Finalize. */
5180 cpp_finish (r, NULL);
5181 cpp_destroy (r);
5182
5183 delete operators;
5184
5185 return 0;
5186 }