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