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