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