]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/genrecog.c
PR testsuite/92016 - Excess errors in Wstringop-overflow-17.c
[thirdparty/gcc.git] / gcc / genrecog.c
CommitLineData
263287f7 1/* Generate code from machine description to recognize rtl as insns.
fbd26352 2 Copyright (C) 1987-2019 Free Software Foundation, Inc.
263287f7 3
f12b58b3 4 This file is part of GCC.
6d69ff19 5
f12b58b3 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
8c4c00c1 8 the Free Software Foundation; either version 3, or (at your option)
6d69ff19 9 any later version.
10
f12b58b3 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.
6d69ff19 15
16 You should have received a copy of the GNU General Public License
8c4c00c1 17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
6d69ff19 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
263287f7 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
6d69ff19 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.
263287f7 41
6d69ff19 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
31d3e01c 44 rtl as an INSN list.
6d69ff19 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,
31d3e01c 48 the new rtl is returned in an INSN list, and LAST_INSN will point
59250a8d 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. */
263287f7 106
805e22b2 107#include "bconfig.h"
802ba5cb 108#define INCLUDE_ALGORITHM
5ce88198 109#include "system.h"
805e22b2 110#include "coretypes.h"
111#include "tm.h"
263287f7 112#include "rtl.h"
04b58880 113#include "errors.h"
960ebfe7 114#include "read-md.h"
c5ddd6b5 115#include "gensupport.h"
59250a8d 116
117#undef GENERATOR_FILE
118enum 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. */
129static const bool merge_states_p = true;
130static const bool collapse_optional_decisions_p = true;
131static const bool cse_tests_p = true;
132static const bool simplify_tests_p = true;
133static const bool use_operand_variables_p = true;
134static const bool use_subroutines_p = true;
135static 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. */
140static 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. */
151static 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. */
155static 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. */
161static 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. */
168static 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. */
00788409 173static const unsigned int MAX_DEPTH = 6;
59250a8d 174
175/* The minimum number of pseudo-statements that a state must have before
176 we split it out into a subroutine. */
00788409 177static const unsigned int MIN_NUM_STATEMENTS = 5;
59250a8d 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.). */
00788409 183static const unsigned int MAX_NUM_STATEMENTS = 200;
59250a8d 184
185/* The minimum number of pseudo-statements that can be used in a pattern
186 routine. */
187static 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. */
193static const unsigned int MAX_PATTERN_PARAMS = 5;
194
195/* The maximum operand number plus one. */
196int num_operands;
41e80e4b 197
2494d261 198/* Ways of obtaining an rtx to be tested. */
199enum 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. */
212struct 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
59250a8d 237 /* The instruction to which the position belongs. */
238 unsigned int insn_id;
a698628e 239
59250a8d 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;
263287f7 244
59250a8d 245 /* A unique identifier for this position. */
246 unsigned int id;
263287f7 247};
248
6d69ff19 249enum routine_type {
59250a8d 250 SUBPATTERN, RECOG, SPLIT, PEEPHOLE2
6d69ff19 251};
82575fa7 252
2494d261 253/* The root position (x0). */
254static struct position root_pos;
255
59250a8d 256/* The number of positions created. Also one higher than the maximum
257 position id. */
258static unsigned int num_positions = 1;
259
2494d261 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. */
262static struct position *peep2_insn_pos_list = &root_pos;
cbf464bd 263\f
2494d261 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
269static struct position *
270next_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);
2494d261 279 pos->type = type;
280 pos->arg = arg;
59250a8d 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++;
2494d261 294 *next_ptr = pos;
295 }
296 return pos;
297}
298
299/* Compare positions POS1 and POS2 lexicographically. */
300
301static int
302compare_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
59250a8d 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. */
263287f7 329
59250a8d 330static struct position *
331common_position (struct position *pos1, struct position *pos2)
6d69ff19 332{
59250a8d 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;
a698628e 345}
59250a8d 346\f
f82dbd66 347/* Search for and return operand N, stop when reaching node STOP. */
3a074b0f 348
349static rtx
f82dbd66 350find_operand (rtx pattern, int n, rtx stop)
3a074b0f 351{
352 const char *fmt;
353 RTX_CODE code;
354 int i, j, len;
355 rtx r;
356
f82dbd66 357 if (pattern == stop)
358 return stop;
359
3a074b0f 360 code = GET_CODE (pattern);
361 if ((code == MATCH_SCRATCH
3a074b0f 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':
f82dbd66 375 if ((r = find_operand (XEXP (pattern, i), n, stop)) != NULL_RTX)
3a074b0f 376 return r;
377 break;
378
386d0079 379 case 'V':
380 if (! XVEC (pattern, i))
381 break;
d632b59a 382 /* Fall through. */
386d0079 383
3a074b0f 384 case 'E':
385 for (j = 0; j < XVECLEN (pattern, i); j++)
f82dbd66 386 if ((r = find_operand (XVECEXP (pattern, i, j), n, stop))
387 != NULL_RTX)
3a074b0f 388 return r;
389 break;
390
9edf7ea8 391 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
3a074b0f 392 break;
393
394 default:
e0a4c0c2 395 gcc_unreachable ();
3a074b0f 396 }
397 }
398
399 return NULL;
400}
401
386d0079 402/* Search for and return operand M, such that it has a matching
403 constraint for operand N. */
404
405static rtx
1a97be37 406find_matching_operand (rtx pattern, int n)
386d0079 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;
d632b59a 434 /* Fall through. */
386d0079 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
9edf7ea8 442 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
386d0079 443 break;
444
445 default:
e0a4c0c2 446 gcc_unreachable ();
386d0079 447 }
448 }
449
450 return NULL;
451}
452
ffcd6b16 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
458static bool
459constraints_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}
386d0079 465
7a23db96 466/* Return the name of the predicate matched by MATCH_RTX. */
467
468static const char *
469predicate_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
480static bool
481special_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
c04601c1 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. */
0922b1b8 502
503static void
c04601c1 504validate_pattern (rtx pattern, md_rtx_info *info, rtx set, int set_code)
0922b1b8 505{
506 const char *fmt;
507 RTX_CODE code;
3a074b0f 508 size_t i, len;
509 int j;
0922b1b8 510
511 code = GET_CODE (pattern);
512 switch (code)
513 {
514 case MATCH_SCRATCH:
ffcd6b16 515 {
516 const char constraints0 = XSTR (pattern, 1)[0];
517
c04601c1 518 if (!constraints_supported_in_insn_p (info->def))
ffcd6b16 519 {
520 if (constraints0)
521 {
c04601c1 522 error_at (info->loc, "constraints not supported in %s",
523 GET_RTX_NAME (GET_CODE (info->def)));
ffcd6b16 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 == '='
0993e186 531 && constraints0
ffcd6b16 532 && constraints0 != '='
533 && constraints0 != '+')
534 {
c04601c1 535 error_at (info->loc, "operand %d missing output reload",
536 XINT (pattern, 0));
ffcd6b16 537 }
538 return;
539 }
f82dbd66 540 case MATCH_DUP:
541 case MATCH_OP_DUP:
542 case MATCH_PAR_DUP:
c04601c1 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));
f82dbd66 546 break;
0922b1b8 547 case MATCH_OPERAND:
3a074b0f 548 case MATCH_OPERATOR:
0922b1b8 549 {
550 const char *pred_name = XSTR (pattern, 1);
cbf464bd 551 const struct pred_data *pred;
3a074b0f 552 const char *c_test;
553
7c1b1064 554 c_test = get_c_test (info->def);
0922b1b8 555
556 if (pred_name[0] != 0)
557 {
cbf464bd 558 pred = lookup_predicate (pred_name);
559 if (!pred)
c04601c1 560 error_at (info->loc, "unknown predicate '%s'", pred_name);
3a074b0f 561 }
cbf464bd 562 else
563 pred = 0;
3a074b0f 564
ad9465d6 565 if (code == MATCH_OPERAND)
4747a74c 566 {
f1a7e25b 567 const char *constraints = XSTR (pattern, 2);
568 const char constraints0 = constraints[0];
ad9465d6 569
c04601c1 570 if (!constraints_supported_in_insn_p (info->def))
d55ea929 571 {
ad9465d6 572 if (constraints0)
ffcd6b16 573 {
c04601c1 574 error_at (info->loc, "constraints not supported in %s",
575 GET_RTX_NAME (GET_CODE (info->def)));
ffcd6b16 576 }
ad9465d6 577 }
1a97be37 578
ad9465d6 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 == '='
c04601c1 589 && find_matching_operand (info->def,
590 XINT (pattern, 0)))
ad9465d6 591 ;
592 else
c04601c1 593 error_at (info->loc, "operand %d missing in-out reload",
594 XINT (pattern, 0));
386d0079 595 }
b638f5c8 596 else if (constraints0 != '=' && constraints0 != '+')
c04601c1 597 error_at (info->loc, "operand %d missing output reload",
598 XINT (pattern, 0));
d55ea929 599 }
f1a7e25b 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))
c04601c1 618 error_at (info->loc, "constraint digit %d is not"
619 " smaller than operand %d",
620 val, XINT (pattern, 0));
f1a7e25b 621 }
622
623 while (constraints[0] && constraints[0] != ',')
624 constraints++;
625 }
4747a74c 626 }
627
3a074b0f 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. */
cbf464bd 631 if (set && pred && pred->allows_non_lvalue)
c04601c1 632 error_at (info->loc, "destination operand %d allows non-lvalue",
633 XINT (pattern, 0));
3a074b0f 634
cbf464bd 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. */
3a074b0f 642
643 if (GET_MODE (pattern) == VOIDmode
644 && code == MATCH_OPERAND
c04601c1 645 && GET_CODE (info->def) == DEFINE_INSN
cbf464bd 646 && pred
647 && !pred->special
648 && pred->allows_non_const
4747a74c 649 && strstr (c_test, "operands") == NULL
650 && ! (set
651 && GET_CODE (set) == SET
652 && GET_CODE (SET_SRC (set)) == CALL))
c04601c1 653 message_at (info->loc, "warning: operand %d missing mode?",
654 XINT (pattern, 0));
0922b1b8 655 return;
656 }
657
658 case SET:
3a074b0f 659 {
3754d046 660 machine_mode dmode, smode;
3a074b0f 661 rtx dest, src;
662
663 dest = SET_DEST (pattern);
664 src = SET_SRC (pattern);
665
ad9465d6 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
40e55fbb 671 /* Find the referent for a DUP. */
3a074b0f 672
673 if (GET_CODE (dest) == MATCH_DUP
674 || GET_CODE (dest) == MATCH_OP_DUP
675 || GET_CODE (dest) == MATCH_PAR_DUP)
c04601c1 676 dest = find_operand (info->def, XINT (dest, 0), NULL);
3a074b0f 677
678 if (GET_CODE (src) == MATCH_DUP
679 || GET_CODE (src) == MATCH_OP_DUP
680 || GET_CODE (src) == MATCH_PAR_DUP)
c04601c1 681 src = find_operand (info->def, XINT (src, 0), NULL);
3a074b0f 682
3a074b0f 683 dmode = GET_MODE (dest);
684 smode = GET_MODE (src);
0922b1b8 685
7a23db96 686 /* Mode checking is not performed for special predicates. */
687 if (special_predicate_operand_p (src)
688 || special_predicate_operand_p (dest))
3a074b0f 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)
c04601c1 694 error_at (info->loc, "mode mismatch in set: %smode vs %smode",
695 GET_MODE_NAME (dmode), GET_MODE_NAME (smode));
3a074b0f 696
fcb53c1e 697 /* If only one of the operands is VOIDmode, and PC or CC0 is
3a074b0f 698 not involved, it's probably a mistake. */
699 else if (dmode != smode
700 && GET_CODE (dest) != PC
701 && GET_CODE (dest) != CC0
4747a74c 702 && GET_CODE (src) != PC
703 && GET_CODE (src) != CC0
971ba038 704 && !CONST_INT_P (src)
219f3246 705 && !CONST_WIDE_INT_P (src)
84e907aa 706 && GET_CODE (src) != CALL)
3a074b0f 707 {
708 const char *which;
709 which = (dmode == VOIDmode ? "destination" : "source");
c04601c1 710 message_at (info->loc, "warning: %s missing a mode?", which);
3a074b0f 711 }
712
713 if (dest != SET_DEST (pattern))
c04601c1 714 validate_pattern (dest, info, pattern, '=');
715 validate_pattern (SET_DEST (pattern), info, pattern, '=');
716 validate_pattern (SET_SRC (pattern), info, NULL_RTX, 0);
3a074b0f 717 return;
718 }
719
720 case CLOBBER:
c04601c1 721 validate_pattern (SET_DEST (pattern), info, pattern, '=');
d55ea929 722 return;
723
724 case ZERO_EXTRACT:
c04601c1 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);
d55ea929 728 return;
729
730 case STRICT_LOW_PART:
c04601c1 731 validate_pattern (XEXP (pattern, 0), info, set, set ? '+' : 0);
0922b1b8 732 return;
3a074b0f 733
0922b1b8 734 case LABEL_REF:
c7799456 735 if (GET_MODE (XEXP (pattern, 0)) != VOIDmode)
c04601c1 736 error_at (info->loc, "operand to label_ref %smode not VOIDmode",
c7799456 737 GET_MODE_NAME (GET_MODE (XEXP (pattern, 0))));
0922b1b8 738 break;
739
9b067f04 740 case VEC_SELECT:
741 if (GET_MODE (pattern) != VOIDmode)
742 {
582adad1 743 machine_mode mode = GET_MODE (pattern);
744 machine_mode imode = GET_MODE (XEXP (pattern, 0));
745 machine_mode emode
9b067f04 746 = VECTOR_MODE_P (mode) ? GET_MODE_INNER (mode) : mode;
747 if (GET_CODE (XEXP (pattern, 1)) == PARALLEL)
748 {
ba7efd65 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)
9b067f04 757 error_at (info->loc,
758 "vec_select parallel with %d elements, expected %d",
759 XVECLEN (XEXP (pattern, 1), 0), expected);
ba7efd65 760 else if (VECTOR_MODE_P (imode)
761 && GET_MODE_NUNITS (imode).is_constant (&nelems))
ddd399ff 762 {
ddd399ff 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 }
9b067f04 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
0922b1b8 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':
c04601c1 798 validate_pattern (XEXP (pattern, i), info, NULL_RTX, 0);
0922b1b8 799 break;
800
801 case 'E':
802 for (j = 0; j < XVECLEN (pattern, i); j++)
c04601c1 803 validate_pattern (XVECEXP (pattern, i, j), info, NULL_RTX, 0);
0922b1b8 804 break;
805
9edf7ea8 806 case 'r': case 'p': case 'i': case 'w': case '0': case 's':
0922b1b8 807 break;
808
809 default:
e0a4c0c2 810 gcc_unreachable ();
0922b1b8 811 }
812 }
0922b1b8 813}
59250a8d 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. */
819template <typename T>
251317e4 820class list_head
263287f7 821{
251317e4 822public:
59250a8d 823 /* A range of linked items. */
251317e4 824 class range
59250a8d 825 {
251317e4 826 public:
59250a8d 827 range (T *);
828 range (T *, T *);
263287f7 829
59250a8d 830 T *start, *end;
831 void set_parent (list_head *);
832 };
263287f7 833
59250a8d 834 list_head ();
835 range release ();
836 void push_back (range);
837 range remove (range);
838 void replace (range, range);
839 T *singleton () const;
263287f7 840
59250a8d 841 T *first, *last;
842};
263287f7 843
59250a8d 844/* Create a range [START_IN, START_IN]. */
393d701f 845
59250a8d 846template <typename T>
847list_head <T>::range::range (T *start_in) : start (start_in), end (start_in) {}
82575fa7 848
59250a8d 849/* Create a range [START_IN, END_IN], linked by next and prev fields. */
6d69ff19 850
59250a8d 851template <typename T>
852list_head <T>::range::range (T *start_in, T *end_in)
853 : start (start_in), end (end_in) {}
6d69ff19 854
59250a8d 855template <typename T>
856void
857list_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}
35b0bfe2 863
59250a8d 864template <typename T>
865list_head <T>::list_head () : first (0), last (0) {}
6d69ff19 866
59250a8d 867/* Add R to the end of the list. */
6d69ff19 868
59250a8d 869template <typename T>
870void
871list_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}
cbf464bd 881
59250a8d 882/* Remove R from the list. R remains valid and can be inserted into
883 other lists. */
6d69ff19 884
59250a8d 885template <typename T>
886typename list_head <T>::range
887list_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}
a698628e 902
59250a8d 903/* Replace OLDR with NEWR. OLDR remains valid and can be inserted into
904 other lists. */
940b9cea 905
59250a8d 906template <typename T>
907void
908list_head <T>::replace (range oldr, range newr)
909{
910 newr.start->prev = oldr.start->prev;
911 newr.end->next = oldr.end->next;
a698628e 912
59250a8d 913 oldr.start->prev = 0;
914 oldr.end->next = 0;
915 oldr.set_parent (0);
a698628e 916
59250a8d 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}
263287f7 927
59250a8d 928/* Empty the list and return the previous contents as a range that can
929 be inserted into other lists. */
6d69ff19 930
59250a8d 931template <typename T>
932typename list_head <T>::range
933list_head <T>::release ()
934{
935 range r (first, last);
936 first = 0;
937 last = 0;
938 r.set_parent (0);
939 return r;
940}
6d69ff19 941
59250a8d 942/* If the list contains a single item, return that item, otherwise return
943 null. */
6d69ff19 944
59250a8d 945template <typename T>
946T *
947list_head <T>::singleton () const
948{
949 return first == last ? first : 0;
950}
951\f
2e966e2a 952class state;
263287f7 953
59250a8d 954/* Describes a possible successful return from a routine. */
955struct acceptance_type
956{
957 /* The type of routine we're returning from. */
958 routine_type type : 16;
6d69ff19 959
59250a8d 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.
263287f7 964
59250a8d 965 False if this structure presents a full match. */
966 unsigned int partial_p : 1;
263287f7 967
59250a8d 968 union
969 {
970 /* If PARTIAL_P, this is the number of the subroutine to call. */
971 int subroutine_id;
6d69ff19 972
59250a8d 973 /* Valid if !PARTIAL_P. */
974 struct
263287f7 975 {
59250a8d 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};
fb16c776 993
59250a8d 994bool
995operator == (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}
3164740a 1004
59250a8d 1005bool
1006operator != (const acceptance_type &a, const acceptance_type &b)
1007{
1008 return !operator == (a, b);
1009}
6d69ff19 1010
59250a8d 1011/* Represents a parameter to a pattern routine. */
251317e4 1012class parameter
59250a8d 1013{
251317e4 1014public:
59250a8d 1015 /* The C type of parameter. */
1016 enum type_enum {
1017 /* Represents an invalid parameter. */
1018 UNSET,
6d69ff19 1019
59250a8d 1020 /* A machine_mode parameter. */
1021 MODE,
6d69ff19 1022
59250a8d 1023 /* An rtx_code parameter. */
1024 CODE,
6d69ff19 1025
59250a8d 1026 /* An int parameter. */
1027 INT,
2494d261 1028
15183fd2 1029 /* An unsigned int parameter. */
1030 UINT,
1031
59250a8d 1032 /* A HOST_WIDE_INT parameter. */
1033 WIDE_INT
1034 };
6d69ff19 1035
59250a8d 1036 parameter ();
1037 parameter (type_enum, bool, uint64_t);
6d69ff19 1038
59250a8d 1039 /* The type of the parameter. */
1040 type_enum type;
6d69ff19 1041
59250a8d 1042 /* True if the value passed is variable, false if it is constant. */
1043 bool is_param;
6d69ff19 1044
59250a8d 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};
6d69ff19 1049
59250a8d 1050parameter::parameter ()
1051 : type (UNSET), is_param (false), value (0) {}
6d69ff19 1052
59250a8d 1053parameter::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) {}
6d69ff19 1055
59250a8d 1056bool
1057operator == (const parameter &param1, const parameter &param2)
6d69ff19 1058{
59250a8d 1059 return (param1.type == param2.type
1060 && param1.is_param == param2.is_param
1061 && param1.value == param2.value);
1062}
6d69ff19 1063
59250a8d 1064bool
1065operator != (const parameter &param1, const parameter &param2)
1066{
1067 return !operator == (param1, param2);
1068}
6d69ff19 1069
59250a8d 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. */
251317e4 1074class pattern_routine
59250a8d 1075{
251317e4 1076public:
59250a8d 1077 /* The state that implements the pattern. */
1078 state *s;
6d69ff19 1079
59250a8d 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;
6d69ff19 1084
59250a8d 1085 /* A unique identifier for the routine. */
1086 unsigned int pattern_id;
6d69ff19 1087
59250a8d 1088 /* True if the routine takes pnum_clobbers as argument. */
1089 bool pnum_clobbers_p;
6d69ff19 1090
59250a8d 1091 /* True if the routine takes the enclosing instruction as argument. */
1092 bool insn_p;
6d69ff19 1093
59250a8d 1094 /* The types of the other parameters to the routine, if any. */
1095 auto_vec <parameter::type_enum, MAX_PATTERN_PARAMS> param_types;
1096};
6d69ff19 1097
59250a8d 1098/* All defined patterns. */
1099static vec <pattern_routine *> patterns;
35b0bfe2 1100
59250a8d 1101/* Represents one use of a pattern routine. */
251317e4 1102class pattern_use
59250a8d 1103{
251317e4 1104public:
59250a8d 1105 /* The pattern routine to use. */
1106 pattern_routine *routine;
6d69ff19 1107
59250a8d 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};
6d69ff19 1112
59250a8d 1113/* Represents a test performed by a decision. */
251317e4 1114class rtx_test
6d69ff19 1115{
251317e4 1116public:
abef0e58 1117 rtx_test ();
6d69ff19 1118
59250a8d 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".
6d69ff19 1122
59250a8d 1123 The order of the enum isn't important. */
1124 enum kind_enum {
1125 /* Check GET_CODE (X) == LABEL. */
1126 CODE,
6d69ff19 1127
59250a8d 1128 /* Check GET_MODE (X) == LABEL. */
1129 MODE,
6d69ff19 1130
15183fd2 1131 /* Check REGNO (X) == LABEL. */
1132 REGNO_FIELD,
1133
9edf7ea8 1134 /* Check known_eq (SUBREG_BYTE (X), LABEL). */
1135 SUBREG_FIELD,
1136
59250a8d 1137 /* Check XINT (X, u.opno) == LABEL. */
1138 INT_FIELD,
263287f7 1139
59250a8d 1140 /* Check XWINT (X, u.opno) == LABEL. */
1141 WIDE_INT_FIELD,
263287f7 1142
59250a8d 1143 /* Check XVECLEN (X, 0) == LABEL. */
1144 VECLEN,
15d18ea0 1145
59250a8d 1146 /* Check peep2_current_count >= u.min_len. */
1147 PEEP2_COUNT,
15d18ea0 1148
59250a8d 1149 /* Check XVECLEN (X, 0) >= u.min_len. */
1150 VECLEN_GE,
15d18ea0 1151
59250a8d 1152 /* Check whether X is a cached const_int with value u.integer. */
1153 SAVED_CONST_INT,
15d18ea0 1154
59250a8d 1155 /* Check u.predicate.data (X, u.predicate.mode). */
1156 PREDICATE,
15d18ea0 1157
59250a8d 1158 /* Check rtx_equal_p (X, operands[u.opno]). */
1159 DUPLICATE,
15d18ea0 1160
59250a8d 1161 /* Check whether X matches pattern u.pattern. */
1162 PATTERN,
15d18ea0 1163
59250a8d 1164 /* Check whether pnum_clobbers is nonnull (RECOG only). */
1165 HAVE_NUM_CLOBBERS,
15d18ea0 1166
59250a8d 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,
a698628e 1170
59250a8d 1171 /* Execute operands[u.opno] = X. (Always succeeds.) */
1172 SET_OP,
6d69ff19 1173
59250a8d 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 };
6d69ff19 1178
59250a8d 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;
a698628e 1183
59250a8d 1184 /* Which element of operands[] already contains POS, or -1 if no element
1185 is known to hold POS. */
1186 int pos_operand;
a698628e 1187
59250a8d 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
263287f7 1195 {
59250a8d 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;
a698628e 1213
abef0e58 1214 static rtx_test code (position *);
1215 static rtx_test mode (position *);
15183fd2 1216 static rtx_test regno_field (position *);
9edf7ea8 1217 static rtx_test subreg_field (position *);
abef0e58 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 &);
59250a8d 1230
1231 bool terminal_p () const;
1232 bool single_outcome_p () const;
1233
1234private:
abef0e58 1235 rtx_test (position *, kind_enum);
59250a8d 1236};
a698628e 1237
abef0e58 1238rtx_test::rtx_test () {}
a698628e 1239
abef0e58 1240rtx_test::rtx_test (position *pos_in, kind_enum kind_in)
59250a8d 1241 : pos (pos_in), pos_operand (-1), kind (kind_in) {}
a698628e 1242
abef0e58 1243rtx_test
1244rtx_test::code (position *pos)
59250a8d 1245{
abef0e58 1246 return rtx_test (pos, rtx_test::CODE);
59250a8d 1247}
a698628e 1248
abef0e58 1249rtx_test
1250rtx_test::mode (position *pos)
59250a8d 1251{
abef0e58 1252 return rtx_test (pos, rtx_test::MODE);
59250a8d 1253}
6d69ff19 1254
15183fd2 1255rtx_test
1256rtx_test::regno_field (position *pos)
1257{
1258 rtx_test res (pos, rtx_test::REGNO_FIELD);
1259 return res;
1260}
1261
9edf7ea8 1262rtx_test
1263rtx_test::subreg_field (position *pos)
1264{
1265 rtx_test res (pos, rtx_test::SUBREG_FIELD);
1266 return res;
1267}
1268
abef0e58 1269rtx_test
1270rtx_test::int_field (position *pos, int opno)
59250a8d 1271{
abef0e58 1272 rtx_test res (pos, rtx_test::INT_FIELD);
59250a8d 1273 res.u.opno = opno;
1274 return res;
1275}
6d69ff19 1276
abef0e58 1277rtx_test
1278rtx_test::wide_int_field (position *pos, int opno)
59250a8d 1279{
abef0e58 1280 rtx_test res (pos, rtx_test::WIDE_INT_FIELD);
59250a8d 1281 res.u.opno = opno;
1282 return res;
6d69ff19 1283}
263287f7 1284
abef0e58 1285rtx_test
1286rtx_test::veclen (position *pos)
59250a8d 1287{
abef0e58 1288 return rtx_test (pos, rtx_test::VECLEN);
59250a8d 1289}
263287f7 1290
abef0e58 1291rtx_test
1292rtx_test::peep2_count (int min_len)
6d69ff19 1293{
abef0e58 1294 rtx_test res (0, rtx_test::PEEP2_COUNT);
59250a8d 1295 res.u.min_len = min_len;
1296 return res;
1297}
a698628e 1298
abef0e58 1299rtx_test
1300rtx_test::veclen_ge (position *pos, int min_len)
59250a8d 1301{
abef0e58 1302 rtx_test res (pos, rtx_test::VECLEN_GE);
59250a8d 1303 res.u.min_len = min_len;
1304 return res;
1305}
a698628e 1306
abef0e58 1307rtx_test
1308rtx_test::predicate (position *pos, const struct pred_data *data,
1309 machine_mode mode)
59250a8d 1310{
abef0e58 1311 rtx_test res (pos, rtx_test::PREDICATE);
59250a8d 1312 res.u.predicate.data = data;
1313 res.u.predicate.mode_is_param = false;
1314 res.u.predicate.mode = mode;
1315 return res;
1316}
4747a74c 1317
abef0e58 1318rtx_test
1319rtx_test::duplicate (position *pos, int opno)
59250a8d 1320{
abef0e58 1321 rtx_test res (pos, rtx_test::DUPLICATE);
59250a8d 1322 res.u.opno = opno;
1323 return res;
1324}
4747a74c 1325
abef0e58 1326rtx_test
1327rtx_test::pattern (position *pos, pattern_use *pattern)
59250a8d 1328{
abef0e58 1329 rtx_test res (pos, rtx_test::PATTERN);
59250a8d 1330 res.u.pattern = pattern;
1331 return res;
a698628e 1332}
a698628e 1333
abef0e58 1334rtx_test
1335rtx_test::have_num_clobbers ()
59250a8d 1336{
abef0e58 1337 return rtx_test (0, rtx_test::HAVE_NUM_CLOBBERS);
59250a8d 1338}
6d69ff19 1339
abef0e58 1340rtx_test
1341rtx_test::c_test (const char *string)
263287f7 1342{
abef0e58 1343 rtx_test res (0, rtx_test::C_TEST);
59250a8d 1344 res.u.string = string;
1345 return res;
1346}
6d69ff19 1347
abef0e58 1348rtx_test
1349rtx_test::set_op (position *pos, int opno)
59250a8d 1350{
abef0e58 1351 rtx_test res (pos, rtx_test::SET_OP);
59250a8d 1352 res.u.opno = opno;
1353 return res;
1354}
a698628e 1355
abef0e58 1356rtx_test
1357rtx_test::accept (const acceptance_type &acceptance)
59250a8d 1358{
abef0e58 1359 rtx_test res (0, rtx_test::ACCEPT);
59250a8d 1360 res.u.acceptance = acceptance;
1361 return res;
1362}
a698628e 1363
59250a8d 1364/* Return true if the test represents an unconditionally successful match. */
a698628e 1365
59250a8d 1366bool
abef0e58 1367rtx_test::terminal_p () const
59250a8d 1368{
abef0e58 1369 return kind == rtx_test::ACCEPT && u.acceptance.type != PEEPHOLE2;
a698628e 1370}
a698628e 1371
59250a8d 1372/* Return true if the test is a boolean that is always true. */
6d69ff19 1373
59250a8d 1374bool
abef0e58 1375rtx_test::single_outcome_p () const
a698628e 1376{
abef0e58 1377 return terminal_p () || kind == rtx_test::SET_OP;
59250a8d 1378}
a698628e 1379
59250a8d 1380bool
abef0e58 1381operator == (const rtx_test &a, const rtx_test &b)
59250a8d 1382{
1383 if (a.pos != b.pos || a.kind != b.kind)
1384 return false;
1385 switch (a.kind)
6d69ff19 1386 {
abef0e58 1387 case rtx_test::CODE:
1388 case rtx_test::MODE:
15183fd2 1389 case rtx_test::REGNO_FIELD:
9edf7ea8 1390 case rtx_test::SUBREG_FIELD:
abef0e58 1391 case rtx_test::VECLEN:
1392 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 1393 return true;
1394
abef0e58 1395 case rtx_test::PEEP2_COUNT:
1396 case rtx_test::VECLEN_GE:
59250a8d 1397 return a.u.min_len == b.u.min_len;
1398
abef0e58 1399 case rtx_test::INT_FIELD:
1400 case rtx_test::WIDE_INT_FIELD:
1401 case rtx_test::DUPLICATE:
1402 case rtx_test::SET_OP:
59250a8d 1403 return a.u.opno == b.u.opno;
1404
abef0e58 1405 case rtx_test::SAVED_CONST_INT:
59250a8d 1406 return (a.u.integer.is_param == b.u.integer.is_param
1407 && a.u.integer.value == b.u.integer.value);
1408
abef0e58 1409 case rtx_test::PREDICATE:
59250a8d 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
abef0e58 1414 case rtx_test::PATTERN:
59250a8d 1415 return (a.u.pattern->routine == b.u.pattern->routine
1416 && a.u.pattern->params == b.u.pattern->params);
1417
abef0e58 1418 case rtx_test::C_TEST:
59250a8d 1419 return strcmp (a.u.string, b.u.string) == 0;
1420
abef0e58 1421 case rtx_test::ACCEPT:
59250a8d 1422 return a.u.acceptance == b.u.acceptance;
6d69ff19 1423 }
59250a8d 1424 gcc_unreachable ();
1425}
263287f7 1426
59250a8d 1427bool
abef0e58 1428operator != (const rtx_test &a, const rtx_test &b)
59250a8d 1429{
1430 return !operator == (a, b);
1431}
a698628e 1432
59250a8d 1433/* A simple set of transition labels. Most transitions have a singleton
1434 label, so try to make that case as efficient as possible. */
251317e4 1435class int_set : public auto_vec <uint64_t, 1>
59250a8d 1436{
251317e4 1437public:
59250a8d 1438 typedef uint64_t *iterator;
a698628e 1439
59250a8d 1440 int_set ();
1441 int_set (uint64_t);
1442 int_set (const int_set &);
a698628e 1443
59250a8d 1444 int_set &operator = (const int_set &);
a698628e 1445
59250a8d 1446 iterator begin ();
1447 iterator end ();
1448};
a698628e 1449
6d443cda 1450int_set::int_set () : auto_vec<uint64_t, 1> () {}
fcb53c1e 1451
6d443cda 1452int_set::int_set (uint64_t label) :
1453 auto_vec<uint64_t, 1> ()
59250a8d 1454{
1455 safe_push (label);
1456}
a698628e 1457
6d443cda 1458int_set::int_set (const int_set &other) :
1459 auto_vec<uint64_t, 1> ()
59250a8d 1460{
1461 safe_splice (other);
1462}
a698628e 1463
59250a8d 1464int_set &
1465int_set::operator = (const int_set &other)
1466{
1467 truncate (0);
1468 safe_splice (other);
1469 return *this;
1470}
ec4c9f0c 1471
59250a8d 1472int_set::iterator
1473int_set::begin ()
1474{
1475 return address ();
1476}
6d69ff19 1477
59250a8d 1478int_set::iterator
1479int_set::end ()
1480{
1481 return address () + length ();
6d69ff19 1482}
6d69ff19 1483
59250a8d 1484bool
1485operator == (const int_set &a, const int_set &b)
6d69ff19 1486{
59250a8d 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}
a698628e 1494
59250a8d 1495bool
1496operator != (const int_set &a, const int_set &b)
1497{
1498 return !operator == (a, b);
1499}
a698628e 1500
2e966e2a 1501class decision;
a698628e 1502
59250a8d 1503/* Represents a transition between states, dependent on the result of
1504 a test T. */
251317e4 1505class transition
59250a8d 1506{
251317e4 1507public:
59250a8d 1508 transition (const int_set &, state *, bool);
263287f7 1509
59250a8d 1510 void set_parent (list_head <transition> *);
263287f7 1511
59250a8d 1512 /* Links to other transitions for T. Always null for boolean tests. */
1513 transition *prev, *next;
fcb53c1e 1514
59250a8d 1515 /* The transition should be taken when T has one of these values.
abef0e58 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
59250a8d 1518 sorted in ascending order. */
1519 int_set labels;
6d69ff19 1520
59250a8d 1521 /* The source decision. */
1522 decision *from;
6d69ff19 1523
59250a8d 1524 /* The target state. */
1525 state *to;
263287f7 1526
59250a8d 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;
263287f7 1533
59250a8d 1534 /* True if LABELS contains parameter numbers rather than constants.
abef0e58 1535 E.g. if this is true for a rtx_test::CODE, the label is the number
59250a8d 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};
263287f7 1540
59250a8d 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. */
251317e4 1546class decision : public list_head <transition>
59250a8d 1547{
251317e4 1548public:
abef0e58 1549 decision (const rtx_test &);
6d69ff19 1550
59250a8d 1551 void set_parent (list_head <decision> *s);
1552 bool if_statement_p (uint64_t * = 0) const;
6d69ff19 1553
59250a8d 1554 /* The state to which this decision belongs. */
1555 state *s;
6d69ff19 1556
59250a8d 1557 /* Links to other decisions in the same state. */
1558 decision *prev, *next;
6d69ff19 1559
59250a8d 1560 /* The test to perform. */
abef0e58 1561 rtx_test test;
59250a8d 1562};
6d69ff19 1563
59250a8d 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. */
251317e4 1567class state : public list_head <decision>
59250a8d 1568{
251317e4 1569public:
59250a8d 1570 void set_parent (list_head <state> *) {}
1571};
6d69ff19 1572
59250a8d 1573transition::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. */
263287f7 1579
59250a8d 1580void
1581transition::set_parent (list_head <transition> *from_in)
1582{
1583 from = static_cast <decision *> (from_in);
263287f7 1584}
6d69ff19 1585
abef0e58 1586decision::decision (const rtx_test &test_in)
59250a8d 1587 : prev (0), next (0), test (test_in) {}
263287f7 1588
59250a8d 1589/* Set the state to which this decision belongs. */
1590
1591void
1592decision::set_parent (list_head <decision> *s_in)
263287f7 1593{
59250a8d 1594 s = static_cast <state *> (s_in);
1595}
a698628e 1596
59250a8d 1597/* Return true if the decision has a single transition with a single label.
1598 If so, return the label in *LABEL if nonnull. */
a698628e 1599
59250a8d 1600inline bool
1601decision::if_statement_p (uint64_t *label) const
1602{
1603 if (singleton () && first->labels.length () == 1)
263287f7 1604 {
59250a8d 1605 if (label)
1606 *label = first->labels[0];
1607 return true;
263287f7 1608 }
59250a8d 1609 return false;
263287f7 1610}
6d69ff19 1611
59250a8d 1612/* Add to FROM a decision that performs TEST and has a single transition
1613 TRANS. */
263287f7 1614
1615static void
abef0e58 1616add_decision (state *from, const rtx_test &test, transition *trans)
263287f7 1617{
59250a8d 1618 decision *d = new decision (test);
1619 from->push_back (d);
1620 d->push_back (trans);
6d69ff19 1621}
a698628e 1622
59250a8d 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. */
a698628e 1626
59250a8d 1627static state *
abef0e58 1628add_decision (state *from, const rtx_test &test, int_set labels, bool optional)
6d69ff19 1629{
59250a8d 1630 state *to = new state;
1631 add_decision (from, test, new transition (labels, to, optional));
1632 return to;
1633}
2494d261 1634
59250a8d 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. */
2494d261 1638
59250a8d 1639static decision *
abef0e58 1640insert_decision_before (state::range r, const rtx_test &test,
59250a8d 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;
6d69ff19 1649}
59250a8d 1650
1651/* Remove any optional transitions from S that turned out not to be useful. */
6d69ff19 1652
1653static void
59250a8d 1654collapse_optional_decisions (state *s)
6d69ff19 1655{
59250a8d 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 }
6d69ff19 1679}
263287f7 1680
59250a8d 1681/* Try to squash several separate tests into simpler ones. */
263287f7 1682
6d69ff19 1683static void
59250a8d 1684simplify_tests (state *s)
6d69ff19 1685{
59250a8d 1686 for (decision *d = s->first; d; d = d->next)
6d69ff19 1687 {
59250a8d 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. */
abef0e58 1691 if (d->test.kind == rtx_test::CODE
59250a8d 1692 && d->if_statement_p (&label)
1693 && label == CONST_INT)
1694 if (decision *second = d->first->to->singleton ())
fe512d6d 1695 if (d->test.pos == second->test.pos
abef0e58 1696 && second->test.kind == rtx_test::WIDE_INT_FIELD
59250a8d 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 {
abef0e58 1702 d->test.kind = rtx_test::SAVED_CONST_INT;
59250a8d 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. */
abef0e58 1717 if (d->test.kind == rtx_test::CODE)
59250a8d 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;
abef0e58 1728 if (d2->test.kind == rtx_test::PREDICATE)
59250a8d 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);
6d69ff19 1740 }
1741}
a698628e 1742
59250a8d 1743/* Return true if all successful returns passing through D require the
1744 condition tested by COMMON to be true.
ad85fb32 1745
59250a8d 1746 When returning true, add all transitions like COMMON in D to WHERE.
1747 WHERE may contain a partial result on failure. */
1748
1749static bool
1750common_test_p (decision *d, transition *common, vec <transition *> *where)
ad85fb32 1751{
abef0e58 1752 if (d->test.kind == rtx_test::ACCEPT)
59250a8d 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;
ad85fb32 1770}
1771
59250a8d 1772/* Indicates that we have tested GET_CODE (X) for a particular rtx X. */
1773const unsigned char TESTED_CODE = 1;
a698628e 1774
59250a8d 1775/* Indicates that we have tested XVECLEN (X, 0) for a particular rtx X. */
1776const unsigned char TESTED_VECLEN = 2;
263287f7 1777
59250a8d 1778/* Represents a set of conditions that are known to hold. */
251317e4 1779class known_conditions
59250a8d 1780{
251317e4 1781public:
59250a8d 1782 /* A mask of TESTED_ values for each position, indexed by the position's
1783 id field. */
1784 auto_vec <unsigned char> position_tests;
a698628e 1785
59250a8d 1786 /* Index N says whether operands[N] has been set. */
1787 auto_vec <bool> set_operands;
a698628e 1788
59250a8d 1789 /* A guranteed lower bound on the value of peep2_current_count. */
1790 int peep2_count;
1791};
263287f7 1792
59250a8d 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. */
263287f7 1799
59250a8d 1800static bool
abef0e58 1801safe_to_hoist_p (decision *d, const rtx_test &test, known_conditions *kc)
59250a8d 1802{
1803 switch (test.kind)
1804 {
abef0e58 1805 case rtx_test::C_TEST:
59250a8d 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
abef0e58 1810 case rtx_test::ACCEPT:
59250a8d 1811 /* Don't accept something before all conditions have been tested. */
1812 return false;
1813
abef0e58 1814 case rtx_test::PREDICATE:
59250a8d 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
abef0e58 1822 && subd->test.kind == rtx_test::VECLEN_GE)
59250a8d 1823 return false;
1824 goto any_rtx;
1825
abef0e58 1826 case rtx_test::DUPLICATE:
59250a8d 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
abef0e58 1833 case rtx_test::CODE:
1834 case rtx_test::MODE:
1835 case rtx_test::SAVED_CONST_INT:
1836 case rtx_test::SET_OP:
59250a8d 1837 any_rtx:
1838 /* Check whether it is safe to access the rtx under test. */
1839 switch (test.pos->type)
263287f7 1840 {
59250a8d 1841 case POS_PEEP2_INSN:
1842 return test.pos->arg < kc->peep2_count;
0ced2f66 1843
59250a8d 1844 case POS_XEXP:
1845 return kc->position_tests[test.pos->base->id] & TESTED_CODE;
6d69ff19 1846
59250a8d 1847 case POS_XVECEXP0:
1848 return kc->position_tests[test.pos->base->id] & TESTED_VECLEN;
6d69ff19 1849 }
59250a8d 1850 gcc_unreachable ();
a698628e 1851
15183fd2 1852 case rtx_test::REGNO_FIELD:
9edf7ea8 1853 case rtx_test::SUBREG_FIELD:
abef0e58 1854 case rtx_test::INT_FIELD:
1855 case rtx_test::WIDE_INT_FIELD:
1856 case rtx_test::VECLEN:
1857 case rtx_test::VECLEN_GE:
59250a8d 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;
a698628e 1861
abef0e58 1862 case rtx_test::PEEP2_COUNT:
1863 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 1864 /* These tests can be performed anywhere. */
1865 return true;
263287f7 1866
abef0e58 1867 case rtx_test::PATTERN:
59250a8d 1868 gcc_unreachable ();
1869 }
1870 gcc_unreachable ();
1871}
a698628e 1872
59250a8d 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
1885static decision *
1886find_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))
263287f7 1907 {
59250a8d 1908 if (common_test_p (outer, trans, where))
63e9de92 1909 {
59250a8d 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;
63e9de92 1931 }
59250a8d 1932 where->truncate (0);
263287f7 1933 }
6d69ff19 1934 }
59250a8d 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. */
ff5decbb 1942
59250a8d 1943static void
1944cse_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)
7abd96cd 1950 {
59250a8d 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 }
7abd96cd 1983 }
59250a8d 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. */
abef0e58 1988 gcc_assert (d->test.kind == rtx_test::C_TEST
1989 || d->test.kind == rtx_test::ACCEPT
59250a8d 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)
6d69ff19 1996 {
abef0e58 1997 case rtx_test::CODE:
59250a8d 1998 prev = kc->position_tests[d->test.pos->id];
1999 kc->position_tests[d->test.pos->id] |= TESTED_CODE;
6d69ff19 2000 break;
59250a8d 2001
abef0e58 2002 case rtx_test::VECLEN:
2003 case rtx_test::VECLEN_GE:
59250a8d 2004 prev = kc->position_tests[d->test.pos->id];
2005 kc->position_tests[d->test.pos->id] |= TESTED_VECLEN;
6d69ff19 2006 break;
59250a8d 2007
abef0e58 2008 case rtx_test::SET_OP:
59250a8d 2009 prev = kc->set_operands[d->test.u.opno];
2010 gcc_assert (!prev);
2011 kc->set_operands[d->test.u.opno] = true;
6d69ff19 2012 break;
59250a8d 2013
abef0e58 2014 case rtx_test::PEEP2_COUNT:
59250a8d 2015 prev = kc->peep2_count;
2016 kc->peep2_count = MAX (prev, d->test.u.min_len);
6d69ff19 2017 break;
59250a8d 2018
6d69ff19 2019 default:
59250a8d 2020 break;
6d69ff19 2021 }
59250a8d 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)
a698628e 2025 {
abef0e58 2026 case rtx_test::CODE:
2027 case rtx_test::VECLEN:
2028 case rtx_test::VECLEN_GE:
59250a8d 2029 kc->position_tests[d->test.pos->id] = prev;
2030 break;
a4245b4f 2031
abef0e58 2032 case rtx_test::SET_OP:
59250a8d 2033 kc->set_operands[d->test.u.opno] = prev;
2034 break;
7903ba8d 2035
abef0e58 2036 case rtx_test::PEEP2_COUNT:
59250a8d 2037 kc->peep2_count = prev;
2038 break;
263287f7 2039
59250a8d 2040 default:
2041 break;
2042 }
6d69ff19 2043 }
59250a8d 2044}
2045
2046/* Return the type of value that can be used to parameterize test KIND,
2047 or parameter::UNSET if none. */
2048
2049parameter::type_enum
abef0e58 2050transition_parameter_type (rtx_test::kind_enum kind)
59250a8d 2051{
2052 switch (kind)
6d69ff19 2053 {
abef0e58 2054 case rtx_test::CODE:
59250a8d 2055 return parameter::CODE;
2056
abef0e58 2057 case rtx_test::MODE:
59250a8d 2058 return parameter::MODE;
2059
15183fd2 2060 case rtx_test::REGNO_FIELD:
9edf7ea8 2061 case rtx_test::SUBREG_FIELD:
15183fd2 2062 return parameter::UINT;
2063
abef0e58 2064 case rtx_test::INT_FIELD:
2065 case rtx_test::VECLEN:
2066 case rtx_test::PATTERN:
59250a8d 2067 return parameter::INT;
2068
abef0e58 2069 case rtx_test::WIDE_INT_FIELD:
59250a8d 2070 return parameter::WIDE_INT;
2071
abef0e58 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:
59250a8d 2081 return parameter::UNSET;
6d69ff19 2082 }
59250a8d 2083 gcc_unreachable ();
6d69ff19 2084}
263287f7 2085
59250a8d 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. */
a698628e 2089
6d69ff19 2090static void
59250a8d 2091find_operand_positions (state *s, vec <int> &operand_pos)
6d69ff19 2092{
59250a8d 2093 for (decision *d = s->first; d; d = d->next)
6d69ff19 2094 {
59250a8d 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;
abef0e58 2098 if (d->test.kind == rtx_test::SET_OP)
59250a8d 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);
abef0e58 2102 if (d->test.kind == rtx_test::SET_OP)
59250a8d 2103 operand_pos[d->test.pos->id] = this_operand;
2104 }
2105}
6d69ff19 2106
59250a8d 2107/* Statistics about a matching routine. */
251317e4 2108class stats
59250a8d 2109{
251317e4 2110public:
59250a8d 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};
6d69ff19 2130
59250a8d 2131stats::stats ()
2132 : num_decisions (0), longest_path (0), longest_path_code (-1),
2133 longest_backtrack (0), longest_backtrack_code (-1) {}
6d69ff19 2134
59250a8d 2135/* Return statistics about S. */
6d69ff19 2136
59250a8d 2137static stats
2138get_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 }
6d69ff19 2164
59250a8d 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 }
abef0e58 2171 if (d->test.kind == rtx_test::ACCEPT)
59250a8d 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 }
7e5202bc 2176
59250a8d 2177 /* Keep a running count of the number of backtracks. */
2178 if (d->prev)
2179 for_s.longest_backtrack += 1;
35b0bfe2 2180
59250a8d 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;
6d69ff19 2185
59250a8d 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 }
6d69ff19 2195
59250a8d 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}
6d69ff19 2202
59250a8d 2203/* Optimize ROOT. Use TYPE to describe ROOT in status messages. */
263287f7 2204
59250a8d 2205static void
2206optimize_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
2e966e2a 2246class merge_pattern_info;
59250a8d 2247
2248/* Represents a transition from one pattern to another. */
251317e4 2249class merge_pattern_transition
59250a8d 2250{
251317e4 2251public:
59250a8d 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
2263merge_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. */
251317e4 2271class merge_pattern_info
59250a8d 2272{
251317e4 2273public:
59250a8d 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
2329merge_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. */
251317e4 2345class merge_state_result
59250a8d 2346{
251317e4 2347public:
59250a8d 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
2369merge_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. */
251317e4 2377class merge_state_info
59250a8d 2378{
251317e4 2379public:
59250a8d 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
2403merge_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
2413static bool
2414useful_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
2422static bool
2423same_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
2433static bool
2434valid_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
2449static void
2450prune_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);
a698628e 2456 }
6d69ff19 2457}
263287f7 2458
59250a8d 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
2463static bool
2464complete_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. */
263287f7 2475
6d69ff19 2476static void
59250a8d 2477update_parameters (vec <parameter> &to, const vec <parameter> &from)
6d69ff19 2478{
59250a8d 2479 for (unsigned int i = to.length (); i < from.length (); ++i)
2480 to.quick_push (from[i]);
2481}
6d69ff19 2482
59250a8d 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
2488static bool
abef0e58 2489compatible_tests_p (const rtx_test &a, const rtx_test &b,
59250a8d 2490 parameter *parama, parameter *paramb)
2491{
2492 if (a.kind != b.kind)
2493 return false;
2494 switch (a.kind)
a698628e 2495 {
abef0e58 2496 case rtx_test::PREDICATE:
59250a8d 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
abef0e58 2503 case rtx_test::SAVED_CONST_INT:
59250a8d 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;
a698628e 2510 }
59250a8d 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. */
263287f7 2518
59250a8d 2519static bool
2520set_parameter (vec <parameter> &params, unsigned int id,
2521 const parameter &value)
2522{
2523 if (params[id].type == parameter::UNSET)
a698628e 2524 {
59250a8d 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
2544static bool
2545add_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;
6d69ff19 2566
59250a8d 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
2577static bool
2578merge_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)
6d69ff19 2586 {
59250a8d 2587 *roota = rootb;
2588 return true;
6d69ff19 2589 }
59250a8d 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;
263287f7 2604 }
59250a8d 2605 if (!*roota)
2606 *roota = a;
2607 return *roota == a;
2608}
263287f7 2609
59250a8d 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"). */
770ff93b 2612struct test_pattern_hasher : nofree_ptr_hash <merge_state_info>
59250a8d 2613{
59250a8d 2614 static inline hashval_t hash (const value_type &);
2615 static inline bool equal (const value_type &, const compare_type &);
2616};
263287f7 2617
59250a8d 2618hashval_t
2619test_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}
6d69ff19 2630
59250a8d 2631bool
2632test_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}
6d69ff19 2645
59250a8d 2646/* Try to make the state described by SINFO1 use the same pattern as the
2647 state described by SINFO2. Return true on success.
3e9f1237 2648
59250a8d 2649 SINFO1 and SINFO2 are known to have the same hash value. */
2650
2651static bool
2652merge_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 }
3e9f1237 2726 }
59250a8d 2727 }
6d69ff19 2728
59250a8d 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;
6d69ff19 2753 }
263287f7 2754 }
59250a8d 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)
6d69ff19 2760 {
59250a8d 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. */
abef0e58 2775 if (d1->test.kind == rtx_test::WIDE_INT_FIELD)
59250a8d 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;
6d69ff19 2802 }
263287f7 2803
59250a8d 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;
263287f7 2830}
2831
59250a8d 2832/* The number of states that were removed by calling pattern routines. */
2833static unsigned int pattern_use_states;
6d69ff19 2834
59250a8d 2835/* The number of states used while defining pattern routines. */
2836static unsigned int pattern_def_states;
2837
2838/* Information used while constructing a use or definition of a pattern
2839 routine. */
2840struct 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
2852static 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
2864static decision *
2865init_pattern_use (create_pattern_info *cpi, merge_state_info *sinfo,
2866 const vec <parameter> &params)
263287f7 2867{
59250a8d 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);
abef0e58 2911 decision *d = new decision (rtx_test::pattern (res->root, use));
59250a8d 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
2924static void
2925add_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;
abef0e58 2931 add_decision (s, rtx_test::accept (acceptance), true, false);
59250a8d 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)". */
263287f7 2945
59250a8d 2946static void
2947populate_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)
6d69ff19 2964 {
59250a8d 2965 const parameter &param = params[pat->param_test];
2966 switch (newd->test.kind)
6d69ff19 2967 {
abef0e58 2968 case rtx_test::PREDICATE:
59250a8d 2969 newd->test.u.predicate.mode_is_param = param.is_param;
2970 newd->test.u.predicate.mode = param.value;
2971 break;
2972
abef0e58 2973 case rtx_test::SAVED_CONST_INT:
59250a8d 2974 newd->test.u.integer.is_param = param.is_param;
2975 newd->test.u.integer.value = param.value;
2976 break;
2977
6d69ff19 2978 default:
e0a4c0c2 2979 gcc_unreachable ();
59250a8d 2980 break;
6d69ff19 2981 }
2982 }
abef0e58 2983 if (d->test.kind == rtx_test::C_TEST)
59250a8d 2984 routine->insn_p = true;
abef0e58 2985 else if (d->test.kind == rtx_test::HAVE_NUM_CLOBBERS)
59250a8d 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 }
263287f7 3014
59250a8d 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;
263287f7 3025
59250a8d 3026 /* Add the pattern routine call to the new target state. */
3027 to_news->push_back (subd);
6d69ff19 3028
59250a8d 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)
7e5202bc 3046 {
59250a8d 3047 const parameter &param = params[pat->param_transition];
3048 new_trans->is_param = param.is_param;
3049 new_trans->labels[0] = param.value;
7e5202bc 3050 }
59250a8d 3051 newd->push_back (new_trans);
3052 i += 1;
7e5202bc 3053 }
59250a8d 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. */
7e5202bc 3059
59250a8d 3060static void
3061populate_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)
6d69ff19 3072 {
59250a8d 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. */
6d69ff19 3090
59250a8d 3091static void
3092use_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
3112static void
3113split_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)
6d69ff19 3124 {
59250a8d 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. */
abef0e58 3146 if (d->test.kind != rtx_test::ACCEPT
59250a8d 3147 && (pattern_have_num_clobbers_p
abef0e58 3148 || d->test.kind != rtx_test::HAVE_NUM_CLOBBERS)
59250a8d 3149 && (pattern_c_test_p
abef0e58 3150 || d->test.kind != rtx_test::C_TEST))
59250a8d 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. */
3363struct 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. */
3374typedef 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
3379static int
3380subroutine_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
3389static state *
3390create_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;
abef0e58 3398 add_decision (news, rtx_test::accept (acceptance), true, false);
59250a8d 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
3406static state_size
3407find_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 ();
abef0e58 3435 if (newd->test.kind == rtx_test::SET_OP
3436 || newd->test.kind == rtx_test::ACCEPT)
59250a8d 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
3488static bool
3489safe_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]
8770d0ad 3495 || pred->codes[CONST_WIDE_INT]
3496 || pred->codes[LABEL_REF]))
59250a8d 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
3504static void
3505get_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
3514static bool
3515has_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
3531static bool
3532mutually_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
3586static bool
3587merge_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
3803static bool
3804merge_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
3868static void
3869merge_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. */
251317e4 3878class pattern_pos {
3879public:
59250a8d 3880 pattern_pos () {}
3881 pattern_pos (rtx, position *);
3882
3883 rtx pattern;
3884 position *pos;
3885};
3886
3887pattern_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
3894bool
3895operator < (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
59250a8d 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
3906static state *
c04601c1 3907match_pattern_2 (state *s, md_rtx_info *info, position *pos, rtx pattern)
59250a8d 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. */
c04601c1 3932 pattern = find_operand (info->def, XINT (pattern, 0), NULL_RTX);
59250a8d 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)
c04601c1 3949 error_at (info->loc, "unknown predicate '%s' used in %s",
3950 pred_name, GET_RTX_NAME (code));
59250a8d 3951 else if (code == MATCH_PARALLEL
3952 && pred->singleton != PARALLEL)
c04601c1 3953 error_at (info->loc, "predicate '%s' used in"
3954 " match_parallel does not allow only PARALLEL",
3955 pred->name);
59250a8d 3956 }
3957 }
3958
3959 if (code == MATCH_PARALLEL || code == MATCH_PAR_DUP)
3960 {
3961 /* Check that we have a parallel with enough elements. */
abef0e58 3962 s = add_decision (s, rtx_test::code (pos), PARALLEL, false);
59250a8d 3963 int min_len = XVECLEN (pattern, 2);
abef0e58 3964 s = add_decision (s, rtx_test::veclen_ge (pos, min_len),
59250a8d 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));
abef0e58 3979 s = add_decision (s, rtx_test::code (pos), codes, !need_codes);
59250a8d 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. */
abef0e58 4020 s = add_decision (s, rtx_test::code (pos), code, false);
59250a8d 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);
abef0e58 4045 s = add_decision (s, rtx_test::veclen (pos),
4046 length, false);
59250a8d 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. */
abef0e58 4062 s = add_decision (s, rtx_test::int_field (pos, i),
59250a8d 4063 XINT (pattern, i), false);
4064 break;
4065
15183fd2 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
59250a8d 4073 case 'w':
4074 /* Make sure that XWINT (X, I) has the right value. */
abef0e58 4075 s = add_decision (s, rtx_test::wide_int_field (pos, i),
59250a8d 4076 XWINT (pattern, 0), false);
4077 break;
4078
9edf7ea8 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
59250a8d 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);
85099d88 4148 if (pred && safe_predicate_mode (pred, mode))
abef0e58 4149 s = add_decision (s, rtx_test::mode (e->pos), mode, true);
59250a8d 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. */
abef0e58 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),
59250a8d 4161 true, false);
4162 }
4163 else
4164 /* Historically we've ignored the mode when there's no
4165 predicate. Just set up operands[] unconditionally. */
abef0e58 4166 s = add_decision (s, rtx_test::set_op (e->pos, opno),
4167 true, false);
59250a8d 4168 break;
4169 }
4170
4171 default:
abef0e58 4172 s = add_decision (s, rtx_test::mode (e->pos),
59250a8d 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)
abef0e58 4180 s = add_decision (s, rtx_test::duplicate (e->pos, XINT (e->pattern, 0)),
59250a8d 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
7c1b1064 4189 (3) the C test required by INFO->def is true
59250a8d 4190
a545c6cd 4191 For peephole2, TOP_PATTERN is a SEQUENCE of the instruction patterns
4192 to match, otherwise it is a single instruction pattern. */
59250a8d 4193
4194static void
7c1b1064 4195match_pattern_1 (state *s, md_rtx_info *info, rtx pattern,
59250a8d 4196 acceptance_type acceptance)
4197{
a545c6cd 4198 if (acceptance.type == PEEPHOLE2)
59250a8d 4199 {
4200 /* Match each individual instruction. */
4201 position **subpos_ptr = &peep2_insn_pos_list;
4202 int count = 0;
c04601c1 4203 for (int i = 0; i < XVECLEN (pattern, 0); ++i)
59250a8d 4204 {
c04601c1 4205 rtx x = XVECEXP (pattern, 0, i);
a545c6cd 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);
c04601c1 4211 s = match_pattern_2 (s, info, subpos, x);
a545c6cd 4212 subpos_ptr = &subpos->next;
4213 count += 1;
59250a8d 4214 }
4215 acceptance.u.full.u.match_len = count - 1;
4216 }
4217 else
4218 {
4219 /* Make the rtx itself. */
c04601c1 4220 s = match_pattern_2 (s, info, &root_pos, pattern);
59250a8d 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)
abef0e58 4225 s = add_decision (s, rtx_test::have_num_clobbers (), true, false);
59250a8d 4226 }
4227
4228 /* Make sure that the C test is true. */
7c1b1064 4229 const char *c_test = get_c_test (info->def);
59250a8d 4230 if (maybe_eval_c_test (c_test) != 1)
abef0e58 4231 s = add_decision (s, rtx_test::c_test (c_test), true, false);
59250a8d 4232
4233 /* Accept the pattern. */
abef0e58 4234 add_decision (s, rtx_test::accept (acceptance), true, false);
59250a8d 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
4241static void
7c1b1064 4242match_pattern (state *s, md_rtx_info *info, rtx pattern,
59250a8d 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. */
7c1b1064 4250 match_pattern_1 (&root, info, pattern, acceptance);
59250a8d 4251 merge_into_state (s, &root);
4252 }
4253 else
7c1b1064 4254 match_pattern_1 (s, info, pattern, acceptance);
59250a8d 4255}
4256
4257/* Begin the output file. */
4258
4259static void
4260write_header (void)
4261{
4262 puts ("\
4263/* Generated automatically by the program `genrecog' from the target\n\
4264 machine description file. */\n\
4265\n\
785790dc 4266#define IN_TARGET_CODE 1\n\
4267\n\
59250a8d 4268#include \"config.h\"\n\
4269#include \"system.h\"\n\
4270#include \"coretypes.h\"\n\
9ef16211 4271#include \"backend.h\"\n\
d040a5b0 4272#include \"predict.h\"\n\
59250a8d 4273#include \"rtl.h\"\n\
ad7b10a2 4274#include \"memmodel.h\"\n\
59250a8d 4275#include \"tm_p.h\"\n\
73bde8df 4276#include \"emit-rtl.h\"\n\
59250a8d 4277#include \"insn-config.h\"\n\
4278#include \"recog.h\"\n\
4279#include \"output.h\"\n\
4280#include \"flags.h\"\n\
9ef16211 4281#include \"df.h\"\n\
59250a8d 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\
59250a8d 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
4322static const char *
4323parameter_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
15183fd2 4339 case parameter::UINT:
4340 return "unsigned int";
4341
59250a8d 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
4351static bool
4352single_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
4377static const char *
4378get_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:
58a87a29 4388 return "NULL";
59250a8d 4389 }
4390 gcc_unreachable ();
4391}
4392
4393/* Indicates whether a block of code always returns or whether it can fall
4394 through. */
4395
4396enum exit_state {
4397 ES_RETURNED,
4398 ES_FALLTHROUGH
4399};
4400
4401/* Information used while writing out code. */
4402
251317e4 4403class output_state
59250a8d 4404{
251317e4 4405public:
59250a8d 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
4427static bool
4428terminal_pattern_p (decision *d, unsigned int *base_out,
4429 unsigned int *count_out)
4430{
abef0e58 4431 if (d->test.kind != rtx_test::PATTERN)
59250a8d 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 ();
abef0e58 4440 if (!subd || subd->test.kind != rtx_test::ACCEPT)
59250a8d 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
4458static bool
abef0e58 4459test_position_available_p (output_state *os, const rtx_test &test)
59250a8d 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
4468static void ATTRIBUTE_PRINTF_2
4469printf_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
4482static void
4483change_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
4514static void
4515print_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
4526static void
4527print_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
4538static void
4539print_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:
1e0295b9 4555 printf ("E_%smode", GET_MODE_NAME ((machine_mode) param.value));
59250a8d 4556 break;
4557
4558 case parameter::INT:
4559 printf ("%d", (int) param.value);
4560 break;
4561
15183fd2 4562 case parameter::UINT:
4563 printf ("%u", (unsigned int) param.value);
4564 break;
4565
59250a8d 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
4574static void
abef0e58 4575print_test_rtx (output_state *os, const rtx_test &test)
59250a8d 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
4585static void
abef0e58 4586print_nonbool_test (output_state *os, const rtx_test &test)
59250a8d 4587{
4588 switch (test.kind)
4589 {
abef0e58 4590 case rtx_test::CODE:
59250a8d 4591 printf ("GET_CODE (");
4592 print_test_rtx (os, test);
4593 printf (")");
4594 break;
4595
abef0e58 4596 case rtx_test::MODE:
59250a8d 4597 printf ("GET_MODE (");
4598 print_test_rtx (os, test);
4599 printf (")");
4600 break;
4601
abef0e58 4602 case rtx_test::VECLEN:
59250a8d 4603 printf ("XVECLEN (");
4604 print_test_rtx (os, test);
4605 printf (", 0)");
4606 break;
4607
abef0e58 4608 case rtx_test::INT_FIELD:
59250a8d 4609 printf ("XINT (");
4610 print_test_rtx (os, test);
4611 printf (", %d)", test.u.opno);
4612 break;
4613
15183fd2 4614 case rtx_test::REGNO_FIELD:
4615 printf ("REGNO (");
4616 print_test_rtx (os, test);
4617 printf (")");
4618 break;
4619
9edf7ea8 4620 case rtx_test::SUBREG_FIELD:
4621 printf ("SUBREG_BYTE (");
4622 print_test_rtx (os, test);
4623 printf (")");
4624 break;
4625
abef0e58 4626 case rtx_test::WIDE_INT_FIELD:
59250a8d 4627 printf ("XWINT (");
4628 print_test_rtx (os, test);
4629 printf (", %d)", test.u.opno);
4630 break;
4631
abef0e58 4632 case rtx_test::PATTERN:
59250a8d 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
abef0e58 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:
59250a8d 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
4678static void
abef0e58 4679print_label_value (const rtx_test &test, bool is_param, uint64_t value)
59250a8d 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
4689static void
abef0e58 4690print_test (output_state *os, const rtx_test &test, bool is_param,
4691 uint64_t value, bool invert_p)
59250a8d 4692{
4693 switch (test.kind)
4694 {
4695 /* Handle the non-boolean TESTs. */
abef0e58 4696 case rtx_test::CODE:
4697 case rtx_test::MODE:
4698 case rtx_test::VECLEN:
15183fd2 4699 case rtx_test::REGNO_FIELD:
abef0e58 4700 case rtx_test::INT_FIELD:
4701 case rtx_test::WIDE_INT_FIELD:
4702 case rtx_test::PATTERN:
59250a8d 4703 print_nonbool_test (os, test);
4704 printf (" %s ", invert_p ? "!=" : "==");
4705 print_label_value (test, is_param, value);
4706 break;
4707
9edf7ea8 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
abef0e58 4716 case rtx_test::SAVED_CONST_INT:
59250a8d 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
abef0e58 4727 case rtx_test::PEEP2_COUNT:
59250a8d 4728 gcc_assert (!is_param && value == 1);
4729 printf ("peep2_current_count %s %d", invert_p ? "<" : ">=",
4730 test.u.min_len);
4731 break;
4732
abef0e58 4733 case rtx_test::VECLEN_GE:
59250a8d 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
abef0e58 4740 case rtx_test::PREDICATE:
59250a8d 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
abef0e58 4751 case rtx_test::DUPLICATE:
59250a8d 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
abef0e58 4758 case rtx_test::HAVE_NUM_CLOBBERS:
59250a8d 4759 gcc_assert (!is_param && value == 1);
4760 printf ("pnum_clobbers %s NULL", invert_p ? "==" : "!=");
4761 break;
4762
abef0e58 4763 case rtx_test::C_TEST:
59250a8d 4764 gcc_assert (!is_param && value == 1);
4765 if (invert_p)
4766 printf ("!");
e1e9159b 4767 rtx_reader_ptr->print_c_condition (test.u.string);
59250a8d 4768 break;
4769
abef0e58 4770 case rtx_test::ACCEPT:
4771 case rtx_test::SET_OP:
59250a8d 4772 gcc_unreachable ();
4773 }
4774}
4775
4776static 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
4783static exit_state
4784print_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
4801static const char *
4802print_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
4829static exit_state
4830print_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
4895static exit_state
4896print_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 }
abef0e58 4947 else if (d->test.kind == rtx_test::ACCEPT)
59250a8d 4948 return print_acceptance (d->test.u.acceptance, indent, is_final);
abef0e58 4949 else if (d->test.kind == rtx_test::SET_OP)
59250a8d 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
abef0e58 4978 || d->test.kind == rtx_test::ACCEPT
4979 || d->test.kind == rtx_test::SET_OP
59250a8d 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 ()
abef0e58 5004 && to->first->test.kind == rtx_test::ACCEPT
59250a8d 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");
6d69ff19 5064
59250a8d 5065 /* Restore the original set of valid variables. */
5066 os->seen_vars.truncate (0);
5067 os->seen_vars.splice (old_seen);
6d69ff19 5068 }
59250a8d 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;
6d69ff19 5078 }
59250a8d 5079}
6d69ff19 5080
59250a8d 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. */
6d69ff19 5083
59250a8d 5084static void
5085assign_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);
263287f7 5094}
5095
59250a8d 5096/* Make sure that OS has the position variables required by S. */
6d69ff19 5097
263287f7 5098static void
59250a8d 5099assign_position_vars (output_state *os, state *s)
263287f7 5100{
59250a8d 5101 for (decision *d = s->first; d; d = d->next)
6d69ff19 5102 {
59250a8d 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);
6d69ff19 5109 }
6d69ff19 5110}
a698628e 5111
59250a8d 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. */
a698628e 5117
5118static void
59250a8d 5119print_subroutine_start (output_state *os, state *s, position *root)
a698628e 5120{
59250a8d 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)
a698628e 5126 {
59250a8d 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);
6d69ff19 5131
59250a8d 5132 /* Associate ROOT with x1. */
5133 assign_position_var (os, root, true);
a698628e 5134
59250a8d 5135 /* Assign xN variables to all other relevant positions. */
5136 assign_position_vars (os, s);
6d69ff19 5137
59250a8d 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)
a698628e 5142 {
59250a8d 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");
6d69ff19 5148 }
a698628e 5149
59250a8d 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;
6d69ff19 5153 }
59250a8d 5154 if (os->type == SUBPATTERN || os->type == RECOG)
5155 printf (" int res ATTRIBUTE_UNUSED;\n");
5156 else
58a87a29 5157 printf (" rtx_insn *res ATTRIBUTE_UNUSED;\n");
a698628e 5158}
5159
59250a8d 5160/* Output the definition of pattern routine ROUTINE. */
82575fa7 5161
6d69ff19 5162static void
59250a8d 5163print_pattern (output_state *os, pattern_routine *routine)
6d69ff19 5164{
59250a8d 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}
a698628e 5199
59250a8d 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. */
6d69ff19 5203
59250a8d 5204static void
5205print_subroutine (output_state *os, state *s, int proc_id)
5206{
59250a8d 5207 printf ("\n");
5208 switch (os->type)
e4ba8ded 5209 {
59250a8d 5210 case SUBPATTERN:
5211 gcc_unreachable ();
5212
e4ba8ded 5213 case RECOG:
59250a8d 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"
30302b7c 5219 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5220 "\tint *pnum_clobbers ATTRIBUTE_UNUSED)\n");
e4ba8ded 5221 break;
59250a8d 5222
e4ba8ded 5223 case SPLIT:
59250a8d 5224 if (proc_id)
58a87a29 5225 printf ("static rtx_insn *\nsplit_%d", proc_id);
59250a8d 5226 else
58a87a29 5227 printf ("rtx_insn *\nsplit_insns");
5228 printf (" (rtx x1 ATTRIBUTE_UNUSED, rtx_insn *insn ATTRIBUTE_UNUSED)\n");
e4ba8ded 5229 break;
59250a8d 5230
e4ba8ded 5231 case PEEPHOLE2:
59250a8d 5232 if (proc_id)
58a87a29 5233 printf ("static rtx_insn *\npeephole2_%d", proc_id);
59250a8d 5234 else
58a87a29 5235 printf ("rtx_insn *\npeephole2_insns");
59250a8d 5236 printf (" (rtx x1 ATTRIBUTE_UNUSED,\n"
58a87a29 5237 "\trtx_insn *insn ATTRIBUTE_UNUSED,\n"
5238 "\tint *pmatch_len_ ATTRIBUTE_UNUSED)\n");
e4ba8ded 5239 break;
5240 }
59250a8d 5241 print_subroutine_start (os, s, &root_pos);
5242 if (proc_id == 0)
bf59a32d 5243 {
60ff05a9 5244 printf (" recog_data.insn = NULL;\n");
bf59a32d 5245 }
59250a8d 5246 print_state (os, s, 2, true);
5247 printf ("}\n");
6d69ff19 5248}
5249
59250a8d 5250/* Print out a routine of type TYPE that performs ROOT. */
a698628e 5251
263287f7 5252static void
59250a8d 5253print_subroutine_group (output_state *os, routine_type type, state *root)
263287f7 5254{
59250a8d 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);
6d69ff19 5271}
82575fa7 5272
a545c6cd 5273/* Return the rtx pattern for the list of rtxes in a define_peephole2. */
5274
5275static rtx
c04601c1 5276get_peephole2_pattern (md_rtx_info *info)
a545c6cd 5277{
5278 int i, j;
c04601c1 5279 rtvec vec = XVEC (info->def, 0);
a545c6cd 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)
c04601c1 5294 error_at (info->loc, "empty define_peephole2");
a545c6cd 5295 return pattern;
5296}
5297
59250a8d 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. */
6d69ff19 5303
59250a8d 5304static bool
5305remove_clobbers (acceptance_type *acceptance_ptr, rtx *pattern_ptr)
5306{
5307 int i;
5308 rtx new_pattern;
6d69ff19 5309
59250a8d 5310 /* Find the last non-clobber in the parallel. */
5311 rtx pattern = *pattern_ptr;
5312 for (i = XVECLEN (pattern, 0); i > 0; i--)
6d69ff19 5313 {
59250a8d 5314 rtx x = XVECEXP (pattern, 0, i - 1);
f03bb97b 5315 if (GET_CODE (x) != CLOBBER
59250a8d 5316 || (!REG_P (XEXP (x, 0))
5317 && GET_CODE (XEXP (x, 0)) != MATCH_SCRATCH))
5318 break;
263287f7 5319 }
a698628e 5320
59250a8d 5321 if (i == XVECLEN (pattern, 0))
5322 return false;
263287f7 5323
59250a8d 5324 /* Build a similar insn without the clobbers. */
5325 if (i == 1)
5326 new_pattern = XVECEXP (pattern, 0, 0);
f4adfe76 5327 else
a5deb6f6 5328 {
59250a8d 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);
a5deb6f6 5333 }
f4adfe76 5334
59250a8d 5335 /* Recognize it. */
5336 acceptance_ptr->u.full.u.num_clobbers = XVECLEN (pattern, 0) - i;
5337 *pattern_ptr = new_pattern;
5338 return true;
6d69ff19 5339}
867b95d0 5340
263287f7 5341int
16570c04 5342main (int argc, const char **argv)
263287f7 5343{
59250a8d 5344 state insn_root, split_root, peephole2_root;
263287f7 5345
04b58880 5346 progname = "genrecog";
6d69ff19 5347
77ba95d0 5348 if (!init_rtx_reader_args (argc, argv))
c5ddd6b5 5349 return (FATAL_EXIT_CODE);
263287f7 5350
6d69ff19 5351 write_header ();
263287f7 5352
5353 /* Read the machine description. */
5354
c04601c1 5355 md_rtx_info info;
5356 while (read_md_rtx (&info))
263287f7 5357 {
c04601c1 5358 rtx def = info.def;
263287f7 5359
59250a8d 5360 acceptance_type acceptance;
5361 acceptance.partial_p = false;
c04601c1 5362 acceptance.u.full.code = info.index;
59250a8d 5363
a545c6cd 5364 rtx pattern;
c04601c1 5365 switch (GET_CODE (def))
6d69ff19 5366 {
cbf464bd 5367 case DEFINE_INSN:
59250a8d 5368 {
5369 /* Match the instruction in the original .md form. */
59250a8d 5370 acceptance.type = RECOG;
5371 acceptance.u.full.u.num_clobbers = 0;
c04601c1 5372 pattern = add_implicit_parallel (XVEC (def, 1));
5373 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5374 match_pattern (&insn_root, &info, pattern, acceptance);
59250a8d 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))
7c1b1064 5380 match_pattern (&insn_root, &info, pattern, acceptance);
59250a8d 5381 break;
5382 }
cbf464bd 5383
5384 case DEFINE_SPLIT:
59250a8d 5385 acceptance.type = SPLIT;
c04601c1 5386 pattern = add_implicit_parallel (XVEC (def, 0));
5387 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5388 match_pattern (&split_root, &info, pattern, acceptance);
59250a8d 5389
5390 /* Declare the gen_split routine that we'll call if the
5391 pattern matches. The definition comes from insn-emit.c. */
58a87a29 5392 printf ("extern rtx_insn *gen_split_%d (rtx_insn *, rtx *);\n",
c04601c1 5393 info.index);
cbf464bd 5394 break;
5395
5396 case DEFINE_PEEPHOLE2:
59250a8d 5397 acceptance.type = PEEPHOLE2;
c04601c1 5398 pattern = get_peephole2_pattern (&info);
5399 validate_pattern (pattern, &info, NULL_RTX, 0);
7c1b1064 5400 match_pattern (&peephole2_root, &info, pattern, acceptance);
59250a8d 5401
5402 /* Declare the gen_peephole2 routine that we'll call if the
5403 pattern matches. The definition comes from insn-emit.c. */
58a87a29 5404 printf ("extern rtx_insn *gen_peephole2_%d (rtx_insn *, rtx *);\n",
c04601c1 5405 info.index);
59250a8d 5406 break;
fcb53c1e 5407
cbf464bd 5408 default:
5409 /* do nothing */;
5410 }
263287f7 5411 }
5412
b638f5c8 5413 if (have_error)
0922b1b8 5414 return FATAL_EXIT_CODE;
5415
6d69ff19 5416 puts ("\n\n");
263287f7 5417
59250a8d 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);
6d69ff19 5422
59250a8d 5423 output_state os;
5424 os.id_to_var.safe_grow_cleared (num_positions);
6d69ff19 5425
59250a8d 5426 if (use_pattern_routines_p)
6d69ff19 5427 {
59250a8d 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);
6d69ff19 5440 }
5441
59250a8d 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);
940b9cea 5446
59250a8d 5447 fflush (stdout);
5448 return (ferror (stdout) != 0 ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE);
940b9cea 5449}