]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/genmatch.c
gcc/
[thirdparty/gcc.git] / gcc / genmatch.c
CommitLineData
2165588a 1/* Generate pattern matching and transform code shared between
2 GENERIC and GIMPLE folding code from match-and-simplify description.
3
d353bf18 4 Copyright (C) 2014-2015 Free Software Foundation, Inc.
2165588a 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"
25#include <new>
2165588a 26#include "system.h"
27#include "coretypes.h"
28#include <cpplib.h>
29#include "errors.h"
2165588a 30#include "hash-table.h"
3c181717 31#include "hash-set.h"
2165588a 32#include "is-a.h"
33
34
80c3d8cf 35/* Stubs for GGC referenced through instantiations triggered by hash-map. */
36void *ggc_internal_cleared_alloc (size_t, void (*)(void *),
35e1a6f4 37 size_t, size_t MEM_STAT_DECL)
80c3d8cf 38{
39 return NULL;
40}
41void ggc_free (void *)
42{
43}
44
45
2165588a 46/* libccp helpers. */
47
48static struct line_maps *line_table;
49
50static bool
51#if GCC_VERSION >= 4001
52__attribute__((format (printf, 6, 0)))
53#endif
38d93c27 54error_cb (cpp_reader *, int errtype, int, source_location location,
2165588a 55 unsigned int, const char *msg, va_list *ap)
56{
551e34da 57 const line_map_ordinary *map;
2165588a 58 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
59 expanded_location loc = linemap_expand_location (line_table, map, location);
38d93c27 60 fprintf (stderr, "%s:%d:%d %s: ", loc.file, loc.line, loc.column,
61 (errtype == CPP_DL_WARNING) ? "warning" : "error");
2165588a 62 vfprintf (stderr, msg, *ap);
63 fprintf (stderr, "\n");
64 FILE *f = fopen (loc.file, "r");
65 if (f)
66 {
67 char buf[128];
68 while (loc.line > 0)
69 {
70 if (!fgets (buf, 128, f))
71 goto notfound;
72 if (buf[strlen (buf) - 1] != '\n')
73 {
74 if (loc.line > 1)
75 loc.line++;
76 }
77 loc.line--;
78 }
79 fprintf (stderr, "%s", buf);
80 for (int i = 0; i < loc.column - 1; ++i)
81 fputc (' ', stderr);
82 fputc ('^', stderr);
83 fputc ('\n', stderr);
84notfound:
85 fclose (f);
86 }
38d93c27 87
88 if (errtype == CPP_DL_FATAL)
89 exit (1);
90 return false;
2165588a 91}
92
93static void
94#if GCC_VERSION >= 4001
95__attribute__((format (printf, 2, 3)))
96#endif
97fatal_at (const cpp_token *tk, const char *msg, ...)
98{
99 va_list ap;
100 va_start (ap, msg);
101 error_cb (NULL, CPP_DL_FATAL, 0, tk->src_loc, 0, msg, &ap);
102 va_end (ap);
103}
104
3c181717 105static void
106#if GCC_VERSION >= 4001
107__attribute__((format (printf, 2, 3)))
108#endif
109fatal_at (source_location loc, const char *msg, ...)
110{
111 va_list ap;
112 va_start (ap, msg);
113 error_cb (NULL, CPP_DL_FATAL, 0, loc, 0, msg, &ap);
114 va_end (ap);
115}
116
38d93c27 117static void
118#if GCC_VERSION >= 4001
119__attribute__((format (printf, 2, 3)))
120#endif
121warning_at (const cpp_token *tk, const char *msg, ...)
122{
123 va_list ap;
124 va_start (ap, msg);
125 error_cb (NULL, CPP_DL_WARNING, 0, tk->src_loc, 0, msg, &ap);
126 va_end (ap);
127}
128
2165588a 129static void
130output_line_directive (FILE *f, source_location location,
131 bool dumpfile = false)
132{
551e34da 133 const line_map_ordinary *map;
2165588a 134 linemap_resolve_location (line_table, location, LRK_SPELLING_LOCATION, &map);
135 expanded_location loc = linemap_expand_location (line_table, map, location);
136 if (dumpfile)
137 {
138 /* When writing to a dumpfile only dump the filename. */
139 const char *file = strrchr (loc.file, DIR_SEPARATOR);
140 if (!file)
141 file = loc.file;
142 else
143 ++file;
144 fprintf (f, "%s:%d", file, loc.line);
145 }
146 else
147 /* Other gen programs really output line directives here, at least for
148 development it's right now more convenient to have line information
149 from the generated file. Still keep the directives as comment for now
150 to easily back-point to the meta-description. */
151 fprintf (f, "/* #line %d \"%s\" */\n", loc.line, loc.file);
152}
153
154
155/* Pull in tree codes and builtin function codes from their
156 definition files. */
157
158#define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM,
159enum tree_code {
160#include "tree.def"
161CONVERT0,
162CONVERT1,
163CONVERT2,
53e2e97e 164VIEW_CONVERT0,
165VIEW_CONVERT1,
166VIEW_CONVERT2,
2165588a 167MAX_TREE_CODES
168};
169#undef DEFTREECODE
170
171#define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) ENUM,
172enum built_in_function {
173#include "builtins.def"
174END_BUILTINS
175};
176#undef DEF_BUILTIN
177
178
179/* Base class for all identifiers the parser knows. */
180
770ff93b 181struct id_base : nofree_ptr_hash<id_base>
2165588a 182{
183 enum id_kind { CODE, FN, PREDICATE, USER } kind;
184
185 id_base (id_kind, const char *, int = -1);
186
187 hashval_t hashval;
188 int nargs;
189 const char *id;
190
191 /* hash_table support. */
9969c043 192 static inline hashval_t hash (const id_base *);
193 static inline int equal (const id_base *, const id_base *);
2165588a 194};
195
196inline hashval_t
9969c043 197id_base::hash (const id_base *op)
2165588a 198{
199 return op->hashval;
200}
201
202inline int
9969c043 203id_base::equal (const id_base *op1,
204 const id_base *op2)
2165588a 205{
206 return (op1->hashval == op2->hashval
207 && strcmp (op1->id, op2->id) == 0);
208}
209
210/* Hashtable of known pattern operators. This is pre-seeded from
211 all known tree codes and all known builtin function ids. */
212static hash_table<id_base> *operators;
213
214id_base::id_base (id_kind kind_, const char *id_, int nargs_)
215{
216 kind = kind_;
217 id = id_;
218 nargs = nargs_;
219 hashval = htab_hash_string (id);
220}
221
222/* Identifier that maps to a tree code. */
223
224struct operator_id : public id_base
225{
226 operator_id (enum tree_code code_, const char *id_, unsigned nargs_,
227 const char *tcc_)
228 : id_base (id_base::CODE, id_, nargs_), code (code_), tcc (tcc_) {}
229 enum tree_code code;
230 const char *tcc;
231};
232
233/* Identifier that maps to a builtin function code. */
234
235struct fn_id : public id_base
236{
237 fn_id (enum built_in_function fn_, const char *id_)
238 : id_base (id_base::FN, id_), fn (fn_) {}
239 enum built_in_function fn;
240};
241
242struct simplify;
243
244/* Identifier that maps to a user-defined predicate. */
245
246struct predicate_id : public id_base
247{
248 predicate_id (const char *id_)
249 : id_base (id_base::PREDICATE, id_), matchers (vNULL) {}
250 vec<simplify *> matchers;
251};
252
253/* Identifier that maps to a operator defined by a 'for' directive. */
254
255struct user_id : public id_base
256{
38d93c27 257 user_id (const char *id_, bool is_oper_list_ = false)
258 : id_base (id_base::USER, id_), substitutes (vNULL),
259 used (false), is_oper_list (is_oper_list_) {}
2165588a 260 vec<id_base *> substitutes;
38d93c27 261 bool used;
262 bool is_oper_list;
2165588a 263};
264
265template<>
266template<>
267inline bool
268is_a_helper <fn_id *>::test (id_base *id)
269{
270 return id->kind == id_base::FN;
271}
272
273template<>
274template<>
275inline bool
276is_a_helper <operator_id *>::test (id_base *id)
277{
278 return id->kind == id_base::CODE;
279}
280
281template<>
282template<>
283inline bool
284is_a_helper <predicate_id *>::test (id_base *id)
285{
286 return id->kind == id_base::PREDICATE;
287}
288
289template<>
290template<>
291inline bool
292is_a_helper <user_id *>::test (id_base *id)
293{
294 return id->kind == id_base::USER;
295}
296
297/* Add a predicate identifier to the hash. */
298
299static predicate_id *
300add_predicate (const char *id)
301{
302 predicate_id *p = new predicate_id (id);
303 id_base **slot = operators->find_slot_with_hash (p, p->hashval, INSERT);
304 if (*slot)
305 fatal ("duplicate id definition");
306 *slot = p;
307 return p;
308}
309
310/* Add a tree code identifier to the hash. */
311
312static void
313add_operator (enum tree_code code, const char *id,
314 const char *tcc, unsigned nargs)
315{
316 if (strcmp (tcc, "tcc_unary") != 0
317 && strcmp (tcc, "tcc_binary") != 0
318 && strcmp (tcc, "tcc_comparison") != 0
319 && strcmp (tcc, "tcc_expression") != 0
320 /* For {REAL,IMAG}PART_EXPR and VIEW_CONVERT_EXPR. */
321 && strcmp (tcc, "tcc_reference") != 0
322 /* To have INTEGER_CST and friends as "predicate operators". */
7c430700 323 && strcmp (tcc, "tcc_constant") != 0
324 /* And allow CONSTRUCTOR for vector initializers. */
325 && !(code == CONSTRUCTOR))
2165588a 326 return;
327 operator_id *op = new operator_id (code, id, nargs, tcc);
328 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
329 if (*slot)
330 fatal ("duplicate id definition");
331 *slot = op;
332}
333
334/* Add a builtin identifier to the hash. */
335
336static void
337add_builtin (enum built_in_function code, const char *id)
338{
339 fn_id *fn = new fn_id (code, id);
340 id_base **slot = operators->find_slot_with_hash (fn, fn->hashval, INSERT);
341 if (*slot)
342 fatal ("duplicate id definition");
343 *slot = fn;
344}
345
346/* Helper for easy comparing ID with tree code CODE. */
347
348static bool
349operator==(id_base &id, enum tree_code code)
350{
351 if (operator_id *oid = dyn_cast <operator_id *> (&id))
352 return oid->code == code;
353 return false;
354}
355
356/* Lookup the identifier ID. */
357
358id_base *
359get_operator (const char *id)
360{
361 id_base tem (id_base::CODE, id);
362
363 id_base *op = operators->find_with_hash (&tem, tem.hashval);
364 if (op)
38d93c27 365 {
366 /* If this is a user-defined identifier track whether it was used. */
367 if (user_id *uid = dyn_cast<user_id *> (op))
368 uid->used = true;
369 return op;
370 }
2165588a 371
372 /* Try all-uppercase. */
373 char *id2 = xstrdup (id);
374 for (unsigned i = 0; i < strlen (id2); ++i)
375 id2[i] = TOUPPER (id2[i]);
376 new (&tem) id_base (id_base::CODE, id2);
377 op = operators->find_with_hash (&tem, tem.hashval);
378 if (op)
379 {
380 free (id2);
381 return op;
382 }
383
384 /* Try _EXPR appended. */
385 id2 = (char *)xrealloc (id2, strlen (id2) + sizeof ("_EXPR") + 1);
386 strcat (id2, "_EXPR");
387 new (&tem) id_base (id_base::CODE, id2);
388 op = operators->find_with_hash (&tem, tem.hashval);
389 if (op)
390 {
391 free (id2);
392 return op;
393 }
394
395 return 0;
396}
397
398
80c3d8cf 399/* Helper for the capture-id map. */
400
401struct capture_id_map_hasher : default_hashmap_traits
402{
403 static inline hashval_t hash (const char *);
404 static inline bool equal_keys (const char *, const char *);
405};
406
407inline hashval_t
408capture_id_map_hasher::hash (const char *id)
409{
410 return htab_hash_string (id);
411}
412
413inline bool
414capture_id_map_hasher::equal_keys (const char *id1, const char *id2)
415{
416 return strcmp (id1, id2) == 0;
417}
418
419typedef hash_map<const char *, unsigned, capture_id_map_hasher> cid_map_t;
420
2165588a 421
422/* The AST produced by parsing of the pattern definitions. */
423
424struct dt_operand;
30d8934c 425struct capture_info;
2165588a 426
427/* The base class for operands. */
428
429struct operand {
430 enum op_type { OP_PREDICATE, OP_EXPR, OP_CAPTURE, OP_C_EXPR };
431 operand (enum op_type type_) : type (type_) {}
432 enum op_type type;
433 virtual void gen_transform (FILE *, const char *, bool, int,
30d8934c 434 const char *, capture_info *,
435 dt_operand ** = 0,
436 bool = true)
2165588a 437 { gcc_unreachable (); }
438};
439
440/* A predicate operand. Predicates are leafs in the AST. */
441
442struct predicate : public operand
443{
444 predicate (predicate_id *p_) : operand (OP_PREDICATE), p (p_) {}
445 predicate_id *p;
446};
447
448/* An operand that constitutes an expression. Expressions include
449 function calls and user-defined predicate invocations. */
450
451struct expr : public operand
452{
453 expr (id_base *operation_, bool is_commutative_ = false)
454 : operand (OP_EXPR), operation (operation_),
30d8934c 455 ops (vNULL), expr_type (NULL), is_commutative (is_commutative_),
456 is_generic (false) {}
2165588a 457 void append_op (operand *op) { ops.safe_push (op); }
458 /* The operator and its operands. */
459 id_base *operation;
460 vec<operand *> ops;
461 /* An explicitely specified type - used exclusively for conversions. */
462 const char *expr_type;
463 /* Whether the operation is to be applied commutatively. This is
464 later lowered to two separate patterns. */
465 bool is_commutative;
30d8934c 466 /* Whether the expression is expected to be in GENERIC form. */
467 bool is_generic;
2165588a 468 virtual void gen_transform (FILE *f, const char *, bool, int,
30d8934c 469 const char *, capture_info *,
470 dt_operand ** = 0, bool = true);
2165588a 471};
472
473/* An operator that is represented by native C code. This is always
474 a leaf operand in the AST. This class is also used to represent
475 the code to be generated for 'if' and 'with' expressions. */
476
477struct c_expr : public operand
478{
479 /* A mapping of an identifier and its replacement. Used to apply
480 'for' lowering. */
481 struct id_tab {
482 const char *id;
483 const char *oper;
484 id_tab (const char *id_, const char *oper_): id (id_), oper (oper_) {}
485 };
486
487 c_expr (cpp_reader *r_, vec<cpp_token> code_, unsigned nr_stmts_,
80c3d8cf 488 vec<id_tab> ids_, cid_map_t *capture_ids_)
2165588a 489 : operand (OP_C_EXPR), r (r_), code (code_), capture_ids (capture_ids_),
490 nr_stmts (nr_stmts_), ids (ids_) {}
491 /* cpplib tokens and state to transform this back to source. */
492 cpp_reader *r;
493 vec<cpp_token> code;
80c3d8cf 494 cid_map_t *capture_ids;
2165588a 495 /* The number of statements parsed (well, the number of ';'s). */
496 unsigned nr_stmts;
497 /* The identifier replacement vector. */
498 vec<id_tab> ids;
499 virtual void gen_transform (FILE *f, const char *, bool, int,
30d8934c 500 const char *, capture_info *,
501 dt_operand ** = 0, bool = true);
2165588a 502};
503
504/* A wrapper around another operand that captures its value. */
505
506struct capture : public operand
507{
508 capture (unsigned where_, operand *what_)
509 : operand (OP_CAPTURE), where (where_), what (what_) {}
510 /* Identifier index for the value. */
511 unsigned where;
512 /* The captured value. */
513 operand *what;
514 virtual void gen_transform (FILE *f, const char *, bool, int,
30d8934c 515 const char *, capture_info *,
516 dt_operand ** = 0, bool = true);
2165588a 517};
518
519template<>
520template<>
521inline bool
522is_a_helper <capture *>::test (operand *op)
523{
524 return op->type == operand::OP_CAPTURE;
525}
526
527template<>
528template<>
529inline bool
530is_a_helper <predicate *>::test (operand *op)
531{
532 return op->type == operand::OP_PREDICATE;
533}
534
535template<>
536template<>
537inline bool
538is_a_helper <c_expr *>::test (operand *op)
539{
540 return op->type == operand::OP_C_EXPR;
541}
542
543template<>
544template<>
545inline bool
546is_a_helper <expr *>::test (operand *op)
547{
548 return op->type == operand::OP_EXPR;
549}
550
551/* Helper to distinguish 'if' from 'with' expressions. */
552
553struct if_or_with
554{
555 if_or_with (operand *cexpr_, source_location location_, bool is_with_)
556 : location (location_), cexpr (cexpr_), is_with (is_with_) {}
557 source_location location;
558 operand *cexpr;
559 bool is_with;
560};
561
562/* The main class of a pattern and its transform. This is used to
563 represent both (simplify ...) and (match ...) kinds. The AST
564 duplicates all outer 'if' and 'for' expressions here so each
565 simplify can exist in isolation. */
566
567struct simplify
568{
569 simplify (operand *match_, source_location match_location_,
570 struct operand *result_, source_location result_location_,
571 vec<if_or_with> ifexpr_vec_, vec<vec<user_id *> > for_vec_,
80c3d8cf 572 cid_map_t *capture_ids_)
2165588a 573 : match (match_), match_location (match_location_),
574 result (result_), result_location (result_location_),
575 ifexpr_vec (ifexpr_vec_), for_vec (for_vec_),
80c3d8cf 576 capture_ids (capture_ids_), capture_max (capture_ids_->elements () - 1) {}
2165588a 577
578 /* The expression that is matched against the GENERIC or GIMPLE IL. */
579 operand *match;
580 source_location match_location;
581 /* For a (simplify ...) the expression produced when the pattern applies.
582 For a (match ...) either NULL if it is a simple predicate or the
583 single expression specifying the matched operands. */
584 struct operand *result;
585 source_location result_location;
586 /* Collected 'if' expressions that need to evaluate to true to make
587 the pattern apply. */
588 vec<if_or_with> ifexpr_vec;
589 /* Collected 'for' expression operators that have to be replaced
590 in the lowering phase. */
591 vec<vec<user_id *> > for_vec;
592 /* A map of capture identifiers to indexes. */
80c3d8cf 593 cid_map_t *capture_ids;
2165588a 594 int capture_max;
595};
596
597/* Debugging routines for dumping the AST. */
598
599DEBUG_FUNCTION void
600print_operand (operand *o, FILE *f = stderr, bool flattened = false)
601{
602 if (capture *c = dyn_cast<capture *> (o))
603 {
604 fprintf (f, "@%u", c->where);
605 if (c->what && flattened == false)
606 {
607 putc (':', f);
608 print_operand (c->what, f, flattened);
609 putc (' ', f);
610 }
611 }
612
613 else if (predicate *p = dyn_cast<predicate *> (o))
614 fprintf (f, "%s", p->p->id);
615
616 else if (is_a<c_expr *> (o))
617 fprintf (f, "c_expr");
618
619 else if (expr *e = dyn_cast<expr *> (o))
620 {
621 fprintf (f, "(%s", e->operation->id);
622
623 if (flattened == false)
624 {
625 putc (' ', f);
626 for (unsigned i = 0; i < e->ops.length (); ++i)
627 {
628 print_operand (e->ops[i], f, flattened);
629 putc (' ', f);
630 }
631 }
632 putc (')', f);
633 }
634
635 else
636 gcc_unreachable ();
637}
638
639DEBUG_FUNCTION void
640print_matches (struct simplify *s, FILE *f = stderr)
641{
642 fprintf (f, "for expression: ");
643 print_operand (s->match, f);
644 putc ('\n', f);
645}
646
647
648/* AST lowering. */
649
650/* Lowering of commutative operators. */
651
652static void
653cartesian_product (const vec< vec<operand *> >& ops_vector,
654 vec< vec<operand *> >& result, vec<operand *>& v, unsigned n)
655{
656 if (n == ops_vector.length ())
657 {
658 vec<operand *> xv = v.copy ();
659 result.safe_push (xv);
660 return;
661 }
662
663 for (unsigned i = 0; i < ops_vector[n].length (); ++i)
664 {
665 v[n] = ops_vector[n][i];
666 cartesian_product (ops_vector, result, v, n + 1);
667 }
668}
669
670/* Lower OP to two operands in case it is marked as commutative. */
671
672static vec<operand *>
673commutate (operand *op)
674{
675 vec<operand *> ret = vNULL;
676
677 if (capture *c = dyn_cast <capture *> (op))
678 {
679 if (!c->what)
680 {
681 ret.safe_push (op);
682 return ret;
683 }
684 vec<operand *> v = commutate (c->what);
685 for (unsigned i = 0; i < v.length (); ++i)
686 {
687 capture *nc = new capture (c->where, v[i]);
688 ret.safe_push (nc);
689 }
690 return ret;
691 }
692
693 expr *e = dyn_cast <expr *> (op);
694 if (!e || e->ops.length () == 0)
695 {
696 ret.safe_push (op);
697 return ret;
698 }
699
700 vec< vec<operand *> > ops_vector = vNULL;
701 for (unsigned i = 0; i < e->ops.length (); ++i)
702 ops_vector.safe_push (commutate (e->ops[i]));
703
704 auto_vec< vec<operand *> > result;
705 auto_vec<operand *> v (e->ops.length ());
706 v.quick_grow_cleared (e->ops.length ());
707 cartesian_product (ops_vector, result, v, 0);
708
709
710 for (unsigned i = 0; i < result.length (); ++i)
711 {
712 expr *ne = new expr (e->operation);
713 for (unsigned j = 0; j < result[i].length (); ++j)
714 ne->append_op (result[i][j]);
715 ret.safe_push (ne);
716 }
717
718 if (!e->is_commutative)
719 return ret;
720
721 for (unsigned i = 0; i < result.length (); ++i)
722 {
723 expr *ne = new expr (e->operation);
724 // result[i].length () is 2 since e->operation is binary
725 for (unsigned j = result[i].length (); j; --j)
726 ne->append_op (result[i][j-1]);
727 ret.safe_push (ne);
728 }
729
730 return ret;
731}
732
733/* Lower operations marked as commutative in the AST of S and push
734 the resulting patterns to SIMPLIFIERS. */
735
736static void
737lower_commutative (simplify *s, vec<simplify *>& simplifiers)
738{
739 vec<operand *> matchers = commutate (s->match);
740 for (unsigned i = 0; i < matchers.length (); ++i)
741 {
742 simplify *ns = new simplify (matchers[i], s->match_location,
743 s->result, s->result_location, s->ifexpr_vec,
744 s->for_vec, s->capture_ids);
745 simplifiers.safe_push (ns);
746 }
747}
748
749/* Strip conditional conversios using operator OPER from O and its
750 children if STRIP, else replace them with an unconditional convert. */
751
752operand *
53e2e97e 753lower_opt_convert (operand *o, enum tree_code oper,
754 enum tree_code to_oper, bool strip)
2165588a 755{
756 if (capture *c = dyn_cast<capture *> (o))
757 {
758 if (c->what)
53e2e97e 759 return new capture (c->where,
760 lower_opt_convert (c->what, oper, to_oper, strip));
2165588a 761 else
762 return c;
763 }
764
765 expr *e = dyn_cast<expr *> (o);
766 if (!e)
767 return o;
768
769 if (*e->operation == oper)
770 {
771 if (strip)
53e2e97e 772 return lower_opt_convert (e->ops[0], oper, to_oper, strip);
2165588a 773
53e2e97e 774 expr *ne = new expr (to_oper == CONVERT_EXPR
775 ? get_operator ("CONVERT_EXPR")
776 : get_operator ("VIEW_CONVERT_EXPR"));
777 ne->append_op (lower_opt_convert (e->ops[0], oper, to_oper, strip));
2165588a 778 return ne;
779 }
780
781 expr *ne = new expr (e->operation, e->is_commutative);
782 for (unsigned i = 0; i < e->ops.length (); ++i)
53e2e97e 783 ne->append_op (lower_opt_convert (e->ops[i], oper, to_oper, strip));
2165588a 784
785 return ne;
786}
787
788/* Determine whether O or its children uses the conditional conversion
789 operator OPER. */
790
791static bool
792has_opt_convert (operand *o, enum tree_code oper)
793{
794 if (capture *c = dyn_cast<capture *> (o))
795 {
796 if (c->what)
797 return has_opt_convert (c->what, oper);
798 else
799 return false;
800 }
801
802 expr *e = dyn_cast<expr *> (o);
803 if (!e)
804 return false;
805
806 if (*e->operation == oper)
807 return true;
808
809 for (unsigned i = 0; i < e->ops.length (); ++i)
810 if (has_opt_convert (e->ops[i], oper))
811 return true;
812
813 return false;
814}
815
816/* Lower conditional convert operators in O, expanding it to a vector
817 if required. */
818
819static vec<operand *>
820lower_opt_convert (operand *o)
821{
822 vec<operand *> v1 = vNULL, v2;
823
824 v1.safe_push (o);
825
53e2e97e 826 enum tree_code opers[]
827 = { CONVERT0, CONVERT_EXPR,
828 CONVERT1, CONVERT_EXPR,
829 CONVERT2, CONVERT_EXPR,
830 VIEW_CONVERT0, VIEW_CONVERT_EXPR,
831 VIEW_CONVERT1, VIEW_CONVERT_EXPR,
832 VIEW_CONVERT2, VIEW_CONVERT_EXPR };
2165588a 833
834 /* Conditional converts are lowered to a pattern with the
835 conversion and one without. The three different conditional
836 convert codes are lowered separately. */
837
53e2e97e 838 for (unsigned i = 0; i < sizeof (opers) / sizeof (enum tree_code); i += 2)
2165588a 839 {
840 v2 = vNULL;
841 for (unsigned j = 0; j < v1.length (); ++j)
842 if (has_opt_convert (v1[j], opers[i]))
843 {
53e2e97e 844 v2.safe_push (lower_opt_convert (v1[j],
845 opers[i], opers[i+1], false));
846 v2.safe_push (lower_opt_convert (v1[j],
847 opers[i], opers[i+1], true));
2165588a 848 }
849
850 if (v2 != vNULL)
851 {
852 v1 = vNULL;
853 for (unsigned j = 0; j < v2.length (); ++j)
854 v1.safe_push (v2[j]);
855 }
856 }
857
858 return v1;
859}
860
861/* Lower conditional convert operators in the AST of S and push
862 the resulting multiple patterns to SIMPLIFIERS. */
863
864static void
865lower_opt_convert (simplify *s, vec<simplify *>& simplifiers)
866{
867 vec<operand *> matchers = lower_opt_convert (s->match);
868 for (unsigned i = 0; i < matchers.length (); ++i)
869 {
870 simplify *ns = new simplify (matchers[i], s->match_location,
871 s->result, s->result_location, s->ifexpr_vec,
872 s->for_vec, s->capture_ids);
873 simplifiers.safe_push (ns);
874 }
875}
876
30d8934c 877/* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
878 GENERIC and a GIMPLE variant. */
879
880static vec<operand *>
881lower_cond (operand *o)
882{
883 vec<operand *> ro = vNULL;
884
885 if (capture *c = dyn_cast<capture *> (o))
886 {
887 if (c->what)
888 {
889 vec<operand *> lop = vNULL;
890 lop = lower_cond (c->what);
891
892 for (unsigned i = 0; i < lop.length (); ++i)
893 ro.safe_push (new capture (c->where, lop[i]));
894 return ro;
895 }
896 }
897
898 expr *e = dyn_cast<expr *> (o);
899 if (!e || e->ops.length () == 0)
900 {
901 ro.safe_push (o);
902 return ro;
903 }
904
905 vec< vec<operand *> > ops_vector = vNULL;
906 for (unsigned i = 0; i < e->ops.length (); ++i)
907 ops_vector.safe_push (lower_cond (e->ops[i]));
908
909 auto_vec< vec<operand *> > result;
910 auto_vec<operand *> v (e->ops.length ());
911 v.quick_grow_cleared (e->ops.length ());
912 cartesian_product (ops_vector, result, v, 0);
913
914 for (unsigned i = 0; i < result.length (); ++i)
915 {
916 expr *ne = new expr (e->operation);
917 for (unsigned j = 0; j < result[i].length (); ++j)
918 ne->append_op (result[i][j]);
919 ro.safe_push (ne);
920 /* If this is a COND with a captured expression or an
921 expression with two operands then also match a GENERIC
922 form on the compare. */
923 if ((*e->operation == COND_EXPR
924 || *e->operation == VEC_COND_EXPR)
925 && ((is_a <capture *> (e->ops[0])
926 && as_a <capture *> (e->ops[0])->what
927 && is_a <expr *> (as_a <capture *> (e->ops[0])->what)
928 && as_a <expr *>
929 (as_a <capture *> (e->ops[0])->what)->ops.length () == 2)
930 || (is_a <expr *> (e->ops[0])
931 && as_a <expr *> (e->ops[0])->ops.length () == 2)))
932 {
933 expr *ne = new expr (e->operation);
934 for (unsigned j = 0; j < result[i].length (); ++j)
935 ne->append_op (result[i][j]);
936 if (capture *c = dyn_cast <capture *> (ne->ops[0]))
937 {
938 expr *ocmp = as_a <expr *> (c->what);
939 expr *cmp = new expr (ocmp->operation);
940 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
941 cmp->append_op (ocmp->ops[j]);
942 cmp->is_generic = true;
943 ne->ops[0] = new capture (c->where, cmp);
944 }
945 else
946 {
947 expr *ocmp = as_a <expr *> (ne->ops[0]);
948 expr *cmp = new expr (ocmp->operation);
949 for (unsigned j = 0; j < ocmp->ops.length (); ++j)
950 cmp->append_op (ocmp->ops[j]);
951 cmp->is_generic = true;
952 ne->ops[0] = cmp;
953 }
954 ro.safe_push (ne);
955 }
956 }
957
958 return ro;
959}
960
961/* Lower the compare operand of COND_EXPRs and VEC_COND_EXPRs to a
962 GENERIC and a GIMPLE variant. */
963
964static void
965lower_cond (simplify *s, vec<simplify *>& simplifiers)
966{
967 vec<operand *> matchers = lower_cond (s->match);
968 for (unsigned i = 0; i < matchers.length (); ++i)
969 {
970 simplify *ns = new simplify (matchers[i], s->match_location,
971 s->result, s->result_location, s->ifexpr_vec,
972 s->for_vec, s->capture_ids);
973 simplifiers.safe_push (ns);
974 }
975}
976
2165588a 977/* In AST operand O replace operator ID with operator WITH. */
978
979operand *
980replace_id (operand *o, user_id *id, id_base *with)
981{
982 /* Deep-copy captures and expressions, replacing operations as
983 needed. */
984 if (capture *c = dyn_cast<capture *> (o))
985 {
986 if (!c->what)
987 return c;
988 return new capture (c->where, replace_id (c->what, id, with));
989 }
990 else if (expr *e = dyn_cast<expr *> (o))
991 {
992 expr *ne = new expr (e->operation == id ? with : e->operation,
993 e->is_commutative);
25ea41ee 994 ne->expr_type = e->expr_type;
2165588a 995 for (unsigned i = 0; i < e->ops.length (); ++i)
996 ne->append_op (replace_id (e->ops[i], id, with));
997 return ne;
998 }
999
1000 /* For c_expr we simply record a string replacement table which is
1001 applied at code-generation time. */
1002 if (c_expr *ce = dyn_cast<c_expr *> (o))
1003 {
1004 vec<c_expr::id_tab> ids = ce->ids.copy ();
1005 ids.safe_push (c_expr::id_tab (id->id, with->id));
1006 return new c_expr (ce->r, ce->code, ce->nr_stmts, ids, ce->capture_ids);
1007 }
1008
1009 return o;
1010}
1011
1012/* Lower recorded fors for SIN and output to SIMPLIFIERS. */
1013
1014static void
1015lower_for (simplify *sin, vec<simplify *>& simplifiers)
1016{
1017 vec<vec<user_id *> >& for_vec = sin->for_vec;
1018 unsigned worklist_start = 0;
1019 auto_vec<simplify *> worklist;
1020 worklist.safe_push (sin);
1021
1022 /* Lower each recorded for separately, operating on the
1023 set of simplifiers created by the previous one.
1024 Lower inner-to-outer so inner for substitutes can refer
1025 to operators replaced by outer fors. */
1026 for (int fi = for_vec.length () - 1; fi >= 0; --fi)
1027 {
1028 vec<user_id *>& ids = for_vec[fi];
1029 unsigned n_ids = ids.length ();
1030 unsigned max_n_opers = 0;
1031 for (unsigned i = 0; i < n_ids; ++i)
1032 if (ids[i]->substitutes.length () > max_n_opers)
1033 max_n_opers = ids[i]->substitutes.length ();
1034
1035 unsigned worklist_end = worklist.length ();
1036 for (unsigned si = worklist_start; si < worklist_end; ++si)
1037 {
1038 simplify *s = worklist[si];
1039 for (unsigned j = 0; j < max_n_opers; ++j)
1040 {
1041 operand *match_op = s->match;
1042 operand *result_op = s->result;
1043 vec<if_or_with> ifexpr_vec = s->ifexpr_vec.copy ();
1044
1045 for (unsigned i = 0; i < n_ids; ++i)
1046 {
1047 user_id *id = ids[i];
1048 id_base *oper = id->substitutes[j % id->substitutes.length ()];
1049 match_op = replace_id (match_op, id, oper);
1050 if (result_op)
1051 result_op = replace_id (result_op, id, oper);
1052 for (unsigned k = 0; k < s->ifexpr_vec.length (); ++k)
1053 ifexpr_vec[k].cexpr = replace_id (ifexpr_vec[k].cexpr,
1054 id, oper);
1055 }
1056 simplify *ns = new simplify (match_op, s->match_location,
1057 result_op, s->result_location,
1058 ifexpr_vec, vNULL, s->capture_ids);
1059 worklist.safe_push (ns);
1060 }
1061 }
1062 worklist_start = worklist_end;
1063 }
1064
1065 /* Copy out the result from the last for lowering. */
1066 for (unsigned i = worklist_start; i < worklist.length (); ++i)
1067 simplifiers.safe_push (worklist[i]);
1068}
1069
1070/* Lower the AST for everything in SIMPLIFIERS. */
1071
1072static void
30d8934c 1073lower (vec<simplify *>& simplifiers, bool gimple)
2165588a 1074{
30d8934c 1075 auto_vec<simplify *> out_simplifiers;
2165588a 1076 for (unsigned i = 0; i < simplifiers.length (); ++i)
30d8934c 1077 lower_opt_convert (simplifiers[i], out_simplifiers);
1078
1079 simplifiers.truncate (0);
1080 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1081 lower_commutative (out_simplifiers[i], simplifiers);
1082
1083 out_simplifiers.truncate (0);
1084 if (gimple)
1085 for (unsigned i = 0; i < simplifiers.length (); ++i)
1086 lower_cond (simplifiers[i], out_simplifiers);
1087 else
1088 out_simplifiers.safe_splice (simplifiers);
2165588a 1089
2165588a 1090
1091 simplifiers.truncate (0);
30d8934c 1092 for (unsigned i = 0; i < out_simplifiers.length (); ++i)
1093 lower_for (out_simplifiers[i], simplifiers);
2165588a 1094}
1095
1096
1097
1098
1099/* The decision tree built for generating GIMPLE and GENERIC pattern
1100 matching code. It represents the 'match' expression of all
1101 simplifies and has those as its leafs. */
1102
1103/* Decision tree base class, used for DT_TRUE and DT_NODE. */
1104
1105struct dt_node
1106{
1107 enum dt_type { DT_NODE, DT_OPERAND, DT_TRUE, DT_MATCH, DT_SIMPLIFY };
1108
1109 enum dt_type type;
1110 unsigned level;
1111 vec<dt_node *> kids;
1112
1113 dt_node (enum dt_type type_): type (type_), level (0), kids (vNULL) {}
1114
1115 dt_node *append_node (dt_node *);
1116 dt_node *append_op (operand *, dt_node *parent = 0, unsigned pos = 0);
1117 dt_node *append_true_op (dt_node *parent = 0, unsigned pos = 0);
1118 dt_node *append_match_op (dt_operand *, dt_node *parent = 0, unsigned pos = 0);
1119 dt_node *append_simplify (simplify *, unsigned, dt_operand **);
1120
1121 virtual void gen (FILE *, bool) {}
1122
1123 void gen_kids (FILE *, bool);
3990a84c 1124 void gen_kids_1 (FILE *, bool,
1125 vec<dt_operand *>, vec<dt_operand *>, vec<dt_operand *>,
1126 vec<dt_operand *>, vec<dt_operand *>, vec<dt_node *>);
2165588a 1127};
1128
1129/* Generic decision tree node used for DT_OPERAND and DT_MATCH. */
1130
1131struct dt_operand : public dt_node
1132{
1133 operand *op;
1134 dt_operand *match_dop;
1135 dt_operand *parent;
1136 unsigned pos;
1137
1138 dt_operand (enum dt_type type, operand *op_, dt_operand *match_dop_,
1139 dt_operand *parent_ = 0, unsigned pos_ = 0)
1140 : dt_node (type), op (op_), match_dop (match_dop_),
1141 parent (parent_), pos (pos_) {}
1142
1143 void gen (FILE *, bool);
1144 unsigned gen_predicate (FILE *, const char *, bool);
1145 unsigned gen_match_op (FILE *, const char *);
1146
1147 unsigned gen_gimple_expr (FILE *);
1148 unsigned gen_generic_expr (FILE *, const char *);
1149
1150 char *get_name (char *);
1151 void gen_opname (char *, unsigned);
1152};
1153
1154/* Leaf node of the decision tree, used for DT_SIMPLIFY. */
1155
1156struct dt_simplify : public dt_node
1157{
1158 simplify *s;
1159 unsigned pattern_no;
1160 dt_operand **indexes;
1161
1162 dt_simplify (simplify *s_, unsigned pattern_no_, dt_operand **indexes_)
1163 : dt_node (DT_SIMPLIFY), s (s_), pattern_no (pattern_no_),
1164 indexes (indexes_) {}
1165
1166 void gen (FILE *f, bool);
1167};
1168
1169template<>
1170template<>
1171inline bool
1172is_a_helper <dt_operand *>::test (dt_node *n)
1173{
1174 return (n->type == dt_node::DT_OPERAND
1175 || n->type == dt_node::DT_MATCH);
1176}
1177
1178/* A container for the actual decision tree. */
1179
1180struct decision_tree
1181{
1182 dt_node *root;
1183
1184 void insert (struct simplify *, unsigned);
1185 void gen_gimple (FILE *f = stderr);
1186 void gen_generic (FILE *f = stderr);
1187 void print (FILE *f = stderr);
1188
1189 decision_tree () { root = new dt_node (dt_node::DT_NODE); }
1190
1191 static dt_node *insert_operand (dt_node *, operand *, dt_operand **indexes,
1192 unsigned pos = 0, dt_node *parent = 0);
1193 static dt_node *find_node (vec<dt_node *>&, dt_node *);
1194 static bool cmp_node (dt_node *, dt_node *);
1195 static void print_node (dt_node *, FILE *f = stderr, unsigned = 0);
1196};
1197
1198/* Compare two AST operands O1 and O2 and return true if they are equal. */
1199
1200bool
1201cmp_operand (operand *o1, operand *o2)
1202{
1203 if (!o1 || !o2 || o1->type != o2->type)
1204 return false;
1205
1206 if (o1->type == operand::OP_PREDICATE)
1207 {
1208 predicate *p1 = as_a<predicate *>(o1);
1209 predicate *p2 = as_a<predicate *>(o2);
1210 return p1->p == p2->p;
1211 }
1212 else if (o1->type == operand::OP_EXPR)
1213 {
1214 expr *e1 = static_cast<expr *>(o1);
1215 expr *e2 = static_cast<expr *>(o2);
30d8934c 1216 return (e1->operation == e2->operation
1217 && e1->is_generic == e2->is_generic);
2165588a 1218 }
1219 else
1220 return false;
1221}
1222
1223/* Compare two decision tree nodes N1 and N2 and return true if they
1224 are equal. */
1225
1226bool
1227decision_tree::cmp_node (dt_node *n1, dt_node *n2)
1228{
1229 if (!n1 || !n2 || n1->type != n2->type)
1230 return false;
1231
3990a84c 1232 if (n1 == n2)
2165588a 1233 return true;
1234
3990a84c 1235 if (n1->type == dt_node::DT_TRUE)
1236 return false;
1237
2165588a 1238 if (n1->type == dt_node::DT_OPERAND)
1239 return cmp_operand ((as_a<dt_operand *> (n1))->op,
1240 (as_a<dt_operand *> (n2))->op);
1241 else if (n1->type == dt_node::DT_MATCH)
1242 return ((as_a<dt_operand *> (n1))->match_dop
1243 == (as_a<dt_operand *> (n2))->match_dop);
1244 return false;
1245}
1246
1247/* Search OPS for a decision tree node like P and return it if found. */
1248
1249dt_node *
1250decision_tree::find_node (vec<dt_node *>& ops, dt_node *p)
1251{
3990a84c 1252 /* We can merge adjacent DT_TRUE. */
1253 if (p->type == dt_node::DT_TRUE
1254 && !ops.is_empty ()
1255 && ops.last ()->type == dt_node::DT_TRUE)
1256 return ops.last ();
1257 for (int i = ops.length () - 1; i >= 0; --i)
1258 {
1259 /* But we can't merge across DT_TRUE nodes as they serve as
1260 pattern order barriers to make sure that patterns apply
1261 in order of appearance in case multiple matches are possible. */
1262 if (ops[i]->type == dt_node::DT_TRUE)
1263 return NULL;
1264 if (decision_tree::cmp_node (ops[i], p))
1265 return ops[i];
1266 }
2165588a 1267 return NULL;
1268}
1269
1270/* Append N to the decision tree if it there is not already an existing
1271 identical child. */
1272
1273dt_node *
1274dt_node::append_node (dt_node *n)
1275{
1276 dt_node *kid;
1277
1278 kid = decision_tree::find_node (kids, n);
1279 if (kid)
1280 return kid;
1281
1282 kids.safe_push (n);
1283 n->level = this->level + 1;
1284
2165588a 1285 return n;
1286}
1287
1288/* Append OP to the decision tree. */
1289
1290dt_node *
1291dt_node::append_op (operand *op, dt_node *parent, unsigned pos)
1292{
1293 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
1294 dt_operand *n = new dt_operand (DT_OPERAND, op, 0, parent_, pos);
1295 return append_node (n);
1296}
1297
1298/* Append a DT_TRUE decision tree node. */
1299
1300dt_node *
1301dt_node::append_true_op (dt_node *parent, unsigned pos)
1302{
d0eb9b3d 1303 dt_operand *parent_ = safe_as_a<dt_operand *> (parent);
2165588a 1304 dt_operand *n = new dt_operand (DT_TRUE, 0, 0, parent_, pos);
1305 return append_node (n);
1306}
1307
1308/* Append a DT_MATCH decision tree node. */
1309
1310dt_node *
1311dt_node::append_match_op (dt_operand *match_dop, dt_node *parent, unsigned pos)
1312{
1313 dt_operand *parent_ = as_a<dt_operand *> (parent);
1314 dt_operand *n = new dt_operand (DT_MATCH, 0, match_dop, parent_, pos);
1315 return append_node (n);
1316}
1317
1318/* Append S to the decision tree. */
1319
1320dt_node *
1321dt_node::append_simplify (simplify *s, unsigned pattern_no,
1322 dt_operand **indexes)
1323{
1324 dt_simplify *n = new dt_simplify (s, pattern_no, indexes);
1325 return append_node (n);
1326}
1327
1328/* Insert O into the decision tree and return the decision tree node found
1329 or created. */
1330
1331dt_node *
1332decision_tree::insert_operand (dt_node *p, operand *o, dt_operand **indexes,
1333 unsigned pos, dt_node *parent)
1334{
1335 dt_node *q, *elm = 0;
1336
1337 if (capture *c = dyn_cast<capture *> (o))
1338 {
1339 unsigned capt_index = c->where;
1340
1341 if (indexes[capt_index] == 0)
1342 {
1343 if (c->what)
1344 q = insert_operand (p, c->what, indexes, pos, parent);
1345 else
1346 {
1347 q = elm = p->append_true_op (parent, pos);
1348 goto at_assert_elm;
1349 }
1350 // get to the last capture
1351 for (operand *what = c->what;
1352 what && is_a<capture *> (what);
1353 c = as_a<capture *> (what), what = c->what)
1354 ;
1355
1356 if (!c->what)
1357 {
1358 unsigned cc_index = c->where;
1359 dt_operand *match_op = indexes[cc_index];
1360
1361 dt_operand temp (dt_node::DT_TRUE, 0, 0);
1362 elm = decision_tree::find_node (p->kids, &temp);
1363
1364 if (elm == 0)
1365 {
1366 dt_operand temp (dt_node::DT_MATCH, 0, match_op);
1367 elm = decision_tree::find_node (p->kids, &temp);
1368 }
1369 }
1370 else
1371 {
1372 dt_operand temp (dt_node::DT_OPERAND, c->what, 0);
1373 elm = decision_tree::find_node (p->kids, &temp);
1374 }
1375
1376at_assert_elm:
1377 gcc_assert (elm->type == dt_node::DT_TRUE
1378 || elm->type == dt_node::DT_OPERAND
1379 || elm->type == dt_node::DT_MATCH);
1380 indexes[capt_index] = static_cast<dt_operand *> (elm);
1381 return q;
1382 }
1383 else
1384 {
1385 p = p->append_match_op (indexes[capt_index], parent, pos);
1386 if (c->what)
1387 return insert_operand (p, c->what, indexes, 0, p);
1388 else
1389 return p;
1390 }
1391 }
1392 p = p->append_op (o, parent, pos);
1393 q = p;
1394
1395 if (expr *e = dyn_cast <expr *>(o))
1396 {
1397 for (unsigned i = 0; i < e->ops.length (); ++i)
1398 q = decision_tree::insert_operand (q, e->ops[i], indexes, i, p);
1399 }
1400
1401 return q;
1402}
1403
1404/* Insert S into the decision tree. */
1405
1406void
1407decision_tree::insert (struct simplify *s, unsigned pattern_no)
1408{
2165588a 1409 dt_operand **indexes = XCNEWVEC (dt_operand *, s->capture_max + 1);
1410 dt_node *p = decision_tree::insert_operand (root, s->match, indexes);
1411 p->append_simplify (s, pattern_no, indexes);
1412}
1413
1414/* Debug functions to dump the decision tree. */
1415
1416DEBUG_FUNCTION void
1417decision_tree::print_node (dt_node *p, FILE *f, unsigned indent)
1418{
1419 if (p->type == dt_node::DT_NODE)
1420 fprintf (f, "root");
1421 else
1422 {
1423 fprintf (f, "|");
1424 for (unsigned i = 0; i < indent; i++)
1425 fprintf (f, "-");
1426
1427 if (p->type == dt_node::DT_OPERAND)
1428 {
1429 dt_operand *dop = static_cast<dt_operand *>(p);
1430 print_operand (dop->op, f, true);
1431 }
1432 else if (p->type == dt_node::DT_TRUE)
1433 fprintf (f, "true");
1434 else if (p->type == dt_node::DT_MATCH)
1435 fprintf (f, "match (%p)", (void *)((as_a<dt_operand *>(p))->match_dop));
1436 else if (p->type == dt_node::DT_SIMPLIFY)
1437 {
1438 dt_simplify *s = static_cast<dt_simplify *> (p);
1439 fprintf (f, "simplify_%u { ", s->pattern_no);
1440 for (int i = 0; i <= s->s->capture_max; ++i)
1441 fprintf (f, "%p, ", (void *) s->indexes[i]);
1442 fprintf (f, " } ");
1443 }
1444 }
1445
1446 fprintf (stderr, " (%p), %u, %u\n", (void *) p, p->level, p->kids.length ());
1447
1448 for (unsigned i = 0; i < p->kids.length (); ++i)
1449 decision_tree::print_node (p->kids[i], f, indent + 2);
1450}
1451
1452DEBUG_FUNCTION void
1453decision_tree::print (FILE *f)
1454{
1455 return decision_tree::print_node (root, f);
1456}
1457
1458
30d8934c 1459/* For GENERIC we have to take care of wrapping multiple-used
1460 expressions with side-effects in save_expr and preserve side-effects
1461 of expressions with omit_one_operand. Analyze captures in
1462 match, result and with expressions and perform early-outs
1463 on the outermost match expression operands for cases we cannot
1464 handle. */
1465
1466struct capture_info
1467{
1468 capture_info (simplify *s);
1469 void walk_match (operand *o, unsigned toplevel_arg, bool, bool);
1470 void walk_result (operand *o, bool);
1471 void walk_c_expr (c_expr *);
1472
1473 struct cinfo
1474 {
1475 bool expr_p;
1476 bool cse_p;
1477 bool force_no_side_effects_p;
1478 bool cond_expr_cond_p;
1479 unsigned long toplevel_msk;
1480 int result_use_count;
1481 };
1482
1483 auto_vec<cinfo> info;
1484 unsigned long force_no_side_effects;
1485};
1486
1487/* Analyze captures in S. */
1488
1489capture_info::capture_info (simplify *s)
1490{
1491 expr *e;
1492 if (!s->result
1493 || ((e = dyn_cast <expr *> (s->result))
1494 && is_a <predicate_id *> (e->operation)))
1495 {
1496 force_no_side_effects = -1;
1497 return;
1498 }
1499
1500 force_no_side_effects = 0;
1501 info.safe_grow_cleared (s->capture_max + 1);
1502 e = as_a <expr *> (s->match);
1503 for (unsigned i = 0; i < e->ops.length (); ++i)
1504 walk_match (e->ops[i], i,
1505 (i != 0 && *e->operation == COND_EXPR)
1506 || *e->operation == TRUTH_ANDIF_EXPR
1507 || *e->operation == TRUTH_ORIF_EXPR,
1508 i == 0
1509 && (*e->operation == COND_EXPR
1510 || *e->operation == VEC_COND_EXPR));
1511
1512 walk_result (s->result, false);
1513
1514 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
1515 if (s->ifexpr_vec[i].is_with)
1516 walk_c_expr (as_a <c_expr *>(s->ifexpr_vec[i].cexpr));
1517}
1518
1519/* Analyze captures in the match expression piece O. */
1520
1521void
1522capture_info::walk_match (operand *o, unsigned toplevel_arg,
1523 bool conditional_p, bool cond_expr_cond_p)
1524{
1525 if (capture *c = dyn_cast <capture *> (o))
1526 {
1527 info[c->where].toplevel_msk |= 1 << toplevel_arg;
1528 info[c->where].force_no_side_effects_p |= conditional_p;
1529 info[c->where].cond_expr_cond_p |= cond_expr_cond_p;
1530 /* Mark expr (non-leaf) captures and recurse. */
1531 if (c->what
1532 && is_a <expr *> (c->what))
1533 {
1534 info[c->where].expr_p = true;
1535 walk_match (c->what, toplevel_arg, conditional_p, false);
1536 }
1537 }
1538 else if (expr *e = dyn_cast <expr *> (o))
1539 {
1540 for (unsigned i = 0; i < e->ops.length (); ++i)
1541 {
1542 bool cond_p = conditional_p;
1543 bool cond_expr_cond_p = false;
1544 if (i != 0 && *e->operation == COND_EXPR)
1545 cond_p = true;
1546 else if (*e->operation == TRUTH_ANDIF_EXPR
1547 || *e->operation == TRUTH_ORIF_EXPR)
1548 cond_p = true;
1549 if (i == 0
1550 && (*e->operation == COND_EXPR
1551 || *e->operation == VEC_COND_EXPR))
1552 cond_expr_cond_p = true;
1553 walk_match (e->ops[i], toplevel_arg, cond_p, cond_expr_cond_p);
1554 }
1555 }
1556 else if (is_a <predicate *> (o))
1557 {
1558 /* Mark non-captured leafs toplevel arg for checking. */
1559 force_no_side_effects |= 1 << toplevel_arg;
1560 }
1561 else
1562 gcc_unreachable ();
1563}
1564
1565/* Analyze captures in the result expression piece O. */
1566
1567void
1568capture_info::walk_result (operand *o, bool conditional_p)
1569{
1570 if (capture *c = dyn_cast <capture *> (o))
1571 {
1572 info[c->where].result_use_count++;
1573 /* If we substitute an expression capture we don't know
1574 which captures this will end up using (well, we don't
1575 compute that). Force the uses to be side-effect free
1576 which means forcing the toplevels that reach the
1577 expression side-effect free. */
1578 if (info[c->where].expr_p)
1579 force_no_side_effects |= info[c->where].toplevel_msk;
1580 /* Mark CSE capture capture uses as forced to have
1581 no side-effects. */
1582 if (c->what
1583 && is_a <expr *> (c->what))
1584 {
1585 info[c->where].cse_p = true;
1586 walk_result (c->what, true);
1587 }
1588 }
1589 else if (expr *e = dyn_cast <expr *> (o))
1590 {
1591 for (unsigned i = 0; i < e->ops.length (); ++i)
1592 {
1593 bool cond_p = conditional_p;
1594 if (i != 0 && *e->operation == COND_EXPR)
1595 cond_p = true;
1596 else if (*e->operation == TRUTH_ANDIF_EXPR
1597 || *e->operation == TRUTH_ORIF_EXPR)
1598 cond_p = true;
1599 walk_result (e->ops[i], cond_p);
1600 }
1601 }
1602 else if (c_expr *e = dyn_cast <c_expr *> (o))
1603 walk_c_expr (e);
1604 else
1605 gcc_unreachable ();
1606}
1607
1608/* Look for captures in the C expr E. */
1609
1610void
1611capture_info::walk_c_expr (c_expr *e)
1612{
1613 /* Give up for C exprs mentioning captures not inside TREE_TYPE (). */
1614 unsigned p_depth = 0;
1615 for (unsigned i = 0; i < e->code.length (); ++i)
1616 {
1617 const cpp_token *t = &e->code[i];
1618 const cpp_token *n = i < e->code.length () - 1 ? &e->code[i+1] : NULL;
1619 if (t->type == CPP_NAME
1620 && strcmp ((const char *)CPP_HASHNODE
1621 (t->val.node.node)->ident.str, "TREE_TYPE") == 0
1622 && n->type == CPP_OPEN_PAREN)
1623 p_depth++;
1624 else if (t->type == CPP_CLOSE_PAREN
1625 && p_depth > 0)
1626 p_depth--;
1627 else if (p_depth == 0
1628 && t->type == CPP_ATSIGN
1629 && (n->type == CPP_NUMBER
1630 || n->type == CPP_NAME)
1631 && !(n->flags & PREV_WHITE))
1632 {
1633 const char *id;
1634 if (n->type == CPP_NUMBER)
1635 id = (const char *)n->val.str.text;
1636 else
1637 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
1638 info[*e->capture_ids->get(id)].force_no_side_effects_p = true;
1639 }
1640 }
1641}
1642
2165588a 1643
1644/* Code generation off the decision tree and the refered AST nodes. */
1645
1646bool
1647is_conversion (id_base *op)
1648{
1649 return (*op == CONVERT_EXPR
1650 || *op == NOP_EXPR
1651 || *op == FLOAT_EXPR
1652 || *op == FIX_TRUNC_EXPR
1653 || *op == VIEW_CONVERT_EXPR);
1654}
1655
1656/* Get the type to be used for generating operands of OP from the
1657 various sources. */
1658
1659static const char *
1660get_operand_type (id_base *op, const char *in_type,
1661 const char *expr_type,
1662 const char *other_oprnd_type)
1663{
1664 /* Generally operands whose type does not match the type of the
1665 expression generated need to know their types but match and
1666 thus can fall back to 'other_oprnd_type'. */
1667 if (is_conversion (op))
1668 return other_oprnd_type;
1669 else if (*op == REALPART_EXPR
1670 || *op == IMAGPART_EXPR)
1671 return other_oprnd_type;
1672 else if (is_a <operator_id *> (op)
1673 && strcmp (as_a <operator_id *> (op)->tcc, "tcc_comparison") == 0)
1674 return other_oprnd_type;
1675 else
1676 {
1677 /* Otherwise all types should match - choose one in order of
1678 preference. */
1679 if (expr_type)
1680 return expr_type;
1681 else if (in_type)
1682 return in_type;
1683 else
1684 return other_oprnd_type;
1685 }
1686}
1687
1688/* Generate transform code for an expression. */
1689
1690void
1691expr::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
30d8934c 1692 const char *in_type, capture_info *cinfo,
1693 dt_operand **indexes, bool)
2165588a 1694{
1695 bool conversion_p = is_conversion (operation);
1696 const char *type = expr_type;
1697 char optype[64];
1698 if (type)
1699 /* If there was a type specification in the pattern use it. */
1700 ;
1701 else if (conversion_p)
1702 /* For conversions we need to build the expression using the
1703 outer type passed in. */
1704 type = in_type;
1705 else if (*operation == REALPART_EXPR
1706 || *operation == IMAGPART_EXPR)
1707 {
1708 /* __real and __imag use the component type of its operand. */
1709 sprintf (optype, "TREE_TYPE (TREE_TYPE (ops%d[0]))", depth);
1710 type = optype;
1711 }
1712 else if (is_a <operator_id *> (operation)
1713 && !strcmp (as_a <operator_id *> (operation)->tcc, "tcc_comparison"))
1714 {
1715 /* comparisons use boolean_type_node (or what gets in), but
1716 their operands need to figure out the types themselves. */
1717 sprintf (optype, "boolean_type_node");
1718 type = optype;
1719 }
8ef22408 1720 else if (*operation == COND_EXPR
1721 || *operation == VEC_COND_EXPR)
1722 {
1723 /* Conditions are of the same type as their first alternative. */
1724 sprintf (optype, "TREE_TYPE (ops%d[1])", depth);
1725 type = optype;
1726 }
2165588a 1727 else
1728 {
1729 /* Other operations are of the same type as their first operand. */
1730 sprintf (optype, "TREE_TYPE (ops%d[0])", depth);
1731 type = optype;
1732 }
1733 if (!type)
1734 fatal ("two conversions in a row");
1735
1736 fprintf (f, "{\n");
1737 fprintf (f, " tree ops%d[%u], res;\n", depth, ops.length ());
1738 char op0type[64];
1739 snprintf (op0type, 64, "TREE_TYPE (ops%d[0])", depth);
1740 for (unsigned i = 0; i < ops.length (); ++i)
1741 {
1742 char dest[32];
1743 snprintf (dest, 32, " ops%d[%u]", depth, i);
1744 const char *optype
1745 = get_operand_type (operation, in_type, expr_type,
1746 i == 0 ? NULL : op0type);
30d8934c 1747 ops[i]->gen_transform (f, dest, gimple, depth + 1, optype, cinfo, indexes,
1748 ((!(*operation == COND_EXPR)
1749 && !(*operation == VEC_COND_EXPR))
1750 || i != 0));
2165588a 1751 }
1752
e8b67bc2 1753 const char *opr;
1754 if (*operation == CONVERT_EXPR)
1755 opr = "NOP_EXPR";
1756 else
1757 opr = operation->id;
1758
2165588a 1759 if (gimple)
1760 {
20617a2b 1761 /* ??? Building a stmt can fail for various reasons here, seq being
1762 NULL or the stmt referencing SSA names occuring in abnormal PHIs.
1763 So if we fail here we should continue matching other patterns. */
1764 fprintf (f, " code_helper tem_code = %s;\n"
1765 " tree tem_ops[3] = { ", opr);
2165588a 1766 for (unsigned i = 0; i < ops.length (); ++i)
20617a2b 1767 fprintf (f, "ops%d[%u]%s", depth, i,
1768 i == ops.length () - 1 ? " };\n" : ", ");
1769 fprintf (f, " gimple_resimplify%d (seq, &tem_code, %s, tem_ops, valueize);\n",
1770 ops.length (), type);
1771 fprintf (f, " res = maybe_push_res_to_seq (tem_code, %s, tem_ops, seq);\n"
1772 " if (!res) return false;\n", type);
2165588a 1773 }
1774 else
1775 {
1776 if (operation->kind == id_base::CODE)
55534d34 1777 fprintf (f, " res = fold_build%d_loc (loc, %s, %s",
e8b67bc2 1778 ops.length(), opr, type);
2165588a 1779 else
55534d34 1780 fprintf (f, " res = build_call_expr_loc (loc, "
e8b67bc2 1781 "builtin_decl_implicit (%s), %d", opr, ops.length());
2165588a 1782 for (unsigned i = 0; i < ops.length (); ++i)
1783 fprintf (f, ", ops%d[%u]", depth, i);
1784 fprintf (f, ");\n");
1785 }
20617a2b 1786 fprintf (f, "%s = res;\n", dest);
2165588a 1787 fprintf (f, "}\n");
1788}
1789
1790/* Generate code for a c_expr which is either the expression inside
1791 an if statement or a sequence of statements which computes a
1792 result to be stored to DEST. */
1793
1794void
1795c_expr::gen_transform (FILE *f, const char *dest,
30d8934c 1796 bool, int, const char *, capture_info *,
1797 dt_operand **, bool)
2165588a 1798{
1799 if (dest && nr_stmts == 1)
1800 fprintf (f, "%s = ", dest);
1801
1802 unsigned stmt_nr = 1;
1803 for (unsigned i = 0; i < code.length (); ++i)
1804 {
1805 const cpp_token *token = &code[i];
1806
1807 /* Replace captures for code-gen. */
1808 if (token->type == CPP_ATSIGN)
1809 {
1810 const cpp_token *n = &code[i+1];
1811 if ((n->type == CPP_NUMBER
1812 || n->type == CPP_NAME)
1813 && !(n->flags & PREV_WHITE))
1814 {
1815 if (token->flags & PREV_WHITE)
1816 fputc (' ', f);
1817 const char *id;
1818 if (n->type == CPP_NUMBER)
1819 id = (const char *)n->val.str.text;
1820 else
1821 id = (const char *)CPP_HASHNODE (n->val.node.node)->ident.str;
80c3d8cf 1822 fprintf (f, "captures[%u]", *capture_ids->get(id));
2165588a 1823 ++i;
1824 continue;
1825 }
1826 }
1827
1828 if (token->flags & PREV_WHITE)
1829 fputc (' ', f);
1830
1831 if (token->type == CPP_NAME)
1832 {
1833 const char *id = (const char *) NODE_NAME (token->val.node.node);
1834 unsigned j;
1835 for (j = 0; j < ids.length (); ++j)
1836 {
1837 if (strcmp (id, ids[j].id) == 0)
1838 {
1839 fprintf (f, "%s", ids[j].oper);
1840 break;
1841 }
1842 }
1843 if (j < ids.length ())
1844 continue;
1845 }
1846
1847 /* Output the token as string. */
1848 char *tk = (char *)cpp_token_as_text (r, token);
1849 fputs (tk, f);
1850
1851 if (token->type == CPP_SEMICOLON)
1852 {
1853 stmt_nr++;
1854 if (dest && stmt_nr == nr_stmts)
1855 fprintf (f, "\n %s = ", dest);
1856 else
1857 fputc ('\n', f);
1858 }
1859 }
1860}
1861
1862/* Generate transform code for a capture. */
1863
1864void
1865capture::gen_transform (FILE *f, const char *dest, bool gimple, int depth,
30d8934c 1866 const char *in_type, capture_info *cinfo,
1867 dt_operand **indexes, bool expand_compares)
2165588a 1868{
1869 if (what && is_a<expr *> (what))
1870 {
1871 if (indexes[where] == 0)
1872 {
1873 char buf[20];
1874 sprintf (buf, "captures[%u]", where);
30d8934c 1875 what->gen_transform (f, buf, gimple, depth, in_type, cinfo, NULL);
2165588a 1876 }
1877 }
1878
1879 fprintf (f, "%s = captures[%u];\n", dest, where);
30d8934c 1880
1881 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
1882 with substituting a capture of that.
1883 ??? Returning false here will also not allow any other patterns
1884 to match. */
1885 if (gimple && expand_compares
1886 && cinfo->info[where].cond_expr_cond_p)
1887 fprintf (f, "if (COMPARISON_CLASS_P (%s))\n"
1888 " {\n"
1889 " if (!seq) return false;\n"
1890 " %s = gimple_build (seq, TREE_CODE (%s),"
1891 " TREE_TYPE (%s), TREE_OPERAND (%s, 0),"
1892 " TREE_OPERAND (%s, 1));\n"
1893 " }\n", dest, dest, dest, dest, dest, dest);
2165588a 1894}
1895
1896/* Return the name of the operand representing the decision tree node.
1897 Use NAME as space to generate it. */
1898
1899char *
1900dt_operand::get_name (char *name)
1901{
1902 if (!parent)
1903 sprintf (name, "t");
1904 else if (parent->level == 1)
1905 sprintf (name, "op%u", pos);
1906 else if (parent->type == dt_node::DT_MATCH)
1907 return parent->get_name (name);
1908 else
1909 sprintf (name, "o%u%u", parent->level, pos);
1910 return name;
1911}
1912
1913/* Fill NAME with the operand name at position POS. */
1914
1915void
1916dt_operand::gen_opname (char *name, unsigned pos)
1917{
1918 if (!parent)
1919 sprintf (name, "op%u", pos);
1920 else
1921 sprintf (name, "o%u%u", level, pos);
1922}
1923
1924/* Generate matching code for the decision tree operand which is
1925 a predicate. */
1926
1927unsigned
1928dt_operand::gen_predicate (FILE *f, const char *opname, bool gimple)
1929{
1930 predicate *p = as_a <predicate *> (op);
1931
1932 if (p->p->matchers.exists ())
1933 {
1934 /* If this is a predicate generated from a pattern mangle its
1935 name and pass on the valueize hook. */
1936 if (gimple)
1937 fprintf (f, "if (gimple_%s (%s, valueize))\n", p->p->id, opname);
1938 else
1939 fprintf (f, "if (tree_%s (%s))\n", p->p->id, opname);
1940 }
1941 else
1942 fprintf (f, "if (%s (%s))\n", p->p->id, opname);
1943 fprintf (f, "{\n");
1944 return 1;
1945}
1946
1947/* Generate matching code for the decision tree operand which is
1948 a capture-match. */
1949
1950unsigned
1951dt_operand::gen_match_op (FILE *f, const char *opname)
1952{
1953 char match_opname[20];
1954 match_dop->get_name (match_opname);
1955 fprintf (f, "if (%s == %s || operand_equal_p (%s, %s, 0))\n",
1956 opname, match_opname, opname, match_opname);
1957 fprintf (f, "{\n");
1958 return 1;
1959}
1960
1961/* Generate GIMPLE matching code for the decision tree operand. */
1962
1963unsigned
1964dt_operand::gen_gimple_expr (FILE *f)
1965{
1966 expr *e = static_cast<expr *> (op);
1967 id_base *id = e->operation;
1968 unsigned n_ops = e->ops.length ();
1969
1970 for (unsigned i = 0; i < n_ops; ++i)
1971 {
1972 char child_opname[20];
1973 gen_opname (child_opname, i);
1974
1975 if (id->kind == id_base::CODE)
1976 {
30d8934c 1977 if (e->is_generic
1978 || *id == REALPART_EXPR || *id == IMAGPART_EXPR
2165588a 1979 || *id == BIT_FIELD_REF || *id == VIEW_CONVERT_EXPR)
1980 {
1981 /* ??? If this is a memory operation we can't (and should not)
1982 match this. The only sensible operand types are
1983 SSA names and invariants. */
1984 fprintf (f, "tree %s = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), %i);\n",
1985 child_opname, i);
1986 fprintf (f, "if ((TREE_CODE (%s) == SSA_NAME\n"
1987 "|| is_gimple_min_invariant (%s))\n"
1988 "&& (%s = do_valueize (valueize, %s)))\n"
1989 "{\n", child_opname, child_opname, child_opname,
1990 child_opname);
1991 continue;
1992 }
1993 else
1994 fprintf (f, "tree %s = gimple_assign_rhs%u (def_stmt);\n",
1995 child_opname, i + 1);
1996 }
1997 else
1998 fprintf (f, "tree %s = gimple_call_arg (def_stmt, %u);\n",
1999 child_opname, i);
c434260f 2000 fprintf (f, "if ((%s = do_valueize (valueize, %s)))\n",
2165588a 2001 child_opname, child_opname);
2002 fprintf (f, "{\n");
2003 }
2004
2005 return n_ops;
2006}
2007
2008/* Generate GENERIC matching code for the decision tree operand. */
2009
2010unsigned
2011dt_operand::gen_generic_expr (FILE *f, const char *opname)
2012{
2013 expr *e = static_cast<expr *> (op);
2014 unsigned n_ops = e->ops.length ();
2015
2016 for (unsigned i = 0; i < n_ops; ++i)
2017 {
2018 char child_opname[20];
2019 gen_opname (child_opname, i);
2020
2021 if (e->operation->kind == id_base::CODE)
2022 fprintf (f, "tree %s = TREE_OPERAND (%s, %u);\n",
2023 child_opname, opname, i);
2024 else
2025 fprintf (f, "tree %s = CALL_EXPR_ARG (%s, %u);\n",
2026 child_opname, opname, i);
2027 }
2028
2029 return 0;
2030}
2031
2032/* Generate matching code for the children of the decision tree node. */
2033
2034void
2035dt_node::gen_kids (FILE *f, bool gimple)
2036{
2037 auto_vec<dt_operand *> gimple_exprs;
2038 auto_vec<dt_operand *> generic_exprs;
2039 auto_vec<dt_operand *> fns;
2040 auto_vec<dt_operand *> generic_fns;
2041 auto_vec<dt_operand *> preds;
2042 auto_vec<dt_node *> others;
2165588a 2043
2044 for (unsigned i = 0; i < kids.length (); ++i)
2045 {
2046 if (kids[i]->type == dt_node::DT_OPERAND)
2047 {
2048 dt_operand *op = as_a<dt_operand *> (kids[i]);
2049 if (expr *e = dyn_cast <expr *> (op->op))
2050 {
7c430700 2051 if (e->ops.length () == 0
2052 && (!gimple || !(*e->operation == CONSTRUCTOR)))
2165588a 2053 generic_exprs.safe_push (op);
2054 else if (e->operation->kind == id_base::FN)
2055 {
2056 if (gimple)
2057 fns.safe_push (op);
2058 else
2059 generic_fns.safe_push (op);
2060 }
2061 else if (e->operation->kind == id_base::PREDICATE)
2062 preds.safe_push (op);
2063 else
2064 {
2065 if (gimple)
2066 gimple_exprs.safe_push (op);
2067 else
2068 generic_exprs.safe_push (op);
2069 }
2070 }
2071 else if (op->op->type == operand::OP_PREDICATE)
2072 others.safe_push (kids[i]);
2073 else
2074 gcc_unreachable ();
2075 }
2076 else if (kids[i]->type == dt_node::DT_MATCH
2077 || kids[i]->type == dt_node::DT_SIMPLIFY)
2078 others.safe_push (kids[i]);
2079 else if (kids[i]->type == dt_node::DT_TRUE)
3990a84c 2080 {
2081 /* A DT_TRUE operand serves as a barrier - generate code now
2082 for what we have collected sofar. */
2083 gen_kids_1 (f, gimple, gimple_exprs, generic_exprs,
2084 fns, generic_fns, preds, others);
2085 /* And output the true operand itself. */
2086 kids[i]->gen (f, gimple);
2087 gimple_exprs.truncate (0);
2088 generic_exprs.truncate (0);
2089 fns.truncate (0);
2090 generic_fns.truncate (0);
2091 preds.truncate (0);
2092 others.truncate (0);
2093 }
2165588a 2094 else
2095 gcc_unreachable ();
2096 }
2097
3990a84c 2098 /* Generate code for the remains. */
2099 gen_kids_1 (f, gimple, gimple_exprs, generic_exprs,
2100 fns, generic_fns, preds, others);
2101}
2102
2103/* Generate matching code for the children of the decision tree node. */
2104
2105void
2106dt_node::gen_kids_1 (FILE *f, bool gimple,
2107 vec<dt_operand *> gimple_exprs,
2108 vec<dt_operand *> generic_exprs,
2109 vec<dt_operand *> fns,
2110 vec<dt_operand *> generic_fns,
2111 vec<dt_operand *> preds,
2112 vec<dt_node *> others)
2113{
2165588a 2114 char buf[128];
2115 char *kid_opname = buf;
2116
2117 unsigned exprs_len = gimple_exprs.length ();
2118 unsigned gexprs_len = generic_exprs.length ();
2119 unsigned fns_len = fns.length ();
2120 unsigned gfns_len = generic_fns.length ();
2121
2122 if (exprs_len || fns_len || gexprs_len || gfns_len)
2123 {
2124 if (exprs_len)
2125 gimple_exprs[0]->get_name (kid_opname);
2126 else if (fns_len)
2127 fns[0]->get_name (kid_opname);
2128 else if (gfns_len)
2129 generic_fns[0]->get_name (kid_opname);
2130 else
2131 generic_exprs[0]->get_name (kid_opname);
2132
2133 fprintf (f, "switch (TREE_CODE (%s))\n"
2134 "{\n", kid_opname);
2135 }
2136
2137 if (exprs_len || fns_len)
2138 {
2139 fprintf (f, "case SSA_NAME:\n");
c434260f 2140 fprintf (f, "if (do_valueize (valueize, %s) != NULL_TREE)\n", kid_opname);
2165588a 2141 fprintf (f, "{\n");
2142 fprintf (f, "gimple def_stmt = SSA_NAME_DEF_STMT (%s);\n", kid_opname);
2143
2144 if (exprs_len)
2145 {
2146 fprintf (f, "if (is_gimple_assign (def_stmt))\n");
2147 fprintf (f, "switch (gimple_assign_rhs_code (def_stmt))\n"
2148 "{\n");
2149 for (unsigned i = 0; i < exprs_len; ++i)
2150 {
2151 expr *e = as_a <expr *> (gimple_exprs[i]->op);
2152 id_base *op = e->operation;
2153 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2154 fprintf (f, "CASE_CONVERT:\n");
2155 else
2156 fprintf (f, "case %s:\n", op->id);
2157 fprintf (f, "{\n");
2158 gimple_exprs[i]->gen (f, true);
2159 fprintf (f, "break;\n"
2160 "}\n");
2161 }
2162 fprintf (f, "default:;\n"
2163 "}\n");
2164 }
2165
2166 if (fns_len)
2167 {
2168 if (exprs_len)
2169 fprintf (f, "else ");
2170
2171 fprintf (f, "if (gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))\n"
2172 "{\n"
2173 "tree fndecl = gimple_call_fndecl (def_stmt);\n"
2174 "switch (DECL_FUNCTION_CODE (fndecl))\n"
2175 "{\n");
2176
2177 for (unsigned i = 0; i < fns_len; ++i)
2178 {
2179 expr *e = as_a <expr *>(fns[i]->op);
2180 fprintf (f, "case %s:\n"
2181 "{\n", e->operation->id);
2182 fns[i]->gen (f, true);
2183 fprintf (f, "break;\n"
2184 "}\n");
2185 }
2186
2187 fprintf (f, "default:;\n"
2188 "}\n"
2189 "}\n");
2190 }
2191
2e064301 2192 fprintf (f, "}\n"
2193 "break;\n");
2165588a 2194 }
2195
2196 for (unsigned i = 0; i < generic_exprs.length (); ++i)
2197 {
2198 expr *e = as_a <expr *>(generic_exprs[i]->op);
2199 id_base *op = e->operation;
2200 if (*op == CONVERT_EXPR || *op == NOP_EXPR)
2201 fprintf (f, "CASE_CONVERT:\n");
2202 else
2203 fprintf (f, "case %s:\n", op->id);
2204 fprintf (f, "{\n");
2205 generic_exprs[i]->gen (f, gimple);
2206 fprintf (f, "break;\n"
2207 "}\n");
2208 }
2209
2210 if (gfns_len)
2211 {
2212 fprintf (f, "case CALL_EXPR:\n"
2213 "{\n"
2214 "tree fndecl = get_callee_fndecl (%s);\n"
2215 "if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)\n"
2216 "switch (DECL_FUNCTION_CODE (fndecl))\n"
2217 "{\n", kid_opname);
2218
2219 for (unsigned j = 0; j < generic_fns.length (); ++j)
2220 {
2221 expr *e = as_a <expr *>(generic_fns[j]->op);
2222 gcc_assert (e->operation->kind == id_base::FN);
2223
2224 fprintf (f, "case %s:\n"
2225 "{\n", e->operation->id);
2226 generic_fns[j]->gen (f, false);
2227 fprintf (f, "break;\n"
2228 "}\n");
2229 }
2230
2231 fprintf (f, "default:;\n"
2232 "}\n"
2233 "break;\n"
2234 "}\n");
2235 }
2236
2237 /* Close switch (TREE_CODE ()). */
2238 if (exprs_len || fns_len || gexprs_len || gfns_len)
2239 fprintf (f, "default:;\n"
2240 "}\n");
2241
2242 for (unsigned i = 0; i < preds.length (); ++i)
2243 {
2244 expr *e = as_a <expr *> (preds[i]->op);
2245 predicate_id *p = as_a <predicate_id *> (e->operation);
2246 preds[i]->get_name (kid_opname);
2247 fprintf (f, "tree %s_pops[%d];\n", kid_opname, p->nargs);
2248 fprintf (f, "if (%s_%s (%s, %s_pops%s))\n",
2249 gimple ? "gimple" : "tree",
2250 p->id, kid_opname, kid_opname,
2251 gimple ? ", valueize" : "");
2252 fprintf (f, "{\n");
2253 for (int j = 0; j < p->nargs; ++j)
2254 {
2255 char child_opname[20];
2256 preds[i]->gen_opname (child_opname, j);
2257 fprintf (f, "tree %s = %s_pops[%d];\n", child_opname, kid_opname, j);
2258 }
2259 preds[i]->gen_kids (f, gimple);
2260 fprintf (f, "}\n");
2261 }
2262
2263 for (unsigned i = 0; i < others.length (); ++i)
2264 others[i]->gen (f, gimple);
2165588a 2265}
2266
2267/* Generate matching code for the decision tree operand. */
2268
2269void
2270dt_operand::gen (FILE *f, bool gimple)
2271{
2272 char opname[20];
2273 get_name (opname);
2274
2275 unsigned n_braces = 0;
2276
2277 if (type == DT_OPERAND)
2278 switch (op->type)
2279 {
2280 case operand::OP_PREDICATE:
2281 n_braces = gen_predicate (f, opname, gimple);
2282 break;
2283
2284 case operand::OP_EXPR:
2285 if (gimple)
2286 n_braces = gen_gimple_expr (f);
2287 else
2288 n_braces = gen_generic_expr (f, opname);
2289 break;
2290
2291 default:
2292 gcc_unreachable ();
2293 }
2294 else if (type == DT_TRUE)
2295 ;
2296 else if (type == DT_MATCH)
2297 n_braces = gen_match_op (f, opname);
2298 else
2299 gcc_unreachable ();
2300
2301 gen_kids (f, gimple);
2302
2303 for (unsigned i = 0; i < n_braces; ++i)
2304 fprintf (f, "}\n");
2305}
2306
55534d34 2307
55534d34 2308
2165588a 2309/* Generate code for the '(if ...)', '(with ..)' and actual transform
2310 step of a '(simplify ...)' or '(match ...)'. This handles everything
2311 that is not part of the decision tree (simplify->match). */
2312
2313void
2314dt_simplify::gen (FILE *f, bool gimple)
2315{
2316 fprintf (f, "{\n");
2317 output_line_directive (f, s->result_location);
2318 if (s->capture_max >= 0)
2319 fprintf (f, "tree captures[%u] ATTRIBUTE_UNUSED = {};\n",
2320 s->capture_max + 1);
2321
2322 for (int i = 0; i <= s->capture_max; ++i)
2323 if (indexes[i])
2324 {
2325 char opname[20];
2326 fprintf (f, "captures[%u] = %s;\n", i, indexes[i]->get_name (opname));
2327 }
2328
2329 unsigned n_braces = 0;
2330 if (s->ifexpr_vec != vNULL)
2331 {
2332 for (unsigned i = 0; i < s->ifexpr_vec.length (); ++i)
2333 {
2334 if_or_with &w = s->ifexpr_vec[i];
2335 if (w.is_with)
2336 {
2337 fprintf (f, "{\n");
2338 output_line_directive (f, w.location);
30d8934c 2339 w.cexpr->gen_transform (f, NULL, true, 1, "type", NULL);
2165588a 2340 n_braces++;
2341 }
2342 else
2343 {
2344 output_line_directive (f, w.location);
2345 fprintf (f, "if (");
2346 if (i == s->ifexpr_vec.length () - 1
2347 || s->ifexpr_vec[i+1].is_with)
30d8934c 2348 w.cexpr->gen_transform (f, NULL, true, 1, "type", NULL);
2165588a 2349 else
2350 {
2351 unsigned j = i;
2352 do
2353 {
2354 if (j != i)
2355 {
2356 fprintf (f, "\n");
2357 output_line_directive (f, s->ifexpr_vec[j].location);
2358 fprintf (f, "&& ");
2359 }
2360 fprintf (f, "(");
2361 s->ifexpr_vec[j].cexpr->gen_transform (f, NULL,
30d8934c 2362 true, 1, "type",
2363 NULL);
2165588a 2364 fprintf (f, ")");
2365 ++j;
2366 }
2367 while (j < s->ifexpr_vec.length ()
2368 && !s->ifexpr_vec[j].is_with);
2369 i = j - 1;
2370 }
2371 fprintf (f, ")\n");
2372 }
2373 }
2374 fprintf (f, "{\n");
2375 n_braces++;
2376 }
2377
55534d34 2378 /* Analyze captures and perform early-outs on the incoming arguments
2379 that cover cases we cannot handle. */
2380 capture_info cinfo (s);
2381 expr *e;
2382 if (!gimple
2383 && s->result
2384 && !((e = dyn_cast <expr *> (s->result))
2385 && is_a <predicate_id *> (e->operation)))
2386 {
2387 for (unsigned i = 0; i < as_a <expr *> (s->match)->ops.length (); ++i)
2388 if (cinfo.force_no_side_effects & (1 << i))
2389 fprintf (f, "if (TREE_SIDE_EFFECTS (op%d)) return NULL_TREE;\n", i);
2390 for (int i = 0; i <= s->capture_max; ++i)
2391 if (cinfo.info[i].cse_p)
2392 ;
2393 else if (cinfo.info[i].force_no_side_effects_p
2394 && (cinfo.info[i].toplevel_msk
2395 & cinfo.force_no_side_effects) == 0)
2396 fprintf (f, "if (TREE_SIDE_EFFECTS (captures[%d])) "
2397 "return NULL_TREE;\n", i);
2398 else if ((cinfo.info[i].toplevel_msk
2399 & cinfo.force_no_side_effects) != 0)
2400 /* Mark capture as having no side-effects if we had to verify
2401 that via forced toplevel operand checks. */
2402 cinfo.info[i].force_no_side_effects_p = true;
2403 }
2404
2165588a 2405 fprintf (f, "if (dump_file && (dump_flags & TDF_DETAILS)) "
2406 "fprintf (dump_file, \"Applying pattern ");
2407 output_line_directive (f, s->result_location, true);
2408 fprintf (f, ", %%s:%%d\\n\", __FILE__, __LINE__);\n");
2409
55534d34 2410 operand *result = s->result;
2411 if (!result)
2165588a 2412 {
2413 /* If there is no result then this is a predicate implementation. */
2414 fprintf (f, "return true;\n");
2415 }
2416 else if (gimple)
2417 {
55534d34 2418 /* For GIMPLE simply drop NON_LVALUE_EXPR (which only appears
2419 in outermost position). */
2420 if (result->type == operand::OP_EXPR
2421 && *as_a <expr *> (result)->operation == NON_LVALUE_EXPR)
2422 result = as_a <expr *> (result)->ops[0];
2423 if (result->type == operand::OP_EXPR)
2165588a 2424 {
55534d34 2425 expr *e = as_a <expr *> (result);
2165588a 2426 bool is_predicate = is_a <predicate_id *> (e->operation);
2427 if (!is_predicate)
e8b67bc2 2428 fprintf (f, "*res_code = %s;\n",
2429 *e->operation == CONVERT_EXPR
2430 ? "NOP_EXPR" : e->operation->id);
2165588a 2431 for (unsigned j = 0; j < e->ops.length (); ++j)
2432 {
2433 char dest[32];
2434 snprintf (dest, 32, " res_ops[%d]", j);
2435 const char *optype
2436 = get_operand_type (e->operation,
2437 "type", e->expr_type,
2438 j == 0
2439 ? NULL : "TREE_TYPE (res_ops[0])");
30d8934c 2440 /* We need to expand GENERIC conditions we captured from
2441 COND_EXPRs. */
2442 bool expand_generic_cond_exprs_p
2443 = (!is_predicate
2444 /* But avoid doing that if the GENERIC condition is
2445 valid - which it is in the first operand of COND_EXPRs
2446 and VEC_COND_EXRPs. */
2447 && ((!(*e->operation == COND_EXPR)
2448 && !(*e->operation == VEC_COND_EXPR))
2449 || j != 0));
2450 e->ops[j]->gen_transform (f, dest, true, 1, optype, &cinfo,
2451 indexes, expand_generic_cond_exprs_p);
2165588a 2452 }
2453
2454 /* Re-fold the toplevel result. It's basically an embedded
2455 gimple_build w/o actually building the stmt. */
2456 if (!is_predicate)
2457 fprintf (f, "gimple_resimplify%d (seq, res_code, type, "
2458 "res_ops, valueize);\n", e->ops.length ());
2459 }
55534d34 2460 else if (result->type == operand::OP_CAPTURE
2461 || result->type == operand::OP_C_EXPR)
2165588a 2462 {
30d8934c 2463 result->gen_transform (f, "res_ops[0]", true, 1, "type",
2464 &cinfo, indexes, false);
2165588a 2465 fprintf (f, "*res_code = TREE_CODE (res_ops[0]);\n");
30d8934c 2466 if (is_a <capture *> (result)
2467 && cinfo.info[as_a <capture *> (result)->where].cond_expr_cond_p)
2468 {
2469 /* ??? Stupid tcc_comparison GENERIC trees in COND_EXPRs. Deal
2470 with substituting a capture of that. */
2471 fprintf (f, "if (COMPARISON_CLASS_P (res_ops[0]))\n"
2472 " {\n"
2473 " tree tem = res_ops[0];\n"
2474 " res_ops[0] = TREE_OPERAND (tem, 0);\n"
2475 " res_ops[1] = TREE_OPERAND (tem, 1);\n"
2476 " }\n");
2477 }
2165588a 2478 }
2479 else
2480 gcc_unreachable ();
2481 fprintf (f, "return true;\n");
2482 }
2483 else /* GENERIC */
2484 {
55534d34 2485 bool is_predicate = false;
2486 if (result->type == operand::OP_EXPR)
2165588a 2487 {
55534d34 2488 expr *e = as_a <expr *> (result);
2489 is_predicate = is_a <predicate_id *> (e->operation);
2490 /* Search for captures used multiple times in the result expression
2491 and dependent on TREE_SIDE_EFFECTS emit a SAVE_EXPR. */
2492 if (!is_predicate)
2493 for (int i = 0; i < s->capture_max + 1; ++i)
2494 {
2495 if (!cinfo.info[i].force_no_side_effects_p
2496 && cinfo.info[i].result_use_count > 1)
2497 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2498 " captures[%d] = save_expr (captures[%d]);\n",
2499 i, i, i);
2500 }
2165588a 2501 for (unsigned j = 0; j < e->ops.length (); ++j)
2502 {
2503 char dest[32];
2504 if (is_predicate)
2505 snprintf (dest, 32, "res_ops[%d]", j);
2506 else
2507 {
2508 fprintf (f, " tree res_op%d;\n", j);
2509 snprintf (dest, 32, " res_op%d", j);
2510 }
2511 const char *optype
2512 = get_operand_type (e->operation,
2513 "type", e->expr_type,
2514 j == 0
2515 ? NULL : "TREE_TYPE (res_op0)");
30d8934c 2516 e->ops[j]->gen_transform (f, dest, false, 1, optype,
2517 &cinfo, indexes);
2165588a 2518 }
55534d34 2519 if (is_predicate)
2165588a 2520 fprintf (f, "return true;\n");
2521 else
2522 {
55534d34 2523 fprintf (f, " tree res;\n");
2524 /* Re-fold the toplevel result. Use non_lvalue to
2525 build NON_LVALUE_EXPRs so they get properly
2526 ignored when in GIMPLE form. */
2527 if (*e->operation == NON_LVALUE_EXPR)
2528 fprintf (f, " res = non_lvalue_loc (loc, res_op0);\n");
2165588a 2529 else
55534d34 2530 {
2531 if (e->operation->kind == id_base::CODE)
2532 fprintf (f, " res = fold_build%d_loc (loc, %s, type",
e8b67bc2 2533 e->ops.length (),
2534 *e->operation == CONVERT_EXPR
2535 ? "NOP_EXPR" : e->operation->id);
55534d34 2536 else
2537 fprintf (f, " res = build_call_expr_loc "
2538 "(loc, builtin_decl_implicit (%s), %d",
2539 e->operation->id, e->ops.length());
2540 for (unsigned j = 0; j < e->ops.length (); ++j)
2541 fprintf (f, ", res_op%d", j);
2542 fprintf (f, ");\n");
2543 }
2165588a 2544 }
2545 }
55534d34 2546 else if (result->type == operand::OP_CAPTURE
2547 || result->type == operand::OP_C_EXPR)
2548
2165588a 2549 {
2550 fprintf (f, " tree res;\n");
30d8934c 2551 s->result->gen_transform (f, " res", false, 1, "type",
2552 &cinfo, indexes);
2165588a 2553 }
2554 else
2555 gcc_unreachable ();
55534d34 2556 if (!is_predicate)
2557 {
2558 /* Search for captures not used in the result expression and dependent
2559 on TREE_SIDE_EFFECTS emit omit_one_operand. */
2560 for (int i = 0; i < s->capture_max + 1; ++i)
2561 {
2562 if (!cinfo.info[i].force_no_side_effects_p
2563 && !cinfo.info[i].expr_p
2564 && cinfo.info[i].result_use_count == 0)
2565 fprintf (f, " if (TREE_SIDE_EFFECTS (captures[%d]))\n"
2566 " res = build2_loc (loc, COMPOUND_EXPR, type,"
2567 " fold_ignored_result (captures[%d]), res);\n",
2568 i, i);
2569 }
2570 fprintf (f, " return res;\n");
2571 }
2165588a 2572 }
2573
2574 for (unsigned i = 0; i < n_braces; ++i)
2575 fprintf (f, "}\n");
2576
2577 fprintf (f, "}\n");
2578}
2579
2580/* Main entry to generate code for matching GIMPLE IL off the decision
2581 tree. */
2582
2583void
2584decision_tree::gen_gimple (FILE *f)
2585{
2586 for (unsigned n = 1; n <= 3; ++n)
2587 {
2588 fprintf (f, "\nstatic bool\n"
2589 "gimple_simplify (code_helper *res_code, tree *res_ops,\n"
2590 " gimple_seq *seq, tree (*valueize)(tree),\n"
2591 " code_helper code, tree type");
2592 for (unsigned i = 0; i < n; ++i)
2593 fprintf (f, ", tree op%d", i);
2594 fprintf (f, ")\n");
2595 fprintf (f, "{\n");
2596
2597 fprintf (f, "switch (code.get_rep())\n"
2598 "{\n");
2599 for (unsigned i = 0; i < root->kids.length (); i++)
2600 {
2601 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2602 expr *e = static_cast<expr *>(dop->op);
2603 if (e->ops.length () != n)
2604 continue;
2605
2606 if (*e->operation == CONVERT_EXPR
2607 || *e->operation == NOP_EXPR)
2608 fprintf (f, "CASE_CONVERT:\n");
2609 else
2610 fprintf (f, "case %s%s:\n",
2611 is_a <fn_id *> (e->operation) ? "-" : "",
2612 e->operation->id);
2613 fprintf (f, "{\n");
2614 dop->gen_kids (f, true);
2615 fprintf (f, "break;\n");
2616 fprintf (f, "}\n");
2617 }
2618 fprintf (f, "default:;\n"
2619 "}\n");
2620
2621 fprintf (f, "return false;\n");
2622 fprintf (f, "}\n");
2623 }
2624}
2625
2626/* Main entry to generate code for matching GENERIC IL off the decision
2627 tree. */
2628
2629void
2630decision_tree::gen_generic (FILE *f)
2631{
2632 for (unsigned n = 1; n <= 3; ++n)
2633 {
2634 fprintf (f, "\ntree\n"
55534d34 2635 "generic_simplify (location_t loc, enum tree_code code, "
2165588a 2636 "tree type ATTRIBUTE_UNUSED");
2637 for (unsigned i = 0; i < n; ++i)
2638 fprintf (f, ", tree op%d", i);
2639 fprintf (f, ")\n");
2640 fprintf (f, "{\n");
2641
2165588a 2642 fprintf (f, "switch (code)\n"
2643 "{\n");
2644 for (unsigned i = 0; i < root->kids.length (); i++)
2645 {
2646 dt_operand *dop = static_cast<dt_operand *>(root->kids[i]);
2647 expr *e = static_cast<expr *>(dop->op);
2648 if (e->ops.length () != n
2649 /* Builtin simplifications are somewhat premature on
2650 GENERIC. The following drops patterns with outermost
2651 calls. It's easy to emit overloads for function code
2652 though if necessary. */
2653 || e->operation->kind != id_base::CODE)
2654 continue;
2655
2656 operator_id *op_id = static_cast <operator_id *> (e->operation);
2657 if (op_id->code == NOP_EXPR || op_id->code == CONVERT_EXPR)
2658 fprintf (f, "CASE_CONVERT:\n");
2659 else
2660 fprintf (f, "case %s:\n", e->operation->id);
2661 fprintf (f, "{\n");
2662 dop->gen_kids (f, false);
2663 fprintf (f, "break;\n"
2664 "}\n");
2665 }
2666 fprintf (f, "default:;\n"
2667 "}\n");
2668
2669 fprintf (f, "return NULL_TREE;\n");
2670 fprintf (f, "}\n");
2671 }
2672}
2673
2674/* Output code to implement the predicate P from the decision tree DT. */
2675
2676void
2677write_predicate (FILE *f, predicate_id *p, decision_tree &dt, bool gimple)
2678{
2679 fprintf (f, "\nbool\n"
2680 "%s%s (tree t%s%s)\n"
2681 "{\n", gimple ? "gimple_" : "tree_", p->id,
2682 p->nargs > 0 ? ", tree *res_ops" : "",
2683 gimple ? ", tree (*valueize)(tree)" : "");
2684 /* Conveniently make 'type' available. */
2685 fprintf (f, "tree type = TREE_TYPE (t);\n");
2686
2687 if (!gimple)
2688 fprintf (f, "if (TREE_SIDE_EFFECTS (t)) return false;\n");
2689 dt.root->gen_kids (f, gimple);
2690
2691 fprintf (f, "return false;\n"
2692 "}\n");
2693}
2694
2695/* Write the common header for the GIMPLE/GENERIC IL matching routines. */
2696
2697static void
2698write_header (FILE *f, const char *head)
2699{
2700 fprintf (f, "/* Generated automatically by the program `genmatch' from\n");
2701 fprintf (f, " a IL pattern matching and simplification description. */\n");
2702
2703 /* Include the header instead of writing it awkwardly quoted here. */
2704 fprintf (f, "\n#include \"%s\"\n", head);
2705}
2706
2707
2708
2709/* AST parsing. */
2710
2711class parser
2712{
2713public:
2714 parser (cpp_reader *);
2715
2716private:
2717 const cpp_token *next ();
2718 const cpp_token *peek ();
2719 const cpp_token *peek_ident (const char * = NULL);
2720 const cpp_token *expect (enum cpp_ttype);
2721 void eat_token (enum cpp_ttype);
2722 const char *get_string ();
2723 const char *get_ident ();
2724 void eat_ident (const char *);
2725 const char *get_number ();
2726
2727 id_base *parse_operation ();
2728 operand *parse_capture (operand *);
2729 operand *parse_expr ();
2730 c_expr *parse_c_expr (cpp_ttype);
2731 operand *parse_op ();
2732
3c181717 2733 void record_operlist (source_location, user_id *);
2734
2165588a 2735 void parse_pattern ();
3c181717 2736 void push_simplify (vec<simplify *>&, operand *, source_location,
2737 operand *, source_location);
2165588a 2738 void parse_simplify (source_location, vec<simplify *>&, predicate_id *,
2739 expr *);
2740 void parse_for (source_location);
2741 void parse_if (source_location);
2742 void parse_predicates (source_location);
38d93c27 2743 void parse_operator_list (source_location);
2165588a 2744
2745 cpp_reader *r;
2746 vec<if_or_with> active_ifs;
2747 vec<vec<user_id *> > active_fors;
3c181717 2748 hash_set<user_id *> *oper_lists_set;
2749 vec<user_id *> oper_lists;
2165588a 2750
80c3d8cf 2751 cid_map_t *capture_ids;
2165588a 2752
2753public:
2754 vec<simplify *> simplifiers;
2755 vec<predicate_id *> user_predicates;
38d93c27 2756 bool parsing_match_operand;
2165588a 2757};
2758
2759/* Lexing helpers. */
2760
2761/* Read the next non-whitespace token from R. */
2762
2763const cpp_token *
2764parser::next ()
2765{
2766 const cpp_token *token;
2767 do
2768 {
2769 token = cpp_get_token (r);
2770 }
2771 while (token->type == CPP_PADDING
2772 && token->type != CPP_EOF);
2773 return token;
2774}
2775
2776/* Peek at the next non-whitespace token from R. */
2777
2778const cpp_token *
2779parser::peek ()
2780{
2781 const cpp_token *token;
2782 unsigned i = 0;
2783 do
2784 {
2785 token = cpp_peek_token (r, i++);
2786 }
2787 while (token->type == CPP_PADDING
2788 && token->type != CPP_EOF);
2789 /* If we peek at EOF this is a fatal error as it leaves the
2790 cpp_reader in unusable state. Assume we really wanted a
2791 token and thus this EOF is unexpected. */
2792 if (token->type == CPP_EOF)
2793 fatal_at (token, "unexpected end of file");
2794 return token;
2795}
2796
2797/* Peek at the next identifier token (or return NULL if the next
2798 token is not an identifier or equal to ID if supplied). */
2799
2800const cpp_token *
2801parser::peek_ident (const char *id)
2802{
2803 const cpp_token *token = peek ();
2804 if (token->type != CPP_NAME)
2805 return 0;
2806
2807 if (id == 0)
2808 return token;
2809
2810 const char *t = (const char *) CPP_HASHNODE (token->val.node.node)->ident.str;
2811 if (strcmp (id, t) == 0)
2812 return token;
2813
2814 return 0;
2815}
2816
2817/* Read the next token from R and assert it is of type TK. */
2818
2819const cpp_token *
2820parser::expect (enum cpp_ttype tk)
2821{
2822 const cpp_token *token = next ();
2823 if (token->type != tk)
2824 fatal_at (token, "expected %s, got %s",
2825 cpp_type2name (tk, 0), cpp_type2name (token->type, 0));
2826
2827 return token;
2828}
2829
2830/* Consume the next token from R and assert it is of type TK. */
2831
2832void
2833parser::eat_token (enum cpp_ttype tk)
2834{
2835 expect (tk);
2836}
2837
2838/* Read the next token from R and assert it is of type CPP_STRING and
2839 return its value. */
2840
2841const char *
2842parser::get_string ()
2843{
2844 const cpp_token *token = expect (CPP_STRING);
2845 return (const char *)token->val.str.text;
2846}
2847
2848/* Read the next token from R and assert it is of type CPP_NAME and
2849 return its value. */
2850
2851const char *
2852parser::get_ident ()
2853{
2854 const cpp_token *token = expect (CPP_NAME);
2855 return (const char *)CPP_HASHNODE (token->val.node.node)->ident.str;
2856}
2857
2858/* Eat an identifier token with value S from R. */
2859
2860void
2861parser::eat_ident (const char *s)
2862{
2863 const cpp_token *token = peek ();
2864 const char *t = get_ident ();
2865 if (strcmp (s, t) != 0)
2866 fatal_at (token, "expected '%s' got '%s'\n", s, t);
2867}
2868
2869/* Read the next token from R and assert it is of type CPP_NUMBER and
2870 return its value. */
2871
2872const char *
2873parser::get_number ()
2874{
2875 const cpp_token *token = expect (CPP_NUMBER);
2876 return (const char *)token->val.str.text;
2877}
2878
2879
3c181717 2880/* Record an operator-list use for transparent for handling. */
2881
2882void
2883parser::record_operlist (source_location loc, user_id *p)
2884{
2885 if (!oper_lists_set->add (p))
2886 {
2887 if (!oper_lists.is_empty ()
2888 && oper_lists[0]->substitutes.length () != p->substitutes.length ())
2889 fatal_at (loc, "User-defined operator list does not have the "
2890 "same number of entries as others used in the pattern");
2891 oper_lists.safe_push (p);
2892 }
2893}
2894
2165588a 2895/* Parse the operator ID, special-casing convert?, convert1? and
2896 convert2? */
2897
2898id_base *
2899parser::parse_operation ()
2900{
2901 const cpp_token *id_tok = peek ();
2902 const char *id = get_ident ();
2903 const cpp_token *token = peek ();
2904 if (strcmp (id, "convert0") == 0)
2905 fatal_at (id_tok, "use 'convert?' here");
53e2e97e 2906 else if (strcmp (id, "view_convert0") == 0)
2907 fatal_at (id_tok, "use 'view_convert?' here");
2165588a 2908 if (token->type == CPP_QUERY
2909 && !(token->flags & PREV_WHITE))
2910 {
2911 if (strcmp (id, "convert") == 0)
2912 id = "convert0";
53e2e97e 2913 else if (strcmp (id, "convert1") == 0)
2165588a 2914 ;
53e2e97e 2915 else if (strcmp (id, "convert2") == 0)
2916 ;
2917 else if (strcmp (id, "view_convert") == 0)
2918 id = "view_convert0";
2919 else if (strcmp (id, "view_convert1") == 0)
2920 ;
2921 else if (strcmp (id, "view_convert2") == 0)
2165588a 2922 ;
2923 else
2924 fatal_at (id_tok, "non-convert operator conditionalized");
38d93c27 2925
2926 if (!parsing_match_operand)
2927 fatal_at (id_tok, "conditional convert can only be used in "
2928 "match expression");
2165588a 2929 eat_token (CPP_QUERY);
2930 }
53e2e97e 2931 else if (strcmp (id, "convert1") == 0
2932 || strcmp (id, "convert2") == 0
2933 || strcmp (id, "view_convert1") == 0
2934 || strcmp (id, "view_convert2") == 0)
2165588a 2935 fatal_at (id_tok, "expected '?' after conditional operator");
2936 id_base *op = get_operator (id);
2937 if (!op)
2938 fatal_at (id_tok, "unknown operator %s", id);
38d93c27 2939
2940 user_id *p = dyn_cast<user_id *> (op);
2941 if (p && p->is_oper_list)
b2f775ec 2942 {
2943 if (active_fors.length() == 0)
2944 record_operlist (id_tok->src_loc, p);
2945 else
2946 fatal_at (id_tok, "operator-list %s cannot be exapnded inside 'for'", id);
2947 }
2165588a 2948 return op;
2949}
2950
2951/* Parse a capture.
2952 capture = '@'<number> */
2953
2954struct operand *
2955parser::parse_capture (operand *op)
2956{
2957 eat_token (CPP_ATSIGN);
2958 const cpp_token *token = peek ();
38d93c27 2959 const char *id = NULL;
2165588a 2960 if (token->type == CPP_NUMBER)
2961 id = get_number ();
2962 else if (token->type == CPP_NAME)
2963 id = get_ident ();
2964 else
2965 fatal_at (token, "expected number or identifier");
80c3d8cf 2966 unsigned next_id = capture_ids->elements ();
2967 bool existed;
2968 unsigned &num = capture_ids->get_or_insert (id, &existed);
2969 if (!existed)
2970 num = next_id;
2971 return new capture (num, op);
2165588a 2972}
2973
2974/* Parse an expression
2975 expr = '(' <operation>[capture][flag][type] <operand>... ')' */
2976
2977struct operand *
2978parser::parse_expr ()
2979{
2980 expr *e = new expr (parse_operation ());
2981 const cpp_token *token = peek ();
2982 operand *op;
2983 bool is_commutative = false;
2984 const char *expr_type = NULL;
2985
2986 if (token->type == CPP_COLON
2987 && !(token->flags & PREV_WHITE))
2988 {
2989 eat_token (CPP_COLON);
2990 token = peek ();
2991 if (token->type == CPP_NAME
2992 && !(token->flags & PREV_WHITE))
2993 {
2994 const char *s = get_ident ();
2995 if (s[0] == 'c' && !s[1])
38d93c27 2996 {
2997 if (!parsing_match_operand)
2998 fatal_at (token,
2999 "flag 'c' can only be used in match expression");
3000 is_commutative = true;
3001 }
2165588a 3002 else if (s[1] != '\0')
38d93c27 3003 {
3004 if (parsing_match_operand)
3005 fatal_at (token, "type can only be used in result expression");
3006 expr_type = s;
3007 }
2165588a 3008 else
3009 fatal_at (token, "flag %s not recognized", s);
38d93c27 3010
2165588a 3011 token = peek ();
3012 }
3013 else
3014 fatal_at (token, "expected flag or type specifying identifier");
3015 }
3016
3017 if (token->type == CPP_ATSIGN
3018 && !(token->flags & PREV_WHITE))
3019 op = parse_capture (e);
3020 else
3021 op = e;
3022 do
3023 {
3024 const cpp_token *token = peek ();
3025 if (token->type == CPP_CLOSE_PAREN)
3026 {
3027 if (e->operation->nargs != -1
3028 && e->operation->nargs != (int) e->ops.length ())
3029 fatal_at (token, "'%s' expects %u operands, not %u",
3030 e->operation->id, e->operation->nargs, e->ops.length ());
3031 if (is_commutative)
3032 {
3033 if (e->ops.length () == 2)
3034 e->is_commutative = true;
3035 else
3036 fatal_at (token, "only binary operators or function with "
3037 "two arguments can be marked commutative");
3038 }
3039 e->expr_type = expr_type;
3040 return op;
3041 }
3042 e->append_op (parse_op ());
3043 }
3044 while (1);
3045}
3046
3047/* Lex native C code delimited by START recording the preprocessing tokens
3048 for later processing.
3049 c_expr = ('{'|'(') <pp token>... ('}'|')') */
3050
3051c_expr *
3052parser::parse_c_expr (cpp_ttype start)
3053{
3054 const cpp_token *token;
3055 cpp_ttype end;
3056 unsigned opencnt;
3057 vec<cpp_token> code = vNULL;
3058 unsigned nr_stmts = 0;
3059 eat_token (start);
3060 if (start == CPP_OPEN_PAREN)
3061 end = CPP_CLOSE_PAREN;
3062 else if (start == CPP_OPEN_BRACE)
3063 end = CPP_CLOSE_BRACE;
3064 else
3065 gcc_unreachable ();
3066 opencnt = 1;
3067 do
3068 {
3069 token = next ();
3070
3071 /* Count brace pairs to find the end of the expr to match. */
3072 if (token->type == start)
3073 opencnt++;
3074 else if (token->type == end
3075 && --opencnt == 0)
3076 break;
3077
3078 /* This is a lame way of counting the number of statements. */
3079 if (token->type == CPP_SEMICOLON)
3080 nr_stmts++;
3081
38d93c27 3082 /* If this is possibly a user-defined identifier mark it used. */
3083 if (token->type == CPP_NAME)
3c181717 3084 {
3085 id_base *idb = get_operator ((const char *)CPP_HASHNODE
3086 (token->val.node.node)->ident.str);
3087 user_id *p;
3088 if (idb && (p = dyn_cast<user_id *> (idb)) && p->is_oper_list)
3089 record_operlist (token->src_loc, p);
3090 }
38d93c27 3091
2165588a 3092 /* Record the token. */
3093 code.safe_push (*token);
3094 }
3095 while (1);
3096 return new c_expr (r, code, nr_stmts, vNULL, capture_ids);
3097}
3098
3099/* Parse an operand which is either an expression, a predicate or
3100 a standalone capture.
3101 op = predicate | expr | c_expr | capture */
3102
3103struct operand *
3104parser::parse_op ()
3105{
3106 const cpp_token *token = peek ();
3107 struct operand *op = NULL;
3108 if (token->type == CPP_OPEN_PAREN)
3109 {
3110 eat_token (CPP_OPEN_PAREN);
3111 op = parse_expr ();
3112 eat_token (CPP_CLOSE_PAREN);
3113 }
3114 else if (token->type == CPP_OPEN_BRACE)
3115 {
3116 op = parse_c_expr (CPP_OPEN_BRACE);
3117 }
3118 else
3119 {
3120 /* Remaining ops are either empty or predicates */
3121 if (token->type == CPP_NAME)
3122 {
3123 const char *id = get_ident ();
3124 id_base *opr = get_operator (id);
3125 if (!opr)
3126 fatal_at (token, "expected predicate name");
3127 if (operator_id *code = dyn_cast <operator_id *> (opr))
3128 {
3129 if (code->nargs != 0)
3130 fatal_at (token, "using an operator with operands as predicate");
3131 /* Parse the zero-operand operator "predicates" as
3132 expression. */
3133 op = new expr (opr);
3134 }
7c430700 3135 else if (user_id *code = dyn_cast <user_id *> (opr))
3136 {
3137 if (code->nargs != 0)
3138 fatal_at (token, "using an operator with operands as predicate");
3139 /* Parse the zero-operand operator "predicates" as
3140 expression. */
3141 op = new expr (opr);
3142 }
2165588a 3143 else if (predicate_id *p = dyn_cast <predicate_id *> (opr))
3144 op = new predicate (p);
3145 else
3146 fatal_at (token, "using an unsupported operator as predicate");
38d93c27 3147 if (!parsing_match_operand)
3148 fatal_at (token, "predicates are only allowed in match expression");
2165588a 3149 token = peek ();
3150 if (token->flags & PREV_WHITE)
3151 return op;
3152 }
3153 else if (token->type != CPP_COLON
3154 && token->type != CPP_ATSIGN)
3155 fatal_at (token, "expected expression or predicate");
3156 /* optionally followed by a capture and a predicate. */
3157 if (token->type == CPP_COLON)
3158 fatal_at (token, "not implemented: predicate on leaf operand");
3159 if (token->type == CPP_ATSIGN)
3160 op = parse_capture (op);
3161 }
3162
3163 return op;
3164}
3165
3c181717 3166/* Create a new simplify from the current parsing state and MATCH,
3167 MATCH_LOC, RESULT and RESULT_LOC and push it to SIMPLIFIERS. */
3168
3169void
3170parser::push_simplify (vec<simplify *>& simplifiers,
3171 operand *match, source_location match_loc,
3172 operand *result, source_location result_loc)
3173{
3174 /* Build and push a temporary for for operator list uses in expressions. */
3175 if (!oper_lists.is_empty ())
3176 active_fors.safe_push (oper_lists);
3177
3178 simplifiers.safe_push
3179 (new simplify (match, match_loc, result, result_loc,
3180 active_ifs.copy (), active_fors.copy (), capture_ids));
3181
3182 if (!oper_lists.is_empty ())
3183 active_fors.pop ();
3184}
3185
2165588a 3186/* Parse
3187 simplify = 'simplify' <expr> <result-op>
3188 or
3189 match = 'match' <ident> <expr> [<result-op>]
3190 with
3191 <result-op> = <op> | <if> | <with>
3192 <if> = '(' 'if' '(' <c-expr> ')' <result-op> ')'
3193 <with> = '(' 'with' '{' <c-expr> '}' <result-op> ')'
3194 and fill SIMPLIFIERS with the results. */
3195
3196void
3197parser::parse_simplify (source_location match_location,
3198 vec<simplify *>& simplifiers, predicate_id *matcher,
3199 expr *result)
3200{
3201 /* Reset the capture map. */
852fa94e 3202 if (!capture_ids)
3203 capture_ids = new cid_map_t;
3c181717 3204 /* Reset oper_lists and set. */
3205 hash_set <user_id *> olist;
3206 oper_lists_set = &olist;
3207 oper_lists = vNULL;
2165588a 3208
3209 const cpp_token *loc = peek ();
38d93c27 3210 parsing_match_operand = true;
2165588a 3211 struct operand *match = parse_op ();
38d93c27 3212 parsing_match_operand = false;
2165588a 3213 if (match->type == operand::OP_CAPTURE && !matcher)
3214 fatal_at (loc, "outermost expression cannot be captured");
3215 if (match->type == operand::OP_EXPR
3216 && is_a <predicate_id *> (as_a <expr *> (match)->operation))
3217 fatal_at (loc, "outermost expression cannot be a predicate");
3218
3219 const cpp_token *token = peek ();
3220
3221 /* If this if is immediately closed then it is part of a predicate
3222 definition. Push it. */
3223 if (token->type == CPP_CLOSE_PAREN)
3224 {
3225 if (!matcher)
3226 fatal_at (token, "expected transform expression");
3c181717 3227 push_simplify (simplifiers, match, match_location,
3228 result, token->src_loc);
2165588a 3229 return;
3230 }
3231
3232 unsigned active_ifs_len = active_ifs.length ();
3233 while (1)
3234 {
3235 if (token->type == CPP_OPEN_PAREN)
3236 {
3237 source_location paren_loc = token->src_loc;
3238 eat_token (CPP_OPEN_PAREN);
3239 if (peek_ident ("if"))
3240 {
3241 eat_ident ("if");
3242 active_ifs.safe_push (if_or_with (parse_c_expr (CPP_OPEN_PAREN),
3243 token->src_loc, false));
3244 /* If this if is immediately closed then it contains a
3245 manual matcher or is part of a predicate definition.
3246 Push it. */
3247 if (peek ()->type == CPP_CLOSE_PAREN)
3248 {
3249 if (!matcher)
3250 fatal_at (token, "manual transform not implemented");
3c181717 3251 push_simplify (simplifiers, match, match_location,
3252 result, paren_loc);
2165588a 3253 }
3254 }
3255 else if (peek_ident ("with"))
3256 {
3257 eat_ident ("with");
3258 /* Parse (with c-expr expr) as (if-with (true) expr). */
3259 c_expr *e = parse_c_expr (CPP_OPEN_BRACE);
3260 e->nr_stmts = 0;
3261 active_ifs.safe_push (if_or_with (e, token->src_loc, true));
3262 }
3263 else
3264 {
3265 operand *op = result;
3266 if (!matcher)
3267 op = parse_expr ();
3c181717 3268 push_simplify (simplifiers, match, match_location,
3269 op, token->src_loc);
2165588a 3270 eat_token (CPP_CLOSE_PAREN);
3271 /* A "default" result closes the enclosing scope. */
3272 if (active_ifs.length () > active_ifs_len)
3273 {
3274 eat_token (CPP_CLOSE_PAREN);
3275 active_ifs.pop ();
3276 }
3277 else
3278 return;
3279 }
3280 }
3281 else if (token->type == CPP_CLOSE_PAREN)
3282 {
3283 /* Close a scope if requested. */
3284 if (active_ifs.length () > active_ifs_len)
3285 {
3286 eat_token (CPP_CLOSE_PAREN);
3287 active_ifs.pop ();
3288 token = peek ();
3289 }
3290 else
3291 return;
3292 }
3293 else
3294 {
3295 if (matcher)
3296 fatal_at (token, "expected match operand expression");
3c181717 3297 push_simplify (simplifiers, match, match_location,
3298 matcher ? result : parse_op (), token->src_loc);
2165588a 3299 /* A "default" result closes the enclosing scope. */
3300 if (active_ifs.length () > active_ifs_len)
3301 {
3302 eat_token (CPP_CLOSE_PAREN);
3303 active_ifs.pop ();
3304 }
3305 else
3306 return;
3307 }
3308 token = peek ();
3309 }
3310}
3311
3312/* Parsing of the outer control structures. */
3313
3314/* Parse a for expression
3315 for = '(' 'for' <subst>... <pattern> ')'
3316 subst = <ident> '(' <ident>... ')' */
3317
3318void
3319parser::parse_for (source_location)
3320{
38d93c27 3321 auto_vec<const cpp_token *> user_id_tokens;
2165588a 3322 vec<user_id *> user_ids = vNULL;
3323 const cpp_token *token;
3324 unsigned min_n_opers = 0, max_n_opers = 0;
3325
3326 while (1)
3327 {
38d93c27 3328 token = peek ();
3329 if (token->type != CPP_NAME)
2165588a 3330 break;
3331
3332 /* Insert the user defined operators into the operator hash. */
3333 const char *id = get_ident ();
38d93c27 3334 if (get_operator (id) != NULL)
3335 fatal_at (token, "operator already defined");
2165588a 3336 user_id *op = new user_id (id);
3337 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
2165588a 3338 *slot = op;
3339 user_ids.safe_push (op);
38d93c27 3340 user_id_tokens.safe_push (token);
2165588a 3341
3342 eat_token (CPP_OPEN_PAREN);
3343
3344 int arity = -1;
3345 while ((token = peek_ident ()) != 0)
3346 {
3347 const char *oper = get_ident ();
3348 id_base *idb = get_operator (oper);
3349 if (idb == NULL)
3350 fatal_at (token, "no such operator '%s'", oper);
53e2e97e 3351 if (*idb == CONVERT0 || *idb == CONVERT1 || *idb == CONVERT2
3352 || *idb == VIEW_CONVERT0 || *idb == VIEW_CONVERT1
3353 || *idb == VIEW_CONVERT2)
2165588a 3354 fatal_at (token, "conditional operators cannot be used inside for");
3355
3356 if (arity == -1)
3357 arity = idb->nargs;
3358 else if (idb->nargs == -1)
3359 ;
3360 else if (idb->nargs != arity)
3361 fatal_at (token, "operator '%s' with arity %d does not match "
3362 "others with arity %d", oper, idb->nargs, arity);
3363
38d93c27 3364 user_id *p = dyn_cast<user_id *> (idb);
dbe4b31f 3365 if (p)
3366 {
3367 if (p->is_oper_list)
3368 op->substitutes.safe_splice (p->substitutes);
3369 else
3370 fatal_at (token, "iterator cannot be used as operator-list");
3371 }
38d93c27 3372 else
3373 op->substitutes.safe_push (idb);
2165588a 3374 }
3375 op->nargs = arity;
3376 token = expect (CPP_CLOSE_PAREN);
3377
3378 unsigned nsubstitutes = op->substitutes.length ();
3379 if (nsubstitutes == 0)
3380 fatal_at (token, "A user-defined operator must have at least "
3381 "one substitution");
3382 if (max_n_opers == 0)
3383 {
3384 min_n_opers = nsubstitutes;
3385 max_n_opers = nsubstitutes;
3386 }
3387 else
3388 {
3389 if (nsubstitutes % min_n_opers != 0
3390 && min_n_opers % nsubstitutes != 0)
3391 fatal_at (token, "All user-defined identifiers must have a "
3392 "multiple number of operator substitutions of the "
3393 "smallest number of substitutions");
3394 if (nsubstitutes < min_n_opers)
3395 min_n_opers = nsubstitutes;
3396 else if (nsubstitutes > max_n_opers)
3397 max_n_opers = nsubstitutes;
3398 }
3399 }
3400
3401 unsigned n_ids = user_ids.length ();
3402 if (n_ids == 0)
3403 fatal_at (token, "for requires at least one user-defined identifier");
3404
3405 token = peek ();
3406 if (token->type == CPP_CLOSE_PAREN)
3407 fatal_at (token, "no pattern defined in for");
3408
3409 active_fors.safe_push (user_ids);
3410 while (1)
3411 {
3412 token = peek ();
3413 if (token->type == CPP_CLOSE_PAREN)
3414 break;
3415 parse_pattern ();
3416 }
3417 active_fors.pop ();
3418
3419 /* Remove user-defined operators from the hash again. */
3420 for (unsigned i = 0; i < user_ids.length (); ++i)
38d93c27 3421 {
3422 if (!user_ids[i]->used)
3423 warning_at (user_id_tokens[i],
3424 "operator %s defined but not used", user_ids[i]->id);
3425 operators->remove_elt (user_ids[i]);
3426 }
3427}
3428
3429/* Parse an identifier associated with a list of operators.
3430 oprs = '(' 'define_operator_list' <ident> <ident>... ')' */
3431
3432void
3433parser::parse_operator_list (source_location)
3434{
3435 const cpp_token *token = peek ();
3436 const char *id = get_ident ();
3437
3438 if (get_operator (id) != 0)
3439 fatal_at (token, "operator %s already defined", id);
3440
3441 user_id *op = new user_id (id, true);
3442 int arity = -1;
3443
3444 while ((token = peek_ident ()) != 0)
3445 {
3446 token = peek ();
3447 const char *oper = get_ident ();
3448 id_base *idb = get_operator (oper);
3449
3450 if (idb == 0)
3451 fatal_at (token, "no such operator '%s'", oper);
3452
3453 if (arity == -1)
3454 arity = idb->nargs;
3455 else if (idb->nargs == -1)
3456 ;
3457 else if (arity != idb->nargs)
3458 fatal_at (token, "operator '%s' with arity %d does not match "
3459 "others with arity %d", oper, idb->nargs, arity);
3460
3461 /* We allow composition of multiple operator lists. */
3462 if (user_id *p = dyn_cast<user_id *> (idb))
3463 op->substitutes.safe_splice (p->substitutes);
3464 else
3465 op->substitutes.safe_push (idb);
3466 }
3467
a03dcfdb 3468 // Check that there is no junk after id-list
3469 token = peek();
3470 if (token->type != CPP_CLOSE_PAREN)
3471 fatal_at (token, "expected identifier got %s", cpp_type2name (token->type, 0));
3472
38d93c27 3473 if (op->substitutes.length () == 0)
3474 fatal_at (token, "operator-list cannot be empty");
3475
3476 op->nargs = arity;
3477 id_base **slot = operators->find_slot_with_hash (op, op->hashval, INSERT);
3478 *slot = op;
2165588a 3479}
3480
3481/* Parse an outer if expression.
3482 if = '(' 'if' '(' <c-expr> ')' <pattern> ')' */
3483
3484void
3485parser::parse_if (source_location loc)
3486{
3487 operand *ifexpr = parse_c_expr (CPP_OPEN_PAREN);
3488
3489 const cpp_token *token = peek ();
3490 if (token->type == CPP_CLOSE_PAREN)
3491 fatal_at (token, "no pattern defined in if");
3492
3493 active_ifs.safe_push (if_or_with (ifexpr, loc, false));
3494 while (1)
3495 {
3496 const cpp_token *token = peek ();
3497 if (token->type == CPP_CLOSE_PAREN)
3498 break;
3499
3500 parse_pattern ();
3501 }
3502 active_ifs.pop ();
3503}
3504
3505/* Parse a list of predefined predicate identifiers.
3506 preds = '(' 'define_predicates' <ident>... ')' */
3507
3508void
3509parser::parse_predicates (source_location)
3510{
3511 do
3512 {
3513 const cpp_token *token = peek ();
3514 if (token->type != CPP_NAME)
3515 break;
3516
3517 add_predicate (get_ident ());
3518 }
3519 while (1);
3520}
3521
3522/* Parse outer control structures.
3523 pattern = <preds>|<for>|<if>|<simplify>|<match> */
3524
3525void
3526parser::parse_pattern ()
3527{
3528 /* All clauses start with '('. */
3529 eat_token (CPP_OPEN_PAREN);
3530 const cpp_token *token = peek ();
3531 const char *id = get_ident ();
3532 if (strcmp (id, "simplify") == 0)
852fa94e 3533 {
3534 parse_simplify (token->src_loc, simplifiers, NULL, NULL);
3535 capture_ids = NULL;
3536 }
2165588a 3537 else if (strcmp (id, "match") == 0)
3538 {
3539 bool with_args = false;
3540 if (peek ()->type == CPP_OPEN_PAREN)
3541 {
3542 eat_token (CPP_OPEN_PAREN);
3543 with_args = true;
3544 }
3545 const char *name = get_ident ();
3546 id_base *id = get_operator (name);
3547 predicate_id *p;
3548 if (!id)
3549 {
3550 p = add_predicate (name);
3551 user_predicates.safe_push (p);
3552 }
3553 else if ((p = dyn_cast <predicate_id *> (id)))
3554 ;
3555 else
3556 fatal_at (token, "cannot add a match to a non-predicate ID");
3557 /* Parse (match <id> <arg>... (match-expr)) here. */
3558 expr *e = NULL;
3559 if (with_args)
3560 {
852fa94e 3561 capture_ids = new cid_map_t;
2165588a 3562 e = new expr (p);
3563 while (peek ()->type == CPP_ATSIGN)
3564 e->append_op (parse_capture (NULL));
3565 eat_token (CPP_CLOSE_PAREN);
3566 }
3567 if (p->nargs != -1
3568 && ((e && e->ops.length () != (unsigned)p->nargs)
3569 || (!e && p->nargs != 0)))
3570 fatal_at (token, "non-matching number of match operands");
3571 p->nargs = e ? e->ops.length () : 0;
3572 parse_simplify (token->src_loc, p->matchers, p, e);
852fa94e 3573 capture_ids = NULL;
2165588a 3574 }
3575 else if (strcmp (id, "for") == 0)
3576 parse_for (token->src_loc);
3577 else if (strcmp (id, "if") == 0)
3578 parse_if (token->src_loc);
3579 else if (strcmp (id, "define_predicates") == 0)
3580 {
3581 if (active_ifs.length () > 0
3582 || active_fors.length () > 0)
3583 fatal_at (token, "define_predicates inside if or for is not supported");
3584 parse_predicates (token->src_loc);
3585 }
38d93c27 3586 else if (strcmp (id, "define_operator_list") == 0)
3587 {
3588 if (active_ifs.length () > 0
3589 || active_fors.length () > 0)
3590 fatal_at (token, "operator-list inside if or for is not supported");
3591 parse_operator_list (token->src_loc);
3592 }
2165588a 3593 else
3594 fatal_at (token, "expected %s'simplify', 'match', 'for' or 'if'",
3595 active_ifs.length () == 0 && active_fors.length () == 0
3596 ? "'define_predicates', " : "");
3597
3598 eat_token (CPP_CLOSE_PAREN);
3599}
3600
3601/* Main entry of the parser. Repeatedly parse outer control structures. */
3602
3603parser::parser (cpp_reader *r_)
3604{
3605 r = r_;
3606 active_ifs = vNULL;
3607 active_fors = vNULL;
3608 simplifiers = vNULL;
3c181717 3609 oper_lists_set = NULL;
3610 oper_lists = vNULL;
852fa94e 3611 capture_ids = NULL;
2165588a 3612 user_predicates = vNULL;
38d93c27 3613 parsing_match_operand = false;
2165588a 3614
3615 const cpp_token *token = next ();
3616 while (token->type != CPP_EOF)
3617 {
3618 _cpp_backup_tokens (r, 1);
3619 parse_pattern ();
3620 token = next ();
3621 }
3622}
3623
3624
3625/* Helper for the linemap code. */
3626
3627static size_t
3628round_alloc_size (size_t s)
3629{
3630 return s;
3631}
3632
3633
3634/* The genmatch generator progam. It reads from a pattern description
3635 and outputs GIMPLE or GENERIC IL matching and simplification routines. */
3636
3637int
3638main (int argc, char **argv)
3639{
3640 cpp_reader *r;
3641
3642 progname = "genmatch";
3643
3644 if (argc < 2)
3645 return 1;
3646
3647 bool gimple = true;
3648 bool verbose = false;
3649 char *input = argv[argc-1];
3650 for (int i = 1; i < argc - 1; ++i)
3651 {
3652 if (strcmp (argv[i], "--gimple") == 0)
3653 gimple = true;
3654 else if (strcmp (argv[i], "--generic") == 0)
3655 gimple = false;
3656 else if (strcmp (argv[i], "-v") == 0)
3657 verbose = true;
3658 else
3659 {
3660 fprintf (stderr, "Usage: genmatch "
3661 "[--gimple] [--generic] [-v] input\n");
3662 return 1;
3663 }
3664 }
3665
3666 line_table = XCNEW (struct line_maps);
3667 linemap_init (line_table, 0);
3668 line_table->reallocator = xrealloc;
3669 line_table->round_alloc_size = round_alloc_size;
3670
3671 r = cpp_create_reader (CLK_GNUC99, NULL, line_table);
3672 cpp_callbacks *cb = cpp_get_callbacks (r);
3673 cb->error = error_cb;
3674
3675 if (!cpp_read_main_file (r, input))
3676 return 1;
3677 cpp_define (r, gimple ? "GIMPLE=1": "GENERIC=1");
3678 cpp_define (r, gimple ? "GENERIC=0": "GIMPLE=0");
3679
3680 /* Pre-seed operators. */
3681 operators = new hash_table<id_base> (1024);
3682#define DEFTREECODE(SYM, STRING, TYPE, NARGS) \
3683 add_operator (SYM, # SYM, # TYPE, NARGS);
3684#define END_OF_BASE_TREE_CODES
3685#include "tree.def"
3686add_operator (CONVERT0, "CONVERT0", "tcc_unary", 1);
3687add_operator (CONVERT1, "CONVERT1", "tcc_unary", 1);
3688add_operator (CONVERT2, "CONVERT2", "tcc_unary", 1);
53e2e97e 3689add_operator (VIEW_CONVERT0, "VIEW_CONVERT0", "tcc_unary", 1);
3690add_operator (VIEW_CONVERT1, "VIEW_CONVERT1", "tcc_unary", 1);
3691add_operator (VIEW_CONVERT2, "VIEW_CONVERT2", "tcc_unary", 1);
2165588a 3692#undef END_OF_BASE_TREE_CODES
3693#undef DEFTREECODE
3694
3695 /* Pre-seed builtin functions.
3696 ??? Cannot use N (name) as that is targetm.emultls.get_address
3697 for BUILT_IN_EMUTLS_GET_ADDRESS ... */
3698#define DEF_BUILTIN(ENUM, N, C, T, LT, B, F, NA, AT, IM, COND) \
3699 add_builtin (ENUM, # ENUM);
3700#include "builtins.def"
3701#undef DEF_BUILTIN
3702
3703 /* Parse ahead! */
3704 parser p (r);
3705
3706 if (gimple)
3707 write_header (stdout, "gimple-match-head.c");
3708 else
3709 write_header (stdout, "generic-match-head.c");
3710
3711 /* Go over all predicates defined with patterns and perform
3712 lowering and code generation. */
3713 for (unsigned i = 0; i < p.user_predicates.length (); ++i)
3714 {
3715 predicate_id *pred = p.user_predicates[i];
30d8934c 3716 lower (pred->matchers, gimple);
2165588a 3717
3718 if (verbose)
3719 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3720 print_matches (pred->matchers[i]);
3721
3722 decision_tree dt;
3723 for (unsigned i = 0; i < pred->matchers.length (); ++i)
3724 dt.insert (pred->matchers[i], i);
3725
3726 if (verbose)
3727 dt.print (stderr);
3728
3729 write_predicate (stdout, pred, dt, gimple);
3730 }
3731
3732 /* Lower the main simplifiers and generate code for them. */
30d8934c 3733 lower (p.simplifiers, gimple);
2165588a 3734
3735 if (verbose)
3736 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3737 print_matches (p.simplifiers[i]);
3738
3739 decision_tree dt;
3740 for (unsigned i = 0; i < p.simplifiers.length (); ++i)
3741 dt.insert (p.simplifiers[i], i);
3742
3743 if (verbose)
3744 dt.print (stderr);
3745
3746 if (gimple)
3747 dt.gen_gimple (stdout);
3748 else
3749 dt.gen_generic (stdout);
3750
3751 /* Finalize. */
3752 cpp_finish (r, NULL);
3753 cpp_destroy (r);
3754
3755 delete operators;
3756
3757 return 0;
3758}