OSDN Git Service

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