]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/genrecog.c
Simple patch only add assumed-rank to the list of possible attributes.
[thirdparty/gcc.git] / gcc / genrecog.c
1 /* Generate code from machine description to recognize rtl as insns.
2 Copyright (C) 1987-2020 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
20
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.
25
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).
32
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.
41
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.
45
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.
50
51
52 At a high level, the algorithm used in this file is as follows:
53
54 1. Build up a decision tree for each routine, using the following
55 approach to matching an rtx:
56
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.
62
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.
67
68 - Next check match_dups.
69
70 - Finally check the C condition and (where appropriate) pnum_clobbers.
71
72 2. Try to optimize the tree by removing redundant tests, CSEing tests,
73 folding tests together, etc.
74
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:
81
82 (plus:SI (match_operand:SI 1 "register_operand")
83 (match_operand:SI 2 "register_operand"))
84
85 we can split the associated matching code out into a subroutine.
86 If a pattern contains:
87
88 (minus:DI (match_operand:DI 1 "register_operand")
89 (match_operand:DI 2 "register_operand"))
90
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.
94
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.
98
99 4. Split the matching trees into functions, trying to limit the
100 size of each function to a sensible amount.
101
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.)
104
105 5. Write out C++ code for each function. */
106
107 #include "bconfig.h"
108 #define INCLUDE_ALGORITHM
109 #include "system.h"
110 #include "coretypes.h"
111 #include "tm.h"
112 #include "rtl.h"
113 #include "errors.h"
114 #include "read-md.h"
115 #include "gensupport.h"
116
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
123 };
124 #define NUM_TRUE_RTX_CODE ((int) FIRST_GENERATOR_RTX_CODE)
125 #define GENERATOR_FILE 1
126
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;
136
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;
141
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.
146
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;
152
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;
156
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;
162
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;
169
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;
174
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;
178
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;
184
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;
188
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;
194
195 /* The maximum operand number plus one. */
196 int num_operands;
197
198 /* Ways of obtaining an rtx to be tested. */
199 enum position_type {
200 /* PATTERN (peep2_next_insn (ARG)). */
201 POS_PEEP2_INSN,
202
203 /* XEXP (BASE, ARG). */
204 POS_XEXP,
205
206 /* XVECEXP (BASE, 0, ARG). */
207 POS_XVECEXP0
208 };
209
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
213 {
214 /* The parent rtx. This is the root position for POS_PEEP2_INSNs. */
215 struct position *base;
216
217 /* A position with the same BASE and TYPE, but with the next value
218 of ARG. */
219 struct position *next;
220
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;
225
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;
230
231 /* The type of position. */
232 enum position_type type;
233
234 /* The argument to TYPE (shown as ARG in the position_type comments). */
235 int arg;
236
237 /* The instruction to which the position belongs. */
238 unsigned int insn_id;
239
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;
244
245 /* A unique identifier for this position. */
246 unsigned int id;
247 };
248
249 enum routine_type {
250 SUBPATTERN, RECOG, SPLIT, PEEPHOLE2
251 };
252
253 /* The root position (x0). */
254 static struct position root_pos;
255
256 /* The number of positions created. Also one higher than the maximum
257 position id. */
258 static unsigned int num_positions = 1;
259
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;
263 \f
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. */
268
269 static struct position *
270 next_position (struct position **next_ptr, struct position *base,
271 enum position_type type, int arg)
272 {
273 struct position *pos;
274
275 pos = *next_ptr;
276 if (!pos)
277 {
278 pos = XCNEW (struct position);
279 pos->type = type;
280 pos->arg = arg;
281 if (type == POS_PEEP2_INSN)
282 {
283 pos->base = 0;
284 pos->insn_id = arg;
285 pos->depth = base->depth;
286 }
287 else
288 {
289 pos->base = base;
290 pos->insn_id = base->insn_id;
291 pos->depth = base->depth + 1;
292 }
293 pos->id = num_positions++;
294 *next_ptr = pos;
295 }
296 return pos;
297 }
298
299 /* Compare positions POS1 and POS2 lexicographically. */
300
301 static int
302 compare_positions (struct position *pos1, struct position *pos2)
303 {
304 int diff;
305
306 diff = pos1->depth - pos2->depth;
307 if (diff < 0)
308 do
309 pos2 = pos2->base;
310 while (pos1->depth != pos2->depth);
311 else if (diff > 0)
312 do
313 pos1 = pos1->base;
314 while (pos1->depth != pos2->depth);
315 while (pos1 != pos2)
316 {
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;
322 }
323 return diff;
324 }
325
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. */
329
330 static struct position *
331 common_position (struct position *pos1, struct position *pos2)
332 {
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)
340 {
341 pos1 = pos1->base;
342 pos2 = pos2->base;
343 }
344 return pos1;
345 }
346 \f
347 /* Search for and return operand N, stop when reaching node STOP. */
348
349 static rtx
350 find_operand (rtx pattern, int n, rtx stop)
351 {
352 const char *fmt;
353 RTX_CODE code;
354 int i, j, len;
355 rtx r;
356
357 if (pattern == stop)
358 return stop;
359
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;
367
368 fmt = GET_RTX_FORMAT (code);
369 len = GET_RTX_LENGTH (code);
370 for (i = 0; i < len; i++)
371 {
372 switch (fmt[i])
373 {
374 case 'e': case 'u':
375 if ((r = find_operand (XEXP (pattern, i), n, stop)) != NULL_RTX)
376 return r;
377 break;
378
379 case 'V':
380 if (! XVEC (pattern, i))
381 break;
382 /* Fall through. */
383
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;
390
391 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
392 break;
393
394 default:
395 gcc_unreachable ();
396 }
397 }
398
399 return NULL;
400 }
401
402 /* Search for and return operand M, such that it has a matching
403 constraint for operand N. */
404
405 static rtx
406 find_matching_operand (rtx pattern, int n)
407 {
408 const char *fmt;
409 RTX_CODE code;
410 int i, j, len;
411 rtx r;
412
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;
419
420 fmt = GET_RTX_FORMAT (code);
421 len = GET_RTX_LENGTH (code);
422 for (i = 0; i < len; i++)
423 {
424 switch (fmt[i])
425 {
426 case 'e': case 'u':
427 if ((r = find_matching_operand (XEXP (pattern, i), n)))
428 return r;
429 break;
430
431 case 'V':
432 if (! XVEC (pattern, i))
433 break;
434 /* Fall through. */
435
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;
441
442 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
443 break;
444
445 default:
446 gcc_unreachable ();
447 }
448 }
449
450 return NULL;
451 }
452
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. */
457
458 static bool
459 constraints_supported_in_insn_p (rtx insn)
460 {
461 return !(GET_CODE (insn) == DEFINE_EXPAND
462 || GET_CODE (insn) == DEFINE_SPLIT
463 || GET_CODE (insn) == DEFINE_PEEPHOLE2);
464 }
465
466 /* Return the name of the predicate matched by MATCH_RTX. */
467
468 static const char *
469 predicate_name (rtx match_rtx)
470 {
471 if (GET_CODE (match_rtx) == MATCH_SCRATCH)
472 return "scratch_operand";
473 else
474 return XSTR (match_rtx, 1);
475 }
476
477 /* Return true if OPERAND is a MATCH_OPERAND using a special predicate
478 function. */
479
480 static bool
481 special_predicate_operand_p (rtx operand)
482 {
483 if (GET_CODE (operand) == MATCH_OPERAND)
484 {
485 const char *pred_name = predicate_name (operand);
486 if (pred_name[0] != 0)
487 {
488 const struct pred_data *pred;
489
490 pred = lookup_predicate (pred_name);
491 return pred != NULL && pred->special;
492 }
493 }
494
495 return false;
496 }
497
498 /* Check for various errors in PATTERN, which is part of INFO.
499 SET is nonnull for a destination, and is the complete set pattern.
500 SET_CODE is '=' for normal sets, and '+' within a context that
501 requires in-out constraints. */
502
503 static void
504 validate_pattern (rtx pattern, md_rtx_info *info, rtx set, int set_code)
505 {
506 const char *fmt;
507 RTX_CODE code;
508 size_t i, len;
509 int j;
510
511 code = GET_CODE (pattern);
512 switch (code)
513 {
514 case MATCH_SCRATCH:
515 {
516 const char constraints0 = XSTR (pattern, 1)[0];
517
518 if (!constraints_supported_in_insn_p (info->def))
519 {
520 if (constraints0)
521 {
522 error_at (info->loc, "constraints not supported in %s",
523 GET_RTX_NAME (GET_CODE (info->def)));
524 }
525 return;
526 }
527
528 /* If a MATCH_SCRATCH is used in a context requiring an write-only
529 or read/write register, validate that. */
530 if (set_code == '='
531 && constraints0
532 && constraints0 != '='
533 && constraints0 != '+')
534 {
535 error_at (info->loc, "operand %d missing output reload",
536 XINT (pattern, 0));
537 }
538 return;
539 }
540 case MATCH_DUP:
541 case MATCH_OP_DUP:
542 case MATCH_PAR_DUP:
543 if (find_operand (info->def, XINT (pattern, 0), pattern) == pattern)
544 error_at (info->loc, "operand %i duplicated before defined",
545 XINT (pattern, 0));
546 break;
547 case MATCH_OPERAND:
548 case MATCH_OPERATOR:
549 {
550 const char *pred_name = XSTR (pattern, 1);
551 const struct pred_data *pred;
552 const char *c_test;
553
554 c_test = get_c_test (info->def);
555
556 if (pred_name[0] != 0)
557 {
558 pred = lookup_predicate (pred_name);
559 if (!pred)
560 error_at (info->loc, "unknown predicate '%s'", pred_name);
561 }
562 else
563 pred = 0;
564
565 if (code == MATCH_OPERAND)
566 {
567 const char *constraints = XSTR (pattern, 2);
568 const char constraints0 = constraints[0];
569
570 if (!constraints_supported_in_insn_p (info->def))
571 {
572 if (constraints0)
573 {
574 error_at (info->loc, "constraints not supported in %s",
575 GET_RTX_NAME (GET_CODE (info->def)));
576 }
577 }
578
579 /* A MATCH_OPERAND that is a SET should have an output reload. */
580 else if (set && constraints0)
581 {
582 if (set_code == '+')
583 {
584 if (constraints0 == '+')
585 ;
586 /* If we've only got an output reload for this operand,
587 we'd better have a matching input operand. */
588 else if (constraints0 == '='
589 && find_matching_operand (info->def,
590 XINT (pattern, 0)))
591 ;
592 else
593 error_at (info->loc, "operand %d missing in-out reload",
594 XINT (pattern, 0));
595 }
596 else if (constraints0 != '=' && constraints0 != '+')
597 error_at (info->loc, "operand %d missing output reload",
598 XINT (pattern, 0));
599 }
600
601 /* For matching constraint in MATCH_OPERAND, the digit must be a
602 smaller number than the number of the operand that uses it in the
603 constraint. */
604 while (1)
605 {
606 while (constraints[0]
607 && (constraints[0] == ' ' || constraints[0] == ','))
608 constraints++;
609 if (!constraints[0])
610 break;
611
612 if (constraints[0] >= '0' && constraints[0] <= '9')
613 {
614 int val;
615
616 sscanf (constraints, "%d", &val);
617 if (val >= XINT (pattern, 0))
618 error_at (info->loc, "constraint digit %d is not"
619 " smaller than operand %d",
620 val, XINT (pattern, 0));
621 }
622
623 while (constraints[0] && constraints[0] != ',')
624 constraints++;
625 }
626 }
627
628 /* Allowing non-lvalues in destinations -- particularly CONST_INT --
629 while not likely to occur at runtime, results in less efficient
630 code from insn-recog.c. */
631 if (set && pred && pred->allows_non_lvalue)
632 error_at (info->loc, "destination operand %d allows non-lvalue",
633 XINT (pattern, 0));
634
635 /* A modeless MATCH_OPERAND can be handy when we can check for
636 multiple modes in the c_test. In most other cases, it is a
637 mistake. Only DEFINE_INSN is eligible, since SPLIT and
638 PEEP2 can FAIL within the output pattern. Exclude special
639 predicates, which check the mode themselves. Also exclude
640 predicates that allow only constants. Exclude the SET_DEST
641 of a call instruction, as that is a common idiom. */
642
643 if (GET_MODE (pattern) == VOIDmode
644 && code == MATCH_OPERAND
645 && GET_CODE (info->def) == DEFINE_INSN
646 && pred
647 && !pred->special
648 && pred->allows_non_const
649 && strstr (c_test, "operands") == NULL
650 && ! (set
651 && GET_CODE (set) == SET
652 && GET_CODE (SET_SRC (set)) == CALL))
653 message_at (info->loc, "warning: operand %d missing mode?",
654 XINT (pattern, 0));
655 return;
656 }
657
658 case SET:
659 {
660 machine_mode dmode, smode;
661 rtx dest, src;
662
663 dest = SET_DEST (pattern);
664 src = SET_SRC (pattern);
665
666 /* STRICT_LOW_PART is a wrapper. Its argument is the real
667 destination, and it's mode should match the source. */
668 if (GET_CODE (dest) == STRICT_LOW_PART)
669 dest = XEXP (dest, 0);
670
671 /* Find the referent for a DUP. */
672
673 if (GET_CODE (dest) == MATCH_DUP
674 || GET_CODE (dest) == MATCH_OP_DUP
675 || GET_CODE (dest) == MATCH_PAR_DUP)
676 dest = find_operand (info->def, XINT (dest, 0), NULL);
677
678 if (GET_CODE (src) == MATCH_DUP
679 || GET_CODE (src) == MATCH_OP_DUP
680 || GET_CODE (src) == MATCH_PAR_DUP)
681 src = find_operand (info->def, XINT (src, 0), NULL);
682
683 dmode = GET_MODE (dest);
684 smode = GET_MODE (src);
685
686 /* Mode checking is not performed for special predicates. */
687 if (special_predicate_operand_p (src)
688 || special_predicate_operand_p (dest))
689 ;
690
691 /* The operands of a SET must have the same mode unless one
692 is VOIDmode. */
693 else if (dmode != VOIDmode && smode != VOIDmode && dmode != smode)
694 error_at (info->loc, "mode mismatch in set: %smode vs %smode",
695 GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
696
697 /* If only one of the operands is VOIDmode, and PC or CC0 is
698 not involved, it's probably a mistake. */
699 else if (dmode != smode
700 && GET_CODE (dest) != PC
701 && GET_CODE (dest) != CC0
702 && GET_CODE (src) != PC
703 && GET_CODE (src) != CC0
704 && !CONST_INT_P (src)
705 && !CONST_WIDE_INT_P (src)
706 && GET_CODE (src) != CALL)
707 {
708 const char *which;
709 which = (dmode == VOIDmode ? "destination" : "source");
710 message_at (info->loc, "warning: %s missing a mode?", which);
711 }
712
713 if (dest != SET_DEST (pattern))
714 validate_pattern (dest, info, pattern, '=');
715 validate_pattern (SET_DEST (pattern), info, pattern, '=');
716 validate_pattern (SET_SRC (pattern), info, NULL_RTX, 0);
717 return;
718 }
719
720 case CLOBBER:
721 validate_pattern (SET_DEST (pattern), info, pattern, '=');
722 return;
723
724 case ZERO_EXTRACT:
725 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
726 validate_pattern (XEXP (pattern, 1), info, NULL_RTX, 0);
727 validate_pattern (XEXP (pattern, 2), info, NULL_RTX, 0);
728 return;
729
730 case STRICT_LOW_PART:
731 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
732 return;
733
734 case LABEL_REF:
735 if (GET_MODE (XEXP (pattern, 0)) != VOIDmode)
736 error_at (info->loc, "operand to label_ref %smode not VOIDmode",
737 GET_MODE_NAME (GET_MODE (XEXP (pattern, 0))));
738 break;
739
740 case VEC_SELECT:
741 if (GET_MODE (pattern) != VOIDmode)
742 {
743 machine_mode mode = GET_MODE (pattern);
744 machine_mode imode = GET_MODE (XEXP (pattern, 0));
745 machine_mode emode
746 = VECTOR_MODE_P (mode) ? GET_MODE_INNER (mode) : mode;
747 if (GET_CODE (XEXP (pattern, 1)) == PARALLEL)
748 {
749 int expected = 1;
750 unsigned int nelems;
751 if (VECTOR_MODE_P (mode)
752 && !GET_MODE_NUNITS (mode).is_constant (&expected))
753 error_at (info->loc,
754 "vec_select with variable-sized mode %s",
755 GET_MODE_NAME (mode));
756 else if (XVECLEN (XEXP (pattern, 1), 0) != expected)
757 error_at (info->loc,
758 "vec_select parallel with %d elements, expected %d",
759 XVECLEN (XEXP (pattern, 1), 0), expected);
760 else if (VECTOR_MODE_P (imode)
761 && GET_MODE_NUNITS (imode).is_constant (&nelems))
762 {
763 int i;
764 for (i = 0; i < expected; ++i)
765 if (CONST_INT_P (XVECEXP (XEXP (pattern, 1), 0, i))
766 && (UINTVAL (XVECEXP (XEXP (pattern, 1), 0, i))
767 >= nelems))
768 error_at (info->loc,
769 "out of bounds selector %u in vec_select, "
770 "expected at most %u",
771 (unsigned)
772 UINTVAL (XVECEXP (XEXP (pattern, 1), 0, i)),
773 nelems - 1);
774 }
775 }
776 if (imode != VOIDmode && !VECTOR_MODE_P (imode))
777 error_at (info->loc, "%smode of first vec_select operand is not a "
778 "vector mode", GET_MODE_NAME (imode));
779 else if (imode != VOIDmode && GET_MODE_INNER (imode) != emode)
780 error_at (info->loc, "element mode mismatch between vec_select "
781 "%smode and its operand %smode",
782 GET_MODE_NAME (emode),
783 GET_MODE_NAME (GET_MODE_INNER (imode)));
784 }
785 break;
786
787 default:
788 break;
789 }
790
791 fmt = GET_RTX_FORMAT (code);
792 len = GET_RTX_LENGTH (code);
793 for (i = 0; i < len; i++)
794 {
795 switch (fmt[i])
796 {
797 case 'e': case 'u':
798 validate_pattern (XEXP (pattern, i), info, NULL_RTX, 0);
799 break;
800
801 case 'E':
802 for (j = 0; j < XVECLEN (pattern, i); j++)
803 validate_pattern (XVECEXP (pattern, i, j), info, NULL_RTX, 0);
804 break;
805
806 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
807 break;
808
809 default:
810 gcc_unreachable ();
811 }
812 }
813 }
814 \f
815 /* Simple list structure for items of type T, for use when being part
816 of a list is an inherent property of T. T must have members equivalent
817 to "T *prev, *next;" and a function "void set_parent (list_head <T> *)"
818 to set the parent list. */
819 template <typename T>
820 class list_head
821 {
822 public:
823 /* A range of linked items. */
824 class range
825 {
826 public:
827 range (T *);
828 range (T *, T *);
829
830 T *start, *end;
831 void set_parent (list_head *);
832 };
833
834 list_head ();
835 range release ();
836 void push_back (range);
837 range remove (range);
838 void replace (range, range);
839 T *singleton () const;
840
841 T *first, *last;
842 };
843
844 /* Create a range [START_IN, START_IN]. */
845
846 template <typename T>
847 list_head <T>::range::range (T *start_in) : start (start_in), end (start_in) {}
848
849 /* Create a range [START_IN, END_IN], linked by next and prev fields. */
850
851 template <typename T>
852 list_head <T>::range::range (T *start_in, T *end_in)
853 : start (start_in), end (end_in) {}
854
855 template <typename T>
856 void
857 list_head <T>::range::set_parent (list_head <T> *owner)
858 {
859 for (T *item = start; item != end; item = item->next)
860 item->set_parent (owner);
861 end->set_parent (owner);
862 }
863
864 template <typename T>
865 list_head <T>::list_head () : first (0), last (0) {}
866
867 /* Add R to the end of the list. */
868
869 template <typename T>
870 void
871 list_head <T>::push_back (range r)
872 {
873 if (last)
874 last->next = r.start;
875 else
876 first = r.start;
877 r.start->prev = last;
878 last = r.end;
879 r.set_parent (this);
880 }
881
882 /* Remove R from the list. R remains valid and can be inserted into
883 other lists. */
884
885 template <typename T>
886 typename list_head <T>::range
887 list_head <T>::remove (range r)
888 {
889 if (r.start->prev)
890 r.start->prev->next = r.end->next;
891 else
892 first = r.end->next;
893 if (r.end->next)
894 r.end->next->prev = r.start->prev;
895 else
896 last = r.start->prev;
897 r.start->prev = 0;
898 r.end->next = 0;
899 r.set_parent (0);
900 return r;
901 }
902
903 /* Replace OLDR with NEWR. OLDR remains valid and can be inserted into
904 other lists. */
905
906 template <typename T>
907 void
908 list_head <T>::replace (range oldr, range newr)
909 {
910 newr.start->prev = oldr.start->prev;
911 newr.end->next = oldr.end->next;
912
913 oldr.start->prev = 0;
914 oldr.end->next = 0;
915 oldr.set_parent (0);
916
917 if (newr.start->prev)
918 newr.start->prev->next = newr.start;
919 else
920 first = newr.start;
921 if (newr.end->next)
922 newr.end->next->prev = newr.end;
923 else
924 last = newr.end;
925 newr.set_parent (this);
926 }
927
928 /* Empty the list and return the previous contents as a range that can
929 be inserted into other lists. */
930
931 template <typename T>
932 typename list_head <T>::range
933 list_head <T>::release ()
934 {
935 range r (first, last);
936 first = 0;
937 last = 0;
938 r.set_parent (0);
939 return r;
940 }
941
942 /* If the list contains a single item, return that item, otherwise return
943 null. */
944
945 template <typename T>
946 T *
947 list_head <T>::singleton () const
948 {
949 return first == last ? first : 0;
950 }
951 \f
952 class state;
953
954 /* Describes a possible successful return from a routine. */
955 struct acceptance_type
956 {
957 /* The type of routine we're returning from. */
958 routine_type type : 16;
959
960 /* True if this structure only really represents a partial match,
961 and if we must call a subroutine of type TYPE to complete the match.
962 In this case we'll call the subroutine and, if it succeeds, return
963 whatever the subroutine returned.
964
965 False if this structure presents a full match. */
966 unsigned int partial_p : 1;
967
968 union
969 {
970 /* If PARTIAL_P, this is the number of the subroutine to call. */
971 int subroutine_id;
972
973 /* Valid if !PARTIAL_P. */
974 struct
975 {
976 /* The identifier of the matching pattern. For SUBPATTERNs this
977 value belongs to an ad-hoc routine-specific enum. For the
978 others it's the number of an .md file pattern. */
979 int code;
980 union
981 {
982 /* For RECOG, the number of clobbers that must be added to the
983 pattern in order for it to match CODE. */
984 int num_clobbers;
985
986 /* For PEEPHOLE2, the number of additional instructions that were
987 included in the optimization. */
988 int match_len;
989 } u;
990 } full;
991 } u;
992 };
993
994 bool
995 operator == (const acceptance_type &a, const acceptance_type &b)
996 {
997 if (a.partial_p != b.partial_p)
998 return false;
999 if (a.partial_p)
1000 return a.u.subroutine_id == b.u.subroutine_id;
1001 else
1002 return a.u.full.code == b.u.full.code;
1003 }
1004
1005 bool
1006 operator != (const acceptance_type &a, const acceptance_type &b)
1007 {
1008 return !operator == (a, b);
1009 }
1010
1011 /* Represents a parameter to a pattern routine. */
1012 class parameter
1013 {
1014 public:
1015 /* The C type of parameter. */
1016 enum type_enum {
1017 /* Represents an invalid parameter. */
1018 UNSET,
1019
1020 /* A machine_mode parameter. */
1021 MODE,
1022
1023 /* An rtx_code parameter. */
1024 CODE,
1025
1026 /* An int parameter. */
1027 INT,
1028
1029 /* An unsigned int parameter. */
1030 UINT,
1031
1032 /* A HOST_WIDE_INT parameter. */
1033 WIDE_INT
1034 };
1035
1036 parameter ();
1037 parameter (type_enum, bool, uint64_t);
1038
1039 /* The type of the parameter. */
1040 type_enum type;
1041
1042 /* True if the value passed is variable, false if it is constant. */
1043 bool is_param;
1044
1045 /* If IS_PARAM, this is the number of the variable passed, for an "i%d"
1046 format string. If !IS_PARAM, this is the constant value passed. */
1047 uint64_t value;
1048 };
1049
1050 parameter::parameter ()
1051 : type (UNSET), is_param (false), value (0) {}
1052
1053 parameter::parameter (type_enum type_in, bool is_param_in, uint64_t value_in)
1054 : type (type_in), is_param (is_param_in), value (value_in) {}
1055
1056 bool
1057 operator == (const parameter &param1, const parameter &param2)
1058 {
1059 return (param1.type == param2.type
1060 && param1.is_param == param2.is_param
1061 && param1.value == param2.value);
1062 }
1063
1064 bool
1065 operator != (const parameter &param1, const parameter &param2)
1066 {
1067 return !operator == (param1, param2);
1068 }
1069
1070 /* Represents a routine that matches a partial rtx pattern, returning
1071 an ad-hoc enum value on success and -1 on failure. The routine can
1072 be used by any subroutine type. The match can be parameterized by
1073 things like mode, code and UNSPEC number. */
1074 class pattern_routine
1075 {
1076 public:
1077 /* The state that implements the pattern. */
1078 state *s;
1079
1080 /* The deepest root position from which S can access all the rtxes it needs.
1081 This is NULL if the pattern doesn't need an rtx input, usually because
1082 all matching is done on operands[] instead. */
1083 position *pos;
1084
1085 /* A unique identifier for the routine. */
1086 unsigned int pattern_id;
1087
1088 /* True if the routine takes pnum_clobbers as argument. */
1089 bool pnum_clobbers_p;
1090
1091 /* True if the routine takes the enclosing instruction as argument. */
1092 bool insn_p;
1093
1094 /* The types of the other parameters to the routine, if any. */
1095 auto_vec <parameter::type_enum, MAX_PATTERN_PARAMS> param_types;
1096 };
1097
1098 /* All defined patterns. */
1099 static vec <pattern_routine *> patterns;
1100
1101 /* Represents one use of a pattern routine. */
1102 class pattern_use
1103 {
1104 public:
1105 /* The pattern routine to use. */
1106 pattern_routine *routine;
1107
1108 /* The values to pass as parameters. This vector has the same length
1109 as ROUTINE->PARAM_TYPES. */
1110 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
1111 };
1112
1113 /* Represents a test performed by a decision. */
1114 class rtx_test
1115 {
1116 public:
1117 rtx_test ();
1118
1119 /* The types of test that can be performed. Most of them take as input
1120 an rtx X. Some also take as input a transition label LABEL; the others
1121 are booleans for which the transition label is always "true".
1122
1123 The order of the enum isn't important. */
1124 enum kind_enum {
1125 /* Check GET_CODE (X) == LABEL. */
1126 CODE,
1127
1128 /* Check GET_MODE (X) == LABEL. */
1129 MODE,
1130
1131 /* Check REGNO (X) == LABEL. */
1132 REGNO_FIELD,
1133
1134 /* Check known_eq (SUBREG_BYTE (X), LABEL). */
1135 SUBREG_FIELD,
1136
1137 /* Check XINT (X, u.opno) == LABEL. */
1138 INT_FIELD,
1139
1140 /* Check XWINT (X, u.opno) == LABEL. */
1141 WIDE_INT_FIELD,
1142
1143 /* Check XVECLEN (X, 0) == LABEL. */
1144 VECLEN,
1145
1146 /* Check peep2_current_count >= u.min_len. */
1147 PEEP2_COUNT,
1148
1149 /* Check XVECLEN (X, 0) >= u.min_len. */
1150 VECLEN_GE,
1151
1152 /* Check whether X is a cached const_int with value u.integer. */
1153 SAVED_CONST_INT,
1154
1155 /* Check u.predicate.data (X, u.predicate.mode). */
1156 PREDICATE,
1157
1158 /* Check rtx_equal_p (X, operands[u.opno]). */
1159 DUPLICATE,
1160
1161 /* Check whether X matches pattern u.pattern. */
1162 PATTERN,
1163
1164 /* Check whether pnum_clobbers is nonnull (RECOG only). */
1165 HAVE_NUM_CLOBBERS,
1166
1167 /* Check whether general C test u.string holds. In general the condition
1168 needs access to "insn" and the full operand list. */
1169 C_TEST,
1170
1171 /* Execute operands[u.opno] = X. (Always succeeds.) */
1172 SET_OP,
1173
1174 /* Accept u.acceptance. Always succeeds for SUBPATTERN, RECOG and SPLIT.
1175 May fail for PEEPHOLE2 if the define_peephole2 C code executes FAIL. */
1176 ACCEPT
1177 };
1178
1179 /* The position of rtx X in the above description, relative to the
1180 incoming instruction "insn". The position is null if the test
1181 doesn't take an X as input. */
1182 position *pos;
1183
1184 /* Which element of operands[] already contains POS, or -1 if no element
1185 is known to hold POS. */
1186 int pos_operand;
1187
1188 /* The type of test and its parameters, as described above. */
1189 kind_enum kind;
1190 union
1191 {
1192 int opno;
1193 int min_len;
1194 struct
1195 {
1196 bool is_param;
1197 int value;
1198 } integer;
1199 struct
1200 {
1201 const struct pred_data *data;
1202 /* True if the mode is taken from a machine_mode parameter
1203 to the routine rather than a constant machine_mode. If true,
1204 MODE is the number of the parameter (for an "i%d" format string),
1205 otherwise it is the mode itself. */
1206 bool mode_is_param;
1207 unsigned int mode;
1208 } predicate;
1209 pattern_use *pattern;
1210 const char *string;
1211 acceptance_type acceptance;
1212 } u;
1213
1214 static rtx_test code (position *);
1215 static rtx_test mode (position *);
1216 static rtx_test regno_field (position *);
1217 static rtx_test subreg_field (position *);
1218 static rtx_test int_field (position *, int);
1219 static rtx_test wide_int_field (position *, int);
1220 static rtx_test veclen (position *);
1221 static rtx_test peep2_count (int);
1222 static rtx_test veclen_ge (position *, int);
1223 static rtx_test predicate (position *, const pred_data *, machine_mode);
1224 static rtx_test duplicate (position *, int);
1225 static rtx_test pattern (position *, pattern_use *);
1226 static rtx_test have_num_clobbers ();
1227 static rtx_test c_test (const char *);
1228 static rtx_test set_op (position *, int);
1229 static rtx_test accept (const acceptance_type &);
1230
1231 bool terminal_p () const;
1232 bool single_outcome_p () const;
1233
1234 private:
1235 rtx_test (position *, kind_enum);
1236 };
1237
1238 rtx_test::rtx_test () {}
1239
1240 rtx_test::rtx_test (position *pos_in, kind_enum kind_in)
1241 : pos (pos_in), pos_operand (-1), kind (kind_in) {}
1242
1243 rtx_test
1244 rtx_test::code (position *pos)
1245 {
1246 return rtx_test (pos, rtx_test::CODE);
1247 }
1248
1249 rtx_test
1250 rtx_test::mode (position *pos)
1251 {
1252 return rtx_test (pos, rtx_test::MODE);
1253 }
1254
1255 rtx_test
1256 rtx_test::regno_field (position *pos)
1257 {
1258 rtx_test res (pos, rtx_test::REGNO_FIELD);
1259 return res;
1260 }
1261
1262 rtx_test
1263 rtx_test::subreg_field (position *pos)
1264 {
1265 rtx_test res (pos, rtx_test::SUBREG_FIELD);
1266 return res;
1267 }
1268
1269 rtx_test
1270 rtx_test::int_field (position *pos, int opno)
1271 {
1272 rtx_test res (pos, rtx_test::INT_FIELD);
1273 res.u.opno = opno;
1274 return res;
1275 }
1276
1277 rtx_test
1278 rtx_test::wide_int_field (position *pos, int opno)
1279 {
1280 rtx_test res (pos, rtx_test::WIDE_INT_FIELD);
1281 res.u.opno = opno;
1282 return res;
1283 }
1284
1285 rtx_test
1286 rtx_test::veclen (position *pos)
1287 {
1288 return rtx_test (pos, rtx_test::VECLEN);
1289 }
1290
1291 rtx_test
1292 rtx_test::peep2_count (int min_len)
1293 {
1294 rtx_test res (0, rtx_test::PEEP2_COUNT);
1295 res.u.min_len = min_len;
1296 return res;
1297 }
1298
1299 rtx_test
1300 rtx_test::veclen_ge (position *pos, int min_len)
1301 {
1302 rtx_test res (pos, rtx_test::VECLEN_GE);
1303 res.u.min_len = min_len;
1304 return res;
1305 }
1306
1307 rtx_test
1308 rtx_test::predicate (position *pos, const struct pred_data *data,
1309 machine_mode mode)
1310 {
1311 rtx_test res (pos, rtx_test::PREDICATE);
1312 res.u.predicate.data = data;
1313 res.u.predicate.mode_is_param = false;
1314 res.u.predicate.mode = mode;
1315 return res;
1316 }
1317
1318 rtx_test
1319 rtx_test::duplicate (position *pos, int opno)
1320 {
1321 rtx_test res (pos, rtx_test::DUPLICATE);
1322 res.u.opno = opno;
1323 return res;
1324 }
1325
1326 rtx_test
1327 rtx_test::pattern (position *pos, pattern_use *pattern)
1328 {
1329 rtx_test res (pos, rtx_test::PATTERN);
1330 res.u.pattern = pattern;
1331 return res;
1332 }
1333
1334 rtx_test
1335 rtx_test::have_num_clobbers ()
1336 {
1337 return rtx_test (0, rtx_test::HAVE_NUM_CLOBBERS);
1338 }
1339
1340 rtx_test
1341 rtx_test::c_test (const char *string)
1342 {
1343 rtx_test res (0, rtx_test::C_TEST);
1344 res.u.string = string;
1345 return res;
1346 }
1347
1348 rtx_test
1349 rtx_test::set_op (position *pos, int opno)
1350 {
1351 rtx_test res (pos, rtx_test::SET_OP);
1352 res.u.opno = opno;
1353 return res;
1354 }
1355
1356 rtx_test
1357 rtx_test::accept (const acceptance_type &acceptance)
1358 {
1359 rtx_test res (0, rtx_test::ACCEPT);
1360 res.u.acceptance = acceptance;
1361 return res;
1362 }
1363
1364 /* Return true if the test represents an unconditionally successful match. */
1365
1366 bool
1367 rtx_test::terminal_p () const
1368 {
1369 return kind == rtx_test::ACCEPT && u.acceptance.type != PEEPHOLE2;
1370 }
1371
1372 /* Return true if the test is a boolean that is always true. */
1373
1374 bool
1375 rtx_test::single_outcome_p () const
1376 {
1377 return terminal_p () || kind == rtx_test::SET_OP;
1378 }
1379
1380 bool
1381 operator == (const rtx_test &a, const rtx_test &b)
1382 {
1383 if (a.pos != b.pos || a.kind != b.kind)
1384 return false;
1385 switch (a.kind)
1386 {
1387 case rtx_test::CODE:
1388 case rtx_test::MODE:
1389 case rtx_test::REGNO_FIELD:
1390 case rtx_test::SUBREG_FIELD:
1391 case rtx_test::VECLEN:
1392 case rtx_test::HAVE_NUM_CLOBBERS:
1393 return true;
1394
1395 case rtx_test::PEEP2_COUNT:
1396 case rtx_test::VECLEN_GE:
1397 return a.u.min_len == b.u.min_len;
1398
1399 case rtx_test::INT_FIELD:
1400 case rtx_test::WIDE_INT_FIELD:
1401 case rtx_test::DUPLICATE:
1402 case rtx_test::SET_OP:
1403 return a.u.opno == b.u.opno;
1404
1405 case rtx_test::SAVED_CONST_INT:
1406 return (a.u.integer.is_param == b.u.integer.is_param
1407 && a.u.integer.value == b.u.integer.value);
1408
1409 case rtx_test::PREDICATE:
1410 return (a.u.predicate.data == b.u.predicate.data
1411 && a.u.predicate.mode_is_param == b.u.predicate.mode_is_param
1412 && a.u.predicate.mode == b.u.predicate.mode);
1413
1414 case rtx_test::PATTERN:
1415 return (a.u.pattern->routine == b.u.pattern->routine
1416 && a.u.pattern->params == b.u.pattern->params);
1417
1418 case rtx_test::C_TEST:
1419 return strcmp (a.u.string, b.u.string) == 0;
1420
1421 case rtx_test::ACCEPT:
1422 return a.u.acceptance == b.u.acceptance;
1423 }
1424 gcc_unreachable ();
1425 }
1426
1427 bool
1428 operator != (const rtx_test &a, const rtx_test &b)
1429 {
1430 return !operator == (a, b);
1431 }
1432
1433 /* A simple set of transition labels. Most transitions have a singleton
1434 label, so try to make that case as efficient as possible. */
1435 class int_set : public auto_vec <uint64_t, 1>
1436 {
1437 public:
1438 typedef uint64_t *iterator;
1439
1440 int_set ();
1441 int_set (uint64_t);
1442 int_set (const int_set &);
1443
1444 int_set &operator = (const int_set &);
1445
1446 iterator begin ();
1447 iterator end ();
1448 };
1449
1450 int_set::int_set () : auto_vec<uint64_t, 1> () {}
1451
1452 int_set::int_set (uint64_t label) :
1453 auto_vec<uint64_t, 1> ()
1454 {
1455 safe_push (label);
1456 }
1457
1458 int_set::int_set (const int_set &other) :
1459 auto_vec<uint64_t, 1> ()
1460 {
1461 safe_splice (other);
1462 }
1463
1464 int_set &
1465 int_set::operator = (const int_set &other)
1466 {
1467 truncate (0);
1468 safe_splice (other);
1469 return *this;
1470 }
1471
1472 int_set::iterator
1473 int_set::begin ()
1474 {
1475 return address ();
1476 }
1477
1478 int_set::iterator
1479 int_set::end ()
1480 {
1481 return address () + length ();
1482 }
1483
1484 bool
1485 operator == (const int_set &a, const int_set &b)
1486 {
1487 if (a.length () != b.length ())
1488 return false;
1489 for (unsigned int i = 0; i < a.length (); ++i)
1490 if (a[i] != b[i])
1491 return false;
1492 return true;
1493 }
1494
1495 bool
1496 operator != (const int_set &a, const int_set &b)
1497 {
1498 return !operator == (a, b);
1499 }
1500
1501 class decision;
1502
1503 /* Represents a transition between states, dependent on the result of
1504 a test T. */
1505 class transition
1506 {
1507 public:
1508 transition (const int_set &, state *, bool);
1509
1510 void set_parent (list_head <transition> *);
1511
1512 /* Links to other transitions for T. Always null for boolean tests. */
1513 transition *prev, *next;
1514
1515 /* The transition should be taken when T has one of these values.
1516 E.g. for rtx_test::CODE this is a set of codes, while for booleans like
1517 rtx_test::PREDICATE it is always a singleton "true". The labels are
1518 sorted in ascending order. */
1519 int_set labels;
1520
1521 /* The source decision. */
1522 decision *from;
1523
1524 /* The target state. */
1525 state *to;
1526
1527 /* True if TO would function correctly even if TEST wasn't performed.
1528 E.g. it isn't necessary to check whether GET_MODE (x1) is SImode
1529 before calling register_operand (x1, SImode), since register_operand
1530 performs its own mode check. However, checking GET_MODE can be a cheap
1531 way of disambiguating SImode and DImode register operands. */
1532 bool optional;
1533
1534 /* True if LABELS contains parameter numbers rather than constants.
1535 E.g. if this is true for a rtx_test::CODE, the label is the number
1536 of an rtx_code parameter rather than an rtx_code itself.
1537 LABELS is always a singleton when this variable is true. */
1538 bool is_param;
1539 };
1540
1541 /* Represents a test and the action that should be taken on the result.
1542 If a transition exists for the test outcome, the machine switches
1543 to the transition's target state. If no suitable transition exists,
1544 the machine either falls through to the next decision or, if there are no
1545 more decisions to try, fails the match. */
1546 class decision : public list_head <transition>
1547 {
1548 public:
1549 decision (const rtx_test &);
1550
1551 void set_parent (list_head <decision> *s);
1552 bool if_statement_p (uint64_t * = 0) const;
1553
1554 /* The state to which this decision belongs. */
1555 state *s;
1556
1557 /* Links to other decisions in the same state. */
1558 decision *prev, *next;
1559
1560 /* The test to perform. */
1561 rtx_test test;
1562 };
1563
1564 /* Represents one machine state. For each state the machine tries a list
1565 of decisions, in order, and acts on the first match. It fails without
1566 further backtracking if no decisions match. */
1567 class state : public list_head <decision>
1568 {
1569 public:
1570 void set_parent (list_head <state> *) {}
1571 };
1572
1573 transition::transition (const int_set &labels_in, state *to_in,
1574 bool optional_in)
1575 : prev (0), next (0), labels (labels_in), from (0), to (to_in),
1576 optional (optional_in), is_param (false) {}
1577
1578 /* Set the source decision of the transition. */
1579
1580 void
1581 transition::set_parent (list_head <transition> *from_in)
1582 {
1583 from = static_cast <decision *> (from_in);
1584 }
1585
1586 decision::decision (const rtx_test &test_in)
1587 : prev (0), next (0), test (test_in) {}
1588
1589 /* Set the state to which this decision belongs. */
1590
1591 void
1592 decision::set_parent (list_head <decision> *s_in)
1593 {
1594 s = static_cast <state *> (s_in);
1595 }
1596
1597 /* Return true if the decision has a single transition with a single label.
1598 If so, return the label in *LABEL if nonnull. */
1599
1600 inline bool
1601 decision::if_statement_p (uint64_t *label) const
1602 {
1603 if (singleton () && first->labels.length () == 1)
1604 {
1605 if (label)
1606 *label = first->labels[0];
1607 return true;
1608 }
1609 return false;
1610 }
1611
1612 /* Add to FROM a decision that performs TEST and has a single transition
1613 TRANS. */
1614
1615 static void
1616 add_decision (state *from, const rtx_test &test, transition *trans)
1617 {
1618 decision *d = new decision (test);
1619 from->push_back (d);
1620 d->push_back (trans);
1621 }
1622
1623 /* Add a transition from FROM to a new, empty state that is taken
1624 when TEST == LABELS. OPTIONAL says whether the new transition
1625 should be optional. Return the new state. */
1626
1627 static state *
1628 add_decision (state *from, const rtx_test &test, int_set labels, bool optional)
1629 {
1630 state *to = new state;
1631 add_decision (from, test, new transition (labels, to, optional));
1632 return to;
1633 }
1634
1635 /* Insert a decision before decisions R to make them dependent on
1636 TEST == LABELS. OPTIONAL says whether the new transition should be
1637 optional. */
1638
1639 static decision *
1640 insert_decision_before (state::range r, const rtx_test &test,
1641 const int_set &labels, bool optional)
1642 {
1643 decision *newd = new decision (test);
1644 state *news = new state;
1645 newd->push_back (new transition (labels, news, optional));
1646 r.start->s->replace (r, newd);
1647 news->push_back (r);
1648 return newd;
1649 }
1650
1651 /* Remove any optional transitions from S that turned out not to be useful. */
1652
1653 static void
1654 collapse_optional_decisions (state *s)
1655 {
1656 decision *d = s->first;
1657 while (d)
1658 {
1659 decision *next = d->next;
1660 for (transition *trans = d->first; trans; trans = trans->next)
1661 collapse_optional_decisions (trans->to);
1662 /* A decision with a single optional transition doesn't help
1663 partition the potential matches and so is unlikely to be
1664 worthwhile. In particular, if the decision that performs the
1665 test is the last in the state, the best it could do is reject
1666 an invalid pattern slightly earlier. If instead the decision
1667 is not the last in the state, the condition it tests could hold
1668 even for the later decisions in the state. The best it can do
1669 is save work in some cases where only the later decisions can
1670 succeed.
1671
1672 In both cases the optional transition would add extra work to
1673 successful matches when the tested condition holds. */
1674 if (transition *trans = d->singleton ())
1675 if (trans->optional)
1676 s->replace (d, trans->to->release ());
1677 d = next;
1678 }
1679 }
1680
1681 /* Try to squash several separate tests into simpler ones. */
1682
1683 static void
1684 simplify_tests (state *s)
1685 {
1686 for (decision *d = s->first; d; d = d->next)
1687 {
1688 uint64_t label;
1689 /* Convert checks for GET_CODE (x) == CONST_INT and XWINT (x, 0) == N
1690 into checks for const_int_rtx[N'], if N is suitably small. */
1691 if (d->test.kind == rtx_test::CODE
1692 && d->if_statement_p (&label)
1693 && label == CONST_INT)
1694 if (decision *second = d->first->to->singleton ())
1695 if (d->test.pos == second->test.pos
1696 && second->test.kind == rtx_test::WIDE_INT_FIELD
1697 && second->test.u.opno == 0
1698 && second->if_statement_p (&label)
1699 && IN_RANGE (int64_t (label),
1700 -MAX_SAVED_CONST_INT, MAX_SAVED_CONST_INT))
1701 {
1702 d->test.kind = rtx_test::SAVED_CONST_INT;
1703 d->test.u.integer.is_param = false;
1704 d->test.u.integer.value = label;
1705 d->replace (d->first, second->release ());
1706 d->first->labels[0] = true;
1707 }
1708 /* If we have a CODE test followed by a PREDICATE test, rely on
1709 the predicate to test the code.
1710
1711 This case exists for match_operators. We initially treat the
1712 CODE test for a match_operator as non-optional so that we can
1713 safely move down to its operands. It may turn out that all
1714 paths that reach that code test require the same predicate
1715 to be true. cse_tests will then put the predicate test in
1716 series with the code test. */
1717 if (d->test.kind == rtx_test::CODE)
1718 if (transition *trans = d->singleton ())
1719 {
1720 state *s = trans->to;
1721 while (decision *d2 = s->singleton ())
1722 {
1723 if (d->test.pos != d2->test.pos)
1724 break;
1725 transition *trans2 = d2->singleton ();
1726 if (!trans2)
1727 break;
1728 if (d2->test.kind == rtx_test::PREDICATE)
1729 {
1730 d->test = d2->test;
1731 trans->labels = int_set (true);
1732 s->replace (d2, trans2->to->release ());
1733 break;
1734 }
1735 s = trans2->to;
1736 }
1737 }
1738 for (transition *trans = d->first; trans; trans = trans->next)
1739 simplify_tests (trans->to);
1740 }
1741 }
1742
1743 /* Return true if all successful returns passing through D require the
1744 condition tested by COMMON to be true.
1745
1746 When returning true, add all transitions like COMMON in D to WHERE.
1747 WHERE may contain a partial result on failure. */
1748
1749 static bool
1750 common_test_p (decision *d, transition *common, vec <transition *> *where)
1751 {
1752 if (d->test.kind == rtx_test::ACCEPT)
1753 /* We found a successful return that didn't require COMMON. */
1754 return false;
1755 if (d->test == common->from->test)
1756 {
1757 transition *trans = d->singleton ();
1758 if (!trans
1759 || trans->optional != common->optional
1760 || trans->labels != common->labels)
1761 return false;
1762 where->safe_push (trans);
1763 return true;
1764 }
1765 for (transition *trans = d->first; trans; trans = trans->next)
1766 for (decision *subd = trans->to->first; subd; subd = subd->next)
1767 if (!common_test_p (subd, common, where))
1768 return false;
1769 return true;
1770 }
1771
1772 /* Indicates that we have tested GET_CODE (X) for a particular rtx X. */
1773 const unsigned char TESTED_CODE = 1;
1774
1775 /* Indicates that we have tested XVECLEN (X, 0) for a particular rtx X. */
1776 const unsigned char TESTED_VECLEN = 2;
1777
1778 /* Represents a set of conditions that are known to hold. */
1779 class known_conditions
1780 {
1781 public:
1782 /* A mask of TESTED_ values for each position, indexed by the position's
1783 id field. */
1784 auto_vec <unsigned char> position_tests;
1785
1786 /* Index N says whether operands[N] has been set. */
1787 auto_vec <bool> set_operands;
1788
1789 /* A guranteed lower bound on the value of peep2_current_count. */
1790 int peep2_count;
1791 };
1792
1793 /* Return true if TEST can safely be performed at D, where
1794 the conditions in KC hold. TEST is known to occur along the
1795 first path from D (i.e. always following the first transition
1796 of the first decision). Any intervening tests can be used as
1797 negative proof that hoisting isn't safe, but only KC can be used
1798 as positive proof. */
1799
1800 static bool
1801 safe_to_hoist_p (decision *d, const rtx_test &test, known_conditions *kc)
1802 {
1803 switch (test.kind)
1804 {
1805 case rtx_test::C_TEST:
1806 /* In general, C tests require everything else to have been
1807 verified and all operands to have been set up. */
1808 return false;
1809
1810 case rtx_test::ACCEPT:
1811 /* Don't accept something before all conditions have been tested. */
1812 return false;
1813
1814 case rtx_test::PREDICATE:
1815 /* Don't move a predicate over a test for VECLEN_GE, since the
1816 predicate used in a match_parallel can legitimately expect the
1817 length to be checked first. */
1818 for (decision *subd = d;
1819 subd->test != test;
1820 subd = subd->first->to->first)
1821 if (subd->test.pos == test.pos
1822 && subd->test.kind == rtx_test::VECLEN_GE)
1823 return false;
1824 goto any_rtx;
1825
1826 case rtx_test::DUPLICATE:
1827 /* Don't test for a match_dup until the associated operand has
1828 been set. */
1829 if (!kc->set_operands[test.u.opno])
1830 return false;
1831 goto any_rtx;
1832
1833 case rtx_test::CODE:
1834 case rtx_test::MODE:
1835 case rtx_test::SAVED_CONST_INT:
1836 case rtx_test::SET_OP:
1837 any_rtx:
1838 /* Check whether it is safe to access the rtx under test. */
1839 switch (test.pos->type)
1840 {
1841 case POS_PEEP2_INSN:
1842 return test.pos->arg < kc->peep2_count;
1843
1844 case POS_XEXP:
1845 return kc->position_tests[test.pos->base->id] & TESTED_CODE;
1846
1847 case POS_XVECEXP0:
1848 return kc->position_tests[test.pos->base->id] & TESTED_VECLEN;
1849 }
1850 gcc_unreachable ();
1851
1852 case rtx_test::REGNO_FIELD:
1853 case rtx_test::SUBREG_FIELD:
1854 case rtx_test::INT_FIELD:
1855 case rtx_test::WIDE_INT_FIELD:
1856 case rtx_test::VECLEN:
1857 case rtx_test::VECLEN_GE:
1858 /* These tests access a specific part of an rtx, so are only safe
1859 once we know what the rtx is. */
1860 return kc->position_tests[test.pos->id] & TESTED_CODE;
1861
1862 case rtx_test::PEEP2_COUNT:
1863 case rtx_test::HAVE_NUM_CLOBBERS:
1864 /* These tests can be performed anywhere. */
1865 return true;
1866
1867 case rtx_test::PATTERN:
1868 gcc_unreachable ();
1869 }
1870 gcc_unreachable ();
1871 }
1872
1873 /* Look for a transition that is taken by all successful returns from a range
1874 of decisions starting at OUTER and that would be better performed by
1875 OUTER's state instead. On success, store all instances of that transition
1876 in WHERE and return the last decision in the range. The range could
1877 just be OUTER, or it could include later decisions as well.
1878
1879 WITH_POSITION_P is true if only tests with position POS should be tried,
1880 false if any test should be tried. WORTHWHILE_SINGLE_P is true if the
1881 result is useful even when the range contains just a single decision
1882 with a single transition. KC are the conditions that are known to
1883 hold at OUTER. */
1884
1885 static decision *
1886 find_common_test (decision *outer, bool with_position_p,
1887 position *pos, bool worthwhile_single_p,
1888 known_conditions *kc, vec <transition *> *where)
1889 {
1890 /* After this, WORTHWHILE_SINGLE_P indicates whether a range that contains
1891 just a single decision is useful, regardless of the number of
1892 transitions it has. */
1893 if (!outer->singleton ())
1894 worthwhile_single_p = true;
1895 /* Quick exit if we don't have enough decisions to form a worthwhile
1896 range. */
1897 if (!worthwhile_single_p && !outer->next)
1898 return 0;
1899 /* Follow the first chain down, as one example of a path that needs
1900 to contain the common test. */
1901 for (decision *d = outer; d; d = d->first->to->first)
1902 {
1903 transition *trans = d->singleton ();
1904 if (trans
1905 && (!with_position_p || d->test.pos == pos)
1906 && safe_to_hoist_p (outer, d->test, kc))
1907 {
1908 if (common_test_p (outer, trans, where))
1909 {
1910 if (!outer->next)
1911 /* We checked above whether the move is worthwhile. */
1912 return outer;
1913 /* See how many decisions in OUTER's chain could reuse
1914 the same test. */
1915 decision *outer_end = outer;
1916 do
1917 {
1918 unsigned int length = where->length ();
1919 if (!common_test_p (outer_end->next, trans, where))
1920 {
1921 where->truncate (length);
1922 break;
1923 }
1924 outer_end = outer_end->next;
1925 }
1926 while (outer_end->next);
1927 /* It is worth moving TRANS if it can be shared by more than
1928 one decision. */
1929 if (outer_end != outer || worthwhile_single_p)
1930 return outer_end;
1931 }
1932 where->truncate (0);
1933 }
1934 }
1935 return 0;
1936 }
1937
1938 /* Try to promote common subtests in S to a single, shared decision.
1939 Also try to bunch tests for the same position together. POS is the
1940 position of the rtx tested before reaching S. KC are the conditions
1941 that are known to hold on entry to S. */
1942
1943 static void
1944 cse_tests (position *pos, state *s, known_conditions *kc)
1945 {
1946 for (decision *d = s->first; d; d = d->next)
1947 {
1948 auto_vec <transition *, 16> where;
1949 if (d->test.pos)
1950 {
1951 /* Try to find conditions that don't depend on a particular rtx,
1952 such as pnum_clobbers != NULL or peep2_current_count >= X.
1953 It's usually better to check these conditions as soon as
1954 possible, so the change is worthwhile even if there is
1955 only one copy of the test. */
1956 decision *endd = find_common_test (d, true, 0, true, kc, &where);
1957 if (!endd && d->test.pos != pos)
1958 /* Try to find other conditions related to position POS
1959 before moving to the new position. Again, this is
1960 worthwhile even if there is only one copy of the test,
1961 since it means that fewer position variables are live
1962 at a given time. */
1963 endd = find_common_test (d, true, pos, true, kc, &where);
1964 if (!endd)
1965 /* Try to find any condition that is used more than once. */
1966 endd = find_common_test (d, false, 0, false, kc, &where);
1967 if (endd)
1968 {
1969 transition *common = where[0];
1970 /* Replace [D, ENDD] with a test like COMMON. We'll recurse
1971 on the common test and see the original D again next time. */
1972 d = insert_decision_before (state::range (d, endd),
1973 common->from->test,
1974 common->labels,
1975 common->optional);
1976 /* Remove the old tests. */
1977 while (!where.is_empty ())
1978 {
1979 transition *trans = where.pop ();
1980 trans->from->s->replace (trans->from, trans->to->release ());
1981 }
1982 }
1983 }
1984
1985 /* Make sure that safe_to_hoist_p isn't being overly conservative.
1986 It should realize that D's test is safe in the current
1987 environment. */
1988 gcc_assert (d->test.kind == rtx_test::C_TEST
1989 || d->test.kind == rtx_test::ACCEPT
1990 || safe_to_hoist_p (d, d->test, kc));
1991
1992 /* D won't be changed any further by the current optimization.
1993 Recurse with the state temporarily updated to include D. */
1994 int prev = 0;
1995 switch (d->test.kind)
1996 {
1997 case rtx_test::CODE:
1998 prev = kc->position_tests[d->test.pos->id];
1999 kc->position_tests[d->test.pos->id] |= TESTED_CODE;
2000 break;
2001
2002 case rtx_test::VECLEN:
2003 case rtx_test::VECLEN_GE:
2004 prev = kc->position_tests[d->test.pos->id];
2005 kc->position_tests[d->test.pos->id] |= TESTED_VECLEN;
2006 break;
2007
2008 case rtx_test::SET_OP:
2009 prev = kc->set_operands[d->test.u.opno];
2010 gcc_assert (!prev);
2011 kc->set_operands[d->test.u.opno] = true;
2012 break;
2013
2014 case rtx_test::PEEP2_COUNT:
2015 prev = kc->peep2_count;
2016 kc->peep2_count = MAX (prev, d->test.u.min_len);
2017 break;
2018
2019 default:
2020 break;
2021 }
2022 for (transition *trans = d->first; trans; trans = trans->next)
2023 cse_tests (d->test.pos ? d->test.pos : pos, trans->to, kc);
2024 switch (d->test.kind)
2025 {
2026 case rtx_test::CODE:
2027 case rtx_test::VECLEN:
2028 case rtx_test::VECLEN_GE:
2029 kc->position_tests[d->test.pos->id] = prev;
2030 break;
2031
2032 case rtx_test::SET_OP:
2033 kc->set_operands[d->test.u.opno] = prev;
2034 break;
2035
2036 case rtx_test::PEEP2_COUNT:
2037 kc->peep2_count = prev;
2038 break;
2039
2040 default:
2041 break;
2042 }
2043 }
2044 }
2045
2046 /* Return the type of value that can be used to parameterize test KIND,
2047 or parameter::UNSET if none. */
2048
2049 parameter::type_enum
2050 transition_parameter_type (rtx_test::kind_enum kind)
2051 {
2052 switch (kind)
2053 {
2054 case rtx_test::CODE:
2055 return parameter::CODE;
2056
2057 case rtx_test::MODE:
2058 return parameter::MODE;
2059
2060 case rtx_test::REGNO_FIELD:
2061 case rtx_test::SUBREG_FIELD:
2062 return parameter::UINT;
2063
2064 case rtx_test::INT_FIELD:
2065 case rtx_test::VECLEN:
2066 case rtx_test::PATTERN:
2067 return parameter::INT;
2068
2069 case rtx_test::WIDE_INT_FIELD:
2070 return parameter::WIDE_INT;
2071
2072 case rtx_test::PEEP2_COUNT:
2073 case rtx_test::VECLEN_GE:
2074 case rtx_test::SAVED_CONST_INT:
2075 case rtx_test::PREDICATE:
2076 case rtx_test::DUPLICATE:
2077 case rtx_test::HAVE_NUM_CLOBBERS:
2078 case rtx_test::C_TEST:
2079 case rtx_test::SET_OP:
2080 case rtx_test::ACCEPT:
2081 return parameter::UNSET;
2082 }
2083 gcc_unreachable ();
2084 }
2085
2086 /* Initialize the pos_operand fields of each state reachable from S.
2087 If OPERAND_POS[ID] >= 0, the position with id ID is stored in
2088 operands[OPERAND_POS[ID]] on entry to S. */
2089
2090 static void
2091 find_operand_positions (state *s, vec <int> &operand_pos)
2092 {
2093 for (decision *d = s->first; d; d = d->next)
2094 {
2095 int this_operand = (d->test.pos ? operand_pos[d->test.pos->id] : -1);
2096 if (this_operand >= 0)
2097 d->test.pos_operand = this_operand;
2098 if (d->test.kind == rtx_test::SET_OP)
2099 operand_pos[d->test.pos->id] = d->test.u.opno;
2100 for (transition *trans = d->first; trans; trans = trans->next)
2101 find_operand_positions (trans->to, operand_pos);
2102 if (d->test.kind == rtx_test::SET_OP)
2103 operand_pos[d->test.pos->id] = this_operand;
2104 }
2105 }
2106
2107 /* Statistics about a matching routine. */
2108 class stats
2109 {
2110 public:
2111 stats ();
2112
2113 /* The total number of decisions in the routine, excluding trivial
2114 ones that never fail. */
2115 unsigned int num_decisions;
2116
2117 /* The number of non-trivial decisions on the longest path through
2118 the routine, and the return value that contributes most to that
2119 long path. */
2120 unsigned int longest_path;
2121 int longest_path_code;
2122
2123 /* The maximum number of times that a single call to the routine
2124 can backtrack, and the value returned at the end of that path.
2125 "Backtracking" here means failing one decision in state and
2126 going onto to the next. */
2127 unsigned int longest_backtrack;
2128 int longest_backtrack_code;
2129 };
2130
2131 stats::stats ()
2132 : num_decisions (0), longest_path (0), longest_path_code (-1),
2133 longest_backtrack (0), longest_backtrack_code (-1) {}
2134
2135 /* Return statistics about S. */
2136
2137 static stats
2138 get_stats (state *s)
2139 {
2140 stats for_s;
2141 unsigned int longest_path = 0;
2142 for (decision *d = s->first; d; d = d->next)
2143 {
2144 /* Work out the statistics for D. */
2145 stats for_d;
2146 for (transition *trans = d->first; trans; trans = trans->next)
2147 {
2148 stats for_trans = get_stats (trans->to);
2149 for_d.num_decisions += for_trans.num_decisions;
2150 /* Each transition is mutually-exclusive, so just pick the
2151 longest of the individual paths. */
2152 if (for_d.longest_path <= for_trans.longest_path)
2153 {
2154 for_d.longest_path = for_trans.longest_path;
2155 for_d.longest_path_code = for_trans.longest_path_code;
2156 }
2157 /* Likewise for backtracking. */
2158 if (for_d.longest_backtrack <= for_trans.longest_backtrack)
2159 {
2160 for_d.longest_backtrack = for_trans.longest_backtrack;
2161 for_d.longest_backtrack_code = for_trans.longest_backtrack_code;
2162 }
2163 }
2164
2165 /* Account for D's test in its statistics. */
2166 if (!d->test.single_outcome_p ())
2167 {
2168 for_d.num_decisions += 1;
2169 for_d.longest_path += 1;
2170 }
2171 if (d->test.kind == rtx_test::ACCEPT)
2172 {
2173 for_d.longest_path_code = d->test.u.acceptance.u.full.code;
2174 for_d.longest_backtrack_code = d->test.u.acceptance.u.full.code;
2175 }
2176
2177 /* Keep a running count of the number of backtracks. */
2178 if (d->prev)
2179 for_s.longest_backtrack += 1;
2180
2181 /* Accumulate D's statistics into S's. */
2182 for_s.num_decisions += for_d.num_decisions;
2183 for_s.longest_path += for_d.longest_path;
2184 for_s.longest_backtrack += for_d.longest_backtrack;
2185
2186 /* Use the code from the decision with the longest individual path,
2187 since that's more likely to be useful if trying to make the
2188 path shorter. In the event of a tie, pick the later decision,
2189 since that's closer to the end of the path. */
2190 if (longest_path <= for_d.longest_path)
2191 {
2192 longest_path = for_d.longest_path;
2193 for_s.longest_path_code = for_d.longest_path_code;
2194 }
2195
2196 /* Later decisions in a state are necessarily in a longer backtrack
2197 than earlier decisions. */
2198 for_s.longest_backtrack_code = for_d.longest_backtrack_code;
2199 }
2200 return for_s;
2201 }
2202
2203 /* Optimize ROOT. Use TYPE to describe ROOT in status messages. */
2204
2205 static void
2206 optimize_subroutine_group (const char *type, state *root)
2207 {
2208 /* Remove optional transitions that turned out not to be worthwhile. */
2209 if (collapse_optional_decisions_p)
2210 collapse_optional_decisions (root);
2211
2212 /* Try to remove duplicated tests and to rearrange tests into a more
2213 logical order. */
2214 if (cse_tests_p)
2215 {
2216 known_conditions kc;
2217 kc.position_tests.safe_grow_cleared (num_positions);
2218 kc.set_operands.safe_grow_cleared (num_operands);
2219 kc.peep2_count = 1;
2220 cse_tests (&root_pos, root, &kc);
2221 }
2222
2223 /* Try to simplify two or more tests into one. */
2224 if (simplify_tests_p)
2225 simplify_tests (root);
2226
2227 /* Try to use operands[] instead of xN variables. */
2228 if (use_operand_variables_p)
2229 {
2230 auto_vec <int> operand_pos (num_positions);
2231 for (unsigned int i = 0; i < num_positions; ++i)
2232 operand_pos.quick_push (-1);
2233 find_operand_positions (root, operand_pos);
2234 }
2235
2236 /* Print a summary of the new state. */
2237 stats st = get_stats (root);
2238 fprintf (stderr, "Statistics for %s:\n", type);
2239 fprintf (stderr, " Number of decisions: %6d\n", st.num_decisions);
2240 fprintf (stderr, " longest path: %6d (code: %6d)\n",
2241 st.longest_path, st.longest_path_code);
2242 fprintf (stderr, " longest backtrack: %6d (code: %6d)\n",
2243 st.longest_backtrack, st.longest_backtrack_code);
2244 }
2245
2246 class merge_pattern_info;
2247
2248 /* Represents a transition from one pattern to another. */
2249 class merge_pattern_transition
2250 {
2251 public:
2252 merge_pattern_transition (merge_pattern_info *);
2253
2254 /* The target pattern. */
2255 merge_pattern_info *to;
2256
2257 /* The parameters that the source pattern passes to the target pattern.
2258 "parameter (TYPE, true, I)" represents parameter I of the source
2259 pattern. */
2260 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2261 };
2262
2263 merge_pattern_transition::merge_pattern_transition (merge_pattern_info *to_in)
2264 : to (to_in)
2265 {
2266 }
2267
2268 /* Represents a pattern that can might match several states. The pattern
2269 may replace parts of the test with a parameter value. It may also
2270 replace transition labels with parameters. */
2271 class merge_pattern_info
2272 {
2273 public:
2274 merge_pattern_info (unsigned int);
2275
2276 /* If PARAM_TEST_P, the state's singleton test should be generalized
2277 to use the runtime value of PARAMS[PARAM_TEST]. */
2278 unsigned int param_test : 8;
2279
2280 /* If PARAM_TRANSITION_P, the state's single transition label should
2281 be replaced by the runtime value of PARAMS[PARAM_TRANSITION]. */
2282 unsigned int param_transition : 8;
2283
2284 /* True if we have decided to generalize the root decision's test,
2285 as per PARAM_TEST. */
2286 unsigned int param_test_p : 1;
2287
2288 /* Likewise for the root decision's transition, as per PARAM_TRANSITION. */
2289 unsigned int param_transition_p : 1;
2290
2291 /* True if the contents of the structure are completely filled in. */
2292 unsigned int complete_p : 1;
2293
2294 /* The number of pseudo-statements in the pattern. Used to decide
2295 whether it's big enough to break out into a subroutine. */
2296 unsigned int num_statements;
2297
2298 /* The number of states that use this pattern. */
2299 unsigned int num_users;
2300
2301 /* The number of distinct success values that the pattern returns. */
2302 unsigned int num_results;
2303
2304 /* This array has one element for each runtime parameter to the pattern.
2305 PARAMS[I] gives the default value of parameter I, which is always
2306 constant.
2307
2308 These default parameters are used in cases where we match the
2309 pattern against some state S1, then add more parameters while
2310 matching against some state S2. S1 is then left passing fewer
2311 parameters than S2. The array gives us enough informatino to
2312 construct a full parameter list for S1 (see update_parameters).
2313
2314 If we decide to create a subroutine for this pattern,
2315 PARAMS[I].type determines the C type of parameter I. */
2316 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2317
2318 /* All states that match this pattern must have the same number of
2319 transitions. TRANSITIONS[I] describes the subpattern for transition
2320 number I; it is null if transition I represents a successful return
2321 from the pattern. */
2322 auto_vec <merge_pattern_transition *, 1> transitions;
2323
2324 /* The routine associated with the pattern, or null if we haven't generated
2325 one yet. */
2326 pattern_routine *routine;
2327 };
2328
2329 merge_pattern_info::merge_pattern_info (unsigned int num_transitions)
2330 : param_test (0),
2331 param_transition (0),
2332 param_test_p (false),
2333 param_transition_p (false),
2334 complete_p (false),
2335 num_statements (0),
2336 num_users (0),
2337 num_results (0),
2338 routine (0)
2339 {
2340 transitions.safe_grow_cleared (num_transitions);
2341 }
2342
2343 /* Describes one way of matching a particular state to a particular
2344 pattern. */
2345 class merge_state_result
2346 {
2347 public:
2348 merge_state_result (merge_pattern_info *, position *, merge_state_result *);
2349
2350 /* A pattern that matches the state. */
2351 merge_pattern_info *pattern;
2352
2353 /* If we decide to use this match and create a subroutine for PATTERN,
2354 the state should pass the rtx at position ROOT to the pattern's
2355 rtx parameter. A null root means that the pattern doesn't need
2356 an rtx parameter; all the rtxes it matches come from elsewhere. */
2357 position *root;
2358
2359 /* The parameters that should be passed to PATTERN for this state.
2360 If the array is shorter than PATTERN->params, the missing entries
2361 should be taken from the corresponding element of PATTERN->params. */
2362 auto_vec <parameter, MAX_PATTERN_PARAMS> params;
2363
2364 /* An earlier match for the same state, or null if none. Patterns
2365 matched by earlier entries are smaller than PATTERN. */
2366 merge_state_result *prev;
2367 };
2368
2369 merge_state_result::merge_state_result (merge_pattern_info *pattern_in,
2370 position *root_in,
2371 merge_state_result *prev_in)
2372 : pattern (pattern_in), root (root_in), prev (prev_in)
2373 {}
2374
2375 /* Information about a state, used while trying to match it against
2376 a pattern. */
2377 class merge_state_info
2378 {
2379 public:
2380 merge_state_info (state *);
2381
2382 /* The state itself. */
2383 state *s;
2384
2385 /* Index I gives information about the target of transition I. */
2386 merge_state_info *to_states;
2387
2388 /* The number of transitions in S. */
2389 unsigned int num_transitions;
2390
2391 /* True if the state has been deleted in favor of a call to a
2392 pattern routine. */
2393 bool merged_p;
2394
2395 /* The previous state that might be a merge candidate for S, or null
2396 if no previous states could be merged with S. */
2397 merge_state_info *prev_same_test;
2398
2399 /* A list of pattern matches for this state. */
2400 merge_state_result *res;
2401 };
2402
2403 merge_state_info::merge_state_info (state *s_in)
2404 : s (s_in),
2405 to_states (0),
2406 num_transitions (0),
2407 merged_p (false),
2408 prev_same_test (0),
2409 res (0) {}
2410
2411 /* True if PAT would be useful as a subroutine. */
2412
2413 static bool
2414 useful_pattern_p (merge_pattern_info *pat)
2415 {
2416 return pat->num_statements >= MIN_COMBINE_COST;
2417 }
2418
2419 /* PAT2 is a subpattern of PAT1. Return true if PAT2 should be inlined
2420 into PAT1's C routine. */
2421
2422 static bool
2423 same_pattern_p (merge_pattern_info *pat1, merge_pattern_info *pat2)
2424 {
2425 return pat1->num_users == pat2->num_users || !useful_pattern_p (pat2);
2426 }
2427
2428 /* PAT was previously matched against SINFO based on tentative matches
2429 for the target states of SINFO's state. Return true if the match
2430 still holds; that is, if the target states of SINFO's state still
2431 match the corresponding transitions of PAT. */
2432
2433 static bool
2434 valid_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2435 {
2436 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2437 if (merge_pattern_transition *ptrans = pat->transitions[j])
2438 {
2439 merge_state_result *to_res = sinfo->to_states[j].res;
2440 if (!to_res || to_res->pattern != ptrans->to)
2441 return false;
2442 }
2443 return true;
2444 }
2445
2446 /* Remove any matches that are no longer valid from the head of SINFO's
2447 list of matches. */
2448
2449 static void
2450 prune_invalid_results (merge_state_info *sinfo)
2451 {
2452 while (sinfo->res && !valid_result_p (sinfo->res->pattern, sinfo))
2453 {
2454 sinfo->res = sinfo->res->prev;
2455 gcc_assert (sinfo->res);
2456 }
2457 }
2458
2459 /* Return true if PAT represents the biggest posssible match for SINFO;
2460 that is, if the next action of SINFO's state on return from PAT will
2461 be something that cannot be merged with any other state. */
2462
2463 static bool
2464 complete_result_p (merge_pattern_info *pat, merge_state_info *sinfo)
2465 {
2466 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
2467 if (sinfo->to_states[j].res && !pat->transitions[j])
2468 return false;
2469 return true;
2470 }
2471
2472 /* Update TO for any parameters that have been added to FROM since TO
2473 was last set. The extra parameters in FROM will be constants or
2474 instructions to duplicate earlier parameters. */
2475
2476 static void
2477 update_parameters (vec <parameter> &to, const vec <parameter> &from)
2478 {
2479 for (unsigned int i = to.length (); i < from.length (); ++i)
2480 to.quick_push (from[i]);
2481 }
2482
2483 /* Return true if A and B can be tested by a single test. If the test
2484 can be parameterised, store the parameter value for A in *PARAMA and
2485 the parameter value for B in *PARAMB, otherwise leave PARAMA and
2486 PARAMB alone. */
2487
2488 static bool
2489 compatible_tests_p (const rtx_test &a, const rtx_test &b,
2490 parameter *parama, parameter *paramb)
2491 {
2492 if (a.kind != b.kind)
2493 return false;
2494 switch (a.kind)
2495 {
2496 case rtx_test::PREDICATE:
2497 if (a.u.predicate.data != b.u.predicate.data)
2498 return false;
2499 *parama = parameter (parameter::MODE, false, a.u.predicate.mode);
2500 *paramb = parameter (parameter::MODE, false, b.u.predicate.mode);
2501 return true;
2502
2503 case rtx_test::SAVED_CONST_INT:
2504 *parama = parameter (parameter::INT, false, a.u.integer.value);
2505 *paramb = parameter (parameter::INT, false, b.u.integer.value);
2506 return true;
2507
2508 default:
2509 return a == b;
2510 }
2511 }
2512
2513 /* PARAMS is an array of the parameters that a state is going to pass
2514 to a pattern routine. It is still incomplete; index I has a kind of
2515 parameter::UNSET if we don't yet know what the state will pass
2516 as parameter I. Try to make parameter ID equal VALUE, returning
2517 true on success. */
2518
2519 static bool
2520 set_parameter (vec <parameter> &params, unsigned int id,
2521 const parameter &value)
2522 {
2523 if (params[id].type == parameter::UNSET)
2524 {
2525 if (force_unique_params_p)
2526 for (unsigned int i = 0; i < params.length (); ++i)
2527 if (params[i] == value)
2528 return false;
2529 params[id] = value;
2530 return true;
2531 }
2532 return params[id] == value;
2533 }
2534
2535 /* PARAMS2 is the "params" array for a pattern and PARAMS1 is the
2536 set of parameters that a particular state is going to pass to
2537 that pattern.
2538
2539 Try to extend PARAMS1 and PARAMS2 so that there is a parameter
2540 that is equal to PARAM1 for the state and has a default value of
2541 PARAM2. Parameters beginning at START were added as part of the
2542 same match and so may be reused. */
2543
2544 static bool
2545 add_parameter (vec <parameter> &params1, vec <parameter> &params2,
2546 const parameter &param1, const parameter &param2,
2547 unsigned int start, unsigned int *res)
2548 {
2549 gcc_assert (params1.length () == params2.length ());
2550 gcc_assert (!param1.is_param && !param2.is_param);
2551
2552 for (unsigned int i = start; i < params2.length (); ++i)
2553 if (params1[i] == param1 && params2[i] == param2)
2554 {
2555 *res = i;
2556 return true;
2557 }
2558
2559 if (force_unique_params_p)
2560 for (unsigned int i = 0; i < params2.length (); ++i)
2561 if (params1[i] == param1 || params2[i] == param2)
2562 return false;
2563
2564 if (params2.length () >= MAX_PATTERN_PARAMS)
2565 return false;
2566
2567 *res = params2.length ();
2568 params1.quick_push (param1);
2569 params2.quick_push (param2);
2570 return true;
2571 }
2572
2573 /* If *ROOTA is nonnull, return true if the same sequence of steps are
2574 required to reach A from *ROOTA as to reach B from ROOTB. If *ROOTA
2575 is null, update it if necessary in order to make the condition hold. */
2576
2577 static bool
2578 merge_relative_positions (position **roota, position *a,
2579 position *rootb, position *b)
2580 {
2581 if (!relative_patterns_p)
2582 {
2583 if (a != b)
2584 return false;
2585 if (!*roota)
2586 {
2587 *roota = rootb;
2588 return true;
2589 }
2590 return *roota == rootb;
2591 }
2592 /* If B does not belong to the same instruction as ROOTB, we don't
2593 start with ROOTB but instead start with a call to peep2_next_insn.
2594 In that case the sequences for B and A are identical iff B and A
2595 are themselves identical. */
2596 if (rootb->insn_id != b->insn_id)
2597 return a == b;
2598 while (rootb != b)
2599 {
2600 if (!a || b->type != a->type || b->arg != a->arg)
2601 return false;
2602 b = b->base;
2603 a = a->base;
2604 }
2605 if (!*roota)
2606 *roota = a;
2607 return *roota == a;
2608 }
2609
2610 /* A hasher of states that treats two states as "equal" if they might be
2611 merged (but trying to be more discriminating than "return true"). */
2612 struct test_pattern_hasher : nofree_ptr_hash <merge_state_info>
2613 {
2614 static inline hashval_t hash (const value_type &);
2615 static inline bool equal (const value_type &, const compare_type &);
2616 };
2617
2618 hashval_t
2619 test_pattern_hasher::hash (merge_state_info *const &sinfo)
2620 {
2621 inchash::hash h;
2622 decision *d = sinfo->s->singleton ();
2623 h.add_int (d->test.pos_operand + 1);
2624 if (!relative_patterns_p)
2625 h.add_int (d->test.pos ? d->test.pos->id + 1 : 0);
2626 h.add_int (d->test.kind);
2627 h.add_int (sinfo->num_transitions);
2628 return h.end ();
2629 }
2630
2631 bool
2632 test_pattern_hasher::equal (merge_state_info *const &sinfo1,
2633 merge_state_info *const &sinfo2)
2634 {
2635 decision *d1 = sinfo1->s->singleton ();
2636 decision *d2 = sinfo2->s->singleton ();
2637 gcc_assert (d1 && d2);
2638
2639 parameter new_param1, new_param2;
2640 return (d1->test.pos_operand == d2->test.pos_operand
2641 && (relative_patterns_p || d1->test.pos == d2->test.pos)
2642 && compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2)
2643 && sinfo1->num_transitions == sinfo2->num_transitions);
2644 }
2645
2646 /* Try to make the state described by SINFO1 use the same pattern as the
2647 state described by SINFO2. Return true on success.
2648
2649 SINFO1 and SINFO2 are known to have the same hash value. */
2650
2651 static bool
2652 merge_patterns (merge_state_info *sinfo1, merge_state_info *sinfo2)
2653 {
2654 merge_state_result *res2 = sinfo2->res;
2655 merge_pattern_info *pat = res2->pattern;
2656
2657 /* Write to temporary arrays while matching, in case we have to abort
2658 half way through. */
2659 auto_vec <parameter, MAX_PATTERN_PARAMS> params1;
2660 auto_vec <parameter, MAX_PATTERN_PARAMS> params2;
2661 params1.quick_grow_cleared (pat->params.length ());
2662 params2.splice (pat->params);
2663 unsigned int start_param = params2.length ();
2664
2665 /* An array for recording changes to PAT->transitions[?].params.
2666 All changes involve replacing a constant parameter with some
2667 PAT->params[N], where N is the second element of the pending_param. */
2668 typedef std::pair <parameter *, unsigned int> pending_param;
2669 auto_vec <pending_param, 32> pending_params;
2670
2671 decision *d1 = sinfo1->s->singleton ();
2672 decision *d2 = sinfo2->s->singleton ();
2673 gcc_assert (d1 && d2);
2674
2675 /* If D2 tests a position, SINFO1's root relative to D1 is the same
2676 as SINFO2's root relative to D2. */
2677 position *root1 = 0;
2678 position *root2 = res2->root;
2679 if (d2->test.pos_operand < 0
2680 && d1->test.pos
2681 && !merge_relative_positions (&root1, d1->test.pos,
2682 root2, d2->test.pos))
2683 return false;
2684
2685 /* Check whether the patterns have the same shape. */
2686 unsigned int num_transitions = sinfo1->num_transitions;
2687 gcc_assert (num_transitions == sinfo2->num_transitions);
2688 for (unsigned int i = 0; i < num_transitions; ++i)
2689 if (merge_pattern_transition *ptrans = pat->transitions[i])
2690 {
2691 merge_state_result *to1_res = sinfo1->to_states[i].res;
2692 merge_state_result *to2_res = sinfo2->to_states[i].res;
2693 merge_pattern_info *to_pat = ptrans->to;
2694 gcc_assert (to2_res && to2_res->pattern == to_pat);
2695 if (!to1_res || to1_res->pattern != to_pat)
2696 return false;
2697 if (to2_res->root
2698 && !merge_relative_positions (&root1, to1_res->root,
2699 root2, to2_res->root))
2700 return false;
2701 /* Match the parameters that TO1_RES passes to TO_PAT with the
2702 parameters that PAT passes to TO_PAT. */
2703 update_parameters (to1_res->params, to_pat->params);
2704 for (unsigned int j = 0; j < to1_res->params.length (); ++j)
2705 {
2706 const parameter &param1 = to1_res->params[j];
2707 const parameter &param2 = ptrans->params[j];
2708 gcc_assert (!param1.is_param);
2709 if (param2.is_param)
2710 {
2711 if (!set_parameter (params1, param2.value, param1))
2712 return false;
2713 }
2714 else if (param1 != param2)
2715 {
2716 unsigned int id;
2717 if (!add_parameter (params1, params2,
2718 param1, param2, start_param, &id))
2719 return false;
2720 /* Record that PAT should now pass parameter ID to TO_PAT,
2721 instead of the current contents of *PARAM2. We only
2722 make the change if the rest of the match succeeds. */
2723 pending_params.safe_push
2724 (pending_param (&ptrans->params[j], id));
2725 }
2726 }
2727 }
2728
2729 unsigned int param_test = pat->param_test;
2730 unsigned int param_transition = pat->param_transition;
2731 bool param_test_p = pat->param_test_p;
2732 bool param_transition_p = pat->param_transition_p;
2733
2734 /* If the tests don't match exactly, try to parameterize them. */
2735 parameter new_param1, new_param2;
2736 if (!compatible_tests_p (d1->test, d2->test, &new_param1, &new_param2))
2737 gcc_unreachable ();
2738 if (new_param1.type != parameter::UNSET)
2739 {
2740 /* If the test has not already been parameterized, all existing
2741 matches use constant NEW_PARAM2. */
2742 if (param_test_p)
2743 {
2744 if (!set_parameter (params1, param_test, new_param1))
2745 return false;
2746 }
2747 else if (new_param1 != new_param2)
2748 {
2749 if (!add_parameter (params1, params2, new_param1, new_param2,
2750 start_param, &param_test))
2751 return false;
2752 param_test_p = true;
2753 }
2754 }
2755
2756 /* Match the transitions. */
2757 transition *trans1 = d1->first;
2758 transition *trans2 = d2->first;
2759 for (unsigned int i = 0; i < num_transitions; ++i)
2760 {
2761 if (param_transition_p || trans1->labels != trans2->labels)
2762 {
2763 /* We can only generalize a single transition with a single
2764 label. */
2765 if (num_transitions != 1
2766 || trans1->labels.length () != 1
2767 || trans2->labels.length () != 1)
2768 return false;
2769
2770 /* Although we can match wide-int fields, in practice it leads
2771 to some odd results for const_vectors. We end up
2772 parameterizing the first N const_ints of the vector
2773 and then (once we reach the maximum number of parameters)
2774 we go on to match the other elements exactly. */
2775 if (d1->test.kind == rtx_test::WIDE_INT_FIELD)
2776 return false;
2777
2778 /* See whether the label has a generalizable type. */
2779 parameter::type_enum param_type
2780 = transition_parameter_type (d1->test.kind);
2781 if (param_type == parameter::UNSET)
2782 return false;
2783
2784 /* Match the labels using parameters. */
2785 new_param1 = parameter (param_type, false, trans1->labels[0]);
2786 if (param_transition_p)
2787 {
2788 if (!set_parameter (params1, param_transition, new_param1))
2789 return false;
2790 }
2791 else
2792 {
2793 new_param2 = parameter (param_type, false, trans2->labels[0]);
2794 if (!add_parameter (params1, params2, new_param1, new_param2,
2795 start_param, &param_transition))
2796 return false;
2797 param_transition_p = true;
2798 }
2799 }
2800 trans1 = trans1->next;
2801 trans2 = trans2->next;
2802 }
2803
2804 /* Set any unset parameters to their default values. This occurs if some
2805 other state needed something to be parameterized in order to match SINFO2,
2806 but SINFO1 on its own does not. */
2807 for (unsigned int i = 0; i < params1.length (); ++i)
2808 if (params1[i].type == parameter::UNSET)
2809 params1[i] = params2[i];
2810
2811 /* The match was successful. Commit all pending changes to PAT. */
2812 update_parameters (pat->params, params2);
2813 {
2814 pending_param *pp;
2815 unsigned int i;
2816 FOR_EACH_VEC_ELT (pending_params, i, pp)
2817 *pp->first = parameter (pp->first->type, true, pp->second);
2818 }
2819 pat->param_test = param_test;
2820 pat->param_transition = param_transition;
2821 pat->param_test_p = param_test_p;
2822 pat->param_transition_p = param_transition_p;
2823
2824 /* Record the match of SINFO1. */
2825 merge_state_result *new_res1 = new merge_state_result (pat, root1,
2826 sinfo1->res);
2827 new_res1->params.splice (params1);
2828 sinfo1->res = new_res1;
2829 return true;
2830 }
2831
2832 /* The number of states that were removed by calling pattern routines. */
2833 static unsigned int pattern_use_states;
2834
2835 /* The number of states used while defining pattern routines. */
2836 static unsigned int pattern_def_states;
2837
2838 /* Information used while constructing a use or definition of a pattern
2839 routine. */
2840 struct create_pattern_info
2841 {
2842 /* The routine itself. */
2843 pattern_routine *routine;
2844
2845 /* The first unclaimed return value for this particular use or definition.
2846 We walk the substates of uses and definitions in the same order
2847 so each return value always refers to the same position within
2848 the pattern. */
2849 unsigned int next_result;
2850 };
2851
2852 static void populate_pattern_routine (create_pattern_info *,
2853 merge_state_info *, state *,
2854 const vec <parameter> &);
2855
2856 /* SINFO matches a pattern for which we've decided to create a C routine.
2857 Return a decision that performs a call to the pattern routine,
2858 but leave the caller to add the transitions to it. Initialize CPI
2859 for this purpose. Also create a definition for the pattern routine,
2860 if it doesn't already have one.
2861
2862 PARAMS are the parameters that SINFO passes to its pattern. */
2863
2864 static decision *
2865 init_pattern_use (create_pattern_info *cpi, merge_state_info *sinfo,
2866 const vec <parameter> &params)
2867 {
2868 state *s = sinfo->s;
2869 merge_state_result *res = sinfo->res;
2870 merge_pattern_info *pat = res->pattern;
2871 cpi->routine = pat->routine;
2872 if (!cpi->routine)
2873 {
2874 /* We haven't defined the pattern routine yet, so create
2875 a definition now. */
2876 pattern_routine *routine = new pattern_routine;
2877 pat->routine = routine;
2878 cpi->routine = routine;
2879 routine->s = new state;
2880 routine->insn_p = false;
2881 routine->pnum_clobbers_p = false;
2882
2883 /* Create an "idempotent" mapping of parameter I to parameter I.
2884 Also record the C type of each parameter to the routine. */
2885 auto_vec <parameter, MAX_PATTERN_PARAMS> def_params;
2886 for (unsigned int i = 0; i < pat->params.length (); ++i)
2887 {
2888 def_params.quick_push (parameter (pat->params[i].type, true, i));
2889 routine->param_types.quick_push (pat->params[i].type);
2890 }
2891
2892 /* Any of the states that match the pattern could be used to
2893 create the routine definition. We might as well use SINFO
2894 since it's already to hand. This means that all positions
2895 in the definition will be relative to RES->root. */
2896 routine->pos = res->root;
2897 cpi->next_result = 0;
2898 populate_pattern_routine (cpi, sinfo, routine->s, def_params);
2899 gcc_assert (cpi->next_result == pat->num_results);
2900
2901 /* Add the routine to the global list, after the subroutines
2902 that it calls. */
2903 routine->pattern_id = patterns.length ();
2904 patterns.safe_push (routine);
2905 }
2906
2907 /* Create a decision to call the routine, passing PARAMS to it. */
2908 pattern_use *use = new pattern_use;
2909 use->routine = pat->routine;
2910 use->params.splice (params);
2911 decision *d = new decision (rtx_test::pattern (res->root, use));
2912
2913 /* If the original decision could use an element of operands[] instead
2914 of an rtx variable, try to transfer it to the new decision. */
2915 if (s->first->test.pos && res->root == s->first->test.pos)
2916 d->test.pos_operand = s->first->test.pos_operand;
2917
2918 cpi->next_result = 0;
2919 return d;
2920 }
2921
2922 /* Make S return the next unclaimed pattern routine result for CPI. */
2923
2924 static void
2925 add_pattern_acceptance (create_pattern_info *cpi, state *s)
2926 {
2927 acceptance_type acceptance;
2928 acceptance.type = SUBPATTERN;
2929 acceptance.partial_p = false;
2930 acceptance.u.full.code = cpi->next_result;
2931 add_decision (s, rtx_test::accept (acceptance), true, false);
2932 cpi->next_result += 1;
2933 }
2934
2935 /* Initialize new empty state NEWS so that it implements SINFO's pattern
2936 (here referred to as "P"). P may be the top level of a pattern routine
2937 or a subpattern that should be inlined into its parent pattern's routine
2938 (as per same_pattern_p). The choice of SINFO for a top-level pattern is
2939 arbitrary; it could be any of the states that use P. The choice for
2940 subpatterns follows the choice for the parent pattern.
2941
2942 PARAMS gives the value of each parameter to P in terms of the parameters
2943 to the top-level pattern. If P itself is the top level pattern, PARAMS[I]
2944 is always "parameter (TYPE, true, I)". */
2945
2946 static void
2947 populate_pattern_routine (create_pattern_info *cpi, merge_state_info *sinfo,
2948 state *news, const vec <parameter> &params)
2949 {
2950 pattern_def_states += 1;
2951
2952 decision *d = sinfo->s->singleton ();
2953 merge_pattern_info *pat = sinfo->res->pattern;
2954 pattern_routine *routine = cpi->routine;
2955
2956 /* Create a copy of D's test for the pattern routine and generalize it
2957 as appropriate. */
2958 decision *newd = new decision (d->test);
2959 gcc_assert (newd->test.pos_operand >= 0
2960 || !newd->test.pos
2961 || common_position (newd->test.pos,
2962 routine->pos) == routine->pos);
2963 if (pat->param_test_p)
2964 {
2965 const parameter &param = params[pat->param_test];
2966 switch (newd->test.kind)
2967 {
2968 case rtx_test::PREDICATE:
2969 newd->test.u.predicate.mode_is_param = param.is_param;
2970 newd->test.u.predicate.mode = param.value;
2971 break;
2972
2973 case rtx_test::SAVED_CONST_INT:
2974 newd->test.u.integer.is_param = param.is_param;
2975 newd->test.u.integer.value = param.value;
2976 break;
2977
2978 default:
2979 gcc_unreachable ();
2980 break;
2981 }
2982 }
2983 if (d->test.kind == rtx_test::C_TEST)
2984 routine->insn_p = true;
2985 else if (d->test.kind == rtx_test::HAVE_NUM_CLOBBERS)
2986 routine->pnum_clobbers_p = true;
2987 news->push_back (newd);
2988
2989 /* Fill in the transitions of NEWD. */
2990 unsigned int i = 0;
2991 for (transition *trans = d->first; trans; trans = trans->next)
2992 {
2993 /* Create a new state to act as the target of the new transition. */
2994 state *to_news = new state;
2995 if (merge_pattern_transition *ptrans = pat->transitions[i])
2996 {
2997 /* The pattern hasn't finished matching yet. Get the target
2998 pattern and the corresponding target state of SINFO. */
2999 merge_pattern_info *to_pat = ptrans->to;
3000 merge_state_info *to = sinfo->to_states + i;
3001 gcc_assert (to->res->pattern == to_pat);
3002 gcc_assert (ptrans->params.length () == to_pat->params.length ());
3003
3004 /* Express the parameters to TO_PAT in terms of the parameters
3005 to the top-level pattern. */
3006 auto_vec <parameter, MAX_PATTERN_PARAMS> to_params;
3007 for (unsigned int j = 0; j < ptrans->params.length (); ++j)
3008 {
3009 const parameter &param = ptrans->params[j];
3010 to_params.quick_push (param.is_param
3011 ? params[param.value]
3012 : param);
3013 }
3014
3015 if (same_pattern_p (pat, to_pat))
3016 /* TO_PAT is part of the current routine, so just recurse. */
3017 populate_pattern_routine (cpi, to, to_news, to_params);
3018 else
3019 {
3020 /* TO_PAT should be matched by calling a separate routine. */
3021 create_pattern_info sub_cpi;
3022 decision *subd = init_pattern_use (&sub_cpi, to, to_params);
3023 routine->insn_p |= sub_cpi.routine->insn_p;
3024 routine->pnum_clobbers_p |= sub_cpi.routine->pnum_clobbers_p;
3025
3026 /* Add the pattern routine call to the new target state. */
3027 to_news->push_back (subd);
3028
3029 /* Add a transition for each successful call result. */
3030 for (unsigned int j = 0; j < to_pat->num_results; ++j)
3031 {
3032 state *res = new state;
3033 add_pattern_acceptance (cpi, res);
3034 subd->push_back (new transition (j, res, false));
3035 }
3036 }
3037 }
3038 else
3039 /* This transition corresponds to a successful match. */
3040 add_pattern_acceptance (cpi, to_news);
3041
3042 /* Create the transition itself, generalizing as necessary. */
3043 transition *new_trans = new transition (trans->labels, to_news,
3044 trans->optional);
3045 if (pat->param_transition_p)
3046 {
3047 const parameter &param = params[pat->param_transition];
3048 new_trans->is_param = param.is_param;
3049 new_trans->labels[0] = param.value;
3050 }
3051 newd->push_back (new_trans);
3052 i += 1;
3053 }
3054 }
3055
3056 /* USE is a decision that calls a pattern routine and SINFO is part of the
3057 original state tree that the call is supposed to replace. Add the
3058 transitions for SINFO and its substates to USE. */
3059
3060 static void
3061 populate_pattern_use (create_pattern_info *cpi, decision *use,
3062 merge_state_info *sinfo)
3063 {
3064 pattern_use_states += 1;
3065 gcc_assert (!sinfo->merged_p);
3066 sinfo->merged_p = true;
3067 merge_state_result *res = sinfo->res;
3068 merge_pattern_info *pat = res->pattern;
3069 decision *d = sinfo->s->singleton ();
3070 unsigned int i = 0;
3071 for (transition *trans = d->first; trans; trans = trans->next)
3072 {
3073 if (pat->transitions[i])
3074 /* The target state is also part of the pattern. */
3075 populate_pattern_use (cpi, use, sinfo->to_states + i);
3076 else
3077 {
3078 /* The transition corresponds to a successful return from the
3079 pattern routine. */
3080 use->push_back (new transition (cpi->next_result, trans->to, false));
3081 cpi->next_result += 1;
3082 }
3083 i += 1;
3084 }
3085 }
3086
3087 /* We have decided to replace SINFO's state with a call to a pattern
3088 routine. Make the change, creating a definition of the pattern routine
3089 if it doesn't have one already. */
3090
3091 static void
3092 use_pattern (merge_state_info *sinfo)
3093 {
3094 merge_state_result *res = sinfo->res;
3095 merge_pattern_info *pat = res->pattern;
3096 state *s = sinfo->s;
3097
3098 /* The pattern may have acquired new parameters after it was matched
3099 against SINFO. Update the parameters that SINFO passes accordingly. */
3100 update_parameters (res->params, pat->params);
3101
3102 create_pattern_info cpi;
3103 decision *d = init_pattern_use (&cpi, sinfo, res->params);
3104 populate_pattern_use (&cpi, d, sinfo);
3105 s->release ();
3106 s->push_back (d);
3107 }
3108
3109 /* Look through the state trees in STATES for common patterns and
3110 split them into subroutines. */
3111
3112 static void
3113 split_out_patterns (vec <merge_state_info> &states)
3114 {
3115 unsigned int first_transition = states.length ();
3116 hash_table <test_pattern_hasher> hashtab (128);
3117 /* Stage 1: Create an order in which parent states come before their child
3118 states and in which sibling states are at consecutive locations.
3119 Having consecutive sibling states allows merge_state_info to have
3120 a single to_states pointer. */
3121 for (unsigned int i = 0; i < states.length (); ++i)
3122 for (decision *d = states[i].s->first; d; d = d->next)
3123 for (transition *trans = d->first; trans; trans = trans->next)
3124 {
3125 states.safe_push (trans->to);
3126 states[i].num_transitions += 1;
3127 }
3128 /* Stage 2: Now that the addresses are stable, set up the to_states
3129 pointers. Look for states that might be merged and enter them
3130 into the hash table. */
3131 for (unsigned int i = 0; i < states.length (); ++i)
3132 {
3133 merge_state_info *sinfo = &states[i];
3134 if (sinfo->num_transitions)
3135 {
3136 sinfo->to_states = &states[first_transition];
3137 first_transition += sinfo->num_transitions;
3138 }
3139 /* For simplicity, we only try to merge states that have a single
3140 decision. This is in any case the best we can do for peephole2,
3141 since whether a peephole2 ACCEPT succeeds or not depends on the
3142 specific peephole2 pattern (which is unique to each ACCEPT
3143 and so couldn't be shared between states). */
3144 if (decision *d = sinfo->s->singleton ())
3145 /* ACCEPT states are unique, so don't even try to merge them. */
3146 if (d->test.kind != rtx_test::ACCEPT
3147 && (pattern_have_num_clobbers_p
3148 || d->test.kind != rtx_test::HAVE_NUM_CLOBBERS)
3149 && (pattern_c_test_p
3150 || d->test.kind != rtx_test::C_TEST))
3151 {
3152 merge_state_info **slot = hashtab.find_slot (sinfo, INSERT);
3153 sinfo->prev_same_test = *slot;
3154 *slot = sinfo;
3155 }
3156 }
3157 /* Stage 3: Walk backwards through the list of states and try to merge
3158 them. This is a greedy, bottom-up match; parent nodes can only start
3159 a new leaf pattern if they fail to match when combined with all child
3160 nodes that have matching patterns.
3161
3162 For each state we keep a list of potential matches, with each
3163 potential match being larger (and deeper) than the next match in
3164 the list. The final element in the list is a leaf pattern that
3165 matches just a single state.
3166
3167 Each candidate pattern created in this loop is unique -- it won't
3168 have been seen by an earlier iteration. We try to match each pattern
3169 with every state that appears earlier in STATES.
3170
3171 Because the patterns created in the loop are unique, any state
3172 that already has a match must have a final potential match that
3173 is different from any new leaf pattern. Therefore, when matching
3174 leaf patterns, we need only consider states whose list of matches
3175 is empty.
3176
3177 The non-leaf patterns that we try are as deep as possible
3178 and are an extension of the state's previous best candidate match (PB).
3179 We need only consider states whose current potential match is also PB;
3180 any states that don't match as much as PB cannnot match the new pattern,
3181 while any states that already match more than PB must be different from
3182 the new pattern. */
3183 for (unsigned int i2 = states.length (); i2-- > 0; )
3184 {
3185 merge_state_info *sinfo2 = &states[i2];
3186
3187 /* Enforce the bottom-upness of the match: remove matches with later
3188 states if SINFO2's child states ended up finding a better match. */
3189 prune_invalid_results (sinfo2);
3190
3191 /* Do nothing if the state doesn't match a later one and if there are
3192 no earlier states it could match. */
3193 if (!sinfo2->res && !sinfo2->prev_same_test)
3194 continue;
3195
3196 merge_state_result *res2 = sinfo2->res;
3197 decision *d2 = sinfo2->s->singleton ();
3198 position *root2 = (d2->test.pos_operand < 0 ? d2->test.pos : 0);
3199 unsigned int num_transitions = sinfo2->num_transitions;
3200
3201 /* If RES2 is null then SINFO2's test in isolation has not been seen
3202 before. First try matching that on its own. */
3203 if (!res2)
3204 {
3205 merge_pattern_info *new_pat
3206 = new merge_pattern_info (num_transitions);
3207 merge_state_result *new_res2
3208 = new merge_state_result (new_pat, root2, res2);
3209 sinfo2->res = new_res2;
3210
3211 new_pat->num_statements = !d2->test.single_outcome_p ();
3212 new_pat->num_results = num_transitions;
3213 bool matched_p = false;
3214 /* Look for states that don't currently match anything but
3215 can be made to match SINFO2 on its own. */
3216 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3217 sinfo1 = sinfo1->prev_same_test)
3218 if (!sinfo1->res && merge_patterns (sinfo1, sinfo2))
3219 matched_p = true;
3220 if (!matched_p)
3221 {
3222 /* No other states match. */
3223 sinfo2->res = res2;
3224 delete new_pat;
3225 delete new_res2;
3226 continue;
3227 }
3228 else
3229 res2 = new_res2;
3230 }
3231
3232 /* Keep the existing pattern if it's as good as anything we'd
3233 create for SINFO2. */
3234 if (complete_result_p (res2->pattern, sinfo2))
3235 {
3236 res2->pattern->num_users += 1;
3237 continue;
3238 }
3239
3240 /* Create a new pattern for SINFO2. */
3241 merge_pattern_info *new_pat = new merge_pattern_info (num_transitions);
3242 merge_state_result *new_res2
3243 = new merge_state_result (new_pat, root2, res2);
3244 sinfo2->res = new_res2;
3245
3246 /* Fill in details about the pattern. */
3247 new_pat->num_statements = !d2->test.single_outcome_p ();
3248 new_pat->num_results = 0;
3249 for (unsigned int j = 0; j < num_transitions; ++j)
3250 if (merge_state_result *to_res = sinfo2->to_states[j].res)
3251 {
3252 /* Count the target state as part of this pattern.
3253 First update the root position so that it can reach
3254 the target state's root. */
3255 if (to_res->root)
3256 {
3257 if (new_res2->root)
3258 new_res2->root = common_position (new_res2->root,
3259 to_res->root);
3260 else
3261 new_res2->root = to_res->root;
3262 }
3263 merge_pattern_info *to_pat = to_res->pattern;
3264 merge_pattern_transition *ptrans
3265 = new merge_pattern_transition (to_pat);
3266
3267 /* TO_PAT may have acquired more parameters when matching
3268 states earlier in STATES than TO_RES's, but the list is
3269 now final. Make sure that TO_RES is up to date. */
3270 update_parameters (to_res->params, to_pat->params);
3271
3272 /* Start out by assuming that every user of NEW_PAT will
3273 want to pass the same (constant) parameters as TO_RES. */
3274 update_parameters (ptrans->params, to_res->params);
3275
3276 new_pat->transitions[j] = ptrans;
3277 new_pat->num_statements += to_pat->num_statements;
3278 new_pat->num_results += to_pat->num_results;
3279 }
3280 else
3281 /* The target state doesn't match anything and so is not part
3282 of the pattern. */
3283 new_pat->num_results += 1;
3284
3285 /* See if any earlier states that match RES2's pattern also match
3286 NEW_PAT. */
3287 bool matched_p = false;
3288 for (merge_state_info *sinfo1 = sinfo2->prev_same_test; sinfo1;
3289 sinfo1 = sinfo1->prev_same_test)
3290 {
3291 prune_invalid_results (sinfo1);
3292 if (sinfo1->res
3293 && sinfo1->res->pattern == res2->pattern
3294 && merge_patterns (sinfo1, sinfo2))
3295 matched_p = true;
3296 }
3297 if (!matched_p)
3298 {
3299 /* Nothing else matches NEW_PAT, so go back to the previous
3300 pattern (possibly just a single-state one). */
3301 sinfo2->res = res2;
3302 delete new_pat;
3303 delete new_res2;
3304 }
3305 /* Assume that SINFO2 will use RES. At this point we don't know
3306 whether earlier states that match the same pattern will use
3307 that match or a different one. */
3308 sinfo2->res->pattern->num_users += 1;
3309 }
3310 /* Step 4: Finalize the choice of pattern for each state, ignoring
3311 patterns that were only used once. Update each pattern's size
3312 so that it doesn't include subpatterns that are going to be split
3313 out into subroutines. */
3314 for (unsigned int i = 0; i < states.length (); ++i)
3315 {
3316 merge_state_info *sinfo = &states[i];
3317 merge_state_result *res = sinfo->res;
3318 /* Wind past patterns that are only used by SINFO. */
3319 while (res && res->pattern->num_users == 1)
3320 {
3321 res = res->prev;
3322 sinfo->res = res;
3323 if (res)
3324 res->pattern->num_users += 1;
3325 }
3326 if (!res)
3327 continue;
3328
3329 /* We have a shared pattern and are now committed to the match. */
3330 merge_pattern_info *pat = res->pattern;
3331 gcc_assert (valid_result_p (pat, sinfo));
3332
3333 if (!pat->complete_p)
3334 {
3335 /* Look for subpatterns that are going to be split out and remove
3336 them from the number of statements. */
3337 for (unsigned int j = 0; j < sinfo->num_transitions; ++j)
3338 if (merge_pattern_transition *ptrans = pat->transitions[j])
3339 {
3340 merge_pattern_info *to_pat = ptrans->to;
3341 if (!same_pattern_p (pat, to_pat))
3342 pat->num_statements -= to_pat->num_statements;
3343 }
3344 pat->complete_p = true;
3345 }
3346 }
3347 /* Step 5: Split out the patterns. */
3348 for (unsigned int i = 0; i < states.length (); ++i)
3349 {
3350 merge_state_info *sinfo = &states[i];
3351 merge_state_result *res = sinfo->res;
3352 if (!sinfo->merged_p && res && useful_pattern_p (res->pattern))
3353 use_pattern (sinfo);
3354 }
3355 fprintf (stderr, "Shared %d out of %d states by creating %d new states,"
3356 " saving %d\n",
3357 pattern_use_states, states.length (), pattern_def_states,
3358 pattern_use_states - pattern_def_states);
3359 }
3360
3361 /* Information about a state tree that we're considering splitting into a
3362 subroutine. */
3363 struct state_size
3364 {
3365 /* The number of pseudo-statements in the state tree. */
3366 unsigned int num_statements;
3367
3368 /* The approximate number of nested "if" and "switch" statements that
3369 would be required if control could fall through to a later state. */
3370 unsigned int depth;
3371 };
3372
3373 /* Pairs a transition with information about its target state. */
3374 typedef std::pair <transition *, state_size> subroutine_candidate;
3375
3376 /* Sort two subroutine_candidates so that the one with the largest
3377 number of statements comes last. */
3378
3379 static int
3380 subroutine_candidate_cmp (const void *a, const void *b)
3381 {
3382 return int (((const subroutine_candidate *) a)->second.num_statements
3383 - ((const subroutine_candidate *) b)->second.num_statements);
3384 }
3385
3386 /* Turn S into a subroutine of type TYPE and add it to PROCS. Return a new
3387 state that performs a subroutine call to S. */
3388
3389 static state *
3390 create_subroutine (routine_type type, state *s, vec <state *> &procs)
3391 {
3392 procs.safe_push (s);
3393 acceptance_type acceptance;
3394 acceptance.type = type;
3395 acceptance.partial_p = true;
3396 acceptance.u.subroutine_id = procs.length ();
3397 state *news = new state;
3398 add_decision (news, rtx_test::accept (acceptance), true, false);
3399 return news;
3400 }
3401
3402 /* Walk state tree S, of type TYPE, and look for subtrees that would be
3403 better split into subroutines. Accumulate all such subroutines in PROCS.
3404 Return the size of the new state tree (excluding subroutines). */
3405
3406 static state_size
3407 find_subroutines (routine_type type, state *s, vec <state *> &procs)
3408 {
3409 auto_vec <subroutine_candidate, 16> candidates;
3410 state_size size;
3411 size.num_statements = 0;
3412 size.depth = 0;
3413 for (decision *d = s->first; d; d = d->next)
3414 {
3415 if (!d->test.single_outcome_p ())
3416 size.num_statements += 1;
3417 for (transition *trans = d->first; trans; trans = trans->next)
3418 {
3419 /* Keep chains of simple decisions together if we know that no
3420 change of position is required. We'll output this chain as a
3421 single "if" statement, so it counts as a single nesting level. */
3422 if (d->test.pos && d->if_statement_p ())
3423 for (;;)
3424 {
3425 decision *newd = trans->to->singleton ();
3426 if (!newd
3427 || (newd->test.pos
3428 && newd->test.pos_operand < 0
3429 && newd->test.pos != d->test.pos)
3430 || !newd->if_statement_p ())
3431 break;
3432 if (!newd->test.single_outcome_p ())
3433 size.num_statements += 1;
3434 trans = newd->singleton ();
3435 if (newd->test.kind == rtx_test::SET_OP
3436 || newd->test.kind == rtx_test::ACCEPT)
3437 break;
3438 }
3439 /* The target of TRANS is a subroutine candidate. First recurse
3440 on it to see how big it is after subroutines have been
3441 split out. */
3442 state_size to_size = find_subroutines (type, trans->to, procs);
3443 if (d->next && to_size.depth > MAX_DEPTH)
3444 /* Keeping the target state in the same routine would lead
3445 to an excessive nesting of "if" and "switch" statements.
3446 Split it out into a subroutine so that it can use
3447 inverted tests that return early on failure. */
3448 trans->to = create_subroutine (type, trans->to, procs);
3449 else
3450 {
3451 size.num_statements += to_size.num_statements;
3452 if (to_size.num_statements < MIN_NUM_STATEMENTS)
3453 /* The target state is too small to be worth splitting.
3454 Keep it in the same routine as S. */
3455 size.depth = MAX (size.depth, to_size.depth);
3456 else
3457 /* Assume for now that we'll keep the target state in the
3458 same routine as S, but record it as a subroutine candidate
3459 if S grows too big. */
3460 candidates.safe_push (subroutine_candidate (trans, to_size));
3461 }
3462 }
3463 }
3464 if (size.num_statements > MAX_NUM_STATEMENTS)
3465 {
3466 /* S is too big. Sort the subroutine candidates so that bigger ones
3467 are nearer the end. */
3468 candidates.qsort (subroutine_candidate_cmp);
3469 while (!candidates.is_empty ()
3470 && size.num_statements > MAX_NUM_STATEMENTS)
3471 {
3472 /* Peel off a candidate and force it into a subroutine. */
3473 subroutine_candidate cand = candidates.pop ();
3474 size.num_statements -= cand.second.num_statements;
3475 cand.first->to = create_subroutine (type, cand.first->to, procs);
3476 }
3477 }
3478 /* Update the depth for subroutine candidates that we decided not to
3479 split out. */
3480 for (unsigned int i = 0; i < candidates.length (); ++i)
3481 size.depth = MAX (size.depth, candidates[i].second.depth);
3482 size.depth += 1;
3483 return size;
3484 }
3485
3486 /* Return true if, for all X, PRED (X, MODE) implies that X has mode MODE. */
3487
3488 static bool
3489 safe_predicate_mode (const struct pred_data *pred, machine_mode mode)
3490 {
3491 /* Scalar integer constants have VOIDmode. */
3492 if (GET_MODE_CLASS (mode) == MODE_INT
3493 && (pred->codes[CONST_INT]
3494 || pred->codes[CONST_DOUBLE]
3495 || pred->codes[CONST_WIDE_INT]
3496 || pred->codes[LABEL_REF]))
3497 return false;
3498
3499 return !pred->special && mode != VOIDmode;
3500 }
3501
3502 /* Fill CODES with the set of codes that could be matched by PRED. */
3503
3504 static void
3505 get_predicate_codes (const struct pred_data *pred, int_set *codes)
3506 {
3507 for (int i = 0; i < NUM_TRUE_RTX_CODE; ++i)
3508 if (!pred || pred->codes[i])
3509 codes->safe_push (i);
3510 }
3511
3512 /* Return true if the first path through D1 tests the same thing as D2. */
3513
3514 static bool
3515 has_same_test_p (decision *d1, decision *d2)
3516 {
3517 do
3518 {
3519 if (d1->test == d2->test)
3520 return true;
3521 d1 = d1->first->to->first;
3522 }
3523 while (d1);
3524 return false;
3525 }
3526
3527 /* Return true if D1 and D2 cannot match the same rtx. All states reachable
3528 from D2 have single decisions and all those decisions have single
3529 transitions. */
3530
3531 static bool
3532 mutually_exclusive_p (decision *d1, decision *d2)
3533 {
3534 /* If one path through D1 fails to test the same thing as D2, assume
3535 that D2's test could be true for D1 and look for a later, more useful,
3536 test. This isn't as expensive as it looks in practice. */
3537 while (!has_same_test_p (d1, d2))
3538 {
3539 d2 = d2->singleton ()->to->singleton ();
3540 if (!d2)
3541 return false;
3542 }
3543 if (d1->test == d2->test)
3544 {
3545 /* Look for any transitions from D1 that have the same labels as
3546 the transition from D2. */
3547 transition *trans2 = d2->singleton ();
3548 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3549 {
3550 int_set::iterator i1 = trans1->labels.begin ();
3551 int_set::iterator end1 = trans1->labels.end ();
3552 int_set::iterator i2 = trans2->labels.begin ();
3553 int_set::iterator end2 = trans2->labels.end ();
3554 while (i1 != end1 && i2 != end2)
3555 if (*i1 < *i2)
3556 ++i1;
3557 else if (*i2 < *i1)
3558 ++i2;
3559 else
3560 {
3561 /* TRANS1 has some labels in common with TRANS2. Assume
3562 that D1 and D2 could match the same rtx if the target
3563 of TRANS1 could match the same rtx as D2. */
3564 for (decision *subd1 = trans1->to->first;
3565 subd1; subd1 = subd1->next)
3566 if (!mutually_exclusive_p (subd1, d2))
3567 return false;
3568 break;
3569 }
3570 }
3571 return true;
3572 }
3573 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3574 for (decision *subd1 = trans1->to->first; subd1; subd1 = subd1->next)
3575 if (!mutually_exclusive_p (subd1, d2))
3576 return false;
3577 return true;
3578 }
3579
3580 /* Try to merge S2's decision into D1, given that they have the same test.
3581 Fail only if EXCLUDE is nonnull and the new transition would have the
3582 same labels as *EXCLUDE. When returning true, set *NEXT_S1, *NEXT_S2
3583 and *NEXT_EXCLUDE as for merge_into_state_1, or set *NEXT_S2 to null
3584 if the merge is complete. */
3585
3586 static bool
3587 merge_into_decision (decision *d1, state *s2, const int_set *exclude,
3588 state **next_s1, state **next_s2,
3589 const int_set **next_exclude)
3590 {
3591 decision *d2 = s2->singleton ();
3592 transition *trans2 = d2->singleton ();
3593
3594 /* Get a list of the transitions that intersect TRANS2. */
3595 auto_vec <transition *, 32> intersecting;
3596 for (transition *trans1 = d1->first; trans1; trans1 = trans1->next)
3597 {
3598 int_set::iterator i1 = trans1->labels.begin ();
3599 int_set::iterator end1 = trans1->labels.end ();
3600 int_set::iterator i2 = trans2->labels.begin ();
3601 int_set::iterator end2 = trans2->labels.end ();
3602 bool trans1_is_subset = true;
3603 bool trans2_is_subset = true;
3604 bool intersect_p = false;
3605 while (i1 != end1 && i2 != end2)
3606 if (*i1 < *i2)
3607 {
3608 trans1_is_subset = false;
3609 ++i1;
3610 }
3611 else if (*i2 < *i1)
3612 {
3613 trans2_is_subset = false;
3614 ++i2;
3615 }
3616 else
3617 {
3618 intersect_p = true;
3619 ++i1;
3620 ++i2;
3621 }
3622 if (i1 != end1)
3623 trans1_is_subset = false;
3624 if (i2 != end2)
3625 trans2_is_subset = false;
3626 if (trans1_is_subset && trans2_is_subset)
3627 {
3628 /* There's already a transition that matches exactly.
3629 Merge the target states. */
3630 trans1->optional &= trans2->optional;
3631 *next_s1 = trans1->to;
3632 *next_s2 = trans2->to;
3633 *next_exclude = 0;
3634 return true;
3635 }
3636 if (trans2_is_subset)
3637 {
3638 /* TRANS1 has all the labels that TRANS2 needs. Merge S2 into
3639 the target of TRANS1, but (to avoid infinite recursion)
3640 make sure that we don't end up creating another transition
3641 like TRANS1. */
3642 *next_s1 = trans1->to;
3643 *next_s2 = s2;
3644 *next_exclude = &trans1->labels;
3645 return true;
3646 }
3647 if (intersect_p)
3648 intersecting.safe_push (trans1);
3649 }
3650
3651 if (intersecting.is_empty ())
3652 {
3653 /* No existing labels intersect the new ones. We can just add
3654 TRANS2 itself. */
3655 d1->push_back (d2->release ());
3656 *next_s1 = 0;
3657 *next_s2 = 0;
3658 *next_exclude = 0;
3659 return true;
3660 }
3661
3662 /* Take the union of the labels in INTERSECTING and TRANS2. Store the
3663 result in COMBINED and use NEXT as a temporary. */
3664 int_set tmp1 = trans2->labels, tmp2;
3665 int_set *combined = &tmp1, *next = &tmp2;
3666 for (unsigned int i = 0; i < intersecting.length (); ++i)
3667 {
3668 transition *trans1 = intersecting[i];
3669 next->truncate (0);
3670 next->safe_grow (trans1->labels.length () + combined->length ());
3671 int_set::iterator end
3672 = std::set_union (trans1->labels.begin (), trans1->labels.end (),
3673 combined->begin (), combined->end (),
3674 next->begin ());
3675 next->truncate (end - next->begin ());
3676 std::swap (next, combined);
3677 }
3678
3679 /* Stop now if we've been told not to create a transition with these
3680 labels. */
3681 if (exclude && *combined == *exclude)
3682 return false;
3683
3684 /* Get the transition that should carry the new labels. */
3685 transition *new_trans = intersecting[0];
3686 if (intersecting.length () == 1)
3687 {
3688 /* We're merging with one existing transition whose labels are a
3689 subset of those required. If both transitions are optional,
3690 we can just expand the set of labels so that it's suitable
3691 for both transitions. It isn't worth preserving the original
3692 transitions since we know that they can't be merged; we would
3693 need to backtrack to S2 if TRANS1->to fails. In contrast,
3694 we might be able to merge the targets of the transitions
3695 without any backtracking.
3696
3697 If instead the existing transition is not optional, ensure that
3698 all target decisions are suitably protected. Some decisions
3699 might already have a more specific requirement than NEW_TRANS,
3700 in which case there's no point testing NEW_TRANS as well. E.g. this
3701 would have happened if a test for an (eq ...) rtx had been
3702 added to a decision that tested whether the code is suitable
3703 for comparison_operator. The original comparison_operator
3704 transition would have been non-optional and the (eq ...) test
3705 would be performed by a second decision in the target of that
3706 transition.
3707
3708 The remaining case -- keeping the original optional transition
3709 when adding a non-optional TRANS2 -- is a wash. Preserving
3710 the optional transition only helps if we later merge another
3711 state S3 that is mutually exclusive with S2 and whose labels
3712 belong to *COMBINED - TRANS1->labels. We can then test the
3713 original NEW_TRANS and S3 in the same decision. We keep the
3714 optional transition around for that case, but it occurs very
3715 rarely. */
3716 gcc_assert (new_trans->labels != *combined);
3717 if (!new_trans->optional || !trans2->optional)
3718 {
3719 decision *start = 0;
3720 for (decision *end = new_trans->to->first; end; end = end->next)
3721 {
3722 if (!start && end->test != d1->test)
3723 /* END belongs to a range of decisions that need to be
3724 protected by NEW_TRANS. */
3725 start = end;
3726 if (start && (!end->next || end->next->test == d1->test))
3727 {
3728 /* Protect [START, END] with NEW_TRANS. The decisions
3729 move to NEW_S and NEW_D becomes part of NEW_TRANS->to. */
3730 state *new_s = new state;
3731 decision *new_d = new decision (d1->test);
3732 new_d->push_back (new transition (new_trans->labels, new_s,
3733 new_trans->optional));
3734 state::range r (start, end);
3735 new_trans->to->replace (r, new_d);
3736 new_s->push_back (r);
3737
3738 /* Continue with an empty range. */
3739 start = 0;
3740
3741 /* Continue from the decision after NEW_D. */
3742 end = new_d;
3743 }
3744 }
3745 }
3746 new_trans->optional = true;
3747 new_trans->labels = *combined;
3748 }
3749 else
3750 {
3751 /* We're merging more than one existing transition together.
3752 Those transitions are successfully dividing the matching space
3753 and so we want to preserve them, even if they're optional.
3754
3755 Create a new transition with the union set of labels and make
3756 it go to a state that has the original transitions. */
3757 decision *new_d = new decision (d1->test);
3758 for (unsigned int i = 0; i < intersecting.length (); ++i)
3759 new_d->push_back (d1->remove (intersecting[i]));
3760
3761 state *new_s = new state;
3762 new_s->push_back (new_d);
3763
3764 new_trans = new transition (*combined, new_s, true);
3765 d1->push_back (new_trans);
3766 }
3767
3768 /* We now have an optional transition with labels *COMBINED. Decide
3769 whether we can use it as TRANS2 or whether we need to merge S2
3770 into the target of NEW_TRANS. */
3771 gcc_assert (new_trans->optional);
3772 if (new_trans->labels == trans2->labels)
3773 {
3774 /* NEW_TRANS matches TRANS2. Just merge the target states. */
3775 new_trans->optional = trans2->optional;
3776 *next_s1 = new_trans->to;
3777 *next_s2 = trans2->to;
3778 *next_exclude = 0;
3779 }
3780 else
3781 {
3782 /* Try to merge TRANS2 into the target of the overlapping transition,
3783 but (to prevent infinite recursion or excessive redundancy) without
3784 creating another transition of the same type. */
3785 *next_s1 = new_trans->to;
3786 *next_s2 = s2;
3787 *next_exclude = &new_trans->labels;
3788 }
3789 return true;
3790 }
3791
3792 /* Make progress in merging S2 into S1, given that each state in S2
3793 has a single decision. If EXCLUDE is nonnull, avoid creating a new
3794 transition with the same test as S2's decision and with the labels
3795 in *EXCLUDE.
3796
3797 Return true if there is still work to do. When returning true,
3798 set *NEXT_S1, *NEXT_S2 and *NEXT_EXCLUDE to the values that
3799 S1, S2 and EXCLUDE should have next time round.
3800
3801 If S1 and S2 both match a particular rtx, give priority to S1. */
3802
3803 static bool
3804 merge_into_state_1 (state *s1, state *s2, const int_set *exclude,
3805 state **next_s1, state **next_s2,
3806 const int_set **next_exclude)
3807 {
3808 decision *d2 = s2->singleton ();
3809 if (decision *d1 = s1->last)
3810 {
3811 if (d1->test.terminal_p ())
3812 /* D1 is an unconditional return, so S2 can never match. This can
3813 sometimes be a bug in the .md description, but might also happen
3814 if genconditions forces some conditions to true for certain
3815 configurations. */
3816 return false;
3817
3818 /* Go backwards through the decisions in S1, stopping once we find one
3819 that could match the same thing as S2. */
3820 while (d1->prev && mutually_exclusive_p (d1, d2))
3821 d1 = d1->prev;
3822
3823 /* Search forwards from that point, merging D2 into the first
3824 decision we can. */
3825 for (; d1; d1 = d1->next)
3826 {
3827 /* If S2 performs some optional tests before testing the same thing
3828 as D1, those tests do not help to distinguish D1 and S2, so it's
3829 better to drop them. Search through such optional decisions
3830 until we find something that tests the same thing as D1. */
3831 state *sub_s2 = s2;
3832 for (;;)
3833 {
3834 decision *sub_d2 = sub_s2->singleton ();
3835 if (d1->test == sub_d2->test)
3836 {
3837 /* Only apply EXCLUDE if we're testing the same thing
3838 as D2. */
3839 const int_set *sub_exclude = (d2 == sub_d2 ? exclude : 0);
3840
3841 /* Try to merge SUB_S2 into D1. This can only fail if
3842 it would involve creating a new transition with
3843 labels SUB_EXCLUDE. */
3844 if (merge_into_decision (d1, sub_s2, sub_exclude,
3845 next_s1, next_s2, next_exclude))
3846 return *next_s2 != 0;
3847
3848 /* Can't merge with D1; try a later decision. */
3849 break;
3850 }
3851 transition *sub_trans2 = sub_d2->singleton ();
3852 if (!sub_trans2->optional)
3853 /* Can't merge with D1; try a later decision. */
3854 break;
3855 sub_s2 = sub_trans2->to;
3856 }
3857 }
3858 }
3859
3860 /* We can't merge D2 with any existing decision. Just add it to the end. */
3861 s1->push_back (s2->release ());
3862 return false;
3863 }
3864
3865 /* Merge S2 into S1. If they both match a particular rtx, give
3866 priority to S1. Each state in S2 has a single decision. */
3867
3868 static void
3869 merge_into_state (state *s1, state *s2)
3870 {
3871 const int_set *exclude = 0;
3872 while (s2 && merge_into_state_1 (s1, s2, exclude, &s1, &s2, &exclude))
3873 continue;
3874 }
3875
3876 /* Pairs a pattern that needs to be matched with the rtx position at
3877 which the pattern should occur. */
3878 class pattern_pos {
3879 public:
3880 pattern_pos () {}
3881 pattern_pos (rtx, position *);
3882
3883 rtx pattern;
3884 position *pos;
3885 };
3886
3887 pattern_pos::pattern_pos (rtx pattern_in, position *pos_in)
3888 : pattern (pattern_in), pos (pos_in)
3889 {}
3890
3891 /* Compare entries according to their depth-first order. There shouldn't
3892 be two entries at the same position. */
3893
3894 bool
3895 operator < (const pattern_pos &e1, const pattern_pos &e2)
3896 {
3897 int diff = compare_positions (e1.pos, e2.pos);
3898 gcc_assert (diff != 0 || e1.pattern == e2.pattern);
3899 return diff < 0;
3900 }
3901
3902 /* Add new decisions to S that check whether the rtx at position POS
3903 matches PATTERN. Return the state that is reached in that case.
3904 TOP_PATTERN is the overall pattern, as passed to match_pattern_1. */
3905
3906 static state *
3907 match_pattern_2 (state *s, md_rtx_info *info, position *pos, rtx pattern)
3908 {
3909 auto_vec <pattern_pos, 32> worklist;
3910 auto_vec <pattern_pos, 32> pred_and_mode_tests;
3911 auto_vec <pattern_pos, 32> dup_tests;
3912
3913 worklist.safe_push (pattern_pos (pattern, pos));
3914 while (!worklist.is_empty ())
3915 {
3916 pattern_pos next = worklist.pop ();
3917 pattern = next.pattern;
3918 pos = next.pos;
3919 unsigned int reverse_s = worklist.length ();
3920
3921 enum rtx_code code = GET_CODE (pattern);
3922 switch (code)
3923 {
3924 case MATCH_OP_DUP:
3925 case MATCH_DUP:
3926 case MATCH_PAR_DUP:
3927 /* Add a test that the rtx matches the earlier one, but only
3928 after the structure and predicates have been checked. */
3929 dup_tests.safe_push (pattern_pos (pattern, pos));
3930
3931 /* Use the same code check as the original operand. */
3932 pattern = find_operand (info->def, XINT (pattern, 0), NULL_RTX);
3933 /* Fall through. */
3934
3935 case MATCH_PARALLEL:
3936 case MATCH_OPERAND:
3937 case MATCH_SCRATCH:
3938 case MATCH_OPERATOR:
3939 {
3940 const char *pred_name = predicate_name (pattern);
3941 const struct pred_data *pred = 0;
3942 if (pred_name[0] != 0)
3943 {
3944 pred = lookup_predicate (pred_name);
3945 /* Only report errors once per rtx. */
3946 if (code == GET_CODE (pattern))
3947 {
3948 if (!pred)
3949 error_at (info->loc, "unknown predicate '%s' used in %s",
3950 pred_name, GET_RTX_NAME (code));
3951 else if (code == MATCH_PARALLEL
3952 && pred->singleton != PARALLEL)
3953 error_at (info->loc, "predicate '%s' used in"
3954 " match_parallel does not allow only PARALLEL",
3955 pred->name);
3956 }
3957 }
3958
3959 if (code == MATCH_PARALLEL || code == MATCH_PAR_DUP)
3960 {
3961 /* Check that we have a parallel with enough elements. */
3962 s = add_decision (s, rtx_test::code (pos), PARALLEL, false);
3963 int min_len = XVECLEN (pattern, 2);
3964 s = add_decision (s, rtx_test::veclen_ge (pos, min_len),
3965 true, false);
3966 }
3967 else
3968 {
3969 /* Check that the rtx has one of codes accepted by the
3970 predicate. This is necessary when matching suboperands
3971 of a MATCH_OPERATOR or MATCH_OP_DUP, since we can't
3972 call XEXP (X, N) without checking that X has at least
3973 N+1 operands. */
3974 int_set codes;
3975 get_predicate_codes (pred, &codes);
3976 bool need_codes = (pred
3977 && (code == MATCH_OPERATOR
3978 || code == MATCH_OP_DUP));
3979 s = add_decision (s, rtx_test::code (pos), codes, !need_codes);
3980 }
3981
3982 /* Postpone the predicate check until we've checked the rest
3983 of the rtx structure. */
3984 if (code == GET_CODE (pattern))
3985 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
3986
3987 /* If we need to match suboperands, add them to the worklist. */
3988 if (code == MATCH_OPERATOR || code == MATCH_PARALLEL)
3989 {
3990 position **subpos_ptr;
3991 enum position_type pos_type;
3992 int i;
3993 if (code == MATCH_OPERATOR || code == MATCH_OP_DUP)
3994 {
3995 pos_type = POS_XEXP;
3996 subpos_ptr = &pos->xexps;
3997 i = (code == MATCH_OPERATOR ? 2 : 1);
3998 }
3999 else
4000 {
4001 pos_type = POS_XVECEXP0;
4002 subpos_ptr = &pos->xvecexp0s;
4003 i = 2;
4004 }
4005 for (int j = 0; j < XVECLEN (pattern, i); ++j)
4006 {
4007 position *subpos = next_position (subpos_ptr, pos,
4008 pos_type, j);
4009 worklist.safe_push (pattern_pos (XVECEXP (pattern, i, j),
4010 subpos));
4011 subpos_ptr = &subpos->next;
4012 }
4013 }
4014 break;
4015 }
4016
4017 default:
4018 {
4019 /* Check that the rtx has the right code. */
4020 s = add_decision (s, rtx_test::code (pos), code, false);
4021
4022 /* Queue a test for the mode if one is specified. */
4023 if (GET_MODE (pattern) != VOIDmode)
4024 pred_and_mode_tests.safe_push (pattern_pos (pattern, pos));
4025
4026 /* Push subrtxes onto the worklist. Match nonrtx operands now. */
4027 const char *fmt = GET_RTX_FORMAT (code);
4028 position **subpos_ptr = &pos->xexps;
4029 for (size_t i = 0; fmt[i]; ++i)
4030 {
4031 position *subpos = next_position (subpos_ptr, pos,
4032 POS_XEXP, i);
4033 switch (fmt[i])
4034 {
4035 case 'e': case 'u':
4036 worklist.safe_push (pattern_pos (XEXP (pattern, i),
4037 subpos));
4038 break;
4039
4040 case 'E':
4041 {
4042 /* Make sure the vector has the right number of
4043 elements. */
4044 int length = XVECLEN (pattern, i);
4045 s = add_decision (s, rtx_test::veclen (pos),
4046 length, false);
4047
4048 position **subpos2_ptr = &pos->xvecexp0s;
4049 for (int j = 0; j < length; j++)
4050 {
4051 position *subpos2 = next_position (subpos2_ptr, pos,
4052 POS_XVECEXP0, j);
4053 rtx x = XVECEXP (pattern, i, j);
4054 worklist.safe_push (pattern_pos (x, subpos2));
4055 subpos2_ptr = &subpos2->next;
4056 }
4057 break;
4058 }
4059
4060 case 'i':
4061 /* Make sure that XINT (X, I) has the right value. */
4062 s = add_decision (s, rtx_test::int_field (pos, i),
4063 XINT (pattern, i), false);
4064 break;
4065
4066 case 'r':
4067 /* Make sure that REGNO (X) has the right value. */
4068 gcc_assert (i == 0);
4069 s = add_decision (s, rtx_test::regno_field (pos),
4070 REGNO (pattern), false);
4071 break;
4072
4073 case 'w':
4074 /* Make sure that XWINT (X, I) has the right value. */
4075 s = add_decision (s, rtx_test::wide_int_field (pos, i),
4076 XWINT (pattern, 0), false);
4077 break;
4078
4079 case 'p':
4080 /* We don't have a way of parsing polynomial offsets yet,
4081 and hopefully never will. */
4082 s = add_decision (s, rtx_test::subreg_field (pos),
4083 SUBREG_BYTE (pattern).to_constant (),
4084 false);
4085 break;
4086
4087 case '0':
4088 break;
4089
4090 default:
4091 gcc_unreachable ();
4092 }
4093 subpos_ptr = &subpos->next;
4094 }
4095 }
4096 break;
4097 }
4098 /* Operands are pushed onto the worklist so that later indices are
4099 nearer the top. That's what we want for SETs, since a SET_SRC
4100 is a better discriminator than a SET_DEST. In other cases it's
4101 usually better to match earlier indices first. This is especially
4102 true of PARALLELs, where the first element tends to be the most
4103 individual. It's also true for commutative operators, where the
4104 canonicalization rules say that the more complex operand should
4105 come first. */
4106 if (code != SET && worklist.length () > reverse_s)
4107 std::reverse (&worklist[0] + reverse_s,
4108 &worklist[0] + worklist.length ());
4109 }
4110
4111 /* Sort the predicate and mode tests so that they're in depth-first order.
4112 The main goal of this is to put SET_SRC match_operands after SET_DEST
4113 match_operands and after mode checks for the enclosing SET_SRC operators
4114 (such as the mode of a PLUS in an addition instruction). The latter
4115 two types of test can determine the mode exactly, whereas a SET_SRC
4116 match_operand often has to cope with the possibility of the operand
4117 being a modeless constant integer. E.g. something that matches
4118 register_operand (x, SImode) never matches register_operand (x, DImode),
4119 but a const_int that matches immediate_operand (x, SImode) also matches
4120 immediate_operand (x, DImode). The register_operand cases can therefore
4121 be distinguished by a switch on the mode, but the immediate_operand
4122 cases can't. */
4123 if (pred_and_mode_tests.length () > 1)
4124 std::sort (&pred_and_mode_tests[0],
4125 &pred_and_mode_tests[0] + pred_and_mode_tests.length ());
4126
4127 /* Add the mode and predicate tests. */
4128 pattern_pos *e;
4129 unsigned int i;
4130 FOR_EACH_VEC_ELT (pred_and_mode_tests, i, e)
4131 {
4132 switch (GET_CODE (e->pattern))
4133 {
4134 case MATCH_PARALLEL:
4135 case MATCH_OPERAND:
4136 case MATCH_SCRATCH:
4137 case MATCH_OPERATOR:
4138 {
4139 int opno = XINT (e->pattern, 0);
4140 num_operands = MAX (num_operands, opno + 1);
4141 const char *pred_name = predicate_name (e->pattern);
4142 if (pred_name[0])
4143 {
4144 const struct pred_data *pred = lookup_predicate (pred_name);
4145 /* Check the mode first, to distinguish things like SImode
4146 and DImode register_operands, as described above. */
4147 machine_mode mode = GET_MODE (e->pattern);
4148 if (pred && safe_predicate_mode (pred, mode))
4149 s = add_decision (s, rtx_test::mode (e->pos), mode, true);
4150
4151 /* Assign to operands[] first, so that the rtx usually doesn't
4152 need to be live across the call to the predicate.
4153
4154 This shouldn't cause a problem with dirtying the page,
4155 since we fully expect to assign to operands[] at some point,
4156 and since the caller usually writes to other parts of
4157 recog_data anyway. */
4158 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4159 true, false);
4160 s = add_decision (s, rtx_test::predicate (e->pos, pred, mode),
4161 true, false);
4162 }
4163 else
4164 /* Historically we've ignored the mode when there's no
4165 predicate. Just set up operands[] unconditionally. */
4166 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4167 true, false);
4168 break;
4169 }
4170
4171 default:
4172 s = add_decision (s, rtx_test::mode (e->pos),
4173 GET_MODE (e->pattern), false);
4174 break;
4175 }
4176 }
4177
4178 /* Finally add rtx_equal_p checks for duplicated operands. */
4179 FOR_EACH_VEC_ELT (dup_tests, i, e)
4180 s = add_decision (s, rtx_test::duplicate (e->pos, XINT (e->pattern, 0)),
4181 true, false);
4182 return s;
4183 }
4184
4185 /* Add new decisions to S that make it return ACCEPTANCE if:
4186
4187 (1) the rtx doesn't match anything already matched by S
4188 (2) the rtx matches TOP_PATTERN and
4189 (3) the C test required by INFO->def is true
4190
4191 For peephole2, TOP_PATTERN is a SEQUENCE of the instruction patterns
4192 to match, otherwise it is a single instruction pattern. */
4193
4194 static void
4195 match_pattern_1 (state *s, md_rtx_info *info, rtx pattern,
4196 acceptance_type acceptance)
4197 {
4198 if (acceptance.type == PEEPHOLE2)
4199 {
4200 /* Match each individual instruction. */
4201 position **subpos_ptr = &peep2_insn_pos_list;
4202 int count = 0;
4203 for (int i = 0; i < XVECLEN (pattern, 0); ++i)
4204 {
4205 rtx x = XVECEXP (pattern, 0, i);
4206 position *subpos = next_position (subpos_ptr, &root_pos,
4207 POS_PEEP2_INSN, count);
4208 if (count > 0)
4209 s = add_decision (s, rtx_test::peep2_count (count + 1),
4210 true, false);
4211 s = match_pattern_2 (s, info, subpos, x);
4212 subpos_ptr = &subpos->next;
4213 count += 1;
4214 }
4215 acceptance.u.full.u.match_len = count - 1;
4216 }
4217 else
4218 {
4219 /* Make the rtx itself. */
4220 s = match_pattern_2 (s, info, &root_pos, pattern);
4221
4222 /* If the match is only valid when extra clobbers are added,
4223 make sure we're able to pass that information to the caller. */
4224 if (acceptance.type == RECOG && acceptance.u.full.u.num_clobbers)
4225 s = add_decision (s, rtx_test::have_num_clobbers (), true, false);
4226 }
4227
4228 /* Make sure that the C test is true. */
4229 const char *c_test = get_c_test (info->def);
4230 if (maybe_eval_c_test (c_test) != 1)
4231 s = add_decision (s, rtx_test::c_test (c_test), true, false);
4232
4233 /* Accept the pattern. */
4234 add_decision (s, rtx_test::accept (acceptance), true, false);
4235 }
4236
4237 /* Like match_pattern_1, but (if merge_states_p) try to merge the
4238 decisions with what's already in S, to reduce the amount of
4239 backtracking. */
4240
4241 static void
4242 match_pattern (state *s, md_rtx_info *info, rtx pattern,
4243 acceptance_type acceptance)
4244 {
4245 if (merge_states_p)
4246 {
4247 state root;
4248 /* Add the decisions to a fresh state and then merge the full tree
4249 into the existing one. */
4250 match_pattern_1 (&root, info, pattern, acceptance);
4251 merge_into_state (s, &root);
4252 }
4253 else
4254 match_pattern_1 (s, info, pattern, acceptance);
4255 }
4256
4257 /* Begin the output file. */
4258
4259 static void
4260 write_header (void)
4261 {
4262 puts ("\
4263 /* Generated automatically by the program `genrecog' from the target\n\
4264 machine description file. */\n\
4265 \n\
4266 #define IN_TARGET_CODE 1\n\
4267 \n\
4268 #include \"config.h\"\n\
4269 #include \"system.h\"\n\
4270 #include \"coretypes.h\"\n\
4271 #include \"backend.h\"\n\
4272 #include \"predict.h\"\n\
4273 #include \"rtl.h\"\n\
4274 #include \"memmodel.h\"\n\
4275 #include \"tm_p.h\"\n\
4276 #include \"emit-rtl.h\"\n\
4277 #include \"insn-config.h\"\n\
4278 #include \"recog.h\"\n\
4279 #include \"output.h\"\n\
4280 #include \"flags.h\"\n\
4281 #include \"df.h\"\n\
4282 #include \"resource.h\"\n\
4283 #include \"diagnostic-core.h\"\n\
4284 #include \"reload.h\"\n\
4285 #include \"regs.h\"\n\
4286 #include \"tm-constrs.h\"\n\
4287 \n");
4288
4289 puts ("\n\
4290 /* `recog' contains a decision tree that recognizes whether the rtx\n\
4291 X0 is a valid instruction.\n\
4292 \n\
4293 recog returns -1 if the rtx is not valid. If the rtx is valid, recog\n\
4294 returns a nonnegative number which is the insn code number for the\n\
4295 pattern that matched. This is the same as the order in the machine\n\
4296 description of the entry that matched. This number can be used as an\n\
4297 index into `insn_data' and other tables.\n");
4298 puts ("\
4299 The third parameter to recog is an optional pointer to an int. If\n\
4300 present, recog will accept a pattern if it matches except for missing\n\
4301 CLOBBER expressions at the end. In that case, the value pointed to by\n\
4302 the optional pointer will be set to the number of CLOBBERs that need\n\
4303 to be added (it should be initialized to zero by the caller). If it");
4304 puts ("\
4305 is set nonzero, the caller should allocate a PARALLEL of the\n\
4306 appropriate size, copy the initial entries, and call add_clobbers\n\
4307 (found in insn-emit.c) to fill in the CLOBBERs.\n\
4308 ");
4309
4310 puts ("\n\
4311 The function split_insns returns 0 if the rtl could not\n\
4312 be split or the split rtl as an INSN list if it can be.\n\
4313 \n\
4314 The function peephole2_insns returns 0 if the rtl could not\n\
4315 be matched. If there was a match, the new rtl is returned in an INSN list,\n\
4316 and LAST_INSN will point to the last recognized insn in the old sequence.\n\
4317 */\n\n");
4318 }
4319
4320 /* Return the C type of a parameter with type TYPE. */
4321
4322 static const char *
4323 parameter_type_string (parameter::type_enum type)
4324 {
4325 switch (type)
4326 {
4327 case parameter::UNSET:
4328 break;
4329
4330 case parameter::CODE:
4331 return "rtx_code";
4332
4333 case parameter::MODE:
4334 return "machine_mode";
4335
4336 case parameter::INT:
4337 return "int";
4338
4339 case parameter::UINT:
4340 return "unsigned int";
4341
4342 case parameter::WIDE_INT:
4343 return "HOST_WIDE_INT";
4344 }
4345 gcc_unreachable ();
4346 }
4347
4348 /* Return true if ACCEPTANCE requires only a single C statement even in
4349 a backtracking context. */
4350
4351 static bool
4352 single_statement_p (const acceptance_type &acceptance)
4353 {
4354 if (acceptance.partial_p)
4355 /* We need to handle failures of the subroutine. */
4356 return false;
4357 switch (acceptance.type)
4358 {
4359 case SUBPATTERN:
4360 case SPLIT:
4361 return true;
4362
4363 case RECOG:
4364 /* False if we need to assign to pnum_clobbers. */
4365 return acceptance.u.full.u.num_clobbers == 0;
4366
4367 case PEEPHOLE2:
4368 /* We need to assign to pmatch_len_ and handle null returns from the
4369 peephole2 routine. */
4370 return false;
4371 }
4372 gcc_unreachable ();
4373 }
4374
4375 /* Return the C failure value for a routine of type TYPE. */
4376
4377 static const char *
4378 get_failure_return (routine_type type)
4379 {
4380 switch (type)
4381 {
4382 case SUBPATTERN:
4383 case RECOG:
4384 return "-1";
4385
4386 case SPLIT:
4387 case PEEPHOLE2:
4388 return "NULL";
4389 }
4390 gcc_unreachable ();
4391 }
4392
4393 /* Indicates whether a block of code always returns or whether it can fall
4394 through. */
4395
4396 enum exit_state {
4397 ES_RETURNED,
4398 ES_FALLTHROUGH
4399 };
4400
4401 /* Information used while writing out code. */
4402
4403 class output_state
4404 {
4405 public:
4406 /* The type of routine that we're generating. */
4407 routine_type type;
4408
4409 /* Maps position ids to xN variable numbers. The entry is only valid if
4410 it is less than the length of VAR_TO_ID, but this holds for every position
4411 tested by a state when writing out that state. */
4412 auto_vec <unsigned int> id_to_var;
4413
4414 /* Maps xN variable numbers to position ids. */
4415 auto_vec <unsigned int> var_to_id;
4416
4417 /* Index N is true if variable xN has already been set. */
4418 auto_vec <bool> seen_vars;
4419 };
4420
4421 /* Return true if D is a call to a pattern routine and if there is some X
4422 such that the transition for pattern result N goes to a successful return
4423 with code X+N. When returning true, set *BASE_OUT to this X and *COUNT_OUT
4424 to the number of return values. (We know that every PATTERN decision has
4425 a transition for every successful return.) */
4426
4427 static bool
4428 terminal_pattern_p (decision *d, unsigned int *base_out,
4429 unsigned int *count_out)
4430 {
4431 if (d->test.kind != rtx_test::PATTERN)
4432 return false;
4433 unsigned int base = 0;
4434 unsigned int count = 0;
4435 for (transition *trans = d->first; trans; trans = trans->next)
4436 {
4437 if (trans->is_param || trans->labels.length () != 1)
4438 return false;
4439 decision *subd = trans->to->singleton ();
4440 if (!subd || subd->test.kind != rtx_test::ACCEPT)
4441 return false;
4442 unsigned int this_base = (subd->test.u.acceptance.u.full.code
4443 - trans->labels[0]);
4444 if (trans == d->first)
4445 base = this_base;
4446 else if (base != this_base)
4447 return false;
4448 count += 1;
4449 }
4450 *base_out = base;
4451 *count_out = count;
4452 return true;
4453 }
4454
4455 /* Return true if TEST doesn't test an rtx or if the rtx it tests is
4456 already available in state OS. */
4457
4458 static bool
4459 test_position_available_p (output_state *os, const rtx_test &test)
4460 {
4461 return (!test.pos
4462 || test.pos_operand >= 0
4463 || os->seen_vars[os->id_to_var[test.pos->id]]);
4464 }
4465
4466 /* Like printf, but print INDENT spaces at the beginning. */
4467
4468 static void ATTRIBUTE_PRINTF_2
4469 printf_indent (unsigned int indent, const char *format, ...)
4470 {
4471 va_list ap;
4472 va_start (ap, format);
4473 printf ("%*s", indent, "");
4474 vprintf (format, ap);
4475 va_end (ap);
4476 }
4477
4478 /* Emit code to initialize the variable associated with POS, if it isn't
4479 already valid in state OS. Indent each line by INDENT spaces. Update
4480 OS with the new state. */
4481
4482 static void
4483 change_state (output_state *os, position *pos, unsigned int indent)
4484 {
4485 unsigned int var = os->id_to_var[pos->id];
4486 gcc_assert (var < os->var_to_id.length () && os->var_to_id[var] == pos->id);
4487 if (os->seen_vars[var])
4488 return;
4489 switch (pos->type)
4490 {
4491 case POS_PEEP2_INSN:
4492 printf_indent (indent, "x%d = PATTERN (peep2_next_insn (%d));\n",
4493 var, pos->arg);
4494 break;
4495
4496 case POS_XEXP:
4497 change_state (os, pos->base, indent);
4498 printf_indent (indent, "x%d = XEXP (x%d, %d);\n",
4499 var, os->id_to_var[pos->base->id], pos->arg);
4500 break;
4501
4502 case POS_XVECEXP0:
4503 change_state (os, pos->base, indent);
4504 printf_indent (indent, "x%d = XVECEXP (x%d, 0, %d);\n",
4505 var, os->id_to_var[pos->base->id], pos->arg);
4506 break;
4507 }
4508 os->seen_vars[var] = true;
4509 }
4510
4511 /* Print the enumerator constant for CODE -- the upcase version of
4512 the name. */
4513
4514 static void
4515 print_code (enum rtx_code code)
4516 {
4517 const char *p;
4518 for (p = GET_RTX_NAME (code); *p; p++)
4519 putchar (TOUPPER (*p));
4520 }
4521
4522 /* Emit a uint64_t as an integer constant expression. We need to take
4523 special care to avoid "decimal constant is so large that it is unsigned"
4524 warnings in the resulting code. */
4525
4526 static void
4527 print_host_wide_int (uint64_t val)
4528 {
4529 uint64_t min = uint64_t (1) << (HOST_BITS_PER_WIDE_INT - 1);
4530 if (val == min)
4531 printf ("(" HOST_WIDE_INT_PRINT_DEC_C " - 1)", val + 1);
4532 else
4533 printf (HOST_WIDE_INT_PRINT_DEC_C, val);
4534 }
4535
4536 /* Print the C expression for actual parameter PARAM. */
4537
4538 static void
4539 print_parameter_value (const parameter &param)
4540 {
4541 if (param.is_param)
4542 printf ("i%d", (int) param.value + 1);
4543 else
4544 switch (param.type)
4545 {
4546 case parameter::UNSET:
4547 gcc_unreachable ();
4548 break;
4549
4550 case parameter::CODE:
4551 print_code ((enum rtx_code) param.value);
4552 break;
4553
4554 case parameter::MODE:
4555 printf ("E_%smode", GET_MODE_NAME ((machine_mode) param.value));
4556 break;
4557
4558 case parameter::INT:
4559 printf ("%d", (int) param.value);
4560 break;
4561
4562 case parameter::UINT:
4563 printf ("%u", (unsigned int) param.value);
4564 break;
4565
4566 case parameter::WIDE_INT:
4567 print_host_wide_int (param.value);
4568 break;
4569 }
4570 }
4571
4572 /* Print the C expression for the rtx tested by TEST. */
4573
4574 static void
4575 print_test_rtx (output_state *os, const rtx_test &test)
4576 {
4577 if (test.pos_operand >= 0)
4578 printf ("operands[%d]", test.pos_operand);
4579 else
4580 printf ("x%d", os->id_to_var[test.pos->id]);
4581 }
4582
4583 /* Print the C expression for non-boolean test TEST. */
4584
4585 static void
4586 print_nonbool_test (output_state *os, const rtx_test &test)
4587 {
4588 switch (test.kind)
4589 {
4590 case rtx_test::CODE:
4591 printf ("GET_CODE (");
4592 print_test_rtx (os, test);
4593 printf (")");
4594 break;
4595
4596 case rtx_test::MODE:
4597 printf ("GET_MODE (");
4598 print_test_rtx (os, test);
4599 printf (")");
4600 break;
4601
4602 case rtx_test::VECLEN:
4603 printf ("XVECLEN (");
4604 print_test_rtx (os, test);
4605 printf (", 0)");
4606 break;
4607
4608 case rtx_test::INT_FIELD:
4609 printf ("XINT (");
4610 print_test_rtx (os, test);
4611 printf (", %d)", test.u.opno);
4612 break;
4613
4614 case rtx_test::REGNO_FIELD:
4615 printf ("REGNO (");
4616 print_test_rtx (os, test);
4617 printf (")");
4618 break;
4619
4620 case rtx_test::SUBREG_FIELD:
4621 printf ("SUBREG_BYTE (");
4622 print_test_rtx (os, test);
4623 printf (")");
4624 break;
4625
4626 case rtx_test::WIDE_INT_FIELD:
4627 printf ("XWINT (");
4628 print_test_rtx (os, test);
4629 printf (", %d)", test.u.opno);
4630 break;
4631
4632 case rtx_test::PATTERN:
4633 {
4634 pattern_routine *routine = test.u.pattern->routine;
4635 printf ("pattern%d (", routine->pattern_id);
4636 const char *sep = "";
4637 if (test.pos)
4638 {
4639 print_test_rtx (os, test);
4640 sep = ", ";
4641 }
4642 if (routine->insn_p)
4643 {
4644 printf ("%sinsn", sep);
4645 sep = ", ";
4646 }
4647 if (routine->pnum_clobbers_p)
4648 {
4649 printf ("%spnum_clobbers", sep);
4650 sep = ", ";
4651 }
4652 for (unsigned int i = 0; i < test.u.pattern->params.length (); ++i)
4653 {
4654 fputs (sep, stdout);
4655 print_parameter_value (test.u.pattern->params[i]);
4656 sep = ", ";
4657 }
4658 printf (")");
4659 break;
4660 }
4661
4662 case rtx_test::PEEP2_COUNT:
4663 case rtx_test::VECLEN_GE:
4664 case rtx_test::SAVED_CONST_INT:
4665 case rtx_test::DUPLICATE:
4666 case rtx_test::PREDICATE:
4667 case rtx_test::SET_OP:
4668 case rtx_test::HAVE_NUM_CLOBBERS:
4669 case rtx_test::C_TEST:
4670 case rtx_test::ACCEPT:
4671 gcc_unreachable ();
4672 }
4673 }
4674
4675 /* IS_PARAM and LABEL are taken from a transition whose source
4676 decision performs TEST. Print the C code for the label. */
4677
4678 static void
4679 print_label_value (const rtx_test &test, bool is_param, uint64_t value)
4680 {
4681 print_parameter_value (parameter (transition_parameter_type (test.kind),
4682 is_param, value));
4683 }
4684
4685 /* If IS_PARAM, print code to compare TEST with the C variable i<VALUE+1>.
4686 If !IS_PARAM, print code to compare TEST with the C constant VALUE.
4687 Test for inequality if INVERT_P, otherwise test for equality. */
4688
4689 static void
4690 print_test (output_state *os, const rtx_test &test, bool is_param,
4691 uint64_t value, bool invert_p)
4692 {
4693 switch (test.kind)
4694 {
4695 /* Handle the non-boolean TESTs. */
4696 case rtx_test::CODE:
4697 case rtx_test::MODE:
4698 case rtx_test::VECLEN:
4699 case rtx_test::REGNO_FIELD:
4700 case rtx_test::INT_FIELD:
4701 case rtx_test::WIDE_INT_FIELD:
4702 case rtx_test::PATTERN:
4703 print_nonbool_test (os, test);
4704 printf (" %s ", invert_p ? "!=" : "==");
4705 print_label_value (test, is_param, value);
4706 break;
4707
4708 case rtx_test::SUBREG_FIELD:
4709 printf ("%s (", invert_p ? "maybe_ne" : "known_eq");
4710 print_nonbool_test (os, test);
4711 printf (", ");
4712 print_label_value (test, is_param, value);
4713 printf (")");
4714 break;
4715
4716 case rtx_test::SAVED_CONST_INT:
4717 gcc_assert (!is_param && value == 1);
4718 print_test_rtx (os, test);
4719 printf (" %s const_int_rtx[MAX_SAVED_CONST_INT + ",
4720 invert_p ? "!=" : "==");
4721 print_parameter_value (parameter (parameter::INT,
4722 test.u.integer.is_param,
4723 test.u.integer.value));
4724 printf ("]");
4725 break;
4726
4727 case rtx_test::PEEP2_COUNT:
4728 gcc_assert (!is_param && value == 1);
4729 printf ("peep2_current_count %s %d", invert_p ? "<" : ">=",
4730 test.u.min_len);
4731 break;
4732
4733 case rtx_test::VECLEN_GE:
4734 gcc_assert (!is_param && value == 1);
4735 printf ("XVECLEN (");
4736 print_test_rtx (os, test);
4737 printf (", 0) %s %d", invert_p ? "<" : ">=", test.u.min_len);
4738 break;
4739
4740 case rtx_test::PREDICATE:
4741 gcc_assert (!is_param && value == 1);
4742 printf ("%s%s (", invert_p ? "!" : "", test.u.predicate.data->name);
4743 print_test_rtx (os, test);
4744 printf (", ");
4745 print_parameter_value (parameter (parameter::MODE,
4746 test.u.predicate.mode_is_param,
4747 test.u.predicate.mode));
4748 printf (")");
4749 break;
4750
4751 case rtx_test::DUPLICATE:
4752 gcc_assert (!is_param && value == 1);
4753 printf ("%srtx_equal_p (", invert_p ? "!" : "");
4754 print_test_rtx (os, test);
4755 printf (", operands[%d])", test.u.opno);
4756 break;
4757
4758 case rtx_test::HAVE_NUM_CLOBBERS:
4759 gcc_assert (!is_param && value == 1);
4760 printf ("pnum_clobbers %s NULL", invert_p ? "==" : "!=");
4761 break;
4762
4763 case rtx_test::C_TEST:
4764 gcc_assert (!is_param && value == 1);
4765 if (invert_p)
4766 printf ("!");
4767 rtx_reader_ptr->print_c_condition (test.u.string);
4768 break;
4769
4770 case rtx_test::ACCEPT:
4771 case rtx_test::SET_OP:
4772 gcc_unreachable ();
4773 }
4774 }
4775
4776 static exit_state print_decision (output_state *, decision *,
4777 unsigned int, bool);
4778
4779 /* Print code to perform S, indent each line by INDENT spaces.
4780 IS_FINAL is true if there are no fallback decisions to test on failure;
4781 if the state fails then the entire routine fails. */
4782
4783 static exit_state
4784 print_state (output_state *os, state *s, unsigned int indent, bool is_final)
4785 {
4786 exit_state es = ES_FALLTHROUGH;
4787 for (decision *d = s->first; d; d = d->next)
4788 es = print_decision (os, d, indent, is_final && !d->next);
4789 if (es != ES_RETURNED && is_final)
4790 {
4791 printf_indent (indent, "return %s;\n", get_failure_return (os->type));
4792 es = ES_RETURNED;
4793 }
4794 return es;
4795 }
4796
4797 /* Print the code for subroutine call ACCEPTANCE (for which partial_p
4798 is known to be true). Return the C condition that indicates a successful
4799 match. */
4800
4801 static const char *
4802 print_subroutine_call (const acceptance_type &acceptance)
4803 {
4804 switch (acceptance.type)
4805 {
4806 case SUBPATTERN:
4807 gcc_unreachable ();
4808
4809 case RECOG:
4810 printf ("recog_%d (x1, insn, pnum_clobbers)",
4811 acceptance.u.subroutine_id);
4812 return ">= 0";
4813
4814 case SPLIT:
4815 printf ("split_%d (x1, insn)", acceptance.u.subroutine_id);
4816 return "!= NULL_RTX";
4817
4818 case PEEPHOLE2:
4819 printf ("peephole2_%d (x1, insn, pmatch_len_)",
4820 acceptance.u.subroutine_id);
4821 return "!= NULL_RTX";
4822 }
4823 gcc_unreachable ();
4824 }
4825
4826 /* Print code for the successful match described by ACCEPTANCE.
4827 INDENT and IS_FINAL are as for print_state. */
4828
4829 static exit_state
4830 print_acceptance (const acceptance_type &acceptance, unsigned int indent,
4831 bool is_final)
4832 {
4833 if (acceptance.partial_p)
4834 {
4835 /* Defer the rest of the match to a subroutine. */
4836 if (is_final)
4837 {
4838 printf_indent (indent, "return ");
4839 print_subroutine_call (acceptance);
4840 printf (";\n");
4841 return ES_RETURNED;
4842 }
4843 else
4844 {
4845 printf_indent (indent, "res = ");
4846 const char *res_test = print_subroutine_call (acceptance);
4847 printf (";\n");
4848 printf_indent (indent, "if (res %s)\n", res_test);
4849 printf_indent (indent + 2, "return res;\n");
4850 return ES_FALLTHROUGH;
4851 }
4852 }
4853 switch (acceptance.type)
4854 {
4855 case SUBPATTERN:
4856 printf_indent (indent, "return %d;\n", acceptance.u.full.code);
4857 return ES_RETURNED;
4858
4859 case RECOG:
4860 if (acceptance.u.full.u.num_clobbers != 0)
4861 printf_indent (indent, "*pnum_clobbers = %d;\n",
4862 acceptance.u.full.u.num_clobbers);
4863 printf_indent (indent, "return %d; /* %s */\n", acceptance.u.full.code,
4864 get_insn_name (acceptance.u.full.code));
4865 return ES_RETURNED;
4866
4867 case SPLIT:
4868 printf_indent (indent, "return gen_split_%d (insn, operands);\n",
4869 acceptance.u.full.code);
4870 return ES_RETURNED;
4871
4872 case PEEPHOLE2:
4873 printf_indent (indent, "*pmatch_len_ = %d;\n",
4874 acceptance.u.full.u.match_len);
4875 if (is_final)
4876 {
4877 printf_indent (indent, "return gen_peephole2_%d (insn, operands);\n",
4878 acceptance.u.full.code);
4879 return ES_RETURNED;
4880 }
4881 else
4882 {
4883 printf_indent (indent, "res = gen_peephole2_%d (insn, operands);\n",
4884 acceptance.u.full.code);
4885 printf_indent (indent, "if (res != NULL_RTX)\n");
4886 printf_indent (indent + 2, "return res;\n");
4887 return ES_FALLTHROUGH;
4888 }
4889 }
4890 gcc_unreachable ();
4891 }
4892
4893 /* Print code to perform D. INDENT and IS_FINAL are as for print_state. */
4894
4895 static exit_state
4896 print_decision (output_state *os, decision *d, unsigned int indent,
4897 bool is_final)
4898 {
4899 uint64_t label;
4900 unsigned int base, count;
4901
4902 /* Make sure the rtx under test is available either in operands[] or
4903 in an xN variable. */
4904 if (d->test.pos && d->test.pos_operand < 0)
4905 change_state (os, d->test.pos, indent);
4906
4907 /* Look for cases where a pattern routine P1 calls another pattern routine
4908 P2 and where P1 returns X + BASE whenever P2 returns X. If IS_FINAL
4909 is true and BASE is zero we can simply use:
4910
4911 return patternN (...);
4912
4913 Otherwise we can use:
4914
4915 res = patternN (...);
4916 if (res >= 0)
4917 return res + BASE;
4918
4919 However, if BASE is nonzero and patternN only returns 0 or -1,
4920 the usual "return BASE;" is better than "return res + BASE;".
4921 If BASE is zero, "return res;" should be better than "return 0;",
4922 since no assignment to the return register is required. */
4923 if (os->type == SUBPATTERN
4924 && terminal_pattern_p (d, &base, &count)
4925 && (base == 0 || count > 1))
4926 {
4927 if (is_final && base == 0)
4928 {
4929 printf_indent (indent, "return ");
4930 print_nonbool_test (os, d->test);
4931 printf ("; /* [-1, %d] */\n", count - 1);
4932 return ES_RETURNED;
4933 }
4934 else
4935 {
4936 printf_indent (indent, "res = ");
4937 print_nonbool_test (os, d->test);
4938 printf (";\n");
4939 printf_indent (indent, "if (res >= 0)\n");
4940 printf_indent (indent + 2, "return res");
4941 if (base != 0)
4942 printf (" + %d", base);
4943 printf ("; /* [%d, %d] */\n", base, base + count - 1);
4944 return ES_FALLTHROUGH;
4945 }
4946 }
4947 else if (d->test.kind == rtx_test::ACCEPT)
4948 return print_acceptance (d->test.u.acceptance, indent, is_final);
4949 else if (d->test.kind == rtx_test::SET_OP)
4950 {
4951 printf_indent (indent, "operands[%d] = ", d->test.u.opno);
4952 print_test_rtx (os, d->test);
4953 printf (";\n");
4954 return print_state (os, d->singleton ()->to, indent, is_final);
4955 }
4956 /* Handle decisions with a single transition and a single transition
4957 label. */
4958 else if (d->if_statement_p (&label))
4959 {
4960 transition *trans = d->singleton ();
4961 if (mark_optional_transitions_p && trans->optional)
4962 printf_indent (indent, "/* OPTIONAL IF */\n");
4963
4964 /* Print the condition associated with TRANS. Invert it if IS_FINAL,
4965 so that we return immediately on failure and fall through on
4966 success. */
4967 printf_indent (indent, "if (");
4968 print_test (os, d->test, trans->is_param, label, is_final);
4969
4970 /* Look for following states that would be handled by this code
4971 on recursion. If they don't need any preparatory statements,
4972 include them in the current "if" statement rather than creating
4973 a new one. */
4974 for (;;)
4975 {
4976 d = trans->to->singleton ();
4977 if (!d
4978 || d->test.kind == rtx_test::ACCEPT
4979 || d->test.kind == rtx_test::SET_OP
4980 || !d->if_statement_p (&label)
4981 || !test_position_available_p (os, d->test))
4982 break;
4983 trans = d->first;
4984 printf ("\n");
4985 if (mark_optional_transitions_p && trans->optional)
4986 printf_indent (indent + 4, "/* OPTIONAL IF */\n");
4987 printf_indent (indent + 4, "%s ", is_final ? "||" : "&&");
4988 print_test (os, d->test, trans->is_param, label, is_final);
4989 }
4990 printf (")\n");
4991
4992 /* Print the conditional code with INDENT + 2 and the fallthrough
4993 code with indent INDENT. */
4994 state *to = trans->to;
4995 if (is_final)
4996 {
4997 /* We inverted the condition above, so return failure in the
4998 "if" body and fall through to the target of the transition. */
4999 printf_indent (indent + 2, "return %s;\n",
5000 get_failure_return (os->type));
5001 return print_state (os, to, indent, is_final);
5002 }
5003 else if (to->singleton ()
5004 && to->first->test.kind == rtx_test::ACCEPT
5005 && single_statement_p (to->first->test.u.acceptance))
5006 {
5007 /* The target of the transition is a simple "return" statement.
5008 It doesn't need any braces and doesn't fall through. */
5009 if (print_acceptance (to->first->test.u.acceptance,
5010 indent + 2, true) != ES_RETURNED)
5011 gcc_unreachable ();
5012 return ES_FALLTHROUGH;
5013 }
5014 else
5015 {
5016 /* The general case. Output code for the target of the transition
5017 in braces. This will not invalidate any of the xN variables
5018 that are already valid, but we mustn't rely on any that are
5019 set by the "if" body. */
5020 auto_vec <bool, 32> old_seen;
5021 old_seen.safe_splice (os->seen_vars);
5022
5023 printf_indent (indent + 2, "{\n");
5024 print_state (os, trans->to, indent + 4, is_final);
5025 printf_indent (indent + 2, "}\n");
5026
5027 os->seen_vars.truncate (0);
5028 os->seen_vars.splice (old_seen);
5029 return ES_FALLTHROUGH;
5030 }
5031 }
5032 else
5033 {
5034 /* Output the decision as a switch statement. */
5035 printf_indent (indent, "switch (");
5036 print_nonbool_test (os, d->test);
5037 printf (")\n");
5038
5039 /* Each case statement starts with the same set of valid variables.
5040 These are also the only variables will be valid on fallthrough. */
5041 auto_vec <bool, 32> old_seen;
5042 old_seen.safe_splice (os->seen_vars);
5043
5044 printf_indent (indent + 2, "{\n");
5045 for (transition *trans = d->first; trans; trans = trans->next)
5046 {
5047 gcc_assert (!trans->is_param);
5048 if (mark_optional_transitions_p && trans->optional)
5049 printf_indent (indent + 2, "/* OPTIONAL CASE */\n");
5050 for (int_set::iterator j = trans->labels.begin ();
5051 j != trans->labels.end (); ++j)
5052 {
5053 printf_indent (indent + 2, "case ");
5054 print_label_value (d->test, trans->is_param, *j);
5055 printf (":\n");
5056 }
5057 if (print_state (os, trans->to, indent + 4, is_final))
5058 {
5059 /* The state can fall through. Add an explicit break. */
5060 gcc_assert (!is_final);
5061 printf_indent (indent + 4, "break;\n");
5062 }
5063 printf ("\n");
5064
5065 /* Restore the original set of valid variables. */
5066 os->seen_vars.truncate (0);
5067 os->seen_vars.splice (old_seen);
5068 }
5069 /* Add a default case. */
5070 printf_indent (indent + 2, "default:\n");
5071 if (is_final)
5072 printf_indent (indent + 4, "return %s;\n",
5073 get_failure_return (os->type));
5074 else
5075 printf_indent (indent + 4, "break;\n");
5076 printf_indent (indent + 2, "}\n");
5077 return is_final ? ES_RETURNED : ES_FALLTHROUGH;
5078 }
5079 }
5080
5081 /* Make sure that OS has a position variable for POS. ROOT_P is true if
5082 POS is the root position for the routine. */
5083
5084 static void
5085 assign_position_var (output_state *os, position *pos, bool root_p)
5086 {
5087 unsigned int idx = os->id_to_var[pos->id];
5088 if (idx < os->var_to_id.length () && os->var_to_id[idx] == pos->id)
5089 return;
5090 if (!root_p && pos->type != POS_PEEP2_INSN)
5091 assign_position_var (os, pos->base, false);
5092 os->id_to_var[pos->id] = os->var_to_id.length ();
5093 os->var_to_id.safe_push (pos->id);
5094 }
5095
5096 /* Make sure that OS has the position variables required by S. */
5097
5098 static void
5099 assign_position_vars (output_state *os, state *s)
5100 {
5101 for (decision *d = s->first; d; d = d->next)
5102 {
5103 /* Positions associated with operands can be read from the
5104 operands[] array. */
5105 if (d->test.pos && d->test.pos_operand < 0)
5106 assign_position_var (os, d->test.pos, false);
5107 for (transition *trans = d->first; trans; trans = trans->next)
5108 assign_position_vars (os, trans->to);
5109 }
5110 }
5111
5112 /* Print the open brace and variable definitions for a routine that
5113 implements S. ROOT is the deepest rtx from which S can access all
5114 relevant parts of the first instruction it matches. Initialize OS
5115 so that every relevant position has an rtx variable xN and so that
5116 only ROOT's variable has a valid value. */
5117
5118 static void
5119 print_subroutine_start (output_state *os, state *s, position *root)
5120 {
5121 printf ("{\n rtx * const operands ATTRIBUTE_UNUSED"
5122 " = &recog_data.operand[0];\n");
5123 os->var_to_id.truncate (0);
5124 os->seen_vars.truncate (0);
5125 if (root)
5126 {
5127 /* Create a fake entry for position 0 so that an id_to_var of 0
5128 is always invalid. This also makes the xN variables naturally
5129 1-based rather than 0-based. */
5130 os->var_to_id.safe_push (num_positions);
5131
5132 /* Associate ROOT with x1. */
5133 assign_position_var (os, root, true);
5134
5135 /* Assign xN variables to all other relevant positions. */
5136 assign_position_vars (os, s);
5137
5138 /* Output the variable declarations (except for ROOT's, which is
5139 passed in as a parameter). */
5140 unsigned int num_vars = os->var_to_id.length ();
5141 if (num_vars > 2)
5142 {
5143 for (unsigned int i = 2; i < num_vars; ++i)
5144 /* Print 8 rtx variables to a line. */
5145 printf ("%s x%d",
5146 i == 2 ? " rtx" : (i - 2) % 8 == 0 ? ";\n rtx" : ",", i);
5147 printf (";\n");
5148 }
5149
5150 /* Say that x1 is valid and the rest aren't. */
5151 os->seen_vars.safe_grow_cleared (num_vars);
5152 os->seen_vars[1] = true;
5153 }
5154 if (os->type == SUBPATTERN || os->type == RECOG)
5155 printf (" int res ATTRIBUTE_UNUSED;\n");
5156 else
5157 printf (" rtx_insn *res ATTRIBUTE_UNUSED;\n");
5158 }
5159
5160 /* Output the definition of pattern routine ROUTINE. */
5161
5162 static void
5163 print_pattern (output_state *os, pattern_routine *routine)
5164 {
5165 printf ("\nstatic int\npattern%d (", routine->pattern_id);
5166 const char *sep = "";
5167 /* Add the top-level rtx parameter, if any. */
5168 if (routine->pos)
5169 {
5170 printf ("%srtx x1", sep);
5171 sep = ", ";
5172 }
5173 /* Add the optional parameters. */
5174 if (routine->insn_p)
5175 {
5176 /* We can't easily tell whether a C condition actually reads INSN,
5177 so add an ATTRIBUTE_UNUSED just in case. */
5178 printf ("%srtx_insn *insn ATTRIBUTE_UNUSED", sep);
5179 sep = ", ";
5180 }
5181 if (routine->pnum_clobbers_p)
5182 {
5183 printf ("%sint *pnum_clobbers", sep);
5184 sep = ", ";
5185 }
5186 /* Add the "i" parameters. */
5187 for (unsigned int i = 0; i < routine->param_types.length (); ++i)
5188 {
5189 printf ("%s%s i%d", sep,
5190 parameter_type_string (routine->param_types[i]), i + 1);
5191 sep = ", ";
5192 }
5193 printf (")\n");
5194 os->type = SUBPATTERN;
5195 print_subroutine_start (os, routine->s, routine->pos);
5196 print_state (os, routine->s, 2, true);
5197 printf ("}\n");
5198 }
5199
5200 /* Output a routine of type TYPE that implements S. PROC_ID is the
5201 number of the subroutine associated with S, or 0 if S is the main
5202 routine. */
5203
5204 static void
5205 print_subroutine (output_state *os, state *s, int proc_id)
5206 {
5207 printf ("\n");
5208 switch (os->type)
5209 {
5210 case SUBPATTERN:
5211 gcc_unreachable ();
5212
5213 case RECOG:
5214 if (proc_id)
5215 printf ("static int\nrecog_%d", proc_id);
5216 else
5217 printf ("int\nrecog");
5218 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5219 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5220 "\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n");
5221 break;
5222
5223 case SPLIT:
5224 if (proc_id)
5225 printf ("static rtx_insn *\nsplit_%d", proc_id);
5226 else
5227 printf ("rtx_insn *\nsplit_insns");
5228 printf (" (rtx x1 ATTRIBUTE_UNUSED, rtx_insn *insn ATTRIBUTE_UNUSED)\n");
5229 break;
5230
5231 case PEEPHOLE2:
5232 if (proc_id)
5233 printf ("static rtx_insn *\npeephole2_%d", proc_id);
5234 else
5235 printf ("rtx_insn *\npeephole2_insns");
5236 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
5237 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5238 "\tint *pmatch_len_ ATTRIBUTE_UNUSED)\n");
5239 break;
5240 }
5241 print_subroutine_start (os, s, &root_pos);
5242 if (proc_id == 0)
5243 {
5244 printf (" recog_data.insn = NULL;\n");
5245 }
5246 print_state (os, s, 2, true);
5247 printf ("}\n");
5248 }
5249
5250 /* Print out a routine of type TYPE that performs ROOT. */
5251
5252 static void
5253 print_subroutine_group (output_state *os, routine_type type, state *root)
5254 {
5255 os->type = type;
5256 if (use_subroutines_p)
5257 {
5258 /* Split ROOT up into smaller pieces, both for readability and to
5259 help the compiler. */
5260 auto_vec <state *> subroutines;
5261 find_subroutines (type, root, subroutines);
5262
5263 /* Output the subroutines (but not ROOT itself). */
5264 unsigned int i;
5265 state *s;
5266 FOR_EACH_VEC_ELT (subroutines, i, s)
5267 print_subroutine (os, s, i + 1);
5268 }
5269 /* Output the main routine. */
5270 print_subroutine (os, root, 0);
5271 }
5272
5273 /* Return the rtx pattern for the list of rtxes in a define_peephole2. */
5274
5275 static rtx
5276 get_peephole2_pattern (md_rtx_info *info)
5277 {
5278 int i, j;
5279 rtvec vec = XVEC (info->def, 0);
5280 rtx pattern = rtx_alloc (SEQUENCE);
5281 XVEC (pattern, 0) = rtvec_alloc (GET_NUM_ELEM (vec));
5282 for (i = j = 0; i < GET_NUM_ELEM (vec); i++)
5283 {
5284 rtx x = RTVEC_ELT (vec, i);
5285 /* Ignore scratch register requirements. */
5286 if (GET_CODE (x) != MATCH_SCRATCH && GET_CODE (x) != MATCH_DUP)
5287 {
5288 XVECEXP (pattern, 0, j) = x;
5289 j++;
5290 }
5291 }
5292 XVECLEN (pattern, 0) = j;
5293 if (j == 0)
5294 error_at (info->loc, "empty define_peephole2");
5295 return pattern;
5296 }
5297
5298 /* Return true if *PATTERN_PTR is a PARALLEL in which at least one trailing
5299 rtx can be added automatically by add_clobbers. If so, update
5300 *ACCEPTANCE_PTR so that its num_clobbers field contains the number
5301 of such trailing rtxes and update *PATTERN_PTR so that it contains
5302 the pattern without those rtxes. */
5303
5304 static bool
5305 remove_clobbers (acceptance_type *acceptance_ptr, rtx *pattern_ptr)
5306 {
5307 int i;
5308 rtx new_pattern;
5309
5310 /* Find the last non-clobber in the parallel. */
5311 rtx pattern = *pattern_ptr;
5312 for (i = XVECLEN (pattern, 0); i > 0; i--)
5313 {
5314 rtx x = XVECEXP (pattern, 0, i - 1);
5315 if (GET_CODE (x) != CLOBBER
5316 || (!REG_P (XEXP (x, 0))
5317 && GET_CODE (XEXP (x, 0)) != MATCH_SCRATCH))
5318 break;
5319 }
5320
5321 if (i == XVECLEN (pattern, 0))
5322 return false;
5323
5324 /* Build a similar insn without the clobbers. */
5325 if (i == 1)
5326 new_pattern = XVECEXP (pattern, 0, 0);
5327 else
5328 {
5329 new_pattern = rtx_alloc (PARALLEL);
5330 XVEC (new_pattern, 0) = rtvec_alloc (i);
5331 for (int j = 0; j < i; ++j)
5332 XVECEXP (new_pattern, 0, j) = XVECEXP (pattern, 0, j);
5333 }
5334
5335 /* Recognize it. */
5336 acceptance_ptr->u.full.u.num_clobbers = XVECLEN (pattern, 0) - i;
5337 *pattern_ptr = new_pattern;
5338 return true;
5339 }
5340
5341 int
5342 main (int argc, const char **argv)
5343 {
5344 state insn_root, split_root, peephole2_root;
5345
5346 progname = "genrecog";
5347
5348 if (!init_rtx_reader_args (argc, argv))
5349 return (FATAL_EXIT_CODE);
5350
5351 write_header ();
5352
5353 /* Read the machine description. */
5354
5355 md_rtx_info info;
5356 while (read_md_rtx (&info))
5357 {
5358 rtx def = info.def;
5359
5360 acceptance_type acceptance;
5361 acceptance.partial_p = false;
5362 acceptance.u.full.code = info.index;
5363
5364 rtx pattern;
5365 switch (GET_CODE (def))
5366 {
5367 case DEFINE_INSN:
5368 {
5369 /* Match the instruction in the original .md form. */
5370 acceptance.type = RECOG;
5371 acceptance.u.full.u.num_clobbers = 0;
5372 pattern = add_implicit_parallel (XVEC (def, 1));
5373 validate_pattern (pattern, &info, NULL_RTX, 0);
5374 match_pattern (&insn_root, &info, pattern, acceptance);
5375
5376 /* If the pattern is a PARALLEL with trailing CLOBBERs,
5377 allow recog_for_combine to match without the clobbers. */
5378 if (GET_CODE (pattern) == PARALLEL
5379 && remove_clobbers (&acceptance, &pattern))
5380 match_pattern (&insn_root, &info, pattern, acceptance);
5381 break;
5382 }
5383
5384 case DEFINE_SPLIT:
5385 acceptance.type = SPLIT;
5386 pattern = add_implicit_parallel (XVEC (def, 0));
5387 validate_pattern (pattern, &info, NULL_RTX, 0);
5388 match_pattern (&split_root, &info, pattern, acceptance);
5389
5390 /* Declare the gen_split routine that we'll call if the
5391 pattern matches. The definition comes from insn-emit.c. */
5392 printf ("extern rtx_insn *gen_split_%d (rtx_insn *, rtx *);\n",
5393 info.index);
5394 break;
5395
5396 case DEFINE_PEEPHOLE2:
5397 acceptance.type = PEEPHOLE2;
5398 pattern = get_peephole2_pattern (&info);
5399 validate_pattern (pattern, &info, NULL_RTX, 0);
5400 match_pattern (&peephole2_root, &info, pattern, acceptance);
5401
5402 /* Declare the gen_peephole2 routine that we'll call if the
5403 pattern matches. The definition comes from insn-emit.c. */
5404 printf ("extern rtx_insn *gen_peephole2_%d (rtx_insn *, rtx *);\n",
5405 info.index);
5406 break;
5407
5408 default:
5409 /* do nothing */;
5410 }
5411 }
5412
5413 if (have_error)
5414 return FATAL_EXIT_CODE;
5415
5416 puts ("\n\n");
5417
5418 /* Optimize each routine in turn. */
5419 optimize_subroutine_group ("recog", &insn_root);
5420 optimize_subroutine_group ("split_insns", &split_root);
5421 optimize_subroutine_group ("peephole2_insns", &peephole2_root);
5422
5423 output_state os;
5424 os.id_to_var.safe_grow_cleared (num_positions);
5425
5426 if (use_pattern_routines_p)
5427 {
5428 /* Look for common patterns and split them out into subroutines. */
5429 auto_vec <merge_state_info> states;
5430 states.safe_push (&insn_root);
5431 states.safe_push (&split_root);
5432 states.safe_push (&peephole2_root);
5433 split_out_patterns (states);
5434
5435 /* Print out the routines that we just created. */
5436 unsigned int i;
5437 pattern_routine *routine;
5438 FOR_EACH_VEC_ELT (patterns, i, routine)
5439 print_pattern (&os, routine);
5440 }
5441
5442 /* Print out the matching routines. */
5443 print_subroutine_group (&os, RECOG, &insn_root);
5444 print_subroutine_group (&os, SPLIT, &split_root);
5445 print_subroutine_group (&os, PEEPHOLE2, &peephole2_root);
5446
5447 fflush (stdout);
5448 return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
5449 }