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