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