OSDN Git Service

* alias.c: Fix comment typos.
[pf3gnuchains/gcc-fork.git] / gcc / genrecog.c
1 /* Generate code from machine description to recognize rtl as insns.
2    Copyright (C) 1987, 1988, 1992, 1993, 1994, 1995, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21
22
23 /* This program is used to produce insn-recog.c, which contains a
24    function called `recog' plus its subroutines.  These functions
25    contain a decision tree that recognizes whether an rtx, the
26    argument given to recog, is a valid instruction.
27
28    recog returns -1 if the rtx is not valid.  If the rtx is valid,
29    recog returns a nonnegative number which is the insn code number
30    for the pattern that matched.  This is the same as the order in the
31    machine description of the entry that matched.  This number can be
32    used as an index into various insn_* tables, such as insn_template,
33    insn_outfun, and insn_n_operands (found in insn-output.c).
34
35    The third argument to recog is an optional pointer to an int.  If
36    present, recog will accept a pattern if it matches except for
37    missing CLOBBER expressions at the end.  In that case, the value
38    pointed to by the optional pointer will be set to the number of
39    CLOBBERs that need to be added (it should be initialized to zero by
40    the caller).  If it is set nonzero, the caller should allocate a
41    PARALLEL of the appropriate size, copy the initial entries, and
42    call add_clobbers (found in insn-emit.c) to fill in the CLOBBERs.
43
44    This program also generates the function `split_insns', which
45    returns 0 if the rtl could not be split, or it returns the split
46    rtl as an INSN list.
47
48    This program also generates the function `peephole2_insns', which
49    returns 0 if the rtl could not be matched.  If there was a match,
50    the new rtl is returned in an INSN list, and LAST_INSN will point
51    to the last recognized insn in the old sequence.  */
52
53 #include "bconfig.h"
54 #include "system.h"
55 #include "coretypes.h"
56 #include "tm.h"
57 #include "rtl.h"
58 #include "errors.h"
59 #include "gensupport.h"
60
61
62 #define OUTPUT_LABEL(INDENT_STRING, LABEL_NUMBER) \
63   printf("%sL%d: ATTRIBUTE_UNUSED_LABEL\n", (INDENT_STRING), (LABEL_NUMBER))
64
65 /* Holds an array of names indexed by insn_code_number.  */
66 static char **insn_name_ptr = 0;
67 static int insn_name_ptr_size = 0;
68
69 /* A listhead of decision trees.  The alternatives to a node are kept
70    in a doubly-linked list so we can easily add nodes to the proper
71    place when merging.  */
72
73 struct decision_head
74 {
75   struct decision *first;
76   struct decision *last;
77 };
78
79 /* A single test.  The two accept types aren't tests per-se, but
80    their equality (or lack thereof) does affect tree merging so
81    it is convenient to keep them here.  */
82
83 struct decision_test
84 {
85   /* A linked list through the tests attached to a node.  */
86   struct decision_test *next;
87
88   /* These types are roughly in the order in which we'd like to test them.  */
89   enum decision_type
90     {
91       DT_mode, DT_code, DT_veclen,
92       DT_elt_zero_int, DT_elt_one_int, DT_elt_zero_wide, DT_elt_zero_wide_safe,
93       DT_veclen_ge, DT_dup, DT_pred, DT_c_test,
94       DT_accept_op, DT_accept_insn
95     } type;
96
97   union
98   {
99     enum machine_mode mode;     /* Machine mode of node.  */
100     RTX_CODE code;              /* Code to test.  */
101
102     struct
103     {
104       const char *name;         /* Predicate to call.  */
105       int index;                /* Index into `preds' or -1.  */
106       enum machine_mode mode;   /* Machine mode for node.  */
107     } pred;
108
109     const char *c_test;         /* Additional test to perform.  */
110     int veclen;                 /* Length of vector.  */
111     int dup;                    /* Number of operand to compare against.  */
112     HOST_WIDE_INT intval;       /* Value for XINT for XWINT.  */
113     int opno;                   /* Operand number matched.  */
114
115     struct {
116       int code_number;          /* Insn number matched.  */
117       int lineno;               /* Line number of the insn.  */
118       int num_clobbers_to_add;  /* Number of CLOBBERs to be added.  */
119     } insn;
120   } u;
121 };
122
123 /* Data structure for decision tree for recognizing legitimate insns.  */
124
125 struct decision
126 {
127   struct decision_head success; /* Nodes to test on success.  */
128   struct decision *next;        /* Node to test on failure.  */
129   struct decision *prev;        /* Node whose failure tests us.  */
130   struct decision *afterward;   /* Node to test on success,
131                                    but failure of successor nodes.  */
132
133   const char *position;         /* String denoting position in pattern.  */
134
135   struct decision_test *tests;  /* The tests for this node.  */
136
137   int number;                   /* Node number, used for labels */
138   int subroutine_number;        /* Number of subroutine this node starts */
139   int need_label;               /* Label needs to be output.  */
140 };
141
142 #define SUBROUTINE_THRESHOLD    100
143
144 static int next_subroutine_number;
145
146 /* We can write three types of subroutines: One for insn recognition,
147    one to split insns, and one for peephole-type optimizations.  This
148    defines which type is being written.  */
149
150 enum routine_type {
151   RECOG, SPLIT, PEEPHOLE2
152 };
153
154 #define IS_SPLIT(X) ((X) != RECOG)
155
156 /* Next available node number for tree nodes.  */
157
158 static int next_number;
159
160 /* Next number to use as an insn_code.  */
161
162 static int next_insn_code;
163
164 /* Similar, but counts all expressions in the MD file; used for
165    error messages.  */
166
167 static int next_index;
168
169 /* Record the highest depth we ever have so we know how many variables to
170    allocate in each subroutine we make.  */
171
172 static int max_depth;
173
174 /* The line number of the start of the pattern currently being processed.  */
175 static int pattern_lineno;
176
177 /* Count of errors.  */
178 static int error_count;
179 \f
180 /* This table contains a list of the rtl codes that can possibly match a
181    predicate defined in recog.c.  The function `maybe_both_true' uses it to
182    deduce that there are no expressions that can be matches by certain pairs
183    of tree nodes.  Also, if a predicate can match only one code, we can
184    hardwire that code into the node testing the predicate.  */
185
186 static const struct pred_table
187 {
188   const char *const name;
189   const RTX_CODE codes[NUM_RTX_CODE];
190 } preds[] = {
191   {"general_operand", {CONST_INT, CONST_DOUBLE, CONST, SYMBOL_REF,
192                        LABEL_REF, SUBREG, REG, MEM, ADDRESSOF}},
193 #ifdef PREDICATE_CODES
194   PREDICATE_CODES
195 #endif
196   {"address_operand", {CONST_INT, CONST_DOUBLE, CONST, SYMBOL_REF,
197                        LABEL_REF, SUBREG, REG, MEM, ADDRESSOF,
198                        PLUS, MINUS, MULT}},
199   {"register_operand", {SUBREG, REG, ADDRESSOF}},
200   {"pmode_register_operand", {SUBREG, REG, ADDRESSOF}},
201   {"scratch_operand", {SCRATCH, REG}},
202   {"immediate_operand", {CONST_INT, CONST_DOUBLE, CONST, SYMBOL_REF,
203                          LABEL_REF}},
204   {"const_int_operand", {CONST_INT}},
205   {"const_double_operand", {CONST_INT, CONST_DOUBLE}},
206   {"nonimmediate_operand", {SUBREG, REG, MEM, ADDRESSOF}},
207   {"nonmemory_operand", {CONST_INT, CONST_DOUBLE, CONST, SYMBOL_REF,
208                          LABEL_REF, SUBREG, REG, ADDRESSOF}},
209   {"push_operand", {MEM}},
210   {"pop_operand", {MEM}},
211   {"memory_operand", {SUBREG, MEM}},
212   {"indirect_operand", {SUBREG, MEM}},
213   {"comparison_operator", {EQ, NE, LE, LT, GE, GT, LEU, LTU, GEU, GTU,
214                            UNORDERED, ORDERED, UNEQ, UNGE, UNGT, UNLE,
215                            UNLT, LTGT}}
216 };
217
218 #define NUM_KNOWN_PREDS ARRAY_SIZE (preds)
219
220 static const char *const special_mode_pred_table[] = {
221 #ifdef SPECIAL_MODE_PREDICATES
222   SPECIAL_MODE_PREDICATES
223 #endif
224   "pmode_register_operand"
225 };
226
227 #define NUM_SPECIAL_MODE_PREDS ARRAY_SIZE (special_mode_pred_table)
228
229 static struct decision *new_decision
230   (const char *, struct decision_head *);
231 static struct decision_test *new_decision_test
232   (enum decision_type, struct decision_test ***);
233 static rtx find_operand
234   (rtx, int);
235 static rtx find_matching_operand
236   (rtx, int);
237 static void validate_pattern
238   (rtx, rtx, rtx, int);
239 static struct decision *add_to_sequence
240   (rtx, struct decision_head *, const char *, enum routine_type, int);
241
242 static int maybe_both_true_2
243   (struct decision_test *, struct decision_test *);
244 static int maybe_both_true_1
245   (struct decision_test *, struct decision_test *);
246 static int maybe_both_true
247   (struct decision *, struct decision *, int);
248
249 static int nodes_identical_1
250   (struct decision_test *, struct decision_test *);
251 static int nodes_identical
252   (struct decision *, struct decision *);
253 static void merge_accept_insn
254   (struct decision *, struct decision *);
255 static void merge_trees
256   (struct decision_head *, struct decision_head *);
257
258 static void factor_tests
259   (struct decision_head *);
260 static void simplify_tests
261   (struct decision_head *);
262 static int break_out_subroutines
263   (struct decision_head *, int);
264 static void find_afterward
265   (struct decision_head *, struct decision *);
266
267 static void change_state
268   (const char *, const char *, struct decision *, const char *);
269 static void print_code
270   (enum rtx_code);
271 static void write_afterward
272   (struct decision *, struct decision *, const char *);
273 static struct decision *write_switch
274   (struct decision *, int);
275 static void write_cond
276   (struct decision_test *, int, enum routine_type);
277 static void write_action
278   (struct decision *, struct decision_test *, int, int,
279    struct decision *, enum routine_type);
280 static int is_unconditional
281   (struct decision_test *, enum routine_type);
282 static int write_node
283   (struct decision *, int, enum routine_type);
284 static void write_tree_1
285   (struct decision_head *, int, enum routine_type);
286 static void write_tree
287   (struct decision_head *, const char *, enum routine_type, int);
288 static void write_subroutine
289   (struct decision_head *, enum routine_type);
290 static void write_subroutines
291   (struct decision_head *, enum routine_type);
292 static void write_header
293   (void);
294
295 static struct decision_head make_insn_sequence
296   (rtx, enum routine_type);
297 static void process_tree
298   (struct decision_head *, enum routine_type);
299
300 static void record_insn_name
301   (int, const char *);
302
303 static void debug_decision_0
304   (struct decision *, int, int);
305 static void debug_decision_1
306   (struct decision *, int);
307 static void debug_decision_2
308   (struct decision_test *);
309 extern void debug_decision
310   (struct decision *);
311 extern void debug_decision_list
312   (struct decision *);
313 \f
314 /* Create a new node in sequence after LAST.  */
315
316 static struct decision *
317 new_decision (const char *position, struct decision_head *last)
318 {
319   struct decision *new = xcalloc (1, sizeof (struct decision));
320
321   new->success = *last;
322   new->position = xstrdup (position);
323   new->number = next_number++;
324
325   last->first = last->last = new;
326   return new;
327 }
328
329 /* Create a new test and link it in at PLACE.  */
330
331 static struct decision_test *
332 new_decision_test (enum decision_type type, struct decision_test ***pplace)
333 {
334   struct decision_test **place = *pplace;
335   struct decision_test *test;
336
337   test = xmalloc (sizeof (*test));
338   test->next = *place;
339   test->type = type;
340   *place = test;
341
342   place = &test->next;
343   *pplace = place;
344
345   return test;
346 }
347
348 /* Search for and return operand N.  */
349
350 static rtx
351 find_operand (rtx pattern, int n)
352 {
353   const char *fmt;
354   RTX_CODE code;
355   int i, j, len;
356   rtx r;
357
358   code = GET_CODE (pattern);
359   if ((code == MATCH_SCRATCH
360        || code == MATCH_INSN
361        || code == MATCH_OPERAND
362        || code == MATCH_OPERATOR
363        || code == MATCH_PARALLEL)
364       && XINT (pattern, 0) == n)
365     return pattern;
366
367   fmt = GET_RTX_FORMAT (code);
368   len = GET_RTX_LENGTH (code);
369   for (i = 0; i < len; i++)
370     {
371       switch (fmt[i])
372         {
373         case 'e': case 'u':
374           if ((r = find_operand (XEXP (pattern, i), n)) != NULL_RTX)
375             return r;
376           break;
377
378         case 'V':
379           if (! XVEC (pattern, i))
380             break;
381           /* Fall through.  */
382
383         case 'E':
384           for (j = 0; j < XVECLEN (pattern, i); j++)
385             if ((r = find_operand (XVECEXP (pattern, i, j), n)) != NULL_RTX)
386               return r;
387           break;
388
389         case 'i': case 'w': case '0': case 's':
390           break;
391
392         default:
393           abort ();
394         }
395     }
396
397   return NULL;
398 }
399
400 /* Search for and return operand M, such that it has a matching
401    constraint for operand N.  */
402
403 static rtx
404 find_matching_operand (rtx pattern, int n)
405 {
406   const char *fmt;
407   RTX_CODE code;
408   int i, j, len;
409   rtx r;
410
411   code = GET_CODE (pattern);
412   if (code == MATCH_OPERAND
413       && (XSTR (pattern, 2)[0] == '0' + n
414           || (XSTR (pattern, 2)[0] == '%'
415               && XSTR (pattern, 2)[1] == '0' + n)))
416     return pattern;
417
418   fmt = GET_RTX_FORMAT (code);
419   len = GET_RTX_LENGTH (code);
420   for (i = 0; i < len; i++)
421     {
422       switch (fmt[i])
423         {
424         case 'e': case 'u':
425           if ((r = find_matching_operand (XEXP (pattern, i), n)))
426             return r;
427           break;
428
429         case 'V':
430           if (! XVEC (pattern, i))
431             break;
432           /* Fall through.  */
433
434         case 'E':
435           for (j = 0; j < XVECLEN (pattern, i); j++)
436             if ((r = find_matching_operand (XVECEXP (pattern, i, j), n)))
437               return r;
438           break;
439
440         case 'i': case 'w': case '0': case 's':
441           break;
442
443         default:
444           abort ();
445         }
446     }
447
448   return NULL;
449 }
450
451
452 /* Check for various errors in patterns.  SET is nonnull for a destination,
453    and is the complete set pattern.  SET_CODE is '=' for normal sets, and
454    '+' within a context that requires in-out constraints.  */
455
456 static void
457 validate_pattern (rtx pattern, rtx insn, rtx set, int set_code)
458 {
459   const char *fmt;
460   RTX_CODE code;
461   size_t i, len;
462   int j;
463
464   code = GET_CODE (pattern);
465   switch (code)
466     {
467     case MATCH_SCRATCH:
468       return;
469
470     case MATCH_INSN:
471     case MATCH_OPERAND:
472     case MATCH_OPERATOR:
473       {
474         const char *pred_name = XSTR (pattern, 1);
475         int allows_non_lvalue = 1, allows_non_const = 1;
476         int special_mode_pred = 0;
477         const char *c_test;
478
479         if (GET_CODE (insn) == DEFINE_INSN)
480           c_test = XSTR (insn, 2);
481         else
482           c_test = XSTR (insn, 1);
483
484         if (pred_name[0] != 0)
485           {
486             for (i = 0; i < NUM_KNOWN_PREDS; i++)
487               if (! strcmp (preds[i].name, pred_name))
488                 break;
489
490             if (i < NUM_KNOWN_PREDS)
491               {
492                 int j;
493
494                 allows_non_lvalue = allows_non_const = 0;
495                 for (j = 0; preds[i].codes[j] != 0; j++)
496                   {
497                     RTX_CODE c = preds[i].codes[j];
498                     if (c != LABEL_REF
499                         && c != SYMBOL_REF
500                         && c != CONST_INT
501                         && c != CONST_DOUBLE
502                         && c != CONST
503                         && c != HIGH
504                         && c != CONSTANT_P_RTX)
505                       allows_non_const = 1;
506
507                     if (c != REG
508                         && c != SUBREG
509                         && c != MEM
510                         && c != ADDRESSOF
511                         && c != CONCAT
512                         && c != PARALLEL
513                         && c != STRICT_LOW_PART)
514                       allows_non_lvalue = 1;
515                   }
516               }
517             else
518               {
519 #ifdef PREDICATE_CODES
520                 /* If the port has a list of the predicates it uses but
521                    omits one, warn.  */
522                 message_with_line (pattern_lineno,
523                                    "warning: `%s' not in PREDICATE_CODES",
524                                    pred_name);
525 #endif
526               }
527
528             for (i = 0; i < NUM_SPECIAL_MODE_PREDS; ++i)
529               if (strcmp (pred_name, special_mode_pred_table[i]) == 0)
530                 {
531                   special_mode_pred = 1;
532                   break;
533                 }
534           }
535
536         if (code == MATCH_OPERAND)
537           {
538             const char constraints0 = XSTR (pattern, 2)[0];
539
540             /* In DEFINE_EXPAND, DEFINE_SPLIT, and DEFINE_PEEPHOLE2, we
541                don't use the MATCH_OPERAND constraint, only the predicate.
542                This is confusing to folks doing new ports, so help them
543                not make the mistake.  */
544             if (GET_CODE (insn) == DEFINE_EXPAND
545                 || GET_CODE (insn) == DEFINE_SPLIT
546                 || GET_CODE (insn) == DEFINE_PEEPHOLE2)
547               {
548                 if (constraints0)
549                   message_with_line (pattern_lineno,
550                                      "warning: constraints not supported in %s",
551                                      rtx_name[GET_CODE (insn)]);
552               }
553
554             /* A MATCH_OPERAND that is a SET should have an output reload.  */
555             else if (set && constraints0)
556               {
557                 if (set_code == '+')
558                   {
559                     if (constraints0 == '+')
560                       ;
561                     /* If we've only got an output reload for this operand,
562                        we'd better have a matching input operand.  */
563                     else if (constraints0 == '='
564                              && find_matching_operand (insn, XINT (pattern, 0)))
565                       ;
566                     else
567                       {
568                         message_with_line (pattern_lineno,
569                                            "operand %d missing in-out reload",
570                                            XINT (pattern, 0));
571                         error_count++;
572                       }
573                   }
574                 else if (constraints0 != '=' && constraints0 != '+')
575                   {
576                     message_with_line (pattern_lineno,
577                                        "operand %d missing output reload",
578                                        XINT (pattern, 0));
579                     error_count++;
580                   }
581               }
582           }
583
584         /* Allowing non-lvalues in destinations -- particularly CONST_INT --
585            while not likely to occur at runtime, results in less efficient
586            code from insn-recog.c.  */
587         if (set
588             && pred_name[0] != '\0'
589             && allows_non_lvalue)
590           {
591             message_with_line (pattern_lineno,
592                         "warning: destination operand %d allows non-lvalue",
593                         XINT (pattern, 0));
594           }
595
596         /* A modeless MATCH_OPERAND can be handy when we can
597            check for multiple modes in the c_test.  In most other cases,
598            it is a mistake.  Only DEFINE_INSN is eligible, since SPLIT
599            and PEEP2 can FAIL within the output pattern.  Exclude
600            address_operand, since its mode is related to the mode of
601            the memory not the operand.  Exclude the SET_DEST of a call
602            instruction, as that is a common idiom.  */
603
604         if (GET_MODE (pattern) == VOIDmode
605             && code == MATCH_OPERAND
606             && GET_CODE (insn) == DEFINE_INSN
607             && allows_non_const
608             && ! special_mode_pred
609             && pred_name[0] != '\0'
610             && strcmp (pred_name, "address_operand") != 0
611             && strstr (c_test, "operands") == NULL
612             && ! (set
613                   && GET_CODE (set) == SET
614                   && GET_CODE (SET_SRC (set)) == CALL))
615           {
616             message_with_line (pattern_lineno,
617                                "warning: operand %d missing mode?",
618                                XINT (pattern, 0));
619           }
620         return;
621       }
622
623     case SET:
624       {
625         enum machine_mode dmode, smode;
626         rtx dest, src;
627
628         dest = SET_DEST (pattern);
629         src = SET_SRC (pattern);
630
631         /* STRICT_LOW_PART is a wrapper.  Its argument is the real
632            destination, and it's mode should match the source.  */
633         if (GET_CODE (dest) == STRICT_LOW_PART)
634           dest = XEXP (dest, 0);
635
636         /* Find the referent for a DUP.  */
637
638         if (GET_CODE (dest) == MATCH_DUP
639             || GET_CODE (dest) == MATCH_OP_DUP
640             || GET_CODE (dest) == MATCH_PAR_DUP)
641           dest = find_operand (insn, XINT (dest, 0));
642
643         if (GET_CODE (src) == MATCH_DUP
644             || GET_CODE (src) == MATCH_OP_DUP
645             || GET_CODE (src) == MATCH_PAR_DUP)
646           src = find_operand (insn, XINT (src, 0));
647
648         dmode = GET_MODE (dest);
649         smode = GET_MODE (src);
650
651         /* The mode of an ADDRESS_OPERAND is the mode of the memory
652            reference, not the mode of the address.  */
653         if (GET_CODE (src) == MATCH_OPERAND
654             && ! strcmp (XSTR (src, 1), "address_operand"))
655           ;
656
657         /* The operands of a SET must have the same mode unless one
658            is VOIDmode.  */
659         else if (dmode != VOIDmode && smode != VOIDmode && dmode != smode)
660           {
661             message_with_line (pattern_lineno,
662                                "mode mismatch in set: %smode vs %smode",
663                                GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
664             error_count++;
665           }
666
667         /* If only one of the operands is VOIDmode, and PC or CC0 is
668            not involved, it's probably a mistake.  */
669         else if (dmode != smode
670                  && GET_CODE (dest) != PC
671                  && GET_CODE (dest) != CC0
672                  && GET_CODE (src) != PC
673                  && GET_CODE (src) != CC0
674                  && GET_CODE (src) != CONST_INT)
675           {
676             const char *which;
677             which = (dmode == VOIDmode ? "destination" : "source");
678             message_with_line (pattern_lineno,
679                                "warning: %s missing a mode?", which);
680           }
681
682         if (dest != SET_DEST (pattern))
683           validate_pattern (dest, insn, pattern, '=');
684         validate_pattern (SET_DEST (pattern), insn, pattern, '=');
685         validate_pattern (SET_SRC (pattern), insn, NULL_RTX, 0);
686         return;
687       }
688
689     case CLOBBER:
690       validate_pattern (SET_DEST (pattern), insn, pattern, '=');
691       return;
692
693     case ZERO_EXTRACT:
694       validate_pattern (XEXP (pattern, 0), insn, set, set ? '+' : 0);
695       validate_pattern (XEXP (pattern, 1), insn, NULL_RTX, 0);
696       validate_pattern (XEXP (pattern, 2), insn, NULL_RTX, 0);
697       return;
698
699     case STRICT_LOW_PART:
700       validate_pattern (XEXP (pattern, 0), insn, set, set ? '+' : 0);
701       return;
702
703     case LABEL_REF:
704       if (GET_MODE (XEXP (pattern, 0)) != VOIDmode)
705         {
706           message_with_line (pattern_lineno,
707                              "operand to label_ref %smode not VOIDmode",
708                              GET_MODE_NAME (GET_MODE (XEXP (pattern, 0))));
709           error_count++;
710         }
711       break;
712
713     default:
714       break;
715     }
716
717   fmt = GET_RTX_FORMAT (code);
718   len = GET_RTX_LENGTH (code);
719   for (i = 0; i < len; i++)
720     {
721       switch (fmt[i])
722         {
723         case 'e': case 'u':
724           validate_pattern (XEXP (pattern, i), insn, NULL_RTX, 0);
725           break;
726
727         case 'E':
728           for (j = 0; j < XVECLEN (pattern, i); j++)
729             validate_pattern (XVECEXP (pattern, i, j), insn, NULL_RTX, 0);
730           break;
731
732         case 'i': case 'w': case '0': case 's':
733           break;
734
735         default:
736           abort ();
737         }
738     }
739 }
740
741 /* Create a chain of nodes to verify that an rtl expression matches
742    PATTERN.
743
744    LAST is a pointer to the listhead in the previous node in the chain (or
745    in the calling function, for the first node).
746
747    POSITION is the string representing the current position in the insn.
748
749    INSN_TYPE is the type of insn for which we are emitting code.
750
751    A pointer to the final node in the chain is returned.  */
752
753 static struct decision *
754 add_to_sequence (rtx pattern, struct decision_head *last, const char *position,
755                  enum routine_type insn_type, int top)
756 {
757   RTX_CODE code;
758   struct decision *this, *sub;
759   struct decision_test *test;
760   struct decision_test **place;
761   char *subpos;
762   size_t i;
763   const char *fmt;
764   int depth = strlen (position);
765   int len;
766   enum machine_mode mode;
767
768   if (depth > max_depth)
769     max_depth = depth;
770
771   subpos = xmalloc (depth + 2);
772   strcpy (subpos, position);
773   subpos[depth + 1] = 0;
774
775   sub = this = new_decision (position, last);
776   place = &this->tests;
777
778  restart:
779   mode = GET_MODE (pattern);
780   code = GET_CODE (pattern);
781
782   switch (code)
783     {
784     case PARALLEL:
785       /* Toplevel peephole pattern.  */
786       if (insn_type == PEEPHOLE2 && top)
787         {
788           /* We don't need the node we just created -- unlink it.  */
789           last->first = last->last = NULL;
790
791           for (i = 0; i < (size_t) XVECLEN (pattern, 0); i++)
792             {
793               /* Which insn we're looking at is represented by A-Z. We don't
794                  ever use 'A', however; it is always implied.  */
795
796               subpos[depth] = (i > 0 ? 'A' + i : 0);
797               sub = add_to_sequence (XVECEXP (pattern, 0, i),
798                                      last, subpos, insn_type, 0);
799               last = &sub->success;
800             }
801           goto ret;
802         }
803
804       /* Else nothing special.  */
805       break;
806
807     case MATCH_PARALLEL:
808       /* The explicit patterns within a match_parallel enforce a minimum
809          length on the vector.  The match_parallel predicate may allow
810          for more elements.  We do need to check for this minimum here
811          or the code generated to match the internals may reference data
812          beyond the end of the vector.  */
813       test = new_decision_test (DT_veclen_ge, &place);
814       test->u.veclen = XVECLEN (pattern, 2);
815       /* Fall through.  */
816
817     case MATCH_OPERAND:
818     case MATCH_SCRATCH:
819     case MATCH_OPERATOR:
820     case MATCH_INSN:
821       {
822         const char *pred_name;
823         RTX_CODE was_code = code;
824         int allows_const_int = 1;
825
826         if (code == MATCH_SCRATCH)
827           {
828             pred_name = "scratch_operand";
829             code = UNKNOWN;
830           }
831         else
832           {
833             pred_name = XSTR (pattern, 1);
834             if (code == MATCH_PARALLEL)
835               code = PARALLEL;
836             else
837               code = UNKNOWN;
838           }
839
840         if (pred_name[0] != 0)
841           {
842             test = new_decision_test (DT_pred, &place);
843             test->u.pred.name = pred_name;
844             test->u.pred.mode = mode;
845
846             /* See if we know about this predicate and save its number.
847                If we do, and it only accepts one code, note that fact.
848
849                If we know that the predicate does not allow CONST_INT,
850                we know that the only way the predicate can match is if
851                the modes match (here we use the kludge of relying on the
852                fact that "address_operand" accepts CONST_INT; otherwise,
853                it would have to be a special case), so we can test the
854                mode (but we need not).  This fact should considerably
855                simplify the generated code.  */
856
857             for (i = 0; i < NUM_KNOWN_PREDS; i++)
858               if (! strcmp (preds[i].name, pred_name))
859                 break;
860
861             if (i < NUM_KNOWN_PREDS)
862               {
863                 int j;
864
865                 test->u.pred.index = i;
866
867                 if (preds[i].codes[1] == 0 && code == UNKNOWN)
868                   code = preds[i].codes[0];
869
870                 allows_const_int = 0;
871                 for (j = 0; preds[i].codes[j] != 0; j++)
872                   if (preds[i].codes[j] == CONST_INT)
873                     {
874                       allows_const_int = 1;
875                       break;
876                     }
877               }
878             else
879               test->u.pred.index = -1;
880           }
881
882         /* Can't enforce a mode if we allow const_int.  */
883         if (allows_const_int)
884           mode = VOIDmode;
885
886         /* Accept the operand, ie. record it in `operands'.  */
887         test = new_decision_test (DT_accept_op, &place);
888         test->u.opno = XINT (pattern, 0);
889
890         if (was_code == MATCH_OPERATOR || was_code == MATCH_PARALLEL)
891           {
892             char base = (was_code == MATCH_OPERATOR ? '0' : 'a');
893             for (i = 0; i < (size_t) XVECLEN (pattern, 2); i++)
894               {
895                 subpos[depth] = i + base;
896                 sub = add_to_sequence (XVECEXP (pattern, 2, i),
897                                        &sub->success, subpos, insn_type, 0);
898               }
899           }
900         goto fini;
901       }
902
903     case MATCH_OP_DUP:
904       code = UNKNOWN;
905
906       test = new_decision_test (DT_dup, &place);
907       test->u.dup = XINT (pattern, 0);
908
909       test = new_decision_test (DT_accept_op, &place);
910       test->u.opno = XINT (pattern, 0);
911
912       for (i = 0; i < (size_t) XVECLEN (pattern, 1); i++)
913         {
914           subpos[depth] = i + '0';
915           sub = add_to_sequence (XVECEXP (pattern, 1, i),
916                                  &sub->success, subpos, insn_type, 0);
917         }
918       goto fini;
919
920     case MATCH_DUP:
921     case MATCH_PAR_DUP:
922       code = UNKNOWN;
923
924       test = new_decision_test (DT_dup, &place);
925       test->u.dup = XINT (pattern, 0);
926       goto fini;
927
928     case ADDRESS:
929       pattern = XEXP (pattern, 0);
930       goto restart;
931
932     default:
933       break;
934     }
935
936   fmt = GET_RTX_FORMAT (code);
937   len = GET_RTX_LENGTH (code);
938
939   /* Do tests against the current node first.  */
940   for (i = 0; i < (size_t) len; i++)
941     {
942       if (fmt[i] == 'i')
943         {
944           if (i == 0)
945             {
946               test = new_decision_test (DT_elt_zero_int, &place);
947               test->u.intval = XINT (pattern, i);
948             }
949           else if (i == 1)
950             {
951               test = new_decision_test (DT_elt_one_int, &place);
952               test->u.intval = XINT (pattern, i);
953             }
954           else
955             abort ();
956         }
957       else if (fmt[i] == 'w')
958         {
959           /* If this value actually fits in an int, we can use a switch
960              statement here, so indicate that.  */
961           enum decision_type type
962             = ((int) XWINT (pattern, i) == XWINT (pattern, i))
963               ? DT_elt_zero_wide_safe : DT_elt_zero_wide;
964
965           if (i != 0)
966             abort ();
967
968           test = new_decision_test (type, &place);
969           test->u.intval = XWINT (pattern, i);
970         }
971       else if (fmt[i] == 'E')
972         {
973           if (i != 0)
974             abort ();
975
976           test = new_decision_test (DT_veclen, &place);
977           test->u.veclen = XVECLEN (pattern, i);
978         }
979     }
980
981   /* Now test our sub-patterns.  */
982   for (i = 0; i < (size_t) len; i++)
983     {
984       switch (fmt[i])
985         {
986         case 'e': case 'u':
987           subpos[depth] = '0' + i;
988           sub = add_to_sequence (XEXP (pattern, i), &sub->success,
989                                  subpos, insn_type, 0);
990           break;
991
992         case 'E':
993           {
994             int j;
995             for (j = 0; j < XVECLEN (pattern, i); j++)
996               {
997                 subpos[depth] = 'a' + j;
998                 sub = add_to_sequence (XVECEXP (pattern, i, j),
999                                        &sub->success, subpos, insn_type, 0);
1000               }
1001             break;
1002           }
1003
1004         case 'i': case 'w':
1005           /* Handled above.  */
1006           break;
1007         case '0':
1008           break;
1009
1010         default:
1011           abort ();
1012         }
1013     }
1014
1015  fini:
1016   /* Insert nodes testing mode and code, if they're still relevant,
1017      before any of the nodes we may have added above.  */
1018   if (code != UNKNOWN)
1019     {
1020       place = &this->tests;
1021       test = new_decision_test (DT_code, &place);
1022       test->u.code = code;
1023     }
1024
1025   if (mode != VOIDmode)
1026     {
1027       place = &this->tests;
1028       test = new_decision_test (DT_mode, &place);
1029       test->u.mode = mode;
1030     }
1031
1032   /* If we didn't insert any tests or accept nodes, hork.  */
1033   if (this->tests == NULL)
1034     abort ();
1035
1036  ret:
1037   free (subpos);
1038   return sub;
1039 }
1040 \f
1041 /* A subroutine of maybe_both_true; examines only one test.
1042    Returns > 0 for "definitely both true" and < 0 for "maybe both true".  */
1043
1044 static int
1045 maybe_both_true_2 (struct decision_test *d1, struct decision_test *d2)
1046 {
1047   if (d1->type == d2->type)
1048     {
1049       switch (d1->type)
1050         {
1051         case DT_mode:
1052           return d1->u.mode == d2->u.mode;
1053
1054         case DT_code:
1055           return d1->u.code == d2->u.code;
1056
1057         case DT_veclen:
1058           return d1->u.veclen == d2->u.veclen;
1059
1060         case DT_elt_zero_int:
1061         case DT_elt_one_int:
1062         case DT_elt_zero_wide:
1063         case DT_elt_zero_wide_safe:
1064           return d1->u.intval == d2->u.intval;
1065
1066         default:
1067           break;
1068         }
1069     }
1070
1071   /* If either has a predicate that we know something about, set
1072      things up so that D1 is the one that always has a known
1073      predicate.  Then see if they have any codes in common.  */
1074
1075   if (d1->type == DT_pred || d2->type == DT_pred)
1076     {
1077       if (d2->type == DT_pred)
1078         {
1079           struct decision_test *tmp;
1080           tmp = d1, d1 = d2, d2 = tmp;
1081         }
1082
1083       /* If D2 tests a mode, see if it matches D1.  */
1084       if (d1->u.pred.mode != VOIDmode)
1085         {
1086           if (d2->type == DT_mode)
1087             {
1088               if (d1->u.pred.mode != d2->u.mode
1089                   /* The mode of an address_operand predicate is the
1090                      mode of the memory, not the operand.  It can only
1091                      be used for testing the predicate, so we must
1092                      ignore it here.  */
1093                   && strcmp (d1->u.pred.name, "address_operand") != 0)
1094                 return 0;
1095             }
1096           /* Don't check two predicate modes here, because if both predicates
1097              accept CONST_INT, then both can still be true even if the modes
1098              are different.  If they don't accept CONST_INT, there will be a
1099              separate DT_mode that will make maybe_both_true_1 return 0.  */
1100         }
1101
1102       if (d1->u.pred.index >= 0)
1103         {
1104           /* If D2 tests a code, see if it is in the list of valid
1105              codes for D1's predicate.  */
1106           if (d2->type == DT_code)
1107             {
1108               const RTX_CODE *c = &preds[d1->u.pred.index].codes[0];
1109               while (*c != 0)
1110                 {
1111                   if (*c == d2->u.code)
1112                     break;
1113                   ++c;
1114                 }
1115               if (*c == 0)
1116                 return 0;
1117             }
1118
1119           /* Otherwise see if the predicates have any codes in common.  */
1120           else if (d2->type == DT_pred && d2->u.pred.index >= 0)
1121             {
1122               const RTX_CODE *c1 = &preds[d1->u.pred.index].codes[0];
1123               int common = 0;
1124
1125               while (*c1 != 0 && !common)
1126                 {
1127                   const RTX_CODE *c2 = &preds[d2->u.pred.index].codes[0];
1128                   while (*c2 != 0 && !common)
1129                     {
1130                       common = (*c1 == *c2);
1131                       ++c2;
1132                     }
1133                   ++c1;
1134                 }
1135
1136               if (!common)
1137                 return 0;
1138             }
1139         }
1140     }
1141
1142   /* Tests vs veclen may be known when strict equality is involved.  */
1143   if (d1->type == DT_veclen && d2->type == DT_veclen_ge)
1144     return d1->u.veclen >= d2->u.veclen;
1145   if (d1->type == DT_veclen_ge && d2->type == DT_veclen)
1146     return d2->u.veclen >= d1->u.veclen;
1147
1148   return -1;
1149 }
1150
1151 /* A subroutine of maybe_both_true; examines all the tests for a given node.
1152    Returns > 0 for "definitely both true" and < 0 for "maybe both true".  */
1153
1154 static int
1155 maybe_both_true_1 (struct decision_test *d1, struct decision_test *d2)
1156 {
1157   struct decision_test *t1, *t2;
1158
1159   /* A match_operand with no predicate can match anything.  Recognize
1160      this by the existence of a lone DT_accept_op test.  */
1161   if (d1->type == DT_accept_op || d2->type == DT_accept_op)
1162     return 1;
1163
1164   /* Eliminate pairs of tests while they can exactly match.  */
1165   while (d1 && d2 && d1->type == d2->type)
1166     {
1167       if (maybe_both_true_2 (d1, d2) == 0)
1168         return 0;
1169       d1 = d1->next, d2 = d2->next;
1170     }
1171
1172   /* After that, consider all pairs.  */
1173   for (t1 = d1; t1 ; t1 = t1->next)
1174     for (t2 = d2; t2 ; t2 = t2->next)
1175       if (maybe_both_true_2 (t1, t2) == 0)
1176         return 0;
1177
1178   return -1;
1179 }
1180
1181 /* Return 0 if we can prove that there is no RTL that can match both
1182    D1 and D2.  Otherwise, return 1 (it may be that there is an RTL that
1183    can match both or just that we couldn't prove there wasn't such an RTL).
1184
1185    TOPLEVEL is nonzero if we are to only look at the top level and not
1186    recursively descend.  */
1187
1188 static int
1189 maybe_both_true (struct decision *d1, struct decision *d2,
1190                  int toplevel)
1191 {
1192   struct decision *p1, *p2;
1193   int cmp;
1194
1195   /* Don't compare strings on the different positions in insn.  Doing so
1196      is incorrect and results in false matches from constructs like
1197
1198         [(set (subreg:HI (match_operand:SI "register_operand" "r") 0)
1199               (subreg:HI (match_operand:SI "register_operand" "r") 0))]
1200      vs
1201         [(set (match_operand:HI "register_operand" "r")
1202               (match_operand:HI "register_operand" "r"))]
1203
1204      If we are presented with such, we are recursing through the remainder
1205      of a node's success nodes (from the loop at the end of this function).
1206      Skip forward until we come to a position that matches.
1207
1208      Due to the way position strings are constructed, we know that iterating
1209      forward from the lexically lower position (e.g. "00") will run into
1210      the lexically higher position (e.g. "1") and not the other way around.
1211      This saves a bit of effort.  */
1212
1213   cmp = strcmp (d1->position, d2->position);
1214   if (cmp != 0)
1215     {
1216       if (toplevel)
1217         abort ();
1218
1219       /* If the d2->position was lexically lower, swap.  */
1220       if (cmp > 0)
1221         p1 = d1, d1 = d2, d2 = p1;
1222
1223       if (d1->success.first == 0)
1224         return 1;
1225       for (p1 = d1->success.first; p1; p1 = p1->next)
1226         if (maybe_both_true (p1, d2, 0))
1227           return 1;
1228
1229       return 0;
1230     }
1231
1232   /* Test the current level.  */
1233   cmp = maybe_both_true_1 (d1->tests, d2->tests);
1234   if (cmp >= 0)
1235     return cmp;
1236
1237   /* We can't prove that D1 and D2 cannot both be true.  If we are only
1238      to check the top level, return 1.  Otherwise, see if we can prove
1239      that all choices in both successors are mutually exclusive.  If
1240      either does not have any successors, we can't prove they can't both
1241      be true.  */
1242
1243   if (toplevel || d1->success.first == 0 || d2->success.first == 0)
1244     return 1;
1245
1246   for (p1 = d1->success.first; p1; p1 = p1->next)
1247     for (p2 = d2->success.first; p2; p2 = p2->next)
1248       if (maybe_both_true (p1, p2, 0))
1249         return 1;
1250
1251   return 0;
1252 }
1253
1254 /* A subroutine of nodes_identical.  Examine two tests for equivalence.  */
1255
1256 static int
1257 nodes_identical_1 (struct decision_test *d1, struct decision_test *d2)
1258 {
1259   switch (d1->type)
1260     {
1261     case DT_mode:
1262       return d1->u.mode == d2->u.mode;
1263
1264     case DT_code:
1265       return d1->u.code == d2->u.code;
1266
1267     case DT_pred:
1268       return (d1->u.pred.mode == d2->u.pred.mode
1269               && strcmp (d1->u.pred.name, d2->u.pred.name) == 0);
1270
1271     case DT_c_test:
1272       return strcmp (d1->u.c_test, d2->u.c_test) == 0;
1273
1274     case DT_veclen:
1275     case DT_veclen_ge:
1276       return d1->u.veclen == d2->u.veclen;
1277
1278     case DT_dup:
1279       return d1->u.dup == d2->u.dup;
1280
1281     case DT_elt_zero_int:
1282     case DT_elt_one_int:
1283     case DT_elt_zero_wide:
1284     case DT_elt_zero_wide_safe:
1285       return d1->u.intval == d2->u.intval;
1286
1287     case DT_accept_op:
1288       return d1->u.opno == d2->u.opno;
1289
1290     case DT_accept_insn:
1291       /* Differences will be handled in merge_accept_insn.  */
1292       return 1;
1293
1294     default:
1295       abort ();
1296     }
1297 }
1298
1299 /* True iff the two nodes are identical (on one level only).  Due
1300    to the way these lists are constructed, we shouldn't have to
1301    consider different orderings on the tests.  */
1302
1303 static int
1304 nodes_identical (struct decision *d1, struct decision *d2)
1305 {
1306   struct decision_test *t1, *t2;
1307
1308   for (t1 = d1->tests, t2 = d2->tests; t1 && t2; t1 = t1->next, t2 = t2->next)
1309     {
1310       if (t1->type != t2->type)
1311         return 0;
1312       if (! nodes_identical_1 (t1, t2))
1313         return 0;
1314     }
1315
1316   /* For success, they should now both be null.  */
1317   if (t1 != t2)
1318     return 0;
1319
1320   /* Check that their subnodes are at the same position, as any one set
1321      of sibling decisions must be at the same position.  Allowing this
1322      requires complications to find_afterward and when change_state is
1323      invoked.  */
1324   if (d1->success.first
1325       && d2->success.first
1326       && strcmp (d1->success.first->position, d2->success.first->position))
1327     return 0;
1328
1329   return 1;
1330 }
1331
1332 /* A subroutine of merge_trees; given two nodes that have been declared
1333    identical, cope with two insn accept states.  If they differ in the
1334    number of clobbers, then the conflict was created by make_insn_sequence
1335    and we can drop the with-clobbers version on the floor.  If both
1336    nodes have no additional clobbers, we have found an ambiguity in the
1337    source machine description.  */
1338
1339 static void
1340 merge_accept_insn (struct decision *oldd, struct decision *addd)
1341 {
1342   struct decision_test *old, *add;
1343
1344   for (old = oldd->tests; old; old = old->next)
1345     if (old->type == DT_accept_insn)
1346       break;
1347   if (old == NULL)
1348     return;
1349
1350   for (add = addd->tests; add; add = add->next)
1351     if (add->type == DT_accept_insn)
1352       break;
1353   if (add == NULL)
1354     return;
1355
1356   /* If one node is for a normal insn and the second is for the base
1357      insn with clobbers stripped off, the second node should be ignored.  */
1358
1359   if (old->u.insn.num_clobbers_to_add == 0
1360       && add->u.insn.num_clobbers_to_add > 0)
1361     {
1362       /* Nothing to do here.  */
1363     }
1364   else if (old->u.insn.num_clobbers_to_add > 0
1365            && add->u.insn.num_clobbers_to_add == 0)
1366     {
1367       /* In this case, replace OLD with ADD.  */
1368       old->u.insn = add->u.insn;
1369     }
1370   else
1371     {
1372       message_with_line (add->u.insn.lineno, "`%s' matches `%s'",
1373                          get_insn_name (add->u.insn.code_number),
1374                          get_insn_name (old->u.insn.code_number));
1375       message_with_line (old->u.insn.lineno, "previous definition of `%s'",
1376                          get_insn_name (old->u.insn.code_number));
1377       error_count++;
1378     }
1379 }
1380
1381 /* Merge two decision trees OLDH and ADDH, modifying OLDH destructively.  */
1382
1383 static void
1384 merge_trees (struct decision_head *oldh, struct decision_head *addh)
1385 {
1386   struct decision *next, *add;
1387
1388   if (addh->first == 0)
1389     return;
1390   if (oldh->first == 0)
1391     {
1392       *oldh = *addh;
1393       return;
1394     }
1395
1396   /* Trying to merge bits at different positions isn't possible.  */
1397   if (strcmp (oldh->first->position, addh->first->position))
1398     abort ();
1399
1400   for (add = addh->first; add ; add = next)
1401     {
1402       struct decision *old, *insert_before = NULL;
1403
1404       next = add->next;
1405
1406       /* The semantics of pattern matching state that the tests are
1407          done in the order given in the MD file so that if an insn
1408          matches two patterns, the first one will be used.  However,
1409          in practice, most, if not all, patterns are unambiguous so
1410          that their order is independent.  In that case, we can merge
1411          identical tests and group all similar modes and codes together.
1412
1413          Scan starting from the end of OLDH until we reach a point
1414          where we reach the head of the list or where we pass a
1415          pattern that could also be true if NEW is true.  If we find
1416          an identical pattern, we can merge them.  Also, record the
1417          last node that tests the same code and mode and the last one
1418          that tests just the same mode.
1419
1420          If we have no match, place NEW after the closest match we found.  */
1421
1422       for (old = oldh->last; old; old = old->prev)
1423         {
1424           if (nodes_identical (old, add))
1425             {
1426               merge_accept_insn (old, add);
1427               merge_trees (&old->success, &add->success);
1428               goto merged_nodes;
1429             }
1430
1431           if (maybe_both_true (old, add, 0))
1432             break;
1433
1434           /* Insert the nodes in DT test type order, which is roughly
1435              how expensive/important the test is.  Given that the tests
1436              are also ordered within the list, examining the first is
1437              sufficient.  */
1438           if ((int) add->tests->type < (int) old->tests->type)
1439             insert_before = old;
1440         }
1441
1442       if (insert_before == NULL)
1443         {
1444           add->next = NULL;
1445           add->prev = oldh->last;
1446           oldh->last->next = add;
1447           oldh->last = add;
1448         }
1449       else
1450         {
1451           if ((add->prev = insert_before->prev) != NULL)
1452             add->prev->next = add;
1453           else
1454             oldh->first = add;
1455           add->next = insert_before;
1456           insert_before->prev = add;
1457         }
1458
1459     merged_nodes:;
1460     }
1461 }
1462 \f
1463 /* Walk the tree looking for sub-nodes that perform common tests.
1464    Factor out the common test into a new node.  This enables us
1465    (depending on the test type) to emit switch statements later.  */
1466
1467 static void
1468 factor_tests (struct decision_head *head)
1469 {
1470   struct decision *first, *next;
1471
1472   for (first = head->first; first && first->next; first = next)
1473     {
1474       enum decision_type type;
1475       struct decision *new, *old_last;
1476
1477       type = first->tests->type;
1478       next = first->next;
1479
1480       /* Want at least two compatible sequential nodes.  */
1481       if (next->tests->type != type)
1482         continue;
1483
1484       /* Don't want all node types, just those we can turn into
1485          switch statements.  */
1486       if (type != DT_mode
1487           && type != DT_code
1488           && type != DT_veclen
1489           && type != DT_elt_zero_int
1490           && type != DT_elt_one_int
1491           && type != DT_elt_zero_wide_safe)
1492         continue;
1493
1494       /* If we'd been performing more than one test, create a new node
1495          below our first test.  */
1496       if (first->tests->next != NULL)
1497         {
1498           new = new_decision (first->position, &first->success);
1499           new->tests = first->tests->next;
1500           first->tests->next = NULL;
1501         }
1502
1503       /* Crop the node tree off after our first test.  */
1504       first->next = NULL;
1505       old_last = head->last;
1506       head->last = first;
1507
1508       /* For each compatible test, adjust to perform only one test in
1509          the top level node, then merge the node back into the tree.  */
1510       do
1511         {
1512           struct decision_head h;
1513
1514           if (next->tests->next != NULL)
1515             {
1516               new = new_decision (next->position, &next->success);
1517               new->tests = next->tests->next;
1518               next->tests->next = NULL;
1519             }
1520           new = next;
1521           next = next->next;
1522           new->next = NULL;
1523           h.first = h.last = new;
1524
1525           merge_trees (head, &h);
1526         }
1527       while (next && next->tests->type == type);
1528
1529       /* After we run out of compatible tests, graft the remaining nodes
1530          back onto the tree.  */
1531       if (next)
1532         {
1533           next->prev = head->last;
1534           head->last->next = next;
1535           head->last = old_last;
1536         }
1537     }
1538
1539   /* Recurse.  */
1540   for (first = head->first; first; first = first->next)
1541     factor_tests (&first->success);
1542 }
1543
1544 /* After factoring, try to simplify the tests on any one node.
1545    Tests that are useful for switch statements are recognizable
1546    by having only a single test on a node -- we'll be manipulating
1547    nodes with multiple tests:
1548
1549    If we have mode tests or code tests that are redundant with
1550    predicates, remove them.  */
1551
1552 static void
1553 simplify_tests (struct decision_head *head)
1554 {
1555   struct decision *tree;
1556
1557   for (tree = head->first; tree; tree = tree->next)
1558     {
1559       struct decision_test *a, *b;
1560
1561       a = tree->tests;
1562       b = a->next;
1563       if (b == NULL)
1564         continue;
1565
1566       /* Find a predicate node.  */
1567       while (b && b->type != DT_pred)
1568         b = b->next;
1569       if (b)
1570         {
1571           /* Due to how these tests are constructed, we don't even need
1572              to check that the mode and code are compatible -- they were
1573              generated from the predicate in the first place.  */
1574           while (a->type == DT_mode || a->type == DT_code)
1575             a = a->next;
1576           tree->tests = a;
1577         }
1578     }
1579
1580   /* Recurse.  */
1581   for (tree = head->first; tree; tree = tree->next)
1582     simplify_tests (&tree->success);
1583 }
1584
1585 /* Count the number of subnodes of HEAD.  If the number is high enough,
1586    make the first node in HEAD start a separate subroutine in the C code
1587    that is generated.  */
1588
1589 static int
1590 break_out_subroutines (struct decision_head *head, int initial)
1591 {
1592   int size = 0;
1593   struct decision *sub;
1594
1595   for (sub = head->first; sub; sub = sub->next)
1596     size += 1 + break_out_subroutines (&sub->success, 0);
1597
1598   if (size > SUBROUTINE_THRESHOLD && ! initial)
1599     {
1600       head->first->subroutine_number = ++next_subroutine_number;
1601       size = 1;
1602     }
1603   return size;
1604 }
1605
1606 /* For each node p, find the next alternative that might be true
1607    when p is true.  */
1608
1609 static void
1610 find_afterward (struct decision_head *head, struct decision *real_afterward)
1611 {
1612   struct decision *p, *q, *afterward;
1613
1614   /* We can't propagate alternatives across subroutine boundaries.
1615      This is not incorrect, merely a minor optimization loss.  */
1616
1617   p = head->first;
1618   afterward = (p->subroutine_number > 0 ? NULL : real_afterward);
1619
1620   for ( ; p ; p = p->next)
1621     {
1622       /* Find the next node that might be true if this one fails.  */
1623       for (q = p->next; q ; q = q->next)
1624         if (maybe_both_true (p, q, 1))
1625           break;
1626
1627       /* If we reached the end of the list without finding one,
1628          use the incoming afterward position.  */
1629       if (!q)
1630         q = afterward;
1631       p->afterward = q;
1632       if (q)
1633         q->need_label = 1;
1634     }
1635
1636   /* Recurse.  */
1637   for (p = head->first; p ; p = p->next)
1638     if (p->success.first)
1639       find_afterward (&p->success, p->afterward);
1640
1641   /* When we are generating a subroutine, record the real afterward
1642      position in the first node where write_tree can find it, and we
1643      can do the right thing at the subroutine call site.  */
1644   p = head->first;
1645   if (p->subroutine_number > 0)
1646     p->afterward = real_afterward;
1647 }
1648 \f
1649 /* Assuming that the state of argument is denoted by OLDPOS, take whatever
1650    actions are necessary to move to NEWPOS.  If we fail to move to the
1651    new state, branch to node AFTERWARD if nonzero, otherwise return.
1652
1653    Failure to move to the new state can only occur if we are trying to
1654    match multiple insns and we try to step past the end of the stream.  */
1655
1656 static void
1657 change_state (const char *oldpos, const char *newpos,
1658               struct decision *afterward, const char *indent)
1659 {
1660   int odepth = strlen (oldpos);
1661   int ndepth = strlen (newpos);
1662   int depth;
1663   int old_has_insn, new_has_insn;
1664
1665   /* Pop up as many levels as necessary.  */
1666   for (depth = odepth; strncmp (oldpos, newpos, depth) != 0; --depth)
1667     continue;
1668
1669   /* Hunt for the last [A-Z] in both strings.  */
1670   for (old_has_insn = odepth - 1; old_has_insn >= 0; --old_has_insn)
1671     if (ISUPPER (oldpos[old_has_insn]))
1672       break;
1673   for (new_has_insn = ndepth - 1; new_has_insn >= 0; --new_has_insn)
1674     if (ISUPPER (newpos[new_has_insn]))
1675       break;
1676
1677   /* Go down to desired level.  */
1678   while (depth < ndepth)
1679     {
1680       /* It's a different insn from the first one.  */
1681       if (ISUPPER (newpos[depth]))
1682         {
1683           /* We can only fail if we're moving down the tree.  */
1684           if (old_has_insn >= 0 && oldpos[old_has_insn] >= newpos[depth])
1685             {
1686               printf ("%stem = peep2_next_insn (%d);\n",
1687                       indent, newpos[depth] - 'A');
1688             }
1689           else
1690             {
1691               printf ("%stem = peep2_next_insn (%d);\n",
1692                       indent, newpos[depth] - 'A');
1693               printf ("%sif (tem == NULL_RTX)\n", indent);
1694               if (afterward)
1695                 printf ("%s  goto L%d;\n", indent, afterward->number);
1696               else
1697                 printf ("%s  goto ret0;\n", indent);
1698             }
1699           printf ("%sx%d = PATTERN (tem);\n", indent, depth + 1);
1700         }
1701       else if (ISLOWER (newpos[depth]))
1702         printf ("%sx%d = XVECEXP (x%d, 0, %d);\n",
1703                 indent, depth + 1, depth, newpos[depth] - 'a');
1704       else
1705         printf ("%sx%d = XEXP (x%d, %c);\n",
1706                 indent, depth + 1, depth, newpos[depth]);
1707       ++depth;
1708     }
1709 }
1710 \f
1711 /* Print the enumerator constant for CODE -- the upcase version of
1712    the name.  */
1713
1714 static void
1715 print_code (enum rtx_code code)
1716 {
1717   const char *p;
1718   for (p = GET_RTX_NAME (code); *p; p++)
1719     putchar (TOUPPER (*p));
1720 }
1721
1722 /* Emit code to cross an afterward link -- change state and branch.  */
1723
1724 static void
1725 write_afterward (struct decision *start, struct decision *afterward,
1726                  const char *indent)
1727 {
1728   if (!afterward || start->subroutine_number > 0)
1729     printf("%sgoto ret0;\n", indent);
1730   else
1731     {
1732       change_state (start->position, afterward->position, NULL, indent);
1733       printf ("%sgoto L%d;\n", indent, afterward->number);
1734     }
1735 }
1736
1737 /* Emit a HOST_WIDE_INT as an integer constant expression.  We need to take
1738    special care to avoid "decimal constant is so large that it is unsigned"
1739    warnings in the resulting code.  */
1740
1741 static void
1742 print_host_wide_int (HOST_WIDE_INT val)
1743 {
1744   HOST_WIDE_INT min = (unsigned HOST_WIDE_INT)1 << (HOST_BITS_PER_WIDE_INT-1);
1745   if (val == min)
1746     printf ("(" HOST_WIDE_INT_PRINT_DEC_C "-1)", val + 1);
1747   else
1748     printf (HOST_WIDE_INT_PRINT_DEC_C, val);
1749 }
1750
1751 /* Emit a switch statement, if possible, for an initial sequence of
1752    nodes at START.  Return the first node yet untested.  */
1753
1754 static struct decision *
1755 write_switch (struct decision *start, int depth)
1756 {
1757   struct decision *p = start;
1758   enum decision_type type = p->tests->type;
1759   struct decision *needs_label = NULL;
1760
1761   /* If we have two or more nodes in sequence that test the same one
1762      thing, we may be able to use a switch statement.  */
1763
1764   if (!p->next
1765       || p->tests->next
1766       || p->next->tests->type != type
1767       || p->next->tests->next
1768       || nodes_identical_1 (p->tests, p->next->tests))
1769     return p;
1770
1771   /* DT_code is special in that we can do interesting things with
1772      known predicates at the same time.  */
1773   if (type == DT_code)
1774     {
1775       char codemap[NUM_RTX_CODE];
1776       struct decision *ret;
1777       RTX_CODE code;
1778
1779       memset (codemap, 0, sizeof(codemap));
1780
1781       printf ("  switch (GET_CODE (x%d))\n    {\n", depth);
1782       code = p->tests->u.code;
1783       do
1784         {
1785           if (p != start && p->need_label && needs_label == NULL)
1786             needs_label = p;
1787
1788           printf ("    case ");
1789           print_code (code);
1790           printf (":\n      goto L%d;\n", p->success.first->number);
1791           p->success.first->need_label = 1;
1792
1793           codemap[code] = 1;
1794           p = p->next;
1795         }
1796       while (p
1797              && ! p->tests->next
1798              && p->tests->type == DT_code
1799              && ! codemap[code = p->tests->u.code]);
1800
1801       /* If P is testing a predicate that we know about and we haven't
1802          seen any of the codes that are valid for the predicate, we can
1803          write a series of "case" statement, one for each possible code.
1804          Since we are already in a switch, these redundant tests are very
1805          cheap and will reduce the number of predicates called.  */
1806
1807       /* Note that while we write out cases for these predicates here,
1808          we don't actually write the test here, as it gets kinda messy.
1809          It is trivial to leave this to later by telling our caller that
1810          we only processed the CODE tests.  */
1811       if (needs_label != NULL)
1812         ret = needs_label;
1813       else
1814         ret = p;
1815
1816       while (p && p->tests->type == DT_pred
1817              && p->tests->u.pred.index >= 0)
1818         {
1819           const RTX_CODE *c;
1820
1821           for (c = &preds[p->tests->u.pred.index].codes[0]; *c ; ++c)
1822             if (codemap[(int) *c] != 0)
1823               goto pred_done;
1824
1825           for (c = &preds[p->tests->u.pred.index].codes[0]; *c ; ++c)
1826             {
1827               printf ("    case ");
1828               print_code (*c);
1829               printf (":\n");
1830               codemap[(int) *c] = 1;
1831             }
1832
1833           printf ("      goto L%d;\n", p->number);
1834           p->need_label = 1;
1835           p = p->next;
1836         }
1837
1838     pred_done:
1839       /* Make the default case skip the predicates we managed to match.  */
1840
1841       printf ("    default:\n");
1842       if (p != ret)
1843         {
1844           if (p)
1845             {
1846               printf ("      goto L%d;\n", p->number);
1847               p->need_label = 1;
1848             }
1849           else
1850             write_afterward (start, start->afterward, "      ");
1851         }
1852       else
1853         printf ("     break;\n");
1854       printf ("   }\n");
1855
1856       return ret;
1857     }
1858   else if (type == DT_mode
1859            || type == DT_veclen
1860            || type == DT_elt_zero_int
1861            || type == DT_elt_one_int
1862            || type == DT_elt_zero_wide_safe)
1863     {
1864       const char *indent = "";
1865
1866       /* We cast switch parameter to integer, so we must ensure that the value
1867          fits.  */
1868       if (type == DT_elt_zero_wide_safe)
1869         {
1870           indent = "  ";
1871           printf("  if ((int) XWINT (x%d, 0) == XWINT (x%d, 0))\n", depth, depth);
1872         }
1873       printf ("%s  switch (", indent);
1874       switch (type)
1875         {
1876         case DT_mode:
1877           printf ("GET_MODE (x%d)", depth);
1878           break;
1879         case DT_veclen:
1880           printf ("XVECLEN (x%d, 0)", depth);
1881           break;
1882         case DT_elt_zero_int:
1883           printf ("XINT (x%d, 0)", depth);
1884           break;
1885         case DT_elt_one_int:
1886           printf ("XINT (x%d, 1)", depth);
1887           break;
1888         case DT_elt_zero_wide_safe:
1889           /* Convert result of XWINT to int for portability since some C
1890              compilers won't do it and some will.  */
1891           printf ("(int) XWINT (x%d, 0)", depth);
1892           break;
1893         default:
1894           abort ();
1895         }
1896       printf (")\n%s    {\n", indent);
1897
1898       do
1899         {
1900           /* Merge trees will not unify identical nodes if their
1901              sub-nodes are at different levels.  Thus we must check
1902              for duplicate cases.  */
1903           struct decision *q;
1904           for (q = start; q != p; q = q->next)
1905             if (nodes_identical_1 (p->tests, q->tests))
1906               goto case_done;
1907
1908           if (p != start && p->need_label && needs_label == NULL)
1909             needs_label = p;
1910
1911           printf ("%s    case ", indent);
1912           switch (type)
1913             {
1914             case DT_mode:
1915               printf ("%smode", GET_MODE_NAME (p->tests->u.mode));
1916               break;
1917             case DT_veclen:
1918               printf ("%d", p->tests->u.veclen);
1919               break;
1920             case DT_elt_zero_int:
1921             case DT_elt_one_int:
1922             case DT_elt_zero_wide:
1923             case DT_elt_zero_wide_safe:
1924               print_host_wide_int (p->tests->u.intval);
1925               break;
1926             default:
1927               abort ();
1928             }
1929           printf (":\n%s      goto L%d;\n", indent, p->success.first->number);
1930           p->success.first->need_label = 1;
1931
1932           p = p->next;
1933         }
1934       while (p && p->tests->type == type && !p->tests->next);
1935
1936     case_done:
1937       printf ("%s    default:\n%s      break;\n%s    }\n",
1938               indent, indent, indent);
1939
1940       return needs_label != NULL ? needs_label : p;
1941     }
1942   else
1943     {
1944       /* None of the other tests are amenable.  */
1945       return p;
1946     }
1947 }
1948
1949 /* Emit code for one test.  */
1950
1951 static void
1952 write_cond (struct decision_test *p, int depth,
1953             enum routine_type subroutine_type)
1954 {
1955   switch (p->type)
1956     {
1957     case DT_mode:
1958       printf ("GET_MODE (x%d) == %smode", depth, GET_MODE_NAME (p->u.mode));
1959       break;
1960
1961     case DT_code:
1962       printf ("GET_CODE (x%d) == ", depth);
1963       print_code (p->u.code);
1964       break;
1965
1966     case DT_veclen:
1967       printf ("XVECLEN (x%d, 0) == %d", depth, p->u.veclen);
1968       break;
1969
1970     case DT_elt_zero_int:
1971       printf ("XINT (x%d, 0) == %d", depth, (int) p->u.intval);
1972       break;
1973
1974     case DT_elt_one_int:
1975       printf ("XINT (x%d, 1) == %d", depth, (int) p->u.intval);
1976       break;
1977
1978     case DT_elt_zero_wide:
1979     case DT_elt_zero_wide_safe:
1980       printf ("XWINT (x%d, 0) == ", depth);
1981       print_host_wide_int (p->u.intval);
1982       break;
1983
1984     case DT_veclen_ge:
1985       printf ("XVECLEN (x%d, 0) >= %d", depth, p->u.veclen);
1986       break;
1987
1988     case DT_dup:
1989       printf ("rtx_equal_p (x%d, operands[%d])", depth, p->u.dup);
1990       break;
1991
1992     case DT_pred:
1993       printf ("%s (x%d, %smode)", p->u.pred.name, depth,
1994               GET_MODE_NAME (p->u.pred.mode));
1995       break;
1996
1997     case DT_c_test:
1998       printf ("(%s)", p->u.c_test);
1999       break;
2000
2001     case DT_accept_insn:
2002       switch (subroutine_type)
2003         {
2004         case RECOG:
2005           if (p->u.insn.num_clobbers_to_add == 0)
2006             abort ();
2007           printf ("pnum_clobbers != NULL");
2008           break;
2009
2010         default:
2011           abort ();
2012         }
2013       break;
2014
2015     default:
2016       abort ();
2017     }
2018 }
2019
2020 /* Emit code for one action.  The previous tests have succeeded;
2021    TEST is the last of the chain.  In the normal case we simply
2022    perform a state change.  For the `accept' tests we must do more work.  */
2023
2024 static void
2025 write_action (struct decision *p, struct decision_test *test,
2026               int depth, int uncond, struct decision *success,
2027               enum routine_type subroutine_type)
2028 {
2029   const char *indent;
2030   int want_close = 0;
2031
2032   if (uncond)
2033     indent = "  ";
2034   else if (test->type == DT_accept_op || test->type == DT_accept_insn)
2035     {
2036       fputs ("    {\n", stdout);
2037       indent = "      ";
2038       want_close = 1;
2039     }
2040   else
2041     indent = "    ";
2042
2043   if (test->type == DT_accept_op)
2044     {
2045       printf("%soperands[%d] = x%d;\n", indent, test->u.opno, depth);
2046
2047       /* Only allow DT_accept_insn to follow.  */
2048       if (test->next)
2049         {
2050           test = test->next;
2051           if (test->type != DT_accept_insn)
2052             abort ();
2053         }
2054     }
2055
2056   /* Sanity check that we're now at the end of the list of tests.  */
2057   if (test->next)
2058     abort ();
2059
2060   if (test->type == DT_accept_insn)
2061     {
2062       switch (subroutine_type)
2063         {
2064         case RECOG:
2065           if (test->u.insn.num_clobbers_to_add != 0)
2066             printf ("%s*pnum_clobbers = %d;\n",
2067                     indent, test->u.insn.num_clobbers_to_add);
2068           printf ("%sreturn %d;\n", indent, test->u.insn.code_number);
2069           break;
2070
2071         case SPLIT:
2072           printf ("%sreturn gen_split_%d (operands);\n",
2073                   indent, test->u.insn.code_number);
2074           break;
2075
2076         case PEEPHOLE2:
2077           {
2078             int match_len = 0, i;
2079
2080             for (i = strlen (p->position) - 1; i >= 0; --i)
2081               if (ISUPPER (p->position[i]))
2082                 {
2083                   match_len = p->position[i] - 'A';
2084                   break;
2085                 }
2086             printf ("%s*_pmatch_len = %d;\n", indent, match_len);
2087             printf ("%stem = gen_peephole2_%d (insn, operands);\n",
2088                     indent, test->u.insn.code_number);
2089             printf ("%sif (tem != 0)\n%s  return tem;\n", indent, indent);
2090           }
2091           break;
2092
2093         default:
2094           abort ();
2095         }
2096     }
2097   else
2098     {
2099       printf("%sgoto L%d;\n", indent, success->number);
2100       success->need_label = 1;
2101     }
2102
2103   if (want_close)
2104     fputs ("    }\n", stdout);
2105 }
2106
2107 /* Return 1 if the test is always true and has no fallthru path.  Return -1
2108    if the test does have a fallthru path, but requires that the condition be
2109    terminated.  Otherwise return 0 for a normal test.  */
2110 /* ??? is_unconditional is a stupid name for a tri-state function.  */
2111
2112 static int
2113 is_unconditional (struct decision_test *t, enum routine_type subroutine_type)
2114 {
2115   if (t->type == DT_accept_op)
2116     return 1;
2117
2118   if (t->type == DT_accept_insn)
2119     {
2120       switch (subroutine_type)
2121         {
2122         case RECOG:
2123           return (t->u.insn.num_clobbers_to_add == 0);
2124         case SPLIT:
2125           return 1;
2126         case PEEPHOLE2:
2127           return -1;
2128         default:
2129           abort ();
2130         }
2131     }
2132
2133   return 0;
2134 }
2135
2136 /* Emit code for one node -- the conditional and the accompanying action.
2137    Return true if there is no fallthru path.  */
2138
2139 static int
2140 write_node (struct decision *p, int depth,
2141             enum routine_type subroutine_type)
2142 {
2143   struct decision_test *test, *last_test;
2144   int uncond;
2145
2146   last_test = test = p->tests;
2147   uncond = is_unconditional (test, subroutine_type);
2148   if (uncond == 0)
2149     {
2150       printf ("  if (");
2151       write_cond (test, depth, subroutine_type);
2152
2153       while ((test = test->next) != NULL)
2154         {
2155           int uncond2;
2156
2157           last_test = test;
2158           uncond2 = is_unconditional (test, subroutine_type);
2159           if (uncond2 != 0)
2160             break;
2161
2162           printf ("\n      && ");
2163           write_cond (test, depth, subroutine_type);
2164         }
2165
2166       printf (")\n");
2167     }
2168
2169   write_action (p, last_test, depth, uncond, p->success.first, subroutine_type);
2170
2171   return uncond > 0;
2172 }
2173
2174 /* Emit code for all of the sibling nodes of HEAD.  */
2175
2176 static void
2177 write_tree_1 (struct decision_head *head, int depth,
2178               enum routine_type subroutine_type)
2179 {
2180   struct decision *p, *next;
2181   int uncond = 0;
2182
2183   for (p = head->first; p ; p = next)
2184     {
2185       /* The label for the first element was printed in write_tree.  */
2186       if (p != head->first && p->need_label)
2187         OUTPUT_LABEL (" ", p->number);
2188
2189       /* Attempt to write a switch statement for a whole sequence.  */
2190       next = write_switch (p, depth);
2191       if (p != next)
2192         uncond = 0;
2193       else
2194         {
2195           /* Failed -- fall back and write one node.  */
2196           uncond = write_node (p, depth, subroutine_type);
2197           next = p->next;
2198         }
2199     }
2200
2201   /* Finished with this chain.  Close a fallthru path by branching
2202      to the afterward node.  */
2203   if (! uncond)
2204     write_afterward (head->last, head->last->afterward, "  ");
2205 }
2206
2207 /* Write out the decision tree starting at HEAD.  PREVPOS is the
2208    position at the node that branched to this node.  */
2209
2210 static void
2211 write_tree (struct decision_head *head, const char *prevpos,
2212             enum routine_type type, int initial)
2213 {
2214   struct decision *p = head->first;
2215
2216   putchar ('\n');
2217   if (p->need_label)
2218     OUTPUT_LABEL (" ", p->number);
2219
2220   if (! initial && p->subroutine_number > 0)
2221     {
2222       static const char * const name_prefix[] = {
2223           "recog", "split", "peephole2"
2224       };
2225
2226       static const char * const call_suffix[] = {
2227           ", pnum_clobbers", "", ", _pmatch_len"
2228       };
2229
2230       /* This node has been broken out into a separate subroutine.
2231          Call it, test the result, and branch accordingly.  */
2232
2233       if (p->afterward)
2234         {
2235           printf ("  tem = %s_%d (x0, insn%s);\n",
2236                   name_prefix[type], p->subroutine_number, call_suffix[type]);
2237           if (IS_SPLIT (type))
2238             printf ("  if (tem != 0)\n    return tem;\n");
2239           else
2240             printf ("  if (tem >= 0)\n    return tem;\n");
2241
2242           change_state (p->position, p->afterward->position, NULL, "  ");
2243           printf ("  goto L%d;\n", p->afterward->number);
2244         }
2245       else
2246         {
2247           printf ("  return %s_%d (x0, insn%s);\n",
2248                   name_prefix[type], p->subroutine_number, call_suffix[type]);
2249         }
2250     }
2251   else
2252     {
2253       int depth = strlen (p->position);
2254
2255       change_state (prevpos, p->position, head->last->afterward, "  ");
2256       write_tree_1 (head, depth, type);
2257
2258       for (p = head->first; p; p = p->next)
2259         if (p->success.first)
2260           write_tree (&p->success, p->position, type, 0);
2261     }
2262 }
2263
2264 /* Write out a subroutine of type TYPE to do comparisons starting at
2265    node TREE.  */
2266
2267 static void
2268 write_subroutine (struct decision_head *head, enum routine_type type)
2269 {
2270   int subfunction = head->first ? head->first->subroutine_number : 0;
2271   const char *s_or_e;
2272   char extension[32];
2273   int i;
2274
2275   s_or_e = subfunction ? "static " : "";
2276
2277   if (subfunction)
2278     sprintf (extension, "_%d", subfunction);
2279   else if (type == RECOG)
2280     extension[0] = '\0';
2281   else
2282     strcpy (extension, "_insns");
2283
2284   switch (type)
2285     {
2286     case RECOG:
2287       printf ("%sint\n\
2288 recog%s (rtx x0 ATTRIBUTE_UNUSED,\n\trtx insn ATTRIBUTE_UNUSED,\n\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n", s_or_e, extension);
2289       break;
2290     case SPLIT:
2291       printf ("%srtx\n\
2292 split%s (rtx x0 ATTRIBUTE_UNUSED, rtx insn ATTRIBUTE_UNUSED)\n",
2293               s_or_e, extension);
2294       break;
2295     case PEEPHOLE2:
2296       printf ("%srtx\n\
2297 peephole2%s (rtx x0 ATTRIBUTE_UNUSED,\n\trtx insn ATTRIBUTE_UNUSED,\n\tint *_pmatch_len ATTRIBUTE_UNUSED)\n",
2298               s_or_e, extension);
2299       break;
2300     }
2301
2302   printf ("{\n  rtx * const operands ATTRIBUTE_UNUSED = &recog_data.operand[0];\n");
2303   for (i = 1; i <= max_depth; i++)
2304     printf ("  rtx x%d ATTRIBUTE_UNUSED;\n", i);
2305
2306   printf ("  %s tem ATTRIBUTE_UNUSED;\n", IS_SPLIT (type) ? "rtx" : "int");
2307
2308   if (!subfunction)
2309     printf ("  recog_data.insn = NULL_RTX;\n");
2310
2311   if (head->first)
2312     write_tree (head, "", type, 1);
2313   else
2314     printf ("  goto ret0;\n");
2315
2316   printf (" ret0:\n  return %d;\n}\n\n", IS_SPLIT (type) ? 0 : -1);
2317 }
2318
2319 /* In break_out_subroutines, we discovered the boundaries for the
2320    subroutines, but did not write them out.  Do so now.  */
2321
2322 static void
2323 write_subroutines (struct decision_head *head, enum routine_type type)
2324 {
2325   struct decision *p;
2326
2327   for (p = head->first; p ; p = p->next)
2328     if (p->success.first)
2329       write_subroutines (&p->success, type);
2330
2331   if (head->first->subroutine_number > 0)
2332     write_subroutine (head, type);
2333 }
2334
2335 /* Begin the output file.  */
2336
2337 static void
2338 write_header (void)
2339 {
2340   puts ("\
2341 /* Generated automatically by the program `genrecog' from the target\n\
2342    machine description file.  */\n\
2343 \n\
2344 #include \"config.h\"\n\
2345 #include \"system.h\"\n\
2346 #include \"coretypes.h\"\n\
2347 #include \"tm.h\"\n\
2348 #include \"rtl.h\"\n\
2349 #include \"tm_p.h\"\n\
2350 #include \"function.h\"\n\
2351 #include \"insn-config.h\"\n\
2352 #include \"recog.h\"\n\
2353 #include \"real.h\"\n\
2354 #include \"output.h\"\n\
2355 #include \"flags.h\"\n\
2356 #include \"hard-reg-set.h\"\n\
2357 #include \"resource.h\"\n\
2358 #include \"toplev.h\"\n\
2359 #include \"reload.h\"\n\
2360 \n");
2361
2362   puts ("\n\
2363 /* `recog' contains a decision tree that recognizes whether the rtx\n\
2364    X0 is a valid instruction.\n\
2365 \n\
2366    recog returns -1 if the rtx is not valid.  If the rtx is valid, recog\n\
2367    returns a nonnegative number which is the insn code number for the\n\
2368    pattern that matched.  This is the same as the order in the machine\n\
2369    description of the entry that matched.  This number can be used as an\n\
2370    index into `insn_data' and other tables.\n");
2371   puts ("\
2372    The third argument to recog is an optional pointer to an int.  If\n\
2373    present, recog will accept a pattern if it matches except for missing\n\
2374    CLOBBER expressions at the end.  In that case, the value pointed to by\n\
2375    the optional pointer will be set to the number of CLOBBERs that need\n\
2376    to be added (it should be initialized to zero by the caller).  If it");
2377   puts ("\
2378    is set nonzero, the caller should allocate a PARALLEL of the\n\
2379    appropriate size, copy the initial entries, and call add_clobbers\n\
2380    (found in insn-emit.c) to fill in the CLOBBERs.\n\
2381 ");
2382
2383   puts ("\n\
2384    The function split_insns returns 0 if the rtl could not\n\
2385    be split or the split rtl as an INSN list if it can be.\n\
2386 \n\
2387    The function peephole2_insns returns 0 if the rtl could not\n\
2388    be matched. If there was a match, the new rtl is returned in an INSN list,\n\
2389    and LAST_INSN will point to the last recognized insn in the old sequence.\n\
2390 */\n\n");
2391 }
2392
2393 \f
2394 /* Construct and return a sequence of decisions
2395    that will recognize INSN.
2396
2397    TYPE says what type of routine we are recognizing (RECOG or SPLIT).  */
2398
2399 static struct decision_head
2400 make_insn_sequence (rtx insn, enum routine_type type)
2401 {
2402   rtx x;
2403   const char *c_test = XSTR (insn, type == RECOG ? 2 : 1);
2404   int truth = maybe_eval_c_test (c_test);
2405   struct decision *last;
2406   struct decision_test *test, **place;
2407   struct decision_head head;
2408   char c_test_pos[2];
2409
2410   /* We should never see an insn whose C test is false at compile time.  */
2411   if (truth == 0)
2412     abort ();
2413
2414   record_insn_name (next_insn_code, (type == RECOG ? XSTR (insn, 0) : NULL));
2415
2416   c_test_pos[0] = '\0';
2417   if (type == PEEPHOLE2)
2418     {
2419       int i, j;
2420
2421       /* peephole2 gets special treatment:
2422          - X always gets an outer parallel even if it's only one entry
2423          - we remove all traces of outer-level match_scratch and match_dup
2424            expressions here.  */
2425       x = rtx_alloc (PARALLEL);
2426       PUT_MODE (x, VOIDmode);
2427       XVEC (x, 0) = rtvec_alloc (XVECLEN (insn, 0));
2428       for (i = j = 0; i < XVECLEN (insn, 0); i++)
2429         {
2430           rtx tmp = XVECEXP (insn, 0, i);
2431           if (GET_CODE (tmp) != MATCH_SCRATCH && GET_CODE (tmp) != MATCH_DUP)
2432             {
2433               XVECEXP (x, 0, j) = tmp;
2434               j++;
2435             }
2436         }
2437       XVECLEN (x, 0) = j;
2438
2439       c_test_pos[0] = 'A' + j - 1;
2440       c_test_pos[1] = '\0';
2441     }
2442   else if (XVECLEN (insn, type == RECOG) == 1)
2443     x = XVECEXP (insn, type == RECOG, 0);
2444   else
2445     {
2446       x = rtx_alloc (PARALLEL);
2447       XVEC (x, 0) = XVEC (insn, type == RECOG);
2448       PUT_MODE (x, VOIDmode);
2449     }
2450
2451   validate_pattern (x, insn, NULL_RTX, 0);
2452
2453   memset(&head, 0, sizeof(head));
2454   last = add_to_sequence (x, &head, "", type, 1);
2455
2456   /* Find the end of the test chain on the last node.  */
2457   for (test = last->tests; test->next; test = test->next)
2458     continue;
2459   place = &test->next;
2460
2461   /* Skip the C test if it's known to be true at compile time.  */
2462   if (truth == -1)
2463     {
2464       /* Need a new node if we have another test to add.  */
2465       if (test->type == DT_accept_op)
2466         {
2467           last = new_decision (c_test_pos, &last->success);
2468           place = &last->tests;
2469         }
2470       test = new_decision_test (DT_c_test, &place);
2471       test->u.c_test = c_test;
2472     }
2473
2474   test = new_decision_test (DT_accept_insn, &place);
2475   test->u.insn.code_number = next_insn_code;
2476   test->u.insn.lineno = pattern_lineno;
2477   test->u.insn.num_clobbers_to_add = 0;
2478
2479   switch (type)
2480     {
2481     case RECOG:
2482       /* If this is a DEFINE_INSN and X is a PARALLEL, see if it ends
2483          with a group of CLOBBERs of (hard) registers or MATCH_SCRATCHes.
2484          If so, set up to recognize the pattern without these CLOBBERs.  */
2485
2486       if (GET_CODE (x) == PARALLEL)
2487         {
2488           int i;
2489
2490           /* Find the last non-clobber in the parallel.  */
2491           for (i = XVECLEN (x, 0); i > 0; i--)
2492             {
2493               rtx y = XVECEXP (x, 0, i - 1);
2494               if (GET_CODE (y) != CLOBBER
2495                   || (GET_CODE (XEXP (y, 0)) != REG
2496                       && GET_CODE (XEXP (y, 0)) != MATCH_SCRATCH))
2497                 break;
2498             }
2499
2500           if (i != XVECLEN (x, 0))
2501             {
2502               rtx new;
2503               struct decision_head clobber_head;
2504
2505               /* Build a similar insn without the clobbers.  */
2506               if (i == 1)
2507                 new = XVECEXP (x, 0, 0);
2508               else
2509                 {
2510                   int j;
2511
2512                   new = rtx_alloc (PARALLEL);
2513                   XVEC (new, 0) = rtvec_alloc (i);
2514                   for (j = i - 1; j >= 0; j--)
2515                     XVECEXP (new, 0, j) = XVECEXP (x, 0, j);
2516                 }
2517
2518               /* Recognize it.  */
2519               memset (&clobber_head, 0, sizeof(clobber_head));
2520               last = add_to_sequence (new, &clobber_head, "", type, 1);
2521
2522               /* Find the end of the test chain on the last node.  */
2523               for (test = last->tests; test->next; test = test->next)
2524                 continue;
2525
2526               /* We definitely have a new test to add -- create a new
2527                  node if needed.  */
2528               place = &test->next;
2529               if (test->type == DT_accept_op)
2530                 {
2531                   last = new_decision ("", &last->success);
2532                   place = &last->tests;
2533                 }
2534
2535               /* Skip the C test if it's known to be true at compile
2536                  time.  */
2537               if (truth == -1)
2538                 {
2539                   test = new_decision_test (DT_c_test, &place);
2540                   test->u.c_test = c_test;
2541                 }
2542
2543               test = new_decision_test (DT_accept_insn, &place);
2544               test->u.insn.code_number = next_insn_code;
2545               test->u.insn.lineno = pattern_lineno;
2546               test->u.insn.num_clobbers_to_add = XVECLEN (x, 0) - i;
2547
2548               merge_trees (&head, &clobber_head);
2549             }
2550         }
2551       break;
2552
2553     case SPLIT:
2554       /* Define the subroutine we will call below and emit in genemit.  */
2555       printf ("extern rtx gen_split_%d (rtx *);\n", next_insn_code);
2556       break;
2557
2558     case PEEPHOLE2:
2559       /* Define the subroutine we will call below and emit in genemit.  */
2560       printf ("extern rtx gen_peephole2_%d (rtx, rtx *);\n",
2561               next_insn_code);
2562       break;
2563     }
2564
2565   return head;
2566 }
2567
2568 static void
2569 process_tree (struct decision_head *head, enum routine_type subroutine_type)
2570 {
2571   if (head->first == NULL)
2572     {
2573       /* We can elide peephole2_insns, but not recog or split_insns.  */
2574       if (subroutine_type == PEEPHOLE2)
2575         return;
2576     }
2577   else
2578     {
2579       factor_tests (head);
2580
2581       next_subroutine_number = 0;
2582       break_out_subroutines (head, 1);
2583       find_afterward (head, NULL);
2584
2585       /* We run this after find_afterward, because find_afterward needs
2586          the redundant DT_mode tests on predicates to determine whether
2587          two tests can both be true or not.  */
2588       simplify_tests(head);
2589
2590       write_subroutines (head, subroutine_type);
2591     }
2592
2593   write_subroutine (head, subroutine_type);
2594 }
2595 \f
2596 extern int main (int, char **);
2597
2598 int
2599 main (int argc, char **argv)
2600 {
2601   rtx desc;
2602   struct decision_head recog_tree, split_tree, peephole2_tree, h;
2603
2604   progname = "genrecog";
2605
2606   memset (&recog_tree, 0, sizeof recog_tree);
2607   memset (&split_tree, 0, sizeof split_tree);
2608   memset (&peephole2_tree, 0, sizeof peephole2_tree);
2609
2610   if (argc <= 1)
2611     fatal ("no input file name");
2612
2613   if (init_md_reader_args (argc, argv) != SUCCESS_EXIT_CODE)
2614     return (FATAL_EXIT_CODE);
2615
2616   next_insn_code = 0;
2617   next_index = 0;
2618
2619   write_header ();
2620
2621   /* Read the machine description.  */
2622
2623   while (1)
2624     {
2625       desc = read_md_rtx (&pattern_lineno, &next_insn_code);
2626       if (desc == NULL)
2627         break;
2628
2629       if (GET_CODE (desc) == DEFINE_INSN)
2630         {
2631           h = make_insn_sequence (desc, RECOG);
2632           merge_trees (&recog_tree, &h);
2633         }
2634       else if (GET_CODE (desc) == DEFINE_SPLIT)
2635         {
2636           h = make_insn_sequence (desc, SPLIT);
2637           merge_trees (&split_tree, &h);
2638         }
2639       else if (GET_CODE (desc) == DEFINE_PEEPHOLE2)
2640         {
2641           h = make_insn_sequence (desc, PEEPHOLE2);
2642           merge_trees (&peephole2_tree, &h);
2643         }
2644
2645       next_index++;
2646     }
2647
2648   if (error_count)
2649     return FATAL_EXIT_CODE;
2650
2651   puts ("\n\n");
2652
2653   process_tree (&recog_tree, RECOG);
2654   process_tree (&split_tree, SPLIT);
2655   process_tree (&peephole2_tree, PEEPHOLE2);
2656
2657   fflush (stdout);
2658   return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
2659 }
2660 \f
2661 /* Define this so we can link with print-rtl.o to get debug_rtx function.  */
2662 const char *
2663 get_insn_name (int code)
2664 {
2665   if (code < insn_name_ptr_size)
2666     return insn_name_ptr[code];
2667   else
2668     return NULL;
2669 }
2670
2671 static void
2672 record_insn_name (int code, const char *name)
2673 {
2674   static const char *last_real_name = "insn";
2675   static int last_real_code = 0;
2676   char *new;
2677
2678   if (insn_name_ptr_size <= code)
2679     {
2680       int new_size;
2681       new_size = (insn_name_ptr_size ? insn_name_ptr_size * 2 : 512);
2682       insn_name_ptr = xrealloc (insn_name_ptr, sizeof(char *) * new_size);
2683       memset (insn_name_ptr + insn_name_ptr_size, 0,
2684               sizeof(char *) * (new_size - insn_name_ptr_size));
2685       insn_name_ptr_size = new_size;
2686     }
2687
2688   if (!name || name[0] == '\0')
2689     {
2690       new = xmalloc (strlen (last_real_name) + 10);
2691       sprintf (new, "%s+%d", last_real_name, code - last_real_code);
2692     }
2693   else
2694     {
2695       last_real_name = new = xstrdup (name);
2696       last_real_code = code;
2697     }
2698
2699   insn_name_ptr[code] = new;
2700 }
2701 \f
2702 static void
2703 debug_decision_2 (struct decision_test *test)
2704 {
2705   switch (test->type)
2706     {
2707     case DT_mode:
2708       fprintf (stderr, "mode=%s", GET_MODE_NAME (test->u.mode));
2709       break;
2710     case DT_code:
2711       fprintf (stderr, "code=%s", GET_RTX_NAME (test->u.code));
2712       break;
2713     case DT_veclen:
2714       fprintf (stderr, "veclen=%d", test->u.veclen);
2715       break;
2716     case DT_elt_zero_int:
2717       fprintf (stderr, "elt0_i=%d", (int) test->u.intval);
2718       break;
2719     case DT_elt_one_int:
2720       fprintf (stderr, "elt1_i=%d", (int) test->u.intval);
2721       break;
2722     case DT_elt_zero_wide:
2723       fprintf (stderr, "elt0_w=" HOST_WIDE_INT_PRINT_DEC, test->u.intval);
2724       break;
2725     case DT_elt_zero_wide_safe:
2726       fprintf (stderr, "elt0_ws=" HOST_WIDE_INT_PRINT_DEC, test->u.intval);
2727       break;
2728     case DT_veclen_ge:
2729       fprintf (stderr, "veclen>=%d", test->u.veclen);
2730       break;
2731     case DT_dup:
2732       fprintf (stderr, "dup=%d", test->u.dup);
2733       break;
2734     case DT_pred:
2735       fprintf (stderr, "pred=(%s,%s)",
2736                test->u.pred.name, GET_MODE_NAME(test->u.pred.mode));
2737       break;
2738     case DT_c_test:
2739       {
2740         char sub[16+4];
2741         strncpy (sub, test->u.c_test, sizeof(sub));
2742         memcpy (sub+16, "...", 4);
2743         fprintf (stderr, "c_test=\"%s\"", sub);
2744       }
2745       break;
2746     case DT_accept_op:
2747       fprintf (stderr, "A_op=%d", test->u.opno);
2748       break;
2749     case DT_accept_insn:
2750       fprintf (stderr, "A_insn=(%d,%d)",
2751                test->u.insn.code_number, test->u.insn.num_clobbers_to_add);
2752       break;
2753
2754     default:
2755       abort ();
2756     }
2757 }
2758
2759 static void
2760 debug_decision_1 (struct decision *d, int indent)
2761 {
2762   int i;
2763   struct decision_test *test;
2764
2765   if (d == NULL)
2766     {
2767       for (i = 0; i < indent; ++i)
2768         putc (' ', stderr);
2769       fputs ("(nil)\n", stderr);
2770       return;
2771     }
2772
2773   for (i = 0; i < indent; ++i)
2774     putc (' ', stderr);
2775
2776   putc ('{', stderr);
2777   test = d->tests;
2778   if (test)
2779     {
2780       debug_decision_2 (test);
2781       while ((test = test->next) != NULL)
2782         {
2783           fputs (" + ", stderr);
2784           debug_decision_2 (test);
2785         }
2786     }
2787   fprintf (stderr, "} %d n %d a %d\n", d->number,
2788            (d->next ? d->next->number : -1),
2789            (d->afterward ? d->afterward->number : -1));
2790 }
2791
2792 static void
2793 debug_decision_0 (struct decision *d, int indent, int maxdepth)
2794 {
2795   struct decision *n;
2796   int i;
2797
2798   if (maxdepth < 0)
2799     return;
2800   if (d == NULL)
2801     {
2802       for (i = 0; i < indent; ++i)
2803         putc (' ', stderr);
2804       fputs ("(nil)\n", stderr);
2805       return;
2806     }
2807
2808   debug_decision_1 (d, indent);
2809   for (n = d->success.first; n ; n = n->next)
2810     debug_decision_0 (n, indent + 2, maxdepth - 1);
2811 }
2812
2813 void
2814 debug_decision (struct decision *d)
2815 {
2816   debug_decision_0 (d, 0, 1000000);
2817 }
2818
2819 void
2820 debug_decision_list (struct decision *d)
2821 {
2822   while (d)
2823     {
2824       debug_decision_0 (d, 0, 0);
2825       d = d->next;
2826     }
2827 }