[PR67828] don't unswitch on default defs of non-parms
[official-gcc.git] / gcc / genrecog.c
blob599121fb693da4e4388f574ec2538c9bd33f38c2
1 /* Generate code from machine description to recognize rtl as insns.
2 Copyright (C) 1987-2015 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
21 /* This program is used to produce insn-recog.c, which contains a
22 function called `recog' plus its subroutines. These functions
23 contain a decision tree that recognizes whether an rtx, the
24 argument given to recog, is a valid instruction.
26 recog returns -1 if the rtx is not valid. If the rtx is valid,
27 recog returns a nonnegative number which is the insn code number
28 for the pattern that matched. This is the same as the order in the
29 machine description of the entry that matched. This number can be
30 used as an index into various insn_* tables, such as insn_template,
31 insn_outfun, and insn_n_operands (found in insn-output.c).
33 The third argument to recog is an optional pointer to an int. If
34 present, recog will accept a pattern if it matches except for
35 missing CLOBBER expressions at the end. In that case, the value
36 pointed to by the optional pointer will be set to the number of
37 CLOBBERs that need to be added (it should be initialized to zero by
38 the caller). If it is set nonzero, the caller should allocate a
39 PARALLEL of the appropriate size, copy the initial entries, and
40 call add_clobbers (found in insn-emit.c) to fill in the CLOBBERs.
42 This program also generates the function `split_insns', which
43 returns 0 if the rtl could not be split, or it returns the split
44 rtl as an INSN list.
46 This program also generates the function `peephole2_insns', which
47 returns 0 if the rtl could not be matched. If there was a match,
48 the new rtl is returned in an INSN list, and LAST_INSN will point
49 to the last recognized insn in the old sequence.
52 At a high level, the algorithm used in this file is as follows:
54 1. Build up a decision tree for each routine, using the following
55 approach to matching an rtx:
57 - First determine the "shape" of the rtx, based on GET_CODE,
58 XVECLEN and XINT. This phase examines SET_SRCs before SET_DESTs
59 since SET_SRCs tend to be more distinctive. It examines other
60 operands in numerical order, since the canonicalization rules
61 prefer putting complex operands of commutative operators first.
63 - Next check modes and predicates. This phase examines all
64 operands in numerical order, even for SETs, since the mode of a
65 SET_DEST is exact while the mode of a SET_SRC can be VOIDmode
66 for constant integers.
68 - Next check match_dups.
70 - Finally check the C condition and (where appropriate) pnum_clobbers.
72 2. Try to optimize the tree by removing redundant tests, CSEing tests,
73 folding tests together, etc.
75 3. Look for common subtrees and split them out into "pattern" routines.
76 These common subtrees can be identical or they can differ in mode,
77 code, or integer (usually an UNSPEC or UNSPEC_VOLATILE code).
78 In the latter case the users of the pattern routine pass the
79 appropriate mode, etc., as argument. For example, if two patterns
80 contain:
82 (plus:SI (match_operand:SI 1 "register_operand")
83 (match_operand:SI 2 "register_operand"))
85 we can split the associated matching code out into a subroutine.
86 If a pattern contains:
88 (minus:DI (match_operand:DI 1 "register_operand")
89 (match_operand:DI 2 "register_operand"))
91 then we can consider using the same matching routine for both
92 the plus and minus expressions, passing PLUS and SImode in the
93 former case and MINUS and DImode in the latter case.
95 The main aim of this phase is to reduce the compile time of the
96 insn-recog.c code and to reduce the amount of object code in
97 insn-recog.o.
99 4. Split the matching trees into functions, trying to limit the
100 size of each function to a sensible amount.
102 Again, the main aim of this phase is to reduce the compile time
103 of insn-recog.c. (It doesn't help with the size of insn-recog.o.)
105 5. Write out C++ code for each function. */
107 #include "bconfig.h"
108 #include "system.h"
109 #include "coretypes.h"
110 #include "tm.h"
111 #include "rtl.h"
112 #include "errors.h"
113 #include "read-md.h"
114 #include "gensupport.h"
115 #include <algorithm>
117 #undef GENERATOR_FILE
118 enum true_rtx_doe {
119 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) TRUE_##ENUM,
120 #include "rtl.def"
121 #undef DEF_RTL_EXPR
122 FIRST_GENERATOR_RTX_CODE
124 #define NUM_TRUE_RTX_CODE ((int) FIRST_GENERATOR_RTX_CODE)
125 #define GENERATOR_FILE 1
127 /* Debugging variables to control which optimizations are performed.
128 Note that disabling merge_states_p leads to very large output. */
129 static const bool merge_states_p = true;
130 static const bool collapse_optional_decisions_p = true;
131 static const bool cse_tests_p = true;
132 static const bool simplify_tests_p = true;
133 static const bool use_operand_variables_p = true;
134 static const bool use_subroutines_p = true;
135 static const bool use_pattern_routines_p = true;
137 /* Whether to add comments for optional tests that we decided to keep.
138 Can be useful when debugging the generator itself but is noise when
139 debugging the generated code. */
140 static const bool mark_optional_transitions_p = false;
142 /* Whether pattern routines should calculate positions relative to their
143 rtx parameter rather than use absolute positions. This e.g. allows
144 a pattern routine to be shared between a plain SET and a PARALLEL
145 that includes a SET.
147 In principle it sounds like this should be useful, especially for
148 recog_for_combine, where the plain SET form is generated automatically
149 from a PARALLEL of a single SET and some CLOBBERs. In practice it doesn't
150 seem to help much and leads to slightly bigger object files. */
151 static const bool relative_patterns_p = false;
153 /* Whether pattern routines should be allowed to test whether pnum_clobbers
154 is null. This requires passing pnum_clobbers around as a parameter. */
155 static const bool pattern_have_num_clobbers_p = true;
157 /* Whether pattern routines should be allowed to test .md file C conditions.
158 This requires passing insn around as a parameter, in case the C
159 condition refers to it. In practice this tends to lead to bigger
160 object files. */
161 static const bool pattern_c_test_p = false;
163 /* Whether to require each parameter passed to a pattern routine to be
164 unique. Disabling this check for example allows unary operators with
165 matching modes (like NEG) and unary operators with mismatched modes
166 (like ZERO_EXTEND) to be matched by a single pattern. However, we then
167 often have cases where the same value is passed too many times. */
168 static const bool force_unique_params_p = true;
170 /* The maximum (approximate) depth of block nesting that an individual
171 routine or subroutine should have. This limit is about keeping the
172 output readable rather than reducing compile time. */
173 static const unsigned int MAX_DEPTH = 6;
175 /* The minimum number of pseudo-statements that a state must have before
176 we split it out into a subroutine. */
177 static const unsigned int MIN_NUM_STATEMENTS = 5;
179 /* The number of pseudo-statements a state can have before we consider
180 splitting out substates into subroutines. This limit is about avoiding
181 compile-time problems with very big functions (and also about keeping
182 functions within --param optimization limits, etc.). */
183 static const unsigned int MAX_NUM_STATEMENTS = 200;
185 /* The minimum number of pseudo-statements that can be used in a pattern
186 routine. */
187 static const unsigned int MIN_COMBINE_COST = 4;
189 /* The maximum number of arguments that a pattern routine can have.
190 The idea is to prevent one pattern getting a ridiculous number of
191 arguments when it would be more beneficial to have a separate pattern
192 routine instead. */
193 static const unsigned int MAX_PATTERN_PARAMS = 5;
195 /* The maximum operand number plus one. */
196 int num_operands;
198 /* Ways of obtaining an rtx to be tested. */
199 enum position_type {
200 /* PATTERN (peep2_next_insn (ARG)). */
201 POS_PEEP2_INSN,
203 /* XEXP (BASE, ARG). */
204 POS_XEXP,
206 /* XVECEXP (BASE, 0, ARG). */
207 POS_XVECEXP0
210 /* The position of an rtx relative to X0. Each useful position is
211 represented by exactly one instance of this structure. */
212 struct position
214 /* The parent rtx. This is the root position for POS_PEEP2_INSNs. */
215 struct position *base;
217 /* A position with the same BASE and TYPE, but with the next value
218 of ARG. */
219 struct position *next;
221 /* A list of all POS_XEXP positions that use this one as their base,
222 chained by NEXT fields. The first entry represents XEXP (this, 0),
223 the second represents XEXP (this, 1), and so on. */
224 struct position *xexps;
226 /* A list of POS_XVECEXP0 positions that use this one as their base,
227 chained by NEXT fields. The first entry represents XVECEXP (this, 0, 0),
228 the second represents XVECEXP (this, 0, 1), and so on. */
229 struct position *xvecexp0s;
231 /* The type of position. */
232 enum position_type type;
234 /* The argument to TYPE (shown as ARG in the position_type comments). */
235 int arg;
237 /* The instruction to which the position belongs. */
238 unsigned int insn_id;
240 /* The depth of this position relative to the instruction pattern.
241 E.g. if the instruction pattern is a SET, the SET itself has a
242 depth of 0 while the SET_DEST and SET_SRC have depths of 1. */
243 unsigned int depth;
245 /* A unique identifier for this position. */
246 unsigned int id;
249 enum routine_type {
250 SUBPATTERN, RECOG, SPLIT, PEEPHOLE2
253 /* The root position (x0). */
254 static struct position root_pos;
256 /* The number of positions created. Also one higher than the maximum
257 position id. */
258 static unsigned int num_positions = 1;
260 /* A list of all POS_PEEP2_INSNs. The entry for insn 0 is the root position,
261 since we are given that instruction's pattern as x0. */
262 static struct position *peep2_insn_pos_list = &root_pos;
264 /* Return a position with the given BASE, TYPE and ARG. NEXT_PTR
265 points to where the unique object that represents the position
266 should be stored. Create the object if it doesn't already exist,
267 otherwise reuse the object that is already there. */
269 static struct position *
270 next_position (struct position **next_ptr, struct position *base,
271 enum position_type type, int arg)
273 struct position *pos;
275 pos = *next_ptr;
276 if (!pos)
278 pos = XCNEW (struct position);
279 pos->type = type;
280 pos->arg = arg;
281 if (type == POS_PEEP2_INSN)
283 pos->base = 0;
284 pos->insn_id = arg;
285 pos->depth = base->depth;
287 else
289 pos->base = base;
290 pos->insn_id = base->insn_id;
291 pos->depth = base->depth + 1;
293 pos->id = num_positions++;
294 *next_ptr = pos;
296 return pos;
299 /* Compare positions POS1 and POS2 lexicographically. */
301 static int
302 compare_positions (struct position *pos1, struct position *pos2)
304 int diff;
306 diff = pos1->depth - pos2->depth;
307 if (diff < 0)
309 pos2 = pos2->base;
310 while (pos1->depth != pos2->depth);
311 else if (diff > 0)
313 pos1 = pos1->base;
314 while (pos1->depth != pos2->depth);
315 while (pos1 != pos2)
317 diff = (int) pos1->type - (int) pos2->type;
318 if (diff == 0)
319 diff = pos1->arg - pos2->arg;
320 pos1 = pos1->base;
321 pos2 = pos2->base;
323 return diff;
326 /* Return the most deeply-nested position that is common to both
327 POS1 and POS2. If the positions are from different instructions,
328 return the one with the lowest insn_id. */
330 static struct position *
331 common_position (struct position *pos1, struct position *pos2)
333 if (pos1->insn_id != pos2->insn_id)
334 return pos1->insn_id < pos2->insn_id ? pos1 : pos2;
335 if (pos1->depth > pos2->depth)
336 std::swap (pos1, pos2);
337 while (pos1->depth != pos2->depth)
338 pos2 = pos2->base;
339 while (pos1 != pos2)
341 pos1 = pos1->base;
342 pos2 = pos2->base;
344 return pos1;
347 /* Search for and return operand N, stop when reaching node STOP. */
349 static rtx
350 find_operand (rtx pattern, int n, rtx stop)
352 const char *fmt;
353 RTX_CODE code;
354 int i, j, len;
355 rtx r;
357 if (pattern == stop)
358 return stop;
360 code = GET_CODE (pattern);
361 if ((code == MATCH_SCRATCH
362 || code == MATCH_OPERAND
363 || code == MATCH_OPERATOR
364 || code == MATCH_PARALLEL)
365 && XINT (pattern, 0) == n)
366 return pattern;
368 fmt = GET_RTX_FORMAT (code);
369 len = GET_RTX_LENGTH (code);
370 for (i = 0; i < len; i++)
372 switch (fmt[i])
374 case 'e': case 'u':
375 if ((r = find_operand (XEXP (pattern, i), n, stop)) != NULL_RTX)
376 return r;
377 break;
379 case 'V':
380 if (! XVEC (pattern, i))
381 break;
382 /* Fall through. */
384 case 'E':
385 for (j = 0; j < XVECLEN (pattern, i); j++)
386 if ((r = find_operand (XVECEXP (pattern, i, j), n, stop))
387 != NULL_RTX)
388 return r;
389 break;
391 case 'i': case 'r': case 'w': case '0': case 's':
392 break;
394 default:
395 gcc_unreachable ();
399 return NULL;
402 /* Search for and return operand M, such that it has a matching
403 constraint for operand N. */
405 static rtx
406 find_matching_operand (rtx pattern, int n)
408 const char *fmt;
409 RTX_CODE code;
410 int i, j, len;
411 rtx r;
413 code = GET_CODE (pattern);
414 if (code == MATCH_OPERAND
415 && (XSTR (pattern, 2)[0] == '0' + n
416 || (XSTR (pattern, 2)[0] == '%'
417 && XSTR (pattern, 2)[1] == '0' + n)))
418 return pattern;
420 fmt = GET_RTX_FORMAT (code);
421 len = GET_RTX_LENGTH (code);
422 for (i = 0; i < len; i++)
424 switch (fmt[i])
426 case 'e': case 'u':
427 if ((r = find_matching_operand (XEXP (pattern, i), n)))
428 return r;
429 break;
431 case 'V':
432 if (! XVEC (pattern, i))
433 break;
434 /* Fall through. */
436 case 'E':
437 for (j = 0; j < XVECLEN (pattern, i); j++)
438 if ((r = find_matching_operand (XVECEXP (pattern, i, j), n)))
439 return r;
440 break;
442 case 'i': case 'r': case 'w': case '0': case 's':
443 break;
445 default:
446 gcc_unreachable ();
450 return NULL;
453 /* In DEFINE_EXPAND, DEFINE_SPLIT, and DEFINE_PEEPHOLE2, we
454 don't use the MATCH_OPERAND constraint, only the predicate.
455 This is confusing to folks doing new ports, so help them
456 not make the mistake. */
458 static bool
459 constraints_supported_in_insn_p (rtx insn)
461 return !(GET_CODE (insn) == DEFINE_EXPAND
462 || GET_CODE (insn) == DEFINE_SPLIT
463 || GET_CODE (insn) == DEFINE_PEEPHOLE2);
466 /* Check for various errors in PATTERN, which is part of INFO.
467 SET is nonnull for a destination, and is the complete set pattern.
468 SET_CODE is '=' for normal sets, and '+' within a context that
469 requires in-out constraints. */
471 static void
472 validate_pattern (rtx pattern, md_rtx_info *info, rtx set, int set_code)
474 const char *fmt;
475 RTX_CODE code;
476 size_t i, len;
477 int j;
479 code = GET_CODE (pattern);
480 switch (code)
482 case MATCH_SCRATCH:
484 const char constraints0 = XSTR (pattern, 1)[0];
486 if (!constraints_supported_in_insn_p (info->def))
488 if (constraints0)
490 error_at (info->loc, "constraints not supported in %s",
491 GET_RTX_NAME (GET_CODE (info->def)));
493 return;
496 /* If a MATCH_SCRATCH is used in a context requiring an write-only
497 or read/write register, validate that. */
498 if (set_code == '='
499 && constraints0
500 && constraints0 != '='
501 && constraints0 != '+')
503 error_at (info->loc, "operand %d missing output reload",
504 XINT (pattern, 0));
506 return;
508 case MATCH_DUP:
509 case MATCH_OP_DUP:
510 case MATCH_PAR_DUP:
511 if (find_operand (info->def, XINT (pattern, 0), pattern) == pattern)
512 error_at (info->loc, "operand %i duplicated before defined",
513 XINT (pattern, 0));
514 break;
515 case MATCH_OPERAND:
516 case MATCH_OPERATOR:
518 const char *pred_name = XSTR (pattern, 1);
519 const struct pred_data *pred;
520 const char *c_test;
522 c_test = get_c_test (info->def);
524 if (pred_name[0] != 0)
526 pred = lookup_predicate (pred_name);
527 if (!pred)
528 error_at (info->loc, "unknown predicate '%s'", pred_name);
530 else
531 pred = 0;
533 if (code == MATCH_OPERAND)
535 const char *constraints = XSTR (pattern, 2);
536 const char constraints0 = constraints[0];
538 if (!constraints_supported_in_insn_p (info->def))
540 if (constraints0)
542 error_at (info->loc, "constraints not supported in %s",
543 GET_RTX_NAME (GET_CODE (info->def)));
547 /* A MATCH_OPERAND that is a SET should have an output reload. */
548 else if (set && constraints0)
550 if (set_code == '+')
552 if (constraints0 == '+')
554 /* If we've only got an output reload for this operand,
555 we'd better have a matching input operand. */
556 else if (constraints0 == '='
557 && find_matching_operand (info->def,
558 XINT (pattern, 0)))
560 else
561 error_at (info->loc, "operand %d missing in-out reload",
562 XINT (pattern, 0));
564 else if (constraints0 != '=' && constraints0 != '+')
565 error_at (info->loc, "operand %d missing output reload",
566 XINT (pattern, 0));
569 /* For matching constraint in MATCH_OPERAND, the digit must be a
570 smaller number than the number of the operand that uses it in the
571 constraint. */
572 while (1)
574 while (constraints[0]
575 && (constraints[0] == ' ' || constraints[0] == ','))
576 constraints++;
577 if (!constraints[0])
578 break;
580 if (constraints[0] >= '0' && constraints[0] <= '9')
582 int val;
584 sscanf (constraints, "%d", &val);
585 if (val >= XINT (pattern, 0))
586 error_at (info->loc, "constraint digit %d is not"
587 " smaller than operand %d",
588 val, XINT (pattern, 0));
591 while (constraints[0] && constraints[0] != ',')
592 constraints++;
596 /* Allowing non-lvalues in destinations -- particularly CONST_INT --
597 while not likely to occur at runtime, results in less efficient
598 code from insn-recog.c. */
599 if (set && pred && pred->allows_non_lvalue)
600 error_at (info->loc, "destination operand %d allows non-lvalue",
601 XINT (pattern, 0));
603 /* A modeless MATCH_OPERAND can be handy when we can check for
604 multiple modes in the c_test. In most other cases, it is a
605 mistake. Only DEFINE_INSN is eligible, since SPLIT and
606 PEEP2 can FAIL within the output pattern. Exclude special
607 predicates, which check the mode themselves. Also exclude
608 predicates that allow only constants. Exclude the SET_DEST
609 of a call instruction, as that is a common idiom. */
611 if (GET_MODE (pattern) == VOIDmode
612 && code == MATCH_OPERAND
613 && GET_CODE (info->def) == DEFINE_INSN
614 && pred
615 && !pred->special
616 && pred->allows_non_const
617 && strstr (c_test, "operands") == NULL
618 && ! (set
619 && GET_CODE (set) == SET
620 && GET_CODE (SET_SRC (set)) == CALL))
621 message_at (info->loc, "warning: operand %d missing mode?",
622 XINT (pattern, 0));
623 return;
626 case SET:
628 machine_mode dmode, smode;
629 rtx dest, src;
631 dest = SET_DEST (pattern);
632 src = SET_SRC (pattern);
634 /* STRICT_LOW_PART is a wrapper. Its argument is the real
635 destination, and it's mode should match the source. */
636 if (GET_CODE (dest) == STRICT_LOW_PART)
637 dest = XEXP (dest, 0);
639 /* Find the referent for a DUP. */
641 if (GET_CODE (dest) == MATCH_DUP
642 || GET_CODE (dest) == MATCH_OP_DUP
643 || GET_CODE (dest) == MATCH_PAR_DUP)
644 dest = find_operand (info->def, XINT (dest, 0), NULL);
646 if (GET_CODE (src) == MATCH_DUP
647 || GET_CODE (src) == MATCH_OP_DUP
648 || GET_CODE (src) == MATCH_PAR_DUP)
649 src = find_operand (info->def, XINT (src, 0), NULL);
651 dmode = GET_MODE (dest);
652 smode = GET_MODE (src);
654 /* The mode of an ADDRESS_OPERAND is the mode of the memory
655 reference, not the mode of the address. */
656 if (GET_CODE (src) == MATCH_OPERAND
657 && ! strcmp (XSTR (src, 1), "address_operand"))
660 /* The operands of a SET must have the same mode unless one
661 is VOIDmode. */
662 else if (dmode != VOIDmode && smode != VOIDmode && dmode != smode)
663 error_at (info->loc, "mode mismatch in set: %smode vs %smode",
664 GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
666 /* If only one of the operands is VOIDmode, and PC or CC0 is
667 not involved, it's probably a mistake. */
668 else if (dmode != smode
669 && GET_CODE (dest) != PC
670 && GET_CODE (dest) != CC0
671 && GET_CODE (src) != PC
672 && GET_CODE (src) != CC0
673 && !CONST_INT_P (src)
674 && !CONST_WIDE_INT_P (src)
675 && GET_CODE (src) != CALL)
677 const char *which;
678 which = (dmode == VOIDmode ? "destination" : "source");
679 message_at (info->loc, "warning: %s missing a mode?", which);
682 if (dest != SET_DEST (pattern))
683 validate_pattern (dest, info, pattern, '=');
684 validate_pattern (SET_DEST (pattern), info, pattern, '=');
685 validate_pattern (SET_SRC (pattern), info, NULL_RTX, 0);
686 return;
689 case CLOBBER:
690 validate_pattern (SET_DEST (pattern), info, pattern, '=');
691 return;
693 case ZERO_EXTRACT:
694 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
695 validate_pattern (XEXP (pattern, 1), info, NULL_RTX, 0);
696 validate_pattern (XEXP (pattern, 2), info, NULL_RTX, 0);
697 return;
699 case STRICT_LOW_PART:
700 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
701 return;
703 case LABEL_REF:
704 if (GET_MODE (LABEL_REF_LABEL (pattern)) != VOIDmode)
705 error_at (info->loc, "operand to label_ref %smode not VOIDmode",
706 GET_MODE_NAME (GET_MODE (LABEL_REF_LABEL (pattern))));
707 break;
709 default:
710 break;
713 fmt = GET_RTX_FORMAT (code);
714 len = GET_RTX_LENGTH (code);
715 for (i = 0; i < len; i++)
717 switch (fmt[i])
719 case 'e': case 'u':
720 validate_pattern (XEXP (pattern, i), info, NULL_RTX, 0);
721 break;
723 case 'E':
724 for (j = 0; j < XVECLEN (pattern, i); j++)
725 validate_pattern (XVECEXP (pattern, i, j), info, NULL_RTX, 0);
726 break;
728 case 'i': case 'r': case 'w': case '0': case 's':
729 break;
731 default:
732 gcc_unreachable ();
737 /* Simple list structure for items of type T, for use when being part
738 of a list is an inherent property of T. T must have members equivalent
739 to "T *prev, *next;" and a function "void set_parent (list_head <T> *)"
740 to set the parent list. */
741 template <typename T>
742 struct list_head
744 /* A range of linked items. */
745 struct range
747 range (T *);
748 range (T *, T *);
750 T *start, *end;
751 void set_parent (list_head *);
754 list_head ();
755 range release ();
756 void push_back (range);
757 range remove (range);
758 void replace (range, range);
759 T *singleton () const;
761 T *first, *last;
764 /* Create a range [START_IN, START_IN]. */
766 template <typename T>
767 list_head <T>::range::range (T *start_in) : start (start_in), end (start_in) {}
769 /* Create a range [START_IN, END_IN], linked by next and prev fields. */
771 template <typename T>
772 list_head <T>::range::range (T *start_in, T *end_in)
773 : start (start_in), end (end_in) {}
775 template <typename T>
776 void
777 list_head <T>::range::set_parent (list_head <T> *owner)
779 for (T *item = start; item != end; item = item->next)
780 item->set_parent (owner);
781 end->set_parent (owner);
784 template <typename T>
785 list_head <T>::list_head () : first (0), last (0) {}
787 /* Add R to the end of the list. */
789 template <typename T>
790 void
791 list_head <T>::push_back (range r)
793 if (last)
794 last->next = r.start;
795 else
796 first = r.start;
797 r.start->prev = last;
798 last = r.end;
799 r.set_parent (this);
802 /* Remove R from the list. R remains valid and can be inserted into
803 other lists. */
805 template <typename T>
806 typename list_head <T>::range
807 list_head <T>::remove (range r)
809 if (r.start->prev)
810 r.start->prev->next = r.end->next;
811 else
812 first = r.end->next;
813 if (r.end->next)
814 r.end->next->prev = r.start->prev;
815 else
816 last = r.start->prev;
817 r.start->prev = 0;
818 r.end->next = 0;
819 r.set_parent (0);
820 return r;
823 /* Replace OLDR with NEWR. OLDR remains valid and can be inserted into
824 other lists. */
826 template <typename T>
827 void
828 list_head <T>::replace (range oldr, range newr)
830 newr.start->prev = oldr.start->prev;
831 newr.end->next = oldr.end->next;
833 oldr.start->prev = 0;
834 oldr.end->next = 0;
835 oldr.set_parent (0);
837 if (newr.start->prev)
838 newr.start->prev->next = newr.start;
839 else
840 first = newr.start;
841 if (newr.end->next)
842 newr.end->next->prev = newr.end;
843 else
844 last = newr.end;
845 newr.set_parent (this);
848 /* Empty the list and return the previous contents as a range that can
849 be inserted into other lists. */
851 template <typename T>
852 typename list_head <T>::range
853 list_head <T>::release ()
855 range r (first, last);
856 first = 0;
857 last = 0;
858 r.set_parent (0);
859 return r;
862 /* If the list contains a single item, return that item, otherwise return
863 null. */
865 template <typename T>
867 list_head <T>::singleton () const
869 return first == last ? first : 0;
872 struct state;
874 /* Describes a possible successful return from a routine. */
875 struct acceptance_type
877 /* The type of routine we're returning from. */
878 routine_type type : 16;
880 /* True if this structure only really represents a partial match,
881 and if we must call a subroutine of type TYPE to complete the match.
882 In this case we'll call the subroutine and, if it succeeds, return
883 whatever the subroutine returned.
885 False if this structure presents a full match. */
886 unsigned int partial_p : 1;
888 union
890 /* If PARTIAL_P, this is the number of the subroutine to call. */
891 int subroutine_id;
893 /* Valid if !PARTIAL_P. */
894 struct
896 /* The identifier of the matching pattern. For SUBPATTERNs this
897 value belongs to an ad-hoc routine-specific enum. For the
898 others it's the number of an .md file pattern. */
899 int code;
900 union
902 /* For RECOG, the number of clobbers that must be added to the
903 pattern in order for it to match CODE. */
904 int num_clobbers;
906 /* For PEEPHOLE2, the number of additional instructions that were
907 included in the optimization. */
908 int match_len;
909 } u;
910 } full;
911 } u;
914 bool
915 operator == (const acceptance_type &a, const acceptance_type &b)
917 if (a.partial_p != b.partial_p)
918 return false;
919 if (a.partial_p)
920 return a.u.subroutine_id == b.u.subroutine_id;
921 else
922 return a.u.full.code == b.u.full.code;
925 bool
926 operator != (const acceptance_type &a, const acceptance_type &b)
928 return !operator == (a, b);
931 /* Represents a parameter to a pattern routine. */
932 struct parameter
934 /* The C type of parameter. */
935 enum type_enum {
936 /* Represents an invalid parameter. */
937 UNSET,
939 /* A machine_mode parameter. */
940 MODE,
942 /* An rtx_code parameter. */
943 CODE,
945 /* An int parameter. */
946 INT,
948 /* An unsigned int parameter. */
949 UINT,
951 /* A HOST_WIDE_INT parameter. */
952 WIDE_INT
955 parameter ();
956 parameter (type_enum, bool, uint64_t);
958 /* The type of the parameter. */
959 type_enum type;
961 /* True if the value passed is variable, false if it is constant. */
962 bool is_param;
964 /* If IS_PARAM, this is the number of the variable passed, for an "i%d"
965 format string. If !IS_PARAM, this is the constant value passed. */
966 uint64_t value;
969 parameter::parameter ()
970 : type (UNSET), is_param (false), value (0) {}
972 parameter::parameter (type_enum type_in, bool is_param_in, uint64_t value_in)
973 : type (type_in), is_param (is_param_in), value (value_in) {}
975 bool
976 operator == (const parameter &param1, const parameter &param2)
978 return (param1.type == param2.type
979 && param1.is_param == param2.is_param
980 && param1.value == param2.value);
983 bool
984 operator != (const parameter &param1, const parameter &param2)
986 return !operator == (param1, param2);
989 /* Represents a routine that matches a partial rtx pattern, returning
990 an ad-hoc enum value on success and -1 on failure. The routine can
991 be used by any subroutine type. The match can be parameterized by
992 things like mode, code and UNSPEC number. */
993 struct pattern_routine
995 /* The state that implements the pattern. */
996 state *s;
998 /* The deepest root position from which S can access all the rtxes it needs.
999 This is NULL if the pattern doesn't need an rtx input, usually because
1000 all matching is done on operands[] instead. */
1001 position *pos;
1003 /* A unique identifier for the routine. */
1004 unsigned int pattern_id;
1006 /* True if the routine takes pnum_clobbers as argument. */
1007 bool pnum_clobbers_p;
1009 /* True if the routine takes the enclosing instruction as argument. */
1010 bool insn_p;
1012 /* The types of the other parameters to the routine, if any. */
1013 auto_vec <parameter::type_enum, MAX_PATTERN_PARAMS> param_types;
1016 /* All defined patterns. */
1017 static vec <pattern_routine *> patterns;
1019 /* Represents one use of a pattern routine. */
1020 struct pattern_use
1022 /* The pattern routine to use. */
1023 pattern_routine *routine;
1025 /* The values to pass as parameters. This vector has the same length
1026 as ROUTINE->PARAM_TYPES. */
1027 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
1030 /* Represents a test performed by a decision. */
1031 struct rtx_test
1033 rtx_test ();
1035 /* The types of test that can be performed. Most of them take as input
1036 an rtx X. Some also take as input a transition label LABEL; the others
1037 are booleans for which the transition label is always "true".
1039 The order of the enum isn't important. */
1040 enum kind_enum {
1041 /* Check GET_CODE (X) == LABEL. */
1042 CODE,
1044 /* Check GET_MODE (X) == LABEL. */
1045 MODE,
1047 /* Check REGNO (X) == LABEL. */
1048 REGNO_FIELD,
1050 /* Check XINT (X, u.opno) == LABEL. */
1051 INT_FIELD,
1053 /* Check XWINT (X, u.opno) == LABEL. */
1054 WIDE_INT_FIELD,
1056 /* Check XVECLEN (X, 0) == LABEL. */
1057 VECLEN,
1059 /* Check peep2_current_count >= u.min_len. */
1060 PEEP2_COUNT,
1062 /* Check XVECLEN (X, 0) >= u.min_len. */
1063 VECLEN_GE,
1065 /* Check whether X is a cached const_int with value u.integer. */
1066 SAVED_CONST_INT,
1068 /* Check u.predicate.data (X, u.predicate.mode). */
1069 PREDICATE,
1071 /* Check rtx_equal_p (X, operands[u.opno]). */
1072 DUPLICATE,
1074 /* Check whether X matches pattern u.pattern. */
1075 PATTERN,
1077 /* Check whether pnum_clobbers is nonnull (RECOG only). */
1078 HAVE_NUM_CLOBBERS,
1080 /* Check whether general C test u.string holds. In general the condition
1081 needs access to "insn" and the full operand list. */
1082 C_TEST,
1084 /* Execute operands[u.opno] = X. (Always succeeds.) */
1085 SET_OP,
1087 /* Accept u.acceptance. Always succeeds for SUBPATTERN, RECOG and SPLIT.
1088 May fail for PEEPHOLE2 if the define_peephole2 C code executes FAIL. */
1089 ACCEPT
1092 /* The position of rtx X in the above description, relative to the
1093 incoming instruction "insn". The position is null if the test
1094 doesn't take an X as input. */
1095 position *pos;
1097 /* Which element of operands[] already contains POS, or -1 if no element
1098 is known to hold POS. */
1099 int pos_operand;
1101 /* The type of test and its parameters, as described above. */
1102 kind_enum kind;
1103 union
1105 int opno;
1106 int min_len;
1107 struct
1109 bool is_param;
1110 int value;
1111 } integer;
1112 struct
1114 const struct pred_data *data;
1115 /* True if the mode is taken from a machine_mode parameter
1116 to the routine rather than a constant machine_mode. If true,
1117 MODE is the number of the parameter (for an "i%d" format string),
1118 otherwise it is the mode itself. */
1119 bool mode_is_param;
1120 unsigned int mode;
1121 } predicate;
1122 pattern_use *pattern;
1123 const char *string;
1124 acceptance_type acceptance;
1125 } u;
1127 static rtx_test code (position *);
1128 static rtx_test mode (position *);
1129 static rtx_test regno_field (position *);
1130 static rtx_test int_field (position *, int);
1131 static rtx_test wide_int_field (position *, int);
1132 static rtx_test veclen (position *);
1133 static rtx_test peep2_count (int);
1134 static rtx_test veclen_ge (position *, int);
1135 static rtx_test predicate (position *, const pred_data *, machine_mode);
1136 static rtx_test duplicate (position *, int);
1137 static rtx_test pattern (position *, pattern_use *);
1138 static rtx_test have_num_clobbers ();
1139 static rtx_test c_test (const char *);
1140 static rtx_test set_op (position *, int);
1141 static rtx_test accept (const acceptance_type &);
1143 bool terminal_p () const;
1144 bool single_outcome_p () const;
1146 private:
1147 rtx_test (position *, kind_enum);
1150 rtx_test::rtx_test () {}
1152 rtx_test::rtx_test (position *pos_in, kind_enum kind_in)
1153 : pos (pos_in), pos_operand (-1), kind (kind_in) {}
1155 rtx_test
1156 rtx_test::code (position *pos)
1158 return rtx_test (pos, rtx_test::CODE);
1161 rtx_test
1162 rtx_test::mode (position *pos)
1164 return rtx_test (pos, rtx_test::MODE);
1167 rtx_test
1168 rtx_test::regno_field (position *pos)
1170 rtx_test res (pos, rtx_test::REGNO_FIELD);
1171 return res;
1174 rtx_test
1175 rtx_test::int_field (position *pos, int opno)
1177 rtx_test res (pos, rtx_test::INT_FIELD);
1178 res.u.opno = opno;
1179 return res;
1182 rtx_test
1183 rtx_test::wide_int_field (position *pos, int opno)
1185 rtx_test res (pos, rtx_test::WIDE_INT_FIELD);
1186 res.u.opno = opno;
1187 return res;
1190 rtx_test
1191 rtx_test::veclen (position *pos)
1193 return rtx_test (pos, rtx_test::VECLEN);
1196 rtx_test
1197 rtx_test::peep2_count (int min_len)
1199 rtx_test res (0, rtx_test::PEEP2_COUNT);
1200 res.u.min_len = min_len;
1201 return res;
1204 rtx_test
1205 rtx_test::veclen_ge (position *pos, int min_len)
1207 rtx_test res (pos, rtx_test::VECLEN_GE);
1208 res.u.min_len = min_len;
1209 return res;
1212 rtx_test
1213 rtx_test::predicate (position *pos, const struct pred_data *data,
1214 machine_mode mode)
1216 rtx_test res (pos, rtx_test::PREDICATE);
1217 res.u.predicate.data = data;
1218 res.u.predicate.mode_is_param = false;
1219 res.u.predicate.mode = mode;
1220 return res;
1223 rtx_test
1224 rtx_test::duplicate (position *pos, int opno)
1226 rtx_test res (pos, rtx_test::DUPLICATE);
1227 res.u.opno = opno;
1228 return res;
1231 rtx_test
1232 rtx_test::pattern (position *pos, pattern_use *pattern)
1234 rtx_test res (pos, rtx_test::PATTERN);
1235 res.u.pattern = pattern;
1236 return res;
1239 rtx_test
1240 rtx_test::have_num_clobbers ()
1242 return rtx_test (0, rtx_test::HAVE_NUM_CLOBBERS);
1245 rtx_test
1246 rtx_test::c_test (const char *string)
1248 rtx_test res (0, rtx_test::C_TEST);
1249 res.u.string = string;
1250 return res;
1253 rtx_test
1254 rtx_test::set_op (position *pos, int opno)
1256 rtx_test res (pos, rtx_test::SET_OP);
1257 res.u.opno = opno;
1258 return res;
1261 rtx_test
1262 rtx_test::accept (const acceptance_type &acceptance)
1264 rtx_test res (0, rtx_test::ACCEPT);
1265 res.u.acceptance = acceptance;
1266 return res;
1269 /* Return true if the test represents an unconditionally successful match. */
1271 bool
1272 rtx_test::terminal_p () const
1274 return kind == rtx_test::ACCEPT && u.acceptance.type != PEEPHOLE2;
1277 /* Return true if the test is a boolean that is always true. */
1279 bool
1280 rtx_test::single_outcome_p () const
1282 return terminal_p () || kind == rtx_test::SET_OP;
1285 bool
1286 operator == (const rtx_test &a, const rtx_test &b)
1288 if (a.pos != b.pos || a.kind != b.kind)
1289 return false;
1290 switch (a.kind)
1292 case rtx_test::CODE:
1293 case rtx_test::MODE:
1294 case rtx_test::REGNO_FIELD:
1295 case rtx_test::VECLEN:
1296 case rtx_test::HAVE_NUM_CLOBBERS:
1297 return true;
1299 case rtx_test::PEEP2_COUNT:
1300 case rtx_test::VECLEN_GE:
1301 return a.u.min_len == b.u.min_len;
1303 case rtx_test::INT_FIELD:
1304 case rtx_test::WIDE_INT_FIELD:
1305 case rtx_test::DUPLICATE:
1306 case rtx_test::SET_OP:
1307 return a.u.opno == b.u.opno;
1309 case rtx_test::SAVED_CONST_INT:
1310 return (a.u.integer.is_param == b.u.integer.is_param
1311 && a.u.integer.value == b.u.integer.value);
1313 case rtx_test::PREDICATE:
1314 return (a.u.predicate.data == b.u.predicate.data
1315 && a.u.predicate.mode_is_param == b.u.predicate.mode_is_param
1316 && a.u.predicate.mode == b.u.predicate.mode);
1318 case rtx_test::PATTERN:
1319 return (a.u.pattern->routine == b.u.pattern->routine
1320 && a.u.pattern->params == b.u.pattern->params);
1322 case rtx_test::C_TEST:
1323 return strcmp (a.u.string, b.u.string) == 0;
1325 case rtx_test::ACCEPT:
1326 return a.u.acceptance == b.u.acceptance;
1328 gcc_unreachable ();
1331 bool
1332 operator != (const rtx_test &a, const rtx_test &b)
1334 return !operator == (a, b);
1337 /* A simple set of transition labels. Most transitions have a singleton
1338 label, so try to make that case as efficient as possible. */
1339 struct int_set : public auto_vec <uint64_t, 1>
1341 typedef uint64_t *iterator;
1343 int_set ();
1344 int_set (uint64_t);
1345 int_set (const int_set &);
1347 int_set &operator = (const int_set &);
1349 iterator begin ();
1350 iterator end ();
1353 int_set::int_set () {}
1355 int_set::int_set (uint64_t label)
1357 safe_push (label);
1360 int_set::int_set (const int_set &other)
1362 safe_splice (other);
1365 int_set &
1366 int_set::operator = (const int_set &other)
1368 truncate (0);
1369 safe_splice (other);
1370 return *this;
1373 int_set::iterator
1374 int_set::begin ()
1376 return address ();
1379 int_set::iterator
1380 int_set::end ()
1382 return address () + length ();
1385 bool
1386 operator == (const int_set &a, const int_set &b)
1388 if (a.length () != b.length ())
1389 return false;
1390 for (unsigned int i = 0; i < a.length (); ++i)
1391 if (a[i] != b[i])
1392 return false;
1393 return true;
1396 bool
1397 operator != (const int_set &a, const int_set &b)
1399 return !operator == (a, b);
1402 struct decision;
1404 /* Represents a transition between states, dependent on the result of
1405 a test T. */
1406 struct transition
1408 transition (const int_set &, state *, bool);
1410 void set_parent (list_head <transition> *);
1412 /* Links to other transitions for T. Always null for boolean tests. */
1413 transition *prev, *next;
1415 /* The transition should be taken when T has one of these values.
1416 E.g. for rtx_test::CODE this is a set of codes, while for booleans like
1417 rtx_test::PREDICATE it is always a singleton "true". The labels are
1418 sorted in ascending order. */
1419 int_set labels;
1421 /* The source decision. */
1422 decision *from;
1424 /* The target state. */
1425 state *to;
1427 /* True if TO would function correctly even if TEST wasn't performed.
1428 E.g. it isn't necessary to check whether GET_MODE (x1) is SImode
1429 before calling register_operand (x1, SImode), since register_operand
1430 performs its own mode check. However, checking GET_MODE can be a cheap
1431 way of disambiguating SImode and DImode register operands. */
1432 bool optional;
1434 /* True if LABELS contains parameter numbers rather than constants.
1435 E.g. if this is true for a rtx_test::CODE, the label is the number
1436 of an rtx_code parameter rather than an rtx_code itself.
1437 LABELS is always a singleton when this variable is true. */
1438 bool is_param;
1441 /* Represents a test and the action that should be taken on the result.
1442 If a transition exists for the test outcome, the machine switches
1443 to the transition's target state. If no suitable transition exists,
1444 the machine either falls through to the next decision or, if there are no
1445 more decisions to try, fails the match. */
1446 struct decision : list_head <transition>
1448 decision (const rtx_test &);
1450 void set_parent (list_head <decision> *s);
1451 bool if_statement_p (uint64_t * = 0) const;
1453 /* The state to which this decision belongs. */
1454 state *s;
1456 /* Links to other decisions in the same state. */
1457 decision *prev, *next;
1459 /* The test to perform. */
1460 rtx_test test;
1463 /* Represents one machine state. For each state the machine tries a list
1464 of decisions, in order, and acts on the first match. It fails without
1465 further backtracking if no decisions match. */
1466 struct state : list_head <decision>
1468 void set_parent (list_head <state> *) {}
1471 transition::transition (const int_set &labels_in, state *to_in,
1472 bool optional_in)
1473 : prev (0), next (0), labels (labels_in), from (0), to (to_in),
1474 optional (optional_in), is_param (false) {}
1476 /* Set the source decision of the transition. */
1478 void
1479 transition::set_parent (list_head <transition> *from_in)
1481 from = static_cast <decision *> (from_in);
1484 decision::decision (const rtx_test &test_in)
1485 : prev (0), next (0), test (test_in) {}
1487 /* Set the state to which this decision belongs. */
1489 void
1490 decision::set_parent (list_head <decision> *s_in)
1492 s = static_cast <state *> (s_in);
1495 /* Return true if the decision has a single transition with a single label.
1496 If so, return the label in *LABEL if nonnull. */
1498 inline bool
1499 decision::if_statement_p (uint64_t *label) const
1501 if (singleton () && first->labels.length () == 1)
1503 if (label)
1504 *label = first->labels[0];
1505 return true;
1507 return false;
1510 /* Add to FROM a decision that performs TEST and has a single transition
1511 TRANS. */
1513 static void
1514 add_decision (state *from, const rtx_test &test, transition *trans)
1516 decision *d = new decision (test);
1517 from->push_back (d);
1518 d->push_back (trans);
1521 /* Add a transition from FROM to a new, empty state that is taken
1522 when TEST == LABELS. OPTIONAL says whether the new transition
1523 should be optional. Return the new state. */
1525 static state *
1526 add_decision (state *from, const rtx_test &test, int_set labels, bool optional)
1528 state *to = new state;
1529 add_decision (from, test, new transition (labels, to, optional));
1530 return to;
1533 /* Insert a decision before decisions R to make them dependent on
1534 TEST == LABELS. OPTIONAL says whether the new transition should be
1535 optional. */
1537 static decision *
1538 insert_decision_before (state::range r, const rtx_test &test,
1539 const int_set &labels, bool optional)
1541 decision *newd = new decision (test);
1542 state *news = new state;
1543 newd->push_back (new transition (labels, news, optional));
1544 r.start->s->replace (r, newd);
1545 news->push_back (r);
1546 return newd;
1549 /* Remove any optional transitions from S that turned out not to be useful. */
1551 static void
1552 collapse_optional_decisions (state *s)
1554 decision *d = s->first;
1555 while (d)
1557 decision *next = d->next;
1558 for (transition *trans = d->first; trans; trans = trans->next)
1559 collapse_optional_decisions (trans->to);
1560 /* A decision with a single optional transition doesn't help
1561 partition the potential matches and so is unlikely to be
1562 worthwhile. In particular, if the decision that performs the
1563 test is the last in the state, the best it could do is reject
1564 an invalid pattern slightly earlier. If instead the decision
1565 is not the last in the state, the condition it tests could hold
1566 even for the later decisions in the state. The best it can do
1567 is save work in some cases where only the later decisions can
1568 succeed.
1570 In both cases the optional transition would add extra work to
1571 successful matches when the tested condition holds. */
1572 if (transition *trans = d->singleton ())
1573 if (trans->optional)
1574 s->replace (d, trans->to->release ());
1575 d = next;
1579 /* Try to squash several separate tests into simpler ones. */
1581 static void
1582 simplify_tests (state *s)
1584 for (decision *d = s->first; d; d = d->next)
1586 uint64_t label;
1587 /* Convert checks for GET_CODE (x) == CONST_INT and XWINT (x, 0) == N
1588 into checks for const_int_rtx[N'], if N is suitably small. */
1589 if (d->test.kind == rtx_test::CODE
1590 && d->if_statement_p (&label)
1591 && label == CONST_INT)
1592 if (decision *second = d->first->to->singleton ())
1593 if (d->test.pos == second->test.pos
1594 && second->test.kind == rtx_test::WIDE_INT_FIELD
1595 && second->test.u.opno == 0
1596 && second->if_statement_p (&label)
1597 && IN_RANGE (int64_t (label),
1598 -MAX_SAVED_CONST_INT, MAX_SAVED_CONST_INT))
1600 d->test.kind = rtx_test::SAVED_CONST_INT;
1601 d->test.u.integer.is_param = false;
1602 d->test.u.integer.value = label;
1603 d->replace (d->first, second->release ());
1604 d->first->labels[0] = true;
1606 /* If we have a CODE test followed by a PREDICATE test, rely on
1607 the predicate to test the code.
1609 This case exists for match_operators. We initially treat the
1610 CODE test for a match_operator as non-optional so that we can
1611 safely move down to its operands. It may turn out that all
1612 paths that reach that code test require the same predicate
1613 to be true. cse_tests will then put the predicate test in
1614 series with the code test. */
1615 if (d->test.kind == rtx_test::CODE)
1616 if (transition *trans = d->singleton ())
1618 state *s = trans->to;
1619 while (decision *d2 = s->singleton ())
1621 if (d->test.pos != d2->test.pos)
1622 break;
1623 transition *trans2 = d2->singleton ();
1624 if (!trans2)
1625 break;
1626 if (d2->test.kind == rtx_test::PREDICATE)
1628 d->test = d2->test;
1629 trans->labels = int_set (true);
1630 s->replace (d2, trans2->to->release ());
1631 break;
1633 s = trans2->to;
1636 for (transition *trans = d->first; trans; trans = trans->next)
1637 simplify_tests (trans->to);
1641 /* Return true if all successful returns passing through D require the
1642 condition tested by COMMON to be true.
1644 When returning true, add all transitions like COMMON in D to WHERE.
1645 WHERE may contain a partial result on failure. */
1647 static bool
1648 common_test_p (decision *d, transition *common, vec <transition *> *where)
1650 if (d->test.kind == rtx_test::ACCEPT)
1651 /* We found a successful return that didn't require COMMON. */
1652 return false;
1653 if (d->test == common->from->test)
1655 transition *trans = d->singleton ();
1656 if (!trans
1657 || trans->optional != common->optional
1658 || trans->labels != common->labels)
1659 return false;
1660 where->safe_push (trans);
1661 return true;
1663 for (transition *trans = d->first; trans; trans = trans->next)
1664 for (decision *subd = trans->to->first; subd; subd = subd->next)
1665 if (!common_test_p (subd, common, where))
1666 return false;
1667 return true;
1670 /* Indicates that we have tested GET_CODE (X) for a particular rtx X. */
1671 const unsigned char TESTED_CODE = 1;
1673 /* Indicates that we have tested XVECLEN (X, 0) for a particular rtx X. */
1674 const unsigned char TESTED_VECLEN = 2;
1676 /* Represents a set of conditions that are known to hold. */
1677 struct known_conditions
1679 /* A mask of TESTED_ values for each position, indexed by the position's
1680 id field. */
1681 auto_vec <unsigned char> position_tests;
1683 /* Index N says whether operands[N] has been set. */
1684 auto_vec <bool> set_operands;
1686 /* A guranteed lower bound on the value of peep2_current_count. */
1687 int peep2_count;
1690 /* Return true if TEST can safely be performed at D, where
1691 the conditions in KC hold. TEST is known to occur along the
1692 first path from D (i.e. always following the first transition
1693 of the first decision). Any intervening tests can be used as
1694 negative proof that hoisting isn't safe, but only KC can be used
1695 as positive proof. */
1697 static bool
1698 safe_to_hoist_p (decision *d, const rtx_test &test, known_conditions *kc)
1700 switch (test.kind)
1702 case rtx_test::C_TEST:
1703 /* In general, C tests require everything else to have been
1704 verified and all operands to have been set up. */
1705 return false;
1707 case rtx_test::ACCEPT:
1708 /* Don't accept something before all conditions have been tested. */
1709 return false;
1711 case rtx_test::PREDICATE:
1712 /* Don't move a predicate over a test for VECLEN_GE, since the
1713 predicate used in a match_parallel can legitimately expect the
1714 length to be checked first. */
1715 for (decision *subd = d;
1716 subd->test != test;
1717 subd = subd->first->to->first)
1718 if (subd->test.pos == test.pos
1719 && subd->test.kind == rtx_test::VECLEN_GE)
1720 return false;
1721 goto any_rtx;
1723 case rtx_test::DUPLICATE:
1724 /* Don't test for a match_dup until the associated operand has
1725 been set. */
1726 if (!kc->set_operands[test.u.opno])
1727 return false;
1728 goto any_rtx;
1730 case rtx_test::CODE:
1731 case rtx_test::MODE:
1732 case rtx_test::SAVED_CONST_INT:
1733 case rtx_test::SET_OP:
1734 any_rtx:
1735 /* Check whether it is safe to access the rtx under test. */
1736 switch (test.pos->type)
1738 case POS_PEEP2_INSN:
1739 return test.pos->arg < kc->peep2_count;
1741 case POS_XEXP:
1742 return kc->position_tests[test.pos->base->id] & TESTED_CODE;
1744 case POS_XVECEXP0:
1745 return kc->position_tests[test.pos->base->id] & TESTED_VECLEN;
1747 gcc_unreachable ();
1749 case rtx_test::REGNO_FIELD:
1750 case rtx_test::INT_FIELD:
1751 case rtx_test::WIDE_INT_FIELD:
1752 case rtx_test::VECLEN:
1753 case rtx_test::VECLEN_GE:
1754 /* These tests access a specific part of an rtx, so are only safe
1755 once we know what the rtx is. */
1756 return kc->position_tests[test.pos->id] & TESTED_CODE;
1758 case rtx_test::PEEP2_COUNT:
1759 case rtx_test::HAVE_NUM_CLOBBERS:
1760 /* These tests can be performed anywhere. */
1761 return true;
1763 case rtx_test::PATTERN:
1764 gcc_unreachable ();
1766 gcc_unreachable ();
1769 /* Look for a transition that is taken by all successful returns from a range
1770 of decisions starting at OUTER and that would be better performed by
1771 OUTER's state instead. On success, store all instances of that transition
1772 in WHERE and return the last decision in the range. The range could
1773 just be OUTER, or it could include later decisions as well.
1775 WITH_POSITION_P is true if only tests with position POS should be tried,
1776 false if any test should be tried. WORTHWHILE_SINGLE_P is true if the
1777 result is useful even when the range contains just a single decision
1778 with a single transition. KC are the conditions that are known to
1779 hold at OUTER. */
1781 static decision *
1782 find_common_test (decision *outer, bool with_position_p,
1783 position *pos, bool worthwhile_single_p,
1784 known_conditions *kc, vec <transition *> *where)
1786 /* After this, WORTHWHILE_SINGLE_P indicates whether a range that contains
1787 just a single decision is useful, regardless of the number of
1788 transitions it has. */
1789 if (!outer->singleton ())
1790 worthwhile_single_p = true;
1791 /* Quick exit if we don't have enough decisions to form a worthwhile
1792 range. */
1793 if (!worthwhile_single_p && !outer->next)
1794 return 0;
1795 /* Follow the first chain down, as one example of a path that needs
1796 to contain the common test. */
1797 for (decision *d = outer; d; d = d->first->to->first)
1799 transition *trans = d->singleton ();
1800 if (trans
1801 && (!with_position_p || d->test.pos == pos)
1802 && safe_to_hoist_p (outer, d->test, kc))
1804 if (common_test_p (outer, trans, where))
1806 if (!outer->next)
1807 /* We checked above whether the move is worthwhile. */
1808 return outer;
1809 /* See how many decisions in OUTER's chain could reuse
1810 the same test. */
1811 decision *outer_end = outer;
1814 unsigned int length = where->length ();
1815 if (!common_test_p (outer_end->next, trans, where))
1817 where->truncate (length);
1818 break;
1820 outer_end = outer_end->next;
1822 while (outer_end->next);
1823 /* It is worth moving TRANS if it can be shared by more than
1824 one decision. */
1825 if (outer_end != outer || worthwhile_single_p)
1826 return outer_end;
1828 where->truncate (0);
1831 return 0;
1834 /* Try to promote common subtests in S to a single, shared decision.
1835 Also try to bunch tests for the same position together. POS is the
1836 position of the rtx tested before reaching S. KC are the conditions
1837 that are known to hold on entry to S. */
1839 static void
1840 cse_tests (position *pos, state *s, known_conditions *kc)
1842 for (decision *d = s->first; d; d = d->next)
1844 auto_vec <transition *, 16> where;
1845 if (d->test.pos)
1847 /* Try to find conditions that don't depend on a particular rtx,
1848 such as pnum_clobbers != NULL or peep2_current_count >= X.
1849 It's usually better to check these conditions as soon as
1850 possible, so the change is worthwhile even if there is
1851 only one copy of the test. */
1852 decision *endd = find_common_test (d, true, 0, true, kc, &where);
1853 if (!endd && d->test.pos != pos)
1854 /* Try to find other conditions related to position POS
1855 before moving to the new position. Again, this is
1856 worthwhile even if there is only one copy of the test,
1857 since it means that fewer position variables are live
1858 at a given time. */
1859 endd = find_common_test (d, true, pos, true, kc, &where);
1860 if (!endd)
1861 /* Try to find any condition that is used more than once. */
1862 endd = find_common_test (d, false, 0, false, kc, &where);
1863 if (endd)
1865 transition *common = where[0];
1866 /* Replace [D, ENDD] with a test like COMMON. We'll recurse
1867 on the common test and see the original D again next time. */
1868 d = insert_decision_before (state::range (d, endd),
1869 common->from->test,
1870 common->labels,
1871 common->optional);
1872 /* Remove the old tests. */
1873 while (!where.is_empty ())
1875 transition *trans = where.pop ();
1876 trans->from->s->replace (trans->from, trans->to->release ());
1881 /* Make sure that safe_to_hoist_p isn't being overly conservative.
1882 It should realize that D's test is safe in the current
1883 environment. */
1884 gcc_assert (d->test.kind == rtx_test::C_TEST
1885 || d->test.kind == rtx_test::ACCEPT
1886 || safe_to_hoist_p (d, d->test, kc));
1888 /* D won't be changed any further by the current optimization.
1889 Recurse with the state temporarily updated to include D. */
1890 int prev = 0;
1891 switch (d->test.kind)
1893 case rtx_test::CODE:
1894 prev = kc->position_tests[d->test.pos->id];
1895 kc->position_tests[d->test.pos->id] |= TESTED_CODE;
1896 break;
1898 case rtx_test::VECLEN:
1899 case rtx_test::VECLEN_GE:
1900 prev = kc->position_tests[d->test.pos->id];
1901 kc->position_tests[d->test.pos->id] |= TESTED_VECLEN;
1902 break;
1904 case rtx_test::SET_OP:
1905 prev = kc->set_operands[d->test.u.opno];
1906 gcc_assert (!prev);
1907 kc->set_operands[d->test.u.opno] = true;
1908 break;
1910 case rtx_test::PEEP2_COUNT:
1911 prev = kc->peep2_count;
1912 kc->peep2_count = MAX (prev, d->test.u.min_len);
1913 break;
1915 default:
1916 break;
1918 for (transition *trans = d->first; trans; trans = trans->next)
1919 cse_tests (d->test.pos ? d->test.pos : pos, trans->to, kc);
1920 switch (d->test.kind)
1922 case rtx_test::CODE:
1923 case rtx_test::VECLEN:
1924 case rtx_test::VECLEN_GE:
1925 kc->position_tests[d->test.pos->id] = prev;
1926 break;
1928 case rtx_test::SET_OP:
1929 kc->set_operands[d->test.u.opno] = prev;
1930 break;
1932 case rtx_test::PEEP2_COUNT:
1933 kc->peep2_count = prev;
1934 break;
1936 default:
1937 break;
1942 /* Return the type of value that can be used to parameterize test KIND,
1943 or parameter::UNSET if none. */
1945 parameter::type_enum
1946 transition_parameter_type (rtx_test::kind_enum kind)
1948 switch (kind)
1950 case rtx_test::CODE:
1951 return parameter::CODE;
1953 case rtx_test::MODE:
1954 return parameter::MODE;
1956 case rtx_test::REGNO_FIELD:
1957 return parameter::UINT;
1959 case rtx_test::INT_FIELD:
1960 case rtx_test::VECLEN:
1961 case rtx_test::PATTERN:
1962 return parameter::INT;
1964 case rtx_test::WIDE_INT_FIELD:
1965 return parameter::WIDE_INT;
1967 case rtx_test::PEEP2_COUNT:
1968 case rtx_test::VECLEN_GE:
1969 case rtx_test::SAVED_CONST_INT:
1970 case rtx_test::PREDICATE:
1971 case rtx_test::DUPLICATE:
1972 case rtx_test::HAVE_NUM_CLOBBERS:
1973 case rtx_test::C_TEST:
1974 case rtx_test::SET_OP:
1975 case rtx_test::ACCEPT:
1976 return parameter::UNSET;
1978 gcc_unreachable ();
1981 /* Initialize the pos_operand fields of each state reachable from S.
1982 If OPERAND_POS[ID] >= 0, the position with id ID is stored in
1983 operands[OPERAND_POS[ID]] on entry to S. */
1985 static void
1986 find_operand_positions (state *s, vec <int> &operand_pos)
1988 for (decision *d = s->first; d; d = d->next)
1990 int this_operand = (d->test.pos ? operand_pos[d->test.pos->id] : -1);
1991 if (this_operand >= 0)
1992 d->test.pos_operand = this_operand;
1993 if (d->test.kind == rtx_test::SET_OP)
1994 operand_pos[d->test.pos->id] = d->test.u.opno;
1995 for (transition *trans = d->first; trans; trans = trans->next)
1996 find_operand_positions (trans->to, operand_pos);
1997 if (d->test.kind == rtx_test::SET_OP)
1998 operand_pos[d->test.pos->id] = this_operand;
2002 /* Statistics about a matching routine. */
2003 struct stats
2005 stats ();
2007 /* The total number of decisions in the routine, excluding trivial
2008 ones that never fail. */
2009 unsigned int num_decisions;
2011 /* The number of non-trivial decisions on the longest path through
2012 the routine, and the return value that contributes most to that
2013 long path. */
2014 unsigned int longest_path;
2015 int longest_path_code;
2017 /* The maximum number of times that a single call to the routine
2018 can backtrack, and the value returned at the end of that path.
2019 "Backtracking" here means failing one decision in state and
2020 going onto to the next. */
2021 unsigned int longest_backtrack;
2022 int longest_backtrack_code;
2025 stats::stats ()
2026 : num_decisions (0), longest_path (0), longest_path_code (-1),
2027 longest_backtrack (0), longest_backtrack_code (-1) {}
2029 /* Return statistics about S. */
2031 static stats
2032 get_stats (state *s)
2034 stats for_s;
2035 unsigned int longest_path = 0;
2036 for (decision *d = s->first; d; d = d->next)
2038 /* Work out the statistics for D. */
2039 stats for_d;
2040 for (transition *trans = d->first; trans; trans = trans->next)
2042 stats for_trans = get_stats (trans->to);
2043 for_d.num_decisions += for_trans.num_decisions;
2044 /* Each transition is mutually-exclusive, so just pick the
2045 longest of the individual paths. */
2046 if (for_d.longest_path <= for_trans.longest_path)
2048 for_d.longest_path = for_trans.longest_path;
2049 for_d.longest_path_code = for_trans.longest_path_code;
2051 /* Likewise for backtracking. */
2052 if (for_d.longest_backtrack <= for_trans.longest_backtrack)
2054 for_d.longest_backtrack = for_trans.longest_backtrack;
2055 for_d.longest_backtrack_code = for_trans.longest_backtrack_code;
2059 /* Account for D's test in its statistics. */
2060 if (!d->test.single_outcome_p ())
2062 for_d.num_decisions += 1;
2063 for_d.longest_path += 1;
2065 if (d->test.kind == rtx_test::ACCEPT)
2067 for_d.longest_path_code = d->test.u.acceptance.u.full.code;
2068 for_d.longest_backtrack_code = d->test.u.acceptance.u.full.code;
2071 /* Keep a running count of the number of backtracks. */
2072 if (d->prev)
2073 for_s.longest_backtrack += 1;
2075 /* Accumulate D's statistics into S's. */
2076 for_s.num_decisions += for_d.num_decisions;
2077 for_s.longest_path += for_d.longest_path;
2078 for_s.longest_backtrack += for_d.longest_backtrack;
2080 /* Use the code from the decision with the longest individual path,
2081 since that's more likely to be useful if trying to make the
2082 path shorter. In the event of a tie, pick the later decision,
2083 since that's closer to the end of the path. */
2084 if (longest_path <= for_d.longest_path)
2086 longest_path = for_d.longest_path;
2087 for_s.longest_path_code = for_d.longest_path_code;
2090 /* Later decisions in a state are necessarily in a longer backtrack
2091 than earlier decisions. */
2092 for_s.longest_backtrack_code = for_d.longest_backtrack_code;
2094 return for_s;
2097 /* Optimize ROOT. Use TYPE to describe ROOT in status messages. */
2099 static void
2100 optimize_subroutine_group (const char *type, state *root)
2102 /* Remove optional transitions that turned out not to be worthwhile. */
2103 if (collapse_optional_decisions_p)
2104 collapse_optional_decisions (root);
2106 /* Try to remove duplicated tests and to rearrange tests into a more
2107 logical order. */
2108 if (cse_tests_p)
2110 known_conditions kc;
2111 kc.position_tests.safe_grow_cleared (num_positions);
2112 kc.set_operands.safe_grow_cleared (num_operands);
2113 kc.peep2_count = 1;
2114 cse_tests (&root_pos, root, &kc);
2117 /* Try to simplify two or more tests into one. */
2118 if (simplify_tests_p)
2119 simplify_tests (root);
2121 /* Try to use operands[] instead of xN variables. */
2122 if (use_operand_variables_p)
2124 auto_vec <int> operand_pos (num_positions);
2125 for (unsigned int i = 0; i < num_positions; ++i)
2126 operand_pos.quick_push (-1);
2127 find_operand_positions (root, operand_pos);
2130 /* Print a summary of the new state. */
2131 stats st = get_stats (root);
2132 fprintf (stderr, "Statistics for %s:\n", type);
2133 fprintf (stderr, " Number of decisions: %6d\n", st.num_decisions);
2134 fprintf (stderr, " longest path: %6d (code: %6d)\n",
2135 st.longest_path, st.longest_path_code);
2136 fprintf (stderr, " longest backtrack: %6d (code: %6d)\n",
2137 st.longest_backtrack, st.longest_backtrack_code);
2140 struct merge_pattern_info;
2142 /* Represents a transition from one pattern to another. */
2143 struct merge_pattern_transition
2145 merge_pattern_transition (merge_pattern_info *);
2147 /* The target pattern. */
2148 merge_pattern_info *to;
2150 /* The parameters that the source pattern passes to the target pattern.
2151 "parameter (TYPE, true, I)" represents parameter I of the source
2152 pattern. */
2153 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2156 merge_pattern_transition::merge_pattern_transition (merge_pattern_info *to_in)
2157 : to (to_in)
2161 /* Represents a pattern that can might match several states. The pattern
2162 may replace parts of the test with a parameter value. It may also
2163 replace transition labels with parameters. */
2164 struct merge_pattern_info
2166 merge_pattern_info (unsigned int);
2168 /* If PARAM_TEST_P, the state's singleton test should be generalized
2169 to use the runtime value of PARAMS[PARAM_TEST]. */
2170 unsigned int param_test : 8;
2172 /* If PARAM_TRANSITION_P, the state's single transition label should
2173 be replaced by the runtime value of PARAMS[PARAM_TRANSITION]. */
2174 unsigned int param_transition : 8;
2176 /* True if we have decided to generalize the root decision's test,
2177 as per PARAM_TEST. */
2178 unsigned int param_test_p : 1;
2180 /* Likewise for the root decision's transition, as per PARAM_TRANSITION. */
2181 unsigned int param_transition_p : 1;
2183 /* True if the contents of the structure are completely filled in. */
2184 unsigned int complete_p : 1;
2186 /* The number of pseudo-statements in the pattern. Used to decide
2187 whether it's big enough to break out into a subroutine. */
2188 unsigned int num_statements;
2190 /* The number of states that use this pattern. */
2191 unsigned int num_users;
2193 /* The number of distinct success values that the pattern returns. */
2194 unsigned int num_results;
2196 /* This array has one element for each runtime parameter to the pattern.
2197 PARAMS[I] gives the default value of parameter I, which is always
2198 constant.
2200 These default parameters are used in cases where we match the
2201 pattern against some state S1, then add more parameters while
2202 matching against some state S2. S1 is then left passing fewer
2203 parameters than S2. The array gives us enough informatino to
2204 construct a full parameter list for S1 (see update_parameters).
2206 If we decide to create a subroutine for this pattern,
2207 PARAMS[I].type determines the C type of parameter I. */
2208 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2210 /* All states that match this pattern must have the same number of
2211 transitions. TRANSITIONS[I] describes the subpattern for transition
2212 number I; it is null if transition I represents a successful return
2213 from the pattern. */
2214 auto_vec <merge_pattern_transition *, 1> transitions;
2216 /* The routine associated with the pattern, or null if we haven't generated
2217 one yet. */
2218 pattern_routine *routine;
2221 merge_pattern_info::merge_pattern_info (unsigned int num_transitions)
2222 : param_test (0),
2223 param_transition (0),
2224 param_test_p (false),
2225 param_transition_p (false),
2226 complete_p (false),
2227 num_statements (0),
2228 num_users (0),
2229 num_results (0),
2230 routine (0)
2232 transitions.safe_grow_cleared (num_transitions);
2235 /* Describes one way of matching a particular state to a particular
2236 pattern. */
2237 struct merge_state_result
2239 merge_state_result (merge_pattern_info *, position *, merge_state_result *);
2241 /* A pattern that matches the state. */
2242 merge_pattern_info *pattern;
2244 /* If we decide to use this match and create a subroutine for PATTERN,
2245 the state should pass the rtx at position ROOT to the pattern's
2246 rtx parameter. A null root means that the pattern doesn't need
2247 an rtx parameter; all the rtxes it matches come from elsewhere. */
2248 position *root;
2250 /* The parameters that should be passed to PATTERN for this state.
2251 If the array is shorter than PATTERN->params, the missing entries
2252 should be taken from the corresponding element of PATTERN->params. */
2253 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2255 /* An earlier match for the same state, or null if none. Patterns
2256 matched by earlier entries are smaller than PATTERN. */
2257 merge_state_result *prev;
2260 merge_state_result::merge_state_result (merge_pattern_info *pattern_in,
2261 position *root_in,
2262 merge_state_result *prev_in)
2263 : pattern (pattern_in), root (root_in), prev (prev_in)
2266 /* Information about a state, used while trying to match it against
2267 a pattern. */
2268 struct merge_state_info
2270 merge_state_info (state *);
2272 /* The state itself. */
2273 state *s;
2275 /* Index I gives information about the target of transition I. */
2276 merge_state_info *to_states;
2278 /* The number of transitions in S. */
2279 unsigned int num_transitions;
2281 /* True if the state has been deleted in favor of a call to a
2282 pattern routine. */
2283 bool merged_p;
2285 /* The previous state that might be a merge candidate for S, or null
2286 if no previous states could be merged with S. */
2287 merge_state_info *prev_same_test;
2289 /* A list of pattern matches for this state. */
2290 merge_state_result *res;
2293 merge_state_info::merge_state_info (state *s_in)
2294 : s (s_in),
2295 to_states (0),
2296 num_transitions (0),
2297 merged_p (false),
2298 prev_same_test (0),
2299 res (0) {}
2301 /* True if PAT would be useful as a subroutine. */
2303 static bool
2304 useful_pattern_p (merge_pattern_info *pat)
2306 return pat->num_statements >= MIN_COMBINE_COST;
2309 /* PAT2 is a subpattern of PAT1. Return true if PAT2 should be inlined
2310 into PAT1's C routine. */
2312 static bool
2313 same_pattern_p (merge_pattern_info *pat1, merge_pattern_info *pat2)
2315 return pat1->num_users == pat2->num_users || !useful_pattern_p (pat2);
2318 /* PAT was previously matched against SINFO based on tentative matches
2319 for the target states of SINFO's state. Return true if the match
2320 still holds; that is, if the target states of SINFO's state still
2321 match the corresponding transitions of PAT. */
2323 static bool
2324 valid_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2326 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2327 if (merge_pattern_transition *ptrans = pat->transitions[j])
2329 merge_state_result *to_res = sinfo->to_states[j].res;
2330 if (!to_res || to_res->pattern != ptrans->to)
2331 return false;
2333 return true;
2336 /* Remove any matches that are no longer valid from the head of SINFO's
2337 list of matches. */
2339 static void
2340 prune_invalid_results (merge_state_info *sinfo)
2342 while (sinfo->res && !valid_result_p (sinfo->res->pattern, sinfo))
2344 sinfo->res = sinfo->res->prev;
2345 gcc_assert (sinfo->res);
2349 /* Return true if PAT represents the biggest posssible match for SINFO;
2350 that is, if the next action of SINFO's state on return from PAT will
2351 be something that cannot be merged with any other state. */
2353 static bool
2354 complete_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2356 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2357 if (sinfo->to_states[j].res && !pat->transitions[j])
2358 return false;
2359 return true;
2362 /* Update TO for any parameters that have been added to FROM since TO
2363 was last set. The extra parameters in FROM will be constants or
2364 instructions to duplicate earlier parameters. */
2366 static void
2367 update_parameters (vec <parameter> &to, const vec <parameter> &from)
2369 for (unsigned int i = to.length (); i < from.length (); ++i)
2370 to.quick_push (from[i]);
2373 /* Return true if A and B can be tested by a single test. If the test
2374 can be parameterised, store the parameter value for A in *PARAMA and
2375 the parameter value for B in *PARAMB, otherwise leave PARAMA and
2376 PARAMB alone. */
2378 static bool
2379 compatible_tests_p (const rtx_test &a, const rtx_test &b,
2380 parameter *parama, parameter *paramb)
2382 if (a.kind != b.kind)
2383 return false;
2384 switch (a.kind)
2386 case rtx_test::PREDICATE:
2387 if (a.u.predicate.data != b.u.predicate.data)
2388 return false;
2389 *parama = parameter (parameter::MODE, false, a.u.predicate.mode);
2390 *paramb = parameter (parameter::MODE, false, b.u.predicate.mode);
2391 return true;
2393 case rtx_test::SAVED_CONST_INT:
2394 *parama = parameter (parameter::INT, false, a.u.integer.value);
2395 *paramb = parameter (parameter::INT, false, b.u.integer.value);
2396 return true;
2398 default:
2399 return a == b;
2403 /* PARAMS is an array of the parameters that a state is going to pass
2404 to a pattern routine. It is still incomplete; index I has a kind of
2405 parameter::UNSET if we don't yet know what the state will pass
2406 as parameter I. Try to make parameter ID equal VALUE, returning
2407 true on success. */
2409 static bool
2410 set_parameter (vec <parameter> &params, unsigned int id,
2411 const parameter &value)
2413 if (params[id].type == parameter::UNSET)
2415 if (force_unique_params_p)
2416 for (unsigned int i = 0; i < params.length (); ++i)
2417 if (params[i] == value)
2418 return false;
2419 params[id] = value;
2420 return true;
2422 return params[id] == value;
2425 /* PARAMS2 is the "params" array for a pattern and PARAMS1 is the
2426 set of parameters that a particular state is going to pass to
2427 that pattern.
2429 Try to extend PARAMS1 and PARAMS2 so that there is a parameter
2430 that is equal to PARAM1 for the state and has a default value of
2431 PARAM2. Parameters beginning at START were added as part of the
2432 same match and so may be reused. */
2434 static bool
2435 add_parameter (vec <parameter> &params1, vec <parameter> &params2,
2436 const parameter &param1, const parameter &param2,
2437 unsigned int start, unsigned int *res)
2439 gcc_assert (params1.length () == params2.length ());
2440 gcc_assert (!param1.is_param && !param2.is_param);
2442 for (unsigned int i = start; i < params2.length (); ++i)
2443 if (params1[i] == param1 && params2[i] == param2)
2445 *res = i;
2446 return true;
2449 if (force_unique_params_p)
2450 for (unsigned int i = 0; i < params2.length (); ++i)
2451 if (params1[i] == param1 || params2[i] == param2)
2452 return false;
2454 if (params2.length () >= MAX_PATTERN_PARAMS)
2455 return false;
2457 *res = params2.length ();
2458 params1.quick_push (param1);
2459 params2.quick_push (param2);
2460 return true;
2463 /* If *ROOTA is nonnull, return true if the same sequence of steps are
2464 required to reach A from *ROOTA as to reach B from ROOTB. If *ROOTA
2465 is null, update it if necessary in order to make the condition hold. */
2467 static bool
2468 merge_relative_positions (position **roota, position *a,
2469 position *rootb, position *b)
2471 if (!relative_patterns_p)
2473 if (a != b)
2474 return false;
2475 if (!*roota)
2477 *roota = rootb;
2478 return true;
2480 return *roota == rootb;
2482 /* If B does not belong to the same instruction as ROOTB, we don't
2483 start with ROOTB but instead start with a call to peep2_next_insn.
2484 In that case the sequences for B and A are identical iff B and A
2485 are themselves identical. */
2486 if (rootb->insn_id != b->insn_id)
2487 return a == b;
2488 while (rootb != b)
2490 if (!a || b->type != a->type || b->arg != a->arg)
2491 return false;
2492 b = b->base;
2493 a = a->base;
2495 if (!*roota)
2496 *roota = a;
2497 return *roota == a;
2500 /* A hasher of states that treats two states as "equal" if they might be
2501 merged (but trying to be more discriminating than "return true"). */
2502 struct test_pattern_hasher : nofree_ptr_hash <merge_state_info>
2504 static inline hashval_t hash (const value_type &);
2505 static inline bool equal (const value_type &, const compare_type &);
2508 hashval_t
2509 test_pattern_hasher::hash (merge_state_info *const &sinfo)
2511 inchash::hash h;
2512 decision *d = sinfo->s->singleton ();
2513 h.add_int (d->test.pos_operand + 1);
2514 if (!relative_patterns_p)
2515 h.add_int (d->test.pos ? d->test.pos->id + 1 : 0);
2516 h.add_int (d->test.kind);
2517 h.add_int (sinfo->num_transitions);
2518 return h.end ();
2521 bool
2522 test_pattern_hasher::equal (merge_state_info *const &sinfo1,
2523 merge_state_info *const &sinfo2)
2525 decision *d1 = sinfo1->s->singleton ();
2526 decision *d2 = sinfo2->s->singleton ();
2527 gcc_assert (d1 && d2);
2529 parameter new_param1, new_param2;
2530 return (d1->test.pos_operand == d2->test.pos_operand
2531 && (relative_patterns_p || d1->test.pos == d2->test.pos)
2532 && compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2)
2533 && sinfo1->num_transitions == sinfo2->num_transitions);
2536 /* Try to make the state described by SINFO1 use the same pattern as the
2537 state described by SINFO2. Return true on success.
2539 SINFO1 and SINFO2 are known to have the same hash value. */
2541 static bool
2542 merge_patterns (merge_state_info *sinfo1, merge_state_info *sinfo2)
2544 merge_state_result *res2 = sinfo2->res;
2545 merge_pattern_info *pat = res2->pattern;
2547 /* Write to temporary arrays while matching, in case we have to abort
2548 half way through. */
2549 auto_vec <parameter, MAX_PATTERN_PARAMS> params1;
2550 auto_vec <parameter, MAX_PATTERN_PARAMS> params2;
2551 params1.quick_grow_cleared (pat->params.length ());
2552 params2.splice (pat->params);
2553 unsigned int start_param = params2.length ();
2555 /* An array for recording changes to PAT->transitions[?].params.
2556 All changes involve replacing a constant parameter with some
2557 PAT->params[N], where N is the second element of the pending_param. */
2558 typedef std::pair <parameter *, unsigned int> pending_param;
2559 auto_vec <pending_param, 32> pending_params;
2561 decision *d1 = sinfo1->s->singleton ();
2562 decision *d2 = sinfo2->s->singleton ();
2563 gcc_assert (d1 && d2);
2565 /* If D2 tests a position, SINFO1's root relative to D1 is the same
2566 as SINFO2's root relative to D2. */
2567 position *root1 = 0;
2568 position *root2 = res2->root;
2569 if (d2->test.pos_operand < 0
2570 && d1->test.pos
2571 && !merge_relative_positions (&root1, d1->test.pos,
2572 root2, d2->test.pos))
2573 return false;
2575 /* Check whether the patterns have the same shape. */
2576 unsigned int num_transitions = sinfo1->num_transitions;
2577 gcc_assert (num_transitions == sinfo2->num_transitions);
2578 for (unsigned int i = 0; i < num_transitions; ++i)
2579 if (merge_pattern_transition *ptrans = pat->transitions[i])
2581 merge_state_result *to1_res = sinfo1->to_states[i].res;
2582 merge_state_result *to2_res = sinfo2->to_states[i].res;
2583 merge_pattern_info *to_pat = ptrans->to;
2584 gcc_assert (to2_res && to2_res->pattern == to_pat);
2585 if (!to1_res || to1_res->pattern != to_pat)
2586 return false;
2587 if (to2_res->root
2588 && !merge_relative_positions (&root1, to1_res->root,
2589 root2, to2_res->root))
2590 return false;
2591 /* Match the parameters that TO1_RES passes to TO_PAT with the
2592 parameters that PAT passes to TO_PAT. */
2593 update_parameters (to1_res->params, to_pat->params);
2594 for (unsigned int j = 0; j < to1_res->params.length (); ++j)
2596 const parameter &param1 = to1_res->params[j];
2597 const parameter &param2 = ptrans->params[j];
2598 gcc_assert (!param1.is_param);
2599 if (param2.is_param)
2601 if (!set_parameter (params1, param2.value, param1))
2602 return false;
2604 else if (param1 != param2)
2606 unsigned int id;
2607 if (!add_parameter (params1, params2,
2608 param1, param2, start_param, &id))
2609 return false;
2610 /* Record that PAT should now pass parameter ID to TO_PAT,
2611 instead of the current contents of *PARAM2. We only
2612 make the change if the rest of the match succeeds. */
2613 pending_params.safe_push
2614 (pending_param (&ptrans->params[j], id));
2619 unsigned int param_test = pat->param_test;
2620 unsigned int param_transition = pat->param_transition;
2621 bool param_test_p = pat->param_test_p;
2622 bool param_transition_p = pat->param_transition_p;
2624 /* If the tests don't match exactly, try to parameterize them. */
2625 parameter new_param1, new_param2;
2626 if (!compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2))
2627 gcc_unreachable ();
2628 if (new_param1.type != parameter::UNSET)
2630 /* If the test has not already been parameterized, all existing
2631 matches use constant NEW_PARAM2. */
2632 if (param_test_p)
2634 if (!set_parameter (params1, param_test, new_param1))
2635 return false;
2637 else if (new_param1 != new_param2)
2639 if (!add_parameter (params1, params2, new_param1, new_param2,
2640 start_param, &param_test))
2641 return false;
2642 param_test_p = true;
2646 /* Match the transitions. */
2647 transition *trans1 = d1->first;
2648 transition *trans2 = d2->first;
2649 for (unsigned int i = 0; i < num_transitions; ++i)
2651 if (param_transition_p || trans1->labels != trans2->labels)
2653 /* We can only generalize a single transition with a single
2654 label. */
2655 if (num_transitions != 1
2656 || trans1->labels.length () != 1
2657 || trans2->labels.length () != 1)
2658 return false;
2660 /* Although we can match wide-int fields, in practice it leads
2661 to some odd results for const_vectors. We end up
2662 parameterizing the first N const_ints of the vector
2663 and then (once we reach the maximum number of parameters)
2664 we go on to match the other elements exactly. */
2665 if (d1->test.kind == rtx_test::WIDE_INT_FIELD)
2666 return false;
2668 /* See whether the label has a generalizable type. */
2669 parameter::type_enum param_type
2670 = transition_parameter_type (d1->test.kind);
2671 if (param_type == parameter::UNSET)
2672 return false;
2674 /* Match the labels using parameters. */
2675 new_param1 = parameter (param_type, false, trans1->labels[0]);
2676 if (param_transition_p)
2678 if (!set_parameter (params1, param_transition, new_param1))
2679 return false;
2681 else
2683 new_param2 = parameter (param_type, false, trans2->labels[0]);
2684 if (!add_parameter (params1, params2, new_param1, new_param2,
2685 start_param, &param_transition))
2686 return false;
2687 param_transition_p = true;
2690 trans1 = trans1->next;
2691 trans2 = trans2->next;
2694 /* Set any unset parameters to their default values. This occurs if some
2695 other state needed something to be parameterized in order to match SINFO2,
2696 but SINFO1 on its own does not. */
2697 for (unsigned int i = 0; i < params1.length (); ++i)
2698 if (params1[i].type == parameter::UNSET)
2699 params1[i] = params2[i];
2701 /* The match was successful. Commit all pending changes to PAT. */
2702 update_parameters (pat->params, params2);
2704 pending_param *pp;
2705 unsigned int i;
2706 FOR_EACH_VEC_ELT (pending_params, i, pp)
2707 *pp->first = parameter (pp->first->type, true, pp->second);
2709 pat->param_test = param_test;
2710 pat->param_transition = param_transition;
2711 pat->param_test_p = param_test_p;
2712 pat->param_transition_p = param_transition_p;
2714 /* Record the match of SINFO1. */
2715 merge_state_result *new_res1 = new merge_state_result (pat, root1,
2716 sinfo1->res);
2717 new_res1->params.splice (params1);
2718 sinfo1->res = new_res1;
2719 return true;
2722 /* The number of states that were removed by calling pattern routines. */
2723 static unsigned int pattern_use_states;
2725 /* The number of states used while defining pattern routines. */
2726 static unsigned int pattern_def_states;
2728 /* Information used while constructing a use or definition of a pattern
2729 routine. */
2730 struct create_pattern_info
2732 /* The routine itself. */
2733 pattern_routine *routine;
2735 /* The first unclaimed return value for this particular use or definition.
2736 We walk the substates of uses and definitions in the same order
2737 so each return value always refers to the same position within
2738 the pattern. */
2739 unsigned int next_result;
2742 static void populate_pattern_routine (create_pattern_info *,
2743 merge_state_info *, state *,
2744 const vec <parameter> &);
2746 /* SINFO matches a pattern for which we've decided to create a C routine.
2747 Return a decision that performs a call to the pattern routine,
2748 but leave the caller to add the transitions to it. Initialize CPI
2749 for this purpose. Also create a definition for the pattern routine,
2750 if it doesn't already have one.
2752 PARAMS are the parameters that SINFO passes to its pattern. */
2754 static decision *
2755 init_pattern_use (create_pattern_info *cpi, merge_state_info *sinfo,
2756 const vec <parameter> &params)
2758 state *s = sinfo->s;
2759 merge_state_result *res = sinfo->res;
2760 merge_pattern_info *pat = res->pattern;
2761 cpi->routine = pat->routine;
2762 if (!cpi->routine)
2764 /* We haven't defined the pattern routine yet, so create
2765 a definition now. */
2766 pattern_routine *routine = new pattern_routine;
2767 pat->routine = routine;
2768 cpi->routine = routine;
2769 routine->s = new state;
2770 routine->insn_p = false;
2771 routine->pnum_clobbers_p = false;
2773 /* Create an "idempotent" mapping of parameter I to parameter I.
2774 Also record the C type of each parameter to the routine. */
2775 auto_vec <parameter, MAX_PATTERN_PARAMS> def_params;
2776 for (unsigned int i = 0; i < pat->params.length (); ++i)
2778 def_params.quick_push (parameter (pat->params[i].type, true, i));
2779 routine->param_types.quick_push (pat->params[i].type);
2782 /* Any of the states that match the pattern could be used to
2783 create the routine definition. We might as well use SINFO
2784 since it's already to hand. This means that all positions
2785 in the definition will be relative to RES->root. */
2786 routine->pos = res->root;
2787 cpi->next_result = 0;
2788 populate_pattern_routine (cpi, sinfo, routine->s, def_params);
2789 gcc_assert (cpi->next_result == pat->num_results);
2791 /* Add the routine to the global list, after the subroutines
2792 that it calls. */
2793 routine->pattern_id = patterns.length ();
2794 patterns.safe_push (routine);
2797 /* Create a decision to call the routine, passing PARAMS to it. */
2798 pattern_use *use = new pattern_use;
2799 use->routine = pat->routine;
2800 use->params.splice (params);
2801 decision *d = new decision (rtx_test::pattern (res->root, use));
2803 /* If the original decision could use an element of operands[] instead
2804 of an rtx variable, try to transfer it to the new decision. */
2805 if (s->first->test.pos && res->root == s->first->test.pos)
2806 d->test.pos_operand = s->first->test.pos_operand;
2808 cpi->next_result = 0;
2809 return d;
2812 /* Make S return the next unclaimed pattern routine result for CPI. */
2814 static void
2815 add_pattern_acceptance (create_pattern_info *cpi, state *s)
2817 acceptance_type acceptance;
2818 acceptance.type = SUBPATTERN;
2819 acceptance.partial_p = false;
2820 acceptance.u.full.code = cpi->next_result;
2821 add_decision (s, rtx_test::accept (acceptance), true, false);
2822 cpi->next_result += 1;
2825 /* Initialize new empty state NEWS so that it implements SINFO's pattern
2826 (here referred to as "P"). P may be the top level of a pattern routine
2827 or a subpattern that should be inlined into its parent pattern's routine
2828 (as per same_pattern_p). The choice of SINFO for a top-level pattern is
2829 arbitrary; it could be any of the states that use P. The choice for
2830 subpatterns follows the choice for the parent pattern.
2832 PARAMS gives the value of each parameter to P in terms of the parameters
2833 to the top-level pattern. If P itself is the top level pattern, PARAMS[I]
2834 is always "parameter (TYPE, true, I)". */
2836 static void
2837 populate_pattern_routine (create_pattern_info *cpi, merge_state_info *sinfo,
2838 state *news, const vec <parameter> &params)
2840 pattern_def_states += 1;
2842 decision *d = sinfo->s->singleton ();
2843 merge_pattern_info *pat = sinfo->res->pattern;
2844 pattern_routine *routine = cpi->routine;
2846 /* Create a copy of D's test for the pattern routine and generalize it
2847 as appropriate. */
2848 decision *newd = new decision (d->test);
2849 gcc_assert (newd->test.pos_operand >= 0
2850 || !newd->test.pos
2851 || common_position (newd->test.pos,
2852 routine->pos) == routine->pos);
2853 if (pat->param_test_p)
2855 const parameter &param = params[pat->param_test];
2856 switch (newd->test.kind)
2858 case rtx_test::PREDICATE:
2859 newd->test.u.predicate.mode_is_param = param.is_param;
2860 newd->test.u.predicate.mode = param.value;
2861 break;
2863 case rtx_test::SAVED_CONST_INT:
2864 newd->test.u.integer.is_param = param.is_param;
2865 newd->test.u.integer.value = param.value;
2866 break;
2868 default:
2869 gcc_unreachable ();
2870 break;
2873 if (d->test.kind == rtx_test::C_TEST)
2874 routine->insn_p = true;
2875 else if (d->test.kind == rtx_test::HAVE_NUM_CLOBBERS)
2876 routine->pnum_clobbers_p = true;
2877 news->push_back (newd);
2879 /* Fill in the transitions of NEWD. */
2880 unsigned int i = 0;
2881 for (transition *trans = d->first; trans; trans = trans->next)
2883 /* Create a new state to act as the target of the new transition. */
2884 state *to_news = new state;
2885 if (merge_pattern_transition *ptrans = pat->transitions[i])
2887 /* The pattern hasn't finished matching yet. Get the target
2888 pattern and the corresponding target state of SINFO. */
2889 merge_pattern_info *to_pat = ptrans->to;
2890 merge_state_info *to = sinfo->to_states + i;
2891 gcc_assert (to->res->pattern == to_pat);
2892 gcc_assert (ptrans->params.length () == to_pat->params.length ());
2894 /* Express the parameters to TO_PAT in terms of the parameters
2895 to the top-level pattern. */
2896 auto_vec <parameter, MAX_PATTERN_PARAMS> to_params;
2897 for (unsigned int j = 0; j < ptrans->params.length (); ++j)
2899 const parameter &param = ptrans->params[j];
2900 to_params.quick_push (param.is_param
2901 ? params[param.value]
2902 : param);
2905 if (same_pattern_p (pat, to_pat))
2906 /* TO_PAT is part of the current routine, so just recurse. */
2907 populate_pattern_routine (cpi, to, to_news, to_params);
2908 else
2910 /* TO_PAT should be matched by calling a separate routine. */
2911 create_pattern_info sub_cpi;
2912 decision *subd = init_pattern_use (&sub_cpi, to, to_params);
2913 routine->insn_p |= sub_cpi.routine->insn_p;
2914 routine->pnum_clobbers_p |= sub_cpi.routine->pnum_clobbers_p;
2916 /* Add the pattern routine call to the new target state. */
2917 to_news->push_back (subd);
2919 /* Add a transition for each successful call result. */
2920 for (unsigned int j = 0; j < to_pat->num_results; ++j)
2922 state *res = new state;
2923 add_pattern_acceptance (cpi, res);
2924 subd->push_back (new transition (j, res, false));
2928 else
2929 /* This transition corresponds to a successful match. */
2930 add_pattern_acceptance (cpi, to_news);
2932 /* Create the transition itself, generalizing as necessary. */
2933 transition *new_trans = new transition (trans->labels, to_news,
2934 trans->optional);
2935 if (pat->param_transition_p)
2937 const parameter &param = params[pat->param_transition];
2938 new_trans->is_param = param.is_param;
2939 new_trans->labels[0] = param.value;
2941 newd->push_back (new_trans);
2942 i += 1;
2946 /* USE is a decision that calls a pattern routine and SINFO is part of the
2947 original state tree that the call is supposed to replace. Add the
2948 transitions for SINFO and its substates to USE. */
2950 static void
2951 populate_pattern_use (create_pattern_info *cpi, decision *use,
2952 merge_state_info *sinfo)
2954 pattern_use_states += 1;
2955 gcc_assert (!sinfo->merged_p);
2956 sinfo->merged_p = true;
2957 merge_state_result *res = sinfo->res;
2958 merge_pattern_info *pat = res->pattern;
2959 decision *d = sinfo->s->singleton ();
2960 unsigned int i = 0;
2961 for (transition *trans = d->first; trans; trans = trans->next)
2963 if (pat->transitions[i])
2964 /* The target state is also part of the pattern. */
2965 populate_pattern_use (cpi, use, sinfo->to_states + i);
2966 else
2968 /* The transition corresponds to a successful return from the
2969 pattern routine. */
2970 use->push_back (new transition (cpi->next_result, trans->to, false));
2971 cpi->next_result += 1;
2973 i += 1;
2977 /* We have decided to replace SINFO's state with a call to a pattern
2978 routine. Make the change, creating a definition of the pattern routine
2979 if it doesn't have one already. */
2981 static void
2982 use_pattern (merge_state_info *sinfo)
2984 merge_state_result *res = sinfo->res;
2985 merge_pattern_info *pat = res->pattern;
2986 state *s = sinfo->s;
2988 /* The pattern may have acquired new parameters after it was matched
2989 against SINFO. Update the parameters that SINFO passes accordingly. */
2990 update_parameters (res->params, pat->params);
2992 create_pattern_info cpi;
2993 decision *d = init_pattern_use (&cpi, sinfo, res->params);
2994 populate_pattern_use (&cpi, d, sinfo);
2995 s->release ();
2996 s->push_back (d);
2999 /* Look through the state trees in STATES for common patterns and
3000 split them into subroutines. */
3002 static void
3003 split_out_patterns (vec <merge_state_info> &states)
3005 unsigned int first_transition = states.length ();
3006 hash_table <test_pattern_hasher> hashtab (128);
3007 /* Stage 1: Create an order in which parent states come before their child
3008 states and in which sibling states are at consecutive locations.
3009 Having consecutive sibling states allows merge_state_info to have
3010 a single to_states pointer. */
3011 for (unsigned int i = 0; i < states.length (); ++i)
3012 for (decision *d = states[i].s->first; d; d = d->next)
3013 for (transition *trans = d->first; trans; trans = trans->next)
3015 states.safe_push (trans->to);
3016 states[i].num_transitions += 1;
3018 /* Stage 2: Now that the addresses are stable, set up the to_states
3019 pointers. Look for states that might be merged and enter them
3020 into the hash table. */
3021 for (unsigned int i = 0; i < states.length (); ++i)
3023 merge_state_info *sinfo = &states[i];
3024 if (sinfo->num_transitions)
3026 sinfo->to_states = &states[first_transition];
3027 first_transition += sinfo->num_transitions;
3029 /* For simplicity, we only try to merge states that have a single
3030 decision. This is in any case the best we can do for peephole2,
3031 since whether a peephole2 ACCEPT succeeds or not depends on the
3032 specific peephole2 pattern (which is unique to each ACCEPT
3033 and so couldn't be shared between states). */
3034 if (decision *d = sinfo->s->singleton ())
3035 /* ACCEPT states are unique, so don't even try to merge them. */
3036 if (d->test.kind != rtx_test::ACCEPT
3037 && (pattern_have_num_clobbers_p
3038 || d->test.kind != rtx_test::HAVE_NUM_CLOBBERS)
3039 && (pattern_c_test_p
3040 || d->test.kind != rtx_test::C_TEST))
3042 merge_state_info **slot = hashtab.find_slot (sinfo, INSERT);
3043 sinfo->prev_same_test = *slot;
3044 *slot = sinfo;
3047 /* Stage 3: Walk backwards through the list of states and try to merge
3048 them. This is a greedy, bottom-up match; parent nodes can only start
3049 a new leaf pattern if they fail to match when combined with all child
3050 nodes that have matching patterns.
3052 For each state we keep a list of potential matches, with each
3053 potential match being larger (and deeper) than the next match in
3054 the list. The final element in the list is a leaf pattern that
3055 matches just a single state.
3057 Each candidate pattern created in this loop is unique -- it won't
3058 have been seen by an earlier iteration. We try to match each pattern
3059 with every state that appears earlier in STATES.
3061 Because the patterns created in the loop are unique, any state
3062 that already has a match must have a final potential match that
3063 is different from any new leaf pattern. Therefore, when matching
3064 leaf patterns, we need only consider states whose list of matches
3065 is empty.
3067 The non-leaf patterns that we try are as deep as possible
3068 and are an extension of the state's previous best candidate match (PB).
3069 We need only consider states whose current potential match is also PB;
3070 any states that don't match as much as PB cannnot match the new pattern,
3071 while any states that already match more than PB must be different from
3072 the new pattern. */
3073 for (unsigned int i2 = states.length (); i2-- > 0; )
3075 merge_state_info *sinfo2 = &states[i2];
3077 /* Enforce the bottom-upness of the match: remove matches with later
3078 states if SINFO2's child states ended up finding a better match. */
3079 prune_invalid_results (sinfo2);
3081 /* Do nothing if the state doesn't match a later one and if there are
3082 no earlier states it could match. */
3083 if (!sinfo2->res && !sinfo2->prev_same_test)
3084 continue;
3086 merge_state_result *res2 = sinfo2->res;
3087 decision *d2 = sinfo2->s->singleton ();
3088 position *root2 = (d2->test.pos_operand < 0 ? d2->test.pos : 0);
3089 unsigned int num_transitions = sinfo2->num_transitions;
3091 /* If RES2 is null then SINFO2's test in isolation has not been seen
3092 before. First try matching that on its own. */
3093 if (!res2)
3095 merge_pattern_info *new_pat
3096 = new merge_pattern_info (num_transitions);
3097 merge_state_result *new_res2
3098 = new merge_state_result (new_pat, root2, res2);
3099 sinfo2->res = new_res2;
3101 new_pat->num_statements = !d2->test.single_outcome_p ();
3102 new_pat->num_results = num_transitions;
3103 bool matched_p = false;
3104 /* Look for states that don't currently match anything but
3105 can be made to match SINFO2 on its own. */
3106 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3107 sinfo1 = sinfo1->prev_same_test)
3108 if (!sinfo1->res && merge_patterns (sinfo1, sinfo2))
3109 matched_p = true;
3110 if (!matched_p)
3112 /* No other states match. */
3113 sinfo2->res = res2;
3114 delete new_pat;
3115 delete new_res2;
3116 continue;
3118 else
3119 res2 = new_res2;
3122 /* Keep the existing pattern if it's as good as anything we'd
3123 create for SINFO2. */
3124 if (complete_result_p (res2->pattern, sinfo2))
3126 res2->pattern->num_users += 1;
3127 continue;
3130 /* Create a new pattern for SINFO2. */
3131 merge_pattern_info *new_pat = new merge_pattern_info (num_transitions);
3132 merge_state_result *new_res2
3133 = new merge_state_result (new_pat, root2, res2);
3134 sinfo2->res = new_res2;
3136 /* Fill in details about the pattern. */
3137 new_pat->num_statements = !d2->test.single_outcome_p ();
3138 new_pat->num_results = 0;
3139 for (unsigned int j = 0; j < num_transitions; ++j)
3140 if (merge_state_result *to_res = sinfo2->to_states[j].res)
3142 /* Count the target state as part of this pattern.
3143 First update the root position so that it can reach
3144 the target state's root. */
3145 if (to_res->root)
3147 if (new_res2->root)
3148 new_res2->root = common_position (new_res2->root,
3149 to_res->root);
3150 else
3151 new_res2->root = to_res->root;
3153 merge_pattern_info *to_pat = to_res->pattern;
3154 merge_pattern_transition *ptrans
3155 = new merge_pattern_transition (to_pat);
3157 /* TO_PAT may have acquired more parameters when matching
3158 states earlier in STATES than TO_RES's, but the list is
3159 now final. Make sure that TO_RES is up to date. */
3160 update_parameters (to_res->params, to_pat->params);
3162 /* Start out by assuming that every user of NEW_PAT will
3163 want to pass the same (constant) parameters as TO_RES. */
3164 update_parameters (ptrans->params, to_res->params);
3166 new_pat->transitions[j] = ptrans;
3167 new_pat->num_statements += to_pat->num_statements;
3168 new_pat->num_results += to_pat->num_results;
3170 else
3171 /* The target state doesn't match anything and so is not part
3172 of the pattern. */
3173 new_pat->num_results += 1;
3175 /* See if any earlier states that match RES2's pattern also match
3176 NEW_PAT. */
3177 bool matched_p = false;
3178 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3179 sinfo1 = sinfo1->prev_same_test)
3181 prune_invalid_results (sinfo1);
3182 if (sinfo1->res
3183 && sinfo1->res->pattern == res2->pattern
3184 && merge_patterns (sinfo1, sinfo2))
3185 matched_p = true;
3187 if (!matched_p)
3189 /* Nothing else matches NEW_PAT, so go back to the previous
3190 pattern (possibly just a single-state one). */
3191 sinfo2->res = res2;
3192 delete new_pat;
3193 delete new_res2;
3195 /* Assume that SINFO2 will use RES. At this point we don't know
3196 whether earlier states that match the same pattern will use
3197 that match or a different one. */
3198 sinfo2->res->pattern->num_users += 1;
3200 /* Step 4: Finalize the choice of pattern for each state, ignoring
3201 patterns that were only used once. Update each pattern's size
3202 so that it doesn't include subpatterns that are going to be split
3203 out into subroutines. */
3204 for (unsigned int i = 0; i < states.length (); ++i)
3206 merge_state_info *sinfo = &states[i];
3207 merge_state_result *res = sinfo->res;
3208 /* Wind past patterns that are only used by SINFO. */
3209 while (res && res->pattern->num_users == 1)
3211 res = res->prev;
3212 sinfo->res = res;
3213 if (res)
3214 res->pattern->num_users += 1;
3216 if (!res)
3217 continue;
3219 /* We have a shared pattern and are now committed to the match. */
3220 merge_pattern_info *pat = res->pattern;
3221 gcc_assert (valid_result_p (pat, sinfo));
3223 if (!pat->complete_p)
3225 /* Look for subpatterns that are going to be split out and remove
3226 them from the number of statements. */
3227 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
3228 if (merge_pattern_transition *ptrans = pat->transitions[j])
3230 merge_pattern_info *to_pat = ptrans->to;
3231 if (!same_pattern_p (pat, to_pat))
3232 pat->num_statements -= to_pat->num_statements;
3234 pat->complete_p = true;
3237 /* Step 5: Split out the patterns. */
3238 for (unsigned int i = 0; i < states.length (); ++i)
3240 merge_state_info *sinfo = &states[i];
3241 merge_state_result *res = sinfo->res;
3242 if (!sinfo->merged_p && res && useful_pattern_p (res->pattern))
3243 use_pattern (sinfo);
3245 fprintf (stderr, "Shared %d out of %d states by creating %d new states,"
3246 " saving %d\n",
3247 pattern_use_states, states.length (), pattern_def_states,
3248 pattern_use_states - pattern_def_states);
3251 /* Information about a state tree that we're considering splitting into a
3252 subroutine. */
3253 struct state_size
3255 /* The number of pseudo-statements in the state tree. */
3256 unsigned int num_statements;
3258 /* The approximate number of nested "if" and "switch" statements that
3259 would be required if control could fall through to a later state. */
3260 unsigned int depth;
3263 /* Pairs a transition with information about its target state. */
3264 typedef std::pair <transition *, state_size> subroutine_candidate;
3266 /* Sort two subroutine_candidates so that the one with the largest
3267 number of statements comes last. */
3269 static int
3270 subroutine_candidate_cmp (const void *a, const void *b)
3272 return int (((const subroutine_candidate *) a)->second.num_statements
3273 - ((const subroutine_candidate *) b)->second.num_statements);
3276 /* Turn S into a subroutine of type TYPE and add it to PROCS. Return a new
3277 state that performs a subroutine call to S. */
3279 static state *
3280 create_subroutine (routine_type type, state *s, vec <state *> &procs)
3282 procs.safe_push (s);
3283 acceptance_type acceptance;
3284 acceptance.type = type;
3285 acceptance.partial_p = true;
3286 acceptance.u.subroutine_id = procs.length ();
3287 state *news = new state;
3288 add_decision (news, rtx_test::accept (acceptance), true, false);
3289 return news;
3292 /* Walk state tree S, of type TYPE, and look for subtrees that would be
3293 better split into subroutines. Accumulate all such subroutines in PROCS.
3294 Return the size of the new state tree (excluding subroutines). */
3296 static state_size
3297 find_subroutines (routine_type type, state *s, vec <state *> &procs)
3299 auto_vec <subroutine_candidate, 16> candidates;
3300 state_size size;
3301 size.num_statements = 0;
3302 size.depth = 0;
3303 for (decision *d = s->first; d; d = d->next)
3305 if (!d->test.single_outcome_p ())
3306 size.num_statements += 1;
3307 for (transition *trans = d->first; trans; trans = trans->next)
3309 /* Keep chains of simple decisions together if we know that no
3310 change of position is required. We'll output this chain as a
3311 single "if" statement, so it counts as a single nesting level. */
3312 if (d->test.pos && d->if_statement_p ())
3313 for (;;)
3315 decision *newd = trans->to->singleton ();
3316 if (!newd
3317 || (newd->test.pos
3318 && newd->test.pos_operand < 0
3319 && newd->test.pos != d->test.pos)
3320 || !newd->if_statement_p ())
3321 break;
3322 if (!newd->test.single_outcome_p ())
3323 size.num_statements += 1;
3324 trans = newd->singleton ();
3325 if (newd->test.kind == rtx_test::SET_OP
3326 || newd->test.kind == rtx_test::ACCEPT)
3327 break;
3329 /* The target of TRANS is a subroutine candidate. First recurse
3330 on it to see how big it is after subroutines have been
3331 split out. */
3332 state_size to_size = find_subroutines (type, trans->to, procs);
3333 if (d->next && to_size.depth > MAX_DEPTH)
3334 /* Keeping the target state in the same routine would lead
3335 to an excessive nesting of "if" and "switch" statements.
3336 Split it out into a subroutine so that it can use
3337 inverted tests that return early on failure. */
3338 trans->to = create_subroutine (type, trans->to, procs);
3339 else
3341 size.num_statements += to_size.num_statements;
3342 if (to_size.num_statements < MIN_NUM_STATEMENTS)
3343 /* The target state is too small to be worth splitting.
3344 Keep it in the same routine as S. */
3345 size.depth = MAX (size.depth, to_size.depth);
3346 else
3347 /* Assume for now that we'll keep the target state in the
3348 same routine as S, but record it as a subroutine candidate
3349 if S grows too big. */
3350 candidates.safe_push (subroutine_candidate (trans, to_size));
3354 if (size.num_statements > MAX_NUM_STATEMENTS)
3356 /* S is too big. Sort the subroutine candidates so that bigger ones
3357 are nearer the end. */
3358 candidates.qsort (subroutine_candidate_cmp);
3359 while (!candidates.is_empty ()
3360 && size.num_statements > MAX_NUM_STATEMENTS)
3362 /* Peel off a candidate and force it into a subroutine. */
3363 subroutine_candidate cand = candidates.pop ();
3364 size.num_statements -= cand.second.num_statements;
3365 cand.first->to = create_subroutine (type, cand.first->to, procs);
3368 /* Update the depth for subroutine candidates that we decided not to
3369 split out. */
3370 for (unsigned int i = 0; i < candidates.length (); ++i)
3371 size.depth = MAX (size.depth, candidates[i].second.depth);
3372 size.depth += 1;
3373 return size;
3376 /* Return true if, for all X, PRED (X, MODE) implies that X has mode MODE. */
3378 static bool
3379 safe_predicate_mode (const struct pred_data *pred, machine_mode mode)
3381 /* Scalar integer constants have VOIDmode. */
3382 if (GET_MODE_CLASS (mode) == MODE_INT
3383 && (pred->codes[CONST_INT]
3384 || pred->codes[CONST_DOUBLE]
3385 || pred->codes[CONST_WIDE_INT]))
3386 return false;
3388 return !pred->special && mode != VOIDmode;
3391 /* Fill CODES with the set of codes that could be matched by PRED. */
3393 static void
3394 get_predicate_codes (const struct pred_data *pred, int_set *codes)
3396 for (int i = 0; i < NUM_TRUE_RTX_CODE; ++i)
3397 if (!pred || pred->codes[i])
3398 codes->safe_push (i);
3401 /* Return true if the first path through D1 tests the same thing as D2. */
3403 static bool
3404 has_same_test_p (decision *d1, decision *d2)
3408 if (d1->test == d2->test)
3409 return true;
3410 d1 = d1->first->to->first;
3412 while (d1);
3413 return false;
3416 /* Return true if D1 and D2 cannot match the same rtx. All states reachable
3417 from D2 have single decisions and all those decisions have single
3418 transitions. */
3420 static bool
3421 mutually_exclusive_p (decision *d1, decision *d2)
3423 /* If one path through D1 fails to test the same thing as D2, assume
3424 that D2's test could be true for D1 and look for a later, more useful,
3425 test. This isn't as expensive as it looks in practice. */
3426 while (!has_same_test_p (d1, d2))
3428 d2 = d2->singleton ()->to->singleton ();
3429 if (!d2)
3430 return false;
3432 if (d1->test == d2->test)
3434 /* Look for any transitions from D1 that have the same labels as
3435 the transition from D2. */
3436 transition *trans2 = d2->singleton ();
3437 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3439 int_set::iterator i1 = trans1->labels.begin ();
3440 int_set::iterator end1 = trans1->labels.end ();
3441 int_set::iterator i2 = trans2->labels.begin ();
3442 int_set::iterator end2 = trans2->labels.end ();
3443 while (i1 != end1 && i2 != end2)
3444 if (*i1 < *i2)
3445 ++i1;
3446 else if (*i2 < *i1)
3447 ++i2;
3448 else
3450 /* TRANS1 has some labels in common with TRANS2. Assume
3451 that D1 and D2 could match the same rtx if the target
3452 of TRANS1 could match the same rtx as D2. */
3453 for (decision *subd1 = trans1->to->first;
3454 subd1; subd1 = subd1->next)
3455 if (!mutually_exclusive_p (subd1, d2))
3456 return false;
3457 break;
3460 return true;
3462 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3463 for (decision *subd1 = trans1->to->first; subd1; subd1 = subd1->next)
3464 if (!mutually_exclusive_p (subd1, d2))
3465 return false;
3466 return true;
3469 /* Try to merge S2's decision into D1, given that they have the same test.
3470 Fail only if EXCLUDE is nonnull and the new transition would have the
3471 same labels as *EXCLUDE. When returning true, set *NEXT_S1, *NEXT_S2
3472 and *NEXT_EXCLUDE as for merge_into_state_1, or set *NEXT_S2 to null
3473 if the merge is complete. */
3475 static bool
3476 merge_into_decision (decision *d1, state *s2, const int_set *exclude,
3477 state **next_s1, state **next_s2,
3478 const int_set **next_exclude)
3480 decision *d2 = s2->singleton ();
3481 transition *trans2 = d2->singleton ();
3483 /* Get a list of the transitions that intersect TRANS2. */
3484 auto_vec <transition *, 32> intersecting;
3485 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3487 int_set::iterator i1 = trans1->labels.begin ();
3488 int_set::iterator end1 = trans1->labels.end ();
3489 int_set::iterator i2 = trans2->labels.begin ();
3490 int_set::iterator end2 = trans2->labels.end ();
3491 bool trans1_is_subset = true;
3492 bool trans2_is_subset = true;
3493 bool intersect_p = false;
3494 while (i1 != end1 && i2 != end2)
3495 if (*i1 < *i2)
3497 trans1_is_subset = false;
3498 ++i1;
3500 else if (*i2 < *i1)
3502 trans2_is_subset = false;
3503 ++i2;
3505 else
3507 intersect_p = true;
3508 ++i1;
3509 ++i2;
3511 if (i1 != end1)
3512 trans1_is_subset = false;
3513 if (i2 != end2)
3514 trans2_is_subset = false;
3515 if (trans1_is_subset && trans2_is_subset)
3517 /* There's already a transition that matches exactly.
3518 Merge the target states. */
3519 trans1->optional &= trans2->optional;
3520 *next_s1 = trans1->to;
3521 *next_s2 = trans2->to;
3522 *next_exclude = 0;
3523 return true;
3525 if (trans2_is_subset)
3527 /* TRANS1 has all the labels that TRANS2 needs. Merge S2 into
3528 the target of TRANS1, but (to avoid infinite recursion)
3529 make sure that we don't end up creating another transition
3530 like TRANS1. */
3531 *next_s1 = trans1->to;
3532 *next_s2 = s2;
3533 *next_exclude = &trans1->labels;
3534 return true;
3536 if (intersect_p)
3537 intersecting.safe_push (trans1);
3540 if (intersecting.is_empty ())
3542 /* No existing labels intersect the new ones. We can just add
3543 TRANS2 itself. */
3544 d1->push_back (d2->release ());
3545 *next_s1 = 0;
3546 *next_s2 = 0;
3547 *next_exclude = 0;
3548 return true;
3551 /* Take the union of the labels in INTERSECTING and TRANS2. Store the
3552 result in COMBINED and use NEXT as a temporary. */
3553 int_set tmp1 = trans2->labels, tmp2;
3554 int_set *combined = &tmp1, *next = &tmp2;
3555 for (unsigned int i = 0; i < intersecting.length (); ++i)
3557 transition *trans1 = intersecting[i];
3558 next->truncate (0);
3559 next->safe_grow (trans1->labels.length () + combined->length ());
3560 int_set::iterator end
3561 = std::set_union (trans1->labels.begin (), trans1->labels.end (),
3562 combined->begin (), combined->end (),
3563 next->begin ());
3564 next->truncate (end - next->begin ());
3565 std::swap (next, combined);
3568 /* Stop now if we've been told not to create a transition with these
3569 labels. */
3570 if (exclude && *combined == *exclude)
3571 return false;
3573 /* Get the transition that should carry the new labels. */
3574 transition *new_trans = intersecting[0];
3575 if (intersecting.length () == 1)
3577 /* We're merging with one existing transition whose labels are a
3578 subset of those required. If both transitions are optional,
3579 we can just expand the set of labels so that it's suitable
3580 for both transitions. It isn't worth preserving the original
3581 transitions since we know that they can't be merged; we would
3582 need to backtrack to S2 if TRANS1->to fails. In contrast,
3583 we might be able to merge the targets of the transitions
3584 without any backtracking.
3586 If instead the existing transition is not optional, ensure that
3587 all target decisions are suitably protected. Some decisions
3588 might already have a more specific requirement than NEW_TRANS,
3589 in which case there's no point testing NEW_TRANS as well. E.g. this
3590 would have happened if a test for an (eq ...) rtx had been
3591 added to a decision that tested whether the code is suitable
3592 for comparison_operator. The original comparison_operator
3593 transition would have been non-optional and the (eq ...) test
3594 would be performed by a second decision in the target of that
3595 transition.
3597 The remaining case -- keeping the original optional transition
3598 when adding a non-optional TRANS2 -- is a wash. Preserving
3599 the optional transition only helps if we later merge another
3600 state S3 that is mutually exclusive with S2 and whose labels
3601 belong to *COMBINED - TRANS1->labels. We can then test the
3602 original NEW_TRANS and S3 in the same decision. We keep the
3603 optional transition around for that case, but it occurs very
3604 rarely. */
3605 gcc_assert (new_trans->labels != *combined);
3606 if (!new_trans->optional || !trans2->optional)
3608 decision *start = 0;
3609 for (decision *end = new_trans->to->first; end; end = end->next)
3611 if (!start && end->test != d1->test)
3612 /* END belongs to a range of decisions that need to be
3613 protected by NEW_TRANS. */
3614 start = end;
3615 if (start && (!end->next || end->next->test == d1->test))
3617 /* Protect [START, END] with NEW_TRANS. The decisions
3618 move to NEW_S and NEW_D becomes part of NEW_TRANS->to. */
3619 state *new_s = new state;
3620 decision *new_d = new decision (d1->test);
3621 new_d->push_back (new transition (new_trans->labels, new_s,
3622 new_trans->optional));
3623 state::range r (start, end);
3624 new_trans->to->replace (r, new_d);
3625 new_s->push_back (r);
3627 /* Continue with an empty range. */
3628 start = 0;
3630 /* Continue from the decision after NEW_D. */
3631 end = new_d;
3635 new_trans->optional = true;
3636 new_trans->labels = *combined;
3638 else
3640 /* We're merging more than one existing transition together.
3641 Those transitions are successfully dividing the matching space
3642 and so we want to preserve them, even if they're optional.
3644 Create a new transition with the union set of labels and make
3645 it go to a state that has the original transitions. */
3646 decision *new_d = new decision (d1->test);
3647 for (unsigned int i = 0; i < intersecting.length (); ++i)
3648 new_d->push_back (d1->remove (intersecting[i]));
3650 state *new_s = new state;
3651 new_s->push_back (new_d);
3653 new_trans = new transition (*combined, new_s, true);
3654 d1->push_back (new_trans);
3657 /* We now have an optional transition with labels *COMBINED. Decide
3658 whether we can use it as TRANS2 or whether we need to merge S2
3659 into the target of NEW_TRANS. */
3660 gcc_assert (new_trans->optional);
3661 if (new_trans->labels == trans2->labels)
3663 /* NEW_TRANS matches TRANS2. Just merge the target states. */
3664 new_trans->optional = trans2->optional;
3665 *next_s1 = new_trans->to;
3666 *next_s2 = trans2->to;
3667 *next_exclude = 0;
3669 else
3671 /* Try to merge TRANS2 into the target of the overlapping transition,
3672 but (to prevent infinite recursion or excessive redundancy) without
3673 creating another transition of the same type. */
3674 *next_s1 = new_trans->to;
3675 *next_s2 = s2;
3676 *next_exclude = &new_trans->labels;
3678 return true;
3681 /* Make progress in merging S2 into S1, given that each state in S2
3682 has a single decision. If EXCLUDE is nonnull, avoid creating a new
3683 transition with the same test as S2's decision and with the labels
3684 in *EXCLUDE.
3686 Return true if there is still work to do. When returning true,
3687 set *NEXT_S1, *NEXT_S2 and *NEXT_EXCLUDE to the values that
3688 S1, S2 and EXCLUDE should have next time round.
3690 If S1 and S2 both match a particular rtx, give priority to S1. */
3692 static bool
3693 merge_into_state_1 (state *s1, state *s2, const int_set *exclude,
3694 state **next_s1, state **next_s2,
3695 const int_set **next_exclude)
3697 decision *d2 = s2->singleton ();
3698 if (decision *d1 = s1->last)
3700 if (d1->test.terminal_p ())
3701 /* D1 is an unconditional return, so S2 can never match. This can
3702 sometimes be a bug in the .md description, but might also happen
3703 if genconditions forces some conditions to true for certain
3704 configurations. */
3705 return false;
3707 /* Go backwards through the decisions in S1, stopping once we find one
3708 that could match the same thing as S2. */
3709 while (d1->prev && mutually_exclusive_p (d1, d2))
3710 d1 = d1->prev;
3712 /* Search forwards from that point, merging D2 into the first
3713 decision we can. */
3714 for (; d1; d1 = d1->next)
3716 /* If S2 performs some optional tests before testing the same thing
3717 as D1, those tests do not help to distinguish D1 and S2, so it's
3718 better to drop them. Search through such optional decisions
3719 until we find something that tests the same thing as D1. */
3720 state *sub_s2 = s2;
3721 for (;;)
3723 decision *sub_d2 = sub_s2->singleton ();
3724 if (d1->test == sub_d2->test)
3726 /* Only apply EXCLUDE if we're testing the same thing
3727 as D2. */
3728 const int_set *sub_exclude = (d2 == sub_d2 ? exclude : 0);
3730 /* Try to merge SUB_S2 into D1. This can only fail if
3731 it would involve creating a new transition with
3732 labels SUB_EXCLUDE. */
3733 if (merge_into_decision (d1, sub_s2, sub_exclude,
3734 next_s1, next_s2, next_exclude))
3735 return *next_s2 != 0;
3737 /* Can't merge with D1; try a later decision. */
3738 break;
3740 transition *sub_trans2 = sub_d2->singleton ();
3741 if (!sub_trans2->optional)
3742 /* Can't merge with D1; try a later decision. */
3743 break;
3744 sub_s2 = sub_trans2->to;
3749 /* We can't merge D2 with any existing decision. Just add it to the end. */
3750 s1->push_back (s2->release ());
3751 return false;
3754 /* Merge S2 into S1. If they both match a particular rtx, give
3755 priority to S1. Each state in S2 has a single decision. */
3757 static void
3758 merge_into_state (state *s1, state *s2)
3760 const int_set *exclude = 0;
3761 while (s2 && merge_into_state_1 (s1, s2, exclude, &s1, &s2, &exclude))
3762 continue;
3765 /* Pairs a pattern that needs to be matched with the rtx position at
3766 which the pattern should occur. */
3767 struct pattern_pos {
3768 pattern_pos () {}
3769 pattern_pos (rtx, position *);
3771 rtx pattern;
3772 position *pos;
3775 pattern_pos::pattern_pos (rtx pattern_in, position *pos_in)
3776 : pattern (pattern_in), pos (pos_in)
3779 /* Compare entries according to their depth-first order. There shouldn't
3780 be two entries at the same position. */
3782 bool
3783 operator < (const pattern_pos &e1, const pattern_pos &e2)
3785 int diff = compare_positions (e1.pos, e2.pos);
3786 gcc_assert (diff != 0 || e1.pattern == e2.pattern);
3787 return diff < 0;
3790 /* Return the name of the predicate matched by MATCH_RTX. */
3792 static const char *
3793 predicate_name (rtx match_rtx)
3795 if (GET_CODE (match_rtx) == MATCH_SCRATCH)
3796 return "scratch_operand";
3797 else
3798 return XSTR (match_rtx, 1);
3801 /* Add new decisions to S that check whether the rtx at position POS
3802 matches PATTERN. Return the state that is reached in that case.
3803 TOP_PATTERN is the overall pattern, as passed to match_pattern_1. */
3805 static state *
3806 match_pattern_2 (state *s, md_rtx_info *info, position *pos, rtx pattern)
3808 auto_vec <pattern_pos, 32> worklist;
3809 auto_vec <pattern_pos, 32> pred_and_mode_tests;
3810 auto_vec <pattern_pos, 32> dup_tests;
3812 worklist.safe_push (pattern_pos (pattern, pos));
3813 while (!worklist.is_empty ())
3815 pattern_pos next = worklist.pop ();
3816 pattern = next.pattern;
3817 pos = next.pos;
3818 unsigned int reverse_s = worklist.length ();
3820 enum rtx_code code = GET_CODE (pattern);
3821 switch (code)
3823 case MATCH_OP_DUP:
3824 case MATCH_DUP:
3825 case MATCH_PAR_DUP:
3826 /* Add a test that the rtx matches the earlier one, but only
3827 after the structure and predicates have been checked. */
3828 dup_tests.safe_push (pattern_pos (pattern, pos));
3830 /* Use the same code check as the original operand. */
3831 pattern = find_operand (info->def, XINT (pattern, 0), NULL_RTX);
3832 /* Fall through. */
3834 case MATCH_PARALLEL:
3835 case MATCH_OPERAND:
3836 case MATCH_SCRATCH:
3837 case MATCH_OPERATOR:
3839 const char *pred_name = predicate_name (pattern);
3840 const struct pred_data *pred = 0;
3841 if (pred_name[0] != 0)
3843 pred = lookup_predicate (pred_name);
3844 /* Only report errors once per rtx. */
3845 if (code == GET_CODE (pattern))
3847 if (!pred)
3848 error_at (info->loc, "unknown predicate '%s' used in %s",
3849 pred_name, GET_RTX_NAME (code));
3850 else if (code == MATCH_PARALLEL
3851 && pred->singleton != PARALLEL)
3852 error_at (info->loc, "predicate '%s' used in"
3853 " match_parallel does not allow only PARALLEL",
3854 pred->name);
3858 if (code == MATCH_PARALLEL || code == MATCH_PAR_DUP)
3860 /* Check that we have a parallel with enough elements. */
3861 s = add_decision (s, rtx_test::code (pos), PARALLEL, false);
3862 int min_len = XVECLEN (pattern, 2);
3863 s = add_decision (s, rtx_test::veclen_ge (pos, min_len),
3864 true, false);
3866 else
3868 /* Check that the rtx has one of codes accepted by the
3869 predicate. This is necessary when matching suboperands
3870 of a MATCH_OPERATOR or MATCH_OP_DUP, since we can't
3871 call XEXP (X, N) without checking that X has at least
3872 N+1 operands. */
3873 int_set codes;
3874 get_predicate_codes (pred, &codes);
3875 bool need_codes = (pred
3876 && (code == MATCH_OPERATOR
3877 || code == MATCH_OP_DUP));
3878 s = add_decision (s, rtx_test::code (pos), codes, !need_codes);
3881 /* Postpone the predicate check until we've checked the rest
3882 of the rtx structure. */
3883 if (code == GET_CODE (pattern))
3884 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
3886 /* If we need to match suboperands, add them to the worklist. */
3887 if (code == MATCH_OPERATOR || code == MATCH_PARALLEL)
3889 position **subpos_ptr;
3890 enum position_type pos_type;
3891 int i;
3892 if (code == MATCH_OPERATOR || code == MATCH_OP_DUP)
3894 pos_type = POS_XEXP;
3895 subpos_ptr = &pos->xexps;
3896 i = (code == MATCH_OPERATOR ? 2 : 1);
3898 else
3900 pos_type = POS_XVECEXP0;
3901 subpos_ptr = &pos->xvecexp0s;
3902 i = 2;
3904 for (int j = 0; j < XVECLEN (pattern, i); ++j)
3906 position *subpos = next_position (subpos_ptr, pos,
3907 pos_type, j);
3908 worklist.safe_push (pattern_pos (XVECEXP (pattern, i, j),
3909 subpos));
3910 subpos_ptr = &subpos->next;
3913 break;
3916 default:
3918 /* Check that the rtx has the right code. */
3919 s = add_decision (s, rtx_test::code (pos), code, false);
3921 /* Queue a test for the mode if one is specified. */
3922 if (GET_MODE (pattern) != VOIDmode)
3923 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
3925 /* Push subrtxes onto the worklist. Match nonrtx operands now. */
3926 const char *fmt = GET_RTX_FORMAT (code);
3927 position **subpos_ptr = &pos->xexps;
3928 for (size_t i = 0; fmt[i]; ++i)
3930 position *subpos = next_position (subpos_ptr, pos,
3931 POS_XEXP, i);
3932 switch (fmt[i])
3934 case 'e': case 'u':
3935 worklist.safe_push (pattern_pos (XEXP (pattern, i),
3936 subpos));
3937 break;
3939 case 'E':
3941 /* Make sure the vector has the right number of
3942 elements. */
3943 int length = XVECLEN (pattern, i);
3944 s = add_decision (s, rtx_test::veclen (pos),
3945 length, false);
3947 position **subpos2_ptr = &pos->xvecexp0s;
3948 for (int j = 0; j < length; j++)
3950 position *subpos2 = next_position (subpos2_ptr, pos,
3951 POS_XVECEXP0, j);
3952 rtx x = XVECEXP (pattern, i, j);
3953 worklist.safe_push (pattern_pos (x, subpos2));
3954 subpos2_ptr = &subpos2->next;
3956 break;
3959 case 'i':
3960 /* Make sure that XINT (X, I) has the right value. */
3961 s = add_decision (s, rtx_test::int_field (pos, i),
3962 XINT (pattern, i), false);
3963 break;
3965 case 'r':
3966 /* Make sure that REGNO (X) has the right value. */
3967 gcc_assert (i == 0);
3968 s = add_decision (s, rtx_test::regno_field (pos),
3969 REGNO (pattern), false);
3970 break;
3972 case 'w':
3973 /* Make sure that XWINT (X, I) has the right value. */
3974 s = add_decision (s, rtx_test::wide_int_field (pos, i),
3975 XWINT (pattern, 0), false);
3976 break;
3978 case '0':
3979 break;
3981 default:
3982 gcc_unreachable ();
3984 subpos_ptr = &subpos->next;
3987 break;
3989 /* Operands are pushed onto the worklist so that later indices are
3990 nearer the top. That's what we want for SETs, since a SET_SRC
3991 is a better discriminator than a SET_DEST. In other cases it's
3992 usually better to match earlier indices first. This is especially
3993 true of PARALLELs, where the first element tends to be the most
3994 individual. It's also true for commutative operators, where the
3995 canonicalization rules say that the more complex operand should
3996 come first. */
3997 if (code != SET && worklist.length () > reverse_s)
3998 std::reverse (&worklist[0] + reverse_s,
3999 &worklist[0] + worklist.length ());
4002 /* Sort the predicate and mode tests so that they're in depth-first order.
4003 The main goal of this is to put SET_SRC match_operands after SET_DEST
4004 match_operands and after mode checks for the enclosing SET_SRC operators
4005 (such as the mode of a PLUS in an addition instruction). The latter
4006 two types of test can determine the mode exactly, whereas a SET_SRC
4007 match_operand often has to cope with the possibility of the operand
4008 being a modeless constant integer. E.g. something that matches
4009 register_operand (x, SImode) never matches register_operand (x, DImode),
4010 but a const_int that matches immediate_operand (x, SImode) also matches
4011 immediate_operand (x, DImode). The register_operand cases can therefore
4012 be distinguished by a switch on the mode, but the immediate_operand
4013 cases can't. */
4014 if (pred_and_mode_tests.length () > 1)
4015 std::sort (&pred_and_mode_tests[0],
4016 &pred_and_mode_tests[0] + pred_and_mode_tests.length ());
4018 /* Add the mode and predicate tests. */
4019 pattern_pos *e;
4020 unsigned int i;
4021 FOR_EACH_VEC_ELT (pred_and_mode_tests, i, e)
4023 switch (GET_CODE (e->pattern))
4025 case MATCH_PARALLEL:
4026 case MATCH_OPERAND:
4027 case MATCH_SCRATCH:
4028 case MATCH_OPERATOR:
4030 int opno = XINT (e->pattern, 0);
4031 num_operands = MAX (num_operands, opno + 1);
4032 const char *pred_name = predicate_name (e->pattern);
4033 if (pred_name[0])
4035 const struct pred_data *pred = lookup_predicate (pred_name);
4036 /* Check the mode first, to distinguish things like SImode
4037 and DImode register_operands, as described above. */
4038 machine_mode mode = GET_MODE (e->pattern);
4039 if (safe_predicate_mode (pred, mode))
4040 s = add_decision (s, rtx_test::mode (e->pos), mode, true);
4042 /* Assign to operands[] first, so that the rtx usually doesn't
4043 need to be live across the call to the predicate.
4045 This shouldn't cause a problem with dirtying the page,
4046 since we fully expect to assign to operands[] at some point,
4047 and since the caller usually writes to other parts of
4048 recog_data anyway. */
4049 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4050 true, false);
4051 s = add_decision (s, rtx_test::predicate (e->pos, pred, mode),
4052 true, false);
4054 else
4055 /* Historically we've ignored the mode when there's no
4056 predicate. Just set up operands[] unconditionally. */
4057 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4058 true, false);
4059 break;
4062 default:
4063 s = add_decision (s, rtx_test::mode (e->pos),
4064 GET_MODE (e->pattern), false);
4065 break;
4069 /* Finally add rtx_equal_p checks for duplicated operands. */
4070 FOR_EACH_VEC_ELT (dup_tests, i, e)
4071 s = add_decision (s, rtx_test::duplicate (e->pos, XINT (e->pattern, 0)),
4072 true, false);
4073 return s;
4076 /* Add new decisions to S that make it return ACCEPTANCE if:
4078 (1) the rtx doesn't match anything already matched by S
4079 (2) the rtx matches TOP_PATTERN and
4080 (3) the C test required by INFO->def is true
4082 For peephole2, TOP_PATTERN is a SEQUENCE of the instruction patterns
4083 to match, otherwise it is a single instruction pattern. */
4085 static void
4086 match_pattern_1 (state *s, md_rtx_info *info, rtx pattern,
4087 acceptance_type acceptance)
4089 if (acceptance.type == PEEPHOLE2)
4091 /* Match each individual instruction. */
4092 position **subpos_ptr = &peep2_insn_pos_list;
4093 int count = 0;
4094 for (int i = 0; i < XVECLEN (pattern, 0); ++i)
4096 rtx x = XVECEXP (pattern, 0, i);
4097 position *subpos = next_position (subpos_ptr, &root_pos,
4098 POS_PEEP2_INSN, count);
4099 if (count > 0)
4100 s = add_decision (s, rtx_test::peep2_count (count + 1),
4101 true, false);
4102 s = match_pattern_2 (s, info, subpos, x);
4103 subpos_ptr = &subpos->next;
4104 count += 1;
4106 acceptance.u.full.u.match_len = count - 1;
4108 else
4110 /* Make the rtx itself. */
4111 s = match_pattern_2 (s, info, &root_pos, pattern);
4113 /* If the match is only valid when extra clobbers are added,
4114 make sure we're able to pass that information to the caller. */
4115 if (acceptance.type == RECOG && acceptance.u.full.u.num_clobbers)
4116 s = add_decision (s, rtx_test::have_num_clobbers (), true, false);
4119 /* Make sure that the C test is true. */
4120 const char *c_test = get_c_test (info->def);
4121 if (maybe_eval_c_test (c_test) != 1)
4122 s = add_decision (s, rtx_test::c_test (c_test), true, false);
4124 /* Accept the pattern. */
4125 add_decision (s, rtx_test::accept (acceptance), true, false);
4128 /* Like match_pattern_1, but (if merge_states_p) try to merge the
4129 decisions with what's already in S, to reduce the amount of
4130 backtracking. */
4132 static void
4133 match_pattern (state *s, md_rtx_info *info, rtx pattern,
4134 acceptance_type acceptance)
4136 if (merge_states_p)
4138 state root;
4139 /* Add the decisions to a fresh state and then merge the full tree
4140 into the existing one. */
4141 match_pattern_1 (&root, info, pattern, acceptance);
4142 merge_into_state (s, &root);
4144 else
4145 match_pattern_1 (s, info, pattern, acceptance);
4148 /* Begin the output file. */
4150 static void
4151 write_header (void)
4153 puts ("\
4154 /* Generated automatically by the program `genrecog' from the target\n\
4155 machine description file. */\n\
4157 #include \"config.h\"\n\
4158 #include \"system.h\"\n\
4159 #include \"coretypes.h\"\n\
4160 #include \"backend.h\"\n\
4161 #include \"predict.h\"\n\
4162 #include \"rtl.h\"\n\
4163 #include \"tm_p.h\"\n\
4164 #include \"emit-rtl.h\"\n\
4165 #include \"insn-config.h\"\n\
4166 #include \"recog.h\"\n\
4167 #include \"output.h\"\n\
4168 #include \"flags.h\"\n\
4169 #include \"df.h\"\n\
4170 #include \"resource.h\"\n\
4171 #include \"diagnostic-core.h\"\n\
4172 #include \"reload.h\"\n\
4173 #include \"regs.h\"\n\
4174 #include \"tm-constrs.h\"\n\
4175 \n");
4177 puts ("\n\
4178 /* `recog' contains a decision tree that recognizes whether the rtx\n\
4179 X0 is a valid instruction.\n\
4181 recog returns -1 if the rtx is not valid. If the rtx is valid, recog\n\
4182 returns a nonnegative number which is the insn code number for the\n\
4183 pattern that matched. This is the same as the order in the machine\n\
4184 description of the entry that matched. This number can be used as an\n\
4185 index into `insn_data' and other tables.\n");
4186 puts ("\
4187 The third parameter to recog is an optional pointer to an int. If\n\
4188 present, recog will accept a pattern if it matches except for missing\n\
4189 CLOBBER expressions at the end. In that case, the value pointed to by\n\
4190 the optional pointer will be set to the number of CLOBBERs that need\n\
4191 to be added (it should be initialized to zero by the caller). If it");
4192 puts ("\
4193 is set nonzero, the caller should allocate a PARALLEL of the\n\
4194 appropriate size, copy the initial entries, and call add_clobbers\n\
4195 (found in insn-emit.c) to fill in the CLOBBERs.\n\
4198 puts ("\n\
4199 The function split_insns returns 0 if the rtl could not\n\
4200 be split or the split rtl as an INSN list if it can be.\n\
4202 The function peephole2_insns returns 0 if the rtl could not\n\
4203 be matched. If there was a match, the new rtl is returned in an INSN list,\n\
4204 and LAST_INSN will point to the last recognized insn in the old sequence.\n\
4205 */\n\n");
4208 /* Return the C type of a parameter with type TYPE. */
4210 static const char *
4211 parameter_type_string (parameter::type_enum type)
4213 switch (type)
4215 case parameter::UNSET:
4216 break;
4218 case parameter::CODE:
4219 return "rtx_code";
4221 case parameter::MODE:
4222 return "machine_mode";
4224 case parameter::INT:
4225 return "int";
4227 case parameter::UINT:
4228 return "unsigned int";
4230 case parameter::WIDE_INT:
4231 return "HOST_WIDE_INT";
4233 gcc_unreachable ();
4236 /* Return true if ACCEPTANCE requires only a single C statement even in
4237 a backtracking context. */
4239 static bool
4240 single_statement_p (const acceptance_type &acceptance)
4242 if (acceptance.partial_p)
4243 /* We need to handle failures of the subroutine. */
4244 return false;
4245 switch (acceptance.type)
4247 case SUBPATTERN:
4248 case SPLIT:
4249 return true;
4251 case RECOG:
4252 /* False if we need to assign to pnum_clobbers. */
4253 return acceptance.u.full.u.num_clobbers == 0;
4255 case PEEPHOLE2:
4256 /* We need to assign to pmatch_len_ and handle null returns from the
4257 peephole2 routine. */
4258 return false;
4260 gcc_unreachable ();
4263 /* Return the C failure value for a routine of type TYPE. */
4265 static const char *
4266 get_failure_return (routine_type type)
4268 switch (type)
4270 case SUBPATTERN:
4271 case RECOG:
4272 return "-1";
4274 case SPLIT:
4275 case PEEPHOLE2:
4276 return "NULL";
4278 gcc_unreachable ();
4281 /* Indicates whether a block of code always returns or whether it can fall
4282 through. */
4284 enum exit_state {
4285 ES_RETURNED,
4286 ES_FALLTHROUGH
4289 /* Information used while writing out code. */
4291 struct output_state
4293 /* The type of routine that we're generating. */
4294 routine_type type;
4296 /* Maps position ids to xN variable numbers. The entry is only valid if
4297 it is less than the length of VAR_TO_ID, but this holds for every position
4298 tested by a state when writing out that state. */
4299 auto_vec <unsigned int> id_to_var;
4301 /* Maps xN variable numbers to position ids. */
4302 auto_vec <unsigned int> var_to_id;
4304 /* Index N is true if variable xN has already been set. */
4305 auto_vec <bool> seen_vars;
4308 /* Return true if D is a call to a pattern routine and if there is some X
4309 such that the transition for pattern result N goes to a successful return
4310 with code X+N. When returning true, set *BASE_OUT to this X and *COUNT_OUT
4311 to the number of return values. (We know that every PATTERN decision has
4312 a transition for every successful return.) */
4314 static bool
4315 terminal_pattern_p (decision *d, unsigned int *base_out,
4316 unsigned int *count_out)
4318 if (d->test.kind != rtx_test::PATTERN)
4319 return false;
4320 unsigned int base = 0;
4321 unsigned int count = 0;
4322 for (transition *trans = d->first; trans; trans = trans->next)
4324 if (trans->is_param || trans->labels.length () != 1)
4325 return false;
4326 decision *subd = trans->to->singleton ();
4327 if (!subd || subd->test.kind != rtx_test::ACCEPT)
4328 return false;
4329 unsigned int this_base = (subd->test.u.acceptance.u.full.code
4330 - trans->labels[0]);
4331 if (trans == d->first)
4332 base = this_base;
4333 else if (base != this_base)
4334 return false;
4335 count += 1;
4337 *base_out = base;
4338 *count_out = count;
4339 return true;
4342 /* Return true if TEST doesn't test an rtx or if the rtx it tests is
4343 already available in state OS. */
4345 static bool
4346 test_position_available_p (output_state *os, const rtx_test &test)
4348 return (!test.pos
4349 || test.pos_operand >= 0
4350 || os->seen_vars[os->id_to_var[test.pos->id]]);
4353 /* Like printf, but print INDENT spaces at the beginning. */
4355 static void ATTRIBUTE_PRINTF_2
4356 printf_indent (unsigned int indent, const char *format, ...)
4358 va_list ap;
4359 va_start (ap, format);
4360 printf ("%*s", indent, "");
4361 vprintf (format, ap);
4362 va_end (ap);
4365 /* Emit code to initialize the variable associated with POS, if it isn't
4366 already valid in state OS. Indent each line by INDENT spaces. Update
4367 OS with the new state. */
4369 static void
4370 change_state (output_state *os, position *pos, unsigned int indent)
4372 unsigned int var = os->id_to_var[pos->id];
4373 gcc_assert (var < os->var_to_id.length () && os->var_to_id[var] == pos->id);
4374 if (os->seen_vars[var])
4375 return;
4376 switch (pos->type)
4378 case POS_PEEP2_INSN:
4379 printf_indent (indent, "x%d = PATTERN (peep2_next_insn (%d));\n",
4380 var, pos->arg);
4381 break;
4383 case POS_XEXP:
4384 change_state (os, pos->base, indent);
4385 printf_indent (indent, "x%d = XEXP (x%d, %d);\n",
4386 var, os->id_to_var[pos->base->id], pos->arg);
4387 break;
4389 case POS_XVECEXP0:
4390 change_state (os, pos->base, indent);
4391 printf_indent (indent, "x%d = XVECEXP (x%d, 0, %d);\n",
4392 var, os->id_to_var[pos->base->id], pos->arg);
4393 break;
4395 os->seen_vars[var] = true;
4398 /* Print the enumerator constant for CODE -- the upcase version of
4399 the name. */
4401 static void
4402 print_code (enum rtx_code code)
4404 const char *p;
4405 for (p = GET_RTX_NAME (code); *p; p++)
4406 putchar (TOUPPER (*p));
4409 /* Emit a uint64_t as an integer constant expression. We need to take
4410 special care to avoid "decimal constant is so large that it is unsigned"
4411 warnings in the resulting code. */
4413 static void
4414 print_host_wide_int (uint64_t val)
4416 uint64_t min = uint64_t (1) << (HOST_BITS_PER_WIDE_INT - 1);
4417 if (val == min)
4418 printf ("(" HOST_WIDE_INT_PRINT_DEC_C " - 1)", val + 1);
4419 else
4420 printf (HOST_WIDE_INT_PRINT_DEC_C, val);
4423 /* Print the C expression for actual parameter PARAM. */
4425 static void
4426 print_parameter_value (const parameter &param)
4428 if (param.is_param)
4429 printf ("i%d", (int) param.value + 1);
4430 else
4431 switch (param.type)
4433 case parameter::UNSET:
4434 gcc_unreachable ();
4435 break;
4437 case parameter::CODE:
4438 print_code ((enum rtx_code) param.value);
4439 break;
4441 case parameter::MODE:
4442 printf ("%smode", GET_MODE_NAME ((machine_mode) param.value));
4443 break;
4445 case parameter::INT:
4446 printf ("%d", (int) param.value);
4447 break;
4449 case parameter::UINT:
4450 printf ("%u", (unsigned int) param.value);
4451 break;
4453 case parameter::WIDE_INT:
4454 print_host_wide_int (param.value);
4455 break;
4459 /* Print the C expression for the rtx tested by TEST. */
4461 static void
4462 print_test_rtx (output_state *os, const rtx_test &test)
4464 if (test.pos_operand >= 0)
4465 printf ("operands[%d]", test.pos_operand);
4466 else
4467 printf ("x%d", os->id_to_var[test.pos->id]);
4470 /* Print the C expression for non-boolean test TEST. */
4472 static void
4473 print_nonbool_test (output_state *os, const rtx_test &test)
4475 switch (test.kind)
4477 case rtx_test::CODE:
4478 printf ("GET_CODE (");
4479 print_test_rtx (os, test);
4480 printf (")");
4481 break;
4483 case rtx_test::MODE:
4484 printf ("GET_MODE (");
4485 print_test_rtx (os, test);
4486 printf (")");
4487 break;
4489 case rtx_test::VECLEN:
4490 printf ("XVECLEN (");
4491 print_test_rtx (os, test);
4492 printf (", 0)");
4493 break;
4495 case rtx_test::INT_FIELD:
4496 printf ("XINT (");
4497 print_test_rtx (os, test);
4498 printf (", %d)", test.u.opno);
4499 break;
4501 case rtx_test::REGNO_FIELD:
4502 printf ("REGNO (");
4503 print_test_rtx (os, test);
4504 printf (")");
4505 break;
4507 case rtx_test::WIDE_INT_FIELD:
4508 printf ("XWINT (");
4509 print_test_rtx (os, test);
4510 printf (", %d)", test.u.opno);
4511 break;
4513 case rtx_test::PATTERN:
4515 pattern_routine *routine = test.u.pattern->routine;
4516 printf ("pattern%d (", routine->pattern_id);
4517 const char *sep = "";
4518 if (test.pos)
4520 print_test_rtx (os, test);
4521 sep = ", ";
4523 if (routine->insn_p)
4525 printf ("%sinsn", sep);
4526 sep = ", ";
4528 if (routine->pnum_clobbers_p)
4530 printf ("%spnum_clobbers", sep);
4531 sep = ", ";
4533 for (unsigned int i = 0; i < test.u.pattern->params.length (); ++i)
4535 fputs (sep, stdout);
4536 print_parameter_value (test.u.pattern->params[i]);
4537 sep = ", ";
4539 printf (")");
4540 break;
4543 case rtx_test::PEEP2_COUNT:
4544 case rtx_test::VECLEN_GE:
4545 case rtx_test::SAVED_CONST_INT:
4546 case rtx_test::DUPLICATE:
4547 case rtx_test::PREDICATE:
4548 case rtx_test::SET_OP:
4549 case rtx_test::HAVE_NUM_CLOBBERS:
4550 case rtx_test::C_TEST:
4551 case rtx_test::ACCEPT:
4552 gcc_unreachable ();
4556 /* IS_PARAM and LABEL are taken from a transition whose source
4557 decision performs TEST. Print the C code for the label. */
4559 static void
4560 print_label_value (const rtx_test &test, bool is_param, uint64_t value)
4562 print_parameter_value (parameter (transition_parameter_type (test.kind),
4563 is_param, value));
4566 /* If IS_PARAM, print code to compare TEST with the C variable i<VALUE+1>.
4567 If !IS_PARAM, print code to compare TEST with the C constant VALUE.
4568 Test for inequality if INVERT_P, otherwise test for equality. */
4570 static void
4571 print_test (output_state *os, const rtx_test &test, bool is_param,
4572 uint64_t value, bool invert_p)
4574 switch (test.kind)
4576 /* Handle the non-boolean TESTs. */
4577 case rtx_test::CODE:
4578 case rtx_test::MODE:
4579 case rtx_test::VECLEN:
4580 case rtx_test::REGNO_FIELD:
4581 case rtx_test::INT_FIELD:
4582 case rtx_test::WIDE_INT_FIELD:
4583 case rtx_test::PATTERN:
4584 print_nonbool_test (os, test);
4585 printf (" %s ", invert_p ? "!=" : "==");
4586 print_label_value (test, is_param, value);
4587 break;
4589 case rtx_test::SAVED_CONST_INT:
4590 gcc_assert (!is_param && value == 1);
4591 print_test_rtx (os, test);
4592 printf (" %s const_int_rtx[MAX_SAVED_CONST_INT + ",
4593 invert_p ? "!=" : "==");
4594 print_parameter_value (parameter (parameter::INT,
4595 test.u.integer.is_param,
4596 test.u.integer.value));
4597 printf ("]");
4598 break;
4600 case rtx_test::PEEP2_COUNT:
4601 gcc_assert (!is_param && value == 1);
4602 printf ("peep2_current_count %s %d", invert_p ? "<" : ">=",
4603 test.u.min_len);
4604 break;
4606 case rtx_test::VECLEN_GE:
4607 gcc_assert (!is_param && value == 1);
4608 printf ("XVECLEN (");
4609 print_test_rtx (os, test);
4610 printf (", 0) %s %d", invert_p ? "<" : ">=", test.u.min_len);
4611 break;
4613 case rtx_test::PREDICATE:
4614 gcc_assert (!is_param && value == 1);
4615 printf ("%s%s (", invert_p ? "!" : "", test.u.predicate.data->name);
4616 print_test_rtx (os, test);
4617 printf (", ");
4618 print_parameter_value (parameter (parameter::MODE,
4619 test.u.predicate.mode_is_param,
4620 test.u.predicate.mode));
4621 printf (")");
4622 break;
4624 case rtx_test::DUPLICATE:
4625 gcc_assert (!is_param && value == 1);
4626 printf ("%srtx_equal_p (", invert_p ? "!" : "");
4627 print_test_rtx (os, test);
4628 printf (", operands[%d])", test.u.opno);
4629 break;
4631 case rtx_test::HAVE_NUM_CLOBBERS:
4632 gcc_assert (!is_param && value == 1);
4633 printf ("pnum_clobbers %s NULL", invert_p ? "==" : "!=");
4634 break;
4636 case rtx_test::C_TEST:
4637 gcc_assert (!is_param && value == 1);
4638 if (invert_p)
4639 printf ("!");
4640 print_c_condition (test.u.string);
4641 break;
4643 case rtx_test::ACCEPT:
4644 case rtx_test::SET_OP:
4645 gcc_unreachable ();
4649 static exit_state print_decision (output_state *, decision *,
4650 unsigned int, bool);
4652 /* Print code to perform S, indent each line by INDENT spaces.
4653 IS_FINAL is true if there are no fallback decisions to test on failure;
4654 if the state fails then the entire routine fails. */
4656 static exit_state
4657 print_state (output_state *os, state *s, unsigned int indent, bool is_final)
4659 exit_state es = ES_FALLTHROUGH;
4660 for (decision *d = s->first; d; d = d->next)
4661 es = print_decision (os, d, indent, is_final && !d->next);
4662 if (es != ES_RETURNED && is_final)
4664 printf_indent (indent, "return %s;\n", get_failure_return (os->type));
4665 es = ES_RETURNED;
4667 return es;
4670 /* Print the code for subroutine call ACCEPTANCE (for which partial_p
4671 is known to be true). Return the C condition that indicates a successful
4672 match. */
4674 static const char *
4675 print_subroutine_call (const acceptance_type &acceptance)
4677 switch (acceptance.type)
4679 case SUBPATTERN:
4680 gcc_unreachable ();
4682 case RECOG:
4683 printf ("recog_%d (x1, insn, pnum_clobbers)",
4684 acceptance.u.subroutine_id);
4685 return ">= 0";
4687 case SPLIT:
4688 printf ("split_%d (x1, insn)", acceptance.u.subroutine_id);
4689 return "!= NULL_RTX";
4691 case PEEPHOLE2:
4692 printf ("peephole2_%d (x1, insn, pmatch_len_)",
4693 acceptance.u.subroutine_id);
4694 return "!= NULL_RTX";
4696 gcc_unreachable ();
4699 /* Print code for the successful match described by ACCEPTANCE.
4700 INDENT and IS_FINAL are as for print_state. */
4702 static exit_state
4703 print_acceptance (const acceptance_type &acceptance, unsigned int indent,
4704 bool is_final)
4706 if (acceptance.partial_p)
4708 /* Defer the rest of the match to a subroutine. */
4709 if (is_final)
4711 printf_indent (indent, "return ");
4712 print_subroutine_call (acceptance);
4713 printf (";\n");
4714 return ES_RETURNED;
4716 else
4718 printf_indent (indent, "res = ");
4719 const char *res_test = print_subroutine_call (acceptance);
4720 printf (";\n");
4721 printf_indent (indent, "if (res %s)\n", res_test);
4722 printf_indent (indent + 2, "return res;\n");
4723 return ES_FALLTHROUGH;
4726 switch (acceptance.type)
4728 case SUBPATTERN:
4729 printf_indent (indent, "return %d;\n", acceptance.u.full.code);
4730 return ES_RETURNED;
4732 case RECOG:
4733 if (acceptance.u.full.u.num_clobbers != 0)
4734 printf_indent (indent, "*pnum_clobbers = %d;\n",
4735 acceptance.u.full.u.num_clobbers);
4736 printf_indent (indent, "return %d; /* %s */\n", acceptance.u.full.code,
4737 get_insn_name (acceptance.u.full.code));
4738 return ES_RETURNED;
4740 case SPLIT:
4741 printf_indent (indent, "return gen_split_%d (insn, operands);\n",
4742 acceptance.u.full.code);
4743 return ES_RETURNED;
4745 case PEEPHOLE2:
4746 printf_indent (indent, "*pmatch_len_ = %d;\n",
4747 acceptance.u.full.u.match_len);
4748 if (is_final)
4750 printf_indent (indent, "return gen_peephole2_%d (insn, operands);\n",
4751 acceptance.u.full.code);
4752 return ES_RETURNED;
4754 else
4756 printf_indent (indent, "res = gen_peephole2_%d (insn, operands);\n",
4757 acceptance.u.full.code);
4758 printf_indent (indent, "if (res != NULL_RTX)\n");
4759 printf_indent (indent + 2, "return res;\n");
4760 return ES_FALLTHROUGH;
4763 gcc_unreachable ();
4766 /* Print code to perform D. INDENT and IS_FINAL are as for print_state. */
4768 static exit_state
4769 print_decision (output_state *os, decision *d, unsigned int indent,
4770 bool is_final)
4772 uint64_t label;
4773 unsigned int base, count;
4775 /* Make sure the rtx under test is available either in operands[] or
4776 in an xN variable. */
4777 if (d->test.pos && d->test.pos_operand < 0)
4778 change_state (os, d->test.pos, indent);
4780 /* Look for cases where a pattern routine P1 calls another pattern routine
4781 P2 and where P1 returns X + BASE whenever P2 returns X. If IS_FINAL
4782 is true and BASE is zero we can simply use:
4784 return patternN (...);
4786 Otherwise we can use:
4788 res = patternN (...);
4789 if (res >= 0)
4790 return res + BASE;
4792 However, if BASE is nonzero and patternN only returns 0 or -1,
4793 the usual "return BASE;" is better than "return res + BASE;".
4794 If BASE is zero, "return res;" should be better than "return 0;",
4795 since no assignment to the return register is required. */
4796 if (os->type == SUBPATTERN
4797 && terminal_pattern_p (d, &base, &count)
4798 && (base == 0 || count > 1))
4800 if (is_final && base == 0)
4802 printf_indent (indent, "return ");
4803 print_nonbool_test (os, d->test);
4804 printf ("; /* [-1, %d] */\n", count - 1);
4805 return ES_RETURNED;
4807 else
4809 printf_indent (indent, "res = ");
4810 print_nonbool_test (os, d->test);
4811 printf (";\n");
4812 printf_indent (indent, "if (res >= 0)\n");
4813 printf_indent (indent + 2, "return res");
4814 if (base != 0)
4815 printf (" + %d", base);
4816 printf ("; /* [%d, %d] */\n", base, base + count - 1);
4817 return ES_FALLTHROUGH;
4820 else if (d->test.kind == rtx_test::ACCEPT)
4821 return print_acceptance (d->test.u.acceptance, indent, is_final);
4822 else if (d->test.kind == rtx_test::SET_OP)
4824 printf_indent (indent, "operands[%d] = ", d->test.u.opno);
4825 print_test_rtx (os, d->test);
4826 printf (";\n");
4827 return print_state (os, d->singleton ()->to, indent, is_final);
4829 /* Handle decisions with a single transition and a single transition
4830 label. */
4831 else if (d->if_statement_p (&label))
4833 transition *trans = d->singleton ();
4834 if (mark_optional_transitions_p && trans->optional)
4835 printf_indent (indent, "/* OPTIONAL IF */\n");
4837 /* Print the condition associated with TRANS. Invert it if IS_FINAL,
4838 so that we return immediately on failure and fall through on
4839 success. */
4840 printf_indent (indent, "if (");
4841 print_test (os, d->test, trans->is_param, label, is_final);
4843 /* Look for following states that would be handled by this code
4844 on recursion. If they don't need any preparatory statements,
4845 include them in the current "if" statement rather than creating
4846 a new one. */
4847 for (;;)
4849 d = trans->to->singleton ();
4850 if (!d
4851 || d->test.kind == rtx_test::ACCEPT
4852 || d->test.kind == rtx_test::SET_OP
4853 || !d->if_statement_p (&label)
4854 || !test_position_available_p (os, d->test))
4855 break;
4856 trans = d->first;
4857 printf ("\n");
4858 if (mark_optional_transitions_p && trans->optional)
4859 printf_indent (indent + 4, "/* OPTIONAL IF */\n");
4860 printf_indent (indent + 4, "%s ", is_final ? "||" : "&&");
4861 print_test (os, d->test, trans->is_param, label, is_final);
4863 printf (")\n");
4865 /* Print the conditional code with INDENT + 2 and the fallthrough
4866 code with indent INDENT. */
4867 state *to = trans->to;
4868 if (is_final)
4870 /* We inverted the condition above, so return failure in the
4871 "if" body and fall through to the target of the transition. */
4872 printf_indent (indent + 2, "return %s;\n",
4873 get_failure_return (os->type));
4874 return print_state (os, to, indent, is_final);
4876 else if (to->singleton ()
4877 && to->first->test.kind == rtx_test::ACCEPT
4878 && single_statement_p (to->first->test.u.acceptance))
4880 /* The target of the transition is a simple "return" statement.
4881 It doesn't need any braces and doesn't fall through. */
4882 if (print_acceptance (to->first->test.u.acceptance,
4883 indent + 2, true) != ES_RETURNED)
4884 gcc_unreachable ();
4885 return ES_FALLTHROUGH;
4887 else
4889 /* The general case. Output code for the target of the transition
4890 in braces. This will not invalidate any of the xN variables
4891 that are already valid, but we mustn't rely on any that are
4892 set by the "if" body. */
4893 auto_vec <bool, 32> old_seen;
4894 old_seen.safe_splice (os->seen_vars);
4896 printf_indent (indent + 2, "{\n");
4897 print_state (os, trans->to, indent + 4, is_final);
4898 printf_indent (indent + 2, "}\n");
4900 os->seen_vars.truncate (0);
4901 os->seen_vars.splice (old_seen);
4902 return ES_FALLTHROUGH;
4905 else
4907 /* Output the decision as a switch statement. */
4908 printf_indent (indent, "switch (");
4909 print_nonbool_test (os, d->test);
4910 printf (")\n");
4912 /* Each case statement starts with the same set of valid variables.
4913 These are also the only variables will be valid on fallthrough. */
4914 auto_vec <bool, 32> old_seen;
4915 old_seen.safe_splice (os->seen_vars);
4917 printf_indent (indent + 2, "{\n");
4918 for (transition *trans = d->first; trans; trans = trans->next)
4920 gcc_assert (!trans->is_param);
4921 if (mark_optional_transitions_p && trans->optional)
4922 printf_indent (indent + 2, "/* OPTIONAL CASE */\n");
4923 for (int_set::iterator j = trans->labels.begin ();
4924 j != trans->labels.end (); ++j)
4926 printf_indent (indent + 2, "case ");
4927 print_label_value (d->test, trans->is_param, *j);
4928 printf (":\n");
4930 if (print_state (os, trans->to, indent + 4, is_final))
4932 /* The state can fall through. Add an explicit break. */
4933 gcc_assert (!is_final);
4934 printf_indent (indent + 4, "break;\n");
4936 printf ("\n");
4938 /* Restore the original set of valid variables. */
4939 os->seen_vars.truncate (0);
4940 os->seen_vars.splice (old_seen);
4942 /* Add a default case. */
4943 printf_indent (indent + 2, "default:\n");
4944 if (is_final)
4945 printf_indent (indent + 4, "return %s;\n",
4946 get_failure_return (os->type));
4947 else
4948 printf_indent (indent + 4, "break;\n");
4949 printf_indent (indent + 2, "}\n");
4950 return is_final ? ES_RETURNED : ES_FALLTHROUGH;
4954 /* Make sure that OS has a position variable for POS. ROOT_P is true if
4955 POS is the root position for the routine. */
4957 static void
4958 assign_position_var (output_state *os, position *pos, bool root_p)
4960 unsigned int idx = os->id_to_var[pos->id];
4961 if (idx < os->var_to_id.length () && os->var_to_id[idx] == pos->id)
4962 return;
4963 if (!root_p && pos->type != POS_PEEP2_INSN)
4964 assign_position_var (os, pos->base, false);
4965 os->id_to_var[pos->id] = os->var_to_id.length ();
4966 os->var_to_id.safe_push (pos->id);
4969 /* Make sure that OS has the position variables required by S. */
4971 static void
4972 assign_position_vars (output_state *os, state *s)
4974 for (decision *d = s->first; d; d = d->next)
4976 /* Positions associated with operands can be read from the
4977 operands[] array. */
4978 if (d->test.pos && d->test.pos_operand < 0)
4979 assign_position_var (os, d->test.pos, false);
4980 for (transition *trans = d->first; trans; trans = trans->next)
4981 assign_position_vars (os, trans->to);
4985 /* Print the open brace and variable definitions for a routine that
4986 implements S. ROOT is the deepest rtx from which S can access all
4987 relevant parts of the first instruction it matches. Initialize OS
4988 so that every relevant position has an rtx variable xN and so that
4989 only ROOT's variable has a valid value. */
4991 static void
4992 print_subroutine_start (output_state *os, state *s, position *root)
4994 printf ("{\n rtx * const operands ATTRIBUTE_UNUSED"
4995 " = &recog_data.operand[0];\n");
4996 os->var_to_id.truncate (0);
4997 os->seen_vars.truncate (0);
4998 if (root)
5000 /* Create a fake entry for position 0 so that an id_to_var of 0
5001 is always invalid. This also makes the xN variables naturally
5002 1-based rather than 0-based. */
5003 os->var_to_id.safe_push (num_positions);
5005 /* Associate ROOT with x1. */
5006 assign_position_var (os, root, true);
5008 /* Assign xN variables to all other relevant positions. */
5009 assign_position_vars (os, s);
5011 /* Output the variable declarations (except for ROOT's, which is
5012 passed in as a parameter). */
5013 unsigned int num_vars = os->var_to_id.length ();
5014 if (num_vars > 2)
5016 for (unsigned int i = 2; i < num_vars; ++i)
5017 /* Print 8 rtx variables to a line. */
5018 printf ("%s x%d",
5019 i == 2 ? " rtx" : (i - 2) % 8 == 0 ? ";\n rtx" : ",", i);
5020 printf (";\n");
5023 /* Say that x1 is valid and the rest aren't. */
5024 os->seen_vars.safe_grow_cleared (num_vars);
5025 os->seen_vars[1] = true;
5027 if (os->type == SUBPATTERN || os->type == RECOG)
5028 printf (" int res ATTRIBUTE_UNUSED;\n");
5029 else
5030 printf (" rtx_insn *res ATTRIBUTE_UNUSED;\n");
5033 /* Output the definition of pattern routine ROUTINE. */
5035 static void
5036 print_pattern (output_state *os, pattern_routine *routine)
5038 printf ("\nstatic int\npattern%d (", routine->pattern_id);
5039 const char *sep = "";
5040 /* Add the top-level rtx parameter, if any. */
5041 if (routine->pos)
5043 printf ("%srtx x1", sep);
5044 sep = ", ";
5046 /* Add the optional parameters. */
5047 if (routine->insn_p)
5049 /* We can't easily tell whether a C condition actually reads INSN,
5050 so add an ATTRIBUTE_UNUSED just in case. */
5051 printf ("%srtx_insn *insn ATTRIBUTE_UNUSED", sep);
5052 sep = ", ";
5054 if (routine->pnum_clobbers_p)
5056 printf ("%sint *pnum_clobbers", sep);
5057 sep = ", ";
5059 /* Add the "i" parameters. */
5060 for (unsigned int i = 0; i < routine->param_types.length (); ++i)
5062 printf ("%s%s i%d", sep,
5063 parameter_type_string (routine->param_types[i]), i + 1);
5064 sep = ", ";
5066 printf (")\n");
5067 os->type = SUBPATTERN;
5068 print_subroutine_start (os, routine->s, routine->pos);
5069 print_state (os, routine->s, 2, true);
5070 printf ("}\n");
5073 /* Output a routine of type TYPE that implements S. PROC_ID is the
5074 number of the subroutine associated with S, or 0 if S is the main
5075 routine. */
5077 static void
5078 print_subroutine (output_state *os, state *s, int proc_id)
5080 /* For now, the top-level "recog" takes a plain "rtx", and performs a
5081 checked cast to "rtx_insn *" for use throughout the rest of the
5082 function and the code it calls. */
5083 const char *insn_param
5084 = proc_id > 0 ? "rtx_insn *insn" : "rtx uncast_insn";
5085 printf ("\n");
5086 switch (os->type)
5088 case SUBPATTERN:
5089 gcc_unreachable ();
5091 case RECOG:
5092 if (proc_id)
5093 printf ("static int\nrecog_%d", proc_id);
5094 else
5095 printf ("int\nrecog");
5096 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5097 "\t%s ATTRIBUTE_UNUSED,\n"
5098 "\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n", insn_param);
5099 break;
5101 case SPLIT:
5102 if (proc_id)
5103 printf ("static rtx_insn *\nsplit_%d", proc_id);
5104 else
5105 printf ("rtx_insn *\nsplit_insns");
5106 printf (" (rtx x1 ATTRIBUTE_UNUSED, rtx_insn *insn ATTRIBUTE_UNUSED)\n");
5107 break;
5109 case PEEPHOLE2:
5110 if (proc_id)
5111 printf ("static rtx_insn *\npeephole2_%d", proc_id);
5112 else
5113 printf ("rtx_insn *\npeephole2_insns");
5114 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5115 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5116 "\tint *pmatch_len_ ATTRIBUTE_UNUSED)\n");
5117 break;
5119 print_subroutine_start (os, s, &root_pos);
5120 if (proc_id == 0)
5122 printf (" recog_data.insn = NULL;\n");
5123 if (os->type == RECOG)
5125 printf (" rtx_insn *insn ATTRIBUTE_UNUSED;\n");
5126 printf (" insn = safe_as_a <rtx_insn *> (uncast_insn);\n");
5129 print_state (os, s, 2, true);
5130 printf ("}\n");
5133 /* Print out a routine of type TYPE that performs ROOT. */
5135 static void
5136 print_subroutine_group (output_state *os, routine_type type, state *root)
5138 os->type = type;
5139 if (use_subroutines_p)
5141 /* Split ROOT up into smaller pieces, both for readability and to
5142 help the compiler. */
5143 auto_vec <state *> subroutines;
5144 find_subroutines (type, root, subroutines);
5146 /* Output the subroutines (but not ROOT itself). */
5147 unsigned int i;
5148 state *s;
5149 FOR_EACH_VEC_ELT (subroutines, i, s)
5150 print_subroutine (os, s, i + 1);
5152 /* Output the main routine. */
5153 print_subroutine (os, root, 0);
5156 /* Return the rtx pattern for the list of rtxes in a define_peephole2. */
5158 static rtx
5159 get_peephole2_pattern (md_rtx_info *info)
5161 int i, j;
5162 rtvec vec = XVEC (info->def, 0);
5163 rtx pattern = rtx_alloc (SEQUENCE);
5164 XVEC (pattern, 0) = rtvec_alloc (GET_NUM_ELEM (vec));
5165 for (i = j = 0; i < GET_NUM_ELEM (vec); i++)
5167 rtx x = RTVEC_ELT (vec, i);
5168 /* Ignore scratch register requirements. */
5169 if (GET_CODE (x) != MATCH_SCRATCH && GET_CODE (x) != MATCH_DUP)
5171 XVECEXP (pattern, 0, j) = x;
5172 j++;
5175 XVECLEN (pattern, 0) = j;
5176 if (j == 0)
5177 error_at (info->loc, "empty define_peephole2");
5178 return pattern;
5181 /* Return true if *PATTERN_PTR is a PARALLEL in which at least one trailing
5182 rtx can be added automatically by add_clobbers. If so, update
5183 *ACCEPTANCE_PTR so that its num_clobbers field contains the number
5184 of such trailing rtxes and update *PATTERN_PTR so that it contains
5185 the pattern without those rtxes. */
5187 static bool
5188 remove_clobbers (acceptance_type *acceptance_ptr, rtx *pattern_ptr)
5190 int i;
5191 rtx new_pattern;
5193 /* Find the last non-clobber in the parallel. */
5194 rtx pattern = *pattern_ptr;
5195 for (i = XVECLEN (pattern, 0); i > 0; i--)
5197 rtx x = XVECEXP (pattern, 0, i - 1);
5198 if (GET_CODE (x) != CLOBBER
5199 || (!REG_P (XEXP (x, 0))
5200 && GET_CODE (XEXP (x, 0)) != MATCH_SCRATCH))
5201 break;
5204 if (i == XVECLEN (pattern, 0))
5205 return false;
5207 /* Build a similar insn without the clobbers. */
5208 if (i == 1)
5209 new_pattern = XVECEXP (pattern, 0, 0);
5210 else
5212 new_pattern = rtx_alloc (PARALLEL);
5213 XVEC (new_pattern, 0) = rtvec_alloc (i);
5214 for (int j = 0; j < i; ++j)
5215 XVECEXP (new_pattern, 0, j) = XVECEXP (pattern, 0, j);
5218 /* Recognize it. */
5219 acceptance_ptr->u.full.u.num_clobbers = XVECLEN (pattern, 0) - i;
5220 *pattern_ptr = new_pattern;
5221 return true;
5225 main (int argc, char **argv)
5227 state insn_root, split_root, peephole2_root;
5229 progname = "genrecog";
5231 if (!init_rtx_reader_args (argc, argv))
5232 return (FATAL_EXIT_CODE);
5234 write_header ();
5236 /* Read the machine description. */
5238 md_rtx_info info;
5239 while (read_md_rtx (&info))
5241 rtx def = info.def;
5243 acceptance_type acceptance;
5244 acceptance.partial_p = false;
5245 acceptance.u.full.code = info.index;
5247 rtx pattern;
5248 switch (GET_CODE (def))
5250 case DEFINE_INSN:
5252 /* Match the instruction in the original .md form. */
5253 acceptance.type = RECOG;
5254 acceptance.u.full.u.num_clobbers = 0;
5255 pattern = add_implicit_parallel (XVEC (def, 1));
5256 validate_pattern (pattern, &info, NULL_RTX, 0);
5257 match_pattern (&insn_root, &info, pattern, acceptance);
5259 /* If the pattern is a PARALLEL with trailing CLOBBERs,
5260 allow recog_for_combine to match without the clobbers. */
5261 if (GET_CODE (pattern) == PARALLEL
5262 && remove_clobbers (&acceptance, &pattern))
5263 match_pattern (&insn_root, &info, pattern, acceptance);
5264 break;
5267 case DEFINE_SPLIT:
5268 acceptance.type = SPLIT;
5269 pattern = add_implicit_parallel (XVEC (def, 0));
5270 validate_pattern (pattern, &info, NULL_RTX, 0);
5271 match_pattern (&split_root, &info, pattern, acceptance);
5273 /* Declare the gen_split routine that we'll call if the
5274 pattern matches. The definition comes from insn-emit.c. */
5275 printf ("extern rtx_insn *gen_split_%d (rtx_insn *, rtx *);\n",
5276 info.index);
5277 break;
5279 case DEFINE_PEEPHOLE2:
5280 acceptance.type = PEEPHOLE2;
5281 pattern = get_peephole2_pattern (&info);
5282 validate_pattern (pattern, &info, NULL_RTX, 0);
5283 match_pattern (&peephole2_root, &info, pattern, acceptance);
5285 /* Declare the gen_peephole2 routine that we'll call if the
5286 pattern matches. The definition comes from insn-emit.c. */
5287 printf ("extern rtx_insn *gen_peephole2_%d (rtx_insn *, rtx *);\n",
5288 info.index);
5289 break;
5291 default:
5292 /* do nothing */;
5296 if (have_error)
5297 return FATAL_EXIT_CODE;
5299 puts ("\n\n");
5301 /* Optimize each routine in turn. */
5302 optimize_subroutine_group ("recog", &insn_root);
5303 optimize_subroutine_group ("split_insns", &split_root);
5304 optimize_subroutine_group ("peephole2_insns", &peephole2_root);
5306 output_state os;
5307 os.id_to_var.safe_grow_cleared (num_positions);
5309 if (use_pattern_routines_p)
5311 /* Look for common patterns and split them out into subroutines. */
5312 auto_vec <merge_state_info> states;
5313 states.safe_push (&insn_root);
5314 states.safe_push (&split_root);
5315 states.safe_push (&peephole2_root);
5316 split_out_patterns (states);
5318 /* Print out the routines that we just created. */
5319 unsigned int i;
5320 pattern_routine *routine;
5321 FOR_EACH_VEC_ELT (patterns, i, routine)
5322 print_pattern (&os, routine);
5325 /* Print out the matching routines. */
5326 print_subroutine_group (&os, RECOG, &insn_root);
5327 print_subroutine_group (&os, SPLIT, &split_root);
5328 print_subroutine_group (&os, PEEPHOLE2, &peephole2_root);
5330 fflush (stdout);
5331 return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);