Debian Codegraph @

gcc/config/riscv/riscv.cc

raw
1 /* Subroutines used for code generation for RISC-V.
2 Copyright (C) 2011-2025 Free Software Foundation, Inc.
3 Contributed by Andrew Waterman ([email protected]).
4 Based on MIPS target for GNU compiler.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
21
22 #define IN_TARGET_CODE 1
23
24 #define INCLUDE_STRING
25 #define INCLUDE_VECTOR
26 #define INCLUDE_ALGORITHM
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "target.h"
31 #include "backend.h"
32 #include "tm.h"
33 #include "rtl.h"
34 #include "regs.h"
35 #include "insn-config.h"
36 #include "insn-attr.h"
37 #include "recog.h"
38 #include "output.h"
39 #include "alias.h"
40 #include "tree.h"
41 #include "stringpool.h"
42 #include "attribs.h"
43 #include "varasm.h"
44 #include "stor-layout.h"
45 #include "calls.h"
46 #include "function.h"
47 #include "explow.h"
48 #include "ifcvt.h"
49 #include "memmodel.h"
50 #include "emit-rtl.h"
51 #include "reload.h"
52 #include "tm_p.h"
53 #include "basic-block.h"
54 #include "expr.h"
55 #include "optabs.h"
56 #include "bitmap.h"
57 #include "df.h"
58 #include "function-abi.h"
59 #include "diagnostic.h"
60 #include "builtins.h"
61 #include "predict.h"
62 #include "tree-pass.h"
63 #include "opts.h"
64 #include "tm-constrs.h"
65 #include "rtl-iter.h"
66 #include "gimple.h"
67 #include "cfghooks.h"
68 #include "cfgloop.h"
69 #include "cfgrtl.h"
70 #include "shrink-wrap.h"
71 #include "sel-sched.h"
72 #include "sched-int.h"
73 #include "fold-const.h"
74 #include "gimple-iterator.h"
75 #include "gimple-expr.h"
76 #include "tree-vectorizer.h"
77 #include "gcse.h"
78 #include "tree-dfa.h"
79 #include "target-globals.h"
80 #include "riscv-v.h"
81 #include "cgraph.h"
82 #include "langhooks.h"
83 #include "gimplify.h"
84
85 /* This file should be included last. */
86 #include "target-def.h"
87 #include "riscv-vector-costs.h"
88 #include "riscv-subset.h"
89
90 /* True if X is an UNSPEC wrapper around a SYMBOL_REF or LABEL_REF. */
91 #define UNSPEC_ADDRESS_P(X) \
92 (GET_CODE (X) == UNSPEC \
93 && XINT (X, 1) >= UNSPEC_ADDRESS_FIRST \
94 && XINT (X, 1) < UNSPEC_ADDRESS_FIRST + NUM_SYMBOL_TYPES)
95
96 /* Extract the symbol or label from UNSPEC wrapper X. */
97 #define UNSPEC_ADDRESS(X) \
98 XVECEXP (X, 0, 0)
99
100 /* Extract the symbol type from UNSPEC wrapper X. */
101 #define UNSPEC_ADDRESS_TYPE(X) \
102 ((enum riscv_symbol_type) (XINT (X, 1) - UNSPEC_ADDRESS_FIRST))
103
104 /* Extract the backup dynamic frm rtl. */
105 #define DYNAMIC_FRM_RTL(c) ((c)->machine->mode_sw_info.dynamic_frm)
106
107 /* True the mode switching has static frm, or false. */
108 #define STATIC_FRM_P(c) ((c)->machine->mode_sw_info.static_frm_p)
109
110 /* True if we can use the instructions in the XTheadInt extension
111 to handle interrupts, or false. */
112 #define TH_INT_INTERRUPT(c) \
113 (TARGET_XTHEADINT \
114 /* The XTheadInt extension only supports rv32. */ \
115 && !TARGET_64BIT \
116 && (c)->machine->interrupt_handler_p \
117 /* The XTheadInt instructions can only be executed in M-mode. */ \
118 && (c)->machine->interrupt_mode == MACHINE_MODE)
119
120 /* Information about a function's frame layout. */
121 struct GTY(()) riscv_frame_info {
122 /* The size of the frame in bytes. */
123 poly_int64 total_size;
124
125 /* Bit X is set if the function saves or restores GPR X. */
126 unsigned int mask;
127
128 /* Likewise FPR X. */
129 unsigned int fmask;
130
131 /* Likewise for vector registers. */
132 unsigned int vmask;
133
134 /* How much the GPR save/restore routines adjust sp (or 0 if unused). */
135 unsigned save_libcall_adjustment;
136
137 /* the minimum number of bytes, in multiples of 16-byte address increments,
138 required to cover the registers in a multi push & pop. */
139 unsigned multi_push_adj_base;
140
141 /* the number of additional 16-byte address increments allocated for the stack
142 frame in a multi push & pop. */
143 unsigned multi_push_adj_addi;
144
145 /* Offsets of fixed-point and floating-point save areas from frame bottom */
146 poly_int64 gp_sp_offset;
147 poly_int64 fp_sp_offset;
148
149 /* Top and bottom offsets of vector save areas from frame bottom. */
150 poly_int64 v_sp_offset_top;
151 poly_int64 v_sp_offset_bottom;
152
153 /* Offset of virtual frame pointer from stack pointer/frame bottom */
154 poly_int64 frame_pointer_offset;
155
156 /* Offset of hard frame pointer from stack pointer/frame bottom */
157 poly_int64 hard_frame_pointer_offset;
158
159 /* The offset of arg_pointer_rtx from the bottom of the frame. */
160 poly_int64 arg_pointer_offset;
161
162 /* Reset this struct, clean all field to zero. */
163 void reset(void);
164 };
165
166 enum riscv_privilege_levels {
167 UNKNOWN_MODE, USER_MODE, SUPERVISOR_MODE, MACHINE_MODE
168 };
169
170 struct GTY(()) mode_switching_info {
171 /* The RTL variable which stores the dynamic FRM value. We always use this
172 RTX to restore dynamic FRM rounding mode in mode switching. */
173 rtx dynamic_frm;
174
175 /* The boolean variables indicates there is at least one static rounding
176 mode instruction in the function or not. */
177 bool static_frm_p;
178
179 mode_switching_info ()
180 {
181 dynamic_frm = NULL_RTX;
182 static_frm_p = false;
183 }
184 };
185
186 struct GTY(()) machine_function {
187 /* The number of extra stack bytes taken up by register varargs.
188 This area is allocated by the callee at the very top of the frame. */
189 int varargs_size;
190
191 /* True if current function is a naked function. */
192 bool naked_p;
193
194 /* True if current function is an interrupt function. */
195 bool interrupt_handler_p;
196 /* For an interrupt handler, indicates the privilege level. */
197 enum riscv_privilege_levels interrupt_mode;
198
199 /* True if attributes on current function have been checked. */
200 bool attributes_checked_p;
201
202 /* True if RA must be saved because of a far jump. */
203 bool far_jump_used;
204
205 /* The current frame information, calculated by riscv_compute_frame_info. */
206 struct riscv_frame_info frame;
207
208 /* The components already handled by separate shrink-wrapping, which should
209 not be considered by the prologue and epilogue. */
210 bool reg_is_wrapped_separately[FIRST_PSEUDO_REGISTER];
211
212 /* The mode switching information for the FRM rounding modes. */
213 struct mode_switching_info mode_sw_info;
214 };
215
216 /* Information about a single argument. */
217 struct riscv_arg_info {
218 /* True if the argument is at least partially passed on the stack. */
219 bool stack_p;
220
221 /* The number of integer registers allocated to this argument. */
222 unsigned int num_gprs;
223
224 /* The offset of the first register used, provided num_gprs is nonzero.
225 If passed entirely on the stack, the value is MAX_ARGS_IN_REGISTERS. */
226 unsigned int gpr_offset;
227
228 /* The number of floating-point registers allocated to this argument. */
229 unsigned int num_fprs;
230
231 /* The offset of the first register used, provided num_fprs is nonzero. */
232 unsigned int fpr_offset;
233
234 /* The number of vector registers allocated to this argument. */
235 unsigned int num_vrs;
236
237 /* The offset of the first register used, provided num_vrs is nonzero. */
238 unsigned int vr_offset;
239
240 /* The number of mask registers allocated to this argument. */
241 unsigned int num_mrs;
242
243 /* The offset of the first register used, provided num_mrs is nonzero. */
244 unsigned int mr_offset;
245 };
246
247 /* One stage in a constant building sequence. These sequences have
248 the form:
249
250 A = VALUE[0]
251 A = A CODE[1] VALUE[1]
252 A = A CODE[2] VALUE[2]
253 ...
254
255 where A is an accumulator, each CODE[i] is a binary rtl operation
256 and each VALUE[i] is a constant integer. CODE[0] is undefined. */
257 struct riscv_integer_op {
258 bool use_uw;
259 bool save_temporary;
260 enum rtx_code code;
261 unsigned HOST_WIDE_INT value;
262 };
263
264 /* The largest number of operations needed to load an integer constant.
265 The worst case is LUI, ADDI, SLLI, ADDI, SLLI, ADDI, SLLI, ADDI. */
266 #define RISCV_MAX_INTEGER_OPS 8
267
268 enum riscv_fusion_pairs
269 {
270 RISCV_FUSE_NOTHING = 0,
271 RISCV_FUSE_ZEXTW = (1 << 0),
272 RISCV_FUSE_ZEXTH = (1 << 1),
273 RISCV_FUSE_ZEXTWS = (1 << 2),
274 RISCV_FUSE_LDINDEXED = (1 << 3),
275 RISCV_FUSE_LUI_ADDI = (1 << 4),
276 RISCV_FUSE_AUIPC_ADDI = (1 << 5),
277 RISCV_FUSE_LUI_LD = (1 << 6),
278 RISCV_FUSE_AUIPC_LD = (1 << 7),
279 RISCV_FUSE_LDPREINCREMENT = (1 << 8),
280 RISCV_FUSE_ALIGNED_STD = (1 << 9),
281 };
282
283 /* Costs of various operations on the different architectures. */
284
285 struct riscv_tune_param
286 {
287 unsigned short fp_add[2];
288 unsigned short fp_mul[2];
289 unsigned short fp_div[2];
290 unsigned short int_mul[2];
291 unsigned short int_div[2];
292 unsigned short issue_rate;
293 unsigned short branch_cost;
294 unsigned short memory_cost;
295 unsigned short fmv_cost;
296 bool slow_unaligned_access;
297 bool vector_unaligned_access;
298 bool use_divmod_expansion;
299 bool overlap_op_by_pieces;
300 unsigned int fusible_ops;
301 const struct cpu_vector_cost *vec_costs;
302 const char *function_align;
303 const char *jump_align;
304 const char *loop_align;
305 };
306
307
308 /* Global variables for machine-dependent things. */
309
310 /* Whether unaligned accesses execute very slowly. */
311 bool riscv_slow_unaligned_access_p;
312
313 /* Whether misaligned vector accesses are supported (i.e. do not
314 throw an exception). */
315 bool riscv_vector_unaligned_access_p;
316
317 /* Whether user explicitly passed -mstrict-align. */
318 bool riscv_user_wants_strict_align;
319
320 /* Stack alignment to assume/maintain. */
321 unsigned riscv_stack_boundary;
322
323 /* Whether in riscv_output_mi_thunk. */
324 static bool riscv_in_thunk_func = false;
325
326 /* If non-zero, this is an offset to be added to SP to redefine the CFA
327 when restoring the FP register from the stack. Only valid when generating
328 the epilogue. */
329 static poly_int64 epilogue_cfa_sp_offset;
330
331 /* Which tuning parameters to use. */
332 static const struct riscv_tune_param *tune_param;
333
334 /* Which automaton to use for tuning. */
335 enum riscv_microarchitecture_type riscv_microarchitecture;
336
337 /* The number of chunks in a single vector register. */
338 poly_uint16 riscv_vector_chunks;
339
340 /* The number of bytes in a vector chunk. */
341 unsigned riscv_bytes_per_vector_chunk;
342
343 /* Whether we are currently registering builtins. */
344 bool riscv_registering_builtins;
345
346 /* Index R is the smallest register class that contains register R. */
347 const enum reg_class riscv_regno_to_class[FIRST_PSEUDO_REGISTER] = {
348 GR_REGS, GR_REGS, GR_REGS, GR_REGS,
349 GR_REGS, GR_REGS, SIBCALL_REGS, SIBCALL_REGS,
350 JALR_REGS, JALR_REGS, SIBCALL_REGS, SIBCALL_REGS,
351 SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS,
352 SIBCALL_REGS, SIBCALL_REGS, JALR_REGS, JALR_REGS,
353 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
354 JALR_REGS, JALR_REGS, JALR_REGS, JALR_REGS,
355 SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS, SIBCALL_REGS,
356 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
357 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
358 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
359 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
360 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
361 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
362 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
363 RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS, RVC_FP_REGS,
364 FRAME_REGS, FRAME_REGS, NO_REGS, NO_REGS,
365 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
366 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
367 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
368 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
369 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
370 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
371 NO_REGS, NO_REGS, NO_REGS, NO_REGS,
372 VM_REGS, VD_REGS, VD_REGS, VD_REGS,
373 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
374 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
375 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
376 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
377 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
378 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
379 VD_REGS, VD_REGS, VD_REGS, VD_REGS,
380 };
381
382 /* RVV costs for VLS vector operations. */
383 static const common_vector_cost rvv_vls_vector_cost = {
384 1, /* int_stmt_cost */
385 1, /* fp_stmt_cost */
386 1, /* gather_load_cost */
387 1, /* scatter_store_cost */
388 1, /* segment_permute (2) */
389 1, /* segment_permute (3) */
390 1, /* segment_permute (4) */
391 1, /* segment_permute (5) */
392 1, /* segment_permute (6) */
393 1, /* segment_permute (7) */
394 1, /* segment_permute (8) */
395 1, /* vec_to_scalar_cost */
396 1, /* scalar_to_vec_cost */
397 1, /* permute_cost */
398 1, /* align_load_cost */
399 1, /* align_store_cost */
400 2, /* unalign_load_cost */
401 2, /* unalign_store_cost */
402 };
403
404 /* RVV costs for VLA vector operations. */
405 static const scalable_vector_cost rvv_vla_vector_cost = {
406 {
407 1, /* int_stmt_cost */
408 1, /* fp_stmt_cost */
409 1, /* gather_load_cost */
410 1, /* scatter_store_cost */
411 1, /* segment_permute (2) */
412 1, /* segment_permute (3) */
413 1, /* segment_permute (4) */
414 1, /* segment_permute (5) */
415 1, /* segment_permute (6) */
416 1, /* segment_permute (7) */
417 1, /* segment_permute (8) */
418 1, /* vec_to_scalar_cost */
419 1, /* scalar_to_vec_cost */
420 1, /* permute_cost */
421 1, /* align_load_cost */
422 1, /* align_store_cost */
423 2, /* unalign_load_cost */
424 2, /* unalign_store_cost */
425 },
426 };
427
428 /* RVV register move cost. */
429 static const regmove_vector_cost rvv_regmove_vector_cost = {
430 2, /* GR2VR */
431 2, /* FR2VR */
432 2, /* VR2GR */
433 2, /* VR2FR */
434 };
435
436 /* Generic costs for vector insn classes. It is supposed to be the vector cost
437 models used by default if no other cost model was specified. */
438 static const struct cpu_vector_cost generic_vector_cost = {
439 1, /* scalar_int_stmt_cost */
440 1, /* scalar_fp_stmt_cost */
441 1, /* scalar_load_cost */
442 1, /* scalar_store_cost */
443 3, /* cond_taken_branch_cost */
444 1, /* cond_not_taken_branch_cost */
445 &rvv_vls_vector_cost, /* vls */
446 &rvv_vla_vector_cost, /* vla */
447 &rvv_regmove_vector_cost, /* regmove */
448 };
449
450 /* Costs to use when optimizing for rocket. */
451 static const struct riscv_tune_param rocket_tune_info = {
452 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_add */
453 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_mul */
454 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
455 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
456 {COSTS_N_INSNS (33), COSTS_N_INSNS (65)}, /* int_div */
457 1, /* issue_rate */
458 3, /* branch_cost */
459 5, /* memory_cost */
460 8, /* fmv_cost */
461 true, /* slow_unaligned_access */
462 false, /* vector_unaligned_access */
463 false, /* use_divmod_expansion */
464 false, /* overlap_op_by_pieces */
465 RISCV_FUSE_NOTHING, /* fusible_ops */
466 NULL, /* vector cost */
467 NULL, /* function_align */
468 NULL, /* jump_align */
469 NULL, /* loop_align */
470 };
471
472 /* Costs to use when optimizing for Sifive 7 Series. */
473 static const struct riscv_tune_param sifive_7_tune_info = {
474 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_add */
475 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_mul */
476 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
477 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
478 {COSTS_N_INSNS (33), COSTS_N_INSNS (65)}, /* int_div */
479 2, /* issue_rate */
480 4, /* branch_cost */
481 3, /* memory_cost */
482 8, /* fmv_cost */
483 true, /* slow_unaligned_access */
484 false, /* vector_unaligned_access */
485 false, /* use_divmod_expansion */
486 false, /* overlap_op_by_pieces */
487 RISCV_FUSE_NOTHING, /* fusible_ops */
488 NULL, /* vector cost */
489 NULL, /* function_align */
490 NULL, /* jump_align */
491 NULL, /* loop_align */
492 };
493
494 /* Costs to use when optimizing for Sifive p400 Series. */
495 static const struct riscv_tune_param sifive_p400_tune_info = {
496 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* fp_add */
497 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* fp_mul */
498 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
499 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
500 {COSTS_N_INSNS (6), COSTS_N_INSNS (6)}, /* int_div */
501 3, /* issue_rate */
502 4, /* branch_cost */
503 3, /* memory_cost */
504 4, /* fmv_cost */
505 true, /* slow_unaligned_access */
506 false, /* vector_unaligned_access */
507 false, /* use_divmod_expansion */
508 false, /* overlap_op_by_pieces */
509 RISCV_FUSE_LUI_ADDI | RISCV_FUSE_AUIPC_ADDI, /* fusible_ops */
510 &generic_vector_cost, /* vector cost */
511 NULL, /* function_align */
512 NULL, /* jump_align */
513 NULL, /* loop_align */
514 };
515
516 /* Costs to use when optimizing for Sifive p600 Series. */
517 static const struct riscv_tune_param sifive_p600_tune_info = {
518 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* fp_add */
519 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* fp_mul */
520 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
521 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
522 {COSTS_N_INSNS (6), COSTS_N_INSNS (6)}, /* int_div */
523 4, /* issue_rate */
524 4, /* branch_cost */
525 3, /* memory_cost */
526 4, /* fmv_cost */
527 true, /* slow_unaligned_access */
528 false, /* vector_unaligned_access */
529 false, /* use_divmod_expansion */
530 false, /* overlap_op_by_pieces */
531 RISCV_FUSE_LUI_ADDI | RISCV_FUSE_AUIPC_ADDI, /* fusible_ops */
532 &generic_vector_cost, /* vector cost */
533 NULL, /* function_align */
534 NULL, /* jump_align */
535 NULL, /* loop_align */
536 };
537
538 /* Costs to use when optimizing for T-HEAD c906. */
539 static const struct riscv_tune_param thead_c906_tune_info = {
540 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_add */
541 {COSTS_N_INSNS (4), COSTS_N_INSNS (5)}, /* fp_mul */
542 {COSTS_N_INSNS (20), COSTS_N_INSNS (20)}, /* fp_div */
543 {COSTS_N_INSNS (4), COSTS_N_INSNS (4)}, /* int_mul */
544 {COSTS_N_INSNS (18), COSTS_N_INSNS (34)}, /* int_div */
545 1, /* issue_rate */
546 3, /* branch_cost */
547 5, /* memory_cost */
548 8, /* fmv_cost */
549 false, /* slow_unaligned_access */
550 false, /* vector_unaligned_access */
551 false, /* use_divmod_expansion */
552 false, /* overlap_op_by_pieces */
553 RISCV_FUSE_NOTHING, /* fusible_ops */
554 NULL, /* vector cost */
555 NULL, /* function_align */
556 NULL, /* jump_align */
557 NULL, /* loop_align */
558 };
559
560 /* Costs to use when optimizing for xiangshan nanhu. */
561 static const struct riscv_tune_param xiangshan_nanhu_tune_info = {
562 {COSTS_N_INSNS (3), COSTS_N_INSNS (3)}, /* fp_add */
563 {COSTS_N_INSNS (3), COSTS_N_INSNS (3)}, /* fp_mul */
564 {COSTS_N_INSNS (10), COSTS_N_INSNS (20)}, /* fp_div */
565 {COSTS_N_INSNS (3), COSTS_N_INSNS (3)}, /* int_mul */
566 {COSTS_N_INSNS (6), COSTS_N_INSNS (6)}, /* int_div */
567 6, /* issue_rate */
568 3, /* branch_cost */
569 3, /* memory_cost */
570 3, /* fmv_cost */
571 true, /* slow_unaligned_access */
572 false, /* vector_unaligned_access */
573 false, /* use_divmod_expansion */
574 false, /* overlap_op_by_pieces */
575 RISCV_FUSE_ZEXTW | RISCV_FUSE_ZEXTH, /* fusible_ops */
576 NULL, /* vector cost */
577 NULL, /* function_align */
578 NULL, /* jump_align */
579 NULL, /* loop_align */
580 };
581
582 /* Costs to use when optimizing for a generic ooo profile. */
583 static const struct riscv_tune_param generic_ooo_tune_info = {
584 {COSTS_N_INSNS (2), COSTS_N_INSNS (2)}, /* fp_add */
585 {COSTS_N_INSNS (5), COSTS_N_INSNS (6)}, /* fp_mul */
586 {COSTS_N_INSNS (7), COSTS_N_INSNS (8)}, /* fp_div */
587 {COSTS_N_INSNS (2), COSTS_N_INSNS (2)}, /* int_mul */
588 {COSTS_N_INSNS (6), COSTS_N_INSNS (6)}, /* int_div */
589 1, /* issue_rate */
590 3, /* branch_cost */
591 4, /* memory_cost */
592 4, /* fmv_cost */
593 false, /* slow_unaligned_access */
594 true, /* vector_unaligned_access */
595 false, /* use_divmod_expansion */
596 true, /* overlap_op_by_pieces */
597 RISCV_FUSE_NOTHING, /* fusible_ops */
598 &generic_vector_cost, /* vector cost */
599 NULL, /* function_align */
600 NULL, /* jump_align */
601 NULL, /* loop_align */
602 };
603
604 /* Costs to use when optimizing for Tenstorrent Ascalon 8 wide. */
605 static const struct riscv_tune_param tt_ascalon_d8_tune_info = {
606 {COSTS_N_INSNS (2), COSTS_N_INSNS (2)}, /* fp_add */
607 {COSTS_N_INSNS (3), COSTS_N_INSNS (3)}, /* fp_mul */
608 {COSTS_N_INSNS (9), COSTS_N_INSNS (16)}, /* fp_div */
609 {COSTS_N_INSNS (3), COSTS_N_INSNS (3)}, /* int_mul */
610 {COSTS_N_INSNS (13), COSTS_N_INSNS (13)}, /* int_div */
611 8, /* issue_rate */
612 3, /* branch_cost */
613 4, /* memory_cost */
614 4, /* fmv_cost */
615 false, /* slow_unaligned_access */
616 true, /* vector_unaligned_access */
617 true, /* use_divmod_expansion */
618 true, /* overlap_op_by_pieces */
619 RISCV_FUSE_NOTHING, /* fusible_ops */
620 &generic_vector_cost, /* vector cost */
621 NULL, /* function_align */
622 NULL, /* jump_align */
623 NULL, /* loop_align */
624 };
625
626 /* Costs to use when optimizing for size. */
627 static const struct riscv_tune_param optimize_size_tune_info = {
628 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_add */
629 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_mul */
630 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* fp_div */
631 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* int_mul */
632 {COSTS_N_INSNS (1), COSTS_N_INSNS (1)}, /* int_div */
633 1, /* issue_rate */
634 1, /* branch_cost */
635 2, /* memory_cost */
636 8, /* fmv_cost */
637 false, /* slow_unaligned_access */
638 false, /* vector_unaligned_access */
639 false, /* use_divmod_expansion */
640 false, /* overlap_op_by_pieces */
641 RISCV_FUSE_NOTHING, /* fusible_ops */
642 NULL, /* vector cost */
643 NULL, /* function_align */
644 NULL, /* jump_align */
645 NULL, /* loop_align */
646 };
647
648 static bool riscv_avoid_shrink_wrapping_separate ();
649 static tree riscv_handle_fndecl_attribute (tree *, tree, tree, int, bool *);
650 static tree riscv_handle_type_attribute (tree *, tree, tree, int, bool *);
651 static tree riscv_handle_rvv_vector_bits_attribute (tree *, tree, tree, int,
652 bool *);
653
654 /* Defining target-specific uses of __attribute__. */
655 static const attribute_spec riscv_gnu_attributes[] =
656 {
657 /* Syntax: { name, min_len, max_len, decl_required, type_required,
658 function_type_required, affects_type_identity, handler,
659 exclude } */
660
661 /* The attribute telling no prologue/epilogue. */
662 {"naked", 0, 0, true, false, false, false, riscv_handle_fndecl_attribute,
663 NULL},
664 /* This attribute generates prologue/epilogue for interrupt handlers. */
665 {"interrupt", 0, 1, false, true, true, false, riscv_handle_type_attribute,
666 NULL},
667
668 /* The following two are used for the built-in properties of the Vector type
669 and are not used externally */
670 {"RVV sizeless type", 4, 4, false, true, false, true, NULL, NULL},
671 {"RVV type", 0, 0, false, true, false, true, NULL, NULL},
672 /* This attribute is used to declare a function, forcing it to use the
673 standard vector calling convention variant. Syntax:
674 __attribute__((riscv_vector_cc)). */
675 {"riscv_vector_cc", 0, 0, false, true, true, true, NULL, NULL},
676 /* This attribute is used to declare a new type, to appoint the exactly
677 bits size of the type. For example:
678
679 typedef vint8m1_t f_vint8m1_t __attribute__((riscv_rvv_vector_bits(256)));
680
681 The new created type f_vint8m1_t will be exactly 256 bits. It can be
682 be used in globals, structs, unions, and arrays instead of sizeless
683 types. */
684 {"riscv_rvv_vector_bits", 1, 1, false, true, false, true,
685 riscv_handle_rvv_vector_bits_attribute, NULL},
686 /* This attribute is used to declare a function, forcing it to use the
687 standard vector calling convention variant. Syntax:
688 __attribute__((norelax)). */
689 {"norelax", 0, 0, true, false, false, false, NULL, NULL},
690 };
691
692 static const scoped_attribute_specs riscv_gnu_attribute_table =
693 {
694 "gnu", {riscv_gnu_attributes}
695 };
696
697 static const attribute_spec riscv_attributes[] =
698 {
699 /* This attribute is used to declare a function, forcing it to use the
700 standard vector calling convention variant. Syntax:
701 [[riscv::vector_cc]]. */
702 {"vector_cc", 0, 0, false, true, true, true, NULL, NULL},
703 /* This attribute is used to declare a new type, to appoint the exactly
704 bits size of the type. For example:
705
706 typedef vint8m1_t f_vint8m1_t __attribute__((riscv_rvv_vector_bits(256)));
707
708 The new created type f_vint8m1_t will be exactly 256 bits. It can be
709 be used in globals, structs, unions, and arrays instead of sizeless
710 types. */
711 {"rvv_vector_bits", 1, 1, false, true, false, true,
712 riscv_handle_rvv_vector_bits_attribute, NULL},
713 };
714
715 static const scoped_attribute_specs riscv_nongnu_attribute_table =
716 {
717 "riscv", {riscv_attributes}
718 };
719
720 static const scoped_attribute_specs *const riscv_attribute_table[] =
721 {
722 &riscv_gnu_attribute_table,
723 &riscv_nongnu_attribute_table
724 };
725
726 /* Order for the CLOBBERs/USEs of gpr_save. */
727 static const unsigned gpr_save_reg_order[] = {
728 INVALID_REGNUM, T0_REGNUM, T1_REGNUM, RETURN_ADDR_REGNUM,
729 S0_REGNUM, S1_REGNUM, S2_REGNUM, S3_REGNUM, S4_REGNUM,
730 S5_REGNUM, S6_REGNUM, S7_REGNUM, S8_REGNUM, S9_REGNUM,
731 S10_REGNUM, S11_REGNUM
732 };
733
734 /* Order for the (ra, s0-sx) of zcmp_save. */
735 static const unsigned zcmp_save_reg_order[]
736 = {RETURN_ADDR_REGNUM, S0_REGNUM, S1_REGNUM, S2_REGNUM, S3_REGNUM,
737 S4_REGNUM, S5_REGNUM, S6_REGNUM, S7_REGNUM, S8_REGNUM,
738 S9_REGNUM, S10_REGNUM, S11_REGNUM, INVALID_REGNUM};
739
740 /* A table describing all the processors GCC knows about. */
741 static const struct riscv_tune_info riscv_tune_info_table[] = {
742 #define RISCV_TUNE(TUNE_NAME, PIPELINE_MODEL, TUNE_INFO) \
743 { TUNE_NAME, PIPELINE_MODEL, & TUNE_INFO},
744 #include "riscv-cores.def"
745 };
746
747 /* Global variable to distinguish whether we should save and restore s0/fp for
748 function. */
749 static bool riscv_save_frame_pointer;
750
751 typedef enum
752 {
753 PUSH_IDX = 0,
754 POP_IDX,
755 POPRET_IDX,
756 POPRETZ_IDX,
757 ZCMP_OP_NUM
758 } riscv_zcmp_op_t;
759
760 typedef insn_code (*code_for_push_pop_t) (machine_mode);
761
762 void riscv_frame_info::reset(void)
763 {
764 total_size = 0;
765 mask = 0;
766 fmask = 0;
767 vmask = 0;
768 save_libcall_adjustment = 0;
769
770 gp_sp_offset = 0;
771 fp_sp_offset = 0;
772 v_sp_offset_top = 0;
773 v_sp_offset_bottom = 0;
774
775 frame_pointer_offset = 0;
776
777 hard_frame_pointer_offset = 0;
778
779 arg_pointer_offset = 0;
780 }
781
782 /* Implement TARGET_MIN_ARITHMETIC_PRECISION. */
783
784 static unsigned int
785 riscv_min_arithmetic_precision (void)
786 {
787 return 32;
788 }
789
790 /* Get the arch string from an options object. */
791
792 template <class T>
793 static const char *
794 get_arch_str (const T *opts)
795 {
796 return opts->x_riscv_arch_string;
797 }
798
799 template <class T>
800 static const char *
801 get_tune_str (const T *opts)
802 {
803 const char *tune_string = RISCV_TUNE_STRING_DEFAULT;
804 if (opts->x_riscv_tune_string)
805 tune_string = opts->x_riscv_tune_string;
806 else if (opts->x_riscv_cpu_string)
807 tune_string = opts->x_riscv_cpu_string;
808 return tune_string;
809 }
810
811 /* Return the riscv_tune_info entry for the given name string, return nullptr
812 if NULL_P is true, otherwise return an placeholder and report error. */
813
814 const struct riscv_tune_info *
815 riscv_parse_tune (const char *tune_string, bool null_p)
816 {
817 const riscv_cpu_info *cpu = riscv_find_cpu (tune_string);
818
819 if (cpu)
820 tune_string = cpu->tune;
821
822 for (unsigned i = 0; i < ARRAY_SIZE (riscv_tune_info_table); i++)
823 if (strcmp (riscv_tune_info_table[i].name, tune_string) == 0)
824 return riscv_tune_info_table + i;
825
826 if (null_p)
827 return nullptr;
828
829 error ("unknown cpu %qs for %<-mtune%>", tune_string);
830 return riscv_tune_info_table;
831 }
832
833 /* Helper function for riscv_build_integer; arguments are as for
834 riscv_build_integer. */
835
836 static int
837 riscv_build_integer_1 (struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS],
838 HOST_WIDE_INT value, machine_mode mode)
839 {
840 HOST_WIDE_INT low_part = CONST_LOW_PART (value);
841 int cost = RISCV_MAX_INTEGER_OPS + 1, alt_cost;
842 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
843 int upper_trailing_ones = ctz_hwi (~value >> 32);
844 int lower_leading_ones = clz_hwi (~value << 32);
845
846
847 if (SMALL_OPERAND (value) || LUI_OPERAND (value))
848 {
849 /* Simply ADDI or LUI. */
850 codes[0].code = UNKNOWN;
851 codes[0].value = value;
852 codes[0].use_uw = false;
853 codes[0].save_temporary = false;
854 return 1;
855 }
856 if (TARGET_ZBS && SINGLE_BIT_MASK_OPERAND (value))
857 {
858 /* Simply BSETI. */
859 codes[0].code = UNKNOWN;
860 codes[0].value = value;
861 codes[0].use_uw = false;
862 codes[0].save_temporary = false;
863
864 /* RISC-V sign-extends all 32bit values that live in a 32bit
865 register. To avoid paradoxes, we thus need to use the
866 sign-extended (negative) representation (-1 << 31) for the
867 value, if we want to build (1 << 31) in SImode. This will
868 then expand to an LUI instruction. */
869 if (TARGET_64BIT && mode == SImode && value == (HOST_WIDE_INT_1U << 31))
870 codes[0].value = (HOST_WIDE_INT_M1U << 31);
871
872 return 1;
873 }
874
875 /* End with ADDI. When constructing HImode constants, do not generate any
876 intermediate value that is not itself a valid HImode constant. The
877 XORI case below will handle those remaining HImode constants. */
878 if (low_part != 0
879 && (mode != HImode
880 || value - low_part <= ((1 << (GET_MODE_BITSIZE (HImode) - 1)) - 1)))
881 {
882 HOST_WIDE_INT upper_part = value - low_part;
883 if (mode != VOIDmode)
884 upper_part = trunc_int_for_mode (value - low_part, mode);
885
886 alt_cost = 1 + riscv_build_integer_1 (alt_codes, upper_part, mode);
887 if (alt_cost < cost)
888 {
889 alt_codes[alt_cost-1].code = PLUS;
890 alt_codes[alt_cost-1].value = low_part;
891 alt_codes[alt_cost-1].use_uw = false;
892 alt_codes[alt_cost-1].save_temporary = false;
893 memcpy (codes, alt_codes, sizeof (alt_codes));
894 cost = alt_cost;
895 }
896 }
897
898 /* End with XORI. */
899 if (cost > 2 && (low_part < 0 || mode == HImode))
900 {
901 alt_cost = 1 + riscv_build_integer_1 (alt_codes, value ^ low_part, mode);
902 if (alt_cost < cost)
903 {
904 alt_codes[alt_cost-1].code = XOR;
905 alt_codes[alt_cost-1].value = low_part;
906 alt_codes[alt_cost-1].use_uw = false;
907 alt_codes[alt_cost-1].save_temporary = false;
908 memcpy (codes, alt_codes, sizeof (alt_codes));
909 cost = alt_cost;
910 }
911 }
912
913 /* Eliminate trailing zeros and end with SLLI. */
914 if (cost > 2 && (value & 1) == 0)
915 {
916 int shift = ctz_hwi (value);
917 unsigned HOST_WIDE_INT x = value;
918 bool use_uw = false;
919 x = sext_hwi (x >> shift, HOST_BITS_PER_WIDE_INT - shift);
920
921 /* Don't eliminate the lower 12 bits if LUI might apply. */
922 if (shift > IMM_BITS
923 && !SMALL_OPERAND (x)
924 && (LUI_OPERAND (x << IMM_BITS)
925 || (TARGET_64BIT
926 && TARGET_ZBA
927 && LUI_OPERAND ((x << IMM_BITS)
928 & ~HOST_WIDE_INT_C (0x80000000)))))
929 shift -= IMM_BITS, x <<= IMM_BITS;
930
931 /* If X has bits 32..63 clear and bit 31 set, then go ahead and mark
932 it as desiring a "uw" operation for the shift. That way we can have
933 LUI+ADDI to generate the constant, then shift it into position
934 clearing out the undesirable bits. */
935 if (!LUI_OPERAND (x)
936 && TARGET_64BIT
937 && TARGET_ZBA
938 && clz_hwi (x) == 32)
939 {
940 x = sext_hwi (x, 32);
941 use_uw = true;
942 }
943
944 alt_cost = 1 + riscv_build_integer_1 (alt_codes, x, mode);
945 if (alt_cost < cost)
946 {
947 alt_codes[alt_cost-1].code = ASHIFT;
948 alt_codes[alt_cost-1].value = shift;
949 alt_codes[alt_cost-1].use_uw = use_uw;
950 alt_codes[alt_cost-1].save_temporary = false;
951 memcpy (codes, alt_codes, sizeof (alt_codes));
952 cost = alt_cost;
953 }
954 }
955
956 if (cost > 2 && TARGET_64BIT && (TARGET_ZBB || TARGET_XTHEADBB))
957 {
958 int leading_ones = clz_hwi (~value);
959 int trailing_ones = ctz_hwi (~value);
960
961 /* If all bits are one except a few that are zero, and the zero bits
962 are within a range of 11 bits, then we can synthesize a constant
963 by loading a small negative constant and rotating. */
964 if (leading_ones < 64
965 && ((64 - leading_ones - trailing_ones) < 12))
966 {
967 codes[0].code = UNKNOWN;
968 /* The sign-bit might be zero, so just rotate to be safe. */
969 codes[0].value = (((unsigned HOST_WIDE_INT) value >> trailing_ones)
970 | (value << (64 - trailing_ones)));
971 codes[0].use_uw = false;
972 codes[0].save_temporary = false;
973 codes[1].code = ROTATERT;
974 codes[1].value = 64 - trailing_ones;
975 codes[1].use_uw = false;
976 codes[1].save_temporary = false;
977 cost = 2;
978 }
979 /* Handle the case where the 11 bit range of zero bits wraps around. */
980 else if (upper_trailing_ones < 32 && lower_leading_ones < 32
981 && ((64 - upper_trailing_ones - lower_leading_ones) < 12))
982 {
983 codes[0].code = UNKNOWN;
984 /* The sign-bit might be zero, so just rotate to be safe. */
985 codes[0].value = ((value << (32 - upper_trailing_ones))
986 | ((unsigned HOST_WIDE_INT) value
987 >> (32 + upper_trailing_ones)));
988 codes[0].use_uw = false;
989 codes[0].save_temporary = false;
990 codes[1].code = ROTATERT;
991 codes[1].value = 32 - upper_trailing_ones;
992 codes[1].use_uw = false;
993 codes[1].save_temporary = false;
994 cost = 2;
995 }
996
997 /* If LUI/ADDI are going to set bits 32..63 and we need a small
998 number of them cleared, we might be able to use bclri profitably.
999
1000 Note we may allow clearing of bit 31 using bclri. There's a class
1001 of constants with that bit clear where this helps. */
1002 else if (TARGET_64BIT
1003 && TARGET_ZBS
1004 && (32 - popcount_hwi (value & HOST_WIDE_INT_C (0xffffffff80000000))) + 1 < cost)
1005 {
1006 /* Turn on all those upper bits and synthesize the result. */
1007 HOST_WIDE_INT nval = value | HOST_WIDE_INT_C (0xffffffff80000000);
1008 alt_cost = riscv_build_integer_1 (alt_codes, nval, mode);
1009
1010 /* Now iterate over the bits we want to clear until the cost is
1011 too high or we're done. */
1012 nval = value ^ HOST_WIDE_INT_C (-1);
1013 nval &= ~HOST_WIDE_INT_C (0x7fffffff);
1014 while (nval && alt_cost < cost)
1015 {
1016 HOST_WIDE_INT bit = ctz_hwi (nval);
1017 alt_codes[alt_cost].code = AND;
1018 alt_codes[alt_cost].value = ~(HOST_WIDE_INT_UC (1) << bit);
1019 alt_codes[alt_cost].use_uw = false;
1020 alt_codes[alt_cost].save_temporary = false;
1021 alt_cost++;
1022 nval &= ~(HOST_WIDE_INT_UC (1) << bit);
1023 }
1024
1025 if (nval == 0 && alt_cost <= cost)
1026 {
1027 memcpy (codes, alt_codes, sizeof (alt_codes));
1028 cost = alt_cost;
1029 }
1030 }
1031 }
1032
1033 if (cost > 2 && TARGET_64BIT && TARGET_ZBA)
1034 {
1035 if ((value % 9) == 0
1036 && (alt_cost
1037 = riscv_build_integer_1 (alt_codes, value / 9, mode) + 1) < cost)
1038 {
1039 alt_codes[alt_cost - 1].code = FMA;
1040 alt_codes[alt_cost - 1].value = 9;
1041 alt_codes[alt_cost - 1].use_uw = false;
1042 alt_codes[alt_cost - 1].save_temporary = false;
1043 memcpy (codes, alt_codes, sizeof (alt_codes));
1044 cost = alt_cost;
1045 }
1046 if ((value % 5) == 0
1047 && (alt_cost
1048 = riscv_build_integer_1 (alt_codes, value / 5, mode) + 1) < cost)
1049 {
1050 alt_codes[alt_cost - 1].code = FMA;
1051 alt_codes[alt_cost - 1].value = 5;
1052 alt_codes[alt_cost - 1].use_uw = false;
1053 alt_codes[alt_cost - 1].save_temporary = false;
1054 memcpy (codes, alt_codes, sizeof (alt_codes));
1055 cost = alt_cost;
1056 }
1057 if ((value % 3) == 0
1058 && (alt_cost
1059 = riscv_build_integer_1 (alt_codes, value / 3, mode) + 1) < cost)
1060 {
1061 alt_codes[alt_cost - 1].code = FMA;
1062 alt_codes[alt_cost - 1].value = 3;
1063 alt_codes[alt_cost - 1].use_uw = false;
1064 alt_codes[alt_cost - 1].save_temporary = false;
1065 memcpy (codes, alt_codes, sizeof (alt_codes));
1066 cost = alt_cost;
1067 }
1068 }
1069
1070 /* We might be able to generate a constant close to our target
1071 then a final ADDI to get the desired constant. */
1072 if (cost > 2
1073 && (value & 0xfff) != 0
1074 && (value & 0x1800) == 0x1000)
1075 {
1076 HOST_WIDE_INT adjustment = -(0x800 - (value & 0xfff));
1077 alt_cost = 1 + riscv_build_integer_1 (alt_codes,
1078 value - adjustment, mode);
1079
1080 if (alt_cost < cost)
1081 {
1082 alt_codes[alt_cost - 1].code = PLUS;
1083 alt_codes[alt_cost - 1].value = adjustment;
1084 alt_codes[alt_cost - 1].use_uw = false;
1085 alt_codes[alt_cost - 1].save_temporary = false;
1086 memcpy (codes, alt_codes, sizeof (alt_codes));
1087 cost = alt_cost;
1088 }
1089 }
1090
1091 /* Final cases, particularly focused on bseti. */
1092 if (cost > 2 && TARGET_ZBS)
1093 {
1094 int i = 0;
1095
1096 /* First handle any bits set by LUI. Be careful of the
1097 SImode sign bit!. */
1098 if (value & 0x7ffff000)
1099 {
1100 alt_codes[i].code = (i == 0 ? UNKNOWN : IOR);
1101 alt_codes[i].value = value & 0x7ffff000;
1102 alt_codes[i].use_uw = false;
1103 alt_codes[i].save_temporary = false;
1104 value &= ~0x7ffff000;
1105 i++;
1106 }
1107
1108 /* Next, any bits we can handle with addi. */
1109 if (value & 0x7ff)
1110 {
1111 alt_codes[i].code = (i == 0 ? UNKNOWN : PLUS);
1112 alt_codes[i].value = value & 0x7ff;
1113 alt_codes[i].use_uw = false;
1114 alt_codes[i].save_temporary = false;
1115 value &= ~0x7ff;
1116 i++;
1117 }
1118
1119 /* And any residuals with bseti. */
1120 while (i < cost && value)
1121 {
1122 HOST_WIDE_INT bit = ctz_hwi (value);
1123 alt_codes[i].code = (i == 0 ? UNKNOWN : IOR);
1124 alt_codes[i].value = HOST_WIDE_INT_1U << bit;
1125 alt_codes[i].use_uw = false;
1126 alt_codes[i].save_temporary = false;
1127 value &= ~(HOST_WIDE_INT_1U << bit);
1128 i++;
1129 }
1130
1131 /* If LUI+ADDI+BSETI resulted in a more efficient
1132 sequence, then use it. */
1133 if (value == 0 && i < cost)
1134 {
1135 memcpy (codes, alt_codes, sizeof (alt_codes));
1136 cost = i;
1137 }
1138 }
1139
1140 gcc_assert (cost <= RISCV_MAX_INTEGER_OPS);
1141 return cost;
1142 }
1143
1144 /* Fill CODES with a sequence of rtl operations to load VALUE.
1145 Return the number of operations needed.
1146
1147 ALLOW_NEW_PSEUDOS indicates if or caller wants to allow new pseudo
1148 registers or not. This is needed for cases where the integer synthesis and
1149 costing code are used in insn conditions, we can't have costing allow
1150 recognition at some points and reject at others. */
1151
1152 static int
1153 riscv_build_integer (struct riscv_integer_op *codes, HOST_WIDE_INT value,
1154 machine_mode mode, bool allow_new_pseudos)
1155 {
1156 int cost = riscv_build_integer_1 (codes, value, mode);
1157
1158 /* Eliminate leading zeros and end with SRLI. */
1159 if (value > 0 && cost > 2)
1160 {
1161 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
1162 int alt_cost, shift = clz_hwi (value);
1163 HOST_WIDE_INT shifted_val;
1164
1165 /* Try filling trailing bits with 1s. */
1166 shifted_val = (value << shift) | ((((HOST_WIDE_INT) 1) << shift) - 1);
1167 alt_cost = 1 + riscv_build_integer_1 (alt_codes, shifted_val, mode);
1168 if (alt_cost < cost)
1169 {
1170 alt_codes[alt_cost-1].code = LSHIFTRT;
1171 alt_codes[alt_cost-1].value = shift;
1172 alt_codes[alt_cost-1].use_uw = false;
1173 alt_codes[alt_cost-1].save_temporary = false;
1174 memcpy (codes, alt_codes, sizeof (alt_codes));
1175 cost = alt_cost;
1176 }
1177
1178 /* Try filling trailing bits with 0s. */
1179 shifted_val = value << shift;
1180 alt_cost = 1 + riscv_build_integer_1 (alt_codes, shifted_val, mode);
1181 if (alt_cost < cost)
1182 {
1183 alt_codes[alt_cost-1].code = LSHIFTRT;
1184 alt_codes[alt_cost-1].value = shift;
1185 alt_codes[alt_cost-1].use_uw = false;
1186 alt_codes[alt_cost-1].save_temporary = false;
1187 memcpy (codes, alt_codes, sizeof (alt_codes));
1188 cost = alt_cost;
1189 }
1190 }
1191
1192 /* See if we can generate the inverted constant, then use
1193 not to get the desired constant.
1194
1195 This can't be in riscv_build_integer_1 as it'll mutually
1196 recurse with another case in there. And it has to recurse
1197 into riscv_build_integer so we get the trailing 0s case
1198 above. */
1199 if (cost > 2 && value < 0)
1200 {
1201 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
1202 int alt_cost;
1203
1204 HOST_WIDE_INT nval = ~value;
1205 alt_cost = 1 + riscv_build_integer (alt_codes, nval,
1206 mode, allow_new_pseudos);
1207 if (alt_cost < cost)
1208 {
1209 alt_codes[alt_cost - 1].code = XOR;
1210 alt_codes[alt_cost - 1].value = -1;
1211 alt_codes[alt_cost - 1].use_uw = false;
1212 alt_codes[alt_cost - 1].save_temporary = false;
1213 memcpy (codes, alt_codes, sizeof (alt_codes));
1214 cost = alt_cost;
1215 }
1216 }
1217
1218
1219 if (!TARGET_64BIT
1220 && (value > INT32_MAX || value < INT32_MIN))
1221 {
1222 unsigned HOST_WIDE_INT loval = sext_hwi (value, 32);
1223 unsigned HOST_WIDE_INT hival = sext_hwi ((value - loval) >> 32, 32);
1224 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
1225 struct riscv_integer_op hicode[RISCV_MAX_INTEGER_OPS];
1226 int hi_cost, lo_cost;
1227
1228 hi_cost = riscv_build_integer_1 (hicode, hival, mode);
1229 if (hi_cost < cost)
1230 {
1231 lo_cost = riscv_build_integer_1 (alt_codes, loval, mode);
1232 if (lo_cost + hi_cost < cost)
1233 {
1234 memcpy (codes, alt_codes,
1235 lo_cost * sizeof (struct riscv_integer_op));
1236 memcpy (codes + lo_cost, hicode,
1237 hi_cost * sizeof (struct riscv_integer_op));
1238 cost = lo_cost + hi_cost;
1239 }
1240 }
1241 }
1242
1243 /* With pack we can generate a 64 bit constant with the same high
1244 and low 32 bits trivially. */
1245 if (cost > 3 && TARGET_64BIT && TARGET_ZBKB)
1246 {
1247 unsigned HOST_WIDE_INT loval = value & 0xffffffff;
1248 unsigned HOST_WIDE_INT hival = (value & ~loval) >> 32;
1249 if (hival == loval)
1250 {
1251 cost = 1 + riscv_build_integer_1 (codes, sext_hwi (loval, 32), mode);
1252 codes[cost - 1].code = CONCAT;
1253 codes[cost - 1].value = 0;
1254 codes[cost - 1].use_uw = false;
1255 codes[cost - 1].save_temporary = false;
1256 }
1257
1258 /* An arbitrary 64 bit constant can be synthesized in 5 instructions
1259 using zbkb. We may do better than that if the upper or lower half
1260 can be synthesized with a single LUI, ADDI or BSET. Regardless the
1261 basic steps are the same. */
1262 if (cost > 3 && can_create_pseudo_p () && allow_new_pseudos)
1263 {
1264 struct riscv_integer_op hi_codes[RISCV_MAX_INTEGER_OPS];
1265 struct riscv_integer_op lo_codes[RISCV_MAX_INTEGER_OPS];
1266 int hi_cost, lo_cost;
1267
1268 /* Synthesize and get cost for each half. */
1269 lo_cost
1270 = riscv_build_integer_1 (lo_codes, sext_hwi (loval, 32), mode);
1271 hi_cost
1272 = riscv_build_integer_1 (hi_codes, sext_hwi (hival, 32), mode);
1273
1274 /* If profitable, finish synthesis using zbkb. */
1275 if (cost > hi_cost + lo_cost + 1)
1276 {
1277 /* We need the low half independent of the high half. So
1278 mark it has creating a temporary we'll use later. */
1279 memcpy (codes, lo_codes,
1280 lo_cost * sizeof (struct riscv_integer_op));
1281 codes[lo_cost - 1].save_temporary = true;
1282
1283 /* Now the high half synthesis. */
1284 memcpy (codes + lo_cost, hi_codes,
1285 hi_cost * sizeof (struct riscv_integer_op));
1286
1287 /* Adjust the cost. */
1288 cost = hi_cost + lo_cost + 1;
1289
1290 /* And finally (ab)use VEC_MERGE to indicate we want to
1291 put merge the two parts together. */
1292 codes[cost - 1].code = VEC_MERGE;
1293 codes[cost - 1].value = 0;
1294 codes[cost - 1].use_uw = false;
1295 codes[cost - 1].save_temporary = false;
1296 }
1297 }
1298
1299 }
1300 else if (cost > 4 && TARGET_64BIT && can_create_pseudo_p ()
1301 && allow_new_pseudos)
1302 {
1303 struct riscv_integer_op alt_codes[RISCV_MAX_INTEGER_OPS];
1304 int alt_cost;
1305
1306 unsigned HOST_WIDE_INT loval = value & 0xffffffff;
1307 unsigned HOST_WIDE_INT hival = (value & ~loval) >> 32;
1308 bool bit31 = (loval & 0x80000000) != 0;
1309 int trailing_shift = ctz_hwi (loval) - ctz_hwi (hival);
1310 int leading_shift = clz_hwi (loval) - clz_hwi (hival);
1311 int shiftval = 0;
1312
1313 /* Adjust the shift into the high half accordingly. */
1314 if ((trailing_shift > 0 && hival == (loval >> trailing_shift)))
1315 shiftval = 32 - trailing_shift;
1316 else if ((leading_shift > 0 && hival == (loval << leading_shift)))
1317 shiftval = 32 + leading_shift;
1318
1319 if (shiftval && !bit31)
1320 alt_cost = 2 + riscv_build_integer_1 (alt_codes, sext_hwi (loval, 32),
1321 mode);
1322
1323 /* For constants where the upper half is a shift of the lower half we
1324 can do a shift followed by an or. */
1325 if (shiftval && !bit31 && alt_cost < cost)
1326 {
1327 /* We need to save the first constant we build. */
1328 alt_codes[alt_cost - 3].save_temporary = true;
1329
1330 /* Now we want to shift the previously generated constant into the
1331 high half. */
1332 alt_codes[alt_cost - 2].code = ASHIFT;
1333 alt_codes[alt_cost - 2].value = shiftval;
1334 alt_codes[alt_cost - 2].use_uw = false;
1335 alt_codes[alt_cost - 2].save_temporary = false;
1336
1337 /* And the final step, IOR the two halves together. Since this uses
1338 the saved temporary, use CONCAT similar to what we do for Zbkb. */
1339 alt_codes[alt_cost - 1].code = CONCAT;
1340 alt_codes[alt_cost - 1].value = 0;
1341 alt_codes[alt_cost - 1].use_uw = false;
1342 alt_codes[alt_cost - 1].save_temporary = false;
1343
1344 memcpy (codes, alt_codes, sizeof (alt_codes));
1345 cost = alt_cost;
1346 }
1347
1348 /* If bit31 is on and the upper constant is one less than the lower
1349 constant, then we can exploit sign extending nature of the lower
1350 half to trivially generate the upper half with an ADD.
1351
1352 Not appropriate for ZBKB since that won't use "add"
1353 at codegen time. */
1354 if (!TARGET_ZBKB
1355 && cost > 4
1356 && bit31
1357 && hival == loval - 1)
1358 {
1359 alt_cost = 2 + riscv_build_integer_1 (alt_codes,
1360 sext_hwi (loval, 32), mode);
1361 alt_codes[alt_cost - 3].save_temporary = true;
1362 alt_codes[alt_cost - 2].code = ASHIFT;
1363 alt_codes[alt_cost - 2].value = 32;
1364 alt_codes[alt_cost - 2].use_uw = false;
1365 alt_codes[alt_cost - 2].save_temporary = false;
1366 /* This will turn into an ADD. */
1367 alt_codes[alt_cost - 1].code = CONCAT;
1368 alt_codes[alt_cost - 1].value = 32;
1369 alt_codes[alt_cost - 1].use_uw = false;
1370 alt_codes[alt_cost - 1].save_temporary = false;
1371
1372 memcpy (codes, alt_codes, sizeof (alt_codes));
1373 cost = alt_cost;
1374 }
1375
1376 if (cost > 4 && !bit31 && TARGET_ZBA)
1377 {
1378 int value = 0;
1379
1380 /* Check for a shNadd. */
1381 if (hival == loval * 3)
1382 value = 3;
1383 else if (hival == loval * 5)
1384 value = 5;
1385 else if (hival == loval * 9)
1386 value = 9;
1387
1388 if (value)
1389 alt_cost = 3 + riscv_build_integer_1 (alt_codes,
1390 sext_hwi (loval, 32), mode);
1391
1392 /* For constants where the upper half is a shNadd of the lower half
1393 we can do a similar transformation. */
1394 if (value && alt_cost < cost)
1395 {
1396 alt_codes[alt_cost - 4].save_temporary = true;
1397 alt_codes[alt_cost - 3].code = FMA;
1398 alt_codes[alt_cost - 3].value = value;
1399 alt_codes[alt_cost - 3].use_uw = false;
1400 alt_codes[alt_cost - 3].save_temporary = false;
1401 alt_codes[alt_cost - 2].code = ASHIFT;
1402 alt_codes[alt_cost - 2].value = 32;
1403 alt_codes[alt_cost - 2].use_uw = false;
1404 alt_codes[alt_cost - 2].save_temporary = false;
1405 alt_codes[alt_cost - 1].code = CONCAT;
1406 alt_codes[alt_cost - 1].value = 0;
1407 alt_codes[alt_cost - 1].use_uw = false;
1408 alt_codes[alt_cost - 1].save_temporary = false;
1409
1410 memcpy (codes, alt_codes, sizeof (alt_codes));
1411 cost = alt_cost;
1412 }
1413 }
1414
1415 if (cost > 4 && !bit31)
1416 {
1417 int value = hival - loval;
1418
1419 /* For constants were the halves differ by less than 2048 we can
1420 generate the upper half by using an addi on the lower half then
1421 using a shift 32 followed by an or. */
1422 if (IN_RANGE (value, -2048, 2047))
1423 {
1424 alt_cost = 3 + riscv_build_integer_1 (alt_codes,
1425 sext_hwi (loval, 32), mode);
1426 if (alt_cost < cost)
1427 {
1428 alt_codes[alt_cost - 4].save_temporary = true;
1429 alt_codes[alt_cost - 3].code = PLUS;
1430 alt_codes[alt_cost - 3].value = value;
1431 alt_codes[alt_cost - 3].use_uw = false;
1432 alt_codes[alt_cost - 3].save_temporary = false;
1433 alt_codes[alt_cost - 2].code = ASHIFT;
1434 alt_codes[alt_cost - 2].value = 32;
1435 alt_codes[alt_cost - 2].use_uw = false;
1436 alt_codes[alt_cost - 2].save_temporary = false;
1437 alt_codes[alt_cost - 1].code = CONCAT;
1438 alt_codes[alt_cost - 1].value = 0;
1439 alt_codes[alt_cost - 1].use_uw = false;
1440 alt_codes[alt_cost - 1].save_temporary = false;
1441
1442 memcpy (codes, alt_codes, sizeof (alt_codes));
1443 cost = alt_cost;
1444 }
1445 }
1446 }
1447
1448 if (cost > 5 && !bit31)
1449 {
1450 /* For constants where the upper half is the lower half inverted we can flip
1451 it with an xor and do a shift 32 followed by an or. */
1452 if (hival == (~loval & 0xffffffff))
1453 {
1454 alt_cost = 3 + riscv_build_integer_1 (alt_codes,
1455 sext_hwi (loval, 32), mode);
1456 if (alt_cost < cost)
1457 {
1458 alt_codes[alt_cost - 4].save_temporary = true;
1459 alt_codes[alt_cost - 3].code = XOR;
1460 alt_codes[alt_cost - 3].value = -1;
1461 alt_codes[alt_cost - 3].use_uw = false;
1462 alt_codes[alt_cost - 3].save_temporary = false;
1463 alt_codes[alt_cost - 2].code = ASHIFT;
1464 alt_codes[alt_cost - 2].value = 32;
1465 alt_codes[alt_cost - 2].use_uw = false;
1466 alt_codes[alt_cost - 2].save_temporary = false;
1467 alt_codes[alt_cost - 1].code = CONCAT;
1468 alt_codes[alt_cost - 1].value = 0;
1469 alt_codes[alt_cost - 1].use_uw = false;
1470 alt_codes[alt_cost - 1].save_temporary = false;
1471
1472 memcpy (codes, alt_codes, sizeof (alt_codes));
1473 cost = alt_cost;
1474 }
1475 }
1476 }
1477 }
1478
1479 return cost;
1480 }
1481
1482 /* Return the cost of constructing VAL in the event that a scratch
1483 register is available. */
1484
1485 static int
1486 riscv_split_integer_cost (HOST_WIDE_INT val)
1487 {
1488 int cost;
1489 unsigned HOST_WIDE_INT loval = val & 0xffffffff;
1490 unsigned HOST_WIDE_INT hival = (val & ~loval) >> 32;
1491 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
1492
1493 /* This routine isn't used by pattern conditions, so whether or
1494 not to allow new pseudos can be a function of where we are in the
1495 RTL pipeline. */
1496 bool allow_new_pseudos = can_create_pseudo_p ();
1497 cost = 2 + riscv_build_integer (codes, loval, VOIDmode, allow_new_pseudos);
1498 if (loval != hival)
1499 cost += riscv_build_integer (codes, hival, VOIDmode, allow_new_pseudos);
1500 else if ((loval & 0x80000000) != 0)
1501 cost = 3 + riscv_build_integer (codes, ~loval & 0xffffffff,
1502 VOIDmode, allow_new_pseudos);
1503
1504 return cost;
1505 }
1506
1507 /* Return the cost of constructing the integer constant VAL. ALLOW_NEW_PSEUDOS
1508 potentially restricts if riscv_build_integer is allowed to create new
1509 pseudo registers. It must be false for calls directly or indirectly from
1510 conditions in patterns. */
1511
1512 static int
1513 riscv_integer_cost (HOST_WIDE_INT val, bool allow_new_pseudos)
1514 {
1515 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
1516 return MIN (riscv_build_integer (codes, val, VOIDmode, allow_new_pseudos),
1517 riscv_split_integer_cost (val));
1518 }
1519
1520 /* Try to split a 64b integer into 32b parts, then reassemble. */
1521
1522 static rtx
1523 riscv_split_integer (HOST_WIDE_INT val, machine_mode mode)
1524 {
1525 unsigned HOST_WIDE_INT loval = val & 0xffffffff;
1526 unsigned HOST_WIDE_INT hival = (val & ~loval) >> 32;
1527 rtx hi = gen_reg_rtx (mode), lo = gen_reg_rtx (mode);
1528 rtx x = gen_reg_rtx (mode);
1529 bool eq_neg = (loval == hival) && ((loval & 0x80000000) != 0);
1530
1531 if (eq_neg)
1532 riscv_move_integer (lo, lo, ~loval & 0xffffffff, mode);
1533 else
1534 riscv_move_integer (lo, lo, loval, mode);
1535
1536 if (loval == hival)
1537 hi = gen_rtx_ASHIFT (mode, lo, GEN_INT (32));
1538 else
1539 {
1540 riscv_move_integer (hi, hi, hival, mode);
1541 hi = gen_rtx_ASHIFT (mode, hi, GEN_INT (32));
1542 }
1543
1544 hi = force_reg (mode, hi);
1545 x = gen_rtx_PLUS (mode, hi, lo);
1546 if (eq_neg)
1547 {
1548 x = force_reg (mode, x);
1549 x = gen_rtx_XOR (mode, x, GEN_INT (-1));
1550 }
1551 return x;
1552 }
1553
1554 /* Return true if X is a thread-local symbol. */
1555
1556 static bool
1557 riscv_tls_symbol_p (const_rtx x)
1558 {
1559 return SYMBOL_REF_P (x) && SYMBOL_REF_TLS_MODEL (x) != 0;
1560 }
1561
1562 /* Return true if symbol X binds locally. */
1563
1564 static bool
1565 riscv_symbol_binds_local_p (const_rtx x)
1566 {
1567 if (SYMBOL_REF_P (x))
1568 return (SYMBOL_REF_DECL (x)
1569 ? targetm.binds_local_p (SYMBOL_REF_DECL (x))
1570 : SYMBOL_REF_LOCAL_P (x));
1571 else
1572 return false;
1573 }
1574
1575 /* Return the method that should be used to access SYMBOL_REF or
1576 LABEL_REF X. */
1577
1578 static enum riscv_symbol_type
1579 riscv_classify_symbol (const_rtx x)
1580 {
1581 if (riscv_tls_symbol_p (x))
1582 return SYMBOL_TLS;
1583
1584 if (GET_CODE (x) == SYMBOL_REF && flag_pic && !riscv_symbol_binds_local_p (x))
1585 return SYMBOL_GOT_DISP;
1586
1587 switch (riscv_cmodel)
1588 {
1589 case CM_MEDLOW:
1590 return SYMBOL_ABSOLUTE;
1591 case CM_LARGE:
1592 if (SYMBOL_REF_P (x))
1593 return CONSTANT_POOL_ADDRESS_P (x) ? SYMBOL_PCREL : SYMBOL_FORCE_TO_MEM;
1594 return SYMBOL_PCREL;
1595 default:
1596 return SYMBOL_PCREL;
1597 }
1598 }
1599
1600 /* Classify the base of symbolic expression X. */
1601
1602 enum riscv_symbol_type
1603 riscv_classify_symbolic_expression (rtx x)
1604 {
1605 rtx offset;
1606
1607 split_const (x, &x, &offset);
1608 if (UNSPEC_ADDRESS_P (x))
1609 return UNSPEC_ADDRESS_TYPE (x);
1610
1611 return riscv_classify_symbol (x);
1612 }
1613
1614 /* Return true if X is a symbolic constant. If it is, store the type of
1615 the symbol in *SYMBOL_TYPE. */
1616
1617 bool
1618 riscv_symbolic_constant_p (rtx x, enum riscv_symbol_type *symbol_type)
1619 {
1620 rtx offset;
1621
1622 split_const (x, &x, &offset);
1623 if (UNSPEC_ADDRESS_P (x))
1624 {
1625 *symbol_type = UNSPEC_ADDRESS_TYPE (x);
1626 x = UNSPEC_ADDRESS (x);
1627 }
1628 else if (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF)
1629 *symbol_type = riscv_classify_symbol (x);
1630 else
1631 return false;
1632
1633 if (offset == const0_rtx)
1634 return true;
1635
1636 /* Nonzero offsets are only valid for references that don't use the GOT. */
1637 switch (*symbol_type)
1638 {
1639 case SYMBOL_ABSOLUTE:
1640 case SYMBOL_PCREL:
1641 case SYMBOL_TLS_LE:
1642 /* GAS rejects offsets outside the range [-2^31, 2^31-1]. */
1643 return sext_hwi (INTVAL (offset), 32) == INTVAL (offset);
1644
1645 default:
1646 return false;
1647 }
1648 }
1649
1650 /* Returns the number of instructions necessary to reference a symbol. */
1651
1652 static int riscv_symbol_insns (enum riscv_symbol_type type)
1653 {
1654 switch (type)
1655 {
1656 case SYMBOL_TLS: return 0; /* Depends on the TLS model. */
1657 case SYMBOL_ABSOLUTE: return 2; /* LUI + the reference. */
1658 case SYMBOL_PCREL: return 2; /* AUIPC + the reference. */
1659 case SYMBOL_TLS_LE: return 3; /* LUI + ADD TP + the reference. */
1660 case SYMBOL_TLSDESC: return 6; /* 4-instruction call + ADD TP + the reference. */
1661 case SYMBOL_GOT_DISP: return 3; /* AUIPC + LD GOT + the reference. */
1662 case SYMBOL_FORCE_TO_MEM: return 3; /* AUIPC + LD + the reference. */
1663 default: gcc_unreachable ();
1664 }
1665 }
1666
1667 /* Immediate values loaded by the FLI.S instruction in Chapter 25 of the latest RISC-V ISA
1668 Manual draft. For details, please see:
1669 https://github.com/riscv/riscv-isa-manual/releases/tag/isa-449cd0c */
1670
1671 static const unsigned HOST_WIDE_INT fli_value_hf[32] =
1672 {
1673 #define P8(v) ((unsigned HOST_WIDE_INT) (v) << 8)
1674 P8(0xbc), P8(0x4), P8(0x1), P8(0x2),
1675 P8(0x1c), P8(0x20), P8(0x2c), P8(0x30),
1676 P8(0x34), P8(0x35), P8(0x36), P8(0x37),
1677 P8(0x38), P8(0x39), P8(0x3a), P8(0x3b),
1678 P8(0x3c), P8(0x3d), P8(0x3e), P8(0x3f),
1679 P8(0x40), P8(0x41), P8(0x42), P8(0x44),
1680 P8(0x48), P8(0x4c), P8(0x58), P8(0x5c),
1681 P8(0x78),
1682 /* Only used for filling, ensuring that 29 and 30 of HF are the same. */
1683 P8(0x78),
1684 P8(0x7c), P8(0x7e)
1685 #undef P8
1686 };
1687
1688 static const unsigned HOST_WIDE_INT fli_value_sf[32] =
1689 {
1690 #define P20(v) ((unsigned HOST_WIDE_INT) (v) << 20)
1691 P20(0xbf8), P20(0x008), P20(0x378), P20(0x380),
1692 P20(0x3b8), P20(0x3c0), P20(0x3d8), P20(0x3e0),
1693 P20(0x3e8), P20(0x3ea), P20(0x3ec), P20(0x3ee),
1694 P20(0x3f0), P20(0x3f2), P20(0x3f4), P20(0x3f6),
1695 P20(0x3f8), P20(0x3fa), P20(0x3fc), P20(0x3fe),
1696 P20(0x400), P20(0x402), P20(0x404), P20(0x408),
1697 P20(0x410), P20(0x418), P20(0x430), P20(0x438),
1698 P20(0x470), P20(0x478), P20(0x7f8), P20(0x7fc)
1699 #undef P20
1700 };
1701
1702 static const unsigned HOST_WIDE_INT fli_value_df[32] =
1703 {
1704 #define P48(v) ((unsigned HOST_WIDE_INT) (v) << 48)
1705 P48(0xbff0), P48(0x10), P48(0x3ef0), P48(0x3f00),
1706 P48(0x3f70), P48(0x3f80), P48(0x3fb0), P48(0x3fc0),
1707 P48(0x3fd0), P48(0x3fd4), P48(0x3fd8), P48(0x3fdc),
1708 P48(0x3fe0), P48(0x3fe4), P48(0x3fe8), P48(0x3fec),
1709 P48(0x3ff0), P48(0x3ff4), P48(0x3ff8), P48(0x3ffc),
1710 P48(0x4000), P48(0x4004), P48(0x4008), P48(0x4010),
1711 P48(0x4020), P48(0x4030), P48(0x4060), P48(0x4070),
1712 P48(0x40e0), P48(0x40f0), P48(0x7ff0), P48(0x7ff8)
1713 #undef P48
1714 };
1715
1716 /* Display floating-point values at the assembly level, which is consistent
1717 with the zfa extension of llvm:
1718 https://reviews.llvm.org/D145645. */
1719
1720 const char *fli_value_print[32] =
1721 {
1722 "-1.0", "min", "1.52587890625e-05", "3.0517578125e-05", "0.00390625", "0.0078125", "0.0625", "0.125",
1723 "0.25", "0.3125", "0.375", "0.4375", "0.5", "0.625", "0.75", "0.875",
1724 "1.0", "1.25", "1.5", "1.75", "2.0", "2.5", "3.0", "4.0",
1725 "8.0", "16.0", "128.0", "256.0", "32768.0", "65536.0", "inf", "nan"
1726 };
1727
1728 /* Return index of the FLI instruction table if rtx X is an immediate constant that can
1729 be moved using a single FLI instruction in zfa extension. Return -1 if not found. */
1730
1731 int
1732 riscv_float_const_rtx_index_for_fli (rtx x)
1733 {
1734 const unsigned HOST_WIDE_INT *fli_value_array;
1735
1736 machine_mode mode = GET_MODE (x);
1737
1738 if (!TARGET_ZFA
1739 || !CONST_DOUBLE_P(x)
1740 || mode == VOIDmode
1741 || (mode == HFmode && !(TARGET_ZFH || TARGET_ZVFH))
1742 || (mode == SFmode && !TARGET_HARD_FLOAT)
1743 || (mode == DFmode && !TARGET_DOUBLE_FLOAT))
1744 return -1;
1745
1746 if (!SCALAR_FLOAT_MODE_P (mode)
1747 || GET_MODE_BITSIZE (mode).to_constant () > HOST_BITS_PER_WIDE_INT
1748 /* Only support up to DF mode. */
1749 || GET_MODE_BITSIZE (mode).to_constant () > GET_MODE_BITSIZE (DFmode))
1750 return -1;
1751
1752 unsigned HOST_WIDE_INT ival = 0;
1753
1754 long res[2];
1755 real_to_target (res,
1756 CONST_DOUBLE_REAL_VALUE (x),
1757 REAL_MODE_FORMAT (mode));
1758
1759 if (mode == DFmode)
1760 {
1761 int order = BYTES_BIG_ENDIAN ? 1 : 0;
1762 ival = zext_hwi (res[order], 32);
1763 ival |= (zext_hwi (res[1 - order], 32) << 32);
1764
1765 /* When the lower 32 bits are not all 0, it is impossible to be in the table. */
1766 if (ival & (unsigned HOST_WIDE_INT)0xffffffff)
1767 return -1;
1768 }
1769 else
1770 ival = zext_hwi (res[0], 32);
1771
1772 switch (mode)
1773 {
1774 case E_HFmode:
1775 fli_value_array = fli_value_hf;
1776 break;
1777 case E_SFmode:
1778 fli_value_array = fli_value_sf;
1779 break;
1780 case E_DFmode:
1781 fli_value_array = fli_value_df;
1782 break;
1783 default:
1784 return -1;
1785 }
1786
1787 if (fli_value_array[0] == ival)
1788 return 0;
1789
1790 if (fli_value_array[1] == ival)
1791 return 1;
1792
1793 /* Perform a binary search to find target index. */
1794 unsigned l, r, m;
1795
1796 l = 2;
1797 r = 31;
1798
1799 while (l <= r)
1800 {
1801 m = (l + r) / 2;
1802 if (fli_value_array[m] == ival)
1803 return m;
1804 else if (fli_value_array[m] < ival)
1805 l = m+1;
1806 else
1807 r = m-1;
1808 }
1809
1810 return -1;
1811 }
1812
1813 /* Implement TARGET_LEGITIMATE_CONSTANT_P. */
1814
1815 static bool
1816 riscv_legitimate_constant_p (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
1817 {
1818 /* With the post-reload usage, it seems best to just pass in FALSE
1819 rather than pass ALLOW_NEW_PSEUDOS through the call chain. */
1820 return riscv_const_insns (x, false) > 0;
1821 }
1822
1823 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.
1824 Return true if X cannot (or should not) be spilled to the
1825 constant pool. */
1826
1827 static bool
1828 riscv_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED, rtx x)
1829 {
1830 enum riscv_symbol_type type;
1831 rtx base, offset;
1832
1833 /* There's no way to calculate VL-based values using relocations. */
1834 subrtx_iterator::array_type array;
1835 FOR_EACH_SUBRTX (iter, array, x, ALL)
1836 if (GET_CODE (*iter) == CONST_POLY_INT)
1837 return true;
1838
1839 /* There is no assembler syntax for expressing an address-sized
1840 high part. */
1841 if (GET_CODE (x) == HIGH)
1842 return true;
1843
1844 if (satisfies_constraint_zfli (x))
1845 return true;
1846
1847 split_const (x, &base, &offset);
1848 if (riscv_symbolic_constant_p (base, &type))
1849 {
1850 if (type == SYMBOL_FORCE_TO_MEM)
1851 return false;
1852
1853 /* As an optimization, don't spill symbolic constants that are as
1854 cheap to rematerialize as to access in the constant pool. */
1855 if (SMALL_OPERAND (INTVAL (offset)) && riscv_symbol_insns (type) > 0)
1856 return true;
1857
1858 /* As an optimization, avoid needlessly generate dynamic relocations. */
1859 if (flag_pic)
1860 return true;
1861 }
1862
1863 /* TLS symbols must be computed by riscv_legitimize_move. */
1864 if (tls_referenced_p (x))
1865 return true;
1866
1867 return false;
1868 }
1869
1870 /* Return true if register REGNO is a valid base register for mode MODE.
1871 STRICT_P is true if REG_OK_STRICT is in effect. */
1872
1873 int
1874 riscv_regno_mode_ok_for_base_p (int regno,
1875 machine_mode mode ATTRIBUTE_UNUSED,
1876 bool strict_p)
1877 {
1878 if (!HARD_REGISTER_NUM_P (regno))
1879 {
1880 if (!strict_p)
1881 return true;
1882 regno = reg_renumber[regno];
1883 }
1884
1885 /* These fake registers will be eliminated to either the stack or
1886 hard frame pointer, both of which are usually valid base registers.
1887 Reload deals with the cases where the eliminated form isn't valid. */
1888 if (regno == ARG_POINTER_REGNUM || regno == FRAME_POINTER_REGNUM)
1889 return true;
1890
1891 return GP_REG_P (regno);
1892 }
1893
1894 /* Get valid index register class.
1895 The RISC-V base instructions don't support index registers,
1896 but extensions might support that. */
1897
1898 enum reg_class
1899 riscv_index_reg_class ()
1900 {
1901 if (TARGET_XTHEADMEMIDX || TARGET_XTHEADFMEMIDX)
1902 return GR_REGS;
1903
1904 return NO_REGS;
1905 }
1906
1907 /* Return true if register REGNO is a valid index register.
1908 The RISC-V base instructions don't support index registers,
1909 but extensions might support that. */
1910
1911 int
1912 riscv_regno_ok_for_index_p (int regno)
1913 {
1914 if (TARGET_XTHEADMEMIDX || TARGET_XTHEADFMEMIDX)
1915 return riscv_regno_mode_ok_for_base_p (regno, VOIDmode, 1);
1916
1917 return 0;
1918 }
1919
1920 /* Return true if X is a valid base register for mode MODE.
1921 STRICT_P is true if REG_OK_STRICT is in effect. */
1922
1923 bool
1924 riscv_valid_base_register_p (rtx x, machine_mode mode, bool strict_p)
1925 {
1926 if (!strict_p && GET_CODE (x) == SUBREG)
1927 x = SUBREG_REG (x);
1928
1929 return (REG_P (x)
1930 && riscv_regno_mode_ok_for_base_p (REGNO (x), mode, strict_p));
1931 }
1932
1933 /* Return true if, for every base register BASE_REG, (plus BASE_REG X)
1934 can address a value of mode MODE. */
1935
1936 static bool
1937 riscv_valid_offset_p (rtx x, machine_mode mode)
1938 {
1939 /* Check that X is a signed 12-bit number. */
1940 if (!const_arith_operand (x, Pmode))
1941 return false;
1942
1943 /* We may need to split multiword moves, so make sure that every word
1944 is accessible. */
1945 if (GET_MODE_SIZE (mode).to_constant () > UNITS_PER_WORD
1946 && !SMALL_OPERAND (INTVAL (x) + GET_MODE_SIZE (mode).to_constant () - UNITS_PER_WORD))
1947 return false;
1948
1949 return true;
1950 }
1951
1952 /* Should a symbol of type SYMBOL_TYPE should be split in two? */
1953
1954 bool
1955 riscv_split_symbol_type (enum riscv_symbol_type symbol_type)
1956 {
1957 if (symbol_type == SYMBOL_TLS_LE)
1958 return true;
1959
1960 if (!TARGET_EXPLICIT_RELOCS)
1961 return false;
1962
1963 return symbol_type == SYMBOL_ABSOLUTE || symbol_type == SYMBOL_PCREL;
1964 }
1965
1966 /* Return true if a LO_SUM can address a value of mode MODE when the
1967 LO_SUM symbol has type SYM_TYPE. X is the LO_SUM second operand, which
1968 is used when the mode is BLKmode. */
1969
1970 static bool
1971 riscv_valid_lo_sum_p (enum riscv_symbol_type sym_type, machine_mode mode,
1972 rtx x)
1973 {
1974 int align, size;
1975
1976 /* Check that symbols of type SYMBOL_TYPE can be used to access values
1977 of mode MODE. */
1978 if (riscv_symbol_insns (sym_type) == 0)
1979 return false;
1980
1981 /* Check that there is a known low-part relocation. */
1982 if (!riscv_split_symbol_type (sym_type))
1983 return false;
1984
1985 /* We can't tell size or alignment when we have BLKmode, so try extracting a
1986 decl from the symbol if possible. */
1987 if (mode == BLKmode)
1988 {
1989 rtx offset;
1990
1991 /* Extract the symbol from the LO_SUM operand, if any. */
1992 split_const (x, &x, &offset);
1993
1994 /* Might be a CODE_LABEL. We can compute align but not size for that,
1995 so don't bother trying to handle it. */
1996 if (!SYMBOL_REF_P (x))
1997 return false;
1998
1999 /* Use worst case assumptions if we don't have a SYMBOL_REF_DECL. */
2000 align = (SYMBOL_REF_DECL (x)
2001 ? DECL_ALIGN (SYMBOL_REF_DECL (x))
2002 : 1);
2003 size = (SYMBOL_REF_DECL (x)
2004 && DECL_SIZE (SYMBOL_REF_DECL (x))
2005 && tree_fits_uhwi_p (DECL_SIZE (SYMBOL_REF_DECL (x)))
2006 ? tree_to_uhwi (DECL_SIZE (SYMBOL_REF_DECL (x)))
2007 : 2*BITS_PER_WORD);
2008 }
2009 else
2010 {
2011 align = GET_MODE_ALIGNMENT (mode);
2012 size = GET_MODE_BITSIZE (mode).to_constant ();
2013 }
2014
2015 /* We may need to split multiword moves, so make sure that each word
2016 can be accessed without inducing a carry. */
2017 if (size > BITS_PER_WORD
2018 && (!TARGET_STRICT_ALIGN || size > align))
2019 return false;
2020
2021 return true;
2022 }
2023
2024 /* Return true if mode is the RVV enabled mode.
2025 For example: 'RVVMF2SI' mode is disabled,
2026 whereas 'RVVM1SI' mode is enabled if MIN_VLEN == 32. */
2027
2028 bool
2029 riscv_v_ext_vector_mode_p (machine_mode mode)
2030 {
2031 #define ENTRY(MODE, REQUIREMENT, ...) \
2032 case MODE##mode: \
2033 return REQUIREMENT;
2034 switch (mode)
2035 {
2036 #include "riscv-vector-switch.def"
2037 default:
2038 return false;
2039 }
2040
2041 return false;
2042 }
2043
2044 /* Return true if mode is the RVV enabled tuple mode. */
2045
2046 bool
2047 riscv_v_ext_tuple_mode_p (machine_mode mode)
2048 {
2049 #define TUPLE_ENTRY(MODE, REQUIREMENT, ...) \
2050 case MODE##mode: \
2051 return REQUIREMENT;
2052 switch (mode)
2053 {
2054 #include "riscv-vector-switch.def"
2055 default:
2056 return false;
2057 }
2058
2059 return false;
2060 }
2061
2062 /* Return true if mode is the RVV enabled vls mode. */
2063
2064 bool
2065 riscv_v_ext_vls_mode_p (machine_mode mode)
2066 {
2067 #define VLS_ENTRY(MODE, REQUIREMENT) \
2068 case MODE##mode: \
2069 return REQUIREMENT;
2070 switch (mode)
2071 {
2072 #include "riscv-vector-switch.def"
2073 default:
2074 return false;
2075 }
2076
2077 return false;
2078 }
2079
2080 /* Return true if it is either of below modes.
2081 1. RVV vector mode.
2082 2. RVV tuple mode.
2083 3. RVV vls mode. */
2084
2085 static bool
2086 riscv_v_ext_mode_p (machine_mode mode)
2087 {
2088 return riscv_v_ext_vector_mode_p (mode) || riscv_v_ext_tuple_mode_p (mode)
2089 || riscv_v_ext_vls_mode_p (mode);
2090 }
2091
2092 static unsigned
2093 riscv_v_vls_mode_aggregate_gpr_count (unsigned vls_unit_size,
2094 unsigned scalar_unit_size)
2095 {
2096 gcc_assert (vls_unit_size != 0 && scalar_unit_size != 0);
2097
2098 if (vls_unit_size < scalar_unit_size)
2099 return 1;
2100
2101 /* Ensure the vls mode is exact_div by scalar_unit_size. */
2102 gcc_assert ((vls_unit_size % scalar_unit_size) == 0);
2103
2104 return vls_unit_size / scalar_unit_size;
2105 }
2106
2107 static machine_mode
2108 riscv_v_vls_to_gpr_mode (unsigned vls_mode_size)
2109 {
2110 switch (vls_mode_size)
2111 {
2112 case 16:
2113 return TImode;
2114 case 8:
2115 return DImode;
2116 case 4:
2117 return SImode;
2118 case 2:
2119 return HImode;
2120 case 1:
2121 return QImode;
2122 default:
2123 gcc_unreachable ();
2124 }
2125 }
2126
2127 /* Call from ADJUST_NUNITS in riscv-modes.def. Return the correct
2128 NUNITS size for corresponding machine_mode. */
2129
2130 poly_int64
2131 riscv_v_adjust_nunits (machine_mode mode, int scale)
2132 {
2133 gcc_assert (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL);
2134 if (riscv_v_ext_mode_p (mode))
2135 {
2136 if (TARGET_MIN_VLEN == 32)
2137 scale = scale / 2;
2138 return riscv_vector_chunks * scale;
2139 }
2140 return scale;
2141 }
2142
2143 /* Call from ADJUST_NUNITS in riscv-modes.def. Return the correct
2144 NUNITS size for corresponding machine_mode. */
2145
2146 poly_int64
2147 riscv_v_adjust_nunits (machine_mode mode, bool fractional_p, int lmul, int nf)
2148 {
2149 if (riscv_v_ext_mode_p (mode))
2150 {
2151 scalar_mode smode = GET_MODE_INNER (mode);
2152 int size = GET_MODE_SIZE (smode);
2153 int nunits_per_chunk = riscv_bytes_per_vector_chunk / size;
2154 if (fractional_p)
2155 return nunits_per_chunk / lmul * riscv_vector_chunks * nf;
2156 else
2157 return nunits_per_chunk * lmul * riscv_vector_chunks * nf;
2158 }
2159 /* Set the disabled RVV modes size as 1 by default. */
2160 return 1;
2161 }
2162
2163 /* Call from ADJUST_BYTESIZE in riscv-modes.def. Return the correct
2164 BYTE size for corresponding machine_mode. */
2165
2166 poly_int64
2167 riscv_v_adjust_bytesize (machine_mode mode, int scale)
2168 {
2169 if (riscv_v_ext_vector_mode_p (mode))
2170 {
2171 if (TARGET_XTHEADVECTOR)
2172 return BYTES_PER_RISCV_VECTOR;
2173
2174 poly_int64 nunits = GET_MODE_NUNITS (mode);
2175
2176 if (nunits.coeffs[0] > 8)
2177 return exact_div (nunits, 8);
2178 else if (nunits.is_constant ())
2179 return 1;
2180 else
2181 return poly_int64 (1, 1);
2182 }
2183
2184 return scale;
2185 }
2186
2187 /* Call from ADJUST_PRECISION in riscv-modes.def. Return the correct
2188 PRECISION size for corresponding machine_mode. */
2189
2190 poly_int64
2191 riscv_v_adjust_precision (machine_mode mode, int scale)
2192 {
2193 return riscv_v_adjust_nunits (mode, scale);
2194 }
2195
2196 /* Return true if X is a valid address for machine mode MODE. If it is,
2197 fill in INFO appropriately. STRICT_P is true if REG_OK_STRICT is in
2198 effect. */
2199
2200 static bool
2201 riscv_classify_address (struct riscv_address_info *info, rtx x,
2202 machine_mode mode, bool strict_p)
2203 {
2204 if (th_classify_address (info, x, mode, strict_p))
2205 return true;
2206
2207 switch (GET_CODE (x))
2208 {
2209 case REG:
2210 case SUBREG:
2211 info->type = ADDRESS_REG;
2212 info->reg = x;
2213 info->offset = const0_rtx;
2214 return riscv_valid_base_register_p (info->reg, mode, strict_p);
2215
2216 case PLUS:
2217 /* RVV load/store disallow any offset. */
2218 if (riscv_v_ext_mode_p (mode))
2219 return false;
2220
2221 info->type = ADDRESS_REG;
2222 info->reg = XEXP (x, 0);
2223 info->offset = XEXP (x, 1);
2224 return (riscv_valid_base_register_p (info->reg, mode, strict_p)
2225 && riscv_valid_offset_p (info->offset, mode));
2226
2227 case LO_SUM:
2228 /* RVV load/store disallow LO_SUM. */
2229 if (riscv_v_ext_mode_p (mode))
2230 return false;
2231
2232 info->type = ADDRESS_LO_SUM;
2233 info->reg = XEXP (x, 0);
2234 info->offset = XEXP (x, 1);
2235 /* We have to trust the creator of the LO_SUM to do something vaguely
2236 sane. Target-independent code that creates a LO_SUM should also
2237 create and verify the matching HIGH. Target-independent code that
2238 adds an offset to a LO_SUM must prove that the offset will not
2239 induce a carry. Failure to do either of these things would be
2240 a bug, and we are not required to check for it here. The RISC-V
2241 backend itself should only create LO_SUMs for valid symbolic
2242 constants, with the high part being either a HIGH or a copy
2243 of _gp. */
2244 info->symbol_type
2245 = riscv_classify_symbolic_expression (info->offset);
2246 return (riscv_valid_base_register_p (info->reg, mode, strict_p)
2247 && riscv_valid_lo_sum_p (info->symbol_type, mode, info->offset));
2248
2249 case CONST_INT:
2250 /* We only allow the const0_rtx for the RVV load/store. For example:
2251 +----------------------------------------------------------+
2252 | li a5,0 |
2253 | vsetvli zero,a1,e32,m1,ta,ma |
2254 | vle32.v v24,0(a5) <- propagate the const 0 to a5 here. |
2255 | vs1r.v v24,0(a0) |
2256 +----------------------------------------------------------+
2257 It can be folded to:
2258 +----------------------------------------------------------+
2259 | vsetvli zero,a1,e32,m1,ta,ma |
2260 | vle32.v v24,0(zero) |
2261 | vs1r.v v24,0(a0) |
2262 +----------------------------------------------------------+
2263 This behavior will benefit the underlying RVV auto vectorization. */
2264 if (riscv_v_ext_mode_p (mode))
2265 return x == const0_rtx;
2266
2267 /* Small-integer addresses don't occur very often, but they
2268 are legitimate if x0 is a valid base register. */
2269 info->type = ADDRESS_CONST_INT;
2270 return SMALL_OPERAND (INTVAL (x));
2271
2272 default:
2273 return false;
2274 }
2275 }
2276
2277 /* Implement TARGET_LEGITIMATE_ADDRESS_P. */
2278
2279 static bool
2280 riscv_legitimate_address_p (machine_mode mode, rtx x, bool strict_p,
2281 code_helper = ERROR_MARK)
2282 {
2283 /* Disallow RVV modes base address.
2284 E.g. (mem:SI (subreg:DI (reg:V1DI 155) 0). */
2285 if (SUBREG_P (x) && riscv_v_ext_mode_p (GET_MODE (SUBREG_REG (x))))
2286 return false;
2287 struct riscv_address_info addr;
2288
2289 return riscv_classify_address (&addr, x, mode, strict_p);
2290 }
2291
2292 /* Return true if hard reg REGNO can be used in compressed instructions. */
2293
2294 static bool
2295 riscv_compressed_reg_p (int regno)
2296 {
2297 /* x8-x15/f8-f15 are compressible registers. */
2298 return ((TARGET_RVC || TARGET_ZCA)
2299 && (IN_RANGE (regno, GP_REG_FIRST + 8, GP_REG_FIRST + 15)
2300 || IN_RANGE (regno, FP_REG_FIRST + 8, FP_REG_FIRST + 15)));
2301 }
2302
2303 /* Return true if x is an unsigned 5-bit immediate scaled by 4. */
2304
2305 static bool
2306 riscv_compressed_lw_offset_p (rtx x)
2307 {
2308 return (CONST_INT_P (x)
2309 && (INTVAL (x) & 3) == 0
2310 && IN_RANGE (INTVAL (x), 0, CSW_MAX_OFFSET));
2311 }
2312
2313 /* Return true if load/store from/to address x can be compressed. */
2314
2315 static bool
2316 riscv_compressed_lw_address_p (rtx x)
2317 {
2318 struct riscv_address_info addr;
2319 bool result = riscv_classify_address (&addr, x, GET_MODE (x),
2320 reload_completed);
2321
2322 /* Return false if address is not compressed_reg + small_offset. */
2323 if (!result
2324 || addr.type != ADDRESS_REG
2325 /* Before reload, assume all registers are OK. */
2326 || (reload_completed
2327 && !riscv_compressed_reg_p (REGNO (addr.reg))
2328 && addr.reg != stack_pointer_rtx)
2329 || !riscv_compressed_lw_offset_p (addr.offset))
2330 return false;
2331
2332 return result;
2333 }
2334
2335 /* Return the number of instructions needed to load or store a value
2336 of mode MODE at address X. Return 0 if X isn't valid for MODE.
2337 Assume that multiword moves may need to be split into word moves
2338 if MIGHT_SPLIT_P, otherwise assume that a single load or store is
2339 enough. */
2340
2341 int
2342 riscv_address_insns (rtx x, machine_mode mode, bool might_split_p)
2343 {
2344 struct riscv_address_info addr = {};
2345 int n = 1;
2346
2347 if (!riscv_classify_address (&addr, x, mode, false))
2348 {
2349 /* This could be a pattern from the pic.md file. In which case we want
2350 this address to always have a cost of 3 to make it as expensive as the
2351 most expensive symbol. This prevents constant propagation from
2352 preferring symbols over register plus offset. */
2353 return 3;
2354 }
2355
2356 /* BLKmode is used for single unaligned loads and stores and should
2357 not count as a multiword mode. */
2358 if (!riscv_v_ext_vector_mode_p (mode) && mode != BLKmode && might_split_p)
2359 n += (GET_MODE_SIZE (mode).to_constant () + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
2360
2361 if (addr.type == ADDRESS_LO_SUM)
2362 n += riscv_symbol_insns (addr.symbol_type) - 1;
2363
2364 return n;
2365 }
2366
2367 /* Return the number of instructions needed to load constant X.
2368 Return 0 if X isn't a valid constant.
2369
2370 ALLOW_NEW_PSEUDOS controls whether or not we're going to be allowed
2371 to create new pseduos. It must be FALSE for any call directly or
2372 indirectly from a pattern's condition. */
2373
2374 int
2375 riscv_const_insns (rtx x, bool allow_new_pseudos)
2376 {
2377 enum riscv_symbol_type symbol_type;
2378 rtx offset;
2379
2380 switch (GET_CODE (x))
2381 {
2382 case HIGH:
2383 if (!riscv_symbolic_constant_p (XEXP (x, 0), &symbol_type)
2384 || !riscv_split_symbol_type (symbol_type))
2385 return 0;
2386
2387 /* This is simply an LUI. */
2388 return 1;
2389
2390 case CONST_INT:
2391 {
2392 int cost = riscv_integer_cost (INTVAL (x), allow_new_pseudos);
2393 /* Force complicated constants to memory. */
2394 return cost < 4 ? cost : 0;
2395 }
2396
2397 case CONST_DOUBLE:
2398 /* See if we can use FMV directly. */
2399 if (satisfies_constraint_zfli (x))
2400 return 1;
2401
2402 /* We can use x0 to load floating-point zero. */
2403 return x == CONST0_RTX (GET_MODE (x)) ? 1 : 0;
2404 case CONST_VECTOR:
2405 {
2406 /* TODO: This is not accurate, we will need to
2407 adapt the COST of CONST_VECTOR in the future
2408 for the following cases:
2409
2410 - 1. const duplicate vector with element value
2411 in range of [-16, 15].
2412 - 2. const duplicate vector with element value
2413 out range of [-16, 15].
2414 - 3. const series vector.
2415 ...etc. */
2416 if (riscv_v_ext_mode_p (GET_MODE (x)))
2417 {
2418 rtx elt;
2419 if (const_vec_duplicate_p (x, &elt))
2420 {
2421 if (GET_MODE_CLASS (GET_MODE (x)) == MODE_VECTOR_BOOL)
2422 /* Duplicate values of 0/1 can be emitted using vmv.v.i. */
2423 return 1;
2424
2425 /* We don't allow CONST_VECTOR for DI vector on RV32
2426 system since the ELT constant value can not held
2427 within a single register to disable reload a DI
2428 register vec_duplicate into vmv.v.x. */
2429 scalar_mode smode = GET_MODE_INNER (GET_MODE (x));
2430 if (maybe_gt (GET_MODE_SIZE (smode), UNITS_PER_WORD)
2431 && !immediate_operand (elt, Pmode))
2432 return 0;
2433 /* Constants in range -16 ~ 15 integer or 0.0 floating-point
2434 can be emitted using vmv.v.i. */
2435 if (valid_vec_immediate_p (x))
2436 return 1;
2437
2438 /* Any int/FP constants can always be broadcast from a
2439 scalar register. Loading of a floating-point
2440 constant incurs a literal-pool access. Allow this in
2441 order to increase vectorization possibilities. */
2442 int n = riscv_const_insns (elt, allow_new_pseudos);
2443 if (CONST_DOUBLE_P (elt))
2444 return 1 + 4; /* vfmv.v.f + memory access. */
2445 else
2446 {
2447 /* We need as many insns as it takes to load the constant
2448 into a GPR and one vmv.v.x. */
2449 if (n != 0)
2450 return 1 + n;
2451 else
2452 return 1 + 4; /*vmv.v.x + memory access. */
2453 }
2454 }
2455
2456 /* const series vector. */
2457 rtx base, step;
2458 if (const_vec_series_p (x, &base, &step))
2459 {
2460 /* This cost is not accurate, we will need to adapt the COST
2461 accurately according to BASE && STEP. */
2462 return 1;
2463 }
2464
2465 if (CONST_VECTOR_STEPPED_P (x))
2466 {
2467 /* Some cases are unhandled so we need construct a builder to
2468 detect/allow those cases to be handled by the fallthrough
2469 handler. */
2470 unsigned int nelts_per_pattern = CONST_VECTOR_NELTS_PER_PATTERN (x);
2471 unsigned int npatterns = CONST_VECTOR_NPATTERNS (x);
2472 rvv_builder builder (GET_MODE(x), npatterns, nelts_per_pattern);
2473 for (unsigned int i = 0; i < nelts_per_pattern; i++)
2474 {
2475 for (unsigned int j = 0; j < npatterns; j++)
2476 builder.quick_push (CONST_VECTOR_ELT (x, i * npatterns + j));
2477 }
2478 builder.finalize ();
2479
2480 if (builder.single_step_npatterns_p ())
2481 {
2482 if (builder.npatterns_all_equal_p ())
2483 {
2484 /* TODO: This cost is not accurate. */
2485 return 1;
2486 }
2487 else
2488 {
2489 /* TODO: This cost is not accurate. */
2490 return 1;
2491 }
2492 }
2493 else if (builder.interleaved_stepped_npatterns_p ())
2494 {
2495 /* TODO: This cost is not accurate. */
2496 return 1;
2497 }
2498
2499 /* Fallthrough. */
2500 }
2501 }
2502
2503 /* TODO: We may support more const vector in the future. */
2504 return x == CONST0_RTX (GET_MODE (x)) ? 1 : 0;
2505 }
2506
2507 case CONST:
2508 /* See if we can refer to X directly. */
2509 if (riscv_symbolic_constant_p (x, &symbol_type))
2510 return riscv_symbol_insns (symbol_type);
2511
2512 /* Otherwise try splitting the constant into a base and offset. */
2513 split_const (x, &x, &offset);
2514 if (offset != 0)
2515 {
2516 int n = riscv_const_insns (x, allow_new_pseudos);
2517 if (n != 0)
2518 return n + riscv_integer_cost (INTVAL (offset), allow_new_pseudos);
2519 }
2520 return 0;
2521
2522 case SYMBOL_REF:
2523 case LABEL_REF:
2524 return riscv_symbol_insns (riscv_classify_symbol (x));
2525
2526 /* TODO: In RVV, we get CONST_POLY_INT by using csrr VLENB
2527 instruction and several scalar shift or mult instructions,
2528 it is so far unknown. We set it to 4 temporarily. */
2529 case CONST_POLY_INT:
2530 return 4;
2531
2532 default:
2533 return 0;
2534 }
2535 }
2536
2537 /* X is a doubleword constant that can be handled by splitting it into
2538 two words and loading each word separately. Return the number of
2539 instructions required to do this. */
2540
2541 int
2542 riscv_split_const_insns (rtx x)
2543 {
2544 unsigned int low, high;
2545
2546 /* This is not called from pattern conditions, so we can let
2547 our location in the RTL pipeline control whether or not
2548 new pseudos are created. */
2549 bool allow_new_pseudos = can_create_pseudo_p ();
2550 low = riscv_const_insns (riscv_subword (x, false), allow_new_pseudos);
2551 high = riscv_const_insns (riscv_subword (x, true), allow_new_pseudos);
2552 gcc_assert (low > 0 && high > 0);
2553 return low + high;
2554 }
2555
2556 /* Return the number of instructions needed to implement INSN,
2557 given that it loads from or stores to MEM. */
2558
2559 int
2560 riscv_load_store_insns (rtx mem, rtx_insn *insn)
2561 {
2562 machine_mode mode;
2563 bool might_split_p;
2564 rtx set;
2565
2566 gcc_assert (MEM_P (mem));
2567 mode = GET_MODE (mem);
2568
2569 /* Try to prove that INSN does not need to be split. */
2570 might_split_p = true;
2571 if (GET_MODE_BITSIZE (mode).to_constant () <= 32)
2572 might_split_p = false;
2573 else if (GET_MODE_BITSIZE (mode).to_constant () == 64)
2574 {
2575 set = single_set (insn);
2576 if (set && !riscv_split_64bit_move_p (SET_DEST (set), SET_SRC (set)))
2577 might_split_p = false;
2578 }
2579
2580 return riscv_address_insns (XEXP (mem, 0), mode, might_split_p);
2581 }
2582
2583 /* Emit a move from SRC to DEST. Assume that the move expanders can
2584 handle all moves if !can_create_pseudo_p (). The distinction is
2585 important because, unlike emit_move_insn, the move expanders know
2586 how to force Pmode objects into the constant pool even when the
2587 constant pool address is not itself legitimate. */
2588
2589 rtx
2590 riscv_emit_move (rtx dest, rtx src)
2591 {
2592 return (can_create_pseudo_p ()
2593 ? emit_move_insn (dest, src)
2594 : emit_move_insn_1 (dest, src));
2595 }
2596
2597 /* Emit an instruction of the form (set TARGET SRC). */
2598
2599 static rtx
2600 riscv_emit_set (rtx target, rtx src)
2601 {
2602 emit_insn (gen_rtx_SET (target, src));
2603 return target;
2604 }
2605
2606 /* Emit an instruction of the form (set DEST (CODE X)). */
2607
2608 rtx
2609 riscv_emit_unary (enum rtx_code code, rtx dest, rtx x)
2610 {
2611 return riscv_emit_set (dest, gen_rtx_fmt_e (code, GET_MODE (dest), x));
2612 }
2613
2614 /* Emit an instruction of the form (set DEST (CODE X Y)). */
2615
2616 rtx
2617 riscv_emit_binary (enum rtx_code code, rtx dest, rtx x, rtx y)
2618 {
2619 return riscv_emit_set (dest, gen_rtx_fmt_ee (code, GET_MODE (dest), x, y));
2620 }
2621
2622 /* Compute (CODE X Y) and store the result in a new register
2623 of mode MODE. Return that new register. */
2624
2625 static rtx
2626 riscv_force_binary (machine_mode mode, enum rtx_code code, rtx x, rtx y)
2627 {
2628 return riscv_emit_binary (code, gen_reg_rtx (mode), x, y);
2629 }
2630
2631 static rtx
2632 riscv_swap_instruction (rtx inst)
2633 {
2634 gcc_assert (GET_MODE (inst) == SImode);
2635 if (BYTES_BIG_ENDIAN)
2636 inst = expand_unop (SImode, bswap_optab, inst, gen_reg_rtx (SImode), 1);
2637 return inst;
2638 }
2639
2640 /* Copy VALUE to a register and return that register. If new pseudos
2641 are allowed, copy it into a new register, otherwise use DEST. */
2642
2643 static rtx
2644 riscv_force_temporary (rtx dest, rtx value)
2645 {
2646 if (can_create_pseudo_p ())
2647 return force_reg (Pmode, value);
2648 else
2649 {
2650 riscv_emit_move (dest, value);
2651 return dest;
2652 }
2653 }
2654
2655 /* Wrap symbol or label BASE in an UNSPEC address of type SYMBOL_TYPE,
2656 then add CONST_INT OFFSET to the result. */
2657
2658 static rtx
2659 riscv_unspec_address_offset (rtx base, rtx offset,
2660 enum riscv_symbol_type symbol_type)
2661 {
2662 base = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, base),
2663 UNSPEC_ADDRESS_FIRST + symbol_type);
2664 if (offset != const0_rtx)
2665 base = gen_rtx_PLUS (Pmode, base, offset);
2666 return gen_rtx_CONST (Pmode, base);
2667 }
2668
2669 /* Return an UNSPEC address with underlying address ADDRESS and symbol
2670 type SYMBOL_TYPE. */
2671
2672 rtx
2673 riscv_unspec_address (rtx address, enum riscv_symbol_type symbol_type)
2674 {
2675 rtx base, offset;
2676
2677 split_const (address, &base, &offset);
2678 return riscv_unspec_address_offset (base, offset, symbol_type);
2679 }
2680
2681 /* If OP is an UNSPEC address, return the address to which it refers,
2682 otherwise return OP itself. */
2683
2684 static rtx
2685 riscv_strip_unspec_address (rtx op)
2686 {
2687 rtx base, offset;
2688
2689 split_const (op, &base, &offset);
2690 if (UNSPEC_ADDRESS_P (base))
2691 op = plus_constant (Pmode, UNSPEC_ADDRESS (base), INTVAL (offset));
2692 return op;
2693 }
2694
2695 /* If riscv_unspec_address (ADDR, SYMBOL_TYPE) is a 32-bit value, add the
2696 high part to BASE and return the result. Just return BASE otherwise.
2697 TEMP is as for riscv_force_temporary.
2698
2699 The returned expression can be used as the first operand to a LO_SUM. */
2700
2701 static rtx
2702 riscv_unspec_offset_high (rtx temp, rtx addr, enum riscv_symbol_type symbol_type)
2703 {
2704 addr = gen_rtx_HIGH (Pmode, riscv_unspec_address (addr, symbol_type));
2705 return riscv_force_temporary (temp, addr);
2706 }
2707
2708 /* Load an entry from the GOT for a TLS GD access. */
2709
2710 static rtx riscv_got_load_tls_gd (rtx dest, rtx sym)
2711 {
2712 if (Pmode == DImode)
2713 return gen_got_load_tls_gddi (dest, sym);
2714 else
2715 return gen_got_load_tls_gdsi (dest, sym);
2716 }
2717
2718 /* Load an entry from the GOT for a TLS IE access. */
2719
2720 static rtx riscv_got_load_tls_ie (rtx dest, rtx sym)
2721 {
2722 if (Pmode == DImode)
2723 return gen_got_load_tls_iedi (dest, sym);
2724 else
2725 return gen_got_load_tls_iesi (dest, sym);
2726 }
2727
2728 /* Add in the thread pointer for a TLS LE access. */
2729
2730 static rtx riscv_tls_add_tp_le (rtx dest, rtx base, rtx sym)
2731 {
2732 rtx tp = gen_rtx_REG (Pmode, THREAD_POINTER_REGNUM);
2733 if (Pmode == DImode)
2734 return gen_tls_add_tp_ledi (dest, base, tp, sym);
2735 else
2736 return gen_tls_add_tp_lesi (dest, base, tp, sym);
2737 }
2738
2739 /* If MODE is MAX_MACHINE_MODE, ADDR appears as a move operand, otherwise
2740 it appears in a MEM of that mode. Return true if ADDR is a legitimate
2741 constant in that context and can be split into high and low parts.
2742 If so, and if LOW_OUT is nonnull, emit the high part and store the
2743 low part in *LOW_OUT. Leave *LOW_OUT unchanged otherwise.
2744
2745 TEMP is as for riscv_force_temporary and is used to load the high
2746 part into a register.
2747
2748 When MODE is MAX_MACHINE_MODE, the low part is guaranteed to be
2749 a legitimize SET_SRC for an .md pattern, otherwise the low part
2750 is guaranteed to be a legitimate address for mode MODE. */
2751
2752 bool
2753 riscv_split_symbol (rtx temp, rtx addr, machine_mode mode, rtx *low_out)
2754 {
2755 enum riscv_symbol_type symbol_type;
2756
2757 if ((GET_CODE (addr) == HIGH && mode == MAX_MACHINE_MODE)
2758 || !riscv_symbolic_constant_p (addr, &symbol_type)
2759 || riscv_symbol_insns (symbol_type) == 0
2760 || !riscv_split_symbol_type (symbol_type))
2761 return false;
2762
2763 if (low_out)
2764 switch (symbol_type)
2765 {
2766 case SYMBOL_FORCE_TO_MEM:
2767 return false;
2768
2769 case SYMBOL_ABSOLUTE:
2770 {
2771 rtx high = gen_rtx_HIGH (Pmode, copy_rtx (addr));
2772 high = riscv_force_temporary (temp, high);
2773 *low_out = gen_rtx_LO_SUM (Pmode, high, addr);
2774 }
2775 break;
2776
2777 case SYMBOL_PCREL:
2778 {
2779 static unsigned seqno;
2780 char buf[32];
2781 rtx label;
2782
2783 ssize_t bytes = snprintf (buf, sizeof (buf), ".LA%u", seqno);
2784 gcc_assert ((size_t) bytes < sizeof (buf));
2785
2786 label = gen_rtx_SYMBOL_REF (Pmode, ggc_strdup (buf));
2787 SYMBOL_REF_FLAGS (label) |= SYMBOL_FLAG_LOCAL;
2788 /* ??? Ugly hack to make weak symbols work. May need to change the
2789 RTL for the auipc and/or low patterns to get a better fix for
2790 this. */
2791 if (! nonzero_address_p (addr))
2792 SYMBOL_REF_WEAK (label) = 1;
2793
2794 if (temp == NULL)
2795 temp = gen_reg_rtx (Pmode);
2796
2797 if (Pmode == DImode)
2798 emit_insn (gen_auipcdi (temp, copy_rtx (addr), GEN_INT (seqno)));
2799 else
2800 emit_insn (gen_auipcsi (temp, copy_rtx (addr), GEN_INT (seqno)));
2801
2802 *low_out = gen_rtx_LO_SUM (Pmode, temp, label);
2803
2804 seqno++;
2805 }
2806 break;
2807
2808 default:
2809 gcc_unreachable ();
2810 }
2811
2812 return true;
2813 }
2814
2815 /* Return a legitimate address for REG + OFFSET. TEMP is as for
2816 riscv_force_temporary; it is only needed when OFFSET is not a
2817 SMALL_OPERAND. */
2818
2819 static rtx
2820 riscv_add_offset (rtx temp, rtx reg, HOST_WIDE_INT offset)
2821 {
2822 if (!SMALL_OPERAND (offset))
2823 {
2824 rtx high;
2825
2826 /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.
2827 The addition inside the macro CONST_HIGH_PART may cause an
2828 overflow, so we need to force a sign-extension check. */
2829 high = gen_int_mode (CONST_HIGH_PART (offset), Pmode);
2830 offset = CONST_LOW_PART (offset);
2831 high = riscv_force_temporary (temp, high);
2832 reg = riscv_force_temporary (temp, gen_rtx_PLUS (Pmode, high, reg));
2833 }
2834 return plus_constant (Pmode, reg, offset);
2835 }
2836
2837 /* The __tls_get_attr symbol. */
2838 static GTY(()) rtx riscv_tls_symbol;
2839
2840 /* Return an instruction sequence that calls __tls_get_addr. SYM is
2841 the TLS symbol we are referencing and TYPE is the symbol type to use
2842 (either global dynamic or local dynamic). RESULT is an RTX for the
2843 return value location. */
2844
2845 static rtx_insn *
2846 riscv_call_tls_get_addr (rtx sym, rtx result)
2847 {
2848 rtx a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST), func;
2849 rtx_insn *insn;
2850
2851 if (!riscv_tls_symbol)
2852 riscv_tls_symbol = init_one_libfunc ("__tls_get_addr");
2853 func = gen_rtx_MEM (FUNCTION_MODE, riscv_tls_symbol);
2854
2855 start_sequence ();
2856
2857 emit_insn (riscv_got_load_tls_gd (a0, sym));
2858 insn = emit_call_insn (gen_call_value (result, func, const0_rtx,
2859 gen_int_mode (RISCV_CC_BASE, SImode)));
2860 RTL_CONST_CALL_P (insn) = 1;
2861 use_reg (&CALL_INSN_FUNCTION_USAGE (insn), a0);
2862 insn = get_insns ();
2863
2864 end_sequence ();
2865
2866 return insn;
2867 }
2868
2869 /* Generate the code to access LOC, a thread-local SYMBOL_REF, and return
2870 its address. The return value will be both a valid address and a valid
2871 SET_SRC (either a REG or a LO_SUM). */
2872
2873 static rtx
2874 riscv_legitimize_tls_address (rtx loc)
2875 {
2876 rtx dest, tp, tmp, a0;
2877 enum tls_model model = SYMBOL_REF_TLS_MODEL (loc);
2878
2879 #if 0
2880 /* TLS copy relocs are now deprecated and should not be used. */
2881 /* Since we support TLS copy relocs, non-PIC TLS accesses may all use LE. */
2882 if (!flag_pic)
2883 model = TLS_MODEL_LOCAL_EXEC;
2884 #endif
2885
2886 switch (model)
2887 {
2888 case TLS_MODEL_LOCAL_DYNAMIC:
2889 /* Rely on section anchors for the optimization that LDM TLS
2890 provides. The anchor's address is loaded with GD TLS. */
2891 case TLS_MODEL_GLOBAL_DYNAMIC:
2892 if (TARGET_TLSDESC)
2893 {
2894 tp = gen_rtx_REG (Pmode, THREAD_POINTER_REGNUM);
2895 a0 = gen_rtx_REG (Pmode, GP_ARG_FIRST);
2896 dest = gen_reg_rtx (Pmode);
2897
2898 emit_insn (gen_tlsdesc (Pmode, loc));
2899 emit_insn (gen_add3_insn (dest, a0, tp));
2900 }
2901 else
2902 {
2903 tmp = gen_rtx_REG (Pmode, GP_RETURN);
2904 dest = gen_reg_rtx (Pmode);
2905 emit_libcall_block (riscv_call_tls_get_addr (loc, tmp), dest, tmp,
2906 loc);
2907 }
2908 break;
2909
2910 case TLS_MODEL_INITIAL_EXEC:
2911 /* la.tls.ie; tp-relative add */
2912 tp = gen_rtx_REG (Pmode, THREAD_POINTER_REGNUM);
2913 tmp = gen_reg_rtx (Pmode);
2914 emit_insn (riscv_got_load_tls_ie (tmp, loc));
2915 dest = gen_reg_rtx (Pmode);
2916 emit_insn (gen_add3_insn (dest, tmp, tp));
2917 break;
2918
2919 case TLS_MODEL_LOCAL_EXEC:
2920 tmp = riscv_unspec_offset_high (NULL, loc, SYMBOL_TLS_LE);
2921 dest = gen_reg_rtx (Pmode);
2922 emit_insn (riscv_tls_add_tp_le (dest, tmp, loc));
2923 dest = gen_rtx_LO_SUM (Pmode, dest,
2924 riscv_unspec_address (loc, SYMBOL_TLS_LE));
2925 break;
2926
2927 default:
2928 gcc_unreachable ();
2929 }
2930 return dest;
2931 }
2932
2933 /* If X is not a valid address for mode MODE, force it into a register. */
2934
2935 static rtx
2936 riscv_force_address (rtx x, machine_mode mode)
2937 {
2938 if (!riscv_legitimate_address_p (mode, x, false))
2939 {
2940 if (can_create_pseudo_p ())
2941 return force_reg (Pmode, x);
2942 else
2943 {
2944 /* It's only safe for the thunk function.
2945 Use ra as the temp register. */
2946 gcc_assert (riscv_in_thunk_func);
2947 rtx reg = RISCV_PROLOGUE_TEMP2 (Pmode);
2948 riscv_emit_move (reg, x);
2949 return reg;
2950 }
2951 }
2952
2953 return x;
2954 }
2955
2956 /* Modify base + offset so that offset fits within a compressed load/store insn
2957 and the excess is added to base. */
2958
2959 static rtx
2960 riscv_shorten_lw_offset (rtx base, HOST_WIDE_INT offset)
2961 {
2962 rtx addr, high;
2963 /* Leave OFFSET as an unsigned 5-bit offset scaled by 4 and put the excess
2964 into HIGH. */
2965 high = GEN_INT (offset & ~CSW_MAX_OFFSET);
2966 offset &= CSW_MAX_OFFSET;
2967 if (!SMALL_OPERAND (INTVAL (high)))
2968 high = force_reg (Pmode, high);
2969 base = force_reg (Pmode, gen_rtx_PLUS (Pmode, high, base));
2970 addr = plus_constant (Pmode, base, offset);
2971 return addr;
2972 }
2973
2974 /* Helper for riscv_legitimize_address. Given X, return true if it
2975 is a left shift by 1, 2 or 3 positions or a multiply by 2, 4 or 8.
2976
2977 This respectively represent canonical shift-add rtxs or scaled
2978 memory addresses. */
2979 static bool
2980 mem_shadd_or_shadd_rtx_p (rtx x)
2981 {
2982 return ((GET_CODE (x) == ASHIFT
2983 || GET_CODE (x) == MULT)
2984 && register_operand (XEXP (x, 0), GET_MODE (x))
2985 && CONST_INT_P (XEXP (x, 1))
2986 && ((GET_CODE (x) == ASHIFT && IN_RANGE (INTVAL (XEXP (x, 1)), 1, 3))
2987 || (GET_CODE (x) == MULT
2988 && IN_RANGE (exact_log2 (INTVAL (XEXP (x, 1))), 1, 3))));
2989 }
2990
2991 /* This function is used to implement LEGITIMIZE_ADDRESS. If X can
2992 be legitimized in a way that the generic machinery might not expect,
2993 return a new address, otherwise return NULL. MODE is the mode of
2994 the memory being accessed. */
2995
2996 static rtx
2997 riscv_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
2998 machine_mode mode)
2999 {
3000 rtx addr;
3001
3002 if (riscv_tls_symbol_p (x))
3003 return riscv_legitimize_tls_address (x);
3004
3005 /* See if the address can split into a high part and a LO_SUM. */
3006 if (riscv_split_symbol (NULL, x, mode, &addr))
3007 return riscv_force_address (addr, mode);
3008
3009 /* Handle BASE + OFFSET. */
3010 if (GET_CODE (x) == PLUS && CONST_INT_P (XEXP (x, 1))
3011 && INTVAL (XEXP (x, 1)) != 0)
3012 {
3013 rtx base = XEXP (x, 0);
3014 HOST_WIDE_INT offset = INTVAL (XEXP (x, 1));
3015
3016 /* Handle (plus (plus (mult (a) (mem_shadd_constant)) (fp)) (C)) case. */
3017 if (GET_CODE (base) == PLUS && mem_shadd_or_shadd_rtx_p (XEXP (base, 0))
3018 && SMALL_OPERAND (offset))
3019 {
3020 rtx index = XEXP (base, 0);
3021 rtx fp = XEXP (base, 1);
3022 if (REG_P (fp) && REGNO (fp) == VIRTUAL_STACK_VARS_REGNUM)
3023 {
3024
3025 /* If we were given a MULT, we must fix the constant
3026 as we're going to create the ASHIFT form. */
3027 int shift_val = INTVAL (XEXP (index, 1));
3028 if (GET_CODE (index) == MULT)
3029 shift_val = exact_log2 (shift_val);
3030
3031 rtx reg1 = gen_reg_rtx (Pmode);
3032 rtx reg2 = gen_reg_rtx (Pmode);
3033 rtx reg3 = gen_reg_rtx (Pmode);
3034 riscv_emit_binary (PLUS, reg1, fp, GEN_INT (offset));
3035 riscv_emit_binary (ASHIFT, reg2, XEXP (index, 0), GEN_INT (shift_val));
3036 riscv_emit_binary (PLUS, reg3, reg2, reg1);
3037
3038 return reg3;
3039 }
3040 }
3041
3042 if (!riscv_valid_base_register_p (base, mode, false))
3043 base = copy_to_mode_reg (Pmode, base);
3044 if (optimize_function_for_size_p (cfun)
3045 && (strcmp (current_pass->name, "shorten_memrefs") == 0)
3046 && mode == SImode)
3047 /* Convert BASE + LARGE_OFFSET into NEW_BASE + SMALL_OFFSET to allow
3048 possible compressed load/store. */
3049 addr = riscv_shorten_lw_offset (base, offset);
3050 else
3051 addr = riscv_add_offset (NULL, base, offset);
3052 return riscv_force_address (addr, mode);
3053 }
3054
3055 return x;
3056 }
3057
3058 /* Load VALUE into DEST. TEMP is as for riscv_force_temporary. ORIG_MODE
3059 is the original src mode before promotion. */
3060
3061 void
3062 riscv_move_integer (rtx temp, rtx dest, HOST_WIDE_INT value,
3063 machine_mode orig_mode)
3064 {
3065 struct riscv_integer_op codes[RISCV_MAX_INTEGER_OPS];
3066 machine_mode mode;
3067 int i, num_ops;
3068 rtx x = NULL_RTX;
3069
3070 mode = GET_MODE (dest);
3071 /* We use the original mode for the riscv_build_integer call, because HImode
3072 values are given special treatment. */
3073 num_ops = riscv_build_integer (codes, value, orig_mode, can_create_pseudo_p ());
3074
3075 if (can_create_pseudo_p () && num_ops > 2 /* not a simple constant */
3076 && num_ops >= riscv_split_integer_cost (value))
3077 x = riscv_split_integer (value, mode);
3078 else
3079 {
3080 rtx old_value = NULL_RTX;
3081 for (i = 0; i < num_ops; i++)
3082 {
3083 if (i != 0 && !can_create_pseudo_p ())
3084 x = riscv_emit_set (temp, x);
3085 else if (i != 0)
3086 x = force_reg (mode, x);
3087 codes[i].value = trunc_int_for_mode (codes[i].value, mode);
3088 if (codes[i].code == UNKNOWN)
3089 {
3090 /* UNKNOWN means load the constant value into X. */
3091 x = GEN_INT (codes[i].value);
3092 }
3093 else if (codes[i].use_uw)
3094 {
3095 /* If the sequence requires using a "uw" form of an insn, we're
3096 going to have to construct the RTL ourselves and put it in
3097 a register to avoid force_reg/force_operand from mucking
3098 things up. */
3099 gcc_assert (TARGET_64BIT || TARGET_ZBA);
3100 rtx t = can_create_pseudo_p () ? gen_reg_rtx (mode) : temp;
3101
3102 /* Create the proper mask for the slli.uw instruction. */
3103 unsigned HOST_WIDE_INT value = 0xffffffff;
3104 value <<= codes[i].value;
3105
3106 /* Right now the only "uw" form we use is slli, we may add more
3107 in the future. */
3108 x = gen_rtx_fmt_ee (codes[i].code, mode,
3109 x, GEN_INT (codes[i].value));
3110 x = gen_rtx_fmt_ee (AND, mode, x, GEN_INT (value));
3111 x = riscv_emit_set (t, x);
3112 }
3113 else if (codes[i].code == FMA)
3114 {
3115 HOST_WIDE_INT value = exact_log2 (codes[i].value - 1);
3116 rtx ashift = gen_rtx_fmt_ee (ASHIFT, mode, x, GEN_INT (value));
3117 x = gen_rtx_fmt_ee (PLUS, mode, ashift, x);
3118 rtx t = can_create_pseudo_p () ? gen_reg_rtx (mode) : temp;
3119 x = riscv_emit_set (t, x);
3120 }
3121 else if (codes[i].code == CONCAT || codes[i].code == VEC_MERGE)
3122 {
3123 if (codes[i].code == CONCAT && !TARGET_ZBKB)
3124 {
3125 /* The two values should have no bits in common, so we can
3126 use PLUS instead of IOR which has a higher chance of
3127 using a compressed instruction. */
3128 x = gen_rtx_PLUS (mode, x, old_value);
3129 }
3130 else
3131 {
3132 rtx t = can_create_pseudo_p () ? gen_reg_rtx (mode) : temp;
3133 rtx t2 = codes[i].code == VEC_MERGE ? old_value : x;
3134 gcc_assert (t2);
3135 t2 = gen_lowpart (SImode, t2);
3136 emit_insn (gen_riscv_xpack_di_si_2 (t, x, GEN_INT (32), t2));
3137 x = t;
3138 }
3139 }
3140 else
3141 x = gen_rtx_fmt_ee (codes[i].code, mode,
3142 x, GEN_INT (codes[i].value));
3143
3144 /* If this entry in the code table indicates we should save away
3145 the temporary holding the current value of X, then do so. */
3146 if (codes[i].save_temporary)
3147 {
3148 gcc_assert (old_value == NULL_RTX);
3149 x = force_reg (mode, x);
3150 old_value = x;
3151 }
3152 }
3153 }
3154
3155 riscv_emit_set (dest, x);
3156 }
3157
3158 /* Subroutine of riscv_legitimize_move. Move constant SRC into register
3159 DEST given that SRC satisfies immediate_operand but doesn't satisfy
3160 move_operand. */
3161
3162 static void
3163 riscv_legitimize_const_move (machine_mode mode, rtx dest, rtx src)
3164 {
3165 rtx base, offset;
3166
3167 /* Split moves of big integers into smaller pieces. */
3168 if (splittable_const_int_operand (src, mode))
3169 {
3170 riscv_move_integer (dest, dest, INTVAL (src), mode);
3171 return;
3172 }
3173
3174 if (satisfies_constraint_zfli (src))
3175 {
3176 riscv_emit_set (dest, src);
3177 return;
3178 }
3179
3180 /* Split moves of symbolic constants into high/low pairs. */
3181 if (riscv_split_symbol (dest, src, MAX_MACHINE_MODE, &src))
3182 {
3183 riscv_emit_set (dest, src);
3184 return;
3185 }
3186
3187 /* Generate the appropriate access sequences for TLS symbols. */
3188 if (riscv_tls_symbol_p (src))
3189 {
3190 riscv_emit_move (dest, riscv_legitimize_tls_address (src));
3191 return;
3192 }
3193
3194 /* If we have (const (plus symbol offset)), and that expression cannot
3195 be forced into memory, load the symbol first and add in the offset. Also
3196 prefer to do this even if the constant _can_ be forced into memory, as it
3197 usually produces better code. */
3198 split_const (src, &base, &offset);
3199 if (offset != const0_rtx
3200 && (targetm.cannot_force_const_mem (mode, src) || can_create_pseudo_p ()))
3201 {
3202 base = riscv_force_temporary (dest, base);
3203 riscv_emit_move (dest, riscv_add_offset (NULL, base, INTVAL (offset)));
3204 return;
3205 }
3206
3207 /* Handle below format.
3208 (const:DI
3209 (plus:DI
3210 (symbol_ref:DI ("ic") [flags 0x2] <var_decl 0x7fe57740be10 ic>) <- op_0
3211 (const_poly_int:DI [16, 16]) // <- op_1
3212 ))
3213 */
3214 if (GET_CODE (src) == CONST && GET_CODE (XEXP (src, 0)) == PLUS
3215 && CONST_POLY_INT_P (XEXP (XEXP (src, 0), 1)))
3216 {
3217 rtx dest_tmp = gen_reg_rtx (mode);
3218 rtx tmp = gen_reg_rtx (mode);
3219
3220 riscv_emit_move (dest, XEXP (XEXP (src, 0), 0));
3221 riscv_legitimize_poly_move (mode, dest_tmp, tmp, XEXP (XEXP (src, 0), 1));
3222
3223 emit_insn (gen_rtx_SET (dest, gen_rtx_PLUS (mode, dest, dest_tmp)));
3224 return;
3225 }
3226
3227 src = force_const_mem (mode, src);
3228
3229 /* When using explicit relocs, constant pool references are sometimes
3230 not legitimate addresses. */
3231 riscv_split_symbol (dest, XEXP (src, 0), mode, &XEXP (src, 0));
3232 riscv_emit_move (dest, src);
3233 }
3234
3235 /* Report when we try to do something that requires vector when vector is
3236 disabled. This is an error of last resort and isn't very high-quality. It
3237 usually involves attempts to measure the vector length in some way. */
3238
3239 static void
3240 riscv_report_v_required (void)
3241 {
3242 static bool reported_p = false;
3243
3244 /* Avoid reporting a slew of messages for a single oversight. */
3245 if (reported_p)
3246 return;
3247
3248 error ("this operation requires the RVV ISA extension");
3249 inform (input_location, "you can enable RVV using the command-line"
3250 " option %<-march%>, or by using the %<target%>"
3251 " attribute or pragma");
3252 reported_p = true;
3253 }
3254
3255 /* Helper function to operation for rtx_code CODE. */
3256 static void
3257 riscv_expand_op (enum rtx_code code, machine_mode mode, rtx op0, rtx op1,
3258 rtx op2)
3259 {
3260 if (can_create_pseudo_p ())
3261 {
3262 rtx result;
3263 if (GET_RTX_CLASS (code) == RTX_UNARY)
3264 result = expand_simple_unop (mode, code, op1, NULL_RTX, false);
3265 else
3266 result = expand_simple_binop (mode, code, op1, op2, NULL_RTX, false,
3267 OPTAB_DIRECT);
3268 riscv_emit_move (op0, result);
3269 }
3270 else
3271 {
3272 rtx pat;
3273 /* The following implementation is for prologue and epilogue.
3274 Because prologue and epilogue can not use pseudo register.
3275 We can't using expand_simple_binop or expand_simple_unop. */
3276 if (GET_RTX_CLASS (code) == RTX_UNARY)
3277 pat = gen_rtx_fmt_e (code, mode, op1);
3278 else
3279 pat = gen_rtx_fmt_ee (code, mode, op1, op2);
3280 emit_insn (gen_rtx_SET (op0, pat));
3281 }
3282 }
3283
3284 /* Expand mult operation with constant integer, multiplicand also used as a
3285 * temporary register. */
3286
3287 static void
3288 riscv_expand_mult_with_const_int (machine_mode mode, rtx dest, rtx multiplicand,
3289 HOST_WIDE_INT multiplier)
3290 {
3291 if (multiplier == 0)
3292 {
3293 riscv_emit_move (dest, GEN_INT (0));
3294 return;
3295 }
3296
3297 bool neg_p = multiplier < 0;
3298 unsigned HOST_WIDE_INT multiplier_abs = abs (multiplier);
3299
3300 if (multiplier_abs == 1)
3301 {
3302 if (neg_p)
3303 riscv_expand_op (NEG, mode, dest, multiplicand, NULL_RTX);
3304 else
3305 riscv_emit_move (dest, multiplicand);
3306 }
3307 else
3308 {
3309 if (pow2p_hwi (multiplier_abs))
3310 {
3311 /*
3312 multiplicand = [BYTES_PER_RISCV_VECTOR].
3313 1. const_poly_int:P [BYTES_PER_RISCV_VECTOR * 8].
3314 Sequence:
3315 csrr a5, vlenb
3316 slli a5, a5, 3
3317 2. const_poly_int:P [-BYTES_PER_RISCV_VECTOR * 8].
3318 Sequence:
3319 csrr a5, vlenb
3320 slli a5, a5, 3
3321 neg a5, a5
3322 */
3323 riscv_expand_op (ASHIFT, mode, dest, multiplicand,
3324 gen_int_mode (exact_log2 (multiplier_abs), QImode));
3325 if (neg_p)
3326 riscv_expand_op (NEG, mode, dest, dest, NULL_RTX);
3327 }
3328 else if (pow2p_hwi (multiplier_abs + 1))
3329 {
3330 /*
3331 multiplicand = [BYTES_PER_RISCV_VECTOR].
3332 1. const_poly_int:P [BYTES_PER_RISCV_VECTOR * 7].
3333 Sequence:
3334 csrr a5, vlenb
3335 slli a4, a5, 3
3336 sub a5, a4, a5
3337 2. const_poly_int:P [-BYTES_PER_RISCV_VECTOR * 7].
3338 Sequence:
3339 csrr a5, vlenb
3340 slli a4, a5, 3
3341 sub a5, a4, a5 + neg a5, a5 => sub a5, a5, a4
3342 */
3343 riscv_expand_op (ASHIFT, mode, dest, multiplicand,
3344 gen_int_mode (exact_log2 (multiplier_abs + 1),
3345 QImode));
3346 if (neg_p)
3347 riscv_expand_op (MINUS, mode, dest, multiplicand, dest);
3348 else
3349 riscv_expand_op (MINUS, mode, dest, dest, multiplicand);
3350 }
3351 else if (pow2p_hwi (multiplier - 1))
3352 {
3353 /*
3354 multiplicand = [BYTES_PER_RISCV_VECTOR].
3355 1. const_poly_int:P [BYTES_PER_RISCV_VECTOR * 9].
3356 Sequence:
3357 csrr a5, vlenb
3358 slli a4, a5, 3
3359 add a5, a4, a5
3360 2. const_poly_int:P [-BYTES_PER_RISCV_VECTOR * 9].
3361 Sequence:
3362 csrr a5, vlenb
3363 slli a4, a5, 3
3364 add a5, a4, a5
3365 neg a5, a5
3366 */
3367 riscv_expand_op (ASHIFT, mode, dest, multiplicand,
3368 gen_int_mode (exact_log2 (multiplier_abs - 1),
3369 QImode));
3370 riscv_expand_op (PLUS, mode, dest, dest, multiplicand);
3371 if (neg_p)
3372 riscv_expand_op (NEG, mode, dest, dest, NULL_RTX);
3373 }
3374 else
3375 {
3376 /* We use multiplication for remaining cases. */
3377 gcc_assert (
3378 TARGET_MUL
3379 && "M-extension must be enabled to calculate the poly_int "
3380 "size/offset.");
3381 riscv_emit_move (dest, gen_int_mode (multiplier, mode));
3382 riscv_expand_op (MULT, mode, dest, dest, multiplicand);
3383 }
3384 }
3385 }
3386
3387 /* Analyze src and emit const_poly_int mov sequence. */
3388
3389 void
3390 riscv_legitimize_poly_move (machine_mode mode, rtx dest, rtx tmp, rtx src)
3391 {
3392 poly_int64 value = rtx_to_poly_int64 (src);
3393 /* It use HOST_WIDE_INT instead of int since 32bit type is not enough
3394 for e.g. (const_poly_int:DI [549755813888, 549755813888]). */
3395 HOST_WIDE_INT offset = value.coeffs[0];
3396 HOST_WIDE_INT factor = value.coeffs[1];
3397 int vlenb = BYTES_PER_RISCV_VECTOR.coeffs[1];
3398 int div_factor = 0;
3399 /* Calculate (const_poly_int:MODE [m, n]) using scalar instructions.
3400 For any (const_poly_int:MODE [m, n]), the calculation formula is as
3401 follows.
3402 constant = m - n.
3403 When minimum VLEN = 32, poly of VLENB = (4, 4).
3404 base = vlenb(4, 4) or vlenb/2(2, 2) or vlenb/4(1, 1).
3405 When minimum VLEN > 32, poly of VLENB = (8, 8).
3406 base = vlenb(8, 8) or vlenb/2(4, 4) or vlenb/4(2, 2) or vlenb/8(1, 1).
3407 magn = (n, n) / base.
3408 (m, n) = base * magn + constant.
3409 This calculation doesn't need div operation. */
3410
3411 if (known_le (GET_MODE_SIZE (mode), GET_MODE_SIZE (Pmode)))
3412 emit_move_insn (tmp, gen_int_mode (BYTES_PER_RISCV_VECTOR, mode));
3413 else
3414 {
3415 emit_move_insn (gen_highpart (Pmode, tmp), CONST0_RTX (Pmode));
3416 emit_move_insn (gen_lowpart (Pmode, tmp),
3417 gen_int_mode (BYTES_PER_RISCV_VECTOR, Pmode));
3418 }
3419
3420 if (BYTES_PER_RISCV_VECTOR.is_constant ())
3421 {
3422 gcc_assert (value.is_constant ());
3423 riscv_emit_move (dest, GEN_INT (value.to_constant ()));
3424 return;
3425 }
3426 else
3427 {
3428 int max_power = exact_log2 (MAX_POLY_VARIANT);
3429 for (int i = 0; i <= max_power; i++)
3430 {
3431 int possible_div_factor = 1 << i;
3432 if (factor % (vlenb / possible_div_factor) == 0)
3433 {
3434 div_factor = possible_div_factor;
3435 break;
3436 }
3437 }
3438 gcc_assert (div_factor != 0);
3439 }
3440
3441 if (div_factor != 1)
3442 riscv_expand_op (LSHIFTRT, mode, tmp, tmp,
3443 gen_int_mode (exact_log2 (div_factor), QImode));
3444
3445 riscv_expand_mult_with_const_int (mode, dest, tmp,
3446 factor / (vlenb / div_factor));
3447 HOST_WIDE_INT constant = offset - factor;
3448
3449 if (constant == 0)
3450 return;
3451 else if (SMALL_OPERAND (constant))
3452 riscv_expand_op (PLUS, mode, dest, dest, gen_int_mode (constant, mode));
3453 else
3454 {
3455 /* Handle the constant value is not a 12-bit value. */
3456 rtx high;
3457
3458 /* Leave OFFSET as a 16-bit offset and put the excess in HIGH.
3459 The addition inside the macro CONST_HIGH_PART may cause an
3460 overflow, so we need to force a sign-extension check. */
3461 high = gen_int_mode (CONST_HIGH_PART (constant), mode);
3462 constant = CONST_LOW_PART (constant);
3463 riscv_emit_move (tmp, high);
3464 riscv_expand_op (PLUS, mode, dest, tmp, dest);
3465 riscv_expand_op (PLUS, mode, dest, dest, gen_int_mode (constant, mode));
3466 }
3467 }
3468
3469 /* Take care below subreg const_poly_int move:
3470
3471 1. (set (subreg:DI (reg:TI 237) 8)
3472 (subreg:DI (const_poly_int:TI [4, 2]) 8))
3473 =>
3474 (set (subreg:DI (reg:TI 237) 8)
3475 (const_int 0)) */
3476
3477 static bool
3478 riscv_legitimize_subreg_const_poly_move (machine_mode mode, rtx dest, rtx src)
3479 {
3480 gcc_assert (SUBREG_P (src) && CONST_POLY_INT_P (SUBREG_REG (src)));
3481 gcc_assert (SUBREG_BYTE (src).is_constant ());
3482
3483 int byte_offset = SUBREG_BYTE (src).to_constant ();
3484 rtx const_poly = SUBREG_REG (src);
3485 machine_mode subreg_mode = GET_MODE (const_poly);
3486
3487 if (subreg_mode != TImode) /* Only TImode is needed for now. */
3488 return false;
3489
3490 if (byte_offset == 8)
3491 {
3492 /* The const_poly_int cannot exceed int64, just set zero here. */
3493 emit_move_insn (dest, CONST0_RTX (mode));
3494 return true;
3495 }
3496
3497 /* The below transform will be covered in somewhere else.
3498 Thus, ignore this here.
3499 (set (subreg:DI (reg:TI 237) 0)
3500 (subreg:DI (const_poly_int:TI [4, 2]) 0))
3501 =>
3502 (set (subreg:DI (reg:TI 237) 0)
3503 (const_poly_int:DI [4, 2])) */
3504
3505 return false;
3506 }
3507
3508 /* If (set DEST SRC) is not a valid move instruction, emit an equivalent
3509 sequence that is valid. */
3510
3511 bool
3512 riscv_legitimize_move (machine_mode mode, rtx dest, rtx src)
3513 {
3514 if (CONST_POLY_INT_P (src))
3515 {
3516 /*
3517 Handle:
3518 (insn 183 182 184 6 (set (mem:QI (plus:DI (reg/f:DI 156)
3519 (const_int 96 [0x60])) [0 S1 A8])
3520 (const_poly_int:QI [8, 8]))
3521 "../../../../riscv-gcc/libgcc/unwind-dw2.c":1579:3 -1 (nil))
3522 */
3523 if (MEM_P (dest))
3524 {
3525 emit_move_insn (dest, force_reg (mode, src));
3526 return true;
3527 }
3528 poly_int64 value = rtx_to_poly_int64 (src);
3529 if (!value.is_constant () && !TARGET_VECTOR)
3530 {
3531 riscv_report_v_required ();
3532 return false;
3533 }
3534
3535 if (satisfies_constraint_vp (src) && GET_MODE (src) == Pmode)
3536 return false;
3537
3538 if (GET_MODE_SIZE (mode).to_constant () < GET_MODE_SIZE (Pmode))
3539 {
3540 /* In RV32 system, handle (const_poly_int:QI [m, n])
3541 (const_poly_int:HI [m, n]).
3542 In RV64 system, handle (const_poly_int:QI [m, n])
3543 (const_poly_int:HI [m, n])
3544 (const_poly_int:SI [m, n]). */
3545 rtx tmp = gen_reg_rtx (Pmode);
3546 rtx tmp2 = gen_reg_rtx (Pmode);
3547 riscv_legitimize_poly_move (Pmode, tmp2, tmp, src);
3548 emit_move_insn (dest, gen_lowpart (mode, tmp2));
3549 }
3550 else
3551 {
3552 /* In RV32 system, handle (const_poly_int:SI [m, n])
3553 (const_poly_int:DI [m, n]).
3554 In RV64 system, handle (const_poly_int:DI [m, n]).
3555 FIXME: Maybe we could gen SImode in RV32 and then sign-extend to
3556 DImode, the offset should not exceed 4GiB in general. */
3557 rtx tmp = gen_reg_rtx (mode);
3558 riscv_legitimize_poly_move (mode, dest, tmp, src);
3559 }
3560 return true;
3561 }
3562
3563 if (SUBREG_P (src) && CONST_POLY_INT_P (SUBREG_REG (src))
3564 && riscv_legitimize_subreg_const_poly_move (mode, dest, src))
3565 return true;
3566
3567 /* Expand
3568 (set (reg:DI target) (subreg:DI (reg:V8QI reg) 0))
3569 Expand this data movement instead of simply forbid it since
3570 we can improve the code generation for this following scenario
3571 by RVV auto-vectorization:
3572 (set (reg:V8QI 149) (vec_duplicate:V8QI (reg:QI))
3573 (set (reg:DI target) (subreg:DI (reg:V8QI reg) 0))
3574 Since RVV mode and scalar mode are in different REG_CLASS,
3575 we need to explicitly move data from V_REGS to GR_REGS by scalar move. */
3576 if (SUBREG_P (src) && riscv_v_ext_mode_p (GET_MODE (SUBREG_REG (src))))
3577 {
3578 machine_mode vmode = GET_MODE (SUBREG_REG (src));
3579 unsigned int mode_size = GET_MODE_SIZE (mode).to_constant ();
3580 unsigned int vmode_size = GET_MODE_SIZE (vmode).to_constant ();
3581 /* We should be able to handle both partial and paradoxical subreg. */
3582 unsigned int nunits = vmode_size > mode_size ? vmode_size / mode_size : 1;
3583 scalar_mode smode = as_a<scalar_mode> (mode);
3584 unsigned int index = SUBREG_BYTE (src).to_constant () / mode_size;
3585 unsigned int num = known_eq (GET_MODE_SIZE (smode), 8)
3586 && !TARGET_VECTOR_ELEN_64 ? 2 : 1;
3587 bool need_int_reg_p = false;
3588
3589 if (num == 2)
3590 {
3591 /* If we want to extract 64bit value but ELEN < 64,
3592 we use RVV vector mode with EEW = 32 to extract
3593 the highpart and lowpart. */
3594 need_int_reg_p = smode == DFmode;
3595 smode = SImode;
3596 nunits = nunits * 2;
3597 }
3598
3599 /* This test can fail if (for example) we want a HF and Z[v]fh is
3600 not enabled. In that case we just want to let the standard
3601 expansion path run. */
3602 if (riscv_vector::get_vector_mode (smode, nunits).exists (&vmode)
3603 && convert_optab_handler (vec_extract_optab, vmode, smode)
3604 && gen_lowpart_common (vmode, SUBREG_REG (src)))
3605 {
3606 rtx v = gen_lowpart (vmode, SUBREG_REG (src));
3607 rtx int_reg = dest;
3608
3609 if (need_int_reg_p)
3610 {
3611 int_reg = gen_reg_rtx (DImode);
3612 emit_move_insn (int_reg, gen_lowpart (GET_MODE (int_reg), dest));
3613 }
3614
3615 for (unsigned int i = 0; i < num; i++)
3616 {
3617 rtx result;
3618 if (num == 1)
3619 result = int_reg;
3620 else if (i == 0)
3621 result = gen_lowpart (smode, int_reg);
3622 else
3623 result = gen_reg_rtx (smode);
3624
3625 riscv_vector::emit_vec_extract (result, v,
3626 gen_int_mode (index + i, Pmode));
3627
3628 if (i == 1)
3629 {
3630 if (UNITS_PER_WORD < mode_size)
3631 /* If Pmode = SImode and mode = DImode, we just need to
3632 extract element of index = 1 from the vector and move it
3633 into the highpart of the DEST since DEST consists of 2
3634 scalar registers. */
3635 emit_move_insn (gen_highpart (smode, int_reg), result);
3636 else
3637 {
3638 rtx tmp = expand_binop (Pmode, ashl_optab,
3639 gen_lowpart (Pmode, result),
3640 gen_int_mode (32, Pmode),
3641 NULL_RTX, 0, OPTAB_DIRECT);
3642 rtx tmp2 = expand_binop (Pmode, ior_optab, tmp, int_reg,
3643 NULL_RTX, 0, OPTAB_DIRECT);
3644 emit_move_insn (int_reg, tmp2);
3645 }
3646 }
3647 }
3648
3649 if (need_int_reg_p)
3650 emit_move_insn (dest, gen_lowpart (GET_MODE (dest), int_reg));
3651 else
3652 emit_move_insn (dest, int_reg);
3653 return true;
3654 }
3655 }
3656
3657 /* Expand
3658 (set (reg:QI target) (mem:QI (address)))
3659 to
3660 (set (reg:DI temp) (zero_extend:DI (mem:QI (address))))
3661 (set (reg:QI target) (subreg:QI (reg:DI temp) 0))
3662 with auto-sign/zero extend. */
3663 if (GET_MODE_CLASS (mode) == MODE_INT
3664 && GET_MODE_SIZE (mode).to_constant () < UNITS_PER_WORD
3665 && can_create_pseudo_p ()
3666 && MEM_P (src))
3667 {
3668 rtx temp_reg;
3669 int zero_extend_p;
3670
3671 temp_reg = gen_reg_rtx (word_mode);
3672 zero_extend_p = (LOAD_EXTEND_OP (mode) == ZERO_EXTEND);
3673 emit_insn (gen_extend_insn (temp_reg, src, word_mode, mode,
3674 zero_extend_p));
3675 riscv_emit_move (dest, gen_lowpart (mode, temp_reg));
3676 return true;
3677 }
3678
3679 if (!register_operand (dest, mode) && !reg_or_0_operand (src, mode))
3680 {
3681 rtx reg;
3682
3683 if (GET_CODE (src) == CONST_INT)
3684 {
3685 /* Apply the equivalent of PROMOTE_MODE here for constants to
3686 improve cse. */
3687 machine_mode promoted_mode = mode;
3688 if (GET_MODE_CLASS (mode) == MODE_INT
3689 && GET_MODE_SIZE (mode).to_constant () < UNITS_PER_WORD)
3690 promoted_mode = word_mode;
3691
3692 if (splittable_const_int_operand (src, mode))
3693 {
3694 reg = gen_reg_rtx (promoted_mode);
3695 riscv_move_integer (reg, reg, INTVAL (src), mode);
3696 }
3697 else
3698 reg = force_reg (promoted_mode, src);
3699
3700 if (promoted_mode != mode)
3701 reg = gen_lowpart (mode, reg);
3702 }
3703 else
3704 reg = force_reg (mode, src);
3705 riscv_emit_move (dest, reg);
3706 return true;
3707 }
3708
3709 /* In order to fit NaN boxing, expand
3710 (set FP_REG (reg:HF/BF src))
3711 to
3712 (set (reg:SI/DI mask) (const_int -65536)
3713 (set (reg:SI/DI temp) (zero_extend:SI/DI (subreg:HI (reg:HF/BF src) 0)))
3714 (set (reg:SI/DI temp) (ior:SI/DI (reg:SI/DI mask) (reg:SI/DI temp)))
3715 (set (reg:HF/BF dest) (unspec:HF/BF[ (reg:SI/DI temp) ] UNSPEC_FMV_FP16_X))
3716 */
3717
3718 if (TARGET_HARD_FLOAT
3719 && !TARGET_ZFHMIN
3720 && (mode == HFmode || mode == BFmode)
3721 && REG_P (dest) && FP_REG_P (REGNO (dest))
3722 && REG_P (src) && !FP_REG_P (REGNO (src))
3723 && can_create_pseudo_p ())
3724 {
3725 rtx mask = force_reg (word_mode, gen_int_mode (-65536, word_mode));
3726 rtx temp = gen_reg_rtx (word_mode);
3727 emit_insn (gen_extend_insn (temp,
3728 gen_lowpart (HImode, src),
3729 word_mode, HImode, 1));
3730 if (word_mode == SImode)
3731 emit_insn (gen_iorsi3 (temp, mask, temp));
3732 else
3733 emit_insn (gen_iordi3 (temp, mask, temp));
3734
3735 riscv_emit_move (dest, gen_rtx_UNSPEC (mode, gen_rtvec (1, temp),
3736 UNSPEC_FMV_FP16_X));
3737
3738 return true;
3739 }
3740
3741 /* We need to deal with constants that would be legitimate
3742 immediate_operands but aren't legitimate move_operands. */
3743 if (CONSTANT_P (src) && !move_operand (src, mode))
3744 {
3745 riscv_legitimize_const_move (mode, dest, src);
3746 set_unique_reg_note (get_last_insn (), REG_EQUAL, copy_rtx (src));
3747 return true;
3748 }
3749
3750 /* RISC-V GCC may generate non-legitimate address due to we provide some
3751 pattern for optimize access PIC local symbol and it's make GCC generate
3752 unrecognizable instruction during optimizing. */
3753
3754 if (MEM_P (dest) && !riscv_legitimate_address_p (mode, XEXP (dest, 0),
3755 reload_completed))
3756 {
3757 XEXP (dest, 0) = riscv_force_address (XEXP (dest, 0), mode);
3758 }
3759
3760 if (MEM_P (src) && !riscv_legitimate_address_p (mode, XEXP (src, 0),
3761 reload_completed))
3762 {
3763 XEXP (src, 0) = riscv_force_address (XEXP (src, 0), mode);
3764 }
3765
3766 return false;
3767 }
3768
3769 /* Return true if there is an instruction that implements CODE and accepts
3770 X as an immediate operand. */
3771
3772 static int
3773 riscv_immediate_operand_p (int code, HOST_WIDE_INT x)
3774 {
3775 switch (code)
3776 {
3777 case ASHIFT:
3778 case ASHIFTRT:
3779 case LSHIFTRT:
3780 /* All shift counts are truncated to a valid constant. */
3781 return true;
3782
3783 case AND:
3784 case IOR:
3785 case XOR:
3786 case PLUS:
3787 case LT:
3788 case LTU:
3789 /* These instructions take 12-bit signed immediates. */
3790 return SMALL_OPERAND (x);
3791
3792 case LE:
3793 /* We add 1 to the immediate and use SLT. */
3794 return SMALL_OPERAND (x + 1);
3795
3796 case LEU:
3797 /* Likewise SLTU, but reject the always-true case. */
3798 return SMALL_OPERAND (x + 1) && x + 1 != 0;
3799
3800 case GE:
3801 case GEU:
3802 /* We can emulate an immediate of 1 by using GT/GTU against x0. */
3803 return x == 1;
3804
3805 default:
3806 /* By default assume that x0 can be used for 0. */
3807 return x == 0;
3808 }
3809 }
3810
3811 /* Return the cost of binary operation X, given that the instruction
3812 sequence for a word-sized or smaller operation takes SINGLE_INSNS
3813 instructions and that the sequence of a double-word operation takes
3814 DOUBLE_INSNS instructions. */
3815
3816 static int
3817 riscv_binary_cost (rtx x, int single_insns, int double_insns)
3818 {
3819 if (!riscv_v_ext_mode_p (GET_MODE (x))
3820 && GET_MODE_SIZE (GET_MODE (x)).to_constant () == UNITS_PER_WORD * 2)
3821 return COSTS_N_INSNS (double_insns);
3822 return COSTS_N_INSNS (single_insns);
3823 }
3824
3825 /* Return the cost of sign- or zero-extending OP. */
3826
3827 static int
3828 riscv_extend_cost (rtx op, bool unsigned_p)
3829 {
3830 if (MEM_P (op))
3831 return 0;
3832
3833 if (unsigned_p && GET_MODE (op) == QImode)
3834 /* We can use ANDI. */
3835 return COSTS_N_INSNS (1);
3836
3837 /* ZBA provide zext.w. */
3838 if (TARGET_ZBA && TARGET_64BIT && unsigned_p && GET_MODE (op) == SImode)
3839 return COSTS_N_INSNS (1);
3840
3841 /* ZBB provide zext.h, sext.b and sext.h. */
3842 if (TARGET_ZBB)
3843 {
3844 if (!unsigned_p && GET_MODE (op) == QImode)
3845 return COSTS_N_INSNS (1);
3846
3847 if (GET_MODE (op) == HImode)
3848 return COSTS_N_INSNS (1);
3849 }
3850
3851 if (!unsigned_p && GET_MODE (op) == SImode)
3852 /* We can use SEXT.W. */
3853 return COSTS_N_INSNS (1);
3854
3855 /* We need to use a shift left and a shift right. */
3856 return COSTS_N_INSNS (2);
3857 }
3858
3859 /* Implement TARGET_RTX_COSTS. */
3860
3861 #define SINGLE_SHIFT_COST 1
3862
3863 static bool
3864 riscv_rtx_costs (rtx x, machine_mode mode, int outer_code, int opno ATTRIBUTE_UNUSED,
3865 int *total, bool speed)
3866 {
3867 /* TODO: We set RVV instruction cost as 1 by default.
3868 Cost Model need to be well analyzed and supported in the future. */
3869 if (riscv_v_ext_mode_p (mode))
3870 {
3871 *total = COSTS_N_INSNS (1);
3872 return true;
3873 }
3874
3875 bool float_mode_p = FLOAT_MODE_P (mode);
3876 int cost;
3877
3878 switch (GET_CODE (x))
3879 {
3880 case SET:
3881 /* If we are called for an INSN that's a simple set of a register,
3882 then cost based on the SET_SRC alone. */
3883 if (outer_code == INSN
3884 && register_operand (SET_DEST (x), GET_MODE (SET_DEST (x))))
3885 {
3886 if (REG_P (SET_SRC (x)) && TARGET_DOUBLE_FLOAT && mode == DFmode)
3887 {
3888 *total = COSTS_N_INSNS (1);
3889 return true;
3890 }
3891 riscv_rtx_costs (SET_SRC (x), mode, SET, opno, total, speed);
3892 return true;
3893 }
3894
3895 /* Otherwise return FALSE indicating we should recurse into both the
3896 SET_DEST and SET_SRC combining the cost of both. */
3897 return false;
3898
3899 case CONST_INT:
3900 /* trivial constants checked using OUTER_CODE in case they are
3901 encodable in insn itself w/o need for additional insn(s). */
3902 if (riscv_immediate_operand_p (outer_code, INTVAL (x)))
3903 {
3904 *total = 0;
3905 return true;
3906 }
3907 /* Fall through. */
3908
3909 case SYMBOL_REF:
3910 case LABEL_REF:
3911 case CONST_DOUBLE:
3912 /* With TARGET_SUPPORTS_WIDE_INT const int can't be in CONST_DOUBLE
3913 rtl object. Weird recheck due to switch-case fall through above. */
3914 if (GET_CODE (x) == CONST_DOUBLE)
3915 gcc_assert (GET_MODE (x) != VOIDmode);
3916 /* Fall through. */
3917
3918 case CONST:
3919 /* Non trivial CONST_INT Fall through: check if need multiple insns. */
3920 if ((cost = riscv_const_insns (x, can_create_pseudo_p ())) > 0)
3921 {
3922 /* 1. Hoist will GCSE constants only if TOTAL returned is non-zero.
3923 2. For constants loaded more than once, the approach so far has
3924 been to duplicate the operation than to CSE the constant.
3925 3. TODO: make cost more accurate specially if riscv_const_insns
3926 returns > 1. */
3927 if (outer_code == SET || GET_MODE (x) == VOIDmode)
3928 *total = COSTS_N_INSNS (1);
3929 }
3930 else /* The instruction will be fetched from the constant pool. */
3931 *total = COSTS_N_INSNS (riscv_symbol_insns (SYMBOL_ABSOLUTE));
3932 return true;
3933
3934 case MEM:
3935 /* If the address is legitimate, return the number of
3936 instructions it needs. */
3937 if ((cost = riscv_address_insns (XEXP (x, 0), mode, true)) > 0)
3938 {
3939 /* When optimizing for size, make uncompressible 32-bit addresses
3940 more expensive so that compressible 32-bit addresses are
3941 preferred. */
3942 if ((TARGET_RVC || TARGET_ZCA)
3943 && !speed && riscv_mshorten_memrefs && mode == SImode
3944 && !riscv_compressed_lw_address_p (XEXP (x, 0)))
3945 cost++;
3946
3947 *total = COSTS_N_INSNS (cost + tune_param->memory_cost);
3948 return true;
3949 }
3950 /* Otherwise use the default handling. */
3951 return false;
3952
3953 case IF_THEN_ELSE:
3954 if ((TARGET_SFB_ALU || TARGET_XTHEADCONDMOV)
3955 && reg_or_0_operand (XEXP (x, 1), mode)
3956 && sfb_alu_operand (XEXP (x, 2), mode)
3957 && comparison_operator (XEXP (x, 0), VOIDmode))
3958 {
3959 /* For predicated conditional-move operations we assume the cost
3960 of a single instruction even though there are actually two. */
3961 *total = COSTS_N_INSNS (1);
3962 return true;
3963 }
3964 else if (TARGET_ZICOND_LIKE
3965 && outer_code == SET
3966 && ((GET_CODE (XEXP (x, 1)) == REG
3967 && XEXP (x, 2) == CONST0_RTX (GET_MODE (XEXP (x, 1))))
3968 || (GET_CODE (XEXP (x, 2)) == REG
3969 && XEXP (x, 1) == CONST0_RTX (GET_MODE (XEXP (x, 2))))
3970 || (COMPARISON_P (XEXP (x, 0))
3971 && GET_CODE (XEXP (x, 1)) == REG
3972 && rtx_equal_p (XEXP (x, 1), XEXP (XEXP (x, 0), 0)))
3973 || (COMPARISON_P (XEXP (x, 0))
3974 && GET_CODE (XEXP (x, 1)) == REG
3975 && rtx_equal_p (XEXP (x, 2), XEXP (XEXP (x, 0), 0)))))
3976 {
3977 *total = COSTS_N_INSNS (1);
3978 return true;
3979 }
3980 else if (LABEL_REF_P (XEXP (x, 1)) && XEXP (x, 2) == pc_rtx)
3981 {
3982 if (equality_operator (XEXP (x, 0), mode)
3983 && GET_CODE (XEXP (XEXP (x, 0), 0)) == ZERO_EXTRACT)
3984 {
3985 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST + 1);
3986 return true;
3987 }
3988 if (ordered_comparison_operator (XEXP (x, 0), mode))
3989 {
3990 *total = COSTS_N_INSNS (1);
3991 return true;
3992 }
3993 }
3994 return false;
3995
3996 case NOT:
3997 *total = COSTS_N_INSNS (GET_MODE_SIZE (mode).to_constant () > UNITS_PER_WORD ? 2 : 1);
3998 return false;
3999
4000 case AND:
4001 /* slli.uw pattern for zba. */
4002 if (TARGET_ZBA && TARGET_64BIT && mode == DImode
4003 && GET_CODE (XEXP (x, 0)) == ASHIFT)
4004 {
4005 rtx and_rhs = XEXP (x, 1);
4006 rtx ashift_lhs = XEXP (XEXP (x, 0), 0);
4007 rtx ashift_rhs = XEXP (XEXP (x, 0), 1);
4008 if (register_operand (ashift_lhs, GET_MODE (ashift_lhs))
4009 && CONST_INT_P (ashift_rhs)
4010 && CONST_INT_P (and_rhs)
4011 && ((INTVAL (and_rhs) >> INTVAL (ashift_rhs)) == 0xffffffff))
4012 *total = COSTS_N_INSNS (1);
4013 return true;
4014 }
4015 /* bclri pattern for zbs. */
4016 if (TARGET_ZBS
4017 && not_single_bit_mask_operand (XEXP (x, 1), VOIDmode))
4018 {
4019 *total = COSTS_N_INSNS (1);
4020 return true;
4021 }
4022 /* bclr pattern for zbs. */
4023 if (TARGET_ZBS
4024 && register_operand (XEXP (x, 1), GET_MODE (XEXP (x, 1)))
4025 && GET_CODE (XEXP (x, 0)) == ROTATE
4026 && CONST_INT_P (XEXP ((XEXP (x, 0)), 0))
4027 && INTVAL (XEXP ((XEXP (x, 0)), 0)) == -2)
4028 {
4029 *total = COSTS_N_INSNS (1);
4030 return true;
4031 }
4032
4033 gcc_fallthrough ();
4034 case IOR:
4035 case XOR:
4036 /* orn, andn and xorn pattern for zbb. */
4037 if (TARGET_ZBB
4038 && GET_CODE (XEXP (x, 0)) == NOT)
4039 {
4040 *total = riscv_binary_cost (x, 1, 2);
4041 return true;
4042 }
4043
4044 /* bset[i] and binv[i] pattern for zbs. */
4045 if ((GET_CODE (x) == IOR || GET_CODE (x) == XOR)
4046 && TARGET_ZBS
4047 && ((GET_CODE (XEXP (x, 0)) == ASHIFT
4048 && CONST_INT_P (XEXP (XEXP (x, 0), 0)))
4049 || single_bit_mask_operand (XEXP (x, 1), VOIDmode)))
4050 {
4051 *total = COSTS_N_INSNS (1);
4052 return true;
4053 }
4054
4055 /* Double-word operations use two single-word operations. */
4056 *total = riscv_binary_cost (x, 1, 2);
4057 return false;
4058
4059 case ZERO_EXTRACT:
4060 /* This is an SImode shift. */
4061 if (outer_code == SET
4062 && CONST_INT_P (XEXP (x, 1))
4063 && CONST_INT_P (XEXP (x, 2))
4064 && (INTVAL (XEXP (x, 2)) > 0)
4065 && (INTVAL (XEXP (x, 1)) + INTVAL (XEXP (x, 2)) == 32))
4066 {
4067 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
4068 return true;
4069 }
4070 /* bit extraction pattern (zbs:bext, xtheadbs:tst). */
4071 if ((TARGET_ZBS || TARGET_XTHEADBS) && outer_code == SET
4072 && GET_CODE (XEXP (x, 1)) == CONST_INT
4073 && INTVAL (XEXP (x, 1)) == 1)
4074 {
4075 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
4076 return true;
4077 }
4078 gcc_fallthrough ();
4079 case SIGN_EXTRACT:
4080 if (TARGET_XTHEADBB && outer_code == SET
4081 && CONST_INT_P (XEXP (x, 1))
4082 && CONST_INT_P (XEXP (x, 2)))
4083 {
4084 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
4085 return true;
4086 }
4087 return false;
4088
4089 case ASHIFT:
4090 /* bset pattern for zbs. */
4091 if (TARGET_ZBS
4092 && CONST_INT_P (XEXP (x, 0))
4093 && INTVAL (XEXP (x, 0)) == 1)
4094 {
4095 *total = COSTS_N_INSNS (1);
4096 return true;
4097 }
4098 gcc_fallthrough ();
4099 case ASHIFTRT:
4100 case LSHIFTRT:
4101 *total = riscv_binary_cost (x, SINGLE_SHIFT_COST,
4102 CONSTANT_P (XEXP (x, 1)) ? 4 : 9);
4103 return false;
4104
4105 case ABS:
4106 *total = COSTS_N_INSNS (float_mode_p ? 1 : 3);
4107 return false;
4108
4109 case LO_SUM:
4110 *total = (set_src_cost (XEXP (x, 0), mode, speed)
4111 + set_src_cost (XEXP (x, 1), mode, speed));
4112 return true;
4113
4114 case LT:
4115 /* This is an SImode shift. */
4116 if (outer_code == SET && GET_MODE (x) == DImode
4117 && GET_MODE (XEXP (x, 0)) == SImode)
4118 {
4119 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
4120 return true;
4121 }
4122 /* Fall through. */
4123 case LTU:
4124 case LE:
4125 case LEU:
4126 case GT:
4127 case GTU:
4128 case GE:
4129 case GEU:
4130 case EQ:
4131 case NE:
4132 /* Branch comparisons have VOIDmode, so use the first operand's
4133 mode instead. */
4134 mode = GET_MODE (XEXP (x, 0));
4135 if (float_mode_p)
4136 *total = tune_param->fp_add[mode == DFmode];
4137 else
4138 *total = riscv_binary_cost (x, 1, 3);
4139 return false;
4140
4141 case UNORDERED:
4142 case ORDERED:
4143 /* (FEQ(A, A) & FEQ(B, B)) compared against 0. */
4144 mode = GET_MODE (XEXP (x, 0));
4145 *total = tune_param->fp_add[mode == DFmode] + COSTS_N_INSNS (2);
4146 return false;
4147
4148 case UNEQ:
4149 /* (FEQ(A, A) & FEQ(B, B)) compared against FEQ(A, B). */
4150 mode = GET_MODE (XEXP (x, 0));
4151 *total = tune_param->fp_add[mode == DFmode] + COSTS_N_INSNS (3);
4152 return false;
4153
4154 case LTGT:
4155 /* (FLT(A, A) || FGT(B, B)). */
4156 mode = GET_MODE (XEXP (x, 0));
4157 *total = tune_param->fp_add[mode == DFmode] + COSTS_N_INSNS (2);
4158 return false;
4159
4160 case UNGE:
4161 case UNGT:
4162 case UNLE:
4163 case UNLT:
4164 /* FLT or FLE, but guarded by an FFLAGS read and write. */
4165 mode = GET_MODE (XEXP (x, 0));
4166 *total = tune_param->fp_add[mode == DFmode] + COSTS_N_INSNS (4);
4167 return false;
4168
4169 case MINUS:
4170 if (float_mode_p)
4171 *total = tune_param->fp_add[mode == DFmode];
4172 else
4173 *total = riscv_binary_cost (x, 1, 4);
4174 return false;
4175
4176 case PLUS:
4177 /* add.uw pattern for zba. */
4178 if (TARGET_ZBA
4179 && (TARGET_64BIT && (mode == DImode))
4180 && GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
4181 && register_operand (XEXP (XEXP (x, 0), 0),
4182 GET_MODE (XEXP (XEXP (x, 0), 0)))
4183 && GET_MODE (XEXP (XEXP (x, 0), 0)) == SImode)
4184 {
4185 *total = COSTS_N_INSNS (1);
4186 return true;
4187 }
4188 /* shNadd pattern for zba. */
4189 if (TARGET_ZBA
4190 && ((!TARGET_64BIT && (mode == SImode)) ||
4191 (TARGET_64BIT && (mode == DImode)))
4192 && (GET_CODE (XEXP (x, 0)) == ASHIFT)
4193 && register_operand (XEXP (XEXP (x, 0), 0),
4194 GET_MODE (XEXP (XEXP (x, 0), 0)))
4195 && CONST_INT_P (XEXP (XEXP (x, 0), 1))
4196 && IN_RANGE (INTVAL (XEXP (XEXP (x, 0), 1)), 1, 3))
4197 {
4198 *total = COSTS_N_INSNS (1);
4199 return true;
4200 }
4201 /* Before strength-reduction, the shNadd can be expressed as the addition
4202 of a multiplication with a power-of-two. If this case is not handled,
4203 the strength-reduction in expmed.c will calculate an inflated cost. */
4204 if (TARGET_ZBA
4205 && mode == word_mode
4206 && GET_CODE (XEXP (x, 0)) == MULT
4207 && register_operand (XEXP (XEXP (x, 0), 0),
4208 GET_MODE (XEXP (XEXP (x, 0), 0)))
4209 && CONST_INT_P (XEXP (XEXP (x, 0), 1))
4210 && pow2p_hwi (INTVAL (XEXP (XEXP (x, 0), 1)))
4211 && IN_RANGE (exact_log2 (INTVAL (XEXP (XEXP (x, 0), 1))), 1, 3))
4212 {
4213 *total = COSTS_N_INSNS (1);
4214 return true;
4215 }
4216 /* shNadd.uw pattern for zba.
4217 [(set (match_operand:DI 0 "register_operand" "=r")
4218 (plus:DI
4219 (and:DI (ashift:DI (match_operand:DI 1 "register_operand" "r")
4220 (match_operand:QI 2 "immediate_operand" "I"))
4221 (match_operand 3 "immediate_operand" ""))
4222 (match_operand:DI 4 "register_operand" "r")))]
4223 "TARGET_64BIT && TARGET_ZBA
4224 && (INTVAL (operands[2]) >= 1) && (INTVAL (operands[2]) <= 3)
4225 && (INTVAL (operands[3]) >> INTVAL (operands[2])) == 0xffffffff"
4226 */
4227 if (TARGET_ZBA
4228 && (TARGET_64BIT && (mode == DImode))
4229 && (GET_CODE (XEXP (x, 0)) == AND)
4230 && register_operand (XEXP (x, 1), GET_MODE (XEXP (x, 1))))
4231 {
4232 do {
4233 rtx and_lhs = XEXP (XEXP (x, 0), 0);
4234 rtx and_rhs = XEXP (XEXP (x, 0), 1);
4235 if (GET_CODE (and_lhs) != ASHIFT)
4236 break;
4237 if (!CONST_INT_P (and_rhs))
4238 break;
4239
4240 rtx ashift_rhs = XEXP (and_lhs, 1);
4241
4242 if (!CONST_INT_P (ashift_rhs)
4243 || !IN_RANGE (INTVAL (ashift_rhs), 1, 3))
4244 break;
4245
4246 if (CONST_INT_P (and_rhs)
4247 && ((INTVAL (and_rhs) >> INTVAL (ashift_rhs)) == 0xffffffff))
4248 {
4249 *total = COSTS_N_INSNS (1);
4250 return true;
4251 }
4252 } while (false);
4253 }
4254
4255 if (float_mode_p)
4256 *total = tune_param->fp_add[mode == DFmode];
4257 else
4258 *total = riscv_binary_cost (x, 1, 4);
4259 return false;
4260
4261 case NEG:
4262 {
4263 rtx op = XEXP (x, 0);
4264 if (GET_CODE (op) == FMA && !HONOR_SIGNED_ZEROS (mode))
4265 {
4266 *total = (tune_param->fp_mul[mode == DFmode]
4267 + set_src_cost (XEXP (op, 0), mode, speed)
4268 + set_src_cost (XEXP (op, 1), mode, speed)
4269 + set_src_cost (XEXP (op, 2), mode, speed));
4270 return true;
4271 }
4272 }
4273
4274 if (float_mode_p)
4275 *total = tune_param->fp_add[mode == DFmode];
4276 else
4277 *total = COSTS_N_INSNS (GET_MODE_SIZE (mode).to_constant () > UNITS_PER_WORD ? 4 : 1);
4278 return false;
4279
4280 case MULT:
4281 if (float_mode_p)
4282 *total = tune_param->fp_mul[mode == DFmode];
4283 else if (!(TARGET_MUL || TARGET_ZMMUL))
4284 /* Estimate the cost of a library call. */
4285 *total = COSTS_N_INSNS (speed ? 32 : 6);
4286 else if (GET_MODE_SIZE (mode).to_constant () > UNITS_PER_WORD)
4287 *total = 3 * tune_param->int_mul[0] + COSTS_N_INSNS (2);
4288 else if (!speed)
4289 *total = COSTS_N_INSNS (1);
4290 else
4291 *total = tune_param->int_mul[mode == DImode];
4292 return false;
4293
4294 case DIV:
4295 case SQRT:
4296 case MOD:
4297 if (float_mode_p)
4298 {
4299 *total = tune_param->fp_div[mode == DFmode];
4300 return false;
4301 }
4302 /* Fall through. */
4303
4304 case UDIV:
4305 case UMOD:
4306 if (!TARGET_DIV)
4307 /* Estimate the cost of a library call. */
4308 *total = COSTS_N_INSNS (speed ? 32 : 6);
4309 else if (speed)
4310 *total = tune_param->int_div[mode == DImode];
4311 else
4312 *total = COSTS_N_INSNS (1);
4313 return false;
4314
4315 case ZERO_EXTEND:
4316 /* This is an SImode shift. */
4317 if (GET_CODE (XEXP (x, 0)) == LSHIFTRT)
4318 {
4319 *total = COSTS_N_INSNS (SINGLE_SHIFT_COST);
4320 return true;
4321 }
4322 /* Fall through. */
4323 case SIGN_EXTEND:
4324 *total = riscv_extend_cost (XEXP (x, 0), GET_CODE (x) == ZERO_EXTEND);
4325 return false;
4326
4327 case BSWAP:
4328 if (TARGET_ZBB)
4329 {
4330 /* RISC-V only defines rev8 for XLEN, so we will need an extra
4331 shift-right instruction for smaller modes. */
4332 *total = COSTS_N_INSNS (mode == word_mode ? 1 : 2);
4333 return true;
4334 }
4335 return false;
4336
4337 case FLOAT:
4338 case UNSIGNED_FLOAT:
4339 case FIX:
4340 case FLOAT_EXTEND:
4341 case FLOAT_TRUNCATE:
4342 *total = tune_param->fp_add[mode == DFmode];
4343 return false;
4344
4345 case FMA:
4346 *total = (tune_param->fp_mul[mode == DFmode]
4347 + set_src_cost (XEXP (x, 0), mode, speed)
4348 + set_src_cost (XEXP (x, 1), mode, speed)
4349 + set_src_cost (XEXP (x, 2), mode, speed));
4350 return true;
4351
4352 case UNSPEC:
4353 if (XINT (x, 1) == UNSPEC_AUIPC)
4354 {
4355 /* Make AUIPC cheap to avoid spilling its result to the stack. */
4356 *total = 1;
4357 return true;
4358 }
4359 return false;
4360
4361 default:
4362 return false;
4363 }
4364 }
4365
4366 /* Implement TARGET_ADDRESS_COST. */
4367
4368 static int
4369 riscv_address_cost (rtx addr, machine_mode mode,
4370 addr_space_t as ATTRIBUTE_UNUSED,
4371 bool speed ATTRIBUTE_UNUSED)
4372 {
4373 /* When optimizing for size, make uncompressible 32-bit addresses more
4374 * expensive so that compressible 32-bit addresses are preferred. */
4375 if ((TARGET_RVC || TARGET_ZCA)
4376 && !speed && riscv_mshorten_memrefs && mode == SImode
4377 && !riscv_compressed_lw_address_p (addr))
4378 return riscv_address_insns (addr, mode, false) + 1;
4379 return riscv_address_insns (addr, mode, false);
4380 }
4381
4382 /* Implement TARGET_INSN_COST. We factor in the branch cost in the cost
4383 calculation for conditional branches: one unit is considered the cost
4384 of microarchitecture-dependent actual branch execution and therefore
4385 multiplied by BRANCH_COST and any remaining units are considered fixed
4386 branch overhead. Branches on a floating-point condition incur an extra
4387 instruction cost as they will be split into an FCMP operation followed
4388 by a branch on an integer condition. */
4389
4390 static int
4391 riscv_insn_cost (rtx_insn *insn, bool speed)
4392 {
4393 rtx x = PATTERN (insn);
4394 int cost = pattern_cost (x, speed);
4395
4396 if (JUMP_P (insn))
4397 {
4398 if (GET_CODE (x) == PARALLEL)
4399 x = XVECEXP (x, 0, 0);
4400 if (GET_CODE (x) == SET
4401 && GET_CODE (SET_DEST (x)) == PC
4402 && GET_CODE (SET_SRC (x)) == IF_THEN_ELSE)
4403 {
4404 cost += COSTS_N_INSNS (BRANCH_COST (speed, false) - 1);
4405 if (FLOAT_MODE_P (GET_MODE (XEXP (XEXP (SET_SRC (x), 0), 0))))
4406 cost += COSTS_N_INSNS (1);
4407 }
4408 }
4409 return cost;
4410 }
4411
4412 /* Implement TARGET_MAX_NOCE_IFCVT_SEQ_COST. Like the default implementation,
4413 but we consider cost units of branch instructions equal to cost units of
4414 other instructions. */
4415
4416 static unsigned int
4417 riscv_max_noce_ifcvt_seq_cost (edge e)
4418 {
4419 bool predictable_p = predictable_edge_p (e);
4420
4421 if (predictable_p)
4422 {
4423 if (OPTION_SET_P (param_max_rtl_if_conversion_predictable_cost))
4424 return param_max_rtl_if_conversion_predictable_cost;
4425 }
4426 else
4427 {
4428 if (OPTION_SET_P (param_max_rtl_if_conversion_unpredictable_cost))
4429 return param_max_rtl_if_conversion_unpredictable_cost;
4430 }
4431
4432 return COSTS_N_INSNS (BRANCH_COST (true, predictable_p));
4433 }
4434
4435 /* Implement TARGET_NOCE_CONVERSION_PROFITABLE_P. We replace the cost of a
4436 conditional branch assumed by `noce_find_if_block' at `COSTS_N_INSNS (2)'
4437 by our actual conditional branch cost, observing that our branches test
4438 conditions directly, so there is no preparatory extra condition-set
4439 instruction. */
4440
4441 static bool
4442 riscv_noce_conversion_profitable_p (rtx_insn *seq,
4443 struct noce_if_info *if_info)
4444 {
4445 struct noce_if_info riscv_if_info = *if_info;
4446
4447 riscv_if_info.original_cost -= COSTS_N_INSNS (2);
4448 riscv_if_info.original_cost += insn_cost (if_info->jump, if_info->speed_p);
4449
4450 /* Hack alert! When `noce_try_store_flag_mask' uses `cstore<mode>4'
4451 to emit a conditional set operation on DImode output it comes up
4452 with a sequence such as:
4453
4454 (insn 26 0 27 (set (reg:SI 140)
4455 (eq:SI (reg/v:DI 137 [ c ])
4456 (const_int 0 [0]))) 302 {*seq_zero_disi}
4457 (nil))
4458 (insn 27 26 28 (set (reg:DI 139)
4459 (zero_extend:DI (reg:SI 140))) 116 {*zero_extendsidi2_internal}
4460 (nil))
4461
4462 because our `cstore<mode>4' pattern expands to an insn that gives
4463 a SImode output. The output of conditional set is 0 or 1 boolean,
4464 so it is valid for input in any scalar integer mode and therefore
4465 combine later folds the zero extend operation into an equivalent
4466 conditional set operation that produces a DImode output, however
4467 this redundant zero extend operation counts towards the cost of
4468 the replacement sequence. Compensate for that by incrementing the
4469 cost of the original sequence as well as the maximum sequence cost
4470 accordingly. Likewise for sign extension. */
4471 rtx last_dest = NULL_RTX;
4472 for (rtx_insn *insn = seq; insn; insn = NEXT_INSN (insn))
4473 {
4474 if (!NONDEBUG_INSN_P (insn))
4475 continue;
4476
4477 rtx x = PATTERN (insn);
4478 if (NONJUMP_INSN_P (insn)
4479 && GET_CODE (x) == SET)
4480 {
4481 rtx src = SET_SRC (x);
4482 enum rtx_code code = GET_CODE (src);
4483 if (last_dest != NULL_RTX
4484 && (code == SIGN_EXTEND || code == ZERO_EXTEND)
4485 && REG_P (XEXP (src, 0))
4486 && REGNO (XEXP (src, 0)) == REGNO (last_dest))
4487 {
4488 riscv_if_info.original_cost += COSTS_N_INSNS (1);
4489 riscv_if_info.max_seq_cost += COSTS_N_INSNS (1);
4490 }
4491
4492 rtx dest = SET_DEST (x);
4493
4494 /* Do something similar for the moves that are likely to
4495 turn into NOP moves by the time the register allocator is
4496 done. These are also side effects of how our sCC expanders
4497 work. We'll want to check and update LAST_DEST here too. */
4498 if (last_dest
4499 && REG_P (dest)
4500 && GET_MODE (dest) == SImode
4501 && SUBREG_P (src)
4502 && SUBREG_PROMOTED_VAR_P (src)
4503 && REGNO (SUBREG_REG (src)) == REGNO (last_dest))
4504 {
4505 riscv_if_info.original_cost += COSTS_N_INSNS (1);
4506 riscv_if_info.max_seq_cost += COSTS_N_INSNS (1);
4507 if (last_dest)
4508 last_dest = dest;
4509 }
4510 else
4511 last_dest = NULL_RTX;
4512
4513 if (COMPARISON_P (src) && REG_P (dest))
4514 last_dest = dest;
4515 }
4516 else
4517 last_dest = NULL_RTX;
4518 }
4519
4520 return default_noce_conversion_profitable_p (seq, &riscv_if_info);
4521 }
4522
4523 /* Return one word of double-word value OP. HIGH_P is true to select the
4524 high part or false to select the low part. */
4525
4526 rtx
4527 riscv_subword (rtx op, bool high_p)
4528 {
4529 unsigned int byte = (high_p != BYTES_BIG_ENDIAN) ? UNITS_PER_WORD : 0;
4530 machine_mode mode = GET_MODE (op);
4531
4532 if (mode == VOIDmode)
4533 mode = TARGET_64BIT ? TImode : DImode;
4534
4535 if (MEM_P (op))
4536 return adjust_address (op, word_mode, byte);
4537
4538 if (REG_P (op))
4539 gcc_assert (!FP_REG_RTX_P (op));
4540
4541 return simplify_gen_subreg (word_mode, op, mode, byte);
4542 }
4543
4544 /* Return true if a 64-bit move from SRC to DEST should be split into two. */
4545
4546 bool
4547 riscv_split_64bit_move_p (rtx dest, rtx src)
4548 {
4549 if (TARGET_64BIT)
4550 return false;
4551
4552 /* There is no need to split if the FLI instruction in the `Zfa` extension can be used. */
4553 if (satisfies_constraint_zfli (src))
4554 return false;
4555
4556 /* Allow FPR <-> FPR and FPR <-> MEM moves, and permit the special case
4557 of zeroing an FPR with FCVT.D.W. */
4558 if (TARGET_DOUBLE_FLOAT
4559 && ((FP_REG_RTX_P (src) && FP_REG_RTX_P (dest))
4560 || (FP_REG_RTX_P (dest) && MEM_P (src))
4561 || (FP_REG_RTX_P (src) && MEM_P (dest))
4562 || (FP_REG_RTX_P (dest) && src == CONST0_RTX (GET_MODE (src)))))
4563 return false;
4564
4565 return true;
4566 }
4567
4568 /* Split a doubleword move from SRC to DEST. On 32-bit targets,
4569 this function handles 64-bit moves for which riscv_split_64bit_move_p
4570 holds. For 64-bit targets, this function handles 128-bit moves. */
4571
4572 void
4573 riscv_split_doubleword_move (rtx dest, rtx src)
4574 {
4575 /* ZFA or XTheadFmv has instructions for accessing the upper bits of a double. */
4576 if (!TARGET_64BIT && (TARGET_ZFA || TARGET_XTHEADFMV))
4577 {
4578 if (FP_REG_RTX_P (dest))
4579 {
4580 rtx low_src = riscv_subword (src, false);
4581 rtx high_src = riscv_subword (src, true);
4582
4583 if (TARGET_ZFA)
4584 emit_insn (gen_movdfsisi3_rv32 (dest, high_src, low_src));
4585 else
4586 emit_insn (gen_th_fmv_hw_w_x (dest, high_src, low_src));
4587 return;
4588 }
4589 if (FP_REG_RTX_P (src))
4590 {
4591 rtx low_dest = riscv_subword (dest, false);
4592 rtx high_dest = riscv_subword (dest, true);
4593
4594 if (TARGET_ZFA)
4595 {
4596 emit_insn (gen_movsidf2_low_rv32 (low_dest, src));
4597 emit_insn (gen_movsidf2_high_rv32 (high_dest, src));
4598 return;
4599 }
4600 else
4601 {
4602 emit_insn (gen_th_fmv_x_w (low_dest, src));
4603 emit_insn (gen_th_fmv_x_hw (high_dest, src));
4604 }
4605 return;
4606 }
4607 }
4608
4609 /* The operation can be split into two normal moves. Decide in
4610 which order to do them. */
4611 rtx low_dest = riscv_subword (dest, false);
4612 if (REG_P (low_dest) && reg_overlap_mentioned_p (low_dest, src))
4613 {
4614 riscv_emit_move (riscv_subword (dest, true), riscv_subword (src, true));
4615 riscv_emit_move (low_dest, riscv_subword (src, false));
4616 }
4617 else
4618 {
4619 riscv_emit_move (low_dest, riscv_subword (src, false));
4620 riscv_emit_move (riscv_subword (dest, true), riscv_subword (src, true));
4621 }
4622 }
4623
4624 /* Constant VAL is known to be sum of two S12 constants. Break it into
4625 comprising BASE and OFF.
4626 Numerically S12 is -2048 to 2047, however it uses the more conservative
4627 range -2048 to 2032 as offsets pertain to stack related registers. */
4628
4629 void
4630 riscv_split_sum_of_two_s12 (HOST_WIDE_INT val, HOST_WIDE_INT *base,
4631 HOST_WIDE_INT *off)
4632 {
4633 if (SUM_OF_TWO_S12_N (val))
4634 {
4635 *base = -2048;
4636 *off = val - (-2048);
4637 }
4638 else if (SUM_OF_TWO_S12_P_ALGN (val))
4639 {
4640 *base = 2032;
4641 *off = val - 2032;
4642 }
4643 else
4644 {
4645 gcc_unreachable ();
4646 }
4647 }
4648
4649
4650 /* Return the appropriate instructions to move SRC into DEST. Assume
4651 that SRC is operand 1 and DEST is operand 0. */
4652
4653 const char *
4654 riscv_output_move (rtx dest, rtx src)
4655 {
4656 enum rtx_code dest_code, src_code;
4657 machine_mode mode;
4658 bool dbl_p;
4659 unsigned width;
4660 const char *insn;
4661
4662 if ((insn = th_output_move (dest, src)))
4663 return insn;
4664
4665 dest_code = GET_CODE (dest);
4666 src_code = GET_CODE (src);
4667 mode = GET_MODE (dest);
4668 dbl_p = (GET_MODE_SIZE (mode).to_constant () == 8);
4669 width = GET_MODE_SIZE (mode).to_constant ();
4670
4671 if (dbl_p && riscv_split_64bit_move_p (dest, src))
4672 return "#";
4673
4674 if (dest_code == REG && GP_REG_P (REGNO (dest)))
4675 {
4676 if (src_code == REG && FP_REG_P (REGNO (src)))
4677 switch (width)
4678 {
4679 case 2:
4680 if (TARGET_ZFHMIN || TARGET_ZFBFMIN)
4681 return "fmv.x.h\t%0,%1";
4682 /* Using fmv.x.s + sign-extend to emulate fmv.x.h. */
4683 return "fmv.x.s\t%0,%1;slli\t%0,%0,16;srai\t%0,%0,16";
4684 case 4:
4685 return "fmv.x.s\t%0,%1";
4686 case 8:
4687 return "fmv.x.d\t%0,%1";
4688 }
4689
4690 if (src_code == MEM)
4691 switch (width)
4692 {
4693 case 1: return "lbu\t%0,%1";
4694 case 2: return "lhu\t%0,%1";
4695 case 4: return "lw\t%0,%1";
4696 case 8: return "ld\t%0,%1";
4697 }
4698
4699 if (src_code == CONST_INT)
4700 {
4701 if (SMALL_OPERAND (INTVAL (src)) || LUI_OPERAND (INTVAL (src)))
4702 return "li\t%0,%1";
4703
4704 if (TARGET_ZBS
4705 && SINGLE_BIT_MASK_OPERAND (INTVAL (src)))
4706 return "bseti\t%0,zero,%S1";
4707
4708 /* Should never reach here. */
4709 abort ();
4710 }
4711
4712 if (src_code == HIGH)
4713 return "lui\t%0,%h1";
4714
4715 if (symbolic_operand (src, VOIDmode))
4716 switch (riscv_classify_symbolic_expression (src))
4717 {
4718 case SYMBOL_GOT_DISP: return "la\t%0,%1";
4719 case SYMBOL_ABSOLUTE: return "lla\t%0,%1";
4720 case SYMBOL_PCREL: return "lla\t%0,%1";
4721 default: gcc_unreachable ();
4722 }
4723 }
4724 if ((src_code == REG && GP_REG_P (REGNO (src)))
4725 || (src == CONST0_RTX (mode)))
4726 {
4727 if (dest_code == REG)
4728 {
4729 if (GP_REG_P (REGNO (dest)))
4730 return "mv\t%0,%z1";
4731
4732 if (FP_REG_P (REGNO (dest)))
4733 switch (width)
4734 {
4735 case 2:
4736 if (TARGET_ZFHMIN || TARGET_ZFBFMIN)
4737 return "fmv.h.x\t%0,%z1";
4738 /* High 16 bits should be all-1, otherwise HW will treated
4739 as a n-bit canonical NaN, but isn't matter for softfloat. */
4740 return "fmv.s.x\t%0,%1";
4741 case 4:
4742 return "fmv.s.x\t%0,%z1";
4743 case 8:
4744 if (TARGET_64BIT)
4745 return "fmv.d.x\t%0,%z1";
4746 /* in RV32, we can emulate fmv.d.x %0, x0 using fcvt.d.w */
4747 gcc_assert (src == CONST0_RTX (mode));
4748 return "fcvt.d.w\t%0,x0";
4749 }
4750 }
4751 if (dest_code == MEM)
4752 switch (width)
4753 {
4754 case 1: return "sb\t%z1,%0";
4755 case 2: return "sh\t%z1,%0";
4756 case 4: return "sw\t%z1,%0";
4757 case 8: return "sd\t%z1,%0";
4758 }
4759 }
4760 if (src_code == REG && FP_REG_P (REGNO (src)))
4761 {
4762 if (dest_code == REG && FP_REG_P (REGNO (dest)))
4763 switch (width)
4764 {
4765 case 2:
4766 if (TARGET_ZFH)
4767 return "fmv.h\t%0,%1";
4768 return "fmv.s\t%0,%1";
4769 case 4:
4770 return "fmv.s\t%0,%1";
4771 case 8:
4772 return "fmv.d\t%0,%1";
4773 }
4774
4775 if (dest_code == MEM)
4776 switch (width)
4777 {
4778 case 2:
4779 return "fsh\t%1,%0";
4780 case 4:
4781 return "fsw\t%1,%0";
4782 case 8:
4783 return "fsd\t%1,%0";
4784 }
4785 }
4786 if (dest_code == REG && FP_REG_P (REGNO (dest)))
4787 {
4788 if (src_code == MEM)
4789 switch (width)
4790 {
4791 case 2:
4792 return "flh\t%0,%1";
4793 case 4:
4794 return "flw\t%0,%1";
4795 case 8:
4796 return "fld\t%0,%1";
4797 }
4798
4799 if (src_code == CONST_DOUBLE && satisfies_constraint_zfli (src))
4800 switch (width)
4801 {
4802 case 2:
4803 return "fli.h\t%0,%1";
4804 case 4:
4805 return "fli.s\t%0,%1";
4806 case 8:
4807 return "fli.d\t%0,%1";
4808 }
4809 }
4810 if (dest_code == REG && GP_REG_P (REGNO (dest)) && src_code == CONST_POLY_INT)
4811 {
4812 /* We only want a single full vector register VLEN read after reload. */
4813 gcc_assert (known_eq (rtx_to_poly_int64 (src), BYTES_PER_RISCV_VECTOR));
4814 return "csrr\t%0,vlenb";
4815 }
4816 gcc_unreachable ();
4817 }
4818
4819 const char *
4820 riscv_output_return ()
4821 {
4822 if (cfun->machine->naked_p)
4823 return "";
4824
4825 return "ret";
4826 }
4827
4828
4829 /* Return true if CMP1 is a suitable second operand for integer ordering
4830 test CODE. See also the *sCC patterns in riscv.md. */
4831
4832 static bool
4833 riscv_int_order_operand_ok_p (enum rtx_code code, rtx cmp1)
4834 {
4835 switch (code)
4836 {
4837 case GT:
4838 case GTU:
4839 return reg_or_0_operand (cmp1, VOIDmode);
4840
4841 case GE:
4842 case GEU:
4843 return cmp1 == const1_rtx;
4844
4845 case LT:
4846 case LTU:
4847 return arith_operand (cmp1, VOIDmode);
4848
4849 case LE:
4850 return sle_operand (cmp1, VOIDmode);
4851
4852 case LEU:
4853 return sleu_operand (cmp1, VOIDmode);
4854
4855 default:
4856 gcc_unreachable ();
4857 }
4858 }
4859
4860 /* Return true if *CMP1 (of mode MODE) is a valid second operand for
4861 integer ordering test *CODE, or if an equivalent combination can
4862 be formed by adjusting *CODE and *CMP1. When returning true, update
4863 *CODE and *CMP1 with the chosen code and operand, otherwise leave
4864 them alone. */
4865
4866 static bool
4867 riscv_canonicalize_int_order_test (enum rtx_code *code, rtx *cmp1,
4868 machine_mode mode)
4869 {
4870 HOST_WIDE_INT plus_one;
4871
4872 if (riscv_int_order_operand_ok_p (*code, *cmp1))
4873 return true;
4874
4875 if (CONST_INT_P (*cmp1))
4876 switch (*code)
4877 {
4878 case LE:
4879 plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
4880 if (INTVAL (*cmp1) < plus_one)
4881 {
4882 *code = LT;
4883 *cmp1 = force_reg (mode, GEN_INT (plus_one));
4884 return true;
4885 }
4886 break;
4887
4888 case LEU:
4889 plus_one = trunc_int_for_mode (UINTVAL (*cmp1) + 1, mode);
4890 if (plus_one != 0)
4891 {
4892 *code = LTU;
4893 *cmp1 = force_reg (mode, GEN_INT (plus_one));
4894 return true;
4895 }
4896 break;
4897
4898 default:
4899 break;
4900 }
4901 return false;
4902 }
4903
4904 /* Compare CMP0 and CMP1 using ordering test CODE and store the result
4905 in TARGET. CMP0 and TARGET are register_operands. If INVERT_PTR
4906 is nonnull, it's OK to set TARGET to the inverse of the result and
4907 flip *INVERT_PTR instead. */
4908
4909 static void
4910 riscv_emit_int_order_test (enum rtx_code code, bool *invert_ptr,
4911 rtx target, rtx cmp0, rtx cmp1)
4912 {
4913 machine_mode mode;
4914
4915 /* First see if there is a RISCV instruction that can do this operation.
4916 If not, try doing the same for the inverse operation. If that also
4917 fails, force CMP1 into a register and try again. */
4918 mode = GET_MODE (cmp0);
4919 if (riscv_canonicalize_int_order_test (&code, &cmp1, mode))
4920 riscv_emit_binary (code, target, cmp0, cmp1);
4921 else
4922 {
4923 enum rtx_code inv_code = reverse_condition (code);
4924 if (!riscv_canonicalize_int_order_test (&inv_code, &cmp1, mode))
4925 {
4926 cmp1 = force_reg (mode, cmp1);
4927 riscv_emit_int_order_test (code, invert_ptr, target, cmp0, cmp1);
4928 }
4929 else if (invert_ptr == 0)
4930 {
4931 rtx inv_target = riscv_force_binary (word_mode,
4932 inv_code, cmp0, cmp1);
4933 riscv_emit_binary (EQ, target, inv_target, const0_rtx);
4934 }
4935 else
4936 {
4937 *invert_ptr = !*invert_ptr;
4938 riscv_emit_binary (inv_code, target, cmp0, cmp1);
4939 }
4940 }
4941 }
4942
4943 /* Return a register that is zero iff CMP0 and CMP1 are equal.
4944 The register will have the same mode as CMP0. */
4945
4946 static rtx
4947 riscv_zero_if_equal (rtx cmp0, rtx cmp1)
4948 {
4949 if (cmp1 == const0_rtx)
4950 return cmp0;
4951
4952 return expand_binop (GET_MODE (cmp0), sub_optab,
4953 cmp0, cmp1, 0, 0, OPTAB_DIRECT);
4954 }
4955
4956 /* Helper function for riscv_extend_comparands to Sign-extend the OP.
4957 However if the OP is SI subreg promoted with an inner DI, such as
4958 (subreg/s/v:SI (reg/v:DI) 0)
4959 just peel off the SUBREG to get DI, avoiding extraneous extension. */
4960
4961 static void
4962 riscv_sign_extend_if_not_subreg_prom (rtx *op)
4963 {
4964 if (GET_CODE (*op) == SUBREG
4965 && SUBREG_PROMOTED_VAR_P (*op)
4966 && SUBREG_PROMOTED_SIGNED_P (*op)
4967 && (GET_MODE_SIZE (GET_MODE (XEXP (*op, 0))).to_constant ()
4968 == GET_MODE_SIZE (word_mode)))
4969 *op = XEXP (*op, 0);
4970 else
4971 *op = gen_rtx_SIGN_EXTEND (word_mode, *op);
4972 }
4973
4974 /* Sign- or zero-extend OP0 and OP1 for integer comparisons. */
4975
4976 static void
4977 riscv_extend_comparands (rtx_code code, rtx *op0, rtx *op1)
4978 {
4979 /* Comparisons consider all XLEN bits, so extend sub-XLEN values. */
4980 if (GET_MODE_SIZE (word_mode) > GET_MODE_SIZE (GET_MODE (*op0)).to_constant ())
4981 {
4982 /* It is more profitable to zero-extend QImode values. But not if the
4983 first operand has already been sign-extended, and the second one is
4984 is a constant or has already been sign-extended also. */
4985 if (unsigned_condition (code) == code
4986 && (GET_MODE (*op0) == QImode
4987 && ! (GET_CODE (*op0) == SUBREG
4988 && SUBREG_PROMOTED_VAR_P (*op0)
4989 && SUBREG_PROMOTED_SIGNED_P (*op0)
4990 && (CONST_INT_P (*op1)
4991 || (GET_CODE (*op1) == SUBREG
4992 && SUBREG_PROMOTED_VAR_P (*op1)
4993 && SUBREG_PROMOTED_SIGNED_P (*op1))))))
4994 {
4995 *op0 = gen_rtx_ZERO_EXTEND (word_mode, *op0);
4996 if (CONST_INT_P (*op1))
4997 *op1 = GEN_INT ((uint8_t) INTVAL (*op1));
4998 else
4999 *op1 = gen_rtx_ZERO_EXTEND (word_mode, *op1);
5000 }
5001 else
5002 {
5003 riscv_sign_extend_if_not_subreg_prom (op0);
5004
5005 if (*op1 != const0_rtx)
5006 riscv_sign_extend_if_not_subreg_prom (op1);
5007 }
5008 }
5009 }
5010
5011 /* Convert a comparison into something that can be used in a branch or
5012 conditional move. On entry, *OP0 and *OP1 are the values being
5013 compared and *CODE is the code used to compare them.
5014
5015 Update *CODE, *OP0 and *OP1 so that they describe the final comparison.
5016 If NEED_EQ_NE_P, then only EQ or NE comparisons against zero are
5017 emitted. */
5018
5019 static void
5020 riscv_emit_int_compare (enum rtx_code *code, rtx *op0, rtx *op1,
5021 bool need_eq_ne_p = false)
5022 {
5023 if (need_eq_ne_p)
5024 {
5025 rtx cmp_op0 = *op0;
5026 rtx cmp_op1 = *op1;
5027 if (*code == EQ || *code == NE)
5028 {
5029 *op0 = riscv_zero_if_equal (cmp_op0, cmp_op1);
5030 *op1 = const0_rtx;
5031 return;
5032 }
5033 gcc_unreachable ();
5034 }
5035
5036 if (splittable_const_int_operand (*op1, VOIDmode))
5037 {
5038 HOST_WIDE_INT rhs = INTVAL (*op1);
5039
5040 if (*code == EQ || *code == NE)
5041 {
5042 /* Convert e.g. OP0 == 2048 into OP0 - 2048 == 0. */
5043 if (SMALL_OPERAND (-rhs))
5044 {
5045 *op0 = riscv_force_binary (GET_MODE (*op0), PLUS, *op0,
5046 GEN_INT (-rhs));
5047 *op1 = const0_rtx;
5048 }
5049 }
5050 else
5051 {
5052 static const enum rtx_code mag_comparisons[][2] = {
5053 {LEU, LTU}, {GTU, GEU}, {LE, LT}, {GT, GE}
5054 };
5055
5056 /* Convert e.g. (OP0 <= 0xFFF) into (OP0 < 0x1000). */
5057 for (size_t i = 0; i < ARRAY_SIZE (mag_comparisons); i++)
5058 {
5059 HOST_WIDE_INT new_rhs;
5060 bool increment = *code == mag_comparisons[i][0];
5061 bool decrement = *code == mag_comparisons[i][1];
5062 if (!increment && !decrement)
5063 continue;
5064
5065 new_rhs = rhs + (increment ? 1 : -1);
5066 new_rhs = trunc_int_for_mode (new_rhs, GET_MODE (*op0));
5067 if (riscv_integer_cost (new_rhs, true) < riscv_integer_cost (rhs, true)
5068 && (rhs < 0) == (new_rhs < 0))
5069 {
5070 *op1 = GEN_INT (new_rhs);
5071 *code = mag_comparisons[i][increment];
5072 }
5073 break;
5074 }
5075 }
5076 }
5077
5078 riscv_extend_comparands (*code, op0, op1);
5079
5080 *op0 = force_reg (word_mode, *op0);
5081 if (*op1 != const0_rtx)
5082 *op1 = force_reg (word_mode, *op1);
5083 }
5084
5085 /* Like riscv_emit_int_compare, but for floating-point comparisons. */
5086
5087 static void
5088 riscv_emit_float_compare (enum rtx_code *code, rtx *op0, rtx *op1,
5089 bool *invert_ptr = nullptr)
5090 {
5091 rtx tmp0, tmp1, cmp_op0 = *op0, cmp_op1 = *op1;
5092 enum rtx_code fp_code = *code;
5093 *code = NE;
5094
5095 switch (fp_code)
5096 {
5097 case UNORDERED:
5098 *code = EQ;
5099 /* Fall through. */
5100
5101 case ORDERED:
5102 /* a == a && b == b */
5103 tmp0 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op0);
5104 tmp1 = riscv_force_binary (word_mode, EQ, cmp_op1, cmp_op1);
5105 *op0 = riscv_force_binary (word_mode, AND, tmp0, tmp1);
5106 *op1 = const0_rtx;
5107 break;
5108
5109 case UNEQ:
5110 /* ordered(a, b) > (a == b) */
5111 *code = EQ;
5112 tmp0 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op0);
5113 tmp1 = riscv_force_binary (word_mode, EQ, cmp_op1, cmp_op1);
5114 *op0 = riscv_force_binary (word_mode, AND, tmp0, tmp1);
5115 *op1 = riscv_force_binary (word_mode, EQ, cmp_op0, cmp_op1);
5116 break;
5117
5118 #define UNORDERED_COMPARISON(CODE, CMP) \
5119 case CODE: \
5120 *code = EQ; \
5121 *op0 = gen_reg_rtx (word_mode); \
5122 if (GET_MODE (cmp_op0) == SFmode && TARGET_64BIT) \
5123 emit_insn (gen_f##CMP##_quietsfdi4 (*op0, cmp_op0, cmp_op1)); \
5124 else if (GET_MODE (cmp_op0) == SFmode) \
5125 emit_insn (gen_f##CMP##_quietsfsi4 (*op0, cmp_op0, cmp_op1)); \
5126 else if (GET_MODE (cmp_op0) == DFmode && TARGET_64BIT) \
5127 emit_insn (gen_f##CMP##_quietdfdi4 (*op0, cmp_op0, cmp_op1)); \
5128 else if (GET_MODE (cmp_op0) == DFmode) \
5129 emit_insn (gen_f##CMP##_quietdfsi4 (*op0, cmp_op0, cmp_op1)); \
5130 else if (GET_MODE (cmp_op0) == HFmode && TARGET_64BIT) \
5131 emit_insn (gen_f##CMP##_quiethfdi4 (*op0, cmp_op0, cmp_op1)); \
5132 else if (GET_MODE (cmp_op0) == HFmode) \
5133 emit_insn (gen_f##CMP##_quiethfsi4 (*op0, cmp_op0, cmp_op1)); \
5134 else \
5135 gcc_unreachable (); \
5136 *op1 = const0_rtx; \
5137 break;
5138
5139 case UNLT:
5140 std::swap (cmp_op0, cmp_op1);
5141 gcc_fallthrough ();
5142
5143 UNORDERED_COMPARISON(UNGT, le)
5144
5145 case UNLE:
5146 std::swap (cmp_op0, cmp_op1);
5147 gcc_fallthrough ();
5148
5149 UNORDERED_COMPARISON(UNGE, lt)
5150 #undef UNORDERED_COMPARISON
5151
5152 case NE:
5153 fp_code = EQ;
5154 if (invert_ptr != nullptr)
5155 *invert_ptr = !*invert_ptr;
5156 else
5157 {
5158 cmp_op0 = riscv_force_binary (word_mode, fp_code, cmp_op0, cmp_op1);
5159 cmp_op1 = const0_rtx;
5160 }
5161 gcc_fallthrough ();
5162
5163 case EQ:
5164 case LE:
5165 case LT:
5166 case GE:
5167 case GT:
5168 /* We have instructions for these cases. */
5169 *code = fp_code;
5170 *op0 = cmp_op0;
5171 *op1 = cmp_op1;
5172 break;
5173
5174 case LTGT:
5175 /* (a < b) | (a > b) */
5176 tmp0 = riscv_force_binary (word_mode, LT, cmp_op0, cmp_op1);
5177 tmp1 = riscv_force_binary (word_mode, GT, cmp_op0, cmp_op1);
5178 *op0 = riscv_force_binary (word_mode, IOR, tmp0, tmp1);
5179 *op1 = const0_rtx;
5180 break;
5181
5182 default:
5183 gcc_unreachable ();
5184 }
5185 }
5186
5187 /* CODE-compare OP0 and OP1. Store the result in TARGET. */
5188
5189 void
5190 riscv_expand_int_scc (rtx target, enum rtx_code code, rtx op0, rtx op1, bool *invert_ptr)
5191 {
5192 riscv_extend_comparands (code, &op0, &op1);
5193 op0 = force_reg (word_mode, op0);
5194
5195 /* For sub-word targets on rv64, do the computation in DImode
5196 then extract the lowpart for the final target, marking it
5197 as sign extended. Note that it's also properly zero extended,
5198 but it's probably more profitable to expose it as sign extended. */
5199 rtx t;
5200 if (TARGET_64BIT && GET_MODE (target) == SImode)
5201 t = gen_reg_rtx (DImode);
5202 else
5203 t = target;
5204
5205 if (code == EQ || code == NE)
5206 {
5207 rtx zie = riscv_zero_if_equal (op0, op1);
5208 riscv_emit_binary (code, t, zie, const0_rtx);
5209 }
5210 else
5211 riscv_emit_int_order_test (code, invert_ptr, t, op0, op1);
5212
5213 if (t != target)
5214 {
5215 t = gen_lowpart (SImode, t);
5216 SUBREG_PROMOTED_VAR_P (t) = 1;
5217 SUBREG_PROMOTED_SET (t, SRP_SIGNED);
5218 emit_move_insn (target, t);
5219 }
5220 }
5221
5222 /* Like riscv_expand_int_scc, but for floating-point comparisons. */
5223
5224 void
5225 riscv_expand_float_scc (rtx target, enum rtx_code code, rtx op0, rtx op1,
5226 bool *invert_ptr)
5227 {
5228 riscv_emit_float_compare (&code, &op0, &op1, invert_ptr);
5229
5230 machine_mode mode = GET_MODE (target);
5231 if (mode != word_mode)
5232 {
5233 rtx cmp = riscv_force_binary (word_mode, code, op0, op1);
5234 riscv_emit_set (target, lowpart_subreg (mode, cmp, word_mode));
5235 }
5236 else
5237 riscv_emit_binary (code, target, op0, op1);
5238 }
5239
5240 /* Jump to LABEL if (CODE OP0 OP1) holds. */
5241
5242 void
5243 riscv_expand_conditional_branch (rtx label, rtx_code code, rtx op0, rtx op1)
5244 {
5245 if (FLOAT_MODE_P (GET_MODE (op1)))
5246 riscv_emit_float_compare (&code, &op0, &op1);
5247 else
5248 riscv_emit_int_compare (&code, &op0, &op1);
5249
5250 if (FLOAT_MODE_P (GET_MODE (op0)))
5251 {
5252 op0 = riscv_force_binary (word_mode, code, op0, op1);
5253 op1 = const0_rtx;
5254 code = NE;
5255 }
5256
5257 rtx condition = gen_rtx_fmt_ee (code, VOIDmode, op0, op1);
5258 emit_jump_insn (gen_condjump (condition, label));
5259 }
5260
5261 /* Emit a cond move: If OP holds, move CONS to DEST; else move ALT to DEST.
5262 Return 0 if expansion failed. */
5263
5264 bool
5265 riscv_expand_conditional_move (rtx dest, rtx op, rtx cons, rtx alt)
5266 {
5267 machine_mode mode = GET_MODE (dest);
5268 rtx_code code = GET_CODE (op);
5269 rtx op0 = XEXP (op, 0);
5270 rtx op1 = XEXP (op, 1);
5271
5272 if (((TARGET_ZICOND_LIKE
5273 || (arith_operand (cons, mode) && arith_operand (alt, mode)))
5274 && (GET_MODE_CLASS (mode) == MODE_INT))
5275 || TARGET_SFB_ALU || TARGET_XTHEADCONDMOV)
5276 {
5277 machine_mode mode0 = GET_MODE (op0);
5278 machine_mode mode1 = GET_MODE (op1);
5279
5280 /* An integer comparison must be comparing WORD_MODE objects. We
5281 must enforce that so that we don't strip away a sign_extension
5282 thinking it is unnecessary. We might consider using
5283 riscv_extend_operands if they are not already properly extended. */
5284 if ((INTEGRAL_MODE_P (mode0) && mode0 != word_mode)
5285 || (INTEGRAL_MODE_P (mode1) && mode1 != word_mode))
5286 return false;
5287
5288 /* In the fallback generic case use MODE rather than WORD_MODE for
5289 the output of the SCC instruction, to match the mode of the NEG
5290 operation below. The output of SCC is 0 or 1 boolean, so it is
5291 valid for input in any scalar integer mode. */
5292 rtx tmp = gen_reg_rtx ((TARGET_ZICOND_LIKE
5293 || TARGET_SFB_ALU || TARGET_XTHEADCONDMOV)
5294 ? word_mode : mode);
5295 bool invert = false;
5296
5297 /* Canonicalize the comparison. It must be an equality comparison
5298 of integer operands, or with SFB it can be any comparison of
5299 integer operands. If it isn't, then emit an SCC instruction
5300 so that we can then use an equality comparison against zero. */
5301 if ((!TARGET_SFB_ALU && !equality_operator (op, VOIDmode))
5302 || !INTEGRAL_MODE_P (mode0))
5303 {
5304 bool *invert_ptr = nullptr;
5305
5306 /* If riscv_expand_int_scc inverts the condition, then it will
5307 flip the value of INVERT. We need to know where so that
5308 we can adjust it for our needs. */
5309 if (code == LE || code == LEU || code == GE || code == GEU)
5310 invert_ptr = &invert;
5311
5312 /* Emit an SCC-like instruction into a temporary so that we can
5313 use an EQ/NE comparison. We can support both FP and integer
5314 conditional moves. */
5315 if (INTEGRAL_MODE_P (mode0))
5316 riscv_expand_int_scc (tmp, code, op0, op1, invert_ptr);
5317 else if (FLOAT_MODE_P (mode0)
5318 && fp_scc_comparison (op, GET_MODE (op)))
5319 riscv_expand_float_scc (tmp, code, op0, op1, &invert);
5320 else
5321 return false;
5322
5323 op = gen_rtx_fmt_ee (invert ? EQ : NE, mode, tmp, const0_rtx);
5324
5325 /* We've generated a new comparison. Update the local variables. */
5326 code = GET_CODE (op);
5327 op0 = XEXP (op, 0);
5328 op1 = XEXP (op, 1);
5329 }
5330 else if (!TARGET_ZICOND_LIKE && !TARGET_SFB_ALU && !TARGET_XTHEADCONDMOV)
5331 riscv_expand_int_scc (tmp, code, op0, op1, &invert);
5332
5333 if (TARGET_SFB_ALU || TARGET_XTHEADCONDMOV)
5334 {
5335 riscv_emit_int_compare (&code, &op0, &op1, !TARGET_SFB_ALU);
5336 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5337
5338 /* The expander is a bit loose in its specification of the true
5339 arm of the conditional move. That allows us to support more
5340 cases for extensions which are more general than SFB. But
5341 does mean we need to force CONS into a register at this point. */
5342 cons = force_reg (mode, cons);
5343 /* With XTheadCondMov we need to force ALT into a register too. */
5344 alt = force_reg (mode, alt);
5345 emit_insn (gen_rtx_SET (dest, gen_rtx_IF_THEN_ELSE (mode, cond,
5346 cons, alt)));
5347 return true;
5348 }
5349 else if (!TARGET_ZICOND_LIKE)
5350 {
5351 if (invert)
5352 std::swap (cons, alt);
5353
5354 rtx reg1 = gen_reg_rtx (mode);
5355 rtx reg2 = gen_reg_rtx (mode);
5356 rtx reg3 = gen_reg_rtx (mode);
5357 rtx reg4 = gen_reg_rtx (mode);
5358
5359 riscv_emit_unary (NEG, reg1, tmp);
5360 riscv_emit_binary (AND, reg2, reg1, cons);
5361 riscv_emit_unary (NOT, reg3, reg1);
5362 riscv_emit_binary (AND, reg4, reg3, alt);
5363 riscv_emit_binary (IOR, dest, reg2, reg4);
5364 return true;
5365 }
5366 /* 0, reg or 0, imm */
5367 else if (cons == CONST0_RTX (mode)
5368 && (REG_P (alt)
5369 || (CONST_INT_P (alt) && alt != CONST0_RTX (mode))))
5370 {
5371 riscv_emit_int_compare (&code, &op0, &op1, true);
5372 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5373 alt = force_reg (mode, alt);
5374 emit_insn (gen_rtx_SET (dest,
5375 gen_rtx_IF_THEN_ELSE (mode, cond,
5376 cons, alt)));
5377 return true;
5378 }
5379 /* imm, imm */
5380 else if (CONST_INT_P (cons) && cons != CONST0_RTX (mode)
5381 && CONST_INT_P (alt) && alt != CONST0_RTX (mode))
5382 {
5383 riscv_emit_int_compare (&code, &op0, &op1, true);
5384 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5385 HOST_WIDE_INT t = INTVAL (alt) - INTVAL (cons);
5386 alt = force_reg (mode, gen_int_mode (t, mode));
5387 emit_insn (gen_rtx_SET (dest,
5388 gen_rtx_IF_THEN_ELSE (mode, cond,
5389 CONST0_RTX (mode),
5390 alt)));
5391 /* CONS might not fit into a signed 12 bit immediate suitable
5392 for an addi instruction. If that's the case, force it
5393 into a register. */
5394 if (!SMALL_OPERAND (INTVAL (cons)))
5395 cons = force_reg (mode, cons);
5396 riscv_emit_binary (PLUS, dest, dest, cons);
5397 return true;
5398 }
5399 /* imm, reg */
5400 else if (CONST_INT_P (cons) && cons != CONST0_RTX (mode) && REG_P (alt))
5401 {
5402 /* Optimize for register value of 0. */
5403 if (code == NE && rtx_equal_p (op0, alt) && op1 == CONST0_RTX (mode))
5404 {
5405 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5406 cons = force_reg (mode, cons);
5407 emit_insn (gen_rtx_SET (dest,
5408 gen_rtx_IF_THEN_ELSE (mode, cond,
5409 cons, alt)));
5410 return true;
5411 }
5412
5413 riscv_emit_int_compare (&code, &op0, &op1, true);
5414 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5415
5416 rtx temp1 = gen_reg_rtx (mode);
5417 rtx temp2 = gen_int_mode (-1 * INTVAL (cons), mode);
5418
5419 /* TEMP2 and/or CONS might not fit into a signed 12 bit immediate
5420 suitable for an addi instruction. If that's the case, force it
5421 into a register. */
5422 if (!SMALL_OPERAND (INTVAL (temp2)))
5423 temp2 = force_reg (mode, temp2);
5424 if (!SMALL_OPERAND (INTVAL (cons)))
5425 cons = force_reg (mode, cons);
5426
5427 riscv_emit_binary (PLUS, temp1, alt, temp2);
5428 emit_insn (gen_rtx_SET (dest,
5429 gen_rtx_IF_THEN_ELSE (mode, cond,
5430 CONST0_RTX (mode),
5431 temp1)));
5432 riscv_emit_binary (PLUS, dest, dest, cons);
5433 return true;
5434 }
5435 /* reg, 0 or imm, 0 */
5436 else if ((REG_P (cons)
5437 || (CONST_INT_P (cons) && cons != CONST0_RTX (mode)))
5438 && alt == CONST0_RTX (mode))
5439 {
5440 riscv_emit_int_compare (&code, &op0, &op1, true);
5441 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5442 cons = force_reg (mode, cons);
5443 emit_insn (gen_rtx_SET (dest, gen_rtx_IF_THEN_ELSE (mode, cond,
5444 cons, alt)));
5445 return true;
5446 }
5447 /* reg, imm */
5448 else if (REG_P (cons) && CONST_INT_P (alt) && alt != CONST0_RTX (mode))
5449 {
5450 /* Optimize for register value of 0. */
5451 if (code == EQ && rtx_equal_p (op0, cons) && op1 == CONST0_RTX (mode))
5452 {
5453 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5454 alt = force_reg (mode, alt);
5455 emit_insn (gen_rtx_SET (dest,
5456 gen_rtx_IF_THEN_ELSE (mode, cond,
5457 cons, alt)));
5458 return true;
5459 }
5460
5461 riscv_emit_int_compare (&code, &op0, &op1, true);
5462 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5463
5464 rtx temp1 = gen_reg_rtx (mode);
5465 rtx temp2 = gen_int_mode (-1 * INTVAL (alt), mode);
5466
5467 /* TEMP2 and/or ALT might not fit into a signed 12 bit immediate
5468 suitable for an addi instruction. If that's the case, force it
5469 into a register. */
5470 if (!SMALL_OPERAND (INTVAL (temp2)))
5471 temp2 = force_reg (mode, temp2);
5472 if (!SMALL_OPERAND (INTVAL (alt)))
5473 alt = force_reg (mode, alt);
5474
5475 riscv_emit_binary (PLUS, temp1, cons, temp2);
5476 emit_insn (gen_rtx_SET (dest,
5477 gen_rtx_IF_THEN_ELSE (mode, cond,
5478 temp1,
5479 CONST0_RTX (mode))));
5480 riscv_emit_binary (PLUS, dest, dest, alt);
5481 return true;
5482 }
5483 /* reg, reg */
5484 else if (REG_P (cons) && REG_P (alt))
5485 {
5486 if (((code == EQ && rtx_equal_p (cons, op0))
5487 || (code == NE && rtx_equal_p (alt, op0)))
5488 && op1 == CONST0_RTX (mode))
5489 {
5490 rtx cond = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5491 alt = force_reg (mode, alt);
5492 emit_insn (gen_rtx_SET (dest,
5493 gen_rtx_IF_THEN_ELSE (mode, cond,
5494 cons, alt)));
5495 return true;
5496 }
5497
5498 rtx reg1 = gen_reg_rtx (mode);
5499 rtx reg2 = gen_reg_rtx (mode);
5500 riscv_emit_int_compare (&code, &op0, &op1, true);
5501 rtx cond1 = gen_rtx_fmt_ee (code, GET_MODE (op0), op0, op1);
5502 rtx cond2 = gen_rtx_fmt_ee (code == NE ? EQ : NE,
5503 GET_MODE (op0), op0, op1);
5504 emit_insn (gen_rtx_SET (reg2,
5505 gen_rtx_IF_THEN_ELSE (mode, cond2,
5506 CONST0_RTX (mode),
5507 cons)));
5508 emit_insn (gen_rtx_SET (reg1,
5509 gen_rtx_IF_THEN_ELSE (mode, cond1,
5510 CONST0_RTX (mode),
5511 alt)));
5512 riscv_emit_binary (PLUS, dest, reg1, reg2);
5513 return true;
5514 }
5515 }
5516
5517 return false;
5518 }
5519
5520 /* Implement TARGET_FUNCTION_ARG_BOUNDARY. Every parameter gets at
5521 least PARM_BOUNDARY bits of alignment, but will be given anything up
5522 to PREFERRED_STACK_BOUNDARY bits if the type requires it. */
5523
5524 static unsigned int
5525 riscv_function_arg_boundary (machine_mode mode, const_tree type)
5526 {
5527 unsigned int alignment;
5528
5529 /* Use natural alignment if the type is not aggregate data. */
5530 if (type && !AGGREGATE_TYPE_P (type))
5531 alignment = TYPE_ALIGN (TYPE_MAIN_VARIANT (type));
5532 else
5533 alignment = type ? TYPE_ALIGN (type) : GET_MODE_ALIGNMENT (mode);
5534
5535 return MIN (PREFERRED_STACK_BOUNDARY, MAX (PARM_BOUNDARY, alignment));
5536 }
5537
5538 /* If MODE represents an argument that can be passed or returned in
5539 floating-point registers, return the number of registers, else 0. */
5540
5541 static unsigned
5542 riscv_pass_mode_in_fpr_p (machine_mode mode)
5543 {
5544 if (GET_MODE_UNIT_SIZE (mode) <= UNITS_PER_FP_ARG)
5545 {
5546 if (GET_MODE_CLASS (mode) == MODE_FLOAT)
5547 return 1;
5548
5549 if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
5550 return 2;
5551 }
5552
5553 return 0;
5554 }
5555
5556 typedef struct {
5557 const_tree type;
5558 HOST_WIDE_INT offset;
5559 } riscv_aggregate_field;
5560
5561 /* Identify subfields of aggregates that are candidates for passing in
5562 floating-point registers. */
5563
5564 static int
5565 riscv_flatten_aggregate_field (const_tree type,
5566 riscv_aggregate_field fields[2],
5567 int n, HOST_WIDE_INT offset,
5568 bool ignore_zero_width_bit_field_p)
5569 {
5570 switch (TREE_CODE (type))
5571 {
5572 case RECORD_TYPE:
5573 /* Can't handle incomplete types nor sizes that are not fixed. */
5574 if (!COMPLETE_TYPE_P (type)
5575 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
5576 || !tree_fits_uhwi_p (TYPE_SIZE (type)))
5577 return -1;
5578
5579 for (tree f = TYPE_FIELDS (type); f; f = DECL_CHAIN (f))
5580 if (TREE_CODE (f) == FIELD_DECL)
5581 {
5582 if (!TYPE_P (TREE_TYPE (f)))
5583 return -1;
5584
5585 /* The C++ front end strips zero-length bit-fields from structs.
5586 So we need to ignore them in the C front end to make C code
5587 compatible with C++ code. */
5588 if (ignore_zero_width_bit_field_p
5589 && DECL_BIT_FIELD (f)
5590 && (DECL_SIZE (f) == NULL_TREE
5591 || integer_zerop (DECL_SIZE (f))))
5592 ;
5593 else
5594 {
5595 HOST_WIDE_INT pos = offset + int_byte_position (f);
5596 n = riscv_flatten_aggregate_field (TREE_TYPE (f),
5597 fields, n, pos,
5598 ignore_zero_width_bit_field_p);
5599 }
5600 if (n < 0)
5601 return -1;
5602 }
5603 return n;
5604
5605 case ARRAY_TYPE:
5606 {
5607 HOST_WIDE_INT n_elts;
5608 riscv_aggregate_field subfields[2];
5609 tree index = TYPE_DOMAIN (type);
5610 tree elt_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
5611 int n_subfields = riscv_flatten_aggregate_field (TREE_TYPE (type),
5612 subfields, 0, offset,
5613 ignore_zero_width_bit_field_p);
5614
5615 /* Can't handle incomplete types nor sizes that are not fixed. */
5616 if (n_subfields <= 0
5617 || !COMPLETE_TYPE_P (type)
5618 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
5619 || !index
5620 || !TYPE_MAX_VALUE (index)
5621 || !tree_fits_uhwi_p (TYPE_MAX_VALUE (index))
5622 || !TYPE_MIN_VALUE (index)
5623 || !tree_fits_uhwi_p (TYPE_MIN_VALUE (index))
5624 || !tree_fits_uhwi_p (elt_size))
5625 return -1;
5626
5627 n_elts = 1 + tree_to_uhwi (TYPE_MAX_VALUE (index))
5628 - tree_to_uhwi (TYPE_MIN_VALUE (index));
5629 gcc_assert (n_elts >= 0);
5630
5631 for (HOST_WIDE_INT i = 0; i < n_elts; i++)
5632 for (int j = 0; j < n_subfields; j++)
5633 {
5634 if (n >= 2)
5635 return -1;
5636
5637 fields[n] = subfields[j];
5638 fields[n++].offset += i * tree_to_uhwi (elt_size);
5639 }
5640
5641 return n;
5642 }
5643
5644 case COMPLEX_TYPE:
5645 {
5646 /* Complex type need consume 2 field, so n must be 0. */
5647 if (n != 0)
5648 return -1;
5649
5650 HOST_WIDE_INT elt_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (type))).to_constant ();
5651
5652 if (elt_size <= UNITS_PER_FP_ARG)
5653 {
5654 fields[0].type = TREE_TYPE (type);
5655 fields[0].offset = offset;
5656 fields[1].type = TREE_TYPE (type);
5657 fields[1].offset = offset + elt_size;
5658
5659 return 2;
5660 }
5661
5662 return -1;
5663 }
5664
5665 default:
5666 if (n < 2
5667 && ((SCALAR_FLOAT_TYPE_P (type)
5668 && GET_MODE_SIZE (TYPE_MODE (type)).to_constant () <= UNITS_PER_FP_ARG)
5669 || (INTEGRAL_TYPE_P (type)
5670 && GET_MODE_SIZE (TYPE_MODE (type)).to_constant () <= UNITS_PER_WORD)))
5671 {
5672 fields[n].type = type;
5673 fields[n].offset = offset;
5674 return n + 1;
5675 }
5676 else
5677 return -1;
5678 }
5679 }
5680
5681 /* Identify candidate aggregates for passing in floating-point registers.
5682 Candidates have at most two fields after flattening. */
5683
5684 static int
5685 riscv_flatten_aggregate_argument (const_tree type,
5686 riscv_aggregate_field fields[2],
5687 bool ignore_zero_width_bit_field_p)
5688 {
5689 if (!type || TREE_CODE (type) != RECORD_TYPE)
5690 return -1;
5691
5692 return riscv_flatten_aggregate_field (type, fields, 0, 0,
5693 ignore_zero_width_bit_field_p);
5694 }
5695
5696 /* See whether TYPE is a record whose fields should be returned in one or
5697 two floating-point registers. If so, populate FIELDS accordingly. */
5698
5699 static unsigned
5700 riscv_pass_aggregate_in_fpr_pair_p (const_tree type,
5701 riscv_aggregate_field fields[2])
5702 {
5703 static int warned = 0;
5704
5705 /* This is the old ABI, which differs for C++ and C. */
5706 int n_old = riscv_flatten_aggregate_argument (type, fields, false);
5707 for (int i = 0; i < n_old; i++)
5708 if (!SCALAR_FLOAT_TYPE_P (fields[i].type))
5709 {
5710 n_old = -1;
5711 break;
5712 }
5713
5714 /* This is the new ABI, which is the same for C++ and C. */
5715 int n_new = riscv_flatten_aggregate_argument (type, fields, true);
5716 for (int i = 0; i < n_new; i++)
5717 if (!SCALAR_FLOAT_TYPE_P (fields[i].type))
5718 {
5719 n_new = -1;
5720 break;
5721 }
5722
5723 if ((n_old != n_new) && (warned == 0))
5724 {
5725 warning (OPT_Wpsabi, "ABI for flattened struct with zero-length "
5726 "bit-fields changed in GCC 10");
5727 warned = 1;
5728 }
5729
5730 return n_new > 0 ? n_new : 0;
5731 }
5732
5733 /* See whether TYPE is a record whose fields should be returned in one or
5734 floating-point register and one integer register. If so, populate
5735 FIELDS accordingly. */
5736
5737 static bool
5738 riscv_pass_aggregate_in_fpr_and_gpr_p (const_tree type,
5739 riscv_aggregate_field fields[2])
5740 {
5741 static int warned = 0;
5742
5743 /* This is the old ABI, which differs for C++ and C. */
5744 unsigned num_int_old = 0, num_float_old = 0;
5745 int n_old = riscv_flatten_aggregate_argument (type, fields, false);
5746 for (int i = 0; i < n_old; i++)
5747 {
5748 num_float_old += SCALAR_FLOAT_TYPE_P (fields[i].type);
5749 num_int_old += INTEGRAL_TYPE_P (fields[i].type);
5750 }
5751
5752 /* This is the new ABI, which is the same for C++ and C. */
5753 unsigned num_int_new = 0, num_float_new = 0;
5754 int n_new = riscv_flatten_aggregate_argument (type, fields, true);
5755 for (int i = 0; i < n_new; i++)
5756 {
5757 num_float_new += SCALAR_FLOAT_TYPE_P (fields[i].type);
5758 num_int_new += INTEGRAL_TYPE_P (fields[i].type);
5759 }
5760
5761 if (((num_int_old == 1 && num_float_old == 1
5762 && (num_int_old != num_int_new || num_float_old != num_float_new))
5763 || (num_int_new == 1 && num_float_new == 1
5764 && (num_int_old != num_int_new || num_float_old != num_float_new)))
5765 && (warned == 0))
5766 {
5767 warning (OPT_Wpsabi, "ABI for flattened struct with zero-length "
5768 "bit-fields changed in GCC 10");
5769 warned = 1;
5770 }
5771
5772 return num_int_new == 1 && num_float_new == 1;
5773 }
5774
5775 /* Return the representation of an argument passed or returned in an FPR
5776 when the value has mode VALUE_MODE and the type has TYPE_MODE. The
5777 two modes may be different for structures like:
5778
5779 struct __attribute__((packed)) foo { float f; }
5780
5781 where the SFmode value "f" is passed in REGNO but the struct itself
5782 has mode BLKmode. */
5783
5784 static rtx
5785 riscv_pass_fpr_single (machine_mode type_mode, unsigned regno,
5786 machine_mode value_mode,
5787 HOST_WIDE_INT offset)
5788 {
5789 rtx x = gen_rtx_REG (value_mode, regno);
5790
5791 if (type_mode != value_mode)
5792 {
5793 x = gen_rtx_EXPR_LIST (VOIDmode, x, GEN_INT (offset));
5794 x = gen_rtx_PARALLEL (type_mode, gen_rtvec (1, x));
5795 }
5796 return x;
5797 }
5798
5799 /* Pass or return a composite value in the FPR pair REGNO and REGNO + 1.
5800 MODE is the mode of the composite. MODE1 and OFFSET1 are the mode and
5801 byte offset for the first value, likewise MODE2 and OFFSET2 for the
5802 second value. */
5803
5804 static rtx
5805 riscv_pass_fpr_pair (machine_mode mode, unsigned regno1,
5806 machine_mode mode1, HOST_WIDE_INT offset1,
5807 unsigned regno2, machine_mode mode2,
5808 HOST_WIDE_INT offset2)
5809 {
5810 return gen_rtx_PARALLEL
5811 (mode,
5812 gen_rtvec (2,
5813 gen_rtx_EXPR_LIST (VOIDmode,
5814 gen_rtx_REG (mode1, regno1),
5815 GEN_INT (offset1)),
5816 gen_rtx_EXPR_LIST (VOIDmode,
5817 gen_rtx_REG (mode2, regno2),
5818 GEN_INT (offset2))));
5819 }
5820
5821 static rtx
5822 riscv_pass_vls_aggregate_in_gpr (struct riscv_arg_info *info, machine_mode mode,
5823 unsigned gpr_base)
5824 {
5825 gcc_assert (riscv_v_ext_vls_mode_p (mode));
5826
5827 unsigned count = 0;
5828 unsigned regnum = 0;
5829 machine_mode gpr_mode = VOIDmode;
5830 unsigned vls_size = GET_MODE_SIZE (mode).to_constant ();
5831 unsigned gpr_size = GET_MODE_SIZE (Xmode);
5832
5833 if (IN_RANGE (vls_size, 0, gpr_size * 2))
5834 {
5835 count = riscv_v_vls_mode_aggregate_gpr_count (vls_size, gpr_size);
5836
5837 if (count + info->gpr_offset <= MAX_ARGS_IN_REGISTERS)
5838 {
5839 regnum = gpr_base + info->gpr_offset;
5840 info->num_gprs = count;
5841 gpr_mode = riscv_v_vls_to_gpr_mode (vls_size);
5842 }
5843 }
5844
5845 if (!regnum)
5846 return NULL_RTX; /* Return NULL_RTX if we cannot find a suitable reg. */
5847
5848 gcc_assert (gpr_mode != VOIDmode);
5849
5850 rtx reg = gen_rtx_REG (gpr_mode, regnum);
5851 rtx x = gen_rtx_EXPR_LIST (VOIDmode, reg, CONST0_RTX (gpr_mode));
5852
5853 return gen_rtx_PARALLEL (mode, gen_rtvec (1, x));
5854 }
5855
5856 /* Initialize a variable CUM of type CUMULATIVE_ARGS
5857 for a call to a function whose data type is FNTYPE.
5858 For a library call, FNTYPE is 0. */
5859
5860 void
5861 riscv_init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype, rtx, tree, int)
5862 {
5863 memset (cum, 0, sizeof (*cum));
5864
5865 if (fntype)
5866 cum->variant_cc = (riscv_cc) fntype_abi (fntype).id ();
5867 else
5868 cum->variant_cc = RISCV_CC_BASE;
5869 }
5870
5871 /* Return true if TYPE is a vector type that can be passed in vector registers.
5872 */
5873
5874 static bool
5875 riscv_vector_type_p (const_tree type)
5876 {
5877 /* Currently, only builtin scalable vector type is allowed, in the future,
5878 more vector types may be allowed, such as GNU vector type, etc. */
5879 return riscv_vector::builtin_type_p (type);
5880 }
5881
5882 static unsigned int
5883 riscv_hard_regno_nregs (unsigned int regno, machine_mode mode);
5884
5885 /* Subroutine of riscv_get_arg_info. */
5886
5887 static rtx
5888 riscv_get_vector_arg (struct riscv_arg_info *info, const CUMULATIVE_ARGS *cum,
5889 machine_mode mode, bool return_p)
5890 {
5891 gcc_assert (riscv_v_ext_mode_p (mode));
5892
5893 info->mr_offset = cum->num_mrs;
5894 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
5895 {
5896 /* For scalable mask return value. */
5897 if (return_p)
5898 return gen_rtx_REG (mode, V_REG_FIRST);
5899
5900 /* For the first scalable mask argument. */
5901 if (info->mr_offset < MAX_ARGS_IN_MASK_REGISTERS)
5902 {
5903 info->num_mrs = 1;
5904 return gen_rtx_REG (mode, V_REG_FIRST);
5905 }
5906 else
5907 {
5908 /* Rest scalable mask arguments are treated as scalable data
5909 arguments. */
5910 }
5911 }
5912
5913 /* The number and alignment of vector registers need for this scalable vector
5914 argument. When the mode size is less than a full vector, we use 1 vector
5915 register to pass. Just call TARGET_HARD_REGNO_NREGS for the number
5916 information. */
5917 int nregs = riscv_hard_regno_nregs (V_ARG_FIRST, mode);
5918 int LMUL = riscv_v_ext_tuple_mode_p (mode)
5919 ? nregs / riscv_vector::get_nf (mode)
5920 : nregs;
5921 int arg_reg_start = V_ARG_FIRST - V_REG_FIRST;
5922 int arg_reg_end = V_ARG_LAST - V_REG_FIRST;
5923 int aligned_reg_start = ROUND_UP (arg_reg_start, LMUL);
5924
5925 /* For scalable data and scalable tuple return value. */
5926 if (return_p)
5927 return gen_rtx_REG (mode, aligned_reg_start + V_REG_FIRST);
5928
5929 /* Iterate through the USED_VRS array to find vector register groups that have
5930 not been allocated and the first register is aligned with LMUL. */
5931 for (int i = aligned_reg_start; i + nregs - 1 <= arg_reg_end; i += LMUL)
5932 {
5933 /* The index in USED_VRS array. */
5934 int idx = i - arg_reg_start;
5935 /* Find the first register unused. */
5936 if (!cum->used_vrs[idx])
5937 {
5938 bool find_set = true;
5939 /* Ensure there are NREGS continuous unused registers. */
5940 for (int j = 1; j < nregs; j++)
5941 if (cum->used_vrs[idx + j])
5942 {
5943 find_set = false;
5944 /* Update I to the last aligned register which
5945 cannot be used and the next iteration will add
5946 LMUL step to I. */
5947 i += (j / LMUL) * LMUL;
5948 break;
5949 }
5950
5951 if (find_set)
5952 {
5953 info->num_vrs = nregs;
5954 info->vr_offset = idx;
5955 return gen_rtx_REG (mode, i + V_REG_FIRST);
5956 }
5957 }
5958 }
5959
5960 return NULL_RTX;
5961 }
5962
5963 /* Fill INFO with information about a single argument, and return an RTL
5964 pattern to pass or return the argument. Return NULL_RTX if argument cannot
5965 pass or return in registers, then the argument may be passed by reference or
5966 through the stack or . CUM is the cumulative state for earlier arguments.
5967 MODE is the mode of this argument and TYPE is its type (if known). NAMED is
5968 true if this is a named (fixed) argument rather than a variable one. RETURN_P
5969 is true if returning the argument, or false if passing the argument. */
5970
5971 static rtx
5972 riscv_get_arg_info (struct riscv_arg_info *info, const CUMULATIVE_ARGS *cum,
5973 machine_mode mode, const_tree type, bool named,
5974 bool return_p)
5975 {
5976 unsigned num_bytes, num_words;
5977 unsigned fpr_base = return_p ? FP_RETURN : FP_ARG_FIRST;
5978 unsigned gpr_base = return_p ? GP_RETURN : GP_ARG_FIRST;
5979 unsigned alignment = riscv_function_arg_boundary (mode, type);
5980
5981 memset (info, 0, sizeof (*info));
5982 info->gpr_offset = cum->num_gprs;
5983 info->fpr_offset = cum->num_fprs;
5984
5985 /* Passed by reference when the scalable vector argument is anonymous. */
5986 if (riscv_v_ext_mode_p (mode) && !named)
5987 return NULL_RTX;
5988
5989 if (named)
5990 {
5991 riscv_aggregate_field fields[2];
5992 unsigned fregno = fpr_base + info->fpr_offset;
5993 unsigned gregno = gpr_base + info->gpr_offset;
5994
5995 /* Pass one- or two-element floating-point aggregates in FPRs. */
5996 if ((info->num_fprs = riscv_pass_aggregate_in_fpr_pair_p (type, fields))
5997 && info->fpr_offset + info->num_fprs <= MAX_ARGS_IN_REGISTERS)
5998 switch (info->num_fprs)
5999 {
6000 case 1:
6001 return riscv_pass_fpr_single (mode, fregno,
6002 TYPE_MODE (fields[0].type),
6003 fields[0].offset);
6004
6005 case 2:
6006 return riscv_pass_fpr_pair (mode, fregno,
6007 TYPE_MODE (fields[0].type),
6008 fields[0].offset,
6009 fregno + 1,
6010 TYPE_MODE (fields[1].type),
6011 fields[1].offset);
6012
6013 default:
6014 gcc_unreachable ();
6015 }
6016
6017 /* Pass real and complex floating-point numbers in FPRs. */
6018 if ((info->num_fprs = riscv_pass_mode_in_fpr_p (mode))
6019 && info->fpr_offset + info->num_fprs <= MAX_ARGS_IN_REGISTERS)
6020 switch (GET_MODE_CLASS (mode))
6021 {
6022 case MODE_FLOAT:
6023 return gen_rtx_REG (mode, fregno);
6024
6025 case MODE_COMPLEX_FLOAT:
6026 return riscv_pass_fpr_pair (mode, fregno, GET_MODE_INNER (mode), 0,
6027 fregno + 1, GET_MODE_INNER (mode),
6028 GET_MODE_UNIT_SIZE (mode));
6029
6030 default:
6031 gcc_unreachable ();
6032 }
6033
6034 /* Pass structs with one float and one integer in an FPR and a GPR. */
6035 if (riscv_pass_aggregate_in_fpr_and_gpr_p (type, fields)
6036 && info->gpr_offset < MAX_ARGS_IN_REGISTERS
6037 && info->fpr_offset < MAX_ARGS_IN_REGISTERS)
6038 {
6039 info->num_gprs = 1;
6040 info->num_fprs = 1;
6041
6042 if (!SCALAR_FLOAT_TYPE_P (fields[0].type))
6043 std::swap (fregno, gregno);
6044
6045 return riscv_pass_fpr_pair (mode, fregno, TYPE_MODE (fields[0].type),
6046 fields[0].offset,
6047 gregno, TYPE_MODE (fields[1].type),
6048 fields[1].offset);
6049 }
6050
6051 /* For scalable vector argument. */
6052 if (riscv_vector_type_p (type) && riscv_v_ext_mode_p (mode))
6053 return riscv_get_vector_arg (info, cum, mode, return_p);
6054
6055 /* For vls mode aggregated in gpr. */
6056 if (riscv_v_ext_vls_mode_p (mode))
6057 return riscv_pass_vls_aggregate_in_gpr (info, mode, gpr_base);
6058 }
6059
6060 /* Work out the size of the argument. */
6061 num_bytes = type ? int_size_in_bytes (type) : GET_MODE_SIZE (mode).to_constant ();
6062 num_words = (num_bytes + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
6063
6064 /* Doubleword-aligned varargs start on an even register boundary. */
6065 if (!named && num_bytes != 0 && alignment > BITS_PER_WORD)
6066 info->gpr_offset += info->gpr_offset & 1;
6067
6068 /* Partition the argument between registers and stack. */
6069 info->num_fprs = 0;
6070 info->num_gprs = MIN (num_words, MAX_ARGS_IN_REGISTERS - info->gpr_offset);
6071 info->stack_p = (num_words - info->num_gprs) != 0;
6072
6073 if (info->num_gprs || return_p)
6074 return gen_rtx_REG (mode, gpr_base + info->gpr_offset);
6075
6076 return NULL_RTX;
6077 }
6078
6079 /* Implement TARGET_FUNCTION_ARG. */
6080
6081 static rtx
6082 riscv_function_arg (cumulative_args_t cum_v, const function_arg_info &arg)
6083 {
6084 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
6085 struct riscv_arg_info info;
6086
6087 if (arg.end_marker_p ())
6088 /* Return the calling convention that used by the current function. */
6089 return gen_int_mode (cum->variant_cc, SImode);
6090
6091 return riscv_get_arg_info (&info, cum, arg.mode, arg.type, arg.named, false);
6092 }
6093
6094 /* Implement TARGET_FUNCTION_ARG_ADVANCE. */
6095
6096 static void
6097 riscv_function_arg_advance (cumulative_args_t cum_v,
6098 const function_arg_info &arg)
6099 {
6100 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
6101 struct riscv_arg_info info;
6102
6103 riscv_get_arg_info (&info, cum, arg.mode, arg.type, arg.named, false);
6104
6105 /* Set the corresponding register in USED_VRS to used status. */
6106 for (unsigned int i = 0; i < info.num_vrs; i++)
6107 {
6108 gcc_assert (!cum->used_vrs[info.vr_offset + i]);
6109 cum->used_vrs[info.vr_offset + i] = true;
6110 }
6111
6112 if ((info.num_vrs > 0 || info.num_mrs > 0) && cum->variant_cc != RISCV_CC_V)
6113 {
6114 error ("RVV type %qT cannot be passed to an unprototyped function",
6115 arg.type);
6116 /* Avoid repeating the message */
6117 cum->variant_cc = RISCV_CC_V;
6118 }
6119
6120 /* Advance the register count. This has the effect of setting
6121 num_gprs to MAX_ARGS_IN_REGISTERS if a doubleword-aligned
6122 argument required us to skip the final GPR and pass the whole
6123 argument on the stack. */
6124 cum->num_fprs = info.fpr_offset + info.num_fprs;
6125 cum->num_gprs = info.gpr_offset + info.num_gprs;
6126 cum->num_mrs = info.mr_offset + info.num_mrs;
6127 }
6128
6129 /* Implement TARGET_ARG_PARTIAL_BYTES. */
6130
6131 static int
6132 riscv_arg_partial_bytes (cumulative_args_t cum,
6133 const function_arg_info &generic_arg)
6134 {
6135 struct riscv_arg_info arg;
6136
6137 riscv_get_arg_info (&arg, get_cumulative_args (cum), generic_arg.mode,
6138 generic_arg.type, generic_arg.named, false);
6139 return arg.stack_p ? arg.num_gprs * UNITS_PER_WORD : 0;
6140 }
6141
6142 /* Implement FUNCTION_VALUE and LIBCALL_VALUE. For normal calls,
6143 VALTYPE is the return type and MODE is VOIDmode. For libcalls,
6144 VALTYPE is null and MODE is the mode of the return value. */
6145
6146 rtx
6147 riscv_function_value (const_tree type, const_tree func, machine_mode mode)
6148 {
6149 struct riscv_arg_info info;
6150 CUMULATIVE_ARGS args;
6151
6152 if (type)
6153 {
6154 int unsigned_p = TYPE_UNSIGNED (type);
6155
6156 mode = TYPE_MODE (type);
6157
6158 /* Since TARGET_PROMOTE_FUNCTION_MODE unconditionally promotes,
6159 return values, promote the mode here too. */
6160 mode = promote_function_mode (type, mode, &unsigned_p, func, 1);
6161 }
6162
6163 memset (&args, 0, sizeof args);
6164
6165 return riscv_get_arg_info (&info, &args, mode, type, true, true);
6166 }
6167
6168 /* Implement TARGET_PASS_BY_REFERENCE. */
6169
6170 static bool
6171 riscv_pass_by_reference (cumulative_args_t cum_v, const function_arg_info &arg)
6172 {
6173 HOST_WIDE_INT size = arg.type_size_in_bytes ().to_constant ();;
6174 struct riscv_arg_info info;
6175 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
6176
6177 /* ??? std_gimplify_va_arg_expr passes NULL for cum. Fortunately, we
6178 never pass variadic arguments in floating-point and vector registers,
6179 so we can avoid the call to riscv_get_arg_info in this case. */
6180 if (cum != NULL)
6181 {
6182 riscv_get_arg_info (&info, cum, arg.mode, arg.type, arg.named, false);
6183
6184 /* Don't pass by reference if we can use a floating-point register. */
6185 if (info.num_fprs)
6186 return false;
6187
6188 /* Don't pass by reference if we can use general register(s) for vls. */
6189 if (info.num_gprs && riscv_v_ext_vls_mode_p (arg.mode))
6190 return false;
6191
6192 /* Don't pass by reference if we can use vector register groups. */
6193 if (info.num_vrs > 0 || info.num_mrs > 0)
6194 return false;
6195 }
6196
6197 /* Passed by reference when:
6198 1. The scalable vector argument is anonymous.
6199 2. Args cannot be passed through vector registers. */
6200 if (riscv_v_ext_mode_p (arg.mode))
6201 return true;
6202
6203 /* Pass by reference if the data do not fit in two integer registers. */
6204 return !IN_RANGE (size, 0, 2 * UNITS_PER_WORD);
6205 }
6206
6207 /* Implement TARGET_RETURN_IN_MEMORY. */
6208
6209 static bool
6210 riscv_return_in_memory (const_tree type, const_tree fndecl ATTRIBUTE_UNUSED)
6211 {
6212 CUMULATIVE_ARGS args;
6213 cumulative_args_t cum = pack_cumulative_args (&args);
6214
6215 /* The rules for returning in memory are the same as for passing the
6216 first named argument by reference. */
6217 memset (&args, 0, sizeof args);
6218 function_arg_info arg (const_cast<tree> (type), /*named=*/true);
6219 return riscv_pass_by_reference (cum, arg);
6220 }
6221
6222 /* Implement TARGET_SETUP_INCOMING_VARARGS. */
6223
6224 static void
6225 riscv_setup_incoming_varargs (cumulative_args_t cum,
6226 const function_arg_info &arg,
6227 int *pretend_size ATTRIBUTE_UNUSED, int no_rtl)
6228 {
6229 CUMULATIVE_ARGS local_cum;
6230 int gp_saved;
6231
6232 /* The caller has advanced CUM up to, but not beyond, the last named
6233 argument. Advance a local copy of CUM past the last "real" named
6234 argument, to find out how many registers are left over. */
6235 local_cum = *get_cumulative_args (cum);
6236 if (!TYPE_NO_NAMED_ARGS_STDARG_P (TREE_TYPE (current_function_decl))
6237 || arg.type != NULL_TREE)
6238 riscv_function_arg_advance (pack_cumulative_args (&local_cum), arg);
6239
6240 /* Found out how many registers we need to save. */
6241 gp_saved = MAX_ARGS_IN_REGISTERS - local_cum.num_gprs;
6242
6243 if (!no_rtl && gp_saved > 0)
6244 {
6245 rtx ptr = plus_constant (Pmode, virtual_incoming_args_rtx,
6246 REG_PARM_STACK_SPACE (cfun->decl)
6247 - gp_saved * UNITS_PER_WORD);
6248 rtx mem = gen_frame_mem (BLKmode, ptr);
6249 set_mem_alias_set (mem, get_varargs_alias_set ());
6250
6251 move_block_from_reg (local_cum.num_gprs + GP_ARG_FIRST,
6252 mem, gp_saved);
6253 }
6254 if (REG_PARM_STACK_SPACE (cfun->decl) == 0)
6255 cfun->machine->varargs_size = gp_saved * UNITS_PER_WORD;
6256 }
6257
6258 /* Return the descriptor of the Standard Vector Calling Convention Variant. */
6259
6260 static const predefined_function_abi &
6261 riscv_v_abi ()
6262 {
6263 predefined_function_abi &v_abi = function_abis[RISCV_CC_V];
6264 if (!v_abi.initialized_p ())
6265 {
6266 HARD_REG_SET full_reg_clobbers
6267 = default_function_abi.full_reg_clobbers ();
6268 /* Callee-saved vector registers: v1-v7, v24-v31. */
6269 for (int regno = V_REG_FIRST + 1; regno <= V_REG_FIRST + 7; regno += 1)
6270 CLEAR_HARD_REG_BIT (full_reg_clobbers, regno);
6271 for (int regno = V_REG_FIRST + 24; regno <= V_REG_FIRST + 31; regno += 1)
6272 CLEAR_HARD_REG_BIT (full_reg_clobbers, regno);
6273 v_abi.initialize (RISCV_CC_V, full_reg_clobbers);
6274 }
6275 return v_abi;
6276 }
6277
6278 static bool
6279 riscv_vector_int_type_p (const_tree type)
6280 {
6281 machine_mode mode = TYPE_MODE (type);
6282
6283 if (VECTOR_MODE_P (mode))
6284 return INTEGRAL_MODE_P (GET_MODE_INNER (mode));
6285
6286 const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
6287 return strstr (name, "int") != NULL || strstr (name, "uint") != NULL;
6288 }
6289
6290 bool
6291 riscv_vector_float_type_p (const_tree type)
6292 {
6293 if (!riscv_vector_type_p (type))
6294 return false;
6295
6296 machine_mode mode = TYPE_MODE (type);
6297
6298 if (VECTOR_MODE_P (mode))
6299 return FLOAT_MODE_P (GET_MODE_INNER (mode));
6300
6301 const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
6302 return strstr (name, "vfloat") != NULL;
6303 }
6304
6305 static int
6306 riscv_vector_element_bitsize (const_tree type)
6307 {
6308 machine_mode mode = TYPE_MODE (type);
6309
6310 if (VECTOR_MODE_P (mode))
6311 return GET_MODE_BITSIZE (GET_MODE_INNER (mode));
6312
6313 const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
6314
6315 if (strstr (name, "bool") != NULL)
6316 return 1;
6317 else if (strstr (name, "int8") != NULL)
6318 return 8;
6319 else if (strstr (name, "int16") != NULL || strstr (name, "float16") != NULL)
6320 return 16;
6321 else if (strstr (name, "int32") != NULL || strstr (name, "float32") != NULL)
6322 return 32;
6323 else if (strstr (name, "int64") != NULL || strstr (name, "float64") != NULL)
6324 return 64;
6325
6326 gcc_unreachable ();
6327 }
6328
6329 static int
6330 riscv_vector_required_min_vlen (const_tree type)
6331 {
6332 machine_mode mode = TYPE_MODE (type);
6333
6334 if (riscv_v_ext_mode_p (mode))
6335 return TARGET_MIN_VLEN;
6336
6337 int element_bitsize = riscv_vector_element_bitsize (type);
6338 const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
6339
6340 if (strstr (name, "bool64") != NULL)
6341 return element_bitsize * 64;
6342 else if (strstr (name, "bool32") != NULL)
6343 return element_bitsize * 32;
6344 else if (strstr (name, "bool16") != NULL)
6345 return element_bitsize * 16;
6346 else if (strstr (name, "bool8") != NULL)
6347 return element_bitsize * 8;
6348 else if (strstr (name, "bool4") != NULL)
6349 return element_bitsize * 4;
6350 else if (strstr (name, "bool2") != NULL)
6351 return element_bitsize * 2;
6352
6353 if (strstr (name, "mf8") != NULL)
6354 return element_bitsize * 8;
6355 else if (strstr (name, "mf4") != NULL)
6356 return element_bitsize * 4;
6357 else if (strstr (name, "mf2") != NULL)
6358 return element_bitsize * 2;
6359
6360 return element_bitsize;
6361 }
6362
6363 static void
6364 riscv_validate_vector_type (const_tree type, const char *hint)
6365 {
6366 gcc_assert (riscv_vector_type_p (type));
6367
6368 if (!TARGET_VECTOR)
6369 {
6370 error_at (input_location, "%s %qT requires the V ISA extension",
6371 hint, type);
6372 return;
6373 }
6374
6375 int element_bitsize = riscv_vector_element_bitsize (type);
6376 bool int_type_p = riscv_vector_int_type_p (type);
6377
6378 if (int_type_p && element_bitsize == 64
6379 && !TARGET_VECTOR_ELEN_64_P (riscv_vector_elen_flags))
6380 {
6381 error_at (input_location,
6382 "%s %qT requires the zve64x, zve64f, zve64d or v ISA extension",
6383 hint, type);
6384 return;
6385 }
6386
6387 bool float_type_p = riscv_vector_float_type_p (type);
6388
6389 if (float_type_p && element_bitsize == 16
6390 && (!TARGET_VECTOR_ELEN_FP_16_P (riscv_vector_elen_flags)
6391 && !TARGET_VECTOR_ELEN_BF_16_P (riscv_vector_elen_flags)))
6392 {
6393 const char *name = IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (type)));
6394 if (strstr (name, "vfloat"))
6395 error_at (input_location,
6396 "%s %qT requires the zvfhmin or zvfh ISA extension",
6397 hint, type);
6398 return;
6399 }
6400
6401 if (float_type_p && element_bitsize == 32
6402 && !TARGET_VECTOR_ELEN_FP_32_P (riscv_vector_elen_flags))
6403 {
6404 error_at (input_location,
6405 "%s %qT requires the zve32f, zve64f, zve64d or v ISA extension",
6406 hint, type);
6407 return;
6408 }
6409
6410 if (float_type_p && element_bitsize == 64
6411 && !TARGET_VECTOR_ELEN_FP_64_P (riscv_vector_elen_flags))
6412 {
6413 error_at (input_location,
6414 "%s %qT requires the zve64d or v ISA extension", hint, type);
6415 return;
6416 }
6417
6418 int required_min_vlen = riscv_vector_required_min_vlen (type);
6419
6420 if (TARGET_MIN_VLEN < required_min_vlen)
6421 {
6422 error_at (
6423 input_location,
6424 "%s %qT requires the minimal vector length %qd but %qd is given",
6425 hint, type, required_min_vlen, TARGET_MIN_VLEN);
6426 return;
6427 }
6428 }
6429
6430 /* Return true if a function with type FNTYPE returns its value in
6431 RISC-V V registers. */
6432
6433 static bool
6434 riscv_return_value_is_vector_type_p (const_tree fntype)
6435 {
6436 tree return_type = TREE_TYPE (fntype);
6437
6438 if (riscv_vector_type_p (return_type))
6439 {
6440 riscv_validate_vector_type (return_type, "return type");
6441 return true;
6442 }
6443 else
6444 return false;
6445 }
6446
6447 /* Return true if a function with type FNTYPE takes arguments in
6448 RISC-V V registers. */
6449
6450 static bool
6451 riscv_arguments_is_vector_type_p (const_tree fntype)
6452 {
6453 for (tree chain = TYPE_ARG_TYPES (fntype); chain && chain != void_list_node;
6454 chain = TREE_CHAIN (chain))
6455 {
6456 tree arg_type = TREE_VALUE (chain);
6457 if (riscv_vector_type_p (arg_type))
6458 {
6459 riscv_validate_vector_type (arg_type, "argument type");
6460 return true;
6461 }
6462 }
6463
6464 return false;
6465 }
6466
6467 /* Return true if FUNC is a riscv_vector_cc function.
6468 For more details please reference the below link.
6469 https://github.com/riscv-non-isa/riscv-c-api-doc/pull/67 */
6470 static bool
6471 riscv_vector_cc_function_p (const_tree fntype)
6472 {
6473 tree attr = TYPE_ATTRIBUTES (fntype);
6474 bool vector_cc_p = lookup_attribute ("vector_cc", attr) != NULL_TREE
6475 || lookup_attribute ("riscv_vector_cc", attr) != NULL_TREE;
6476
6477 if (vector_cc_p && !TARGET_VECTOR)
6478 error_at (input_location,
6479 "function attribute %qs requires the V ISA extension",
6480 "riscv_vector_cc");
6481
6482 return vector_cc_p;
6483 }
6484
6485 /* Implement TARGET_FNTYPE_ABI. */
6486
6487 static const predefined_function_abi &
6488 riscv_fntype_abi (const_tree fntype)
6489 {
6490 /* Implement the vector calling convention. For more details please
6491 reference the below link.
6492 https://github.com/riscv-non-isa/riscv-elf-psabi-doc/pull/389 */
6493 bool validate_v_abi_p = false;
6494
6495 validate_v_abi_p |= riscv_return_value_is_vector_type_p (fntype);
6496 validate_v_abi_p |= riscv_arguments_is_vector_type_p (fntype);
6497 validate_v_abi_p |= riscv_vector_cc_function_p (fntype);
6498
6499 if (validate_v_abi_p)
6500 return riscv_v_abi ();
6501
6502 return default_function_abi;
6503 }
6504
6505 /* Return riscv calling convention of call_insn. */
6506 riscv_cc
6507 get_riscv_cc (const rtx use)
6508 {
6509 gcc_assert (GET_CODE (use) == USE);
6510 rtx unspec = XEXP (use, 0);
6511 gcc_assert (GET_CODE (unspec) == UNSPEC
6512 && XINT (unspec, 1) == UNSPEC_CALLEE_CC);
6513 riscv_cc cc = (riscv_cc) INTVAL (XVECEXP (unspec, 0, 0));
6514 gcc_assert (cc < RISCV_CC_UNKNOWN);
6515 return cc;
6516 }
6517
6518 /* Implement TARGET_INSN_CALLEE_ABI. */
6519
6520 const predefined_function_abi &
6521 riscv_insn_callee_abi (const rtx_insn *insn)
6522 {
6523 rtx pat = PATTERN (insn);
6524 gcc_assert (GET_CODE (pat) == PARALLEL);
6525 riscv_cc cc = get_riscv_cc (XVECEXP (pat, 0, 1));
6526 return function_abis[cc];
6527 }
6528
6529 /* Handle an attribute requiring a FUNCTION_DECL;
6530 arguments as in struct attribute_spec.handler. */
6531 static tree
6532 riscv_handle_fndecl_attribute (tree *node, tree name,
6533 tree args ATTRIBUTE_UNUSED,
6534 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
6535 {
6536 if (TREE_CODE (*node) != FUNCTION_DECL)
6537 {
6538 warning (OPT_Wattributes, "%qE attribute only applies to functions",
6539 name);
6540 *no_add_attrs = true;
6541 }
6542
6543 return NULL_TREE;
6544 }
6545
6546 /* Verify type based attributes. NODE is the what the attribute is being
6547 applied to. NAME is the attribute name. ARGS are the attribute args.
6548 FLAGS gives info about the context. NO_ADD_ATTRS should be set to true if
6549 the attribute should be ignored. */
6550
6551 static tree
6552 riscv_handle_type_attribute (tree *node ATTRIBUTE_UNUSED, tree name, tree args,
6553 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
6554 {
6555 /* Check for an argument. */
6556 if (is_attribute_p ("interrupt", name))
6557 {
6558 if (args)
6559 {
6560 tree cst = TREE_VALUE (args);
6561 const char *string;
6562
6563 if (TREE_CODE (cst) != STRING_CST)
6564 {
6565 warning (OPT_Wattributes,
6566 "%qE attribute requires a string argument",
6567 name);
6568 *no_add_attrs = true;
6569 return NULL_TREE;
6570 }
6571
6572 string = TREE_STRING_POINTER (cst);
6573 if (strcmp (string, "user") && strcmp (string, "supervisor")
6574 && strcmp (string, "machine"))
6575 {
6576 warning (OPT_Wattributes,
6577 "argument to %qE attribute is not %<\"user\"%>, %<\"supervisor\"%>, "
6578 "or %<\"machine\"%>", name);
6579 *no_add_attrs = true;
6580 }
6581 }
6582 }
6583
6584 return NULL_TREE;
6585 }
6586
6587 static tree
6588 riscv_handle_rvv_vector_bits_attribute (tree *node, tree name, tree args,
6589 ATTRIBUTE_UNUSED int flags,
6590 bool *no_add_attrs)
6591 {
6592 if (!is_attribute_p ("riscv_rvv_vector_bits", name))
6593 return NULL_TREE;
6594
6595 *no_add_attrs = true;
6596
6597 if (rvv_vector_bits != RVV_VECTOR_BITS_ZVL)
6598 {
6599 error (
6600 "%qs is only supported when %<-mrvv-vector-bits=zvl%> is specified",
6601 "riscv_rvv_vector_bits");
6602 return NULL_TREE;
6603 }
6604
6605 tree type = *node;
6606
6607 if (!VECTOR_TYPE_P (type) || !riscv_vector::builtin_type_p (type))
6608 {
6609 error ("%qs applied to non-RVV type %qT", "riscv_rvv_vector_bits", type);
6610 return NULL_TREE;
6611 }
6612
6613 tree size = TREE_VALUE (args);
6614
6615 if (TREE_CODE (size) != INTEGER_CST)
6616 {
6617 error ("%qs requires an integer constant", "riscv_rvv_vector_bits");
6618 return NULL_TREE;
6619 }
6620
6621 unsigned HOST_WIDE_INT args_in_bits = tree_to_uhwi (size);
6622 unsigned HOST_WIDE_INT type_mode_bits
6623 = GET_MODE_PRECISION (TYPE_MODE (type)).to_constant ();
6624
6625 if (args_in_bits != type_mode_bits)
6626 {
6627 error ("invalid RVV vector size %qd, "
6628 "expected size is %qd based on LMUL of type and %qs",
6629 (int)args_in_bits, (int)type_mode_bits, "-mrvv-vector-bits=zvl");
6630 return NULL_TREE;
6631 }
6632
6633 type = build_distinct_type_copy (type);
6634 TYPE_ATTRIBUTES (type)
6635 = remove_attribute ("RVV sizeless type",
6636 copy_list (TYPE_ATTRIBUTES (type)));
6637
6638 /* The operations like alu/cmp on vbool*_t is not well defined,
6639 continue to treat vbool*_t as indivisible. */
6640 if (!VECTOR_BOOLEAN_TYPE_P (type))
6641 TYPE_INDIVISIBLE_P (type) = 0;
6642
6643 *node = type;
6644
6645 return NULL_TREE;
6646 }
6647
6648 /* Return true if function TYPE is an interrupt function. */
6649 static bool
6650 riscv_interrupt_type_p (tree type)
6651 {
6652 return lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type)) != NULL;
6653 }
6654
6655 /* Return true if FUNC is a naked function. */
6656 static bool
6657 riscv_naked_function_p (tree func)
6658 {
6659 tree func_decl = func;
6660 if (func == NULL_TREE)
6661 func_decl = current_function_decl;
6662 return NULL_TREE != lookup_attribute ("naked", DECL_ATTRIBUTES (func_decl));
6663 }
6664
6665 /* Implement TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS. */
6666 static bool
6667 riscv_allocate_stack_slots_for_args ()
6668 {
6669 /* Naked functions should not allocate stack slots for arguments. */
6670 return !riscv_naked_function_p (current_function_decl);
6671 }
6672
6673 /* Implement TARGET_WARN_FUNC_RETURN. */
6674 static bool
6675 riscv_warn_func_return (tree decl)
6676 {
6677 /* Naked functions are implemented entirely in assembly, including the
6678 return sequence, so suppress warnings about this. */
6679 return !riscv_naked_function_p (decl);
6680 }
6681
6682 /* Implement TARGET_EXPAND_BUILTIN_VA_START. */
6683
6684 static void
6685 riscv_va_start (tree valist, rtx nextarg)
6686 {
6687 nextarg = plus_constant (Pmode, nextarg, -cfun->machine->varargs_size);
6688 std_expand_builtin_va_start (valist, nextarg);
6689 }
6690
6691 /* Make ADDR suitable for use as a call or sibcall target. */
6692
6693 rtx
6694 riscv_legitimize_call_address (rtx addr)
6695 {
6696 if (!call_insn_operand (addr, VOIDmode))
6697 {
6698 rtx reg = RISCV_CALL_ADDRESS_TEMP (Pmode);
6699 riscv_emit_move (reg, addr);
6700
6701 if (is_zicfilp_p ())
6702 {
6703 rtx sw_guarded = RISCV_CALL_ADDRESS_LPAD (Pmode);
6704 emit_insn (gen_set_guarded (Pmode, reg));
6705 return sw_guarded;
6706 }
6707
6708 return reg;
6709 }
6710
6711 if (is_zicfilp_p () && REG_P (addr))
6712 emit_insn (gen_set_lpl (Pmode, const0_rtx));
6713
6714 return addr;
6715 }
6716
6717 /* Print symbolic operand OP, which is part of a HIGH or LO_SUM
6718 in context CONTEXT. HI_RELOC indicates a high-part reloc. */
6719
6720 static void
6721 riscv_print_operand_reloc (FILE *file, rtx op, bool hi_reloc)
6722 {
6723 const char *reloc;
6724
6725 switch (riscv_classify_symbolic_expression (op))
6726 {
6727 case SYMBOL_ABSOLUTE:
6728 reloc = hi_reloc ? "%hi" : "%lo";
6729 break;
6730
6731 case SYMBOL_PCREL:
6732 reloc = hi_reloc ? "%pcrel_hi" : "%pcrel_lo";
6733 break;
6734
6735 case SYMBOL_TLS_LE:
6736 reloc = hi_reloc ? "%tprel_hi" : "%tprel_lo";
6737 break;
6738
6739 default:
6740 output_operand_lossage ("invalid use of '%%%c'", hi_reloc ? 'h' : 'R');
6741 return;
6742 }
6743
6744 fprintf (file, "%s(", reloc);
6745 output_addr_const (file, riscv_strip_unspec_address (op));
6746 fputc (')', file);
6747 }
6748
6749 /* Return the memory model that encapsulates both given models. */
6750
6751 enum memmodel
6752 riscv_union_memmodels (enum memmodel model1, enum memmodel model2)
6753 {
6754 model1 = memmodel_base (model1);
6755 model2 = memmodel_base (model2);
6756
6757 enum memmodel weaker = model1 <= model2 ? model1 : model2;
6758 enum memmodel stronger = model1 > model2 ? model1 : model2;
6759
6760 switch (stronger)
6761 {
6762 case MEMMODEL_SEQ_CST:
6763 case MEMMODEL_ACQ_REL:
6764 return stronger;
6765 case MEMMODEL_RELEASE:
6766 if (weaker == MEMMODEL_ACQUIRE || weaker == MEMMODEL_CONSUME)
6767 return MEMMODEL_ACQ_REL;
6768 else
6769 return stronger;
6770 case MEMMODEL_ACQUIRE:
6771 case MEMMODEL_CONSUME:
6772 case MEMMODEL_RELAXED:
6773 return stronger;
6774 default:
6775 gcc_unreachable ();
6776 }
6777 }
6778
6779 /* Return true if the .AQ suffix should be added to an AMO to implement the
6780 acquire portion of memory model MODEL. */
6781
6782 static bool
6783 riscv_memmodel_needs_amo_acquire (enum memmodel model)
6784 {
6785 /* ZTSO amo mappings require no annotations. */
6786 if (TARGET_ZTSO)
6787 return false;
6788
6789 switch (model)
6790 {
6791 case MEMMODEL_ACQ_REL:
6792 case MEMMODEL_SEQ_CST:
6793 case MEMMODEL_ACQUIRE:
6794 case MEMMODEL_CONSUME:
6795 return true;
6796
6797 case MEMMODEL_RELEASE:
6798 case MEMMODEL_RELAXED:
6799 return false;
6800
6801 default:
6802 gcc_unreachable ();
6803 }
6804 }
6805
6806 /* Return true if the .RL suffix should be added to an AMO to implement the
6807 release portion of memory model MODEL. */
6808
6809 static bool
6810 riscv_memmodel_needs_amo_release (enum memmodel model)
6811 {
6812 /* ZTSO amo mappings require no annotations. */
6813 if (TARGET_ZTSO)
6814 return false;
6815
6816 switch (model)
6817 {
6818 case MEMMODEL_ACQ_REL:
6819 case MEMMODEL_SEQ_CST:
6820 case MEMMODEL_RELEASE:
6821 return true;
6822
6823 case MEMMODEL_ACQUIRE:
6824 case MEMMODEL_CONSUME:
6825 case MEMMODEL_RELAXED:
6826 return false;
6827
6828 default:
6829 gcc_unreachable ();
6830 }
6831 }
6832
6833 /* Get REGNO alignment of vector mode.
6834 The alignment = LMUL when the LMUL >= 1.
6835 Otherwise, alignment = 1. */
6836 int
6837 riscv_get_v_regno_alignment (machine_mode mode)
6838 {
6839 /* 3.3.2. LMUL = 2,4,8, register numbers should be multiple of 2,4,8.
6840 but for mask vector register, register numbers can be any number. */
6841 int lmul = 1;
6842 machine_mode rvv_mode = mode;
6843 if (riscv_v_ext_vls_mode_p (rvv_mode))
6844 {
6845 int size = GET_MODE_BITSIZE (rvv_mode).to_constant ();
6846 if (size < TARGET_MIN_VLEN)
6847 return 1;
6848 else
6849 return size / TARGET_MIN_VLEN;
6850 }
6851 if (riscv_v_ext_tuple_mode_p (rvv_mode))
6852 rvv_mode = riscv_vector::get_subpart_mode (rvv_mode);
6853 poly_int64 size = GET_MODE_SIZE (rvv_mode);
6854 if (known_gt (size, UNITS_PER_V_REG))
6855 lmul = exact_div (size, UNITS_PER_V_REG).to_constant ();
6856 return lmul;
6857 }
6858
6859 /* Define ASM_OUTPUT_OPCODE to do anything special before
6860 emitting an opcode. */
6861 const char *
6862 riscv_asm_output_opcode (FILE *asm_out_file, const char *p)
6863 {
6864 if (TARGET_XTHEADVECTOR)
6865 return th_asm_output_opcode (asm_out_file, p);
6866
6867 return p;
6868 }
6869
6870 /* Implement TARGET_PRINT_OPERAND. The RISCV-specific operand codes are:
6871
6872 'h' Print the high-part relocation associated with OP, after stripping
6873 any outermost HIGH.
6874 'R' Print the low-part relocation associated with OP.
6875 'C' Print the integer branch condition for comparison OP.
6876 'r' Print the inverse of the integer branch condition for comparison OP.
6877 'A' Print the atomic operation suffix for memory model OP.
6878 'I' Print the LR suffix for memory model OP.
6879 'J' Print the SC suffix for memory model OP.
6880 'L' Print a non-temporal locality hints instruction.
6881 'z' Print x0 if OP is zero, otherwise print OP normally.
6882 'i' Print i if the operand is not a register.
6883 'S' Print shift-index of single-bit mask OP.
6884 'T' Print shift-index of inverted single-bit mask OP.
6885 '~' Print w if TARGET_64BIT is true; otherwise not print anything.
6886 'N' Print register encoding as integer (0-31).
6887
6888 Note please keep this list and the list in riscv.md in sync. */
6889
6890 static void
6891 riscv_print_operand (FILE *file, rtx op, int letter)
6892 {
6893 /* `~` does not take an operand so op will be null
6894 Check for before accessing op.
6895 */
6896 if (letter == '~')
6897 {
6898 if (TARGET_64BIT)
6899 fputc('w', file);
6900 return;
6901 }
6902 machine_mode mode = GET_MODE (op);
6903 enum rtx_code code = GET_CODE (op);
6904
6905 switch (letter)
6906 {
6907 case 'o': {
6908 /* Print 'OP' variant for RVV instructions.
6909 1. If the operand is VECTOR REG, we print 'v'(vnsrl.wv).
6910 2. If the operand is CONST_INT/CONST_VECTOR, we print 'i'(vnsrl.wi).
6911 3. If the operand is SCALAR REG, we print 'x'(vnsrl.wx). */
6912 if (riscv_v_ext_mode_p (mode))
6913 {
6914 if (REG_P (op))
6915 asm_fprintf (file, "v");
6916 else if (CONST_VECTOR_P (op))
6917 asm_fprintf (file, "i");
6918 else
6919 output_operand_lossage ("invalid vector operand");
6920 }
6921 else
6922 {
6923 if (CONST_INT_P (op))
6924 asm_fprintf (file, "i");
6925 else
6926 asm_fprintf (file, "x");
6927 }
6928 break;
6929 }
6930 case 'v': {
6931 rtx elt;
6932
6933 if (REG_P (op))
6934 asm_fprintf (file, "%s", reg_names[REGNO (op)]);
6935 else
6936 {
6937 if (!const_vec_duplicate_p (op, &elt))
6938 output_operand_lossage ("invalid vector constant");
6939 else if (satisfies_constraint_Wc0 (op))
6940 asm_fprintf (file, "0");
6941 else if (satisfies_constraint_vi (op)
6942 || satisfies_constraint_vj (op)
6943 || satisfies_constraint_vk (op))
6944 asm_fprintf (file, "%wd", INTVAL (elt));
6945 else
6946 output_operand_lossage ("invalid vector constant");
6947 }
6948 break;
6949 }
6950 case 'V': {
6951 rtx elt;
6952 if (!const_vec_duplicate_p (op, &elt))
6953 output_operand_lossage ("invalid vector constant");
6954 else if (satisfies_constraint_vj (op))
6955 asm_fprintf (file, "%wd", -INTVAL (elt));
6956 else
6957 output_operand_lossage ("invalid vector constant");
6958 break;
6959 }
6960 case 'm': {
6961 if (riscv_v_ext_mode_p (mode))
6962 {
6963 /* Calculate lmul according to mode and print the value. */
6964 int lmul = riscv_get_v_regno_alignment (mode);
6965 asm_fprintf (file, "%d", lmul);
6966 }
6967 else if (code == CONST_INT)
6968 {
6969 /* If it is a const_int value, it denotes the VLMUL field enum. */
6970 unsigned int vlmul = UINTVAL (op);
6971 switch (vlmul)
6972 {
6973 case riscv_vector::LMUL_1:
6974 asm_fprintf (file, "%s", "m1");
6975 break;
6976 case riscv_vector::LMUL_2:
6977 asm_fprintf (file, "%s", "m2");
6978 break;
6979 case riscv_vector::LMUL_4:
6980 asm_fprintf (file, "%s", "m4");
6981 break;
6982 case riscv_vector::LMUL_8:
6983 asm_fprintf (file, "%s", "m8");
6984 break;
6985 case riscv_vector::LMUL_F8:
6986 asm_fprintf (file, "%s", "mf8");
6987 break;
6988 case riscv_vector::LMUL_F4:
6989 asm_fprintf (file, "%s", "mf4");
6990 break;
6991 case riscv_vector::LMUL_F2:
6992 asm_fprintf (file, "%s", "mf2");
6993 break;
6994 default:
6995 gcc_unreachable ();
6996 }
6997 }
6998 else
6999 output_operand_lossage ("invalid vector constant");
7000 break;
7001 }
7002 case 'p': {
7003 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
7004 {
7005 /* Print for RVV mask operand.
7006 If op is reg, print ",v0.t".
7007 Otherwise, don't print anything. */
7008 if (code == REG)
7009 fprintf (file, ",%s.t", reg_names[REGNO (op)]);
7010 }
7011 else if (code == CONST_INT)
7012 {
7013 /* Tail && Mask policy. */
7014 asm_fprintf (file, "%s", IS_AGNOSTIC (UINTVAL (op)) ? "a" : "u");
7015 }
7016 else
7017 output_operand_lossage ("invalid vector constant");
7018 break;
7019 }
7020 case 'h':
7021 if (code == HIGH)
7022 op = XEXP (op, 0);
7023 riscv_print_operand_reloc (file, op, true);
7024 break;
7025
7026 case 'R':
7027 riscv_print_operand_reloc (file, op, false);
7028 break;
7029
7030 case 'C':
7031 /* The RTL names match the instruction names. */
7032 fputs (GET_RTX_NAME (code), file);
7033 break;
7034
7035 case 'r':
7036 /* The RTL names match the instruction names. */
7037 fputs (GET_RTX_NAME (reverse_condition (code)), file);
7038 break;
7039
7040 case 'A':
7041 if (!CONST_INT_P (op))
7042 output_operand_lossage ("invalid operand for '%%%c'", letter);
7043 else
7044 {
7045 const enum memmodel model = memmodel_base (INTVAL (op));
7046 if (riscv_memmodel_needs_amo_acquire (model)
7047 && riscv_memmodel_needs_amo_release (model))
7048 fputs (".aqrl", file);
7049 else if (riscv_memmodel_needs_amo_acquire (model))
7050 fputs (".aq", file);
7051 else if (riscv_memmodel_needs_amo_release (model))
7052 fputs (".rl", file);
7053 }
7054 break;
7055
7056 case 'I':
7057 if (!CONST_INT_P (op))
7058 output_operand_lossage ("invalid operand for '%%%c'", letter);
7059 else
7060 {
7061 const enum memmodel model = memmodel_base (INTVAL (op));
7062 if (TARGET_ZTSO && model != MEMMODEL_SEQ_CST)
7063 /* LR ops only have an annotation for SEQ_CST in the Ztso mapping. */
7064 break;
7065 else if (model == MEMMODEL_SEQ_CST)
7066 fputs (".aqrl", file);
7067 else if (riscv_memmodel_needs_amo_acquire (model))
7068 fputs (".aq", file);
7069 }
7070 break;
7071
7072 case 'J':
7073 if (!CONST_INT_P (op))
7074 output_operand_lossage ("invalid operand for '%%%c'", letter);
7075 else
7076 {
7077 const enum memmodel model = memmodel_base (INTVAL (op));
7078 if (TARGET_ZTSO && model == MEMMODEL_SEQ_CST)
7079 /* SC ops only have an annotation for SEQ_CST in the Ztso mapping. */
7080 fputs (".rl", file);
7081 else if (TARGET_ZTSO)
7082 break;
7083 else if (riscv_memmodel_needs_amo_release (model))
7084 fputs (".rl", file);
7085 }
7086 break;
7087
7088 case 'L':
7089 if (!CONST_INT_P (op))
7090 output_operand_lossage ("invalid operand for '%%%c'", letter);
7091 else
7092 {
7093 const char *ntl_hint = NULL;
7094 switch (INTVAL (op))
7095 {
7096 case 0:
7097 ntl_hint = "ntl.all";
7098 break;
7099 case 1:
7100 ntl_hint = "ntl.pall";
7101 break;
7102 case 2:
7103 ntl_hint = "ntl.p1";
7104 break;
7105 }
7106
7107 if (ntl_hint)
7108 asm_fprintf (file, "%s\n\t", ntl_hint);
7109 }
7110 break;
7111
7112 case 'i':
7113 if (code != REG)
7114 fputs ("i", file);
7115 break;
7116
7117 case 'B':
7118 fputs (GET_RTX_NAME (code), file);
7119 break;
7120
7121 case 'S':
7122 if (!CONST_INT_P (op))
7123 output_operand_lossage ("invalid operand for '%%%c'", letter);
7124 else
7125 {
7126 rtx newop = GEN_INT (ctz_hwi (INTVAL (op)));
7127 output_addr_const (file, newop);
7128 }
7129 break;
7130 case 'T':
7131 if (!CONST_INT_P (op))
7132 output_operand_lossage ("invalid operand for '%%%c'", letter);
7133 else
7134 {
7135 rtx newop = GEN_INT (ctz_hwi (~INTVAL (op)));
7136 output_addr_const (file, newop);
7137 }
7138 break;
7139 case 'X':
7140 if (!CONST_INT_P (op))
7141 output_operand_lossage ("invalid operand for '%%%c'", letter);
7142 else
7143 {
7144 int ival = INTVAL (op) + 1;
7145 rtx newop = GEN_INT (ctz_hwi (ival) + 1);
7146 output_addr_const (file, newop);
7147 }
7148 break;
7149 case 'Y':
7150 if (!CONST_INT_P (op))
7151 output_operand_lossage ("invalid operand for '%%%c'", letter);
7152 else
7153 {
7154 unsigned int imm = (UINTVAL (op) & 63);
7155 gcc_assert (imm <= 63);
7156 rtx newop = GEN_INT (imm);
7157 output_addr_const (file, newop);
7158 }
7159 break;
7160 case 'N':
7161 {
7162 if (!REG_P(op))
7163 {
7164 output_operand_lossage ("modifier 'N' require register operand");
7165 break;
7166 }
7167
7168 unsigned regno = REGNO (op);
7169 unsigned offset = 0;
7170 if (IN_RANGE (regno, GP_REG_FIRST, GP_REG_LAST))
7171 offset = GP_REG_FIRST;
7172 else if (IN_RANGE (regno, FP_REG_FIRST, FP_REG_LAST))
7173 offset = FP_REG_FIRST;
7174 else if (IN_RANGE (regno, V_REG_FIRST, V_REG_LAST))
7175 offset = V_REG_FIRST;
7176 else
7177 output_operand_lossage ("invalid register number for 'N' modifier");
7178
7179 asm_fprintf (file, "%u", (regno - offset));
7180 break;
7181 }
7182 default:
7183 switch (code)
7184 {
7185 case REG:
7186 if (letter && letter != 'z')
7187 output_operand_lossage ("invalid use of '%%%c'", letter);
7188 fprintf (file, "%s", reg_names[REGNO (op)]);
7189 break;
7190
7191 case MEM:
7192 if (letter && letter != 'z')
7193 output_operand_lossage ("invalid use of '%%%c'", letter);
7194 else
7195 output_address (mode, XEXP (op, 0));
7196 break;
7197
7198 case CONST_DOUBLE:
7199 {
7200 if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
7201 {
7202 fputs (reg_names[GP_REG_FIRST], file);
7203 break;
7204 }
7205
7206 int fli_index = riscv_float_const_rtx_index_for_fli (op);
7207 if (fli_index == -1 || fli_index > 31)
7208 {
7209 output_operand_lossage ("invalid use of '%%%c'", letter);
7210 break;
7211 }
7212 asm_fprintf (file, "%s", fli_value_print[fli_index]);
7213 break;
7214 }
7215
7216 default:
7217 if (letter == 'z' && op == CONST0_RTX (GET_MODE (op)))
7218 fputs (reg_names[GP_REG_FIRST], file);
7219 else if (letter && letter != 'z')
7220 output_operand_lossage ("invalid use of '%%%c'", letter);
7221 else
7222 output_addr_const (file, riscv_strip_unspec_address (op));
7223 break;
7224 }
7225 }
7226 }
7227
7228 /* Implement TARGET_PRINT_OPERAND_PUNCT_VALID_P */
7229 static bool
7230 riscv_print_operand_punct_valid_p (unsigned char code)
7231 {
7232 return (code == '~');
7233 }
7234
7235 /* Implement TARGET_PRINT_OPERAND_ADDRESS. */
7236
7237 static void
7238 riscv_print_operand_address (FILE *file, machine_mode mode ATTRIBUTE_UNUSED, rtx x)
7239 {
7240 struct riscv_address_info addr;
7241
7242 if (th_print_operand_address (file, mode, x))
7243 return;
7244
7245 if (riscv_classify_address (&addr, x, word_mode, true))
7246 switch (addr.type)
7247 {
7248 case ADDRESS_REG:
7249 output_addr_const (file, riscv_strip_unspec_address (addr.offset));
7250 fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
7251 return;
7252
7253 case ADDRESS_LO_SUM:
7254 riscv_print_operand_reloc (file, addr.offset, false);
7255 fprintf (file, "(%s)", reg_names[REGNO (addr.reg)]);
7256 return;
7257
7258 case ADDRESS_CONST_INT:
7259 output_addr_const (file, x);
7260 fprintf (file, "(%s)", reg_names[GP_REG_FIRST]);
7261 return;
7262
7263 case ADDRESS_SYMBOLIC:
7264 output_addr_const (file, riscv_strip_unspec_address (x));
7265 return;
7266
7267 default:
7268 gcc_unreachable ();
7269 }
7270
7271 gcc_unreachable ();
7272 }
7273
7274 static bool
7275 riscv_size_ok_for_small_data_p (int size)
7276 {
7277 return g_switch_value && IN_RANGE (size, 1, g_switch_value);
7278 }
7279
7280 /* Return true if EXP should be placed in the small data section. */
7281
7282 static bool
7283 riscv_in_small_data_p (const_tree x)
7284 {
7285 /* Because default_use_anchors_for_symbol_p doesn't gather small data to use
7286 the anchor symbol to address nearby objects. In large model, it can get
7287 the better result using the anchor optimization. */
7288 if (riscv_cmodel == CM_LARGE)
7289 return false;
7290
7291 if (TREE_CODE (x) == STRING_CST || TREE_CODE (x) == FUNCTION_DECL)
7292 return false;
7293
7294 if (VAR_P (x) && DECL_SECTION_NAME (x))
7295 {
7296 const char *sec = DECL_SECTION_NAME (x);
7297 return strcmp (sec, ".sdata") == 0 || strcmp (sec, ".sbss") == 0;
7298 }
7299
7300 return riscv_size_ok_for_small_data_p (int_size_in_bytes (TREE_TYPE (x)));
7301 }
7302
7303 /* Switch to the appropriate section for output of DECL. */
7304
7305 static section *
7306 riscv_select_section (tree decl, int reloc,
7307 unsigned HOST_WIDE_INT align)
7308 {
7309 switch (categorize_decl_for_section (decl, reloc))
7310 {
7311 case SECCAT_SRODATA:
7312 return get_named_section (decl, ".srodata", reloc);
7313
7314 default:
7315 return default_elf_select_section (decl, reloc, align);
7316 }
7317 }
7318
7319 /* Switch to the appropriate section for output of DECL. */
7320
7321 static void
7322 riscv_unique_section (tree decl, int reloc)
7323 {
7324 const char *prefix = NULL;
7325 bool one_only = DECL_ONE_ONLY (decl) && !HAVE_COMDAT_GROUP;
7326
7327 switch (categorize_decl_for_section (decl, reloc))
7328 {
7329 case SECCAT_SRODATA:
7330 prefix = one_only ? ".sr" : ".srodata";
7331 break;
7332
7333 default:
7334 break;
7335 }
7336 if (prefix)
7337 {
7338 const char *name, *linkonce;
7339 char *string;
7340
7341 name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
7342 name = targetm.strip_name_encoding (name);
7343
7344 /* If we're using one_only, then there needs to be a .gnu.linkonce
7345 prefix to the section name. */
7346 linkonce = one_only ? ".gnu.linkonce" : "";
7347
7348 string = ACONCAT ((linkonce, prefix, ".", name, NULL));
7349
7350 set_decl_section_name (decl, string);
7351 return;
7352 }
7353 default_unique_section (decl, reloc);
7354 }
7355
7356 /* Constant pools are per-function when in large code model. */
7357
7358 static inline bool
7359 riscv_can_use_per_function_literal_pools_p (void)
7360 {
7361 return riscv_cmodel == CM_LARGE;
7362 }
7363
7364 static bool
7365 riscv_use_blocks_for_constant_p (machine_mode, const_rtx)
7366 {
7367 /* We can't use blocks for constants when we're using a per-function
7368 constant pool. */
7369 return !riscv_can_use_per_function_literal_pools_p ();
7370 }
7371
7372 /* Return a section for X, handling small data. */
7373
7374 static section *
7375 riscv_elf_select_rtx_section (machine_mode mode, rtx x,
7376 unsigned HOST_WIDE_INT align)
7377 {
7378 /* The literal pool stays with the function. */
7379 if (riscv_can_use_per_function_literal_pools_p ())
7380 return function_section (current_function_decl);
7381
7382 section *s = default_elf_select_rtx_section (mode, x, align);
7383
7384 if (riscv_size_ok_for_small_data_p (GET_MODE_SIZE (mode).to_constant ()))
7385 {
7386 if (startswith (s->named.name, ".rodata.cst"))
7387 {
7388 /* Rename .rodata.cst* to .srodata.cst*. */
7389 char *name = (char *) alloca (strlen (s->named.name) + 2);
7390 sprintf (name, ".s%s", s->named.name + 1);
7391 return get_section (name, s->named.common.flags, NULL);
7392 }
7393
7394 if (s == data_section)
7395 return sdata_section;
7396 }
7397
7398 return s;
7399 }
7400
7401 /* Make the last instruction frame-related and note that it performs
7402 the operation described by FRAME_PATTERN. */
7403
7404 static void
7405 riscv_set_frame_expr (rtx frame_pattern)
7406 {
7407 rtx insn;
7408
7409 insn = get_last_insn ();
7410 RTX_FRAME_RELATED_P (insn) = 1;
7411 REG_NOTES (insn) = alloc_EXPR_LIST (REG_FRAME_RELATED_EXPR,
7412 frame_pattern,
7413 REG_NOTES (insn));
7414 }
7415
7416 /* Return a frame-related rtx that stores REG at MEM.
7417 REG must be a single register. */
7418
7419 static rtx
7420 riscv_frame_set (rtx mem, rtx reg)
7421 {
7422 rtx set = gen_rtx_SET (mem, reg);
7423 RTX_FRAME_RELATED_P (set) = 1;
7424 return set;
7425 }
7426
7427 /* Returns true if the current function might contain a far jump. */
7428
7429 static bool
7430 riscv_far_jump_used_p ()
7431 {
7432 size_t func_size = 0;
7433
7434 if (cfun->machine->far_jump_used)
7435 return true;
7436
7437 /* We can't change far_jump_used during or after reload, as there is
7438 no chance to change stack frame layout. So we must rely on the
7439 conservative heuristic below having done the right thing. */
7440 if (reload_in_progress || reload_completed)
7441 return false;
7442
7443 /* Estimate the function length. */
7444 for (rtx_insn *insn = get_insns (); insn; insn = NEXT_INSN (insn))
7445 func_size += get_attr_length (insn);
7446
7447 /* Conservatively determine whether some jump might exceed 1 MiB
7448 displacement. */
7449 if (func_size * 2 >= 0x100000)
7450 cfun->machine->far_jump_used = true;
7451
7452 return cfun->machine->far_jump_used;
7453 }
7454
7455 /* Return true, if the current function must save the incoming return
7456 address. */
7457
7458 static bool
7459 riscv_save_return_addr_reg_p (void)
7460 {
7461 /* The $ra register is call-clobbered: if this is not a leaf function,
7462 save it. */
7463 if (!crtl->is_leaf)
7464 return true;
7465
7466 /* We need to save the incoming return address if __builtin_eh_return
7467 is being used to set a different return address. */
7468 if (crtl->calls_eh_return)
7469 return true;
7470
7471 /* Far jumps/branches use $ra as a temporary to set up the target jump
7472 location (clobbering the incoming return address). */
7473 if (riscv_far_jump_used_p ())
7474 return true;
7475
7476 /* We need to save it if anyone has used that. */
7477 if (df_regs_ever_live_p (RETURN_ADDR_REGNUM))
7478 return true;
7479
7480 /* Need not to use ra for leaf when frame pointer is turned off by
7481 option whatever the omit-leaf-frame's value. */
7482 if (frame_pointer_needed && crtl->is_leaf
7483 && !TARGET_OMIT_LEAF_FRAME_POINTER)
7484 return true;
7485
7486 return false;
7487 }
7488
7489 /* Return true if the current function must save register REGNO. */
7490
7491 static bool
7492 riscv_save_reg_p (unsigned int regno)
7493 {
7494 bool call_saved = !global_regs[regno] && !call_used_or_fixed_reg_p (regno);
7495 bool might_clobber = crtl->saves_all_registers
7496 || df_regs_ever_live_p (regno);
7497
7498 if (call_saved && might_clobber)
7499 return true;
7500
7501 /* Save callee-saved V registers. */
7502 if (V_REG_P (regno) && !crtl->abi->clobbers_full_reg_p (regno)
7503 && might_clobber)
7504 return true;
7505
7506 if (regno == HARD_FRAME_POINTER_REGNUM && frame_pointer_needed)
7507 return true;
7508
7509 if (regno == RETURN_ADDR_REGNUM && riscv_save_return_addr_reg_p ())
7510 return true;
7511
7512 /* If this is an interrupt handler, then must save extra registers. */
7513 if (cfun->machine->interrupt_handler_p)
7514 {
7515 /* zero register is always zero. */
7516 if (regno == GP_REG_FIRST)
7517 return false;
7518
7519 /* The function will return the stack pointer to its original value. */
7520 if (regno == STACK_POINTER_REGNUM)
7521 return false;
7522
7523 /* By convention, we assume that gp and tp are safe. */
7524 if (regno == GP_REGNUM || regno == THREAD_POINTER_REGNUM)
7525 return false;
7526
7527 if (regno == RETURN_ADDR_REGNUM && is_zicfiss_p ())
7528 return true;
7529
7530 /* We must save every register used in this function. If this is not a
7531 leaf function, then we must save all temporary registers. */
7532 if (df_regs_ever_live_p (regno)
7533 || (!crtl->is_leaf && call_used_or_fixed_reg_p (regno)))
7534 return true;
7535 }
7536
7537 return false;
7538 }
7539
7540 /* Return TRUE if Zcmp push and pop insns should be
7541 avoided. FALSE otherwise.
7542 Only use multi push & pop if all GPRs masked can be covered,
7543 and stack access is SP based,
7544 and GPRs are at top of the stack frame,
7545 and no conflicts in stack allocation with other features */
7546 static bool
7547 riscv_avoid_multi_push (const struct riscv_frame_info *frame)
7548 {
7549 if (!TARGET_ZCMP || crtl->calls_eh_return || frame_pointer_needed
7550 || cfun->machine->interrupt_handler_p || cfun->machine->varargs_size != 0
7551 || crtl->args.pretend_args_size != 0
7552 || (use_shrink_wrapping_separate ()
7553 && !riscv_avoid_shrink_wrapping_separate ())
7554 || (frame->mask & ~MULTI_PUSH_GPR_MASK))
7555 return true;
7556
7557 return false;
7558 }
7559
7560 /* Determine whether to use multi push insn. */
7561 static bool
7562 riscv_use_multi_push (const struct riscv_frame_info *frame)
7563 {
7564 if (riscv_avoid_multi_push (frame))
7565 return false;
7566
7567 return (frame->multi_push_adj_base != 0);
7568 }
7569
7570 /* Return TRUE if a libcall to save/restore GPRs should be
7571 avoided. FALSE otherwise. */
7572 static bool
7573 riscv_avoid_save_libcall (void)
7574 {
7575 if (!TARGET_SAVE_RESTORE
7576 || crtl->calls_eh_return
7577 || frame_pointer_needed
7578 || cfun->machine->interrupt_handler_p
7579 || cfun->machine->varargs_size != 0
7580 || crtl->args.pretend_args_size != 0)
7581 return true;
7582
7583 return false;
7584 }
7585
7586 /* Determine whether to call GPR save/restore routines. */
7587 static bool
7588 riscv_use_save_libcall (const struct riscv_frame_info *frame)
7589 {
7590 if (riscv_avoid_save_libcall ())
7591 return false;
7592
7593 return frame->save_libcall_adjustment != 0;
7594 }
7595
7596 /* Determine which GPR save/restore routine to call. */
7597
7598 static unsigned
7599 riscv_save_libcall_count (unsigned mask)
7600 {
7601 for (unsigned n = GP_REG_LAST; n > GP_REG_FIRST; n--)
7602 if (BITSET_P (mask, n))
7603 return CALLEE_SAVED_REG_NUMBER (n) + 1;
7604 abort ();
7605 }
7606
7607 /* calculate number of s regs in multi push and pop.
7608 Note that {s0-s10} is not valid in Zcmp, use {s0-s11} instead. */
7609 static unsigned
7610 riscv_multi_push_sregs_count (unsigned mask)
7611 {
7612 unsigned num = riscv_save_libcall_count (mask);
7613 return (num == ZCMP_INVALID_S0S10_SREGS_COUNTS) ? ZCMP_S0S11_SREGS_COUNTS
7614 : num;
7615 }
7616
7617 /* calculate number of regs(ra, s0-sx) in multi push and pop. */
7618 static unsigned
7619 riscv_multi_push_regs_count (unsigned mask)
7620 {
7621 /* 1 is for ra */
7622 return riscv_multi_push_sregs_count (mask) + 1;
7623 }
7624
7625 /* Handle 16 bytes align for poly_int. */
7626 static poly_int64
7627 riscv_16bytes_align (poly_int64 value)
7628 {
7629 return aligned_upper_bound (value, 16);
7630 }
7631
7632 static HOST_WIDE_INT
7633 riscv_16bytes_align (HOST_WIDE_INT value)
7634 {
7635 return ROUND_UP (value, 16);
7636 }
7637
7638 /* Handle stack align for poly_int. */
7639 static poly_int64
7640 riscv_stack_align (poly_int64 value)
7641 {
7642 return aligned_upper_bound (value, PREFERRED_STACK_BOUNDARY / 8);
7643 }
7644
7645 static HOST_WIDE_INT
7646 riscv_stack_align (HOST_WIDE_INT value)
7647 {
7648 return RISCV_STACK_ALIGN (value);
7649 }
7650
7651 /* Populate the current function's riscv_frame_info structure.
7652
7653 RISC-V stack frames grown downward. High addresses are at the top.
7654
7655 +-------------------------------+
7656 | |
7657 | incoming stack arguments |
7658 | |
7659 +-------------------------------+ <-- incoming stack pointer
7660 | |
7661 | callee-allocated save area |
7662 | for arguments that are |
7663 | split between registers and |
7664 | the stack |
7665 | |
7666 +-------------------------------+ <-- arg_pointer_rtx
7667 | |
7668 | callee-allocated save area |
7669 | for register varargs |
7670 | |
7671 +-------------------------------+ <-- hard_frame_pointer_rtx;
7672 | | stack_pointer_rtx + gp_sp_offset
7673 | GPR save area | + UNITS_PER_WORD
7674 | |
7675 +-------------------------------+ <-- stack_pointer_rtx + fp_sp_offset
7676 | | + UNITS_PER_FP_REG
7677 | FPR save area |
7678 | |
7679 +-------------------------------+ <-- stack_pointer_rtx
7680 | | + v_sp_offset_top
7681 | Vector Registers save area |
7682 | |
7683 | ----------------------------- | <-- stack_pointer_rtx
7684 | padding | + v_sp_offset_bottom
7685 +-------------------------------+ <-- frame_pointer_rtx (virtual)
7686 | |
7687 | local variables |
7688 | |
7689 P +-------------------------------+
7690 | |
7691 | outgoing stack arguments |
7692 | |
7693 +-------------------------------+ <-- stack_pointer_rtx
7694
7695 Dynamic stack allocations such as alloca insert data at point P.
7696 They decrease stack_pointer_rtx but leave frame_pointer_rtx and
7697 hard_frame_pointer_rtx unchanged. */
7698
7699 static HOST_WIDE_INT riscv_first_stack_step (struct riscv_frame_info *frame, poly_int64 remaining_size);
7700
7701 static void
7702 riscv_compute_frame_info (void)
7703 {
7704 struct riscv_frame_info *frame;
7705 poly_int64 offset;
7706 bool interrupt_save_prologue_temp = false;
7707 unsigned int regno, i, num_x_saved = 0, num_f_saved = 0, x_save_size = 0;
7708 unsigned int num_v_saved = 0;
7709
7710 frame = &cfun->machine->frame;
7711
7712 /* Adjust the outgoing arguments size if required. Keep it in sync with what
7713 the mid-end is doing. */
7714 crtl->outgoing_args_size = STACK_DYNAMIC_OFFSET (cfun);
7715
7716 /* In an interrupt function, there are two cases in which t0 needs to be used:
7717 1, If we have a large frame, then we need to save/restore t0. We check for
7718 this before clearing the frame struct.
7719 2, Need to save and restore some CSRs in the frame. */
7720 if (cfun->machine->interrupt_handler_p)
7721 {
7722 HOST_WIDE_INT step1 = riscv_first_stack_step (frame, frame->total_size);
7723 if (! POLY_SMALL_OPERAND_P ((frame->total_size - step1))
7724 || (TARGET_HARD_FLOAT || TARGET_ZFINX))
7725 interrupt_save_prologue_temp = true;
7726 }
7727
7728 frame->reset();
7729
7730 if (!cfun->machine->naked_p)
7731 {
7732 /* Find out which GPRs we need to save. */
7733 for (regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
7734 if (riscv_save_reg_p (regno)
7735 || (interrupt_save_prologue_temp
7736 && (regno == RISCV_PROLOGUE_TEMP_REGNUM)))
7737 frame->mask |= 1 << (regno - GP_REG_FIRST), num_x_saved++;
7738
7739 /* If this function calls eh_return, we must also save and restore the
7740 EH data registers. */
7741 if (crtl->calls_eh_return)
7742 for (i = 0; (regno = EH_RETURN_DATA_REGNO (i)) != INVALID_REGNUM; i++)
7743 frame->mask |= 1 << (regno - GP_REG_FIRST), num_x_saved++;
7744
7745 /* Find out which FPRs we need to save. This loop must iterate over
7746 the same space as its companion in riscv_for_each_saved_reg. */
7747 if (TARGET_HARD_FLOAT)
7748 for (regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
7749 if (riscv_save_reg_p (regno))
7750 frame->fmask |= 1 << (regno - FP_REG_FIRST), num_f_saved++;
7751
7752 /* Find out which V registers we need to save. */
7753 if (TARGET_VECTOR)
7754 for (regno = V_REG_FIRST; regno <= V_REG_LAST; regno++)
7755 if (riscv_save_reg_p (regno))
7756 {
7757 frame->vmask |= 1 << (regno - V_REG_FIRST);
7758 num_v_saved++;
7759 }
7760 }
7761
7762 if (frame->mask)
7763 {
7764 x_save_size = riscv_stack_align (num_x_saved * UNITS_PER_WORD);
7765
7766 /* 1 is for ra */
7767 unsigned num_save_restore = 1 + riscv_save_libcall_count (frame->mask);
7768 /* Only use save/restore routines if they don't alter the stack size. */
7769 if (riscv_stack_align (num_save_restore * UNITS_PER_WORD) == x_save_size
7770 && !riscv_avoid_save_libcall ())
7771 {
7772 /* Libcall saves/restores 3 registers at once, so we need to
7773 allocate 12 bytes for callee-saved register. */
7774 if (TARGET_RVE)
7775 x_save_size = 3 * UNITS_PER_WORD;
7776
7777 frame->save_libcall_adjustment = x_save_size;
7778 }
7779
7780 if (!riscv_avoid_multi_push (frame))
7781 {
7782 /* num(ra, s0-sx) */
7783 unsigned num_multi_push = riscv_multi_push_regs_count (frame->mask);
7784 x_save_size = riscv_stack_align (num_multi_push * UNITS_PER_WORD);
7785 frame->multi_push_adj_base = riscv_16bytes_align (x_save_size);
7786 }
7787 }
7788
7789 /* In an interrupt function, we need extra space for the initial saves of CSRs. */
7790 if (cfun->machine->interrupt_handler_p
7791 && ((TARGET_HARD_FLOAT && frame->fmask)
7792 || (TARGET_ZFINX
7793 /* Except for RISCV_PROLOGUE_TEMP_REGNUM. */
7794 && (frame->mask & ~(1 << RISCV_PROLOGUE_TEMP_REGNUM)))))
7795 /* Save and restore FCSR. */
7796 /* TODO: When P or V extensions support interrupts, some of their CSRs
7797 may also need to be saved and restored. */
7798 x_save_size += riscv_stack_align (1 * UNITS_PER_WORD);
7799
7800 /* At the bottom of the frame are any outgoing stack arguments. */
7801 offset = riscv_stack_align (crtl->outgoing_args_size);
7802 /* Next are local stack variables. */
7803 offset += riscv_stack_align (get_frame_size ());
7804 /* The virtual frame pointer points above the local variables. */
7805 frame->frame_pointer_offset = offset;
7806 /* Next are the callee-saved VRs. */
7807 if (frame->vmask)
7808 offset += riscv_stack_align (num_v_saved * UNITS_PER_V_REG);
7809 frame->v_sp_offset_top = offset;
7810 frame->v_sp_offset_bottom
7811 = frame->v_sp_offset_top - num_v_saved * UNITS_PER_V_REG;
7812 /* Next are the callee-saved FPRs. */
7813 if (frame->fmask)
7814 offset += riscv_stack_align (num_f_saved * UNITS_PER_FP_REG);
7815 frame->fp_sp_offset = offset - UNITS_PER_FP_REG;
7816 /* Next are the callee-saved GPRs. */
7817 if (frame->mask)
7818 {
7819 offset += x_save_size;
7820 /* align to 16 bytes and add paddings to GPR part to honor
7821 both stack alignment and zcmp pus/pop size alignment. */
7822 if (riscv_use_multi_push (frame)
7823 && known_lt (offset, frame->multi_push_adj_base
7824 + ZCMP_SP_INC_STEP * ZCMP_MAX_SPIMM))
7825 offset = riscv_16bytes_align (offset);
7826 }
7827 frame->gp_sp_offset = offset - UNITS_PER_WORD;
7828 /* The hard frame pointer points above the callee-saved GPRs. */
7829 frame->hard_frame_pointer_offset = offset;
7830 /* Above the hard frame pointer is the callee-allocated varags save area. */
7831 offset += riscv_stack_align (cfun->machine->varargs_size);
7832 /* Next is the callee-allocated area for pretend stack arguments. */
7833 offset += riscv_stack_align (crtl->args.pretend_args_size);
7834 /* Arg pointer must be below pretend args, but must be above alignment
7835 padding. */
7836 frame->arg_pointer_offset = offset - crtl->args.pretend_args_size;
7837 frame->total_size = offset;
7838
7839 /* Next points the incoming stack pointer and any incoming arguments. */
7840 }
7841
7842 /* Implement TARGET_CAN_INLINE_P. Determine whether inlining the function
7843 CALLER into the function CALLEE is safe. Inlining should be rejected if
7844 there is no always_inline attribute and the target options differ except
7845 for differences in ISA extensions or performance tuning options like the
7846 code model, TLS dialect, and stack protector, etc. Inlining is
7847 permissible when the non-ISA extension options are identical and the ISA
7848 extensions of CALLEE are a subset of those of CALLER, thereby improving
7849 the performance of Function Multi-Versioning. */
7850
7851 static bool
7852 riscv_can_inline_p (tree caller, tree callee)
7853 {
7854 /* Do not inline when callee is versioned but caller is not. */
7855 if (DECL_FUNCTION_VERSIONED (callee) && ! DECL_FUNCTION_VERSIONED (caller))
7856 return false;
7857
7858 tree callee_tree = DECL_FUNCTION_SPECIFIC_TARGET (callee);
7859 tree caller_tree = DECL_FUNCTION_SPECIFIC_TARGET (caller);
7860
7861 /* It's safe to inline if callee has no opts. */
7862 if (! callee_tree)
7863 return true;
7864
7865 if (! caller_tree)
7866 caller_tree = target_option_default_node;
7867
7868 struct cl_target_option *callee_opts = TREE_TARGET_OPTION (callee_tree);
7869 struct cl_target_option *caller_opts = TREE_TARGET_OPTION (caller_tree);
7870
7871 int isa_flag_mask = riscv_x_target_flags_isa_mask ();
7872
7873 /* Callee and caller should have the same target options except for ISA. */
7874 int callee_target_flags = callee_opts->x_target_flags & ~isa_flag_mask;
7875 int caller_target_flags = caller_opts->x_target_flags & ~isa_flag_mask;
7876
7877 if (callee_target_flags != caller_target_flags)
7878 return false;
7879
7880 /* Callee's ISA should be a subset of the caller's ISA. */
7881 if (! riscv_ext_is_subset (caller_opts, callee_opts))
7882 return false;
7883
7884 /* If the callee has always_inline set, we can ignore the rest attributes. */
7885 if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (callee)))
7886 return true;
7887
7888 if (caller_opts->x_riscv_cmodel != callee_opts->x_riscv_cmodel)
7889 return false;
7890
7891 if (caller_opts->x_riscv_tls_dialect != callee_opts->x_riscv_tls_dialect)
7892 return false;
7893
7894 if (caller_opts->x_riscv_stack_protector_guard_reg
7895 != callee_opts->x_riscv_stack_protector_guard_reg)
7896 return false;
7897
7898 if (caller_opts->x_riscv_stack_protector_guard_offset
7899 != callee_opts->x_riscv_stack_protector_guard_offset)
7900 return false;
7901
7902 if (caller_opts->x_rvv_vector_strict_align
7903 != callee_opts->x_rvv_vector_strict_align)
7904 return false;
7905
7906 return true;
7907 }
7908
7909 /* Make sure that we're not trying to eliminate to the wrong hard frame
7910 pointer. */
7911
7912 static bool
7913 riscv_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
7914 {
7915 return (to == HARD_FRAME_POINTER_REGNUM || to == STACK_POINTER_REGNUM);
7916 }
7917
7918 /* Helper to determine if reg X pertains to stack. */
7919 bool
7920 riscv_reg_frame_related (rtx x)
7921 {
7922 return REG_P (x)
7923 && (REGNO (x) == FRAME_POINTER_REGNUM
7924 || REGNO (x) == HARD_FRAME_POINTER_REGNUM
7925 || REGNO (x) == ARG_POINTER_REGNUM
7926 || REGNO (x) == VIRTUAL_STACK_VARS_REGNUM);
7927 }
7928
7929 /* Implement INITIAL_ELIMINATION_OFFSET. FROM is either the frame pointer
7930 or argument pointer. TO is either the stack pointer or hard frame
7931 pointer. */
7932
7933 poly_int64
7934 riscv_initial_elimination_offset (int from, int to)
7935 {
7936 poly_int64 src, dest;
7937
7938 riscv_compute_frame_info ();
7939
7940 if (to == HARD_FRAME_POINTER_REGNUM)
7941 dest = cfun->machine->frame.hard_frame_pointer_offset;
7942 else if (to == STACK_POINTER_REGNUM)
7943 dest = 0; /* The stack pointer is the base of all offsets, hence 0. */
7944 else
7945 gcc_unreachable ();
7946
7947 if (from == FRAME_POINTER_REGNUM)
7948 src = cfun->machine->frame.frame_pointer_offset;
7949 else if (from == ARG_POINTER_REGNUM)
7950 src = cfun->machine->frame.arg_pointer_offset;
7951 else
7952 gcc_unreachable ();
7953
7954 return src - dest;
7955 }
7956
7957 /* Implement RETURN_ADDR_RTX. We do not support moving back to a
7958 previous frame. */
7959
7960 rtx
7961 riscv_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
7962 {
7963 if (count != 0)
7964 return const0_rtx;
7965
7966 return get_hard_reg_initial_val (Pmode, RETURN_ADDR_REGNUM);
7967 }
7968
7969 /* Emit code to change the current function's return address to
7970 ADDRESS. SCRATCH is available as a scratch register, if needed.
7971 ADDRESS and SCRATCH are both word-mode GPRs. */
7972
7973 void
7974 riscv_set_return_address (rtx address, rtx scratch)
7975 {
7976 rtx slot_address;
7977
7978 gcc_assert (BITSET_P (cfun->machine->frame.mask, RETURN_ADDR_REGNUM));
7979 slot_address = riscv_add_offset (scratch, stack_pointer_rtx,
7980 cfun->machine->frame.gp_sp_offset.to_constant());
7981 riscv_emit_move (gen_frame_mem (GET_MODE (address), slot_address), address);
7982 }
7983
7984 /* Save register REG to MEM. Make the instruction frame-related. */
7985
7986 static void
7987 riscv_save_reg (rtx reg, rtx mem)
7988 {
7989 riscv_emit_move (mem, reg);
7990 riscv_set_frame_expr (riscv_frame_set (mem, reg));
7991 }
7992
7993 /* Restore register REG from MEM. */
7994
7995 static void
7996 riscv_restore_reg (rtx reg, rtx mem)
7997 {
7998 rtx insn = riscv_emit_move (reg, mem);
7999 rtx dwarf = NULL_RTX;
8000 dwarf = alloc_reg_note (REG_CFA_RESTORE, reg, dwarf);
8001
8002 if (known_gt (epilogue_cfa_sp_offset, 0)
8003 && REGNO (reg) == HARD_FRAME_POINTER_REGNUM)
8004 {
8005 rtx cfa_adjust_rtx
8006 = gen_rtx_PLUS (Pmode, stack_pointer_rtx,
8007 gen_int_mode (epilogue_cfa_sp_offset, Pmode));
8008 dwarf = alloc_reg_note (REG_CFA_DEF_CFA, cfa_adjust_rtx, dwarf);
8009 }
8010
8011 REG_NOTES (insn) = dwarf;
8012 RTX_FRAME_RELATED_P (insn) = 1;
8013 }
8014
8015 /* A function to save or store a register. The first argument is the
8016 register and the second is the stack slot. */
8017 typedef void (*riscv_save_restore_fn) (rtx, rtx);
8018
8019 /* Use FN to save or restore register REGNO. MODE is the register's
8020 mode and OFFSET is the offset of its save slot from the current
8021 stack pointer. */
8022
8023 static void
8024 riscv_save_restore_reg (machine_mode mode, int regno,
8025 HOST_WIDE_INT offset, riscv_save_restore_fn fn)
8026 {
8027 rtx mem;
8028
8029 mem = gen_frame_mem (mode, plus_constant (Pmode, stack_pointer_rtx, offset));
8030 fn (gen_rtx_REG (mode, regno), mem);
8031 }
8032
8033 /* Return the next register up from REGNO up to LIMIT for the callee
8034 to save or restore. OFFSET will be adjusted accordingly.
8035 If INC is set, then REGNO will be incremented first.
8036 Returns INVALID_REGNUM if there is no such next register. */
8037
8038 static unsigned int
8039 riscv_next_saved_reg (unsigned int regno, unsigned int limit,
8040 HOST_WIDE_INT *offset, bool inc = true)
8041 {
8042 if (inc)
8043 regno++;
8044
8045 while (regno <= limit)
8046 {
8047 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
8048 {
8049 *offset = *offset - UNITS_PER_WORD;
8050 return regno;
8051 }
8052
8053 regno++;
8054 }
8055 return INVALID_REGNUM;
8056 }
8057
8058 /* Return TRUE if provided REGNO is eh return data register. */
8059
8060 static bool
8061 riscv_is_eh_return_data_register (unsigned int regno)
8062 {
8063 unsigned int i, regnum;
8064
8065 if (!crtl->calls_eh_return)
8066 return false;
8067
8068 for (i = 0; (regnum = EH_RETURN_DATA_REGNO (i)) != INVALID_REGNUM; i++)
8069 if (regno == regnum)
8070 {
8071 return true;
8072 }
8073
8074 return false;
8075 }
8076
8077 /* Call FN for each register that is saved by the current function.
8078 SP_OFFSET is the offset of the current stack pointer from the start
8079 of the frame. */
8080
8081 static void
8082 riscv_for_each_saved_reg (poly_int64 sp_offset, riscv_save_restore_fn fn,
8083 bool epilogue, bool maybe_eh_return, bool sibcall_p)
8084 {
8085 HOST_WIDE_INT offset, first_fp_offset;
8086 unsigned int regno, num_masked_fp = 0;
8087 unsigned int start = GP_REG_FIRST;
8088 unsigned int limit = GP_REG_LAST;
8089
8090 /* Save the link register and s-registers. */
8091 offset = (cfun->machine->frame.gp_sp_offset - sp_offset).to_constant ()
8092 + UNITS_PER_WORD;
8093 for (regno = riscv_next_saved_reg (start, limit, &offset, false);
8094 regno != INVALID_REGNUM;
8095 regno = riscv_next_saved_reg (regno, limit, &offset))
8096 {
8097 if (cfun->machine->reg_is_wrapped_separately[regno])
8098 continue;
8099
8100 /* If this is a normal return in a function that calls the eh_return
8101 builtin, then do not restore the eh return data registers as that
8102 would clobber the return value. But we do still need to save them
8103 in the prologue, and restore them for an exception return, so we
8104 need special handling here. */
8105 if (epilogue && !maybe_eh_return
8106 && riscv_is_eh_return_data_register (regno))
8107 continue;
8108
8109 /* In an interrupt function, save and restore some necessary CSRs in the stack
8110 to avoid changes in CSRs. */
8111 if (regno == RISCV_PROLOGUE_TEMP_REGNUM
8112 && cfun->machine->interrupt_handler_p
8113 && ((TARGET_HARD_FLOAT && cfun->machine->frame.fmask)
8114 || (TARGET_ZFINX
8115 && (cfun->machine->frame.mask & ~(1 << RISCV_PROLOGUE_TEMP_REGNUM)))))
8116 {
8117 /* Always assume FCSR occupy UNITS_PER_WORD to prevent stack
8118 offset misaligned later. */
8119 unsigned int fcsr_size = UNITS_PER_WORD;
8120 if (!epilogue)
8121 {
8122 riscv_save_restore_reg (word_mode, regno, offset, fn);
8123 offset -= fcsr_size;
8124 emit_insn (gen_riscv_frcsr (RISCV_PROLOGUE_TEMP (SImode)));
8125 riscv_save_restore_reg (SImode, RISCV_PROLOGUE_TEMP_REGNUM,
8126 offset, riscv_save_reg);
8127 }
8128 else
8129 {
8130 riscv_save_restore_reg (SImode, RISCV_PROLOGUE_TEMP_REGNUM,
8131 offset - fcsr_size, riscv_restore_reg);
8132 emit_insn (gen_riscv_fscsr (RISCV_PROLOGUE_TEMP (SImode)));
8133 riscv_save_restore_reg (word_mode, regno, offset, fn);
8134 offset -= fcsr_size;
8135 }
8136 continue;
8137 }
8138
8139 if (TARGET_XTHEADMEMPAIR)
8140 {
8141 /* Get the next reg/offset pair. */
8142 HOST_WIDE_INT offset2 = offset;
8143 unsigned int regno2 = riscv_next_saved_reg (regno, limit, &offset2);
8144
8145 /* Validate everything before emitting a mempair instruction. */
8146 if (regno2 != INVALID_REGNUM
8147 && !cfun->machine->reg_is_wrapped_separately[regno2]
8148 && !(epilogue && !maybe_eh_return
8149 && riscv_is_eh_return_data_register (regno2)))
8150 {
8151 bool load_p = (fn == riscv_restore_reg);
8152 rtx operands[4];
8153 th_mempair_prepare_save_restore_operands (operands,
8154 load_p, word_mode,
8155 regno, offset,
8156 regno2, offset2);
8157
8158 /* If the operands fit into a mempair insn, then emit one. */
8159 if (th_mempair_operands_p (operands, load_p, word_mode))
8160 {
8161 th_mempair_save_restore_regs (operands, load_p, word_mode);
8162 offset = offset2;
8163 regno = regno2;
8164 continue;
8165 }
8166 }
8167 }
8168
8169 if (need_shadow_stack_push_pop_p () && epilogue && !sibcall_p
8170 && !(maybe_eh_return && crtl->calls_eh_return)
8171 && (regno == RETURN_ADDR_REGNUM)
8172 && !cfun->machine->interrupt_handler_p)
8173 riscv_save_restore_reg (word_mode, RISCV_PROLOGUE_TEMP_REGNUM,
8174 offset, fn);
8175 else
8176 riscv_save_restore_reg (word_mode, regno, offset, fn);
8177 }
8178
8179 /* This loop must iterate over the same space as its companion in
8180 riscv_compute_frame_info. */
8181 first_fp_offset
8182 = (cfun->machine->frame.fp_sp_offset - sp_offset).to_constant ();
8183 for (unsigned int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
8184 if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
8185 {
8186 bool handle_reg = !cfun->machine->reg_is_wrapped_separately[regno];
8187 machine_mode mode = TARGET_DOUBLE_FLOAT ? DFmode : SFmode;
8188 unsigned int slot = (riscv_use_multi_push (&cfun->machine->frame))
8189 ? CALLEE_SAVED_FREG_NUMBER (regno)
8190 : num_masked_fp;
8191 offset = first_fp_offset - slot * GET_MODE_SIZE (mode).to_constant ();
8192 if (handle_reg)
8193 riscv_save_restore_reg (mode, regno, offset, fn);
8194 num_masked_fp++;
8195 }
8196 }
8197
8198 /* Call FN for each V register that is saved by the current function. */
8199
8200 static void
8201 riscv_for_each_saved_v_reg (poly_int64 &remaining_size,
8202 riscv_save_restore_fn fn, bool prologue)
8203 {
8204 rtx vlen = NULL_RTX;
8205 if (cfun->machine->frame.vmask != 0)
8206 {
8207 if (UNITS_PER_V_REG.is_constant ()
8208 && SMALL_OPERAND (UNITS_PER_V_REG.to_constant ()))
8209 vlen = GEN_INT (UNITS_PER_V_REG.to_constant ());
8210 else
8211 {
8212 vlen = RISCV_PROLOGUE_TEMP (Pmode);
8213 rtx insn
8214 = emit_move_insn (vlen, gen_int_mode (UNITS_PER_V_REG, Pmode));
8215 RTX_FRAME_RELATED_P (insn) = 1;
8216 }
8217 }
8218
8219 /* Select the mode where LMUL is 1 and SEW is largest. */
8220 machine_mode m1_mode = TARGET_VECTOR_ELEN_64 ? RVVM1DImode : RVVM1SImode;
8221
8222 if (prologue)
8223 {
8224 /* This loop must iterate over the same space as its companion in
8225 riscv_compute_frame_info. */
8226 for (unsigned int regno = V_REG_FIRST; regno <= V_REG_LAST; regno++)
8227 if (BITSET_P (cfun->machine->frame.vmask, regno - V_REG_FIRST))
8228 {
8229 bool handle_reg = !cfun->machine->reg_is_wrapped_separately[regno];
8230 if (handle_reg)
8231 {
8232 rtx insn = NULL_RTX;
8233 if (CONST_INT_P (vlen))
8234 {
8235 gcc_assert (SMALL_OPERAND (-INTVAL (vlen)));
8236 insn = emit_insn (gen_add3_insn (stack_pointer_rtx,
8237 stack_pointer_rtx,
8238 GEN_INT (-INTVAL (vlen))));
8239 }
8240 else
8241 insn = emit_insn (
8242 gen_sub3_insn (stack_pointer_rtx, stack_pointer_rtx, vlen));
8243 gcc_assert (insn != NULL_RTX);
8244 RTX_FRAME_RELATED_P (insn) = 1;
8245 riscv_save_restore_reg (m1_mode, regno, 0, fn);
8246 remaining_size -= UNITS_PER_V_REG;
8247 }
8248 }
8249 }
8250 else
8251 {
8252 /* This loop must iterate over the same space as its companion in
8253 riscv_compute_frame_info. */
8254 for (unsigned int regno = V_REG_LAST; regno >= V_REG_FIRST; regno--)
8255 if (BITSET_P (cfun->machine->frame.vmask, regno - V_REG_FIRST))
8256 {
8257 bool handle_reg = !cfun->machine->reg_is_wrapped_separately[regno];
8258 if (handle_reg)
8259 {
8260 riscv_save_restore_reg (m1_mode, regno, 0, fn);
8261 rtx insn = emit_insn (
8262 gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx, vlen));
8263 gcc_assert (insn != NULL_RTX);
8264 RTX_FRAME_RELATED_P (insn) = 1;
8265 remaining_size -= UNITS_PER_V_REG;
8266 }
8267 }
8268 }
8269 }
8270
8271 /* For stack frames that can't be allocated with a single ADDI instruction,
8272 compute the best value to initially allocate. It must at a minimum
8273 allocate enough space to spill the callee-saved registers. If TARGET_RVC,
8274 try to pick a value that will allow compression of the register saves
8275 without adding extra instructions. */
8276
8277 static HOST_WIDE_INT
8278 riscv_first_stack_step (struct riscv_frame_info *frame, poly_int64 remaining_size)
8279 {
8280 HOST_WIDE_INT remaining_const_size;
8281 if (!remaining_size.is_constant ())
8282 remaining_const_size
8283 = riscv_stack_align (remaining_size.coeffs[0])
8284 - riscv_stack_align (remaining_size.coeffs[1]);
8285 else
8286 remaining_const_size = remaining_size.to_constant ();
8287
8288 /* First step must be set to the top of vector registers save area if any
8289 vector registers need be preserved. */
8290 if (frame->vmask != 0)
8291 return (remaining_size - frame->v_sp_offset_top).to_constant ();
8292
8293 if (SMALL_OPERAND (remaining_const_size))
8294 return remaining_const_size;
8295
8296 poly_int64 callee_saved_first_step =
8297 remaining_size - frame->frame_pointer_offset;
8298 gcc_assert(callee_saved_first_step.is_constant ());
8299 HOST_WIDE_INT min_first_step =
8300 riscv_stack_align (callee_saved_first_step.to_constant ());
8301 HOST_WIDE_INT max_first_step = IMM_REACH / 2 - PREFERRED_STACK_BOUNDARY / 8;
8302 HOST_WIDE_INT min_second_step = remaining_const_size - max_first_step;
8303 gcc_assert (min_first_step <= max_first_step);
8304
8305 /* As an optimization, use the least-significant bits of the total frame
8306 size, so that the second adjustment step is just LUI + ADD. */
8307 if (!SMALL_OPERAND (min_second_step)
8308 && remaining_const_size % IMM_REACH <= max_first_step
8309 && remaining_const_size % IMM_REACH >= min_first_step)
8310 return remaining_const_size % IMM_REACH;
8311
8312 if (TARGET_RVC || TARGET_ZCA)
8313 {
8314 /* If we need two subtracts, and one is small enough to allow compressed
8315 loads and stores, then put that one first. */
8316 if (IN_RANGE (min_second_step, 0,
8317 (TARGET_64BIT ? SDSP_REACH : SWSP_REACH)))
8318 return MAX (min_second_step, min_first_step);
8319
8320 /* If we need LUI + ADDI + ADD for the second adjustment step, then start
8321 with the minimum first step, so that we can get compressed loads and
8322 stores. */
8323 else if (!SMALL_OPERAND (min_second_step))
8324 return min_first_step;
8325 }
8326
8327 return max_first_step;
8328 }
8329
8330 static rtx
8331 riscv_adjust_libcall_cfi_prologue ()
8332 {
8333 rtx dwarf = NULL_RTX;
8334 rtx adjust_sp_rtx, reg, mem, insn;
8335 int saved_size = cfun->machine->frame.save_libcall_adjustment;
8336 int offset;
8337
8338 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
8339 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
8340 {
8341 /* The save order is ra, s0, s1, s2 to s11. */
8342 if (regno == RETURN_ADDR_REGNUM)
8343 offset = saved_size - UNITS_PER_WORD;
8344 else if (regno == S0_REGNUM)
8345 offset = saved_size - UNITS_PER_WORD * 2;
8346 else if (regno == S1_REGNUM)
8347 offset = saved_size - UNITS_PER_WORD * 3;
8348 else
8349 offset = saved_size - ((regno - S2_REGNUM + 4) * UNITS_PER_WORD);
8350
8351 reg = gen_rtx_REG (Pmode, regno);
8352 mem = gen_frame_mem (Pmode, plus_constant (Pmode,
8353 stack_pointer_rtx,
8354 offset));
8355
8356 insn = gen_rtx_SET (mem, reg);
8357 dwarf = alloc_reg_note (REG_CFA_OFFSET, insn, dwarf);
8358 }
8359
8360 /* Debug info for adjust sp. */
8361 adjust_sp_rtx =
8362 gen_rtx_SET (stack_pointer_rtx,
8363 gen_rtx_PLUS (GET_MODE(stack_pointer_rtx), stack_pointer_rtx, GEN_INT (-saved_size)));
8364 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
8365 dwarf);
8366 return dwarf;
8367 }
8368
8369 static rtx
8370 riscv_adjust_multi_push_cfi_prologue (int saved_size)
8371 {
8372 rtx dwarf = NULL_RTX;
8373 rtx adjust_sp_rtx, reg, mem, insn;
8374 unsigned int mask = cfun->machine->frame.mask;
8375 int offset;
8376 int saved_cnt = 0;
8377
8378 unsigned int num_multi_push = riscv_multi_push_regs_count (mask);
8379 for (unsigned int i = 0; i < num_multi_push; i++) {
8380 gcc_assert(zcmp_save_reg_order[i] != INVALID_REGNUM);
8381 mask |= 1 << (zcmp_save_reg_order[i] - GP_REG_FIRST);
8382 }
8383
8384 for (int regno = GP_REG_LAST; regno >= GP_REG_FIRST; regno--)
8385 if (BITSET_P (mask & MULTI_PUSH_GPR_MASK, regno - GP_REG_FIRST))
8386 {
8387 /* The save order is s11-s0, ra
8388 from high to low addr. */
8389 offset = saved_size - UNITS_PER_WORD * (++saved_cnt);
8390
8391 reg = gen_rtx_REG (Pmode, regno);
8392 mem = gen_frame_mem (Pmode,
8393 plus_constant (Pmode, stack_pointer_rtx, offset));
8394
8395 insn = gen_rtx_SET (mem, reg);
8396 dwarf = alloc_reg_note (REG_CFA_OFFSET, insn, dwarf);
8397 }
8398
8399 /* Debug info for adjust sp. */
8400 adjust_sp_rtx
8401 = gen_rtx_SET (stack_pointer_rtx,
8402 plus_constant (Pmode, stack_pointer_rtx, -saved_size));
8403 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx, dwarf);
8404 return dwarf;
8405 }
8406
8407 static void
8408 riscv_emit_stack_tie (rtx reg)
8409 {
8410 if (Pmode == SImode)
8411 emit_insn (gen_stack_tiesi (stack_pointer_rtx, reg));
8412 else
8413 emit_insn (gen_stack_tiedi (stack_pointer_rtx, reg));
8414 }
8415
8416 /*zcmp multi push and pop code_for_push_pop function ptr array */
8417 static const code_for_push_pop_t code_for_push_pop[ZCMP_MAX_GRP_SLOTS][ZCMP_OP_NUM]
8418 = {{code_for_gpr_multi_push_up_to_ra, code_for_gpr_multi_pop_up_to_ra,
8419 code_for_gpr_multi_popret_up_to_ra, code_for_gpr_multi_popretz_up_to_ra},
8420 {code_for_gpr_multi_push_up_to_s0, code_for_gpr_multi_pop_up_to_s0,
8421 code_for_gpr_multi_popret_up_to_s0, code_for_gpr_multi_popretz_up_to_s0},
8422 {code_for_gpr_multi_push_up_to_s1, code_for_gpr_multi_pop_up_to_s1,
8423 code_for_gpr_multi_popret_up_to_s1, code_for_gpr_multi_popretz_up_to_s1},
8424 {code_for_gpr_multi_push_up_to_s2, code_for_gpr_multi_pop_up_to_s2,
8425 code_for_gpr_multi_popret_up_to_s2, code_for_gpr_multi_popretz_up_to_s2},
8426 {code_for_gpr_multi_push_up_to_s3, code_for_gpr_multi_pop_up_to_s3,
8427 code_for_gpr_multi_popret_up_to_s3, code_for_gpr_multi_popretz_up_to_s3},
8428 {code_for_gpr_multi_push_up_to_s4, code_for_gpr_multi_pop_up_to_s4,
8429 code_for_gpr_multi_popret_up_to_s4, code_for_gpr_multi_popretz_up_to_s4},
8430 {code_for_gpr_multi_push_up_to_s5, code_for_gpr_multi_pop_up_to_s5,
8431 code_for_gpr_multi_popret_up_to_s5, code_for_gpr_multi_popretz_up_to_s5},
8432 {code_for_gpr_multi_push_up_to_s6, code_for_gpr_multi_pop_up_to_s6,
8433 code_for_gpr_multi_popret_up_to_s6, code_for_gpr_multi_popretz_up_to_s6},
8434 {code_for_gpr_multi_push_up_to_s7, code_for_gpr_multi_pop_up_to_s7,
8435 code_for_gpr_multi_popret_up_to_s7, code_for_gpr_multi_popretz_up_to_s7},
8436 {code_for_gpr_multi_push_up_to_s8, code_for_gpr_multi_pop_up_to_s8,
8437 code_for_gpr_multi_popret_up_to_s8, code_for_gpr_multi_popretz_up_to_s8},
8438 {code_for_gpr_multi_push_up_to_s9, code_for_gpr_multi_pop_up_to_s9,
8439 code_for_gpr_multi_popret_up_to_s9, code_for_gpr_multi_popretz_up_to_s9},
8440 {nullptr, nullptr, nullptr, nullptr},
8441 {code_for_gpr_multi_push_up_to_s11, code_for_gpr_multi_pop_up_to_s11,
8442 code_for_gpr_multi_popret_up_to_s11,
8443 code_for_gpr_multi_popretz_up_to_s11}};
8444
8445 /* Set a probe loop for stack clash protection. */
8446 static void
8447 riscv_allocate_and_probe_stack_loop (rtx tmp, enum rtx_code code,
8448 rtx op0, rtx op1, bool vector,
8449 HOST_WIDE_INT offset)
8450 {
8451 tmp = riscv_force_temporary (tmp, gen_int_mode (offset, Pmode));
8452
8453 /* Loop. */
8454 rtx label = gen_label_rtx ();
8455 emit_label (label);
8456
8457 /* Allocate and probe stack. */
8458 emit_insn (gen_sub3_insn (stack_pointer_rtx, stack_pointer_rtx, tmp));
8459 emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
8460 STACK_CLASH_CALLER_GUARD));
8461 emit_insn (gen_blockage ());
8462
8463 /* Adjust the remaining vector length. */
8464 if (vector)
8465 emit_insn (gen_sub3_insn (op0, op0, tmp));
8466
8467 /* Branch if there's still more bytes to probe. */
8468 riscv_expand_conditional_branch (label, code, op0, op1);
8469 JUMP_LABEL (get_last_insn ()) = label;
8470
8471 emit_insn (gen_blockage ());
8472 }
8473
8474 /* Adjust scalable frame of vector for prologue && epilogue. */
8475
8476 static void
8477 riscv_v_adjust_scalable_frame (rtx target, poly_int64 offset, bool epilogue)
8478 {
8479 rtx tmp = RISCV_PROLOGUE_TEMP (Pmode);
8480 rtx adjust_size = RISCV_PROLOGUE_TEMP2 (Pmode);
8481 rtx insn, dwarf, adjust_frame_rtx;
8482
8483 riscv_legitimize_poly_move (Pmode, adjust_size, tmp,
8484 gen_int_mode (offset, Pmode));
8485
8486 /* If doing stack clash protection then we use a loop to allocate and probe
8487 the stack. */
8488 if (flag_stack_clash_protection)
8489 {
8490 if (epilogue)
8491 {
8492 insn = emit_insn (gen_add3_insn (target, target, adjust_size));
8493
8494 if (!frame_pointer_needed)
8495 {
8496 add_reg_note (insn, REG_CFA_DEF_CFA,
8497 plus_constant (Pmode, stack_pointer_rtx, -offset));
8498 RTX_FRAME_RELATED_P (insn) = 1;
8499 }
8500
8501 return;
8502 }
8503
8504 HOST_WIDE_INT min_probe_threshold
8505 = (1 << param_stack_clash_protection_guard_size) - STACK_CLASH_CALLER_GUARD;
8506
8507 if (!frame_pointer_needed)
8508 {
8509 /* This is done to provide unwinding information for the stack
8510 adjustments we're about to do, however to prevent the optimizers
8511 from removing the T3 move and leaving the CFA note (which would be
8512 very wrong) we tie the old and new stack pointer together.
8513 The tie will expand to nothing but the optimizers will not touch
8514 the instruction. */
8515 insn = get_last_insn ();
8516 rtx stack_ptr_copy = gen_rtx_REG (Pmode, RISCV_STACK_CLASH_VECTOR_CFA_REGNUM);
8517 emit_move_insn (stack_ptr_copy, stack_pointer_rtx);
8518 riscv_emit_stack_tie (stack_ptr_copy);
8519
8520 /* We want the CFA independent of the stack pointer for the
8521 duration of the loop. */
8522 add_reg_note (insn, REG_CFA_DEF_CFA, stack_ptr_copy);
8523 RTX_FRAME_RELATED_P (insn) = 1;
8524 }
8525
8526 riscv_allocate_and_probe_stack_loop (tmp, GE, adjust_size, tmp, true,
8527 min_probe_threshold);
8528
8529 /* Allocate the residual. */
8530 insn = emit_insn (gen_sub3_insn (target, target, adjust_size));
8531
8532 /* Now reset the CFA register if needed. */
8533 if (!frame_pointer_needed)
8534 {
8535 add_reg_note (insn, REG_CFA_DEF_CFA,
8536 plus_constant (Pmode, stack_pointer_rtx, offset));
8537 RTX_FRAME_RELATED_P (insn) = 1;
8538 }
8539
8540 return;
8541 }
8542
8543 if (epilogue)
8544 insn = gen_add3_insn (target, target, adjust_size);
8545 else
8546 insn = gen_sub3_insn (target, target, adjust_size);
8547
8548 insn = emit_insn (insn);
8549
8550 RTX_FRAME_RELATED_P (insn) = 1;
8551
8552 adjust_frame_rtx
8553 = gen_rtx_SET (target,
8554 plus_constant (Pmode, target, epilogue ? offset : -offset));
8555
8556 dwarf = alloc_reg_note (REG_FRAME_RELATED_EXPR, copy_rtx (adjust_frame_rtx),
8557 NULL_RTX);
8558
8559 REG_NOTES (insn) = dwarf;
8560 }
8561
8562 static rtx
8563 riscv_gen_multi_push_pop_insn (riscv_zcmp_op_t op, HOST_WIDE_INT adj_size,
8564 unsigned int regs_num)
8565 {
8566 gcc_assert (op < ZCMP_OP_NUM);
8567 gcc_assert (regs_num <= ZCMP_MAX_GRP_SLOTS
8568 && regs_num != ZCMP_INVALID_S0S10_SREGS_COUNTS + 1); /* 1 for ra*/
8569 rtx stack_adj = GEN_INT (adj_size);
8570 return GEN_FCN (code_for_push_pop[regs_num - 1][op](Pmode)) (stack_adj);
8571 }
8572
8573 static unsigned
8574 get_multi_push_fpr_mask (unsigned max_fprs_push)
8575 {
8576 unsigned mask_fprs_push = 0, num_f_pushed = 0;
8577 for (unsigned regno = FP_REG_FIRST;
8578 regno <= FP_REG_LAST && num_f_pushed < max_fprs_push; regno++)
8579 if (riscv_save_reg_p (regno))
8580 mask_fprs_push |= 1 << (regno - FP_REG_FIRST), num_f_pushed++;
8581 return mask_fprs_push;
8582 }
8583
8584 /* Allocate SIZE bytes of stack space using TEMP1 as a scratch register.
8585 If SIZE is not large enough to require a probe this function will only
8586 adjust the stack.
8587
8588 We emit barriers after each stack adjustment to prevent optimizations from
8589 breaking the invariant that we never drop the stack more than a page. This
8590 invariant is needed to make it easier to correctly handle asynchronous
8591 events, e.g. if we were to allow the stack to be dropped by more than a page
8592 and then have multiple probes up and we take a signal somewhere in between
8593 then the signal handler doesn't know the state of the stack and can make no
8594 assumptions about which pages have been probed. */
8595
8596 static void
8597 riscv_allocate_and_probe_stack_space (rtx temp1, HOST_WIDE_INT size)
8598 {
8599 HOST_WIDE_INT guard_size
8600 = 1 << param_stack_clash_protection_guard_size;
8601 HOST_WIDE_INT guard_used_by_caller = STACK_CLASH_CALLER_GUARD;
8602 HOST_WIDE_INT byte_sp_alignment = STACK_BOUNDARY / BITS_PER_UNIT;
8603 HOST_WIDE_INT min_probe_threshold = guard_size - guard_used_by_caller;
8604 rtx insn;
8605
8606 /* We should always have a positive probe threshold. */
8607 gcc_assert (min_probe_threshold > 0);
8608
8609 /* If SIZE is not large enough to require probing, just adjust the stack and
8610 exit. */
8611 if (known_lt (size, min_probe_threshold)
8612 || !flag_stack_clash_protection)
8613 {
8614 if (flag_stack_clash_protection)
8615 {
8616 if (known_eq (cfun->machine->frame.total_size, 0))
8617 dump_stack_clash_frame_info (NO_PROBE_NO_FRAME, false);
8618 else
8619 dump_stack_clash_frame_info (NO_PROBE_SMALL_FRAME, true);
8620 }
8621
8622 if (SMALL_OPERAND (-size))
8623 {
8624 insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx, GEN_INT (-size));
8625 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
8626 }
8627 else if (SUM_OF_TWO_S12_ALGN (-size))
8628 {
8629 HOST_WIDE_INT one, two;
8630 riscv_split_sum_of_two_s12 (-size, &one, &two);
8631 insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
8632 GEN_INT (one));
8633 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
8634 insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
8635 GEN_INT (two));
8636 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
8637 }
8638 else
8639 {
8640 temp1 = riscv_force_temporary (temp1, GEN_INT (-size));
8641 emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx, temp1));
8642 insn = plus_constant (Pmode, stack_pointer_rtx, -size);
8643 insn = gen_rtx_SET (stack_pointer_rtx, insn);
8644 riscv_set_frame_expr (insn);
8645 }
8646
8647 /* We must have allocated the remainder of the stack frame.
8648 Emit a stack tie if we have a frame pointer so that the
8649 allocation is ordered WRT fp setup and subsequent writes
8650 into the frame. */
8651 if (frame_pointer_needed)
8652 riscv_emit_stack_tie (hard_frame_pointer_rtx);
8653
8654 return;
8655 }
8656
8657 gcc_assert (multiple_p (size, byte_sp_alignment));
8658
8659 if (dump_file)
8660 fprintf (dump_file,
8661 "Stack clash prologue: " HOST_WIDE_INT_PRINT_DEC
8662 " bytes, probing will be required.\n", size);
8663
8664 /* Round size to the nearest multiple of guard_size, and calculate the
8665 residual as the difference between the original size and the rounded
8666 size. */
8667 HOST_WIDE_INT rounded_size = ROUND_DOWN (size, guard_size);
8668 HOST_WIDE_INT residual = size - rounded_size;
8669
8670 /* We can handle a small number of allocations/probes inline. Otherwise
8671 punt to a loop. */
8672 if (rounded_size <= STACK_CLASH_MAX_UNROLL_PAGES * guard_size)
8673 {
8674 temp1 = riscv_force_temporary (temp1, gen_int_mode (guard_size, Pmode));
8675 for (HOST_WIDE_INT i = 0; i < rounded_size; i += guard_size)
8676 {
8677 emit_insn (gen_sub3_insn (stack_pointer_rtx, stack_pointer_rtx, temp1));
8678 insn = plus_constant (Pmode, stack_pointer_rtx, -guard_size);
8679 insn = gen_rtx_SET (stack_pointer_rtx, insn);
8680 riscv_set_frame_expr (insn);
8681 emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
8682 guard_used_by_caller));
8683 emit_insn (gen_blockage ());
8684 }
8685 dump_stack_clash_frame_info (PROBE_INLINE, size != rounded_size);
8686 }
8687 else
8688 {
8689 /* Compute the ending address. */
8690 rtx temp2 = gen_rtx_REG (Pmode, RISCV_PROLOGUE_TEMP2_REGNUM);
8691 temp2 = riscv_force_temporary (temp2, gen_int_mode (rounded_size, Pmode));
8692 insn = emit_insn (gen_sub3_insn (temp2, stack_pointer_rtx, temp2));
8693
8694 /* The size does not represent actual stack pointer address shift
8695 from the top of the frame, as it might be lowered before.
8696 To consider the correct SP addresses for the CFA notes, it is needed
8697 to correct them with the initial offset value. */
8698 HOST_WIDE_INT initial_cfa_offset
8699 = cfun->machine->frame.total_size.to_constant () - size;
8700
8701 if (!frame_pointer_needed)
8702 {
8703 /* We want the CFA independent of the stack pointer for the
8704 duration of the loop. */
8705 add_reg_note (insn, REG_CFA_DEF_CFA,
8706 plus_constant (Pmode, temp2,
8707 initial_cfa_offset + rounded_size));
8708 RTX_FRAME_RELATED_P (insn) = 1;
8709 }
8710
8711 /* This allocates and probes the stack. */
8712 riscv_allocate_and_probe_stack_loop (temp1, NE, stack_pointer_rtx, temp2,
8713 false, guard_size);
8714
8715 /* Now reset the CFA register if needed. */
8716 if (!frame_pointer_needed)
8717 {
8718 insn = get_last_insn ();
8719 add_reg_note (insn, REG_CFA_DEF_CFA,
8720 plus_constant (Pmode, stack_pointer_rtx,
8721 initial_cfa_offset + rounded_size));
8722 RTX_FRAME_RELATED_P (insn) = 1;
8723 }
8724
8725 dump_stack_clash_frame_info (PROBE_LOOP, size != rounded_size);
8726 }
8727
8728 /* Handle any residuals. Residuals of at least MIN_PROBE_THRESHOLD have to
8729 be probed. This maintains the requirement that each page is probed at
8730 least once. For initial probing we probe only if the allocation is
8731 more than GUARD_SIZE - buffer, and below the saved registers we probe
8732 if the amount is larger than buffer. GUARD_SIZE - buffer + buffer ==
8733 GUARD_SIZE. This works that for any allocation that is large enough to
8734 trigger a probe here, we'll have at least one, and if they're not large
8735 enough for this code to emit anything for them, The page would have been
8736 probed by the saving of FP/LR either by this function or any callees. If
8737 we don't have any callees then we won't have more stack adjustments and so
8738 are still safe. */
8739 if (residual)
8740 {
8741 gcc_assert (guard_used_by_caller + byte_sp_alignment <= size);
8742
8743 temp1 = riscv_force_temporary (temp1, gen_int_mode (residual, Pmode));
8744 emit_insn (gen_sub3_insn (stack_pointer_rtx, stack_pointer_rtx, temp1));
8745 insn = plus_constant (Pmode, stack_pointer_rtx, -residual);
8746 insn = gen_rtx_SET (stack_pointer_rtx, insn);
8747 riscv_set_frame_expr (insn);
8748 if (residual >= min_probe_threshold)
8749 {
8750 if (dump_file)
8751 fprintf (dump_file,
8752 "Stack clash prologue residuals: "
8753 HOST_WIDE_INT_PRINT_DEC " bytes, probing will be required."
8754 "\n", residual);
8755
8756 emit_stack_probe (plus_constant (Pmode, stack_pointer_rtx,
8757 guard_used_by_caller));
8758 emit_insn (gen_blockage ());
8759 }
8760 }
8761 }
8762
8763 /* Expand the "prologue" pattern. */
8764
8765 void
8766 riscv_expand_prologue (void)
8767 {
8768 struct riscv_frame_info *frame = &cfun->machine->frame;
8769 poly_int64 remaining_size = frame->total_size;
8770 unsigned mask = frame->mask;
8771 unsigned fmask = frame->fmask;
8772 int spimm, multi_push_additional, stack_adj;
8773 rtx insn, dwarf = NULL_RTX;
8774 unsigned th_int_mask = 0;
8775
8776 if (flag_stack_usage_info)
8777 current_function_static_stack_size = constant_lower_bound (remaining_size);
8778
8779 if (cfun->machine->naked_p)
8780 return;
8781
8782 if (need_shadow_stack_push_pop_p ())
8783 emit_insn (gen_sspush (Pmode, gen_rtx_REG (Pmode, RETURN_ADDR_REGNUM)));
8784
8785 /* prefer multi-push to save-restore libcall. */
8786 if (riscv_use_multi_push (frame))
8787 {
8788 remaining_size -= frame->multi_push_adj_base;
8789 /* If there are vector registers that need to be saved, then it can only
8790 be reduced to the frame->v_sp_offset_top position at most, since the
8791 vector registers will need to be saved one by one by decreasing the SP
8792 later. */
8793 poly_int64 remaining_size_above_varea
8794 = frame->vmask != 0
8795 ? remaining_size - frame->v_sp_offset_top
8796 : remaining_size;
8797
8798 if (known_gt (remaining_size_above_varea, 2 * ZCMP_SP_INC_STEP))
8799 spimm = 3;
8800 else if (known_gt (remaining_size_above_varea, ZCMP_SP_INC_STEP))
8801 spimm = 2;
8802 else if (known_gt (remaining_size_above_varea, 0))
8803 spimm = 1;
8804 else
8805 spimm = 0;
8806 multi_push_additional = spimm * ZCMP_SP_INC_STEP;
8807 frame->multi_push_adj_addi = multi_push_additional;
8808 remaining_size -= multi_push_additional;
8809
8810 /* emit multi push insn & dwarf along with it. */
8811 stack_adj = frame->multi_push_adj_base + multi_push_additional;
8812 insn = emit_insn (riscv_gen_multi_push_pop_insn (
8813 PUSH_IDX, -stack_adj, riscv_multi_push_regs_count (frame->mask)));
8814 dwarf = riscv_adjust_multi_push_cfi_prologue (stack_adj);
8815 RTX_FRAME_RELATED_P (insn) = 1;
8816 REG_NOTES (insn) = dwarf;
8817
8818 /* Temporarily fib that we need not save GPRs. */
8819 frame->mask = 0;
8820
8821 /* push FPRs into the additional reserved space by cm.push. */
8822 if (fmask)
8823 {
8824 unsigned mask_fprs_push
8825 = get_multi_push_fpr_mask (multi_push_additional / UNITS_PER_WORD);
8826 frame->fmask &= mask_fprs_push;
8827 riscv_for_each_saved_reg (remaining_size, riscv_save_reg, false,
8828 false, false);
8829 frame->fmask = fmask & ~mask_fprs_push; /* mask for the rest FPRs. */
8830 }
8831 }
8832 /* When optimizing for size, call a subroutine to save the registers. */
8833 else if (riscv_use_save_libcall (frame))
8834 {
8835 rtx dwarf = NULL_RTX;
8836 dwarf = riscv_adjust_libcall_cfi_prologue ();
8837
8838 remaining_size -= frame->save_libcall_adjustment;
8839 insn = emit_insn (riscv_gen_gpr_save_insn (frame));
8840 frame->mask = 0; /* Temporarily fib that we need not save GPRs. */
8841
8842 RTX_FRAME_RELATED_P (insn) = 1;
8843 REG_NOTES (insn) = dwarf;
8844 }
8845
8846 th_int_mask = th_int_get_mask (frame->mask);
8847 if (th_int_mask && TH_INT_INTERRUPT (cfun))
8848 {
8849 frame->mask &= ~th_int_mask;
8850
8851 /* RISCV_PROLOGUE_TEMP may be used to handle some CSR for
8852 interrupts, such as fcsr. */
8853 if ((TARGET_HARD_FLOAT && frame->fmask)
8854 || (TARGET_ZFINX && frame->mask))
8855 frame->mask |= (1 << RISCV_PROLOGUE_TEMP_REGNUM);
8856
8857 unsigned save_adjustment = th_int_get_save_adjustment ();
8858 frame->gp_sp_offset -= save_adjustment;
8859 remaining_size -= save_adjustment;
8860
8861 insn = emit_insn (gen_th_int_push ());
8862
8863 rtx dwarf = th_int_adjust_cfi_prologue (th_int_mask);
8864 RTX_FRAME_RELATED_P (insn) = 1;
8865 REG_NOTES (insn) = dwarf;
8866 }
8867
8868 /* Save the GP, FP registers. */
8869 if ((frame->mask | frame->fmask) != 0)
8870 {
8871 if (known_gt (remaining_size, frame->frame_pointer_offset))
8872 {
8873 HOST_WIDE_INT step1 = riscv_first_stack_step (frame, remaining_size);
8874 remaining_size -= step1;
8875 insn = gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
8876 GEN_INT (-step1));
8877 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
8878 }
8879 riscv_for_each_saved_reg (remaining_size, riscv_save_reg,
8880 false, false, false);
8881 }
8882
8883 /* Undo the above fib. */
8884 frame->mask = mask;
8885 frame->fmask = fmask;
8886
8887 /* Set up the frame pointer, if we're using one. */
8888 if (frame_pointer_needed)
8889 {
8890 insn = gen_add3_insn (hard_frame_pointer_rtx, stack_pointer_rtx,
8891 GEN_INT ((frame->hard_frame_pointer_offset - remaining_size).to_constant ()));
8892 RTX_FRAME_RELATED_P (emit_insn (insn)) = 1;
8893
8894 riscv_emit_stack_tie (hard_frame_pointer_rtx);
8895 }
8896
8897 /* Save the V registers. */
8898 if (frame->vmask != 0)
8899 riscv_for_each_saved_v_reg (remaining_size, riscv_save_reg, true);
8900
8901 /* Allocate the rest of the frame. */
8902 if (known_gt (remaining_size, 0))
8903 {
8904 /* Two step adjustment:
8905 1.scalable frame. 2.constant frame. */
8906 poly_int64 scalable_frame (0, 0);
8907 if (!remaining_size.is_constant ())
8908 {
8909 /* First for scalable frame. */
8910 poly_int64 scalable_frame = remaining_size;
8911 scalable_frame.coeffs[0] = remaining_size.coeffs[1];
8912 riscv_v_adjust_scalable_frame (stack_pointer_rtx, scalable_frame, false);
8913 remaining_size -= scalable_frame;
8914 }
8915
8916 /* Second step for constant frame. */
8917 HOST_WIDE_INT constant_frame = remaining_size.to_constant ();
8918 if (constant_frame == 0)
8919 {
8920 /* We must have allocated stack space for the scalable frame.
8921 Emit a stack tie if we have a frame pointer so that the
8922 allocation is ordered WRT fp setup and subsequent writes
8923 into the frame. */
8924 if (frame_pointer_needed)
8925 riscv_emit_stack_tie (hard_frame_pointer_rtx);
8926 return;
8927 }
8928
8929 riscv_allocate_and_probe_stack_space (RISCV_PROLOGUE_TEMP (Pmode), constant_frame);
8930 }
8931 else if (flag_stack_clash_protection)
8932 {
8933 if (known_eq (frame->total_size, 0))
8934 dump_stack_clash_frame_info (NO_PROBE_NO_FRAME, false);
8935 else
8936 dump_stack_clash_frame_info (NO_PROBE_SMALL_FRAME, true);
8937 }
8938 }
8939
8940 static rtx
8941 riscv_adjust_multi_pop_cfi_epilogue (int saved_size)
8942 {
8943 rtx dwarf = NULL_RTX;
8944 rtx adjust_sp_rtx, reg;
8945 unsigned int mask = cfun->machine->frame.mask;
8946
8947 if (mask & S10_MASK)
8948 mask |= S11_MASK;
8949
8950 /* Debug info for adjust sp. */
8951 adjust_sp_rtx
8952 = gen_rtx_SET (stack_pointer_rtx,
8953 plus_constant (Pmode, stack_pointer_rtx, saved_size));
8954 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx, dwarf);
8955
8956 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
8957 if (BITSET_P (mask, regno - GP_REG_FIRST))
8958 {
8959 reg = gen_rtx_REG (Pmode, regno);
8960 dwarf = alloc_reg_note (REG_CFA_RESTORE, reg, dwarf);
8961 }
8962
8963 return dwarf;
8964 }
8965
8966 static rtx
8967 riscv_adjust_libcall_cfi_epilogue ()
8968 {
8969 rtx dwarf = NULL_RTX;
8970 rtx adjust_sp_rtx, reg;
8971 int saved_size = cfun->machine->frame.save_libcall_adjustment;
8972
8973 /* Debug info for adjust sp. */
8974 adjust_sp_rtx =
8975 gen_rtx_SET (stack_pointer_rtx,
8976 gen_rtx_PLUS (Pmode, stack_pointer_rtx, GEN_INT (saved_size)));
8977 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, adjust_sp_rtx,
8978 dwarf);
8979
8980 for (int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
8981 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
8982 {
8983 reg = gen_rtx_REG (Pmode, regno);
8984 dwarf = alloc_reg_note (REG_CFA_RESTORE, reg, dwarf);
8985 }
8986
8987 return dwarf;
8988 }
8989
8990 static void
8991 riscv_gen_multi_pop_insn (bool use_multi_pop_normal, unsigned mask,
8992 unsigned multipop_size)
8993 {
8994 rtx insn;
8995 unsigned regs_count = riscv_multi_push_regs_count (mask);
8996
8997 if (!use_multi_pop_normal)
8998 insn = emit_insn (
8999 riscv_gen_multi_push_pop_insn (POP_IDX, multipop_size, regs_count));
9000 else
9001 insn = emit_jump_insn (
9002 riscv_gen_multi_push_pop_insn (POPRET_IDX, multipop_size, regs_count));
9003
9004 rtx dwarf = riscv_adjust_multi_pop_cfi_epilogue (multipop_size);
9005 RTX_FRAME_RELATED_P (insn) = 1;
9006 REG_NOTES (insn) = dwarf;
9007 }
9008
9009 /* Expand an "epilogue", "sibcall_epilogue", or "eh_return_internal" pattern;
9010 style says which. */
9011
9012 void
9013 riscv_expand_epilogue (int style)
9014 {
9015 /* Split the frame into 3 steps. STEP1 is the amount of stack we should
9016 deallocate before restoring the registers. STEP2 is the amount we
9017 should deallocate afterwards including the callee saved regs. STEP3
9018 is the amount deallocated by save-restore libcall.
9019
9020 Start off by assuming that no registers need to be restored. */
9021 struct riscv_frame_info *frame = &cfun->machine->frame;
9022 unsigned mask = frame->mask;
9023 unsigned fmask = frame->fmask;
9024 unsigned mask_fprs_push = 0;
9025 poly_int64 step2 = 0;
9026 bool use_multi_pop_normal
9027 = ((style == NORMAL_RETURN) && riscv_use_multi_push (frame));
9028 bool use_multi_pop_sibcall
9029 = ((style == SIBCALL_RETURN) && riscv_use_multi_push (frame));
9030 bool use_multi_pop = use_multi_pop_normal || use_multi_pop_sibcall;
9031
9032 bool use_restore_libcall
9033 = !use_multi_pop
9034 && ((style == NORMAL_RETURN) && riscv_use_save_libcall (frame));
9035 unsigned libcall_size = use_restore_libcall && !use_multi_pop
9036 ? frame->save_libcall_adjustment
9037 : 0;
9038 unsigned multipop_size
9039 = use_multi_pop ? frame->multi_push_adj_base + frame->multi_push_adj_addi
9040 : 0;
9041 rtx ra = gen_rtx_REG (Pmode, RETURN_ADDR_REGNUM);
9042 rtx t0 = gen_rtx_REG (Pmode, RISCV_PROLOGUE_TEMP_REGNUM);
9043 unsigned th_int_mask = 0;
9044 rtx insn;
9045
9046 /* We need to add memory barrier to prevent read from deallocated stack. */
9047 bool need_barrier_p = known_ne (get_frame_size ()
9048 + cfun->machine->frame.arg_pointer_offset, 0);
9049
9050 if (cfun->machine->naked_p)
9051 {
9052 gcc_assert (style == NORMAL_RETURN);
9053
9054 emit_jump_insn (gen_return ());
9055
9056 return;
9057 }
9058
9059 if ((style == NORMAL_RETURN) && riscv_can_use_return_insn ())
9060 {
9061 emit_jump_insn (gen_return ());
9062 return;
9063 }
9064
9065 /* Reset the epilogue cfa info before starting to emit the epilogue. */
9066 epilogue_cfa_sp_offset = 0;
9067
9068 /* Move past any dynamic stack allocations. */
9069 if (cfun->calls_alloca)
9070 {
9071 /* Emit a barrier to prevent loads from a deallocated stack. */
9072 riscv_emit_stack_tie (hard_frame_pointer_rtx);
9073 need_barrier_p = false;
9074
9075 poly_int64 adjust_offset = -frame->hard_frame_pointer_offset;
9076 rtx dwarf_adj = gen_int_mode (adjust_offset, Pmode);
9077 rtx adjust = NULL_RTX;
9078 bool sum_of_two_s12 = false;
9079 HOST_WIDE_INT one, two;
9080
9081 if (!adjust_offset.is_constant ())
9082 {
9083 rtx tmp1 = RISCV_PROLOGUE_TEMP (Pmode);
9084 rtx tmp2 = RISCV_PROLOGUE_TEMP2 (Pmode);
9085 riscv_legitimize_poly_move (Pmode, tmp1, tmp2,
9086 gen_int_mode (adjust_offset, Pmode));
9087 adjust = tmp1;
9088 }
9089 else
9090 {
9091 HOST_WIDE_INT adj_off_value = adjust_offset.to_constant ();
9092 if (SMALL_OPERAND (adj_off_value))
9093 {
9094 adjust = GEN_INT (adj_off_value);
9095 }
9096 else if (SUM_OF_TWO_S12_ALGN (adj_off_value))
9097 {
9098 riscv_split_sum_of_two_s12 (adj_off_value, &one, &two);
9099 dwarf_adj = adjust = GEN_INT (one);
9100 sum_of_two_s12 = true;
9101 }
9102 else
9103 {
9104 riscv_emit_move (RISCV_PROLOGUE_TEMP (Pmode),
9105 GEN_INT (adj_off_value));
9106 adjust = RISCV_PROLOGUE_TEMP (Pmode);
9107 }
9108 }
9109
9110 insn = emit_insn (
9111 gen_add3_insn (stack_pointer_rtx, hard_frame_pointer_rtx,
9112 adjust));
9113
9114 rtx dwarf = NULL_RTX;
9115 rtx cfa_adjust_value = gen_rtx_PLUS (Pmode, hard_frame_pointer_rtx,
9116 dwarf_adj);
9117 rtx cfa_adjust_rtx = gen_rtx_SET (stack_pointer_rtx, cfa_adjust_value);
9118 dwarf = alloc_reg_note (REG_CFA_ADJUST_CFA, cfa_adjust_rtx, dwarf);
9119
9120 RTX_FRAME_RELATED_P (insn) = 1;
9121
9122 REG_NOTES (insn) = dwarf;
9123
9124 if (sum_of_two_s12)
9125 {
9126 insn = emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
9127 GEN_INT (two)));
9128 RTX_FRAME_RELATED_P (insn) = 1;
9129 }
9130 }
9131
9132 if (use_restore_libcall || use_multi_pop)
9133 frame->mask = 0; /* Temporarily fib that we need not restore GPRs. */
9134
9135 /* If we need to restore registers, deallocate as much stack as
9136 possible in the second step without going out of range. */
9137 if (use_multi_pop)
9138 {
9139 if (frame->fmask
9140 && known_gt (frame->total_size - multipop_size,
9141 frame->frame_pointer_offset))
9142 step2
9143 = riscv_first_stack_step (frame, frame->total_size - multipop_size);
9144 }
9145 else if ((frame->mask | frame->fmask) != 0)
9146 step2 = riscv_first_stack_step (frame, frame->total_size - libcall_size);
9147
9148 if (use_restore_libcall || use_multi_pop)
9149 frame->mask = mask; /* Undo the above fib. */
9150
9151 poly_int64 step1;
9152 /* STEP1 must be set to the bottom of vector registers save area if any
9153 vector registers need be preserved. */
9154 if (frame->vmask != 0)
9155 {
9156 step1 = frame->v_sp_offset_bottom;
9157 step2 = frame->total_size - step1 - libcall_size - multipop_size;
9158 }
9159 else
9160 step1 = frame->total_size - step2 - libcall_size - multipop_size;
9161
9162 /* Set TARGET to BASE + STEP1. */
9163 if (known_gt (step1, 0))
9164 {
9165 /* Emit a barrier to prevent loads from a deallocated stack. */
9166 riscv_emit_stack_tie (hard_frame_pointer_rtx);
9167 need_barrier_p = false;
9168
9169 /* Restore the scalable frame which is assigned in prologue. */
9170 if (!step1.is_constant ())
9171 {
9172 poly_int64 scalable_frame = step1;
9173 scalable_frame.coeffs[0] = step1.coeffs[1];
9174 riscv_v_adjust_scalable_frame (stack_pointer_rtx, scalable_frame,
9175 true);
9176 step1 -= scalable_frame;
9177 }
9178
9179 /* Get an rtx for STEP1 that we can add to BASE.
9180 Skip if adjust equal to zero. */
9181 HOST_WIDE_INT step1_value = step1.to_constant ();
9182 if (step1_value != 0)
9183 {
9184 rtx adjust = GEN_INT (step1_value);
9185 if (SUM_OF_TWO_S12_ALGN (step1_value))
9186 {
9187 HOST_WIDE_INT one, two;
9188 riscv_split_sum_of_two_s12 (step1_value, &one, &two);
9189 insn = emit_insn (gen_add3_insn (stack_pointer_rtx,
9190 stack_pointer_rtx,
9191 GEN_INT (one)));
9192 RTX_FRAME_RELATED_P (insn) = 1;
9193 adjust = GEN_INT (two);
9194 }
9195 else if (!SMALL_OPERAND (step1_value))
9196 {
9197 riscv_emit_move (RISCV_PROLOGUE_TEMP (Pmode), adjust);
9198 adjust = RISCV_PROLOGUE_TEMP (Pmode);
9199 }
9200
9201 insn = emit_insn (gen_add3_insn (stack_pointer_rtx,
9202 stack_pointer_rtx,
9203 adjust));
9204 rtx dwarf = NULL_RTX;
9205 rtx cfa_adjust_rtx
9206 = gen_rtx_PLUS (Pmode, stack_pointer_rtx,
9207 gen_int_mode (step2 + libcall_size + multipop_size,
9208 Pmode));
9209
9210 dwarf = alloc_reg_note (REG_CFA_DEF_CFA, cfa_adjust_rtx, dwarf);
9211 RTX_FRAME_RELATED_P (insn) = 1;
9212
9213 REG_NOTES (insn) = dwarf;
9214 }
9215 }
9216 else if (frame_pointer_needed)
9217 {
9218 /* Tell riscv_restore_reg to emit dwarf to redefine CFA when restoring
9219 old value of FP. */
9220 epilogue_cfa_sp_offset = step2;
9221 }
9222
9223 if (use_multi_pop)
9224 {
9225 frame->mask = 0; /* Temporarily fib that we need not restore GPRs. */
9226 if (fmask)
9227 {
9228 mask_fprs_push = get_multi_push_fpr_mask (frame->multi_push_adj_addi
9229 / UNITS_PER_WORD);
9230 frame->fmask &= ~mask_fprs_push; /* FPRs not saved by cm.push */
9231 }
9232 }
9233 else if (use_restore_libcall)
9234 frame->mask = 0; /* Temporarily fib that we need not restore GPRs. */
9235
9236 th_int_mask = th_int_get_mask (frame->mask);
9237 if (th_int_mask && TH_INT_INTERRUPT (cfun))
9238 {
9239 frame->mask &= ~th_int_mask;
9240
9241 /* RISCV_PROLOGUE_TEMP may be used to handle some CSR for
9242 interrupts, such as fcsr. */
9243 if ((TARGET_HARD_FLOAT && frame->fmask)
9244 || (TARGET_ZFINX && frame->mask))
9245 frame->mask |= (1 << RISCV_PROLOGUE_TEMP_REGNUM);
9246 }
9247
9248 /* Restore the registers. */
9249 riscv_for_each_saved_v_reg (step2, riscv_restore_reg, false);
9250 riscv_for_each_saved_reg (frame->total_size - step2 - libcall_size
9251 - multipop_size,
9252 riscv_restore_reg, true, style == EXCEPTION_RETURN,
9253 style == SIBCALL_RETURN);
9254
9255 if (th_int_mask && TH_INT_INTERRUPT (cfun))
9256 {
9257 frame->mask = mask; /* Undo the above fib. */
9258 unsigned save_adjustment = th_int_get_save_adjustment ();
9259 gcc_assert (step2.to_constant () >= save_adjustment);
9260 step2 -= save_adjustment;
9261 }
9262
9263 if (use_restore_libcall)
9264 frame->mask = mask; /* Undo the above fib. */
9265
9266 if (need_barrier_p)
9267 riscv_emit_stack_tie (hard_frame_pointer_rtx);
9268
9269 /* Deallocate the final bit of the frame. */
9270 if (step2.to_constant () > 0)
9271 {
9272 insn = emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
9273 GEN_INT (step2.to_constant ())));
9274
9275 rtx dwarf = NULL_RTX;
9276 rtx cfa_adjust_rtx
9277 = gen_rtx_PLUS (Pmode, stack_pointer_rtx,
9278 GEN_INT (libcall_size + multipop_size));
9279 dwarf = alloc_reg_note (REG_CFA_DEF_CFA, cfa_adjust_rtx, dwarf);
9280 RTX_FRAME_RELATED_P (insn) = 1;
9281
9282 REG_NOTES (insn) = dwarf;
9283 }
9284
9285 if (use_multi_pop)
9286 {
9287 /* restore FPRs pushed by cm.push. */
9288 frame->fmask = fmask & mask_fprs_push;
9289 if (frame->fmask)
9290 riscv_for_each_saved_reg (frame->total_size - libcall_size
9291 - multipop_size,
9292 riscv_restore_reg, true,
9293 style == EXCEPTION_RETURN, false);
9294
9295 /* Undo the above fib. */
9296 frame->mask = mask;
9297 frame->fmask = fmask;
9298 riscv_gen_multi_pop_insn (use_multi_pop_normal, frame->mask,
9299 multipop_size);
9300 if (use_multi_pop_normal)
9301 return;
9302 }
9303 else if (use_restore_libcall)
9304 {
9305 rtx dwarf = riscv_adjust_libcall_cfi_epilogue ();
9306 insn = emit_insn (gen_gpr_restore (GEN_INT (riscv_save_libcall_count (mask))));
9307 RTX_FRAME_RELATED_P (insn) = 1;
9308 REG_NOTES (insn) = dwarf;
9309
9310 emit_jump_insn (gen_gpr_restore_return (ra));
9311 return;
9312 }
9313
9314 /* Add in the __builtin_eh_return stack adjustment. */
9315 if ((style == EXCEPTION_RETURN) && crtl->calls_eh_return)
9316 emit_insn (gen_add3_insn (stack_pointer_rtx, stack_pointer_rtx,
9317 EH_RETURN_STACKADJ_RTX));
9318
9319 if (need_shadow_stack_push_pop_p ()
9320 && !((style == EXCEPTION_RETURN) && crtl->calls_eh_return))
9321 {
9322 if (BITSET_P (cfun->machine->frame.mask, RETURN_ADDR_REGNUM)
9323 && style != SIBCALL_RETURN
9324 && !cfun->machine->interrupt_handler_p)
9325 emit_insn (gen_sspopchk (Pmode, t0));
9326 else
9327 emit_insn (gen_sspopchk (Pmode, ra));
9328 }
9329
9330 /* Return from interrupt. */
9331 if (cfun->machine->interrupt_handler_p)
9332 {
9333 enum riscv_privilege_levels mode = cfun->machine->interrupt_mode;
9334
9335 gcc_assert (mode != UNKNOWN_MODE);
9336
9337 if (th_int_mask && TH_INT_INTERRUPT (cfun))
9338 emit_jump_insn (gen_th_int_pop ());
9339 else if (mode == MACHINE_MODE)
9340 emit_jump_insn (gen_riscv_mret ());
9341 else if (mode == SUPERVISOR_MODE)
9342 emit_jump_insn (gen_riscv_sret ());
9343 else
9344 emit_jump_insn (gen_riscv_uret ());
9345 }
9346 else if (style != SIBCALL_RETURN)
9347 {
9348 if (need_shadow_stack_push_pop_p ()
9349 && !((style == EXCEPTION_RETURN) && crtl->calls_eh_return)
9350 && BITSET_P (cfun->machine->frame.mask, RETURN_ADDR_REGNUM)
9351 && !cfun->machine->interrupt_handler_p)
9352 emit_jump_insn (gen_simple_return_internal (t0));
9353 else
9354 emit_jump_insn (gen_simple_return_internal (ra));
9355 }
9356 }
9357
9358 /* Implement EPILOGUE_USES. */
9359
9360 bool
9361 riscv_epilogue_uses (unsigned int regno)
9362 {
9363 if (regno == RETURN_ADDR_REGNUM)
9364 return true;
9365
9366 if (epilogue_completed && cfun->machine->interrupt_handler_p)
9367 {
9368 /* An interrupt function restores temp regs, so we must indicate that
9369 they are live at function end. */
9370 if (df_regs_ever_live_p (regno)
9371 || (!crtl->is_leaf && call_used_or_fixed_reg_p (regno)))
9372 return true;
9373 }
9374
9375 return false;
9376 }
9377
9378 static bool
9379 riscv_avoid_shrink_wrapping_separate ()
9380 {
9381 if (riscv_use_save_libcall (&cfun->machine->frame)
9382 || cfun->machine->interrupt_handler_p
9383 || !cfun->machine->frame.gp_sp_offset.is_constant ())
9384 return true;
9385
9386 return false;
9387 }
9388
9389 /* Implement TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS. */
9390
9391 static sbitmap
9392 riscv_get_separate_components (void)
9393 {
9394 HOST_WIDE_INT offset;
9395 sbitmap components = sbitmap_alloc (FIRST_PSEUDO_REGISTER);
9396 bitmap_clear (components);
9397
9398 if (riscv_avoid_shrink_wrapping_separate ())
9399 return components;
9400
9401 offset = cfun->machine->frame.gp_sp_offset.to_constant ();
9402 for (unsigned int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
9403 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
9404 {
9405 /* We can only wrap registers that have small operand offsets.
9406 For large offsets a pseudo register might be needed which
9407 cannot be created during the shrink wrapping pass. */
9408 if (SMALL_OPERAND (offset))
9409 bitmap_set_bit (components, regno);
9410
9411 offset -= UNITS_PER_WORD;
9412 }
9413
9414 offset = cfun->machine->frame.fp_sp_offset.to_constant ();
9415 for (unsigned int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
9416 if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
9417 {
9418 machine_mode mode = TARGET_DOUBLE_FLOAT ? DFmode : SFmode;
9419
9420 /* We can only wrap registers that have small operand offsets.
9421 For large offsets a pseudo register might be needed which
9422 cannot be created during the shrink wrapping pass. */
9423 if (SMALL_OPERAND (offset))
9424 bitmap_set_bit (components, regno);
9425
9426 offset -= GET_MODE_SIZE (mode).to_constant ();
9427 }
9428
9429 /* Don't mess with the hard frame pointer. */
9430 if (frame_pointer_needed)
9431 bitmap_clear_bit (components, HARD_FRAME_POINTER_REGNUM);
9432
9433 bitmap_clear_bit (components, RETURN_ADDR_REGNUM);
9434
9435 return components;
9436 }
9437
9438 /* Implement TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB. */
9439
9440 static sbitmap
9441 riscv_components_for_bb (basic_block bb)
9442 {
9443 bitmap in = DF_LIVE_IN (bb);
9444 bitmap gen = &DF_LIVE_BB_INFO (bb)->gen;
9445 bitmap kill = &DF_LIVE_BB_INFO (bb)->kill;
9446
9447 sbitmap components = sbitmap_alloc (FIRST_PSEUDO_REGISTER);
9448 bitmap_clear (components);
9449
9450 function_abi_aggregator callee_abis;
9451 rtx_insn *insn;
9452 FOR_BB_INSNS (bb, insn)
9453 if (CALL_P (insn))
9454 callee_abis.note_callee_abi (insn_callee_abi (insn));
9455 HARD_REG_SET extra_caller_saves = callee_abis.caller_save_regs (*crtl->abi);
9456
9457 /* GPRs are used in a bb if they are in the IN, GEN, or KILL sets. */
9458 for (unsigned int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
9459 if (!fixed_regs[regno]
9460 && !crtl->abi->clobbers_full_reg_p (regno)
9461 && (TEST_HARD_REG_BIT (extra_caller_saves, regno)
9462 || bitmap_bit_p (in, regno)
9463 || bitmap_bit_p (gen, regno)
9464 || bitmap_bit_p (kill, regno)))
9465 bitmap_set_bit (components, regno);
9466
9467 for (unsigned int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
9468 if (!fixed_regs[regno]
9469 && !crtl->abi->clobbers_full_reg_p (regno)
9470 && (TEST_HARD_REG_BIT (extra_caller_saves, regno)
9471 || bitmap_bit_p (in, regno)
9472 || bitmap_bit_p (gen, regno)
9473 || bitmap_bit_p (kill, regno)))
9474 bitmap_set_bit (components, regno);
9475
9476 return components;
9477 }
9478
9479 /* Implement TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS. */
9480
9481 static void
9482 riscv_disqualify_components (sbitmap, edge, sbitmap, bool)
9483 {
9484 /* Nothing to do for riscv. */
9485 }
9486
9487 static void
9488 riscv_process_components (sbitmap components, bool prologue_p)
9489 {
9490 HOST_WIDE_INT offset;
9491 riscv_save_restore_fn fn = prologue_p? riscv_save_reg : riscv_restore_reg;
9492
9493 offset = cfun->machine->frame.gp_sp_offset.to_constant ();
9494 for (unsigned int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
9495 if (BITSET_P (cfun->machine->frame.mask, regno - GP_REG_FIRST))
9496 {
9497 if (bitmap_bit_p (components, regno))
9498 riscv_save_restore_reg (word_mode, regno, offset, fn);
9499
9500 offset -= UNITS_PER_WORD;
9501 }
9502
9503 offset = cfun->machine->frame.fp_sp_offset.to_constant ();
9504 for (unsigned int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
9505 if (BITSET_P (cfun->machine->frame.fmask, regno - FP_REG_FIRST))
9506 {
9507 machine_mode mode = TARGET_DOUBLE_FLOAT ? DFmode : SFmode;
9508
9509 if (bitmap_bit_p (components, regno))
9510 riscv_save_restore_reg (mode, regno, offset, fn);
9511
9512 offset -= GET_MODE_SIZE (mode).to_constant ();
9513 }
9514 }
9515
9516 /* Implement TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS. */
9517
9518 static void
9519 riscv_emit_prologue_components (sbitmap components)
9520 {
9521 riscv_process_components (components, true);
9522 }
9523
9524 /* Implement TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS. */
9525
9526 static void
9527 riscv_emit_epilogue_components (sbitmap components)
9528 {
9529 riscv_process_components (components, false);
9530 }
9531
9532 static void
9533 riscv_set_handled_components (sbitmap components)
9534 {
9535 for (unsigned int regno = GP_REG_FIRST; regno <= GP_REG_LAST; regno++)
9536 if (bitmap_bit_p (components, regno))
9537 cfun->machine->reg_is_wrapped_separately[regno] = true;
9538
9539 for (unsigned int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
9540 if (bitmap_bit_p (components, regno))
9541 cfun->machine->reg_is_wrapped_separately[regno] = true;
9542 }
9543
9544 /* Return nonzero if this function is known to have a null epilogue.
9545 This allows the optimizer to omit jumps to jumps if no stack
9546 was created. */
9547
9548 bool
9549 riscv_can_use_return_insn (void)
9550 {
9551 return (reload_completed && known_eq (cfun->machine->frame.total_size, 0)
9552 && ! cfun->machine->interrupt_handler_p
9553 && ! need_shadow_stack_push_pop_p ());
9554 }
9555
9556 /* Given that there exists at least one variable that is set (produced)
9557 by OUT_INSN and read (consumed) by IN_INSN, return true iff
9558 IN_INSN represents one or more memory store operations and none of
9559 the variables set by OUT_INSN is used by IN_INSN as the address of a
9560 store operation. If either IN_INSN or OUT_INSN does not represent
9561 a "single" RTL SET expression (as loosely defined by the
9562 implementation of the single_set function) or a PARALLEL with only
9563 SETs, CLOBBERs, and USEs inside, this function returns false.
9564
9565 Borrowed from rs6000, riscv_store_data_bypass_p checks for certain
9566 conditions that result in assertion failures in the generic
9567 store_data_bypass_p function and returns FALSE in such cases.
9568
9569 This is required to make -msave-restore work with the sifive-7
9570 pipeline description. */
9571
9572 bool
9573 riscv_store_data_bypass_p (rtx_insn *out_insn, rtx_insn *in_insn)
9574 {
9575 rtx out_set, in_set;
9576 rtx out_pat, in_pat;
9577 rtx out_exp, in_exp;
9578 int i, j;
9579
9580 in_set = single_set (in_insn);
9581 if (in_set)
9582 {
9583 if (MEM_P (SET_DEST (in_set)))
9584 {
9585 out_set = single_set (out_insn);
9586 if (!out_set)
9587 {
9588 out_pat = PATTERN (out_insn);
9589 if (GET_CODE (out_pat) == PARALLEL)
9590 {
9591 for (i = 0; i < XVECLEN (out_pat, 0); i++)
9592 {
9593 out_exp = XVECEXP (out_pat, 0, i);
9594 if ((GET_CODE (out_exp) == CLOBBER)
9595 || (GET_CODE (out_exp) == USE))
9596 continue;
9597 else if (GET_CODE (out_exp) != SET)
9598 return false;
9599 }
9600 }
9601 }
9602 }
9603 }
9604 else
9605 {
9606 in_pat = PATTERN (in_insn);
9607 if (GET_CODE (in_pat) != PARALLEL)
9608 return false;
9609
9610 for (i = 0; i < XVECLEN (in_pat, 0); i++)
9611 {
9612 in_exp = XVECEXP (in_pat, 0, i);
9613 if ((GET_CODE (in_exp) == CLOBBER) || (GET_CODE (in_exp) == USE))
9614 continue;
9615 else if (GET_CODE (in_exp) != SET)
9616 return false;
9617
9618 if (MEM_P (SET_DEST (in_exp)))
9619 {
9620 out_set = single_set (out_insn);
9621 if (!out_set)
9622 {
9623 out_pat = PATTERN (out_insn);
9624 if (GET_CODE (out_pat) != PARALLEL)
9625 return false;
9626 for (j = 0; j < XVECLEN (out_pat, 0); j++)
9627 {
9628 out_exp = XVECEXP (out_pat, 0, j);
9629 if ((GET_CODE (out_exp) == CLOBBER)
9630 || (GET_CODE (out_exp) == USE))
9631 continue;
9632 else if (GET_CODE (out_exp) != SET)
9633 return false;
9634 }
9635 }
9636 }
9637 }
9638 }
9639
9640 return store_data_bypass_p (out_insn, in_insn);
9641 }
9642
9643 /* Implement TARGET_SECONDARY_MEMORY_NEEDED.
9644
9645 When floating-point registers are wider than integer ones, moves between
9646 them must go through memory. */
9647
9648 static bool
9649 riscv_secondary_memory_needed (machine_mode mode, reg_class_t class1,
9650 reg_class_t class2)
9651 {
9652 bool class1_is_fpr = class1 == FP_REGS || class1 == RVC_FP_REGS;
9653 bool class2_is_fpr = class2 == FP_REGS || class2 == RVC_FP_REGS;
9654 return (!riscv_v_ext_mode_p (mode)
9655 && GET_MODE_SIZE (mode).to_constant () > UNITS_PER_WORD
9656 && (class1_is_fpr != class2_is_fpr)
9657 && !TARGET_XTHEADFMV
9658 && !TARGET_ZFA);
9659 }
9660
9661 /* Implement TARGET_REGISTER_MOVE_COST. */
9662
9663 int
9664 riscv_register_move_cost (machine_mode mode,
9665 reg_class_t from, reg_class_t to)
9666 {
9667 bool from_is_fpr = from == FP_REGS || from == RVC_FP_REGS;
9668 bool from_is_gpr = from == GR_REGS || from == RVC_GR_REGS;
9669 bool to_is_fpr = to == FP_REGS || to == RVC_FP_REGS;
9670 bool to_is_gpr = to == GR_REGS || to == RVC_GR_REGS;
9671 if ((from_is_fpr && to_is_gpr) || (from_is_gpr && to_is_fpr))
9672 return tune_param->fmv_cost;
9673
9674 if (from == V_REGS)
9675 {
9676 if (to == GR_REGS)
9677 return get_vector_costs ()->regmove->VR2GR;
9678 else if (to == FP_REGS)
9679 return get_vector_costs ()->regmove->VR2FR;
9680 }
9681
9682 if (to == V_REGS)
9683 {
9684 if (from == GR_REGS)
9685 return get_vector_costs ()->regmove->GR2VR;
9686 else if (from == FP_REGS)
9687 return get_vector_costs ()->regmove->FR2VR;
9688 }
9689
9690 return riscv_secondary_memory_needed (mode, from, to) ? 8 : 2;
9691 }
9692
9693 /* Implement TARGET_HARD_REGNO_NREGS. */
9694
9695 static unsigned int
9696 riscv_hard_regno_nregs (unsigned int regno, machine_mode mode)
9697 {
9698 if (riscv_v_ext_vector_mode_p (mode))
9699 {
9700 /* Handle fractional LMUL, it only occupy part of vector register but
9701 still need one vector register to hold. */
9702 if (maybe_lt (GET_MODE_SIZE (mode), UNITS_PER_V_REG))
9703 return 1;
9704
9705 return exact_div (GET_MODE_SIZE (mode), UNITS_PER_V_REG).to_constant ();
9706 }
9707
9708 /* For tuple modes, the number of register = NF * LMUL. */
9709 if (riscv_v_ext_tuple_mode_p (mode))
9710 {
9711 unsigned int nf = riscv_vector::get_nf (mode);
9712 machine_mode subpart_mode = riscv_vector::get_subpart_mode (mode);
9713 poly_int64 size = GET_MODE_SIZE (subpart_mode);
9714 gcc_assert (known_eq (size * nf, GET_MODE_SIZE (mode)));
9715 if (maybe_lt (size, UNITS_PER_V_REG))
9716 return nf;
9717 else
9718 {
9719 unsigned int lmul = exact_div (size, UNITS_PER_V_REG).to_constant ();
9720 return nf * lmul;
9721 }
9722 }
9723
9724 /* For VLS modes, we allocate registers according to TARGET_MIN_VLEN. */
9725 if (riscv_v_ext_vls_mode_p (mode))
9726 {
9727 int size = GET_MODE_BITSIZE (mode).to_constant ();
9728 if (size < TARGET_MIN_VLEN)
9729 return 1;
9730 else
9731 return size / TARGET_MIN_VLEN;
9732 }
9733
9734 /* mode for VL or VTYPE are just a marker, not holding value,
9735 so it always consume one register. */
9736 if (VTYPE_REG_P (regno) || VL_REG_P (regno) || VXRM_REG_P (regno)
9737 || FRM_REG_P (regno))
9738 return 1;
9739
9740 /* Assume every valid non-vector mode fits in one vector register. */
9741 if (V_REG_P (regno))
9742 return 1;
9743
9744 if (FP_REG_P (regno))
9745 return (GET_MODE_SIZE (mode).to_constant () + UNITS_PER_FP_REG - 1) / UNITS_PER_FP_REG;
9746
9747 /* All other registers are word-sized. */
9748 return (GET_MODE_SIZE (mode).to_constant () + UNITS_PER_WORD - 1) / UNITS_PER_WORD;
9749 }
9750
9751 /* Implement TARGET_HARD_REGNO_MODE_OK. */
9752
9753 static bool
9754 riscv_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
9755 {
9756 unsigned int nregs = riscv_hard_regno_nregs (regno, mode);
9757
9758 if (GP_REG_P (regno))
9759 {
9760 if (riscv_v_ext_mode_p (mode))
9761 return false;
9762
9763 if (!GP_REG_P (regno + nregs - 1))
9764 return false;
9765 }
9766 else if (FP_REG_P (regno))
9767 {
9768 if (riscv_v_ext_mode_p (mode))
9769 return false;
9770
9771 if (!FP_REG_P (regno + nregs - 1))
9772 return false;
9773
9774 if (GET_MODE_CLASS (mode) != MODE_FLOAT
9775 && GET_MODE_CLASS (mode) != MODE_COMPLEX_FLOAT)
9776 return false;
9777
9778 /* Only use callee-saved registers if a potential callee is guaranteed
9779 to spill the requisite width. */
9780 if (GET_MODE_UNIT_SIZE (mode) > UNITS_PER_FP_REG
9781 || (!call_used_or_fixed_reg_p (regno)
9782 && GET_MODE_UNIT_SIZE (mode) > UNITS_PER_FP_ARG))
9783 return false;
9784 }
9785 else if (V_REG_P (regno))
9786 {
9787 if (!riscv_v_ext_mode_p (mode))
9788 return false;
9789
9790 if (!V_REG_P (regno + nregs - 1))
9791 return false;
9792
9793 int regno_alignment = riscv_get_v_regno_alignment (mode);
9794 if (regno_alignment != 1)
9795 return ((regno % regno_alignment) == 0);
9796 }
9797 else if (VTYPE_REG_P (regno) || VL_REG_P (regno) || VXRM_REG_P (regno)
9798 || FRM_REG_P (regno))
9799 return true;
9800 else
9801 return false;
9802
9803 /* Require same callee-savedness for all registers. */
9804 for (unsigned i = 1; i < nregs; i++)
9805 if (call_used_or_fixed_reg_p (regno)
9806 != call_used_or_fixed_reg_p (regno + i))
9807 return false;
9808
9809 /* Only use even registers in RV32 ZDINX */
9810 if (!TARGET_64BIT && TARGET_ZDINX){
9811 if (GET_MODE_CLASS (mode) == MODE_FLOAT &&
9812 GET_MODE_UNIT_SIZE (mode) == GET_MODE_SIZE (DFmode))
9813 return !(regno & 1);
9814 }
9815
9816 return true;
9817 }
9818
9819 /* Implement TARGET_MODES_TIEABLE_P.
9820
9821 Don't allow floating-point modes to be tied, since type punning of
9822 single-precision and double-precision is implementation defined. */
9823
9824 static bool
9825 riscv_modes_tieable_p (machine_mode mode1, machine_mode mode2)
9826 {
9827 /* We don't allow different REG_CLASS modes tieable since it
9828 will cause ICE in register allocation (RA).
9829 E.g. V2SI and DI are not tieable. */
9830 if (riscv_v_ext_mode_p (mode1) != riscv_v_ext_mode_p (mode2))
9831 return false;
9832 return (mode1 == mode2
9833 || !(GET_MODE_CLASS (mode1) == MODE_FLOAT
9834 && GET_MODE_CLASS (mode2) == MODE_FLOAT));
9835 }
9836
9837 /* Implement TARGET_CLASS_MAX_NREGS. */
9838
9839 static unsigned char
9840 riscv_class_max_nregs (reg_class_t rclass, machine_mode mode)
9841 {
9842 if (reg_class_subset_p (rclass, FP_REGS))
9843 return riscv_hard_regno_nregs (FP_REG_FIRST, mode);
9844
9845 if (reg_class_subset_p (rclass, GR_REGS))
9846 return riscv_hard_regno_nregs (GP_REG_FIRST, mode);
9847
9848 if (reg_class_subset_p (rclass, V_REGS))
9849 return riscv_hard_regno_nregs (V_REG_FIRST, mode);
9850
9851 return 0;
9852 }
9853
9854 /* Implement TARGET_MEMORY_MOVE_COST. */
9855
9856 static int
9857 riscv_memory_move_cost (machine_mode mode, reg_class_t rclass, bool in)
9858 {
9859 return (tune_param->memory_cost
9860 + memory_move_secondary_cost (mode, rclass, in));
9861 }
9862
9863 /* Return the number of instructions that can be issued per cycle. */
9864
9865 static int
9866 riscv_issue_rate (void)
9867 {
9868 return tune_param->issue_rate;
9869 }
9870
9871 /* Implement TARGET_SCHED_VARIABLE_ISSUE. */
9872 static int
9873 riscv_sched_variable_issue (FILE *, int, rtx_insn *insn, int more)
9874 {
9875 if (DEBUG_INSN_P (insn))
9876 return more;
9877
9878 rtx_code code = GET_CODE (PATTERN (insn));
9879 if (code == USE || code == CLOBBER)
9880 return more;
9881
9882 /* GHOST insns are used for blockage and similar cases which
9883 effectively end a cycle. */
9884 if (get_attr_type (insn) == TYPE_GHOST)
9885 return 0;
9886
9887 /* If we ever encounter an insn with an unknown type, trip
9888 an assert so we can find and fix this problem. */
9889 gcc_assert (get_attr_type (insn) != TYPE_UNKNOWN);
9890
9891 /* If we ever encounter an insn without an insn reservation, trip
9892 an assert so we can find and fix this problem. */
9893 gcc_assert (insn_has_dfa_reservation_p (insn));
9894
9895 return more - 1;
9896 }
9897
9898 /* Implement TARGET_SCHED_MACRO_FUSION_P. Return true if target supports
9899 instruction fusion of some sort. */
9900
9901 static bool
9902 riscv_macro_fusion_p (void)
9903 {
9904 return tune_param->fusible_ops != RISCV_FUSE_NOTHING;
9905 }
9906
9907 /* Return true iff the instruction fusion described by OP is enabled. */
9908
9909 static bool
9910 riscv_fusion_enabled_p(enum riscv_fusion_pairs op)
9911 {
9912 return tune_param->fusible_ops & op;
9913 }
9914
9915 /* Implement TARGET_SCHED_MACRO_FUSION_PAIR_P. Return true if PREV and CURR
9916 should be kept together during scheduling. */
9917
9918 static bool
9919 riscv_macro_fusion_pair_p (rtx_insn *prev, rtx_insn *curr)
9920 {
9921 rtx prev_set = single_set (prev);
9922 rtx curr_set = single_set (curr);
9923 /* prev and curr are simple SET insns i.e. no flag setting or branching. */
9924 bool simple_sets_p = prev_set && curr_set && !any_condjump_p (curr);
9925
9926 if (!riscv_macro_fusion_p ())
9927 return false;
9928
9929 if (simple_sets_p
9930 && (riscv_fusion_enabled_p (RISCV_FUSE_ZEXTW)
9931 || riscv_fusion_enabled_p (RISCV_FUSE_ZEXTWS)))
9932 {
9933 /* We are trying to match the following:
9934 prev (slli) == (set (reg:DI rD)
9935 (ashift:DI (reg:DI rS) (const_int 32)))
9936 curr (slri) == (set (reg:DI rD)
9937 (lshiftrt:DI (reg:DI rD) (const_int <shift>)))
9938 with <shift> being either 32 for FUSE_ZEXTW, or
9939 `less than 32 for FUSE_ZEXTWS. */
9940
9941 if (GET_CODE (SET_SRC (prev_set)) == ASHIFT
9942 && GET_CODE (SET_SRC (curr_set)) == LSHIFTRT
9943 && REG_P (SET_DEST (prev_set))
9944 && REG_P (SET_DEST (curr_set))
9945 && REGNO (SET_DEST (prev_set)) == REGNO (SET_DEST (curr_set))
9946 && REGNO (XEXP (SET_SRC (curr_set), 0)) == REGNO(SET_DEST (curr_set))
9947 && CONST_INT_P (XEXP (SET_SRC (prev_set), 1))
9948 && CONST_INT_P (XEXP (SET_SRC (curr_set), 1))
9949 && INTVAL (XEXP (SET_SRC (prev_set), 1)) == 32
9950 && (( INTVAL (XEXP (SET_SRC (curr_set), 1)) == 32
9951 && riscv_fusion_enabled_p(RISCV_FUSE_ZEXTW) )
9952 || ( INTVAL (XEXP (SET_SRC (curr_set), 1)) < 32
9953 && riscv_fusion_enabled_p(RISCV_FUSE_ZEXTWS))))
9954 return true;
9955 }
9956
9957 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_ZEXTH))
9958 {
9959 /* We are trying to match the following:
9960 prev (slli) == (set (reg:DI rD)
9961 (ashift:DI (reg:DI rS) (const_int 48)))
9962 curr (slri) == (set (reg:DI rD)
9963 (lshiftrt:DI (reg:DI rD) (const_int 48))) */
9964
9965 if (GET_CODE (SET_SRC (prev_set)) == ASHIFT
9966 && GET_CODE (SET_SRC (curr_set)) == LSHIFTRT
9967 && REG_P (SET_DEST (prev_set))
9968 && REG_P (SET_DEST (curr_set))
9969 && REGNO (SET_DEST (prev_set)) == REGNO (SET_DEST (curr_set))
9970 && REGNO (XEXP (SET_SRC (curr_set), 0)) == REGNO(SET_DEST (curr_set))
9971 && CONST_INT_P (XEXP (SET_SRC (prev_set), 1))
9972 && CONST_INT_P (XEXP (SET_SRC (curr_set), 1))
9973 && INTVAL (XEXP (SET_SRC (prev_set), 1)) == 48
9974 && INTVAL (XEXP (SET_SRC (curr_set), 1)) == 48)
9975 return true;
9976 }
9977
9978 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_LDINDEXED))
9979 {
9980 /* We are trying to match the following:
9981 prev (add) == (set (reg:DI rD)
9982 (plus:DI (reg:DI rS1) (reg:DI rS2))
9983 curr (ld) == (set (reg:DI rD)
9984 (mem:DI (reg:DI rD))) */
9985
9986 if (MEM_P (SET_SRC (curr_set))
9987 && REG_P (XEXP (SET_SRC (curr_set), 0))
9988 && REGNO (XEXP (SET_SRC (curr_set), 0)) == REGNO (SET_DEST (prev_set))
9989 && GET_CODE (SET_SRC (prev_set)) == PLUS
9990 && REG_P (XEXP (SET_SRC (prev_set), 0))
9991 && REG_P (XEXP (SET_SRC (prev_set), 1)))
9992 return true;
9993
9994 /* We are trying to match the following:
9995 prev (add) == (set (reg:DI rD)
9996 (plus:DI (reg:DI rS1) (reg:DI rS2)))
9997 curr (lw) == (set (any_extend:DI (mem:SUBX (reg:DI rD)))) */
9998
9999 if ((GET_CODE (SET_SRC (curr_set)) == SIGN_EXTEND
10000 || (GET_CODE (SET_SRC (curr_set)) == ZERO_EXTEND))
10001 && MEM_P (XEXP (SET_SRC (curr_set), 0))
10002 && REG_P (XEXP (XEXP (SET_SRC (curr_set), 0), 0))
10003 && REGNO (XEXP (XEXP (SET_SRC (curr_set), 0), 0)) == REGNO (SET_DEST (prev_set))
10004 && GET_CODE (SET_SRC (prev_set)) == PLUS
10005 && REG_P (XEXP (SET_SRC (prev_set), 0))
10006 && REG_P (XEXP (SET_SRC (prev_set), 1)))
10007 return true;
10008 }
10009
10010 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_LDPREINCREMENT))
10011 {
10012 /* We are trying to match the following:
10013 prev (add) == (set (reg:DI rS)
10014 (plus:DI (reg:DI rS) (const_int))
10015 curr (ld) == (set (reg:DI rD)
10016 (mem:DI (reg:DI rS))) */
10017
10018 if (MEM_P (SET_SRC (curr_set))
10019 && REG_P (XEXP (SET_SRC (curr_set), 0))
10020 && REGNO (XEXP (SET_SRC (curr_set), 0)) == REGNO (SET_DEST (prev_set))
10021 && GET_CODE (SET_SRC (prev_set)) == PLUS
10022 && REG_P (XEXP (SET_SRC (prev_set), 0))
10023 && CONST_INT_P (XEXP (SET_SRC (prev_set), 1)))
10024 return true;
10025 }
10026
10027 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_LUI_ADDI))
10028 {
10029 /* We are trying to match the following:
10030 prev (lui) == (set (reg:DI rD) (const_int UPPER_IMM_20))
10031 curr (addi) == (set (reg:DI rD)
10032 (plus:DI (reg:DI rD) (const_int IMM12))) */
10033
10034 if ((GET_CODE (SET_SRC (curr_set)) == LO_SUM
10035 || (GET_CODE (SET_SRC (curr_set)) == PLUS
10036 && CONST_INT_P (XEXP (SET_SRC (curr_set), 1))
10037 && SMALL_OPERAND (INTVAL (XEXP (SET_SRC (curr_set), 1)))))
10038 && (GET_CODE (SET_SRC (prev_set)) == HIGH
10039 || (CONST_INT_P (SET_SRC (prev_set))
10040 && LUI_OPERAND (INTVAL (SET_SRC (prev_set))))))
10041 return true;
10042 }
10043
10044 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_AUIPC_ADDI))
10045 {
10046 /* We are trying to match the following:
10047 prev (auipc) == (set (reg:DI rD) (unspec:DI [...] UNSPEC_AUIPC))
10048 curr (addi) == (set (reg:DI rD)
10049 (plus:DI (reg:DI rD) (const_int IMM12)))
10050 and
10051 prev (auipc) == (set (reg:DI rD) (unspec:DI [...] UNSPEC_AUIPC))
10052 curr (addi) == (set (reg:DI rD)
10053 (lo_sum:DI (reg:DI rD) (const_int IMM12))) */
10054
10055 if (GET_CODE (SET_SRC (prev_set)) == UNSPEC
10056 && XINT (SET_SRC (prev_set), 1) == UNSPEC_AUIPC
10057 && (GET_CODE (SET_SRC (curr_set)) == LO_SUM
10058 || (GET_CODE (SET_SRC (curr_set)) == PLUS
10059 && CONST_INT_P (XEXP (SET_SRC (curr_set), 1))
10060 && SMALL_OPERAND (INTVAL (XEXP (SET_SRC (curr_set), 1))))))
10061
10062 return true;
10063 }
10064
10065 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_LUI_LD))
10066 {
10067 /* We are trying to match the following:
10068 prev (lui) == (set (reg:DI rD) (const_int UPPER_IMM_20))
10069 curr (ld) == (set (reg:DI rD)
10070 (mem:DI (plus:DI (reg:DI rD) (const_int IMM12)))) */
10071
10072 if (CONST_INT_P (SET_SRC (prev_set))
10073 && LUI_OPERAND (INTVAL (SET_SRC (prev_set)))
10074 && MEM_P (SET_SRC (curr_set))
10075 && GET_CODE (XEXP (SET_SRC (curr_set), 0)) == PLUS)
10076 return true;
10077
10078 if (GET_CODE (SET_SRC (prev_set)) == HIGH
10079 && MEM_P (SET_SRC (curr_set))
10080 && GET_CODE (XEXP (SET_SRC (curr_set), 0)) == LO_SUM
10081 && REGNO (SET_DEST (prev_set)) == REGNO (XEXP (XEXP (SET_SRC (curr_set), 0), 0)))
10082 return true;
10083
10084 if (GET_CODE (SET_SRC (prev_set)) == HIGH
10085 && (GET_CODE (SET_SRC (curr_set)) == SIGN_EXTEND
10086 || GET_CODE (SET_SRC (curr_set)) == ZERO_EXTEND)
10087 && MEM_P (XEXP (SET_SRC (curr_set), 0))
10088 && (GET_CODE (XEXP (XEXP (SET_SRC (curr_set), 0), 0)) == LO_SUM
10089 && REGNO (SET_DEST (prev_set)) == REGNO (XEXP (XEXP (XEXP (SET_SRC (curr_set), 0), 0), 0))))
10090 return true;
10091 }
10092
10093 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_AUIPC_LD))
10094 {
10095 /* We are trying to match the following:
10096 prev (auipc) == (set (reg:DI rD) (unspec:DI [...] UNSPEC_AUIPC))
10097 curr (ld) == (set (reg:DI rD)
10098 (mem:DI (plus:DI (reg:DI rD) (const_int IMM12)))) */
10099
10100 if (GET_CODE (SET_SRC (prev_set)) == UNSPEC
10101 && XINT (prev_set, 1) == UNSPEC_AUIPC
10102 && MEM_P (SET_SRC (curr_set))
10103 && GET_CODE (XEXP (SET_SRC (curr_set), 0)) == PLUS)
10104 return true;
10105 }
10106
10107 if (simple_sets_p && riscv_fusion_enabled_p (RISCV_FUSE_ALIGNED_STD))
10108 {
10109 /* We are trying to match the following:
10110 prev (sd) == (set (mem (plus (reg sp|fp) (const_int)))
10111 (reg rS1))
10112 curr (sd) == (set (mem (plus (reg sp|fp) (const_int)))
10113 (reg rS2)) */
10114
10115 if (MEM_P (SET_DEST (prev_set))
10116 && MEM_P (SET_DEST (curr_set))
10117 /* We can probably relax this condition. The documentation is a bit
10118 unclear about sub-word cases. So we just model DImode for now. */
10119 && GET_MODE (SET_DEST (curr_set)) == DImode
10120 && GET_MODE (SET_DEST (prev_set)) == DImode)
10121 {
10122 rtx base_prev, base_curr, offset_prev, offset_curr;
10123
10124 extract_base_offset_in_addr (SET_DEST (prev_set), &base_prev, &offset_prev);
10125 extract_base_offset_in_addr (SET_DEST (curr_set), &base_curr, &offset_curr);
10126
10127 /* Fail if we did not find both bases. */
10128 if (base_prev == NULL_RTX || base_curr == NULL_RTX)
10129 return false;
10130
10131 /* Fail if either base is not a register. */
10132 if (!REG_P (base_prev) || !REG_P (base_curr))
10133 return false;
10134
10135 /* Fail if the bases are not the same register. */
10136 if (REGNO (base_prev) != REGNO (base_curr))
10137 return false;
10138
10139 /* Originally the thought was to check MEM_ALIGN, but that was
10140 reporting incorrect alignments, even for SP/FP accesses, so we
10141 gave up on that approach. Instead just check for stack/hfp
10142 which we know are aligned. */
10143 if (REGNO (base_prev) != STACK_POINTER_REGNUM
10144 && REGNO (base_prev) != HARD_FRAME_POINTER_REGNUM)
10145 return false;
10146
10147 /* The two stores must be contained within opposite halves of the
10148 same 16 byte aligned block of memory. We know that the stack
10149 pointer and the frame pointer have suitable alignment. So we
10150 just need to check the offsets of the two stores for suitable
10151 alignment. */
10152 /* Get the smaller offset into OFFSET_PREV. */
10153 if (INTVAL (offset_prev) > INTVAL (offset_curr))
10154 std::swap (offset_prev, offset_curr);
10155
10156 /* If the smaller offset (OFFSET_PREV) is not 16 byte aligned,
10157 then fail. */
10158 if ((INTVAL (offset_prev) % 16) != 0)
10159 return false;
10160
10161 /* The higher offset must be 8 bytes more than the lower
10162 offset. */
10163 return (INTVAL (offset_prev) + 8 == INTVAL (offset_curr));
10164 }
10165 }
10166
10167 return false;
10168 }
10169
10170 /* Adjust the cost/latency of instructions for scheduling.
10171 For now this is just used to change the latency of vector instructions
10172 according to their LMUL. We assume that an insn with LMUL == 8 requires
10173 eight times more execution cycles than the same insn with LMUL == 1.
10174 As this may cause very high latencies which lead to scheduling artifacts
10175 we currently only perform the adjustment when -madjust-lmul-cost is given.
10176 */
10177 static int
10178 riscv_sched_adjust_cost (rtx_insn *, int, rtx_insn *insn, int cost,
10179 unsigned int)
10180 {
10181 /* Only do adjustments for the generic out-of-order scheduling model. */
10182 if (!TARGET_VECTOR || riscv_microarchitecture != generic_ooo)
10183 return cost;
10184
10185 if (recog_memoized (insn) < 0)
10186 return cost;
10187
10188 enum attr_type type = get_attr_type (insn);
10189
10190 if (type == TYPE_VFREDO || type == TYPE_VFWREDO)
10191 {
10192 /* TODO: For ordered reductions scale the base cost relative to the
10193 number of units. */
10194 ;
10195 }
10196
10197 /* Don't do any LMUL-based latency adjustment unless explicitly asked to. */
10198 if (!TARGET_ADJUST_LMUL_COST)
10199 return cost;
10200
10201 /* vsetvl has a vlmul attribute but its latency does not depend on it. */
10202 if (type == TYPE_VSETVL || type == TYPE_VSETVL_PRE)
10203 return cost;
10204
10205 enum riscv_vector::vlmul_type lmul =
10206 (riscv_vector::vlmul_type)get_attr_vlmul (insn);
10207
10208 double factor = 1;
10209 switch (lmul)
10210 {
10211 case riscv_vector::LMUL_2:
10212 factor = 2;
10213 break;
10214 case riscv_vector::LMUL_4:
10215 factor = 4;
10216 break;
10217 case riscv_vector::LMUL_8:
10218 factor = 8;
10219 break;
10220 case riscv_vector::LMUL_F2:
10221 factor = 0.5;
10222 break;
10223 case riscv_vector::LMUL_F4:
10224 factor = 0.25;
10225 break;
10226 case riscv_vector::LMUL_F8:
10227 factor = 0.125;
10228 break;
10229 default:
10230 factor = 1;
10231 }
10232
10233 /* If the latency was nonzero, keep it that way. */
10234 int new_cost = MAX (cost > 0 ? 1 : 0, cost * factor);
10235
10236 return new_cost;
10237 }
10238
10239 /* Auxiliary function to emit RISC-V ELF attribute. */
10240 static void
10241 riscv_emit_attribute ()
10242 {
10243 fprintf (asm_out_file, "\t.attribute arch, \"%s\"\n",
10244 riscv_arch_str ().c_str ());
10245
10246 fprintf (asm_out_file, "\t.attribute unaligned_access, %d\n",
10247 TARGET_STRICT_ALIGN ? 0 : 1);
10248
10249 fprintf (asm_out_file, "\t.attribute stack_align, %d\n",
10250 riscv_stack_boundary / 8);
10251 }
10252
10253 /* Output .variant_cc for function symbol which follows vector calling
10254 convention. */
10255
10256 static void
10257 riscv_asm_output_variant_cc (FILE *stream, const tree decl, const char *name)
10258 {
10259 if (TREE_CODE (decl) == FUNCTION_DECL)
10260 {
10261 riscv_cc cc = (riscv_cc) fndecl_abi (decl).id ();
10262 if (cc == RISCV_CC_V)
10263 {
10264 fprintf (stream, "\t.variant_cc\t");
10265 assemble_name (stream, name);
10266 fprintf (stream, "\n");
10267 }
10268 }
10269 }
10270
10271 /* Implement ASM_DECLARE_FUNCTION_NAME. */
10272
10273 void
10274 riscv_declare_function_name (FILE *stream, const char *name, tree fndecl)
10275 {
10276 riscv_asm_output_variant_cc (stream, fndecl, name);
10277 ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "function");
10278 ASM_OUTPUT_FUNCTION_LABEL (stream, name, fndecl);
10279 if (DECL_FUNCTION_SPECIFIC_TARGET (fndecl)
10280 || lookup_attribute ("norelax", DECL_ATTRIBUTES (fndecl)))
10281 {
10282 fprintf (stream, "\t.option push\n");
10283 if (lookup_attribute ("norelax", DECL_ATTRIBUTES (fndecl)))
10284 {
10285 fprintf (stream, "\t.option norelax\n");
10286 }
10287 if (DECL_FUNCTION_SPECIFIC_TARGET (fndecl))
10288 {
10289 struct cl_target_option *local_cl_target
10290 = TREE_TARGET_OPTION (DECL_FUNCTION_SPECIFIC_TARGET (fndecl));
10291 struct cl_target_option *global_cl_target
10292 = TREE_TARGET_OPTION (target_option_default_node);
10293
10294 const char *local_arch_str = get_arch_str (local_cl_target);
10295 const char *arch_str = local_arch_str != NULL
10296 ? local_arch_str
10297 : riscv_arch_str (true).c_str ();
10298 fprintf (stream, "\t.option arch, %s\n", arch_str);
10299 const char *local_tune_str = get_tune_str (local_cl_target);
10300 const char *global_tune_str = get_tune_str (global_cl_target);
10301 if (strcmp (local_tune_str, global_tune_str) != 0)
10302 fprintf (stream, "\t# tune = %s\n", local_tune_str);
10303 }
10304 }
10305 }
10306
10307 void
10308 riscv_declare_function_size (FILE *stream, const char *name, tree fndecl)
10309 {
10310 if (!flag_inhibit_size_directive)
10311 ASM_OUTPUT_MEASURED_SIZE (stream, name);
10312
10313 if (DECL_FUNCTION_SPECIFIC_TARGET (fndecl)
10314 || lookup_attribute ("norelax", DECL_ATTRIBUTES (fndecl)))
10315 {
10316 fprintf (stream, "\t.option pop\n");
10317 }
10318 }
10319
10320 /* Implement ASM_OUTPUT_DEF_FROM_DECLS. */
10321
10322 void
10323 riscv_asm_output_alias (FILE *stream, const tree decl, const tree target)
10324 {
10325 const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
10326 const char *value = IDENTIFIER_POINTER (target);
10327 riscv_asm_output_variant_cc (stream, decl, name);
10328 ASM_OUTPUT_DEF (stream, name, value);
10329 }
10330
10331 /* Implement ASM_OUTPUT_EXTERNAL. */
10332
10333 void
10334 riscv_asm_output_external (FILE *stream, tree decl, const char *name)
10335 {
10336 default_elf_asm_output_external (stream, decl, name);
10337 riscv_asm_output_variant_cc (stream, decl, name);
10338 }
10339
10340 /* Implement TARGET_ASM_FILE_START. */
10341
10342 static void
10343 riscv_file_start (void)
10344 {
10345 default_file_start ();
10346
10347 /* Instruct GAS to generate position-[in]dependent code. */
10348 fprintf (asm_out_file, "\t.option %spic\n", (flag_pic ? "" : "no"));
10349
10350 /* If the user specifies "-mno-relax" on the command line then disable linker
10351 relaxation in the assembler. */
10352 if (! riscv_mrelax)
10353 fprintf (asm_out_file, "\t.option norelax\n");
10354
10355 /* If the user specifies "-mcsr-check" on the command line then enable csr
10356 check in the assembler. */
10357 if (riscv_mcsr_check)
10358 fprintf (asm_out_file, "\t.option csr-check\n");
10359
10360 if (riscv_emit_attribute_p)
10361 riscv_emit_attribute ();
10362 }
10363
10364 void
10365 riscv_file_end ()
10366 {
10367 file_end_indicate_exec_stack ();
10368 unsigned long feature_1_and = 0;
10369
10370 if (is_zicfilp_p ())
10371 feature_1_and |= 0x1 << 0;
10372
10373 if (is_zicfiss_p ())
10374 feature_1_and |= 0x1 << 1;
10375
10376 if (feature_1_and)
10377 {
10378 /* Generate .note.gnu.property section. */
10379 switch_to_section (get_section (".note.gnu.property",
10380 SECTION_NOTYPE, NULL));
10381
10382 /* The program property descriptor is aligned to 4 bytes in 32-bit
10383 objects and 8 bytes in 64-bit objects. */
10384 unsigned p2align = TARGET_64BIT ? 3 : 2;
10385
10386 fprintf (asm_out_file, "\t.p2align\t%u\n", p2align);
10387 /* name length. */
10388 fprintf (asm_out_file, "\t.long\t1f - 0f\n");
10389 /* data length. */
10390 fprintf (asm_out_file, "\t.long\t5f - 2f\n");
10391 /* note type. */
10392 fprintf (asm_out_file, "\t.long\t5\n");
10393 fprintf (asm_out_file, "0:\n");
10394 /* vendor name: "GNU". */
10395 fprintf (asm_out_file, "\t.asciz\t\"GNU\"\n");
10396 fprintf (asm_out_file, "1:\n");
10397
10398 /* pr_type. */
10399 fprintf (asm_out_file, "\t.p2align\t%u\n", p2align);
10400 fprintf (asm_out_file, "2:\n");
10401 fprintf (asm_out_file, "\t.long\t0xc0000000\n");
10402 /* pr_datasz. */
10403 fprintf (asm_out_file, "\t.long\t4f - 3f\n");
10404 fprintf (asm_out_file, "3:\n");
10405 /* zicfiss, zicfilp. */
10406 fprintf (asm_out_file, "\t.long\t%lx\n", feature_1_and);
10407 fprintf (asm_out_file, "4:\n");
10408 fprintf (asm_out_file, "\t.p2align\t%u\n", p2align);
10409 fprintf (asm_out_file, "5:\n");
10410 }
10411 }
10412
10413 /* Implement TARGET_ASM_OUTPUT_MI_THUNK. Generate rtl rather than asm text
10414 in order to avoid duplicating too much logic from elsewhere. */
10415
10416 static void
10417 riscv_output_mi_thunk (FILE *file, tree thunk_fndecl ATTRIBUTE_UNUSED,
10418 HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
10419 tree function)
10420 {
10421 const char *fnname = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk_fndecl));
10422 rtx this_rtx, temp1, temp2, fnaddr;
10423 rtx_insn *insn;
10424
10425 riscv_in_thunk_func = true;
10426
10427 /* Pretend to be a post-reload pass while generating rtl. */
10428 reload_completed = 1;
10429
10430 /* Mark the end of the (empty) prologue. */
10431 emit_note (NOTE_INSN_PROLOGUE_END);
10432
10433 if (is_zicfilp_p ())
10434 emit_insn(gen_lpad (const0_rtx));
10435
10436 /* Determine if we can use a sibcall to call FUNCTION directly. */
10437 fnaddr = gen_rtx_MEM (FUNCTION_MODE, XEXP (DECL_RTL (function), 0));
10438
10439 /* We need two temporary registers in some cases. */
10440 temp1 = gen_rtx_REG (Pmode, RISCV_PROLOGUE_TEMP_REGNUM);
10441 temp2 = gen_rtx_REG (Pmode, STATIC_CHAIN_REGNUM);
10442
10443 /* Find out which register contains the "this" pointer. */
10444 if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
10445 this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST + 1);
10446 else
10447 this_rtx = gen_rtx_REG (Pmode, GP_ARG_FIRST);
10448
10449 /* Add DELTA to THIS_RTX. */
10450 if (delta != 0)
10451 {
10452 rtx offset = GEN_INT (delta);
10453 if (!SMALL_OPERAND (delta))
10454 {
10455 riscv_emit_move (temp1, offset);
10456 offset = temp1;
10457 }
10458 emit_insn (gen_add3_insn (this_rtx, this_rtx, offset));
10459 }
10460
10461 /* If needed, add *(*THIS_RTX + VCALL_OFFSET) to THIS_RTX. */
10462 if (vcall_offset != 0)
10463 {
10464 rtx addr;
10465
10466 /* Set TEMP1 to *THIS_RTX. */
10467 riscv_emit_move (temp1, gen_rtx_MEM (Pmode, this_rtx));
10468
10469 /* Set ADDR to a legitimate address for *THIS_RTX + VCALL_OFFSET. */
10470 addr = riscv_add_offset (temp2, temp1, vcall_offset);
10471
10472 /* Load the offset and add it to THIS_RTX. */
10473 riscv_emit_move (temp1, gen_rtx_MEM (Pmode, addr));
10474 emit_insn (gen_add3_insn (this_rtx, this_rtx, temp1));
10475 }
10476
10477 /* Jump to the target function. */
10478 rtx callee_cc = gen_int_mode (fndecl_abi (function).id (), SImode);
10479 insn = emit_call_insn (gen_sibcall (fnaddr, const0_rtx, callee_cc));
10480 SIBLING_CALL_P (insn) = 1;
10481
10482 /* Run just enough of rest_of_compilation. This sequence was
10483 "borrowed" from alpha.cc. */
10484 insn = get_insns ();
10485 split_all_insns_noflow ();
10486 shorten_branches (insn);
10487 assemble_start_function (thunk_fndecl, fnname);
10488 final_start_function (insn, file, 1);
10489 final (insn, file, 1);
10490 final_end_function ();
10491 assemble_end_function (thunk_fndecl, fnname);
10492
10493 /* Clean up the vars set above. Note that final_end_function resets
10494 the global pointer for us. */
10495 reload_completed = 0;
10496 riscv_in_thunk_func = false;
10497 }
10498
10499 /* Allocate a chunk of memory for per-function machine-dependent data. */
10500
10501 static struct machine_function *
10502 riscv_init_machine_status (void)
10503 {
10504 return ggc_cleared_alloc<machine_function> ();
10505 }
10506
10507 /* Return the VLEN value associated with -march and -mrvv-vector-bits.
10508 TODO: So far we only support length-agnostic value. */
10509 static poly_uint16
10510 riscv_convert_vector_chunks (struct gcc_options *opts)
10511 {
10512 int chunk_num;
10513 int min_vlen = TARGET_MIN_VLEN_OPTS (opts);
10514 if (min_vlen > 32)
10515 {
10516 /* When targeting minimum VLEN > 32, we should use 64-bit chunk size.
10517 Otherwise we can not include SEW = 64bits.
10518 Runtime invariant: The single indeterminate represent the
10519 number of 64-bit chunks in a vector beyond minimum length of 64 bits.
10520 Thus the number of bytes in a vector is 8 + 8 * x1 which is
10521 riscv_vector_chunks * 8 = poly_int (8, 8). */
10522 riscv_bytes_per_vector_chunk = 8;
10523 /* Adjust BYTES_PER_RISCV_VECTOR according to TARGET_MIN_VLEN:
10524 - TARGET_MIN_VLEN = 64bit: [8,8]
10525 - TARGET_MIN_VLEN = 128bit: [16,16]
10526 - TARGET_MIN_VLEN = 256bit: [32,32]
10527 - TARGET_MIN_VLEN = 512bit: [64,64]
10528 - TARGET_MIN_VLEN = 1024bit: [128,128]
10529 - TARGET_MIN_VLEN = 2048bit: [256,256]
10530 - TARGET_MIN_VLEN = 4096bit: [512,512]
10531 FIXME: We currently DON'T support TARGET_MIN_VLEN > 4096bit. */
10532 chunk_num = min_vlen / 64;
10533 }
10534 else
10535 {
10536 /* When targeting minimum VLEN = 32, we should use 32-bit
10537 chunk size. Runtime invariant: The single indeterminate represent the
10538 number of 32-bit chunks in a vector beyond minimum length of 32 bits.
10539 Thus the number of bytes in a vector is 4 + 4 * x1 which is
10540 riscv_vector_chunks * 4 = poly_int (4, 4). */
10541 riscv_bytes_per_vector_chunk = 4;
10542 chunk_num = 1;
10543 }
10544
10545 /* Set riscv_vector_chunks as poly (1, 1) run-time constant if TARGET_VECTOR
10546 is enabled. Set riscv_vector_chunks as 1 compile-time constant if
10547 TARGET_VECTOR is disabled. riscv_vector_chunks is used in "riscv-modes.def"
10548 to set RVV mode size. The RVV machine modes size are run-time constant if
10549 TARGET_VECTOR is enabled. The RVV machine modes size remains default
10550 compile-time constant if TARGET_VECTOR is disabled. */
10551 if (TARGET_VECTOR_OPTS_P (opts))
10552 {
10553 switch (opts->x_rvv_vector_bits)
10554 {
10555 case RVV_VECTOR_BITS_SCALABLE:
10556 return poly_uint16 (chunk_num, chunk_num);
10557 case RVV_VECTOR_BITS_ZVL:
10558 return (int) min_vlen / (riscv_bytes_per_vector_chunk * 8);
10559 default:
10560 gcc_unreachable ();
10561 }
10562 }
10563 else
10564 return 1;
10565 }
10566
10567 /* 'Unpack' up the internal tuning structs and update the options
10568 in OPTS. The caller must have set up selected_tune and selected_arch
10569 as all the other target-specific codegen decisions are
10570 derived from them. */
10571 void
10572 riscv_override_options_internal (struct gcc_options *opts)
10573 {
10574 const struct riscv_tune_info *cpu;
10575
10576 /* The presence of the M extension implies that division instructions
10577 are present, so include them unless explicitly disabled.
10578 Similarly, if the M extension is not available, then disable
10579 division instructions, unless they are explicitly enabled. */
10580 if (TARGET_MUL_OPTS_P (opts) && (target_flags_explicit & MASK_DIV) == 0)
10581 opts->x_target_flags |= MASK_DIV;
10582 else if (!TARGET_MUL_OPTS_P (opts) && (target_flags_explicit & MASK_DIV) == 0)
10583 opts->x_target_flags &= ~MASK_DIV;
10584 else if (!TARGET_MUL_OPTS_P (opts) && TARGET_DIV_OPTS_P (opts))
10585 error ("%<-mdiv%> requires %<-march%> to subsume the %<M%> extension");
10586
10587 /* We might use a multiplication to calculate the scalable vector length at
10588 runtime. Therefore, require the M extension. */
10589 if (TARGET_VECTOR && !TARGET_MUL)
10590 sorry ("Currently the %<V%> implementation requires the %<M%> extension");
10591
10592 /* Likewise floating-point division and square root. */
10593 if ((TARGET_HARD_FLOAT_OPTS_P (opts) || TARGET_ZFINX_OPTS_P (opts))
10594 && ((target_flags_explicit & MASK_FDIV) == 0))
10595 opts->x_target_flags |= MASK_FDIV;
10596
10597 /* Handle -mtune, use -mcpu if -mtune is not given, and use default -mtune
10598 if both -mtune and -mcpu are not given. */
10599 const char *tune_string = get_tune_str (opts);
10600 cpu = riscv_parse_tune (tune_string, false);
10601 riscv_microarchitecture = cpu->microarchitecture;
10602 tune_param = opts->x_optimize_size
10603 ? &optimize_size_tune_info
10604 : cpu->tune_param;
10605
10606 /* If not optimizing for size, set the default
10607 alignment to what the target wants. */
10608 if (!opts->x_optimize_size)
10609 {
10610 if (opts->x_flag_align_loops && !opts->x_str_align_loops)
10611 opts->x_str_align_loops = tune_param->loop_align;
10612 if (opts->x_flag_align_jumps && !opts->x_str_align_jumps)
10613 opts->x_str_align_jumps = tune_param->jump_align;
10614 if (opts->x_flag_align_functions && !opts->x_str_align_functions)
10615 opts->x_str_align_functions = tune_param->function_align;
10616 }
10617
10618 /* Use -mtune's setting for slow_unaligned_access, even when optimizing
10619 for size. For architectures that trap and emulate unaligned accesses,
10620 the performance cost is too great, even for -Os. Similarly, if
10621 -m[no-]strict-align is left unspecified, heed -mtune's advice. */
10622 riscv_slow_unaligned_access_p = (cpu->tune_param->slow_unaligned_access
10623 || TARGET_STRICT_ALIGN);
10624
10625 /* By default, when -mno-vector-strict-align is not specified, do not allow
10626 unaligned vector memory accesses except if -mtune's setting explicitly
10627 allows it. */
10628 riscv_vector_unaligned_access_p = opts->x_rvv_vector_strict_align == 0
10629 || cpu->tune_param->vector_unaligned_access;
10630
10631 /* Make a note if user explicitly passed -mstrict-align for later
10632 builtin macro generation. Can't use target_flags_explicitly since
10633 it is set even for -mno-strict-align. */
10634 riscv_user_wants_strict_align = TARGET_STRICT_ALIGN_OPTS_P (opts);
10635
10636 if ((target_flags_explicit & MASK_STRICT_ALIGN) == 0
10637 && cpu->tune_param->slow_unaligned_access)
10638 opts->x_target_flags |= MASK_STRICT_ALIGN;
10639
10640 /* If the user hasn't specified a branch cost, use the processor's
10641 default. */
10642 if (opts->x_riscv_branch_cost == 0)
10643 opts->x_riscv_branch_cost = tune_param->branch_cost;
10644
10645 /* FIXME: We don't allow TARGET_MIN_VLEN > 4096 since the datatypes of
10646 both GET_MODE_SIZE and GET_MODE_BITSIZE are poly_uint16.
10647
10648 We can only allow TARGET_MIN_VLEN * 8 (LMUL) < 65535. */
10649 if (TARGET_MIN_VLEN_OPTS (opts) > 4096)
10650 sorry ("Current RISC-V GCC does not support VLEN greater than 4096bit for "
10651 "'V' Extension");
10652
10653 /* FIXME: We don't support RVV in big-endian for now, we may enable RVV with
10654 big-endian after finishing full coverage testing. */
10655 if (TARGET_VECTOR && TARGET_BIG_ENDIAN)
10656 sorry ("Current RISC-V GCC does not support RVV in big-endian mode");
10657
10658 /* Convert -march and -mrvv-vector-bits to a chunks count. */
10659 riscv_vector_chunks = riscv_convert_vector_chunks (opts);
10660
10661 if (opts->x_flag_cf_protection != CF_NONE)
10662 {
10663 if ((opts->x_flag_cf_protection & CF_RETURN) == CF_RETURN
10664 && !TARGET_ZICFISS)
10665 error ("%<-fcf-protection%> is not compatible with this target");
10666
10667 if ((opts->x_flag_cf_protection & CF_BRANCH) == CF_BRANCH
10668 && !TARGET_ZICFILP)
10669 error ("%<-fcf-protection%> is not compatible with this target");
10670
10671 opts->x_flag_cf_protection
10672 = (cf_protection_level) (opts->x_flag_cf_protection | CF_SET);
10673 }
10674 }
10675
10676 /* Implement TARGET_OPTION_OVERRIDE. */
10677
10678 void
10679 riscv_option_override (void)
10680 {
10681 #ifdef SUBTARGET_OVERRIDE_OPTIONS
10682 SUBTARGET_OVERRIDE_OPTIONS;
10683 #endif
10684
10685 flag_pcc_struct_return = 0;
10686
10687 if (flag_pic)
10688 g_switch_value = 0;
10689
10690 /* Always prefer medlow than medany for RV32 since medlow can access
10691 full address space. */
10692 if (riscv_cmodel == CM_LARGE && !TARGET_64BIT)
10693 riscv_cmodel = CM_MEDLOW;
10694
10695 if (riscv_cmodel == CM_LARGE && TARGET_EXPLICIT_RELOCS)
10696 sorry ("code model %qs with %qs", "large", "-mexplicit-relocs");
10697
10698 if (riscv_cmodel == CM_LARGE && flag_pic)
10699 sorry ("code model %qs with %qs", "large",
10700 global_options.x_flag_pic > 1 ? "-fPIC" : "-fpic");
10701
10702 if (flag_pic)
10703 riscv_cmodel = CM_PIC;
10704
10705 /* We need to save the fp with ra for non-leaf functions with no fp and ra
10706 for leaf functions while no-omit-frame-pointer with
10707 omit-leaf-frame-pointer. The x_flag_omit_frame_pointer has the first
10708 priority to determine whether the frame pointer is needed. If we do not
10709 override it, the fp and ra will be stored for leaf functions, which is not
10710 our wanted. */
10711 riscv_save_frame_pointer = false;
10712 if (TARGET_OMIT_LEAF_FRAME_POINTER_P (global_options.x_target_flags))
10713 {
10714 if (!global_options.x_flag_omit_frame_pointer)
10715 riscv_save_frame_pointer = true;
10716
10717 global_options.x_flag_omit_frame_pointer = 1;
10718 }
10719
10720 /* We get better code with explicit relocs for CM_MEDLOW, but
10721 worse code for the others (for now). Pick the best default. */
10722 if ((target_flags_explicit & MASK_EXPLICIT_RELOCS) == 0)
10723 if (riscv_cmodel == CM_MEDLOW)
10724 target_flags |= MASK_EXPLICIT_RELOCS;
10725
10726 /* Require that the ISA supports the requested floating-point ABI. */
10727 if (UNITS_PER_FP_ARG > (TARGET_HARD_FLOAT ? UNITS_PER_FP_REG : 0))
10728 error ("requested ABI requires %<-march%> to subsume the %qc extension",
10729 UNITS_PER_FP_ARG > 8 ? 'Q' : (UNITS_PER_FP_ARG > 4 ? 'D' : 'F'));
10730
10731 /* RVE requires specific ABI. */
10732 if (TARGET_RVE)
10733 {
10734 if (!TARGET_64BIT && riscv_abi != ABI_ILP32E)
10735 error ("rv32e requires ilp32e ABI");
10736 else if (TARGET_64BIT && riscv_abi != ABI_LP64E)
10737 error ("rv64e requires lp64e ABI");
10738 }
10739
10740 /* ILP32E does not support the 'd' extension. */
10741 if (riscv_abi == ABI_ILP32E && UNITS_PER_FP_REG > 4)
10742 error ("ILP32E ABI does not support the %qc extension",
10743 UNITS_PER_FP_REG > 8 ? 'Q' : 'D');
10744
10745 if (riscv_abi == ABI_LP64E)
10746 {
10747 if (warning (OPT_Wdeprecated, "LP64E ABI is marked for deprecation in GCC"))
10748 inform (UNKNOWN_LOCATION, "if you need LP64E please notify the GCC "
10749 "project via %{PR116152%}", "https://gcc.gnu.org/PR116152");
10750 }
10751
10752 /* Zfinx require abi ilp32, ilp32e, lp64 or lp64e. */
10753 if (TARGET_ZFINX
10754 && riscv_abi != ABI_ILP32 && riscv_abi != ABI_LP64
10755 && riscv_abi != ABI_ILP32E && riscv_abi != ABI_LP64E)
10756 error ("z*inx requires ABI ilp32, ilp32e, lp64 or lp64e");
10757
10758 /* We do not yet support ILP32 on RV64. */
10759 if (BITS_PER_WORD != POINTER_SIZE)
10760 error ("ABI requires %<-march=rv%d%>", POINTER_SIZE);
10761
10762 /* Validate -mpreferred-stack-boundary= value. */
10763 riscv_stack_boundary = ABI_STACK_BOUNDARY;
10764 if (riscv_preferred_stack_boundary_arg)
10765 {
10766 int min = ctz_hwi (STACK_BOUNDARY / 8);
10767 int max = 8;
10768
10769 if (!IN_RANGE (riscv_preferred_stack_boundary_arg, min, max))
10770 error ("%<-mpreferred-stack-boundary=%d%> must be between %d and %d",
10771 riscv_preferred_stack_boundary_arg, min, max);
10772
10773 riscv_stack_boundary = 8 << riscv_preferred_stack_boundary_arg;
10774 }
10775
10776 if (riscv_emit_attribute_p < 0)
10777 #ifdef HAVE_AS_RISCV_ATTRIBUTE
10778 riscv_emit_attribute_p = TARGET_RISCV_ATTRIBUTE;
10779 #else
10780 riscv_emit_attribute_p = 0;
10781
10782 if (riscv_emit_attribute_p)
10783 error ("%<-mriscv-attribute%> RISC-V ELF attribute requires GNU as 2.32"
10784 " [%<-mriscv-attribute%>]");
10785 #endif
10786
10787 if (riscv_stack_protector_guard == SSP_GLOBAL
10788 && OPTION_SET_P (riscv_stack_protector_guard_offset_str))
10789 {
10790 error ("incompatible options %<-mstack-protector-guard=global%> and "
10791 "%<-mstack-protector-guard-offset=%s%>",
10792 riscv_stack_protector_guard_offset_str);
10793 }
10794
10795 if (riscv_stack_protector_guard == SSP_TLS
10796 && !(OPTION_SET_P (riscv_stack_protector_guard_offset_str)
10797 && OPTION_SET_P (riscv_stack_protector_guard_reg_str)))
10798 {
10799 error ("both %<-mstack-protector-guard-offset%> and "
10800 "%<-mstack-protector-guard-reg%> must be used "
10801 "with %<-mstack-protector-guard=sysreg%>");
10802 }
10803
10804 if (OPTION_SET_P (riscv_stack_protector_guard_reg_str))
10805 {
10806 const char *str = riscv_stack_protector_guard_reg_str;
10807 int reg = decode_reg_name (str);
10808
10809 if (!IN_RANGE (reg, GP_REG_FIRST + 1, GP_REG_LAST))
10810 error ("%qs is not a valid base register in %qs", str,
10811 "-mstack-protector-guard-reg=");
10812
10813 riscv_stack_protector_guard_reg = reg;
10814 }
10815
10816 if (OPTION_SET_P (riscv_stack_protector_guard_offset_str))
10817 {
10818 char *end;
10819 const char *str = riscv_stack_protector_guard_offset_str;
10820 errno = 0;
10821 long offs = strtol (riscv_stack_protector_guard_offset_str, &end, 0);
10822
10823 if (!*str || *end || errno)
10824 error ("%qs is not a valid number in %qs", str,
10825 "-mstack-protector-guard-offset=");
10826
10827 if (!SMALL_OPERAND (offs))
10828 error ("%qs is not a valid offset in %qs", str,
10829 "-mstack-protector-guard-offset=");
10830
10831 riscv_stack_protector_guard_offset = offs;
10832 }
10833
10834 int guard_size = param_stack_clash_protection_guard_size;
10835
10836 /* Enforce that interval is the same size as guard size so the mid-end does
10837 the right thing. */
10838 SET_OPTION_IF_UNSET (&global_options, &global_options_set,
10839 param_stack_clash_protection_probe_interval,
10840 guard_size);
10841
10842 /* The maybe_set calls won't update the value if the user has explicitly set
10843 one. Which means we need to validate that probing interval and guard size
10844 are equal. */
10845 int probe_interval
10846 = param_stack_clash_protection_probe_interval;
10847 if (guard_size != probe_interval)
10848 error ("stack clash guard size %<%d%> must be equal to probing interval "
10849 "%<%d%>", guard_size, probe_interval);
10850
10851 SET_OPTION_IF_UNSET (&global_options, &global_options_set,
10852 param_sched_pressure_algorithm,
10853 SCHED_PRESSURE_MODEL);
10854
10855 SET_OPTION_IF_UNSET (&global_options, &global_options_set,
10856 param_cycle_accurate_model,
10857 0);
10858
10859 /* Function to allocate machine-dependent function status. */
10860 init_machine_status = &riscv_init_machine_status;
10861
10862 riscv_override_options_internal (&global_options);
10863
10864 /* Save these options as the default ones in case we push and pop them later
10865 while processing functions with potential target attributes. */
10866 target_option_default_node = target_option_current_node
10867 = build_target_option_node (&global_options, &global_options_set);
10868 }
10869
10870 /* Restore or save the TREE_TARGET_GLOBALS from or to NEW_TREE.
10871 Used by riscv_set_current_function to
10872 make sure optab availability predicates are recomputed when necessary. */
10873
10874 void
10875 riscv_save_restore_target_globals (tree new_tree)
10876 {
10877 if (TREE_TARGET_GLOBALS (new_tree))
10878 restore_target_globals (TREE_TARGET_GLOBALS (new_tree));
10879 else if (new_tree == target_option_default_node)
10880 restore_target_globals (&default_target_globals);
10881 else
10882 TREE_TARGET_GLOBALS (new_tree) = save_target_globals_default_opts ();
10883 }
10884
10885 /* Implements TARGET_OPTION_RESTORE. Restore the backend codegen decisions
10886 using the information saved in PTR. */
10887
10888 static void
10889 riscv_option_restore (struct gcc_options *opts,
10890 struct gcc_options * /* opts_set */,
10891 struct cl_target_option * /* ptr */)
10892 {
10893 riscv_override_options_internal (opts);
10894 }
10895
10896 static GTY (()) tree riscv_previous_fndecl;
10897
10898 /* Implement TARGET_CONDITIONAL_REGISTER_USAGE. */
10899
10900 static void
10901 riscv_conditional_register_usage (void)
10902 {
10903 /* We have only x0~x15 on RV32E/RV64E. */
10904 if (TARGET_RVE)
10905 {
10906 for (int r = 16; r <= 31; r++)
10907 fixed_regs[r] = 1;
10908 }
10909
10910 if (riscv_abi == ABI_ILP32E)
10911 {
10912 for (int r = 16; r <= 31; r++)
10913 call_used_regs[r] = 1;
10914 }
10915
10916 if (TARGET_HARD_FLOAT)
10917 global_regs[FRM_REGNUM] = 1;
10918 else
10919 {
10920 for (int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
10921 fixed_regs[regno] = call_used_regs[regno] = 1;
10922 }
10923
10924 /* In the soft-float ABI, there are no callee-saved FP registers. */
10925 if (UNITS_PER_FP_ARG == 0)
10926 {
10927 for (int regno = FP_REG_FIRST; regno <= FP_REG_LAST; regno++)
10928 call_used_regs[regno] = 1;
10929 }
10930
10931 if (TARGET_VECTOR)
10932 global_regs[VXRM_REGNUM] = 1;
10933 else
10934 {
10935 for (int regno = V_REG_FIRST; regno <= V_REG_LAST; regno++)
10936 fixed_regs[regno] = call_used_regs[regno] = 1;
10937
10938 fixed_regs[VTYPE_REGNUM] = call_used_regs[VTYPE_REGNUM] = 1;
10939 fixed_regs[VL_REGNUM] = call_used_regs[VL_REGNUM] = 1;
10940 fixed_regs[VXRM_REGNUM] = call_used_regs[VXRM_REGNUM] = 1;
10941 fixed_regs[FRM_REGNUM] = call_used_regs[FRM_REGNUM] = 1;
10942 }
10943 }
10944
10945 /* Return a register priority for hard reg REGNO. */
10946
10947 static int
10948 riscv_register_priority (int regno)
10949 {
10950 /* Favor compressed registers to improve the odds of RVC instruction
10951 selection. */
10952 if (riscv_compressed_reg_p (regno))
10953 return 1;
10954
10955 return 0;
10956 }
10957
10958 /* Implement TARGET_TRAMPOLINE_INIT. */
10959
10960 static void
10961 riscv_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
10962 {
10963 rtx addr, end_addr, mem;
10964 uint32_t trampoline[4];
10965 uint32_t trampoline_cfi[6];
10966 unsigned int i;
10967 HOST_WIDE_INT static_chain_offset, target_function_offset;
10968 HOST_WIDE_INT lp_value = 0;
10969
10970 /* Work out the offsets of the pointers from the start of the
10971 trampoline code. */
10972 if (!is_zicfilp_p ())
10973 gcc_assert (ARRAY_SIZE (trampoline) * 4 == TRAMPOLINE_CODE_SIZE);
10974 else
10975 gcc_assert (ARRAY_SIZE (trampoline_cfi) * 4 == TRAMPOLINE_CODE_SIZE);
10976
10977 /* Get pointers to the beginning and end of the code block. */
10978 addr = force_reg (Pmode, XEXP (m_tramp, 0));
10979 end_addr = riscv_force_binary (Pmode, PLUS, addr,
10980 GEN_INT (TRAMPOLINE_CODE_SIZE));
10981
10982
10983 if (Pmode == SImode)
10984 {
10985 chain_value = force_reg (Pmode, chain_value);
10986
10987 rtx target_function = force_reg (Pmode, XEXP (DECL_RTL (fndecl), 0));
10988 /* lui t2, hi(chain)
10989 lui t0, hi(func)
10990 addi t2, t2, lo(chain)
10991 jr t0, lo(func)
10992 */
10993 unsigned HOST_WIDE_INT lui_hi_chain_code, lui_hi_func_code;
10994 unsigned HOST_WIDE_INT lo_chain_code, lo_func_code;
10995
10996 rtx uimm_mask = force_reg (SImode, gen_int_mode (-IMM_REACH, SImode));
10997 unsigned insn_count = 0;
10998
10999 /* Insert lpad, if zicfilp is enabled. */
11000 if (is_zicfilp_p ())
11001 {
11002 unsigned HOST_WIDE_INT lpad_code;
11003 lpad_code = OPCODE_AUIPC | (0 << SHIFT_RD) | (lp_value << IMM_BITS);
11004 mem = adjust_address (m_tramp, SImode, 0);
11005 riscv_emit_move (mem, gen_int_mode (lpad_code, SImode));
11006 insn_count++;
11007 }
11008
11009 /* 0xfff. */
11010 rtx imm12_mask = gen_reg_rtx (SImode);
11011 emit_insn (gen_one_cmplsi2 (imm12_mask, uimm_mask));
11012
11013 rtx fixup_value = force_reg (SImode, gen_int_mode (IMM_REACH/2, SImode));
11014
11015 /* Gen lui t2, hi(chain). */
11016 rtx hi_chain = riscv_force_binary (SImode, PLUS, chain_value,
11017 fixup_value);
11018 hi_chain = riscv_force_binary (SImode, AND, hi_chain,
11019 uimm_mask);
11020 lui_hi_chain_code = OPCODE_LUI | (STATIC_CHAIN_REGNUM << SHIFT_RD);
11021 rtx lui_hi_chain_value = force_reg (SImode, gen_int_mode (lui_hi_chain_code,
11022 SImode));
11023 rtx lui_hi_chain = riscv_force_binary (SImode, IOR, hi_chain,
11024 lui_hi_chain_value);
11025 mem = adjust_address (m_tramp, SImode,
11026 insn_count * GET_MODE_SIZE (SImode));
11027 riscv_emit_move (mem, riscv_swap_instruction (lui_hi_chain));
11028 insn_count++;
11029
11030 /* Gen lui t0, hi(func). */
11031 rtx hi_func = riscv_force_binary (SImode, PLUS, target_function,
11032 fixup_value);
11033 hi_func = riscv_force_binary (SImode, AND, hi_func,
11034 uimm_mask);
11035 lui_hi_func_code = OPCODE_LUI | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RD);
11036 rtx lui_hi_func = riscv_force_binary (SImode, IOR, hi_func,
11037 gen_int_mode (lui_hi_func_code, SImode));
11038
11039 mem = adjust_address (m_tramp, SImode,
11040 insn_count * GET_MODE_SIZE (SImode));
11041 riscv_emit_move (mem, riscv_swap_instruction (lui_hi_func));
11042 insn_count++;
11043
11044 /* Gen addi t2, t2, lo(chain). */
11045 rtx lo_chain = riscv_force_binary (SImode, AND, chain_value,
11046 imm12_mask);
11047 lo_chain = riscv_force_binary (SImode, ASHIFT, lo_chain, GEN_INT (20));
11048
11049 lo_chain_code = OPCODE_ADDI
11050 | (STATIC_CHAIN_REGNUM << SHIFT_RD)
11051 | (STATIC_CHAIN_REGNUM << SHIFT_RS1);
11052
11053 rtx addi_lo_chain = riscv_force_binary (SImode, IOR, lo_chain,
11054 force_reg (SImode, GEN_INT (lo_chain_code)));
11055
11056 mem = adjust_address (m_tramp, SImode,
11057 insn_count * GET_MODE_SIZE (SImode));
11058 riscv_emit_move (mem, riscv_swap_instruction (addi_lo_chain));
11059 insn_count++;
11060
11061 /* For zicfilp only, insert lui t2, 1, because use jr t0. */
11062 if (is_zicfilp_p ())
11063 {
11064 unsigned HOST_WIDE_INT set_lpl_code;
11065 set_lpl_code = OPCODE_LUI
11066 | (RISCV_CALL_ADDRESS_LPAD_REGNUM << SHIFT_RD)
11067 | (lp_value << IMM_BITS);
11068 mem = adjust_address (m_tramp, SImode,
11069 insn_count * GET_MODE_SIZE (SImode));
11070 riscv_emit_move (mem, gen_int_mode (set_lpl_code, SImode));
11071 insn_count++;
11072 }
11073
11074 /* Gen jr t0, lo(func). */
11075 rtx lo_func = riscv_force_binary (SImode, AND, target_function,
11076 imm12_mask);
11077 lo_func = riscv_force_binary (SImode, ASHIFT, lo_func, GEN_INT (20));
11078
11079 lo_func_code = OPCODE_JALR | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RS1);
11080
11081 rtx jr_lo_func = riscv_force_binary (SImode, IOR, lo_func,
11082 force_reg (SImode, GEN_INT (lo_func_code)));
11083
11084 mem = adjust_address (m_tramp, SImode, insn_count * GET_MODE_SIZE (SImode));
11085 riscv_emit_move (mem, riscv_swap_instruction (jr_lo_func));
11086 }
11087 else
11088 {
11089 static_chain_offset = TRAMPOLINE_CODE_SIZE;
11090 target_function_offset = static_chain_offset + GET_MODE_SIZE (ptr_mode);
11091
11092 if (!is_zicfilp_p ())
11093 {
11094 /* auipc t2, 0
11095 l[wd] t0, (target_function_offset)(t2)
11096 l[wd] t2, (static_chain_offset)(t2)
11097 jr t0
11098 */
11099 trampoline[0] = OPCODE_AUIPC | (STATIC_CHAIN_REGNUM << SHIFT_RD);
11100 trampoline[1] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
11101 | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RD)
11102 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
11103 | (target_function_offset << SHIFT_IMM);
11104 trampoline[2] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
11105 | (STATIC_CHAIN_REGNUM << SHIFT_RD)
11106 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
11107 | (static_chain_offset << SHIFT_IMM);
11108 trampoline[3] = OPCODE_JALR | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RS1);
11109
11110 /* Copy the trampoline code. */
11111 for (i = 0; i < ARRAY_SIZE (trampoline); i++)
11112 {
11113 if (BYTES_BIG_ENDIAN)
11114 trampoline[i] = __builtin_bswap32 (trampoline[i]);
11115 mem = adjust_address (m_tramp, SImode, i * GET_MODE_SIZE (SImode));
11116 riscv_emit_move (mem, gen_int_mode (trampoline[i], SImode));
11117 }
11118 }
11119 else
11120 {
11121 /* lpad 1
11122 auipc t3, 0
11123 l[wd] t0, (target_function_offset - 4)(t3)
11124 l[wd] t3, (static_chain_offset - 4)(t3)
11125 lui t2, 1
11126 jr t0
11127 */
11128 trampoline_cfi[0] = OPCODE_AUIPC | (0 << SHIFT_RD) | (lp_value << IMM_BITS);
11129 trampoline_cfi[1] = OPCODE_AUIPC | (STATIC_CHAIN_REGNUM << SHIFT_RD);
11130 trampoline_cfi[2] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
11131 | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RD)
11132 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
11133 | ((target_function_offset - 4) << SHIFT_IMM);
11134 trampoline_cfi[3] = (Pmode == DImode ? OPCODE_LD : OPCODE_LW)
11135 | (STATIC_CHAIN_REGNUM << SHIFT_RD)
11136 | (STATIC_CHAIN_REGNUM << SHIFT_RS1)
11137 | ((static_chain_offset - 4) << SHIFT_IMM);
11138 trampoline_cfi[4] = OPCODE_LUI
11139 | (RISCV_CALL_ADDRESS_LPAD_REGNUM << SHIFT_RD)
11140 | (lp_value << IMM_BITS);
11141 trampoline_cfi[5] = OPCODE_JALR | (RISCV_PROLOGUE_TEMP_REGNUM << SHIFT_RS1);
11142
11143 /* Copy the trampoline code. */
11144 for (i = 0; i < ARRAY_SIZE (trampoline_cfi); i++)
11145 {
11146 if (BYTES_BIG_ENDIAN)
11147 trampoline_cfi[i] = __builtin_bswap32 (trampoline_cfi[i]);
11148 mem = adjust_address (m_tramp, SImode, i * GET_MODE_SIZE (SImode));
11149 riscv_emit_move (mem, gen_int_mode (trampoline_cfi[i], SImode));
11150 }
11151 }
11152
11153 /* Set up the static chain pointer field. */
11154 mem = adjust_address (m_tramp, ptr_mode, static_chain_offset);
11155 riscv_emit_move (mem, chain_value);
11156
11157 /* Set up the target function field. */
11158 mem = adjust_address (m_tramp, ptr_mode, target_function_offset);
11159 riscv_emit_move (mem, XEXP (DECL_RTL (fndecl), 0));
11160 }
11161
11162 /* Flush the code part of the trampoline. */
11163 emit_insn (gen_add3_insn (end_addr, addr, GEN_INT (TRAMPOLINE_SIZE)));
11164 emit_insn (gen_clear_cache (addr, end_addr));
11165 }
11166
11167 /* Implement TARGET_FUNCTION_OK_FOR_SIBCALL. */
11168
11169 static bool
11170 riscv_function_ok_for_sibcall (tree decl ATTRIBUTE_UNUSED,
11171 tree exp ATTRIBUTE_UNUSED)
11172 {
11173 /* Don't use sibcalls when use save-restore routine. */
11174 if (TARGET_SAVE_RESTORE)
11175 return false;
11176
11177 /* Don't use sibcall for naked functions. */
11178 if (cfun->machine->naked_p)
11179 return false;
11180
11181 /* Don't use sibcall for interrupt functions. */
11182 if (cfun->machine->interrupt_handler_p)
11183 return false;
11184
11185 /* Don't use sibcalls in the large model, because a sibcall instruction
11186 expanding and a epilogue expanding both use RISCV_PROLOGUE_TEMP
11187 register. */
11188 if (riscv_cmodel == CM_LARGE)
11189 return false;
11190
11191 return true;
11192 }
11193
11194 /* Get the interrupt type, return UNKNOWN_MODE if it's not
11195 interrupt function. */
11196 static enum riscv_privilege_levels
11197 riscv_get_interrupt_type (tree decl)
11198 {
11199 gcc_assert (decl != NULL_TREE);
11200
11201 if ((TREE_CODE(decl) != FUNCTION_DECL)
11202 || (!riscv_interrupt_type_p (TREE_TYPE (decl))))
11203 return UNKNOWN_MODE;
11204
11205 tree attr_args
11206 = TREE_VALUE (lookup_attribute ("interrupt",
11207 TYPE_ATTRIBUTES (TREE_TYPE (decl))));
11208
11209 if (attr_args && TREE_CODE (TREE_VALUE (attr_args)) != VOID_TYPE)
11210 {
11211 const char *string = TREE_STRING_POINTER (TREE_VALUE (attr_args));
11212
11213 if (!strcmp (string, "user"))
11214 return USER_MODE;
11215 else if (!strcmp (string, "supervisor"))
11216 return SUPERVISOR_MODE;
11217 else /* Must be "machine". */
11218 return MACHINE_MODE;
11219 }
11220 else
11221 /* Interrupt attributes are machine mode by default. */
11222 return MACHINE_MODE;
11223 }
11224
11225 /* Implement `TARGET_SET_CURRENT_FUNCTION'. Unpack the codegen decisions
11226 like tuning and ISA features from the DECL_FUNCTION_SPECIFIC_TARGET
11227 of the function, if such exists. This function may be called multiple
11228 times on a single function so use aarch64_previous_fndecl to avoid
11229 setting up identical state. */
11230
11231 /* Sanity checking for above function attributes. */
11232 static void
11233 riscv_set_current_function (tree decl)
11234 {
11235 if (decl == NULL_TREE
11236 || current_function_decl == NULL_TREE
11237 || current_function_decl == error_mark_node
11238 || ! cfun->machine)
11239 return;
11240
11241 if (!cfun->machine->attributes_checked_p)
11242 {
11243 cfun->machine->naked_p = riscv_naked_function_p (decl);
11244 cfun->machine->interrupt_handler_p
11245 = riscv_interrupt_type_p (TREE_TYPE (decl));
11246
11247 if (cfun->machine->naked_p && cfun->machine->interrupt_handler_p)
11248 error ("function attributes %qs and %qs are mutually exclusive",
11249 "interrupt", "naked");
11250
11251 if (cfun->machine->interrupt_handler_p)
11252 {
11253 tree ret = TREE_TYPE (TREE_TYPE (decl));
11254 tree args = TYPE_ARG_TYPES (TREE_TYPE (decl));
11255
11256 if (TREE_CODE (ret) != VOID_TYPE)
11257 error ("%qs function cannot return a value", "interrupt");
11258
11259 if (args && TREE_CODE (TREE_VALUE (args)) != VOID_TYPE)
11260 error ("%qs function cannot have arguments", "interrupt");
11261
11262 cfun->machine->interrupt_mode = riscv_get_interrupt_type (decl);
11263
11264 gcc_assert (cfun->machine->interrupt_mode != UNKNOWN_MODE);
11265 }
11266
11267 /* Don't print the above diagnostics more than once. */
11268 cfun->machine->attributes_checked_p = 1;
11269 }
11270
11271 if (!decl || decl == riscv_previous_fndecl)
11272 return;
11273
11274 tree old_tree = (riscv_previous_fndecl
11275 ? DECL_FUNCTION_SPECIFIC_TARGET (riscv_previous_fndecl)
11276 : NULL_TREE);
11277
11278 tree new_tree = DECL_FUNCTION_SPECIFIC_TARGET (decl);
11279
11280 /* If current function has no attributes but the previous one did,
11281 use the default node. */
11282 if (!new_tree && old_tree)
11283 new_tree = target_option_default_node;
11284
11285 /* If nothing to do, return. #pragma GCC reset or #pragma GCC pop to
11286 the default have been handled by aarch64_save_restore_target_globals from
11287 aarch64_pragma_target_parse. */
11288 if (old_tree == new_tree)
11289 return;
11290
11291 riscv_previous_fndecl = decl;
11292
11293 /* First set the target options. */
11294 cl_target_option_restore (&global_options, &global_options_set,
11295 TREE_TARGET_OPTION (new_tree));
11296
11297 /* The ISA extension can vary based on the function extension like target.
11298 Thus, make sure that the machine modes are reflected correctly here. */
11299 init_adjust_machine_modes ();
11300
11301 riscv_save_restore_target_globals (new_tree);
11302 }
11303
11304 /* Implement TARGET_MERGE_DECL_ATTRIBUTES. */
11305 static tree
11306 riscv_merge_decl_attributes (tree olddecl, tree newdecl)
11307 {
11308 tree combined_attrs;
11309
11310 enum riscv_privilege_levels old_interrupt_type
11311 = riscv_get_interrupt_type (olddecl);
11312 enum riscv_privilege_levels new_interrupt_type
11313 = riscv_get_interrupt_type (newdecl);
11314
11315 /* Check old and new has same interrupt type. */
11316 if ((old_interrupt_type != UNKNOWN_MODE)
11317 && (new_interrupt_type != UNKNOWN_MODE)
11318 && (old_interrupt_type != new_interrupt_type))
11319 error ("%qs function cannot have different interrupt type", "interrupt");
11320
11321 /* Create combined attributes. */
11322 combined_attrs = merge_attributes (DECL_ATTRIBUTES (olddecl),
11323 DECL_ATTRIBUTES (newdecl));
11324
11325 return combined_attrs;
11326 }
11327
11328 /* Implement TARGET_CANNOT_COPY_INSN_P. */
11329
11330 static bool
11331 riscv_cannot_copy_insn_p (rtx_insn *insn)
11332 {
11333 return recog_memoized (insn) >= 0 && get_attr_cannot_copy (insn);
11334 }
11335
11336 /* Implement TARGET_SLOW_UNALIGNED_ACCESS. */
11337
11338 static bool
11339 riscv_slow_unaligned_access (machine_mode mode, unsigned int)
11340 {
11341 return VECTOR_MODE_P (mode) ? TARGET_VECTOR_MISALIGN_SUPPORTED
11342 : riscv_slow_unaligned_access_p;
11343 }
11344
11345 static bool
11346 riscv_overlap_op_by_pieces (void)
11347 {
11348 return tune_param->overlap_op_by_pieces;
11349 }
11350
11351 /* Implement TARGET_CAN_CHANGE_MODE_CLASS. */
11352
11353 static bool
11354 riscv_can_change_mode_class (machine_mode from, machine_mode to,
11355 reg_class_t rclass)
11356 {
11357 /* We have RVV VLS modes and VLA modes sharing same REG_CLASS.
11358 In 'cprop_hardreg' stage, we will try to do hard reg copy propagation
11359 between wider mode (FROM) and narrow mode (TO).
11360
11361 E.g. We should not allow copy propagation
11362 - RVVMF8BI (precision = [16, 16]) -> V32BI (precision = [32, 0])
11363 since we can't order their size which will cause ICE in regcprop.
11364
11365 TODO: Even though they are have different size, they always change
11366 the whole register. We may enhance such case in regcprop to optimize
11367 it in the future. */
11368 if (reg_classes_intersect_p (V_REGS, rclass)
11369 && !ordered_p (GET_MODE_PRECISION (from), GET_MODE_PRECISION (to)))
11370 return false;
11371
11372 /* Subregs of modes larger than one vector are ambiguous.
11373 A V4DImode with rv64gcv_zvl128b could, for example, span two registers/one
11374 register group of two at VLEN = 128 or one register at VLEN >= 256 and
11375 we cannot, statically, determine which part of it to extract.
11376 Therefore prevent that. */
11377 if (reg_classes_intersect_p (V_REGS, rclass)
11378 && riscv_v_ext_vls_mode_p (from)
11379 && !ordered_p (BITS_PER_RISCV_VECTOR, GET_MODE_PRECISION (from)))
11380 return false;
11381
11382 return !reg_classes_intersect_p (FP_REGS, rclass);
11383 }
11384
11385 /* Implement TARGET_CONSTANT_ALIGNMENT. */
11386
11387 static HOST_WIDE_INT
11388 riscv_constant_alignment (const_tree exp, HOST_WIDE_INT align)
11389 {
11390 if ((TREE_CODE (exp) == STRING_CST || TREE_CODE (exp) == CONSTRUCTOR)
11391 && (riscv_align_data_type == riscv_align_data_type_xlen))
11392 return MAX (align, BITS_PER_WORD);
11393 return align;
11394 }
11395
11396 /* Implement TARGET_PROMOTE_FUNCTION_MODE. */
11397
11398 /* This function is equivalent to default_promote_function_mode_always_promote
11399 except that it returns a promoted mode even if type is NULL_TREE. This is
11400 needed by libcalls which have no type (only a mode) such as fixed conversion
11401 routines that take a signed or unsigned char/short/int argument and convert
11402 it to a fixed type. */
11403
11404 static machine_mode
11405 riscv_promote_function_mode (const_tree type ATTRIBUTE_UNUSED,
11406 machine_mode mode,
11407 int *punsignedp ATTRIBUTE_UNUSED,
11408 const_tree fntype ATTRIBUTE_UNUSED,
11409 int for_return ATTRIBUTE_UNUSED)
11410 {
11411 int unsignedp;
11412
11413 if (type != NULL_TREE)
11414 return promote_mode (type, mode, punsignedp);
11415
11416 unsignedp = *punsignedp;
11417 scalar_mode smode = as_a <scalar_mode> (mode);
11418 PROMOTE_MODE (smode, unsignedp, type);
11419 *punsignedp = unsignedp;
11420 return smode;
11421 }
11422
11423 /* Implement TARGET_MACHINE_DEPENDENT_REORG. */
11424
11425 static void
11426 riscv_reorg (void)
11427 {
11428 /* Do nothing unless we have -msave-restore */
11429 if (TARGET_SAVE_RESTORE)
11430 riscv_remove_unneeded_save_restore_calls ();
11431 }
11432
11433 /* Return nonzero if register FROM_REGNO can be renamed to register
11434 TO_REGNO. */
11435
11436 bool
11437 riscv_hard_regno_rename_ok (unsigned from_regno ATTRIBUTE_UNUSED,
11438 unsigned to_regno)
11439 {
11440 /* Interrupt functions can only use registers that have already been
11441 saved by the prologue, even if they would normally be
11442 call-clobbered. */
11443 return !cfun->machine->interrupt_handler_p || df_regs_ever_live_p (to_regno);
11444 }
11445
11446 /* Implement TARGET_NEW_ADDRESS_PROFITABLE_P. */
11447
11448 bool
11449 riscv_new_address_profitable_p (rtx memref, rtx_insn *insn, rtx new_addr)
11450 {
11451 /* Prefer old address if it is less expensive. */
11452 addr_space_t as = MEM_ADDR_SPACE (memref);
11453 bool speed = optimize_bb_for_speed_p (BLOCK_FOR_INSN (insn));
11454 int old_cost = address_cost (XEXP (memref, 0), GET_MODE (memref), as, speed);
11455 int new_cost = address_cost (new_addr, GET_MODE (memref), as, speed);
11456 return new_cost <= old_cost;
11457 }
11458
11459 /* Helper function for generating gpr_save pattern. */
11460
11461 rtx
11462 riscv_gen_gpr_save_insn (struct riscv_frame_info *frame)
11463 {
11464 unsigned count = riscv_save_libcall_count (frame->mask);
11465 /* 1 for unspec 2 for clobber t0/t1 and 1 for ra. */
11466 unsigned veclen = 1 + 2 + 1 + count;
11467 rtvec vec = rtvec_alloc (veclen);
11468
11469 gcc_assert (veclen <= ARRAY_SIZE (gpr_save_reg_order));
11470
11471 RTVEC_ELT (vec, 0) =
11472 gen_rtx_UNSPEC_VOLATILE (VOIDmode,
11473 gen_rtvec (1, GEN_INT (count)), UNSPECV_GPR_SAVE);
11474
11475 for (unsigned i = 1; i < veclen; ++i)
11476 {
11477 unsigned regno = gpr_save_reg_order[i];
11478 rtx reg = gen_rtx_REG (Pmode, regno);
11479 rtx elt;
11480
11481 /* t0 and t1 are CLOBBERs, others are USEs. */
11482 if (i < 3)
11483 elt = gen_rtx_CLOBBER (Pmode, reg);
11484 else
11485 elt = gen_rtx_USE (Pmode, reg);
11486
11487 RTVEC_ELT (vec, i) = elt;
11488 }
11489
11490 /* Largest number of caller-save register must set in mask if we are
11491 not using __riscv_save_0. */
11492 gcc_assert ((count == 0) ||
11493 BITSET_P (frame->mask, gpr_save_reg_order[veclen - 1]));
11494
11495 return gen_rtx_PARALLEL (VOIDmode, vec);
11496 }
11497
11498 static HOST_WIDE_INT
11499 zcmp_base_adj (int regs_num)
11500 {
11501 return riscv_16bytes_align ((regs_num) *GET_MODE_SIZE (word_mode));
11502 }
11503
11504 static HOST_WIDE_INT
11505 zcmp_additional_adj (HOST_WIDE_INT total, int regs_num)
11506 {
11507 return total - zcmp_base_adj (regs_num);
11508 }
11509
11510 bool
11511 riscv_zcmp_valid_stack_adj_bytes_p (HOST_WIDE_INT total, int regs_num)
11512 {
11513 HOST_WIDE_INT additioanl_bytes = zcmp_additional_adj (total, regs_num);
11514 return additioanl_bytes == 0 || additioanl_bytes == 1 * ZCMP_SP_INC_STEP
11515 || additioanl_bytes == 2 * ZCMP_SP_INC_STEP
11516 || additioanl_bytes == ZCMP_MAX_SPIMM * ZCMP_SP_INC_STEP;
11517 }
11518
11519 /* Return true if it's valid gpr_save pattern. */
11520
11521 bool
11522 riscv_gpr_save_operation_p (rtx op)
11523 {
11524 unsigned len = XVECLEN (op, 0);
11525
11526 if (len > ARRAY_SIZE (gpr_save_reg_order))
11527 return false;
11528
11529 for (unsigned i = 0; i < len; i++)
11530 {
11531 rtx elt = XVECEXP (op, 0, i);
11532 if (i == 0)
11533 {
11534 /* First element in parallel is unspec. */
11535 if (GET_CODE (elt) != UNSPEC_VOLATILE
11536 || GET_CODE (XVECEXP (elt, 0, 0)) != CONST_INT
11537 || XINT (elt, 1) != UNSPECV_GPR_SAVE)
11538 return false;
11539 }
11540 else
11541 {
11542 /* Two CLOBBER and USEs, must check the order. */
11543 unsigned expect_code = i < 3 ? CLOBBER : USE;
11544 if (GET_CODE (elt) != expect_code
11545 || !REG_P (XEXP (elt, 1))
11546 || (REGNO (XEXP (elt, 1)) != gpr_save_reg_order[i]))
11547 return false;
11548 }
11549 break;
11550 }
11551 return true;
11552 }
11553
11554 /* Implement TARGET_ASAN_SHADOW_OFFSET. */
11555
11556 static unsigned HOST_WIDE_INT
11557 riscv_asan_shadow_offset (void)
11558 {
11559 /* This number must match ASAN_SHADOW_OFFSET_CONST in the file
11560 libsanitizer/asan/asan_mapping.h, we use 0 here because RV64
11561 using dynamic shadow offset, and RV32 isn't support yet. */
11562 return 0;
11563 }
11564
11565 /* Implement TARGET_ASAN_DYNAMIC_SHADOW_OFFSET_P. */
11566
11567 static bool
11568 riscv_asan_dynamic_shadow_offset_p (void)
11569 {
11570 return TARGET_64BIT;
11571 }
11572
11573 /* Implement TARGET_MANGLE_TYPE. */
11574
11575 static const char *
11576 riscv_mangle_type (const_tree type)
11577 {
11578 /* Half-precision float, _Float16 is "DF16_" and __bf16 is "DF16b". */
11579 if (SCALAR_FLOAT_TYPE_P (type) && TYPE_PRECISION (type) == 16)
11580 {
11581 if (TYPE_MODE (type) == HFmode)
11582 return "DF16_";
11583
11584 if (TYPE_MODE (type) == BFmode)
11585 return "DF16b";
11586
11587 gcc_unreachable ();
11588 }
11589
11590 /* Mangle all vector type for vector extension. */
11591 /* The mangle name follows the rule of RVV LLVM
11592 that is "u" + length of (abi_name) + abi_name. */
11593 if (TYPE_NAME (type) != NULL)
11594 {
11595 const char *res = riscv_vector::mangle_builtin_type (type);
11596 if (res)
11597 return res;
11598 }
11599
11600 /* Use the default mangling. */
11601 return NULL;
11602 }
11603
11604 /* Implement TARGET_SCALAR_MODE_SUPPORTED_P. */
11605
11606 static bool
11607 riscv_scalar_mode_supported_p (scalar_mode mode)
11608 {
11609 if (mode == HFmode || mode == BFmode)
11610 return true;
11611 else
11612 return default_scalar_mode_supported_p (mode);
11613 }
11614
11615 /* Implement TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P - return TRUE
11616 if MODE is HFmode or BFmode, and punt to the generic implementation
11617 otherwise. */
11618
11619 static bool
11620 riscv_libgcc_floating_mode_supported_p (scalar_float_mode mode)
11621 {
11622 if (mode == HFmode || mode == BFmode)
11623 return true;
11624 else
11625 return default_libgcc_floating_mode_supported_p (mode);
11626 }
11627
11628 /* Set the value of FLT_EVAL_METHOD.
11629 ISO/IEC TS 18661-3 defines two values that we'd like to make use of:
11630
11631 0: evaluate all operations and constants, whose semantic type has at
11632 most the range and precision of type float, to the range and
11633 precision of float; evaluate all other operations and constants to
11634 the range and precision of the semantic type;
11635
11636 N, where _FloatN is a supported interchange floating type
11637 evaluate all operations and constants, whose semantic type has at
11638 most the range and precision of _FloatN type, to the range and
11639 precision of the _FloatN type; evaluate all other operations and
11640 constants to the range and precision of the semantic type;
11641
11642 If we have the zfh/zhinx/zvfh extensions then we support _Float16
11643 in native precision, so we should set this to 16. */
11644 static enum flt_eval_method
11645 riscv_excess_precision (enum excess_precision_type type)
11646 {
11647 switch (type)
11648 {
11649 case EXCESS_PRECISION_TYPE_FAST:
11650 case EXCESS_PRECISION_TYPE_STANDARD:
11651 return ((TARGET_ZFH || TARGET_ZHINX || TARGET_ZVFH)
11652 ? FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16
11653 : FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
11654 case EXCESS_PRECISION_TYPE_IMPLICIT:
11655 case EXCESS_PRECISION_TYPE_FLOAT16:
11656 return FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16;
11657 default:
11658 gcc_unreachable ();
11659 }
11660 return FLT_EVAL_METHOD_UNPREDICTABLE;
11661 }
11662
11663 /* Implement TARGET_FLOATN_MODE. */
11664 static opt_scalar_float_mode
11665 riscv_floatn_mode (int n, bool extended)
11666 {
11667 if (!extended && n == 16)
11668 return HFmode;
11669
11670 return default_floatn_mode (n, extended);
11671 }
11672
11673 /* Record that we have no arithmetic or comparison libfuncs for
11674 machine_mode MODE. */
11675 static void
11676 riscv_block_arith_comp_libfuncs_for_mode (machine_mode mode)
11677 {
11678 /* Half-precision float or Brain float operations. The compiler handles all
11679 operations with NULL libfuncs by converting to SFmode. */
11680
11681 /* Arithmetic. */
11682 set_optab_libfunc (add_optab, mode, NULL);
11683 set_optab_libfunc (sdiv_optab, mode, NULL);
11684 set_optab_libfunc (smul_optab, mode, NULL);
11685 set_optab_libfunc (neg_optab, mode, NULL);
11686 set_optab_libfunc (sub_optab, mode, NULL);
11687
11688 /* Comparisons. */
11689 set_optab_libfunc (eq_optab, mode, NULL);
11690 set_optab_libfunc (ne_optab, mode, NULL);
11691 set_optab_libfunc (lt_optab, mode, NULL);
11692 set_optab_libfunc (le_optab, mode, NULL);
11693 set_optab_libfunc (ge_optab, mode, NULL);
11694 set_optab_libfunc (gt_optab, mode, NULL);
11695 set_optab_libfunc (unord_optab, mode, NULL);
11696 }
11697
11698 static void
11699 riscv_init_libfuncs (void)
11700 {
11701 riscv_block_arith_comp_libfuncs_for_mode (HFmode);
11702 riscv_block_arith_comp_libfuncs_for_mode (BFmode);
11703
11704 /* Convert between BFmode and HFmode using only trunc libfunc if needed. */
11705 set_conv_libfunc (sext_optab, BFmode, HFmode, "__trunchfbf2");
11706 set_conv_libfunc (sext_optab, HFmode, BFmode, "__truncbfhf2");
11707 set_conv_libfunc (trunc_optab, BFmode, HFmode, "__trunchfbf2");
11708 set_conv_libfunc (trunc_optab, HFmode, BFmode, "__truncbfhf2");
11709 }
11710
11711 #if CHECKING_P
11712 void
11713 riscv_reinit (void)
11714 {
11715 riscv_option_override ();
11716 init_adjust_machine_modes ();
11717 init_derived_machine_modes ();
11718 reinit_regs ();
11719 init_optabs ();
11720 }
11721 #endif
11722
11723 #if CHECKING_P
11724 #undef TARGET_RUN_TARGET_SELFTESTS
11725 #define TARGET_RUN_TARGET_SELFTESTS selftest::riscv_run_selftests
11726 #endif /* #if CHECKING_P */
11727
11728 /* Implement TARGET_VECTOR_MODE_SUPPORTED_P. */
11729
11730 static bool
11731 riscv_vector_mode_supported_p (machine_mode mode)
11732 {
11733 if (TARGET_VECTOR)
11734 {
11735 /* Avoid fractional LMUL modes for xtheadvector with the exception
11736 of builtin registration time. During registration, all modes
11737 must be available so the order and numbering is consistent,
11738 see PR123279. */
11739 if (TARGET_XTHEADVECTOR && !riscv_registering_builtins
11740 && maybe_lt (GET_MODE_SIZE (mode), BYTES_PER_RISCV_VECTOR))
11741 return false;
11742
11743 return riscv_v_ext_mode_p (mode);
11744 }
11745
11746 return false;
11747 }
11748
11749 /* Implement TARGET_VERIFY_TYPE_CONTEXT. */
11750
11751 static bool
11752 riscv_verify_type_context (location_t loc, type_context_kind context,
11753 const_tree type, bool silent_p)
11754 {
11755 return riscv_vector::verify_type_context (loc, context, type, silent_p);
11756 }
11757
11758 /* Implement TARGET_VECTOR_ALIGNMENT. */
11759
11760 static HOST_WIDE_INT
11761 riscv_vector_alignment (const_tree type)
11762 {
11763 /* ??? Checking the mode isn't ideal, but VECTOR_BOOLEAN_TYPE_P can
11764 be set for non-predicate vectors of booleans. Modes are the most
11765 direct way we have of identifying real RVV predicate types. */
11766 /* FIXME: RVV didn't mention the alignment of bool, we uses
11767 one byte align. */
11768 if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_VECTOR_BOOL)
11769 return 8;
11770
11771 widest_int min_size
11772 = constant_lower_bound (wi::to_poly_widest (TYPE_SIZE (type)));
11773 return wi::umin (min_size, 128).to_uhwi ();
11774 }
11775
11776 /* Implement REGMODE_NATURAL_SIZE. */
11777
11778 poly_uint64
11779 riscv_regmode_natural_size (machine_mode mode)
11780 {
11781 /* The natural size for RVV data modes is one RVV data vector,
11782 and similarly for predicates. We can't independently modify
11783 anything smaller than that. */
11784 /* ??? For now, only do this for variable-width RVV registers.
11785 Doing it for constant-sized registers breaks lower-subreg.c. */
11786
11787 if (riscv_v_ext_mode_p (mode))
11788 {
11789 poly_uint64 size = GET_MODE_SIZE (mode);
11790 if (riscv_v_ext_tuple_mode_p (mode))
11791 {
11792 size = GET_MODE_SIZE (riscv_vector::get_subpart_mode (mode));
11793 if (known_lt (size, BYTES_PER_RISCV_VECTOR))
11794 return size;
11795 }
11796 else if (riscv_v_ext_vector_mode_p (mode))
11797 {
11798 /* RVV mask modes always consume a single register. */
11799 if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL)
11800 return BYTES_PER_RISCV_VECTOR;
11801 }
11802 if (!size.is_constant ())
11803 return BYTES_PER_RISCV_VECTOR;
11804 else if (!riscv_v_ext_vls_mode_p (mode))
11805 /* For -march=rv64gc_zve32f, the natural vector register size
11806 is 32bits which is smaller than scalar register size, so we
11807 return minimum size between vector register size and scalar
11808 register size. */
11809 return MIN (size.to_constant (), UNITS_PER_WORD);
11810 }
11811 return UNITS_PER_WORD;
11812 }
11813
11814 /* Implement the TARGET_DWARF_POLY_INDETERMINATE_VALUE hook. */
11815
11816 static unsigned int
11817 riscv_dwarf_poly_indeterminate_value (unsigned int i, unsigned int *factor,
11818 int *offset)
11819 {
11820 /* Polynomial invariant 1 == (VLENB / BYTES_PER_RISCV_VECTOR) - 1.
11821 1. TARGET_MIN_VLEN == 32, polynomial invariant 1 == (VLENB / 4) - 1.
11822 2. TARGET_MIN_VLEN > 32, polynomial invariant 1 == (VLENB / 8) - 1.
11823 */
11824 gcc_assert (i == 1);
11825 *factor = BYTES_PER_RISCV_VECTOR.coeffs[1];
11826
11827 /* The factor will be zero if vector is not enabled. That ultimately
11828 causes problems in the dwarf2 emitter as the factor is used for
11829 a division, causing a divide by zero. */
11830 if (*factor == 0)
11831 *factor = 1;
11832
11833 *offset = 1;
11834 return RISCV_DWARF_VLENB;
11835 }
11836
11837 /* Implement TARGET_ESTIMATED_POLY_VALUE. */
11838
11839 static HOST_WIDE_INT
11840 riscv_estimated_poly_value (poly_int64 val,
11841 poly_value_estimate_kind kind = POLY_VALUE_LIKELY)
11842 {
11843 if (TARGET_VECTOR)
11844 return riscv_vector::estimated_poly_value (val, kind);
11845 return default_estimated_poly_value (val, kind);
11846 }
11847
11848 /* Return true if the vector misalignment factor is supported by the
11849 target. */
11850 bool
11851 riscv_support_vector_misalignment (machine_mode mode,
11852 const_tree type ATTRIBUTE_UNUSED,
11853 int misalignment,
11854 bool is_packed ATTRIBUTE_UNUSED)
11855 {
11856 /* Depend on movmisalign pattern. */
11857 return default_builtin_support_vector_misalignment (mode, type, misalignment,
11858 is_packed);
11859 }
11860
11861 /* Implement TARGET_VECTORIZE_GET_MASK_MODE. */
11862
11863 static opt_machine_mode
11864 riscv_get_mask_mode (machine_mode mode)
11865 {
11866 if (TARGET_VECTOR && riscv_v_ext_mode_p (mode))
11867 return riscv_vector::get_mask_mode (mode);
11868
11869 return default_get_mask_mode (mode);
11870 }
11871
11872 /* Implement TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE. Assume for now that
11873 it isn't worth branching around empty masked ops (including masked
11874 stores). */
11875
11876 static bool
11877 riscv_empty_mask_is_expensive (unsigned)
11878 {
11879 return false;
11880 }
11881
11882 /* Return true if a shift-amount matches the trailing cleared bits on
11883 a bitmask. */
11884
11885 bool
11886 riscv_shamt_matches_mask_p (int shamt, HOST_WIDE_INT mask)
11887 {
11888 return shamt == ctz_hwi (mask);
11889 }
11890
11891 static HARD_REG_SET
11892 vector_zero_call_used_regs (HARD_REG_SET need_zeroed_hardregs)
11893 {
11894 HARD_REG_SET zeroed_hardregs;
11895 CLEAR_HARD_REG_SET (zeroed_hardregs);
11896
11897 /* Find a register to hold vl. */
11898 unsigned vl_regno = INVALID_REGNUM;
11899 /* Skip the first GPR, otherwise the existing vl is kept due to the same
11900 between vl and avl. */
11901 for (unsigned regno = GP_REG_FIRST + 1; regno <= GP_REG_LAST; regno++)
11902 {
11903 if (TEST_HARD_REG_BIT (need_zeroed_hardregs, regno))
11904 {
11905 vl_regno = regno;
11906 break;
11907 }
11908 }
11909
11910 if (vl_regno > GP_REG_LAST)
11911 sorry ("cannot allocate vl register for %qs on this target",
11912 "-fzero-call-used-regs");
11913
11914 /* Vector configurations need not be saved and restored here. The
11915 -fzero-call-used-regs=* option will zero all vector registers and
11916 return. So there's no vector operations between them. */
11917
11918 bool emitted_vlmax_vsetvl = false;
11919 rtx vl = gen_rtx_REG (Pmode, vl_regno); /* vl is VLMAX. */
11920 for (unsigned regno = V_REG_FIRST; regno <= V_REG_LAST; ++regno)
11921 {
11922 if (TEST_HARD_REG_BIT (need_zeroed_hardregs, regno))
11923 {
11924 rtx target = regno_reg_rtx[regno];
11925 machine_mode mode = GET_MODE (target);
11926
11927 if (!emitted_vlmax_vsetvl)
11928 {
11929 riscv_vector::emit_hard_vlmax_vsetvl (mode, vl);
11930 emitted_vlmax_vsetvl = true;
11931 }
11932
11933 rtx ops[] = {target, CONST0_RTX (mode)};
11934 riscv_vector::emit_vlmax_insn_lra (code_for_pred_mov (mode),
11935 riscv_vector::UNARY_OP, ops, vl);
11936
11937 SET_HARD_REG_BIT (zeroed_hardregs, regno);
11938 }
11939 }
11940
11941 return zeroed_hardregs;
11942 }
11943
11944 /* Generate a sequence of instructions that zero registers specified by
11945 NEED_ZEROED_HARDREGS. Return the ZEROED_HARDREGS that are actually
11946 zeroed. */
11947 HARD_REG_SET
11948 riscv_zero_call_used_regs (HARD_REG_SET need_zeroed_hardregs)
11949 {
11950 HARD_REG_SET zeroed_hardregs;
11951 CLEAR_HARD_REG_SET (zeroed_hardregs);
11952
11953 if (TARGET_VECTOR)
11954 zeroed_hardregs |= vector_zero_call_used_regs (need_zeroed_hardregs);
11955
11956 return zeroed_hardregs | default_zero_call_used_regs (need_zeroed_hardregs
11957 & ~zeroed_hardregs);
11958 }
11959
11960 /* Implement target hook TARGET_ARRAY_MODE. */
11961
11962 static opt_machine_mode
11963 riscv_array_mode (machine_mode mode, unsigned HOST_WIDE_INT nelems)
11964 {
11965 machine_mode vmode;
11966 if (TARGET_VECTOR
11967 && riscv_vector::get_tuple_mode (mode, nelems).exists (&vmode))
11968 return vmode;
11969
11970 return opt_machine_mode ();
11971 }
11972
11973 /* Given memory reference MEM, expand code to compute the aligned
11974 memory address, shift and mask values and store them into
11975 *ALIGNED_MEM, *SHIFT, *MASK and *NOT_MASK. */
11976
11977 void
11978 riscv_subword_address (rtx mem, rtx *aligned_mem, rtx *shift, rtx *mask,
11979 rtx *not_mask)
11980 {
11981 /* Align the memory address to a word. */
11982 rtx addr = force_reg (Pmode, XEXP (mem, 0));
11983
11984 rtx addr_mask = gen_int_mode (-4, Pmode);
11985
11986 rtx aligned_addr = gen_reg_rtx (Pmode);
11987 emit_move_insn (aligned_addr, gen_rtx_AND (Pmode, addr, addr_mask));
11988
11989 *aligned_mem = change_address (mem, SImode, aligned_addr);
11990
11991 /* Calculate the shift amount. */
11992 emit_move_insn (*shift, gen_rtx_AND (SImode, gen_lowpart (SImode, addr),
11993 gen_int_mode (3, SImode)));
11994 emit_move_insn (*shift, gen_rtx_ASHIFT (SImode, *shift,
11995 gen_int_mode (3, SImode)));
11996
11997 /* Calculate the mask. */
11998 int unshifted_mask = GET_MODE_MASK (GET_MODE (mem));
11999
12000 emit_move_insn (*mask, gen_int_mode (unshifted_mask, SImode));
12001
12002 emit_move_insn (*mask, gen_rtx_ASHIFT (SImode, *mask,
12003 gen_lowpart (QImode, *shift)));
12004
12005 emit_move_insn (*not_mask, gen_rtx_NOT (SImode, *mask));
12006 }
12007
12008 /* Leftshift a subword within an SImode register. */
12009
12010 void
12011 riscv_lshift_subword (machine_mode mode ATTRIBUTE_UNUSED, rtx value, rtx shift,
12012 rtx *shifted_value)
12013 {
12014 rtx value_reg = gen_reg_rtx (SImode);
12015 emit_move_insn (value_reg, gen_lowpart (SImode, value));
12016 emit_move_insn (*shifted_value, gen_rtx_ASHIFT (SImode, value_reg,
12017 gen_lowpart (QImode, shift)));
12018 }
12019
12020 /* Return TRUE if we should use the divmod expander, FALSE otherwise. This
12021 allows the behavior to be tuned for specific implementations as well as
12022 when optimizing for size. */
12023
12024 bool
12025 riscv_use_divmod_expander (void)
12026 {
12027 return tune_param->use_divmod_expansion;
12028 }
12029
12030 /* Implement TARGET_VECTORIZE_PREFERRED_SIMD_MODE. */
12031
12032 static machine_mode
12033 riscv_preferred_simd_mode (scalar_mode mode)
12034 {
12035 if (TARGET_VECTOR && !TARGET_XTHEADVECTOR)
12036 return riscv_vector::preferred_simd_mode (mode);
12037
12038 return word_mode;
12039 }
12040
12041 /* Implement target hook TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT. */
12042
12043 static poly_uint64
12044 riscv_vectorize_preferred_vector_alignment (const_tree type)
12045 {
12046 if (riscv_v_ext_mode_p (TYPE_MODE (type)))
12047 return TYPE_ALIGN (TREE_TYPE (type));
12048 return TYPE_ALIGN (type);
12049 }
12050
12051 /* Return true if it is static FRM rounding mode. */
12052
12053 static bool
12054 riscv_static_frm_mode_p (int mode)
12055 {
12056 switch (mode)
12057 {
12058 case riscv_vector::FRM_RDN:
12059 case riscv_vector::FRM_RUP:
12060 case riscv_vector::FRM_RTZ:
12061 case riscv_vector::FRM_RMM:
12062 case riscv_vector::FRM_RNE:
12063 return true;
12064 default:
12065 return false;
12066 }
12067
12068 gcc_unreachable ();
12069 }
12070
12071 /* Implement the floating-point Mode Switching. */
12072
12073 static void
12074 riscv_emit_frm_mode_set (int mode, int prev_mode)
12075 {
12076 rtx backup_reg = DYNAMIC_FRM_RTL (cfun);
12077
12078 if (prev_mode == riscv_vector::FRM_DYN_CALL)
12079 emit_insn (gen_frrmsi (backup_reg)); /* Backup frm when DYN_CALL. */
12080
12081 if (mode != prev_mode)
12082 {
12083 rtx frm = gen_int_mode (mode, SImode);
12084
12085 if (mode == riscv_vector::FRM_DYN_CALL
12086 && prev_mode != riscv_vector::FRM_DYN && STATIC_FRM_P (cfun))
12087 /* No need to emit when prev mode is DYN already. */
12088 emit_insn (gen_fsrmsi_restore_volatile (backup_reg));
12089 else if (mode == riscv_vector::FRM_DYN_EXIT && STATIC_FRM_P (cfun)
12090 && prev_mode != riscv_vector::FRM_DYN
12091 && prev_mode != riscv_vector::FRM_DYN_CALL)
12092 /* No need to emit when prev mode is DYN or DYN_CALL already. */
12093 emit_insn (gen_fsrmsi_restore_volatile (backup_reg));
12094 else if (mode == riscv_vector::FRM_DYN
12095 && prev_mode != riscv_vector::FRM_DYN_CALL)
12096 /* Restore frm value from backup when switch to DYN mode. */
12097 emit_insn (gen_fsrmsi_restore (backup_reg));
12098 else if (riscv_static_frm_mode_p (mode))
12099 /* Set frm value when switch to static mode. */
12100 emit_insn (gen_fsrmsi_restore (frm));
12101 }
12102 }
12103
12104 /* Implement Mode switching. */
12105
12106 static void
12107 riscv_emit_mode_set (int entity, int mode, int prev_mode,
12108 HARD_REG_SET regs_live ATTRIBUTE_UNUSED)
12109 {
12110 switch (entity)
12111 {
12112 case RISCV_VXRM:
12113 if (mode != VXRM_MODE_NONE && mode != prev_mode)
12114 emit_insn (gen_vxrmsi (gen_int_mode (mode, SImode)));
12115 break;
12116 case RISCV_FRM:
12117 riscv_emit_frm_mode_set (mode, prev_mode);
12118 break;
12119 default:
12120 gcc_unreachable ();
12121 }
12122 }
12123
12124 /* Adjust the FRM_NONE insn after a call to FRM_DYN for the
12125 underlying emit. */
12126
12127 static int
12128 riscv_frm_adjust_mode_after_call (rtx_insn *cur_insn, int mode)
12129 {
12130 rtx_insn *insn = prev_nonnote_nondebug_insn_bb (cur_insn);
12131
12132 if (insn && CALL_P (insn))
12133 return riscv_vector::FRM_DYN;
12134
12135 return mode;
12136 }
12137
12138 /* Insert the backup frm insn to the end of the bb if and only if the call
12139 is the last insn of this bb. */
12140
12141 static void
12142 riscv_frm_emit_after_bb_end (rtx_insn *cur_insn)
12143 {
12144 edge eg;
12145 bool abnormal_edge_p = false;
12146 edge_iterator eg_iterator;
12147 basic_block bb = BLOCK_FOR_INSN (cur_insn);
12148
12149 FOR_EACH_EDGE (eg, eg_iterator, bb->succs)
12150 {
12151 if (eg->flags & EDGE_ABNORMAL)
12152 abnormal_edge_p = true;
12153 else
12154 {
12155 start_sequence ();
12156 emit_insn (gen_frrmsi (DYNAMIC_FRM_RTL (cfun)));
12157 rtx_insn *backup_insn = get_insns ();
12158 end_sequence ();
12159
12160 insert_insn_on_edge (backup_insn, eg);
12161 }
12162 }
12163
12164 if (abnormal_edge_p)
12165 {
12166 start_sequence ();
12167 emit_insn (gen_frrmsi (DYNAMIC_FRM_RTL (cfun)));
12168 rtx_insn *backup_insn = get_insns ();
12169 end_sequence ();
12170
12171 insert_insn_end_basic_block (backup_insn, bb);
12172 }
12173
12174 commit_edge_insertions ();
12175 }
12176
12177 /* Return mode that frm must be switched into
12178 prior to the execution of insn. */
12179
12180 static int
12181 riscv_frm_mode_needed (rtx_insn *cur_insn, int code)
12182 {
12183 if (!DYNAMIC_FRM_RTL(cfun))
12184 {
12185 /* The dynamic frm will be initialized only onece during cfun. */
12186 DYNAMIC_FRM_RTL (cfun) = gen_reg_rtx (SImode);
12187 emit_insn_at_entry (gen_frrmsi (DYNAMIC_FRM_RTL (cfun)));
12188 }
12189
12190 if (CALL_P (cur_insn))
12191 {
12192 rtx_insn *insn = next_nonnote_nondebug_insn_bb (cur_insn);
12193
12194 if (!insn)
12195 riscv_frm_emit_after_bb_end (cur_insn);
12196
12197 return riscv_vector::FRM_DYN_CALL;
12198 }
12199
12200 int mode = code >= 0 ? get_attr_frm_mode (cur_insn) : riscv_vector::FRM_NONE;
12201
12202 if (mode == riscv_vector::FRM_NONE)
12203 /* After meet a call, we need to backup the frm because it may be
12204 updated during the call. Here, for each insn, we will check if
12205 the previous insn is a call or not. When previous insn is call,
12206 there will be 2 cases for the emit mode set.
12207
12208 1. Current insn is not MODE_NONE, then the mode switch framework
12209 will do the mode switch from MODE_CALL to MODE_NONE natively.
12210 2. Current insn is MODE_NONE, we need to adjust the MODE_NONE to
12211 the MODE_DYN, and leave the mode switch itself to perform
12212 the emit mode set.
12213 */
12214 mode = riscv_frm_adjust_mode_after_call (cur_insn, mode);
12215
12216 return mode;
12217 }
12218
12219 /* If the current function needs a single VXRM mode, return it. Else
12220 return VXRM_MODE_NONE.
12221
12222 This is called on the first insn in the chain and scans the full function
12223 once to collect VXRM mode settings. If a single mode is needed, it will
12224 often be better to set it once at the start of the function rather than
12225 at an anticipation point. */
12226 static int
12227 singleton_vxrm_need (void)
12228 {
12229 /* Only needed for vector code. */
12230 if (!TARGET_VECTOR)
12231 return VXRM_MODE_NONE;
12232
12233 /* If ENTRY has more than once successor, then don't optimize, just to
12234 keep things simple. */
12235 if (EDGE_COUNT (ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs) > 1)
12236 return VXRM_MODE_NONE;
12237
12238 /* Walk the IL noting if VXRM is needed and if there's more than one
12239 mode needed. */
12240 bool found = false;
12241 int saved_vxrm_mode;
12242 for (rtx_insn *insn = get_insns (); insn; insn = NEXT_INSN (insn))
12243 {
12244 if (!INSN_P (insn) || DEBUG_INSN_P (insn))
12245 continue;
12246
12247 int code = recog_memoized (insn);
12248 if (code < 0)
12249 continue;
12250
12251 int vxrm_mode = get_attr_vxrm_mode (insn);
12252 if (vxrm_mode == VXRM_MODE_NONE)
12253 continue;
12254
12255 /* If this is the first VXRM need, note it. */
12256 if (!found)
12257 {
12258 saved_vxrm_mode = vxrm_mode;
12259 found = true;
12260 continue;
12261 }
12262
12263 /* Not the first VXRM need. If this is different than
12264 the saved need, then we're not going to be able to
12265 optimize and we can stop scanning now. */
12266 if (saved_vxrm_mode != vxrm_mode)
12267 return VXRM_MODE_NONE;
12268
12269 /* Same mode as we've seen, keep scanning. */
12270 }
12271
12272 /* If we got here we scanned the whole function. If we found
12273 some VXRM state, then we can optimize. If we didn't find
12274 VXRM state, then there's nothing to optimize. */
12275 return found ? saved_vxrm_mode : VXRM_MODE_NONE;
12276 }
12277
12278 /* Return mode that entity must be switched into
12279 prior to the execution of insn. */
12280
12281 static int
12282 riscv_mode_needed (int entity, rtx_insn *insn, HARD_REG_SET)
12283 {
12284 int code = recog_memoized (insn);
12285
12286 switch (entity)
12287 {
12288 case RISCV_VXRM:
12289 /* If CUR_INSN is the first insn in the function, then determine if we
12290 want to signal a need in ENTRY->succs to allow for aggressive
12291 elimination of subsequent sets of VXRM. */
12292 if (insn == get_first_nonnote_insn ())
12293 {
12294 int need = singleton_vxrm_need ();
12295 if (need != VXRM_MODE_NONE)
12296 return need;
12297 }
12298
12299 return code >= 0 ? get_attr_vxrm_mode (insn) : VXRM_MODE_NONE;
12300 case RISCV_FRM:
12301 return riscv_frm_mode_needed (insn, code);
12302 default:
12303 gcc_unreachable ();
12304 }
12305 }
12306
12307 /* Return TRUE that an insn is asm. */
12308
12309 static bool
12310 asm_insn_p (rtx_insn *insn)
12311 {
12312 extract_insn (insn);
12313
12314 return recog_data.is_asm;
12315 }
12316
12317 /* Return TRUE that an insn is unknown for VXRM. */
12318
12319 static bool
12320 vxrm_unknown_p (rtx_insn *insn)
12321 {
12322 /* Return true if there is a definition of VXRM. */
12323 if (reg_set_p (gen_rtx_REG (SImode, VXRM_REGNUM), insn))
12324 return true;
12325
12326 /* A CALL function may contain an instruction that modifies the VXRM,
12327 return true in this situation. */
12328 if (CALL_P (insn))
12329 return true;
12330
12331 /* Return true for all assembly since users may hardcode a assembly
12332 like this: asm volatile ("csrwi vxrm, 0"). */
12333 if (asm_insn_p (insn))
12334 return true;
12335
12336 return false;
12337 }
12338
12339 /* Return TRUE that an insn is unknown dynamic for FRM. */
12340
12341 static bool
12342 frm_unknown_dynamic_p (rtx_insn *insn)
12343 {
12344 /* Return true if there is a definition of FRM. */
12345 if (reg_set_p (gen_rtx_REG (SImode, FRM_REGNUM), insn))
12346 return true;
12347
12348 return false;
12349 }
12350
12351 /* Return the mode that an insn results in for VXRM. */
12352
12353 static int
12354 riscv_vxrm_mode_after (rtx_insn *insn, int mode)
12355 {
12356 if (vxrm_unknown_p (insn))
12357 return VXRM_MODE_NONE;
12358
12359 if (recog_memoized (insn) < 0)
12360 return mode;
12361
12362 if (reg_mentioned_p (gen_rtx_REG (SImode, VXRM_REGNUM), PATTERN (insn)))
12363 return get_attr_vxrm_mode (insn);
12364 else
12365 return mode;
12366 }
12367
12368 /* Return the mode that an insn results in for FRM. */
12369
12370 static int
12371 riscv_frm_mode_after (rtx_insn *insn, int mode)
12372 {
12373 STATIC_FRM_P (cfun) = STATIC_FRM_P (cfun) || riscv_static_frm_mode_p (mode);
12374
12375 if (CALL_P (insn))
12376 return mode;
12377
12378 if (frm_unknown_dynamic_p (insn))
12379 return riscv_vector::FRM_DYN;
12380
12381 if (recog_memoized (insn) < 0)
12382 return mode;
12383
12384 if (reg_mentioned_p (gen_rtx_REG (SImode, FRM_REGNUM), PATTERN (insn)))
12385 return get_attr_frm_mode (insn);
12386 else
12387 return mode;
12388 }
12389
12390 /* Return the mode that an insn results in. */
12391
12392 static int
12393 riscv_mode_after (int entity, int mode, rtx_insn *insn, HARD_REG_SET)
12394 {
12395 switch (entity)
12396 {
12397 case RISCV_VXRM:
12398 return riscv_vxrm_mode_after (insn, mode);
12399 case RISCV_FRM:
12400 return riscv_frm_mode_after (insn, mode);
12401 default:
12402 gcc_unreachable ();
12403 }
12404 }
12405
12406 /* Return a mode that ENTITY is assumed to be
12407 switched to at function entry. */
12408
12409 static int
12410 riscv_mode_entry (int entity)
12411 {
12412 switch (entity)
12413 {
12414 case RISCV_VXRM:
12415 return VXRM_MODE_NONE;
12416 case RISCV_FRM:
12417 {
12418 /* According to RVV 1.0 spec, all vector floating-point operations use
12419 the dynamic rounding mode in the frm register. Likewise in other
12420 similar places. */
12421 return riscv_vector::FRM_DYN;
12422 }
12423 default:
12424 gcc_unreachable ();
12425 }
12426 }
12427
12428 /* Return a mode that ENTITY is assumed to be
12429 switched to at function exit. */
12430
12431 static int
12432 riscv_mode_exit (int entity)
12433 {
12434 switch (entity)
12435 {
12436 case RISCV_VXRM:
12437 return VXRM_MODE_NONE;
12438 case RISCV_FRM:
12439 return riscv_vector::FRM_DYN_EXIT;
12440 default:
12441 gcc_unreachable ();
12442 }
12443 }
12444
12445 static int
12446 riscv_mode_priority (int, int n)
12447 {
12448 return n;
12449 }
12450
12451 /* Implement TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_MODES. */
12452 unsigned int
12453 riscv_autovectorize_vector_modes (vector_modes *modes, bool all)
12454 {
12455 if (TARGET_VECTOR && !TARGET_XTHEADVECTOR)
12456 return riscv_vector::autovectorize_vector_modes (modes, all);
12457
12458 return default_autovectorize_vector_modes (modes, all);
12459 }
12460
12461 /* Implement TARGET_VECTORIZE_RELATED_MODE. */
12462 opt_machine_mode
12463 riscv_vectorize_related_mode (machine_mode vector_mode, scalar_mode element_mode,
12464 poly_uint64 nunits)
12465 {
12466 if (TARGET_VECTOR)
12467 return riscv_vector::vectorize_related_mode (vector_mode, element_mode,
12468 nunits);
12469 return default_vectorize_related_mode (vector_mode, element_mode, nunits);
12470 }
12471
12472 /* Implement TARGET_VECTORIZE_VEC_PERM_CONST. */
12473
12474 static bool
12475 riscv_vectorize_vec_perm_const (machine_mode vmode, machine_mode op_mode,
12476 rtx target, rtx op0, rtx op1,
12477 const vec_perm_indices &sel)
12478 {
12479 if (TARGET_VECTOR && riscv_v_ext_mode_p (vmode))
12480 return riscv_vector::expand_vec_perm_const (vmode, op_mode, target, op0,
12481 op1, sel);
12482
12483 return false;
12484 }
12485
12486 static bool
12487 riscv_frame_pointer_required (void)
12488 {
12489 return riscv_save_frame_pointer && !crtl->is_leaf;
12490 }
12491
12492 /* Return the appropriate common costs according to VECTYPE from COSTS. */
12493 static const common_vector_cost *
12494 get_common_costs (const cpu_vector_cost *costs, tree vectype)
12495 {
12496 gcc_assert (costs);
12497
12498 if (vectype && riscv_v_ext_vls_mode_p (TYPE_MODE (vectype)))
12499 return costs->vls;
12500 return costs->vla;
12501 }
12502
12503 /* Return the CPU vector costs according to -mtune if tune info has non-NULL
12504 vector cost. Otherwise, return the default generic vector costs. */
12505 const cpu_vector_cost *
12506 get_vector_costs ()
12507 {
12508 const cpu_vector_cost *costs = tune_param->vec_costs;
12509 if (!costs)
12510 return &generic_vector_cost;
12511 return costs;
12512 }
12513
12514 /* Implement targetm.vectorize.builtin_vectorization_cost. */
12515
12516 static int
12517 riscv_builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost,
12518 tree vectype, int misalign ATTRIBUTE_UNUSED)
12519 {
12520 const cpu_vector_cost *costs = get_vector_costs ();
12521 bool fp = false;
12522
12523 if (vectype != NULL)
12524 fp = FLOAT_TYPE_P (vectype);
12525
12526 const common_vector_cost *common_costs = get_common_costs (costs, vectype);
12527 gcc_assert (common_costs != NULL);
12528 switch (type_of_cost)
12529 {
12530 case scalar_stmt:
12531 return fp ? costs->scalar_fp_stmt_cost : costs->scalar_int_stmt_cost;
12532
12533 case scalar_load:
12534 return costs->scalar_load_cost;
12535
12536 case scalar_store:
12537 return costs->scalar_store_cost;
12538
12539 case vector_stmt:
12540 return fp ? common_costs->fp_stmt_cost : common_costs->int_stmt_cost;
12541
12542 case vector_load:
12543 return common_costs->align_load_cost;
12544
12545 case vector_store:
12546 return common_costs->align_store_cost;
12547
12548 case vec_to_scalar:
12549 return common_costs->vec_to_scalar_cost;
12550
12551 case scalar_to_vec:
12552 return common_costs->scalar_to_vec_cost;
12553
12554 case unaligned_load:
12555 return common_costs->unalign_load_cost;
12556 case vector_gather_load:
12557 return common_costs->gather_load_cost;
12558
12559 case unaligned_store:
12560 return common_costs->unalign_store_cost;
12561 case vector_scatter_store:
12562 return common_costs->scatter_store_cost;
12563
12564 case cond_branch_taken:
12565 return costs->cond_taken_branch_cost;
12566
12567 case cond_branch_not_taken:
12568 return costs->cond_not_taken_branch_cost;
12569
12570 case vec_perm:
12571 return common_costs->permute_cost;
12572
12573 case vec_promote_demote:
12574 return fp ? common_costs->fp_stmt_cost : common_costs->int_stmt_cost;
12575
12576 case vec_construct:
12577 {
12578 /* TODO: This is too pessimistic in case we can splat. */
12579 int regmove_cost = fp ? costs->regmove->FR2VR
12580 : costs->regmove->GR2VR;
12581 return (regmove_cost + common_costs->scalar_to_vec_cost)
12582 * estimated_poly_value (TYPE_VECTOR_SUBPARTS (vectype));
12583 }
12584
12585 default:
12586 gcc_unreachable ();
12587 }
12588
12589 return default_builtin_vectorization_cost (type_of_cost, vectype, misalign);
12590 }
12591
12592 /* Implement targetm.vectorize.create_costs. */
12593
12594 static vector_costs *
12595 riscv_vectorize_create_costs (vec_info *vinfo, bool costing_for_scalar)
12596 {
12597 if (TARGET_VECTOR)
12598 return new riscv_vector::costs (vinfo, costing_for_scalar);
12599 /* Default vector costs. */
12600 return new vector_costs (vinfo, costing_for_scalar);
12601 }
12602
12603 /* Implement TARGET_PREFERRED_ELSE_VALUE. */
12604
12605 static tree
12606 riscv_preferred_else_value (unsigned ifn, tree vectype, unsigned int nops,
12607 tree *ops)
12608 {
12609 if (riscv_v_ext_mode_p (TYPE_MODE (vectype)))
12610 {
12611 tree tmp_var = create_tmp_var (vectype);
12612 TREE_NO_WARNING (tmp_var) = 1;
12613 return get_or_create_ssa_default_def (cfun, tmp_var);
12614 }
12615
12616 return default_preferred_else_value (ifn, vectype, nops, ops);
12617 }
12618
12619 /* If MEM is in the form of "base+offset", extract the two parts
12620 of address and set to BASE and OFFSET, otherwise return false
12621 after clearing BASE and OFFSET. */
12622
12623 bool
12624 extract_base_offset_in_addr (rtx mem, rtx *base, rtx *offset)
12625 {
12626 rtx addr;
12627
12628 gcc_assert (MEM_P (mem));
12629
12630 addr = XEXP (mem, 0);
12631
12632 if (REG_P (addr))
12633 {
12634 *base = addr;
12635 *offset = const0_rtx;
12636 return true;
12637 }
12638
12639 if (GET_CODE (addr) == PLUS
12640 && REG_P (XEXP (addr, 0)) && CONST_INT_P (XEXP (addr, 1)))
12641 {
12642 *base = XEXP (addr, 0);
12643 *offset = XEXP (addr, 1);
12644 return true;
12645 }
12646
12647 *base = NULL_RTX;
12648 *offset = NULL_RTX;
12649
12650 return false;
12651 }
12652
12653 /* Implements target hook vector_mode_supported_any_target_p. */
12654
12655 static bool
12656 riscv_vector_mode_supported_any_target_p (machine_mode)
12657 {
12658 return true;
12659 }
12660
12661 /* Implements hook TARGET_FUNCTION_VALUE_REGNO_P. */
12662
12663 static bool
12664 riscv_function_value_regno_p (const unsigned regno)
12665 {
12666 if (GP_RETURN_FIRST <= regno && regno <= GP_RETURN_LAST)
12667 return true;
12668
12669 if (FP_RETURN_FIRST <= regno && regno <= FP_RETURN_LAST)
12670 return true;
12671
12672 if (TARGET_VECTOR && regno == V_RETURN)
12673 return true;
12674
12675 return false;
12676 }
12677
12678 /* Implements hook TARGET_GET_RAW_RESULT_MODE. */
12679
12680 static fixed_size_mode
12681 riscv_get_raw_result_mode (int regno)
12682 {
12683 if (!is_a <fixed_size_mode> (reg_raw_mode[regno]))
12684 return as_a <fixed_size_mode> (VOIDmode);
12685
12686 return default_get_reg_raw_mode (regno);
12687 }
12688
12689 /* Generate a REG rtx of Xmode from the given rtx and mode.
12690 The rtx x can be REG (QI/HI/SI/DI) or const_int.
12691 The machine_mode mode is the original mode from define pattern.
12692 The rtx_code can be ZERO_EXTEND or SIGN_EXTEND.
12693
12694 If rtx is REG:
12695
12696 1. If rtx Xmode, the RTX x will be returned directly.
12697 2. If rtx non-Xmode, the value extended into a new REG of Xmode will be
12698 returned.
12699
12700 The scalar ALU like add don't support non-Xmode like QI/HI. Then the
12701 gen_lowpart will have problem here. For example, when we would like
12702 to add -1 (0xff if QImode) and 2 (0x2 if QImode). The 0xff and 0x2 will
12703 be loaded to register for adding. Aka:
12704
12705 0xff + 0x2 = 0x101 instead of -1 + 2 = 1.
12706
12707 Thus we need to sign extend 0xff to 0xffffffffffffffff if Xmode is DImode
12708 for correctness. Similar the unsigned also need zero extend.
12709
12710 If rtx is const_int:
12711
12712 1. A new REG rtx will be created to hold the value of const_int.
12713
12714 According to the gccint doc, the constants generated for modes with fewer
12715 bits than in HOST_WIDE_INT must be sign extended to full width. Thus there
12716 will be two cases here, take QImode as example.
12717
12718 For .SAT_SUB (127, y) in QImode, we have (const_int 127) and one simple
12719 mov from const_int to the new REG rtx is good enough here.
12720
12721 For .SAT_SUB (254, y) in QImode, we have (const_int -2) after define_expand.
12722 Aka 0xfffffffffffffffe in Xmode of RV64 but we actually need 0xfe in Xmode
12723 of RV64. So we need to cleanup the highest 56 bits of the new REG rtx moved
12724 from the (const_int -2).
12725
12726 Then the underlying expanding can perform the code generation based on
12727 the REG rtx of Xmode, instead of taking care of these in expand func. */
12728
12729 static rtx
12730 riscv_extend_to_xmode_reg (rtx x, machine_mode mode, enum rtx_code rcode)
12731 {
12732 gcc_assert (rcode == ZERO_EXTEND || rcode == SIGN_EXTEND);
12733
12734 rtx xmode_reg = gen_reg_rtx (Xmode);
12735
12736 if (CONST_INT_P (x))
12737 {
12738 if (mode == Xmode)
12739 emit_move_insn (xmode_reg, x);
12740 else if (rcode == ZERO_EXTEND)
12741 {
12742 /* Combine deliberately does not simplify extensions of constants
12743 (long story). So try to generate the zero extended constant
12744 efficiently.
12745
12746 First extract the constant and mask off all the bits not in
12747 MODE. */
12748 HOST_WIDE_INT val = INTVAL (x);
12749 val &= GET_MODE_MASK (mode);
12750
12751 /* X may need synthesis, so do not blindly copy it. */
12752 xmode_reg = force_reg (Xmode, gen_int_mode (val, Xmode));
12753 }
12754 else /* SIGN_EXTEND. */
12755 {
12756 rtx x_reg = gen_reg_rtx (mode);
12757 emit_move_insn (x_reg, x);
12758 riscv_emit_unary (rcode, xmode_reg, x_reg);
12759 }
12760 }
12761 else if (mode == Xmode)
12762 return x;
12763 else
12764 riscv_emit_unary (rcode, xmode_reg, x);
12765
12766 return xmode_reg;
12767 }
12768
12769 /* Implements the unsigned saturation add standard name usadd for int mode.
12770
12771 z = SAT_ADD(x, y).
12772 =>
12773 1. sum = x + y.
12774 2. sum = truncate (sum) for non-Xmode.
12775 3. lt = sum < x.
12776 4. lt = -lt.
12777 5. z = sum | lt. */
12778
12779 void
12780 riscv_expand_usadd (rtx dest, rtx x, rtx y)
12781 {
12782 machine_mode mode = GET_MODE (dest);
12783 rtx xmode_sum = gen_reg_rtx (Xmode);
12784 rtx xmode_lt = gen_reg_rtx (Xmode);
12785 rtx xmode_x = riscv_extend_to_xmode_reg (x, mode, ZERO_EXTEND);
12786 rtx xmode_y = riscv_extend_to_xmode_reg (y, mode, ZERO_EXTEND);
12787 rtx xmode_dest = gen_reg_rtx (Xmode);
12788
12789 /* Step-1: sum = x + y */
12790 riscv_emit_binary (PLUS, xmode_sum, xmode_x, xmode_y);
12791
12792 /* Step-1.1: truncate sum for non-Xmode for overflow check. */
12793 if (mode != Xmode)
12794 {
12795 int shift_bits = GET_MODE_BITSIZE (Xmode)
12796 - GET_MODE_BITSIZE (mode).to_constant ();
12797
12798 gcc_assert (shift_bits > 0);
12799
12800 riscv_emit_binary (ASHIFT, xmode_sum, xmode_sum, GEN_INT (shift_bits));
12801 riscv_emit_binary (LSHIFTRT, xmode_sum, xmode_sum, GEN_INT (shift_bits));
12802 }
12803
12804 /* Step-2: lt = sum < x */
12805 riscv_emit_binary (LTU, xmode_lt, xmode_sum, xmode_x);
12806
12807 /* Step-3: lt = -lt */
12808 riscv_emit_unary (NEG, xmode_lt, xmode_lt);
12809
12810 /* Step-4: xmode_dest = sum | lt */
12811 riscv_emit_binary (IOR, xmode_dest, xmode_lt, xmode_sum);
12812
12813 /* Step-5: dest = xmode_dest */
12814 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
12815 }
12816
12817 /* Return a new const RTX of MAX value based on given mode. Only
12818 int scalar mode is allowed. */
12819
12820 static rtx
12821 riscv_gen_sign_max_cst (machine_mode mode)
12822 {
12823 switch (mode)
12824 {
12825 case QImode:
12826 return GEN_INT (INT8_MAX);
12827 case HImode:
12828 return GEN_INT (INT16_MAX);
12829 case SImode:
12830 return GEN_INT (INT32_MAX);
12831 case DImode:
12832 return GEN_INT (INT64_MAX);
12833 default:
12834 gcc_unreachable ();
12835 }
12836 }
12837
12838 /* Implements the signed saturation sub standard name ssadd for int mode.
12839
12840 z = SAT_ADD(x, y).
12841 =>
12842 1. sum = x + y
12843 2. xor_0 = x ^ y
12844 3. xor_1 = x ^ sum
12845 4. lt = xor_1 < 0
12846 5. ge = xor_0 >= 0
12847 6. and = ge & lt
12848 7. lt = x < 0
12849 8. neg = -lt
12850 9. max = INT_MAX
12851 10. max = max ^ neg
12852 11. neg = -and
12853 12. max = max & neg
12854 13. and = and - 1
12855 14. z = sum & and
12856 15. z = z | max */
12857
12858 void
12859 riscv_expand_ssadd (rtx dest, rtx x, rtx y)
12860 {
12861 machine_mode mode = GET_MODE (dest);
12862 unsigned bitsize = GET_MODE_BITSIZE (mode).to_constant ();
12863 rtx shift_bits = GEN_INT (bitsize - 1);
12864 rtx xmode_x = riscv_extend_to_xmode_reg (x, mode, SIGN_EXTEND);
12865 rtx xmode_y = riscv_extend_to_xmode_reg (y, mode, SIGN_EXTEND);
12866 rtx xmode_sum = gen_reg_rtx (Xmode);
12867 rtx xmode_dest = gen_reg_rtx (Xmode);
12868 rtx xmode_xor_0 = gen_reg_rtx (Xmode);
12869 rtx xmode_xor_1 = gen_reg_rtx (Xmode);
12870 rtx xmode_ge = gen_reg_rtx (Xmode);
12871 rtx xmode_lt = gen_reg_rtx (Xmode);
12872 rtx xmode_neg = gen_reg_rtx (Xmode);
12873 rtx xmode_and = gen_reg_rtx (Xmode);
12874 rtx xmode_max = gen_reg_rtx (Xmode);
12875
12876 /* Step-1: sum = x + y, xor_0 = x ^ y, xor_1 = x ^ sum. */
12877 riscv_emit_binary (PLUS, xmode_sum, xmode_x, xmode_y);
12878 riscv_emit_binary (XOR, xmode_xor_0, xmode_x, xmode_y);
12879 riscv_emit_binary (XOR, xmode_xor_1, xmode_x, xmode_sum);
12880
12881 /* Step-2: lt = xor_1 < 0, ge = xor_0 >= 0, and = ge & lt. */
12882 riscv_emit_binary (LSHIFTRT, xmode_lt, xmode_xor_1, shift_bits);
12883 riscv_emit_binary (LSHIFTRT, xmode_ge, xmode_xor_0, shift_bits);
12884 riscv_emit_binary (XOR, xmode_ge, xmode_ge, CONST1_RTX (Xmode));
12885 riscv_emit_binary (AND, xmode_and, xmode_lt, xmode_ge);
12886 riscv_emit_binary (AND, xmode_and, xmode_and, CONST1_RTX (Xmode));
12887
12888 /* Step-3: lt = x < 0, neg = -lt */
12889 riscv_emit_binary (LT, xmode_lt, xmode_x, CONST0_RTX (Xmode));
12890 riscv_emit_unary (NEG, xmode_neg, xmode_lt);
12891
12892 /* Step-4: max = 0x7f..., max = max ^ neg, neg = -and, max = max & neg */
12893 riscv_emit_move (xmode_max, riscv_gen_sign_max_cst (mode));
12894 riscv_emit_binary (XOR, xmode_max, xmode_max, xmode_neg);
12895 riscv_emit_unary (NEG, xmode_neg, xmode_and);
12896 riscv_emit_binary (AND, xmode_max, xmode_max, xmode_neg);
12897
12898 /* Step-5: and = and - 1, dest = sum & and */
12899 riscv_emit_binary (PLUS, xmode_and, xmode_and, CONSTM1_RTX (Xmode));
12900 riscv_emit_binary (AND, xmode_dest, xmode_sum, xmode_and);
12901
12902 /* Step-6: xmode_dest = xmode_dest | xmode_max, dest = xmode_dest */
12903 riscv_emit_binary (IOR, xmode_dest, xmode_dest, xmode_max);
12904 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
12905 }
12906
12907 /* Implements the unsigned saturation sub standard name usadd for int mode.
12908
12909 z = SAT_SUB(x, y).
12910 =>
12911 1. minus = x - y.
12912 2. lt = x < y.
12913 3. lt = lt - 1.
12914 4. z = minus & lt. */
12915
12916 void
12917 riscv_expand_ussub (rtx dest, rtx x, rtx y)
12918 {
12919 machine_mode mode = GET_MODE (dest);
12920 rtx xmode_x = riscv_extend_to_xmode_reg (x, mode, ZERO_EXTEND);
12921 rtx xmode_y = riscv_extend_to_xmode_reg (y, mode, ZERO_EXTEND);
12922 rtx xmode_lt = gen_reg_rtx (Xmode);
12923 rtx xmode_minus = gen_reg_rtx (Xmode);
12924 rtx xmode_dest = gen_reg_rtx (Xmode);
12925
12926 /* Step-1: minus = x - y */
12927 riscv_emit_binary (MINUS, xmode_minus, xmode_x, xmode_y);
12928
12929 /* Step-2: lt = x < y */
12930 riscv_emit_binary (LTU, xmode_lt, xmode_x, xmode_y);
12931
12932 /* Step-3: lt = lt - 1 (lt + (-1)) */
12933 riscv_emit_binary (PLUS, xmode_lt, xmode_lt, CONSTM1_RTX (Xmode));
12934
12935 /* Step-4: xmode_dest = minus & lt */
12936 riscv_emit_binary (AND, xmode_dest, xmode_lt, xmode_minus);
12937
12938 /* Step-5: dest = xmode_dest */
12939 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
12940 }
12941
12942 /* Implements the signed saturation sub standard name ssadd for int mode.
12943
12944 z = SAT_SUB(x, y).
12945 =>
12946 1. minus = x - y
12947 2. xor_0 = x ^ y
12948 3. xor_1 = x ^ minus
12949 4. lt_0 = xor_1 < 0
12950 5. lt_1 = xor_0 < 0
12951 6. and = lt_0 & lt_1
12952 7. lt = x < 0
12953 8. neg = -lt
12954 9. max = INT_MAX
12955 10. max = max ^ neg
12956 11. neg = -and
12957 12. max = max & neg
12958 13. and = and - 1
12959 14. z = minus & and
12960 15. z = z | max */
12961
12962 void
12963 riscv_expand_sssub (rtx dest, rtx x, rtx y)
12964 {
12965 machine_mode mode = GET_MODE (dest);
12966 unsigned bitsize = GET_MODE_BITSIZE (mode).to_constant ();
12967 rtx shift_bits = GEN_INT (bitsize - 1);
12968 rtx xmode_x = riscv_extend_to_xmode_reg (x, mode, SIGN_EXTEND);
12969 rtx xmode_y = riscv_extend_to_xmode_reg (y, mode, SIGN_EXTEND);
12970 rtx xmode_minus = gen_reg_rtx (Xmode);
12971 rtx xmode_xor_0 = gen_reg_rtx (Xmode);
12972 rtx xmode_xor_1 = gen_reg_rtx (Xmode);
12973 rtx xmode_lt_0 = gen_reg_rtx (Xmode);
12974 rtx xmode_lt_1 = gen_reg_rtx (Xmode);
12975 rtx xmode_and = gen_reg_rtx (Xmode);
12976 rtx xmode_lt = gen_reg_rtx (Xmode);
12977 rtx xmode_neg = gen_reg_rtx (Xmode);
12978 rtx xmode_max = gen_reg_rtx (Xmode);
12979 rtx xmode_dest = gen_reg_rtx (Xmode);
12980
12981 /* Step-1: mins = x - y, xor_0 = x ^ y, xor_1 = x ^ minus. */
12982 riscv_emit_binary (MINUS, xmode_minus, xmode_x, xmode_y);
12983 riscv_emit_binary (XOR, xmode_xor_0, xmode_x, xmode_y);
12984 riscv_emit_binary (XOR, xmode_xor_1, xmode_x, xmode_minus);
12985
12986 /* Step-2: and = xor_0 < 0 & xor_1 < 0. */
12987 riscv_emit_binary (LSHIFTRT, xmode_lt_0, xmode_xor_0, shift_bits);
12988 riscv_emit_binary (LSHIFTRT, xmode_lt_1, xmode_xor_1, shift_bits);
12989 riscv_emit_binary (AND, xmode_and, xmode_lt_0, xmode_lt_1);
12990 riscv_emit_binary (AND, xmode_and, xmode_and, CONST1_RTX (Xmode));
12991
12992 /* Step-3: lt = x < 0, neg = -lt. */
12993 riscv_emit_binary (LT, xmode_lt, xmode_x, CONST0_RTX (Xmode));
12994 riscv_emit_unary (NEG, xmode_neg, xmode_lt);
12995
12996 /* Step-4: max = 0x7f..., max = max ^ neg, neg = -and, max = max & neg. */
12997 riscv_emit_move (xmode_max, riscv_gen_sign_max_cst (mode));
12998 riscv_emit_binary (XOR, xmode_max, xmode_max, xmode_neg);
12999 riscv_emit_unary (NEG, xmode_neg, xmode_and);
13000 riscv_emit_binary (AND, xmode_max, xmode_max, xmode_neg);
13001
13002 /* Step-5: and = and - 1, dest = minus & and. */
13003 riscv_emit_binary (PLUS, xmode_and, xmode_and, CONSTM1_RTX (Xmode));
13004 riscv_emit_binary (AND, xmode_dest, xmode_minus, xmode_and);
13005
13006 /* Step-6: dest = dest | max. */
13007 riscv_emit_binary (IOR, xmode_dest, xmode_dest, xmode_max);
13008 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
13009 }
13010
13011 /* Implement the unsigned saturation truncation for int mode.
13012
13013 b = SAT_TRUNC (a);
13014 =>
13015 1. max = half truncated max
13016 2. lt = a < max
13017 3. lt = lt - 1 (lt 0, ge -1)
13018 4. d = a | lt
13019 5. b = (trunc)d */
13020
13021 void
13022 riscv_expand_ustrunc (rtx dest, rtx src)
13023 {
13024 machine_mode mode = GET_MODE (dest);
13025 rtx xmode_max = gen_reg_rtx (Xmode);
13026 unsigned precision = GET_MODE_PRECISION (mode).to_constant ();
13027
13028 gcc_assert (precision < 64);
13029
13030 uint64_t max = ((uint64_t)1u << precision) - 1u;
13031 rtx xmode_src = riscv_extend_to_xmode_reg (src, GET_MODE (src), ZERO_EXTEND);
13032 rtx xmode_dest = gen_reg_rtx (Xmode);
13033 rtx xmode_lt = gen_reg_rtx (Xmode);
13034
13035 /* Step-1: max = half truncated max */
13036 emit_move_insn (xmode_max, gen_int_mode (max, Xmode));
13037
13038 /* Step-2: lt = src < max */
13039 riscv_emit_binary (LTU, xmode_lt, xmode_src, xmode_max);
13040
13041 /* Step-3: lt = lt - 1 */
13042 riscv_emit_binary (PLUS, xmode_lt, xmode_lt, CONSTM1_RTX (Xmode));
13043
13044 /* Step-4: xmode_dest = lt | src */
13045 riscv_emit_binary (IOR, xmode_dest, xmode_lt, xmode_src);
13046
13047 /* Step-5: dest = xmode_dest */
13048 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
13049 }
13050
13051 /* Implement the signed saturation truncation for int mode.
13052
13053 b = SAT_TRUNC (a);
13054 =>
13055 1. lt = a < max
13056 2. gt = min < a
13057 3. mask = lt & gt
13058 4. trunc_mask = -mask
13059 5. sat_mask = mask - 1
13060 6. lt = a < 0
13061 7. neg = -lt
13062 8. sat = neg ^ max
13063 9. trunc = src & trunc_mask
13064 10. sat = sat & sat_mask
13065 11. dest = trunc | sat */
13066
13067 void
13068 riscv_expand_sstrunc (rtx dest, rtx src)
13069 {
13070 machine_mode mode = GET_MODE (dest);
13071 unsigned narrow_prec = GET_MODE_PRECISION (mode).to_constant ();
13072 HOST_WIDE_INT narrow_max = ((int64_t)1 << (narrow_prec - 1)) - 1; // 127
13073 HOST_WIDE_INT narrow_min = -narrow_max - 1; // -128
13074
13075 rtx xmode_narrow_max = gen_reg_rtx (Xmode);
13076 rtx xmode_narrow_min = gen_reg_rtx (Xmode);
13077 rtx xmode_lt = gen_reg_rtx (Xmode);
13078 rtx xmode_gt = gen_reg_rtx (Xmode);
13079 rtx xmode_src = riscv_extend_to_xmode_reg (src, GET_MODE (src), SIGN_EXTEND);
13080 rtx xmode_dest = gen_reg_rtx (Xmode);
13081 rtx xmode_mask = gen_reg_rtx (Xmode);
13082 rtx xmode_sat = gen_reg_rtx (Xmode);
13083 rtx xmode_trunc = gen_reg_rtx (Xmode);
13084 rtx xmode_sat_mask = gen_reg_rtx (Xmode);
13085 rtx xmode_trunc_mask = gen_reg_rtx (Xmode);
13086
13087 /* Step-1: lt = src < max, gt = min < src, mask = lt & gt */
13088 emit_move_insn (xmode_narrow_min, gen_int_mode (narrow_min, Xmode));
13089 emit_move_insn (xmode_narrow_max, gen_int_mode (narrow_max, Xmode));
13090 riscv_emit_binary (LT, xmode_lt, xmode_src, xmode_narrow_max);
13091 riscv_emit_binary (LT, xmode_gt, xmode_narrow_min, xmode_src);
13092 riscv_emit_binary (AND, xmode_mask, xmode_lt, xmode_gt);
13093
13094 /* Step-2: sat_mask = mask - 1, trunc_mask = ~mask */
13095 riscv_emit_binary (PLUS, xmode_sat_mask, xmode_mask, CONSTM1_RTX (Xmode));
13096 riscv_emit_unary (NEG, xmode_trunc_mask, xmode_mask);
13097
13098 /* Step-3: lt = src < 0, lt = -lt, sat = lt ^ narrow_max */
13099 riscv_emit_binary (LT, xmode_lt, xmode_src, CONST0_RTX (Xmode));
13100 riscv_emit_unary (NEG, xmode_lt, xmode_lt);
13101 riscv_emit_binary (XOR, xmode_sat, xmode_lt, xmode_narrow_max);
13102
13103 /* Step-4: xmode_dest = (src & trunc_mask) | (sat & sat_mask) */
13104 riscv_emit_binary (AND, xmode_trunc, xmode_src, xmode_trunc_mask);
13105 riscv_emit_binary (AND, xmode_sat, xmode_sat, xmode_sat_mask);
13106 riscv_emit_binary (IOR, xmode_dest, xmode_trunc, xmode_sat);
13107
13108 /* Step-5: dest = xmode_dest */
13109 emit_move_insn (dest, gen_lowpart (mode, xmode_dest));
13110 }
13111
13112 /* Implement TARGET_C_MODE_FOR_FLOATING_TYPE. Return TFmode for
13113 TI_LONG_DOUBLE_TYPE which is for long double type, go with the
13114 default one for the others. */
13115
13116 static machine_mode
13117 riscv_c_mode_for_floating_type (enum tree_index ti)
13118 {
13119 if (ti == TI_LONG_DOUBLE_TYPE)
13120 return TFmode;
13121 return default_mode_for_floating_type (ti);
13122 }
13123
13124 /* This parses the attribute arguments to target_version in DECL and modifies
13125 the feature mask and priority required to select those targets. */
13126 static void
13127 parse_features_for_version (tree decl,
13128 struct riscv_feature_bits &res,
13129 int &priority)
13130 {
13131 tree version_attr = lookup_attribute ("target_version",
13132 DECL_ATTRIBUTES (decl));
13133 if (version_attr == NULL_TREE)
13134 {
13135 res.length = 0;
13136 priority = 0;
13137 return;
13138 }
13139
13140 const char *version_string = TREE_STRING_POINTER (TREE_VALUE (TREE_VALUE
13141 (version_attr)));
13142 gcc_assert (version_string != NULL);
13143 if (strcmp (version_string, "default") == 0)
13144 {
13145 res.length = 0;
13146 priority = 0;
13147 return;
13148 }
13149 struct cl_target_option cur_target;
13150 cl_target_option_save (&cur_target, &global_options,
13151 &global_options_set);
13152 /* Always set to default option before parsing "arch=+..." */
13153 struct cl_target_option *default_opts
13154 = TREE_TARGET_OPTION (target_option_default_node);
13155 cl_target_option_restore (&global_options, &global_options_set,
13156 default_opts);
13157
13158 riscv_process_target_version_attr (TREE_VALUE (version_attr),
13159 DECL_SOURCE_LOCATION (decl));
13160
13161 priority = global_options.x_riscv_fmv_priority;
13162 const char *arch_string = global_options.x_riscv_arch_string;
13163 bool parse_res
13164 = riscv_minimal_hwprobe_feature_bits (arch_string, &res,
13165 DECL_SOURCE_LOCATION (decl));
13166 gcc_assert (parse_res);
13167
13168 if (arch_string != default_opts->x_riscv_arch_string)
13169 free (CONST_CAST (void *, (const void *) arch_string));
13170
13171 cl_target_option_restore (&global_options, &global_options_set,
13172 &cur_target);
13173 }
13174
13175 /* Compare priorities of two feature masks. Return:
13176 1: mask1 is higher priority
13177 -1: mask2 is higher priority
13178 0: masks are equal.
13179 Since riscv_feature_bits has total 128 bits to be used as mask, when counting
13180 the total 1s in the mask, the 1s in group1 needs to multiply a weight. */
13181 static int
13182 compare_fmv_features (const struct riscv_feature_bits &mask1,
13183 const struct riscv_feature_bits &mask2,
13184 int prio1, int prio2)
13185 {
13186 unsigned length1 = mask1.length, length2 = mask2.length;
13187 /* 1. Compare length, for length == 0 means default version, which should be
13188 the lowest priority). */
13189 if (length1 != length2)
13190 return length1 > length2 ? 1 : -1;
13191 /* 2. Compare the priority. */
13192 if (prio1 != prio2)
13193 return prio1 > prio2 ? 1 : -1;
13194 /* 3. Compare the total number of 1s in the mask. */
13195 unsigned pop1 = 0, pop2 = 0;
13196 for (unsigned i = 0; i < length1; i++)
13197 {
13198 pop1 += __builtin_popcountll (mask1.features[i]);
13199 pop2 += __builtin_popcountll (mask2.features[i]);
13200 }
13201 if (pop1 != pop2)
13202 return pop1 > pop2 ? 1 : -1;
13203 /* 4. Compare the mask bit by bit order. */
13204 for (unsigned i = 0; i < length1; i++)
13205 {
13206 unsigned long long xor_mask = mask1.features[i] ^ mask2.features[i];
13207 if (xor_mask == 0)
13208 continue;
13209 return TEST_BIT (mask1.features[i], __builtin_ctzll (xor_mask)) ? 1 : -1;
13210 }
13211 /* 5. If all bits are equal, return 0. */
13212 return 0;
13213 }
13214
13215 /* Compare priorities of two version decls. Return:
13216 1: mask1 is higher priority
13217 -1: mask2 is higher priority
13218 0: masks are equal. */
13219 int
13220 riscv_compare_version_priority (tree decl1, tree decl2)
13221 {
13222 struct riscv_feature_bits mask1, mask2;
13223 int prio1, prio2;
13224
13225 parse_features_for_version (decl1, mask1, prio1);
13226 parse_features_for_version (decl2, mask2, prio2);
13227
13228 return compare_fmv_features (mask1, mask2, prio1, prio2);
13229 }
13230
13231 /* This function returns true if FN1 and FN2 are versions of the same function,
13232 that is, the target_version attributes of the function decls are different.
13233 This assumes that FN1 and FN2 have the same signature. */
13234
13235 bool
13236 riscv_common_function_versions (tree fn1, tree fn2)
13237 {
13238 if (TREE_CODE (fn1) != FUNCTION_DECL
13239 || TREE_CODE (fn2) != FUNCTION_DECL)
13240 return false;
13241
13242 return riscv_compare_version_priority (fn1, fn2) != 0;
13243 }
13244
13245 /* Implement TARGET_MANGLE_DECL_ASSEMBLER_NAME, to add function multiversioning
13246 suffixes. */
13247
13248 tree
13249 riscv_mangle_decl_assembler_name (tree decl, tree id)
13250 {
13251 /* For function version, add the target suffix to the assembler name. */
13252 if (TREE_CODE (decl) == FUNCTION_DECL
13253 && DECL_FUNCTION_VERSIONED (decl))
13254 {
13255 std::string name = IDENTIFIER_POINTER (id) + std::string (".");
13256 tree target_attr = lookup_attribute ("target_version",
13257 DECL_ATTRIBUTES (decl));
13258
13259 if (target_attr == NULL_TREE)
13260 {
13261 name += "default";
13262 return get_identifier (name.c_str ());
13263 }
13264
13265 const char *version_string = TREE_STRING_POINTER (TREE_VALUE (TREE_VALUE
13266 (target_attr)));
13267
13268 /* Replace non-alphanumeric characters with underscores as the suffix. */
13269 for (const char *c = version_string; *c; c++)
13270 name += ISALNUM (*c) == 0 ? '_' : *c;
13271
13272 if (DECL_ASSEMBLER_NAME_SET_P (decl))
13273 SET_DECL_RTL (decl, NULL);
13274
13275 id = get_identifier (name.c_str ());
13276 }
13277
13278 return id;
13279 }
13280
13281 /* This adds a condition to the basic_block NEW_BB in function FUNCTION_DECL
13282 to return a pointer to VERSION_DECL if all feature bits specified in
13283 FEATURE_MASK are not set in MASK_VAR. This function will be called during
13284 version dispatch to decide which function version to execute. It returns
13285 the basic block at the end, to which more conditions can be added. */
13286 static basic_block
13287 add_condition_to_bb (tree function_decl, tree version_decl,
13288 const struct riscv_feature_bits *features,
13289 tree mask_var, basic_block new_bb)
13290 {
13291 gimple *return_stmt;
13292 tree convert_expr, result_var;
13293 gimple *convert_stmt;
13294 gimple *if_else_stmt;
13295
13296 basic_block bb1, bb2, bb3;
13297 edge e12, e23;
13298
13299 gimple_seq gseq;
13300
13301 push_cfun (DECL_STRUCT_FUNCTION (function_decl));
13302
13303 gcc_assert (new_bb != NULL);
13304 gseq = bb_seq (new_bb);
13305
13306 convert_expr = build1 (CONVERT_EXPR, ptr_type_node,
13307 build_fold_addr_expr (version_decl));
13308 result_var = create_tmp_var (ptr_type_node);
13309 convert_stmt = gimple_build_assign (result_var, convert_expr);
13310 return_stmt = gimple_build_return (result_var);
13311
13312 if (features->length == 0)
13313 {
13314 /* Default version. */
13315 gimple_seq_add_stmt (&gseq, convert_stmt);
13316 gimple_seq_add_stmt (&gseq, return_stmt);
13317 set_bb_seq (new_bb, gseq);
13318 gimple_set_bb (convert_stmt, new_bb);
13319 gimple_set_bb (return_stmt, new_bb);
13320 pop_cfun ();
13321 return new_bb;
13322 }
13323
13324 tree zero_llu = build_int_cst (long_long_unsigned_type_node, 0);
13325 tree cond_status = create_tmp_var (boolean_type_node);
13326 tree mask_array_ele_var = create_tmp_var (long_long_unsigned_type_node);
13327 tree and_expr_var = create_tmp_var (long_long_unsigned_type_node);
13328 tree eq_expr_var = create_tmp_var (boolean_type_node);
13329
13330 /* cond_status = true. */
13331 gimple *cond_init_stmt = gimple_build_assign (cond_status, boolean_true_node);
13332 gimple_set_block (cond_init_stmt, DECL_INITIAL (function_decl));
13333 gimple_set_bb (cond_init_stmt, new_bb);
13334 gimple_seq_add_stmt (&gseq, cond_init_stmt);
13335
13336 for (int i = 0; i < RISCV_FEATURE_BITS_LENGTH; i++)
13337 {
13338 tree index_expr = build_int_cst (unsigned_type_node, i);
13339 /* mask_array_ele_var = mask_var[i] */
13340 tree mask_array_ref = build4 (ARRAY_REF, long_long_unsigned_type_node,
13341 mask_var, index_expr, NULL_TREE, NULL_TREE);
13342
13343 gimple *mask_stmt = gimple_build_assign (mask_array_ele_var,
13344 mask_array_ref);
13345 gimple_set_block (mask_stmt, DECL_INITIAL (function_decl));
13346 gimple_set_bb (mask_stmt, new_bb);
13347 gimple_seq_add_stmt (&gseq, mask_stmt);
13348 /* and_expr_var = mask_array_ele_var & features[i] */
13349 tree and_expr = build2 (BIT_AND_EXPR,
13350 long_long_unsigned_type_node,
13351 mask_array_ele_var,
13352 build_int_cst (long_long_unsigned_type_node,
13353 features->features[i]));
13354 gimple *and_stmt = gimple_build_assign (and_expr_var, and_expr);
13355 gimple_set_block (and_stmt, DECL_INITIAL (function_decl));
13356 gimple_set_bb (and_stmt, new_bb);
13357 gimple_seq_add_stmt (&gseq, and_stmt);
13358 /* eq_expr_var = and_expr_var == 0. */
13359 tree eq_expr = build2 (EQ_EXPR, boolean_type_node,
13360 and_expr_var, zero_llu);
13361 gimple *eq_stmt = gimple_build_assign (eq_expr_var, eq_expr);
13362 gimple_set_block (eq_stmt, DECL_INITIAL (function_decl));
13363 gimple_set_bb (eq_stmt, new_bb);
13364 gimple_seq_add_stmt (&gseq, eq_stmt);
13365 /* cond_status = cond_status & eq_expr_var. */
13366 tree cond_expr = build2 (BIT_AND_EXPR, boolean_type_node,
13367 cond_status, eq_expr_var);
13368 gimple *cond_stmt = gimple_build_assign (cond_status, cond_expr);
13369 gimple_set_block (cond_stmt, DECL_INITIAL (function_decl));
13370 gimple_set_bb (cond_stmt, new_bb);
13371 gimple_seq_add_stmt (&gseq, cond_stmt);
13372 }
13373 if_else_stmt = gimple_build_cond (EQ_EXPR, cond_status, boolean_true_node,
13374 NULL_TREE, NULL_TREE);
13375 gimple_set_block (if_else_stmt, DECL_INITIAL (function_decl));
13376 gimple_set_bb (if_else_stmt, new_bb);
13377 gimple_seq_add_stmt (&gseq, if_else_stmt);
13378
13379 gimple_seq_add_stmt (&gseq, convert_stmt);
13380 gimple_seq_add_stmt (&gseq, return_stmt);
13381 set_bb_seq (new_bb, gseq);
13382
13383 bb1 = new_bb;
13384 e12 = split_block (bb1, if_else_stmt);
13385 bb2 = e12->dest;
13386 e12->flags &= ~EDGE_FALLTHRU;
13387 e12->flags |= EDGE_TRUE_VALUE;
13388
13389 e23 = split_block (bb2, return_stmt);
13390
13391 gimple_set_bb (convert_stmt, bb2);
13392 gimple_set_bb (return_stmt, bb2);
13393
13394 bb3 = e23->dest;
13395 make_edge (bb1, bb3, EDGE_FALSE_VALUE);
13396
13397 remove_edge (e23);
13398 make_edge (bb2, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
13399
13400 pop_cfun ();
13401
13402 return bb3;
13403 }
13404
13405 /* This function generates the dispatch function for
13406 multi-versioned functions. DISPATCH_DECL is the function which will
13407 contain the dispatch logic. FNDECLS are the function choices for
13408 dispatch, and is a tree chain. EMPTY_BB is the basic block pointer
13409 in DISPATCH_DECL in which the dispatch code is generated. */
13410
13411 static int
13412 dispatch_function_versions (tree dispatch_decl,
13413 void *fndecls_p,
13414 basic_block *empty_bb)
13415 {
13416 gimple *ifunc_cpu_init_stmt;
13417 gimple_seq gseq;
13418 vec<tree> *fndecls;
13419
13420 gcc_assert (dispatch_decl != NULL
13421 && fndecls_p != NULL
13422 && empty_bb != NULL);
13423
13424 push_cfun (DECL_STRUCT_FUNCTION (dispatch_decl));
13425
13426 gseq = bb_seq (*empty_bb);
13427 /* Function version dispatch is via IFUNC. IFUNC resolvers fire before
13428 constructors, so explicity call __init_riscv_feature_bits here. */
13429 tree init_fn_type = build_function_type_list (void_type_node,
13430 long_unsigned_type_node,
13431 ptr_type_node,
13432 NULL);
13433 tree init_fn_id = get_identifier ("__init_riscv_feature_bits");
13434 tree init_fn_decl = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL,
13435 init_fn_id, init_fn_type);
13436 DECL_EXTERNAL (init_fn_decl) = 1;
13437 TREE_PUBLIC (init_fn_decl) = 1;
13438 DECL_VISIBILITY (init_fn_decl) = VISIBILITY_HIDDEN;
13439 DECL_VISIBILITY_SPECIFIED (init_fn_decl) = 1;
13440 ifunc_cpu_init_stmt = gimple_build_call (init_fn_decl, 0);
13441 gimple_seq_add_stmt (&gseq, ifunc_cpu_init_stmt);
13442 gimple_set_bb (ifunc_cpu_init_stmt, *empty_bb);
13443
13444 /* Build the struct type for __riscv_feature_bits. */
13445 tree global_type = lang_hooks.types.make_type (RECORD_TYPE);
13446 tree features_type = build_array_type_nelts (long_long_unsigned_type_node,
13447 RISCV_FEATURE_BITS_LENGTH);
13448 tree field1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
13449 get_identifier ("length"),
13450 unsigned_type_node);
13451 tree field2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
13452 get_identifier ("features"),
13453 features_type);
13454 DECL_FIELD_CONTEXT (field1) = global_type;
13455 DECL_FIELD_CONTEXT (field2) = global_type;
13456 TYPE_FIELDS (global_type) = field1;
13457 DECL_CHAIN (field1) = field2;
13458 layout_type (global_type);
13459
13460 tree global_var = build_decl (UNKNOWN_LOCATION, VAR_DECL,
13461 get_identifier ("__riscv_feature_bits"),
13462 global_type);
13463 DECL_EXTERNAL (global_var) = 1;
13464 TREE_PUBLIC (global_var) = 1;
13465 DECL_VISIBILITY (global_var) = VISIBILITY_HIDDEN;
13466 DECL_VISIBILITY_SPECIFIED (global_var) = 1;
13467 tree mask_var = create_tmp_var (features_type);
13468 tree feature_ele_var = create_tmp_var (long_long_unsigned_type_node);
13469 tree noted_var = create_tmp_var (long_long_unsigned_type_node);
13470
13471
13472 for (int i = 0; i < RISCV_FEATURE_BITS_LENGTH; i++)
13473 {
13474 tree index_expr = build_int_cst (unsigned_type_node, i);
13475 /* feature_ele_var = __riscv_feature_bits.features[i] */
13476 tree component_expr = build3 (COMPONENT_REF, features_type,
13477 global_var, field2, NULL_TREE);
13478 tree feature_array_ref = build4 (ARRAY_REF, long_long_unsigned_type_node,
13479 component_expr, index_expr,
13480 NULL_TREE, NULL_TREE);
13481 gimple *feature_stmt = gimple_build_assign (feature_ele_var,
13482 feature_array_ref);
13483 gimple_set_block (feature_stmt, DECL_INITIAL (dispatch_decl));
13484 gimple_set_bb (feature_stmt, *empty_bb);
13485 gimple_seq_add_stmt (&gseq, feature_stmt);
13486 /* noted_var = ~feature_ele_var. */
13487 tree not_expr = build1 (BIT_NOT_EXPR, long_long_unsigned_type_node,
13488 feature_ele_var);
13489 gimple *not_stmt = gimple_build_assign (noted_var, not_expr);
13490 gimple_set_block (not_stmt, DECL_INITIAL (dispatch_decl));
13491 gimple_set_bb (not_stmt, *empty_bb);
13492 gimple_seq_add_stmt (&gseq, not_stmt);
13493 /* mask_var[i] = noted_var. */
13494 tree mask_array_ref = build4 (ARRAY_REF, long_long_unsigned_type_node,
13495 mask_var, index_expr, NULL_TREE, NULL_TREE);
13496 gimple *mask_assign_stmt = gimple_build_assign (mask_array_ref,
13497 noted_var);
13498 gimple_set_block (mask_assign_stmt, DECL_INITIAL (dispatch_decl));
13499 gimple_set_bb (mask_assign_stmt, *empty_bb);
13500 gimple_seq_add_stmt (&gseq, mask_assign_stmt);
13501 }
13502
13503 set_bb_seq (*empty_bb, gseq);
13504
13505 pop_cfun ();
13506
13507 /* fndecls_p is actually a vector. */
13508 fndecls = static_cast<vec<tree> *> (fndecls_p);
13509
13510 /* At least one more version other than the default. */
13511 unsigned int num_versions = fndecls->length ();
13512 gcc_assert (num_versions >= 2);
13513
13514 struct function_version_info
13515 {
13516 tree version_decl;
13517 struct riscv_feature_bits features;
13518 int prio;
13519 };
13520
13521 std::vector <function_version_info> function_versions;
13522
13523 for (tree version_decl : *fndecls)
13524 {
13525 struct function_version_info version_info;
13526 version_info.version_decl = version_decl;
13527 // Get attribute string, parse it and find the right features.
13528 parse_features_for_version (version_decl,
13529 version_info.features,
13530 version_info.prio);
13531 function_versions.push_back (version_info);
13532 }
13533
13534
13535 auto compare_feature_version_info = [](const struct function_version_info &v1,
13536 const struct function_version_info &v2)
13537 {
13538 return compare_fmv_features (v1.features, v2.features,
13539 v1.prio, v2.prio) > 0;
13540 };
13541
13542 /* Sort the versions according to descending order of dispatch priority. */
13543 std::sort (function_versions.begin (), function_versions.end (),
13544 compare_feature_version_info);
13545
13546 for (auto version : function_versions)
13547 {
13548 *empty_bb = add_condition_to_bb (dispatch_decl,
13549 version.version_decl,
13550 &version.features,
13551 mask_var,
13552 *empty_bb);
13553 }
13554
13555 return 0;
13556 }
13557
13558 /* Return an identifier for the base assembler name of a versioned function.
13559 This is computed by taking the default version's assembler name, and
13560 stripping off the ".default" suffix if it's already been appended. */
13561
13562 static tree
13563 get_suffixed_assembler_name (tree default_decl, const char *suffix)
13564 {
13565 std::string name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (default_decl));
13566
13567 auto size = name.size ();
13568 if (size >= 8 && name.compare (size - 8, 8, ".default") == 0)
13569 name.resize (size - 8);
13570 name += suffix;
13571 return get_identifier (name.c_str ());
13572 }
13573
13574 /* Make the resolver function decl to dispatch the versions of
13575 a multi-versioned function, DEFAULT_DECL. IFUNC_ALIAS_DECL is
13576 ifunc alias that will point to the created resolver. Create an
13577 empty basic block in the resolver and store the pointer in
13578 EMPTY_BB. Return the decl of the resolver function. */
13579
13580 static tree
13581 make_resolver_func (const tree default_decl,
13582 const tree ifunc_alias_decl,
13583 basic_block *empty_bb)
13584 {
13585 tree decl, type, t;
13586
13587 /* Create resolver function name based on default_decl. We need to remove an
13588 existing ".default" suffix if this has already been appended. */
13589 tree decl_name = get_suffixed_assembler_name (default_decl, ".resolver");
13590 const char *resolver_name = IDENTIFIER_POINTER (decl_name);
13591
13592 /* The resolver function should have signature
13593 (void *) resolver (uint64_t, void *) */
13594 type = build_function_type_list (ptr_type_node,
13595 uint64_type_node,
13596 ptr_type_node,
13597 NULL_TREE);
13598
13599 decl = build_fn_decl (resolver_name, type);
13600 SET_DECL_ASSEMBLER_NAME (decl, decl_name);
13601
13602 DECL_NAME (decl) = decl_name;
13603 TREE_USED (decl) = 1;
13604 DECL_ARTIFICIAL (decl) = 1;
13605 DECL_IGNORED_P (decl) = 1;
13606 TREE_PUBLIC (decl) = 0;
13607 DECL_UNINLINABLE (decl) = 1;
13608
13609 /* Resolver is not external, body is generated. */
13610 DECL_EXTERNAL (decl) = 0;
13611 DECL_EXTERNAL (ifunc_alias_decl) = 0;
13612
13613 DECL_CONTEXT (decl) = NULL_TREE;
13614 DECL_INITIAL (decl) = make_node (BLOCK);
13615 DECL_STATIC_CONSTRUCTOR (decl) = 0;
13616
13617 if (DECL_COMDAT_GROUP (default_decl)
13618 || TREE_PUBLIC (default_decl))
13619 {
13620 /* In this case, each translation unit with a call to this
13621 versioned function will put out a resolver. Ensure it
13622 is comdat to keep just one copy. */
13623 DECL_COMDAT (decl) = 1;
13624 make_decl_one_only (decl, DECL_ASSEMBLER_NAME (decl));
13625 }
13626 else
13627 TREE_PUBLIC (ifunc_alias_decl) = 0;
13628
13629 /* Build result decl and add to function_decl. */
13630 t = build_decl (UNKNOWN_LOCATION, RESULT_DECL, NULL_TREE, ptr_type_node);
13631 DECL_CONTEXT (t) = decl;
13632 DECL_ARTIFICIAL (t) = 1;
13633 DECL_IGNORED_P (t) = 1;
13634 DECL_RESULT (decl) = t;
13635
13636 /* Build parameter decls and add to function_decl. */
13637 tree arg1 = build_decl (UNKNOWN_LOCATION, PARM_DECL,
13638 get_identifier ("hwcap"),
13639 uint64_type_node);
13640 tree arg2 = build_decl (UNKNOWN_LOCATION, PARM_DECL,
13641 get_identifier ("hwprobe_func"),
13642 ptr_type_node);
13643 DECL_CONTEXT (arg1) = decl;
13644 DECL_CONTEXT (arg2) = decl;
13645 DECL_ARTIFICIAL (arg1) = 1;
13646 DECL_ARTIFICIAL (arg2) = 1;
13647 DECL_IGNORED_P (arg1) = 1;
13648 DECL_IGNORED_P (arg2) = 1;
13649 DECL_ARG_TYPE (arg1) = uint64_type_node;
13650 DECL_ARG_TYPE (arg2) = ptr_type_node;
13651 DECL_ARGUMENTS (decl) = arg1;
13652 TREE_CHAIN (arg1) = arg2;
13653
13654 gimplify_function_tree (decl);
13655 push_cfun (DECL_STRUCT_FUNCTION (decl));
13656 *empty_bb = init_lowered_empty_function (decl, false,
13657 profile_count::uninitialized ());
13658
13659 cgraph_node::add_new_function (decl, true);
13660 symtab->call_cgraph_insertion_hooks (cgraph_node::get_create (decl));
13661
13662 pop_cfun ();
13663
13664 gcc_assert (ifunc_alias_decl != NULL);
13665 /* Mark ifunc_alias_decl as "ifunc" with resolver as resolver_name. */
13666 DECL_ATTRIBUTES (ifunc_alias_decl)
13667 = make_attribute ("ifunc", resolver_name,
13668 DECL_ATTRIBUTES (ifunc_alias_decl));
13669
13670 /* Create the alias for dispatch to resolver here. */
13671 cgraph_node::create_same_body_alias (ifunc_alias_decl, decl);
13672 return decl;
13673 }
13674
13675 /* Implement TARGET_GENERATE_VERSION_DISPATCHER_BODY. */
13676
13677 tree
13678 riscv_generate_version_dispatcher_body (void *node_p)
13679 {
13680 tree resolver_decl;
13681 basic_block empty_bb;
13682 tree default_ver_decl;
13683 struct cgraph_node *versn;
13684 struct cgraph_node *node;
13685
13686 struct cgraph_function_version_info *node_version_info = NULL;
13687 struct cgraph_function_version_info *versn_info = NULL;
13688
13689 node = (cgraph_node *)node_p;
13690
13691 node_version_info = node->function_version ();
13692 gcc_assert (node->dispatcher_function
13693 && node_version_info != NULL);
13694
13695 if (node_version_info->dispatcher_resolver)
13696 return node_version_info->dispatcher_resolver;
13697
13698 /* The first version in the chain corresponds to the default version. */
13699 default_ver_decl = node_version_info->next->this_node->decl;
13700
13701 /* node is going to be an alias, so remove the finalized bit. */
13702 node->definition = false;
13703
13704 resolver_decl = make_resolver_func (default_ver_decl,
13705 node->decl, &empty_bb);
13706
13707 node_version_info->dispatcher_resolver = resolver_decl;
13708
13709 push_cfun (DECL_STRUCT_FUNCTION (resolver_decl));
13710
13711 auto_vec<tree, 2> fn_ver_vec;
13712
13713 for (versn_info = node_version_info->next; versn_info;
13714 versn_info = versn_info->next)
13715 {
13716 versn = versn_info->this_node;
13717 /* Check for virtual functions here again, as by this time it should
13718 have been determined if this function needs a vtable index or
13719 not. This happens for methods in derived classes that override
13720 virtual methods in base classes but are not explicitly marked as
13721 virtual. */
13722 if (DECL_VINDEX (versn->decl))
13723 sorry ("virtual function multiversioning not supported");
13724
13725 fn_ver_vec.safe_push (versn->decl);
13726 }
13727
13728 dispatch_function_versions (resolver_decl, &fn_ver_vec, &empty_bb);
13729 cgraph_edge::rebuild_edges ();
13730 pop_cfun ();
13731
13732 /* Fix up symbol names. First we need to obtain the base name, which may
13733 have already been mangled. */
13734 tree base_name = get_suffixed_assembler_name (default_ver_decl, "");
13735
13736 /* We need to redo the version mangling on the non-default versions for the
13737 target_clones case. Redoing the mangling for the target_version case is
13738 redundant but does no harm. We need to skip the default version, because
13739 expand_clones will append ".default" later; fortunately that suffix is the
13740 one we want anyway. */
13741 for (versn_info = node_version_info->next->next; versn_info;
13742 versn_info = versn_info->next)
13743 {
13744 tree version_decl = versn_info->this_node->decl;
13745 tree name = riscv_mangle_decl_assembler_name (version_decl,
13746 base_name);
13747 symtab->change_decl_assembler_name (version_decl, name);
13748 }
13749
13750 /* We also need to use the base name for the ifunc declaration. */
13751 symtab->change_decl_assembler_name (node->decl, base_name);
13752
13753 return resolver_decl;
13754 }
13755
13756 /* Make a dispatcher declaration for the multi-versioned function DECL.
13757 Calls to DECL function will be replaced with calls to the dispatcher
13758 by the front-end. Returns the decl of the dispatcher function. */
13759
13760 tree
13761 riscv_get_function_versions_dispatcher (void *decl)
13762 {
13763 tree fn = (tree) decl;
13764 struct cgraph_node *node = NULL;
13765 struct cgraph_node *default_node = NULL;
13766 struct cgraph_function_version_info *node_v = NULL;
13767 struct cgraph_function_version_info *first_v = NULL;
13768
13769 tree dispatch_decl = NULL;
13770
13771 struct cgraph_function_version_info *default_version_info = NULL;
13772
13773 gcc_assert (fn != NULL && DECL_FUNCTION_VERSIONED (fn));
13774
13775 node = cgraph_node::get (fn);
13776 gcc_assert (node != NULL);
13777
13778 node_v = node->function_version ();
13779 gcc_assert (node_v != NULL);
13780
13781 if (node_v->dispatcher_resolver != NULL)
13782 return node_v->dispatcher_resolver;
13783
13784 /* Find the default version and make it the first node. */
13785 first_v = node_v;
13786 /* Go to the beginning of the chain. */
13787 while (first_v->prev != NULL)
13788 first_v = first_v->prev;
13789 default_version_info = first_v;
13790
13791 while (default_version_info != NULL)
13792 {
13793 struct riscv_feature_bits res;
13794 int priority; /* Unused. */
13795 parse_features_for_version (default_version_info->this_node->decl,
13796 res, priority);
13797 if (res.length == 0)
13798 break;
13799 default_version_info = default_version_info->next;
13800 }
13801
13802 /* If there is no default node, just return NULL. */
13803 if (default_version_info == NULL)
13804 return NULL;
13805
13806 /* Make default info the first node. */
13807 if (first_v != default_version_info)
13808 {
13809 default_version_info->prev->next = default_version_info->next;
13810 if (default_version_info->next)
13811 default_version_info->next->prev = default_version_info->prev;
13812 first_v->prev = default_version_info;
13813 default_version_info->next = first_v;
13814 default_version_info->prev = NULL;
13815 }
13816
13817 default_node = default_version_info->this_node;
13818
13819 if (targetm.has_ifunc_p ())
13820 {
13821 struct cgraph_function_version_info *it_v = NULL;
13822 struct cgraph_node *dispatcher_node = NULL;
13823 struct cgraph_function_version_info *dispatcher_version_info = NULL;
13824
13825 /* Right now, the dispatching is done via ifunc. */
13826 dispatch_decl = make_dispatcher_decl (default_node->decl);
13827 TREE_NOTHROW (dispatch_decl) = TREE_NOTHROW (fn);
13828
13829 dispatcher_node = cgraph_node::get_create (dispatch_decl);
13830 gcc_assert (dispatcher_node != NULL);
13831 dispatcher_node->dispatcher_function = 1;
13832 dispatcher_version_info
13833 = dispatcher_node->insert_new_function_version ();
13834 dispatcher_version_info->next = default_version_info;
13835 dispatcher_node->definition = 1;
13836
13837 /* Set the dispatcher for all the versions. */
13838 it_v = default_version_info;
13839 while (it_v != NULL)
13840 {
13841 it_v->dispatcher_resolver = dispatch_decl;
13842 it_v = it_v->next;
13843 }
13844 }
13845 else
13846 {
13847 error_at (DECL_SOURCE_LOCATION (default_node->decl),
13848 "multiversioning needs %<ifunc%> which is not supported "
13849 "on this target");
13850 }
13851
13852 return dispatch_decl;
13853 }
13854
13855 /* On riscv we have an ABI defined safe buffer. This constant is used to
13856 determining the probe offset for alloca. */
13857
13858 static HOST_WIDE_INT
13859 riscv_stack_clash_protection_alloca_probe_range (void)
13860 {
13861 return STACK_CLASH_CALLER_GUARD;
13862 }
13863
13864 static bool
13865 riscv_use_by_pieces_infrastructure_p (unsigned HOST_WIDE_INT size,
13866 unsigned alignment,
13867 enum by_pieces_operation op, bool speed_p)
13868 {
13869 /* For set/clear with size > UNITS_PER_WORD, by pieces uses vector broadcasts
13870 with UNITS_PER_WORD size pieces. Use setmem<mode> instead which can use
13871 bigger chunks. */
13872 if (TARGET_VECTOR && stringop_strategy & STRATEGY_VECTOR
13873 && (op == CLEAR_BY_PIECES || op == SET_BY_PIECES)
13874 && speed_p && size > UNITS_PER_WORD)
13875 return false;
13876
13877 return default_use_by_pieces_infrastructure_p (size, alignment, op, speed_p);
13878 }
13879
13880 /* Generate instruction sequence
13881 which reflects the value of the OP using bswap and brev8 instructions.
13882 OP's mode may be less than word_mode, to get the correct number,
13883 after reflecting we shift right the value by SHIFT_VAL.
13884 E.g. we have 1111 0001, after reflection (target 32-bit) we will get
13885 1000 1111 0000 0000, if we shift-out 16 bits,
13886 we will get the desired one: 1000 1111. */
13887
13888 void
13889 generate_reflecting_code_using_brev (rtx *op_p)
13890 {
13891 rtx op = *op_p;
13892 machine_mode op_mode = GET_MODE (op);
13893
13894 /* OP may be smaller than a word. We can use a paradoxical subreg
13895 to compensate for that. It should never be larger than a word
13896 for RISC-V. */
13897 gcc_assert (op_mode <= word_mode);
13898 if (op_mode != word_mode)
13899 op = gen_lowpart (word_mode, op);
13900
13901 HOST_WIDE_INT shift_val = (BITS_PER_WORD
13902 - GET_MODE_BITSIZE (op_mode).to_constant ());
13903 riscv_expand_op (BSWAP, word_mode, op, op, op);
13904 riscv_expand_op (LSHIFTRT, word_mode, op, op,
13905 gen_int_mode (shift_val, word_mode));
13906 if (TARGET_64BIT)
13907 emit_insn (gen_riscv_brev8_di (op, op));
13908 else
13909 emit_insn (gen_riscv_brev8_si (op, op));
13910 }
13911
13912
13913 /* Generate assembly to calculate CRC using clmul instruction.
13914 The following code will be generated when the CRC and data sizes are equal:
13915 li a4,quotient
13916 li a5,polynomial
13917 xor a0,a1,a0
13918 clmul a0,a0,a4
13919 srli a0,a0,crc_size
13920 clmul a0,a0,a5
13921 slli a0,a0,word_mode_size - crc_size
13922 srli a0,a0,word_mode_size - crc_size
13923 ret
13924 crc_size may be 8, 16, 32.
13925 Some instructions will be added for the cases when CRC's size is larger than
13926 data's size.
13927 OPERANDS[1] is input CRC,
13928 OPERANDS[2] is data (message),
13929 OPERANDS[3] is the polynomial without the leading 1. */
13930
13931 void
13932 expand_crc_using_clmul (scalar_mode crc_mode, scalar_mode data_mode,
13933 rtx *operands)
13934 {
13935 /* Check and keep arguments. */
13936 gcc_assert (!CONST_INT_P (operands[0]));
13937 gcc_assert (CONST_INT_P (operands[3]));
13938 unsigned short crc_size = GET_MODE_BITSIZE (crc_mode);
13939 gcc_assert (crc_size <= 32);
13940 unsigned short data_size = GET_MODE_BITSIZE (data_mode);
13941
13942 /* Calculate the quotient. */
13943 unsigned HOST_WIDE_INT
13944 q = gf2n_poly_long_div_quotient (UINTVAL (operands[3]), crc_size);
13945
13946 rtx crc_extended = gen_rtx_ZERO_EXTEND (word_mode, operands[1]);
13947 rtx crc = gen_reg_rtx (word_mode);
13948 if (crc_size > data_size)
13949 riscv_expand_op (LSHIFTRT, word_mode, crc, crc_extended,
13950 gen_int_mode (crc_size - data_size, word_mode));
13951 else
13952 crc = gen_rtx_ZERO_EXTEND (word_mode, operands[1]);
13953 rtx t0 = gen_reg_rtx (word_mode);
13954 riscv_emit_move (t0, gen_int_mode (q, word_mode));
13955 rtx t1 = gen_reg_rtx (word_mode);
13956 riscv_emit_move (t1, operands[3]);
13957
13958 rtx a0 = gen_reg_rtx (word_mode);
13959 rtx data = gen_rtx_ZERO_EXTEND (word_mode, operands[2]);
13960 riscv_expand_op (XOR, word_mode, a0, crc, data);
13961
13962 if (TARGET_64BIT)
13963 emit_insn (gen_riscv_clmul_di (a0, a0, t0));
13964 else
13965 emit_insn (gen_riscv_clmul_si (a0, a0, t0));
13966
13967 riscv_expand_op (LSHIFTRT, word_mode, a0, a0,
13968 gen_int_mode (crc_size, word_mode));
13969 if (TARGET_64BIT)
13970 emit_insn (gen_riscv_clmul_di (a0, a0, t1));
13971 else
13972 emit_insn (gen_riscv_clmul_si (a0, a0, t1));
13973
13974 if (crc_size > data_size)
13975 {
13976 rtx crc_part = gen_reg_rtx (word_mode);
13977 riscv_expand_op (ASHIFT, word_mode, crc_part, operands[1],
13978 gen_int_mode (data_size, word_mode));
13979 riscv_expand_op (XOR, word_mode, a0, a0, crc_part);
13980 }
13981 riscv_emit_move (operands[0], gen_lowpart (crc_mode, a0));
13982 }
13983
13984 /* Generate assembly to calculate reversed CRC using clmul instruction.
13985 OPERANDS[1] is input CRC,
13986 OPERANDS[2] is data (message),
13987 OPERANDS[3] is the polynomial without the leading 1. */
13988
13989 void
13990 expand_reversed_crc_using_clmul (scalar_mode crc_mode, scalar_mode data_mode,
13991 rtx *operands)
13992 {
13993 /* Check and keep arguments. */
13994 gcc_assert (!CONST_INT_P (operands[0]));
13995 gcc_assert (CONST_INT_P (operands[3]));
13996 unsigned short crc_size = GET_MODE_BITSIZE (crc_mode);
13997 gcc_assert (crc_size <= 32);
13998 unsigned short data_size = GET_MODE_BITSIZE (data_mode);
13999 rtx polynomial = operands[3];
14000
14001 /* Calculate the quotient. */
14002 unsigned HOST_WIDE_INT
14003 q = gf2n_poly_long_div_quotient (UINTVAL (polynomial), crc_size);
14004 /* Reflect the calculated quotient. */
14005 q = reflect_hwi (q, crc_size + 1);
14006 rtx t0 = gen_reg_rtx (word_mode);
14007 riscv_emit_move (t0, gen_int_mode (q, word_mode));
14008
14009 /* Reflect the polynomial. */
14010 unsigned HOST_WIDE_INT
14011 ref_polynomial = reflect_hwi (UINTVAL (polynomial),
14012 crc_size);
14013 rtx t1 = gen_reg_rtx (word_mode);
14014 riscv_emit_move (t1, gen_int_mode (ref_polynomial << 1, word_mode));
14015
14016 rtx crc = gen_rtx_ZERO_EXTEND (word_mode, operands[1]);
14017 rtx data = gen_rtx_ZERO_EXTEND (word_mode, operands[2]);
14018 rtx a0 = gen_reg_rtx (word_mode);
14019 riscv_expand_op (XOR, word_mode, a0, crc, data);
14020
14021 if (TARGET_64BIT)
14022 emit_insn (gen_riscv_clmul_di (a0, a0, t0));
14023 else
14024 emit_insn (gen_riscv_clmul_si (a0, a0, t0));
14025
14026 rtx num_shift = gen_int_mode (GET_MODE_BITSIZE (word_mode) - data_size,
14027 word_mode);
14028 riscv_expand_op (ASHIFT, word_mode, a0, a0, num_shift);
14029
14030 if (TARGET_64BIT)
14031 emit_insn (gen_riscv_clmulh_di (a0, a0, t1));
14032 else
14033 emit_insn (gen_riscv_clmulh_si (a0, a0, t1));
14034
14035 if (crc_size > data_size)
14036 {
14037 rtx data_size_shift = gen_int_mode (data_size, word_mode);
14038 rtx crc_part = gen_reg_rtx (word_mode);
14039 riscv_expand_op (LSHIFTRT, word_mode, crc_part, crc, data_size_shift);
14040 riscv_expand_op (XOR, word_mode, a0, a0, crc_part);
14041 }
14042
14043 riscv_emit_move (operands[0], gen_lowpart (crc_mode, a0));
14044 }
14045
14046 bool is_zicfiss_p ()
14047 {
14048 if (TARGET_ZICFISS && (flag_cf_protection & CF_RETURN))
14049 return true;
14050
14051 return false;
14052 }
14053
14054 bool is_zicfilp_p ()
14055 {
14056 if (TARGET_ZICFILP && (flag_cf_protection & CF_BRANCH))
14057 return true;
14058
14059 return false;
14060 }
14061
14062 bool need_shadow_stack_push_pop_p ()
14063 {
14064 return is_zicfiss_p () && riscv_save_return_addr_reg_p ();
14065 }
14066
14067 /* Initialize the GCC target structure. */
14068 #undef TARGET_ASM_ALIGNED_HI_OP
14069 #define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
14070 #undef TARGET_ASM_ALIGNED_SI_OP
14071 #define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
14072 #undef TARGET_ASM_ALIGNED_DI_OP
14073 #define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"
14074
14075 #undef TARGET_OPTION_OVERRIDE
14076 #define TARGET_OPTION_OVERRIDE riscv_option_override
14077
14078 #undef TARGET_OPTION_RESTORE
14079 #define TARGET_OPTION_RESTORE riscv_option_restore
14080
14081 #undef TARGET_OPTION_VALID_ATTRIBUTE_P
14082 #define TARGET_OPTION_VALID_ATTRIBUTE_P riscv_option_valid_attribute_p
14083
14084 #undef TARGET_LEGITIMIZE_ADDRESS
14085 #define TARGET_LEGITIMIZE_ADDRESS riscv_legitimize_address
14086
14087 #undef TARGET_SCHED_ISSUE_RATE
14088 #define TARGET_SCHED_ISSUE_RATE riscv_issue_rate
14089 #undef TARGET_SCHED_MACRO_FUSION_P
14090 #define TARGET_SCHED_MACRO_FUSION_P riscv_macro_fusion_p
14091 #undef TARGET_SCHED_MACRO_FUSION_PAIR_P
14092 #define TARGET_SCHED_MACRO_FUSION_PAIR_P riscv_macro_fusion_pair_p
14093
14094 #undef TARGET_SCHED_VARIABLE_ISSUE
14095 #define TARGET_SCHED_VARIABLE_ISSUE riscv_sched_variable_issue
14096
14097 #undef TARGET_SCHED_ADJUST_COST
14098 #define TARGET_SCHED_ADJUST_COST riscv_sched_adjust_cost
14099
14100 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
14101 #define TARGET_FUNCTION_OK_FOR_SIBCALL riscv_function_ok_for_sibcall
14102
14103 #undef TARGET_SET_CURRENT_FUNCTION
14104 #define TARGET_SET_CURRENT_FUNCTION riscv_set_current_function
14105
14106 #undef TARGET_REGISTER_MOVE_COST
14107 #define TARGET_REGISTER_MOVE_COST riscv_register_move_cost
14108 #undef TARGET_MEMORY_MOVE_COST
14109 #define TARGET_MEMORY_MOVE_COST riscv_memory_move_cost
14110 #undef TARGET_RTX_COSTS
14111 #define TARGET_RTX_COSTS riscv_rtx_costs
14112 #undef TARGET_ADDRESS_COST
14113 #define TARGET_ADDRESS_COST riscv_address_cost
14114 #undef TARGET_INSN_COST
14115 #define TARGET_INSN_COST riscv_insn_cost
14116
14117 #undef TARGET_MAX_NOCE_IFCVT_SEQ_COST
14118 #define TARGET_MAX_NOCE_IFCVT_SEQ_COST riscv_max_noce_ifcvt_seq_cost
14119 #undef TARGET_NOCE_CONVERSION_PROFITABLE_P
14120 #define TARGET_NOCE_CONVERSION_PROFITABLE_P riscv_noce_conversion_profitable_p
14121
14122 #undef TARGET_ASM_FILE_START
14123 #define TARGET_ASM_FILE_START riscv_file_start
14124 #undef TARGET_ASM_FILE_START_FILE_DIRECTIVE
14125 #define TARGET_ASM_FILE_START_FILE_DIRECTIVE true
14126 #undef TARGET_ASM_FILE_END
14127 #define TARGET_ASM_FILE_END riscv_file_end
14128
14129 #undef TARGET_EXPAND_BUILTIN_VA_START
14130 #define TARGET_EXPAND_BUILTIN_VA_START riscv_va_start
14131
14132 #undef TARGET_PROMOTE_FUNCTION_MODE
14133 #define TARGET_PROMOTE_FUNCTION_MODE riscv_promote_function_mode
14134
14135 #undef TARGET_RETURN_IN_MEMORY
14136 #define TARGET_RETURN_IN_MEMORY riscv_return_in_memory
14137
14138 #undef TARGET_ASM_OUTPUT_MI_THUNK
14139 #define TARGET_ASM_OUTPUT_MI_THUNK riscv_output_mi_thunk
14140 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
14141 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
14142
14143 #undef TARGET_PRINT_OPERAND
14144 #define TARGET_PRINT_OPERAND riscv_print_operand
14145 #undef TARGET_PRINT_OPERAND_ADDRESS
14146 #define TARGET_PRINT_OPERAND_ADDRESS riscv_print_operand_address
14147 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
14148 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P riscv_print_operand_punct_valid_p
14149
14150 #undef TARGET_SETUP_INCOMING_VARARGS
14151 #define TARGET_SETUP_INCOMING_VARARGS riscv_setup_incoming_varargs
14152 #undef TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
14153 #define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS riscv_allocate_stack_slots_for_args
14154 #undef TARGET_STRICT_ARGUMENT_NAMING
14155 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
14156 #undef TARGET_MUST_PASS_IN_STACK
14157 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
14158 #undef TARGET_PASS_BY_REFERENCE
14159 #define TARGET_PASS_BY_REFERENCE riscv_pass_by_reference
14160 #undef TARGET_ARG_PARTIAL_BYTES
14161 #define TARGET_ARG_PARTIAL_BYTES riscv_arg_partial_bytes
14162 #undef TARGET_FUNCTION_ARG
14163 #define TARGET_FUNCTION_ARG riscv_function_arg
14164 #undef TARGET_FUNCTION_ARG_ADVANCE
14165 #define TARGET_FUNCTION_ARG_ADVANCE riscv_function_arg_advance
14166 #undef TARGET_FUNCTION_ARG_BOUNDARY
14167 #define TARGET_FUNCTION_ARG_BOUNDARY riscv_function_arg_boundary
14168 #undef TARGET_FNTYPE_ABI
14169 #define TARGET_FNTYPE_ABI riscv_fntype_abi
14170 #undef TARGET_INSN_CALLEE_ABI
14171 #define TARGET_INSN_CALLEE_ABI riscv_insn_callee_abi
14172
14173 #undef TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS
14174 #define TARGET_SHRINK_WRAP_GET_SEPARATE_COMPONENTS \
14175 riscv_get_separate_components
14176
14177 #undef TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB
14178 #define TARGET_SHRINK_WRAP_COMPONENTS_FOR_BB \
14179 riscv_components_for_bb
14180
14181 #undef TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS
14182 #define TARGET_SHRINK_WRAP_DISQUALIFY_COMPONENTS \
14183 riscv_disqualify_components
14184
14185 #undef TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS
14186 #define TARGET_SHRINK_WRAP_EMIT_PROLOGUE_COMPONENTS \
14187 riscv_emit_prologue_components
14188
14189 #undef TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS
14190 #define TARGET_SHRINK_WRAP_EMIT_EPILOGUE_COMPONENTS \
14191 riscv_emit_epilogue_components
14192
14193 #undef TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS
14194 #define TARGET_SHRINK_WRAP_SET_HANDLED_COMPONENTS \
14195 riscv_set_handled_components
14196
14197 /* The generic ELF target does not always have TLS support. */
14198 #ifdef HAVE_AS_TLS
14199 #undef TARGET_HAVE_TLS
14200 #define TARGET_HAVE_TLS true
14201 #endif
14202
14203 #undef TARGET_CANNOT_FORCE_CONST_MEM
14204 #define TARGET_CANNOT_FORCE_CONST_MEM riscv_cannot_force_const_mem
14205
14206 #undef TARGET_LEGITIMATE_CONSTANT_P
14207 #define TARGET_LEGITIMATE_CONSTANT_P riscv_legitimate_constant_p
14208
14209 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
14210 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P riscv_use_blocks_for_constant_p
14211
14212 #undef TARGET_LEGITIMATE_ADDRESS_P
14213 #define TARGET_LEGITIMATE_ADDRESS_P riscv_legitimate_address_p
14214
14215 #undef TARGET_CAN_INLINE_P
14216 #define TARGET_CAN_INLINE_P riscv_can_inline_p
14217
14218 #undef TARGET_CAN_ELIMINATE
14219 #define TARGET_CAN_ELIMINATE riscv_can_eliminate
14220
14221 #undef TARGET_CONDITIONAL_REGISTER_USAGE
14222 #define TARGET_CONDITIONAL_REGISTER_USAGE riscv_conditional_register_usage
14223
14224 #undef TARGET_CLASS_MAX_NREGS
14225 #define TARGET_CLASS_MAX_NREGS riscv_class_max_nregs
14226
14227 #undef TARGET_TRAMPOLINE_INIT
14228 #define TARGET_TRAMPOLINE_INIT riscv_trampoline_init
14229
14230 #undef TARGET_IN_SMALL_DATA_P
14231 #define TARGET_IN_SMALL_DATA_P riscv_in_small_data_p
14232
14233 #undef TARGET_HAVE_SRODATA_SECTION
14234 #define TARGET_HAVE_SRODATA_SECTION true
14235
14236 #undef TARGET_ASM_SELECT_SECTION
14237 #define TARGET_ASM_SELECT_SECTION riscv_select_section
14238
14239 #undef TARGET_ASM_UNIQUE_SECTION
14240 #define TARGET_ASM_UNIQUE_SECTION riscv_unique_section
14241
14242 #undef TARGET_ASM_SELECT_RTX_SECTION
14243 #define TARGET_ASM_SELECT_RTX_SECTION riscv_elf_select_rtx_section
14244
14245 #undef TARGET_MIN_ANCHOR_OFFSET
14246 #define TARGET_MIN_ANCHOR_OFFSET (-IMM_REACH/2)
14247
14248 #undef TARGET_MAX_ANCHOR_OFFSET
14249 #define TARGET_MAX_ANCHOR_OFFSET (IMM_REACH/2-1)
14250
14251 #undef TARGET_REGISTER_PRIORITY
14252 #define TARGET_REGISTER_PRIORITY riscv_register_priority
14253
14254 #undef TARGET_CANNOT_COPY_INSN_P
14255 #define TARGET_CANNOT_COPY_INSN_P riscv_cannot_copy_insn_p
14256
14257 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
14258 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV riscv_atomic_assign_expand_fenv
14259
14260 #undef TARGET_INIT_BUILTINS
14261 #define TARGET_INIT_BUILTINS riscv_init_builtins
14262
14263 #undef TARGET_BUILTIN_DECL
14264 #define TARGET_BUILTIN_DECL riscv_builtin_decl
14265
14266 #undef TARGET_GIMPLE_FOLD_BUILTIN
14267 #define TARGET_GIMPLE_FOLD_BUILTIN riscv_gimple_fold_builtin
14268
14269 #undef TARGET_EXPAND_BUILTIN
14270 #define TARGET_EXPAND_BUILTIN riscv_expand_builtin
14271
14272 #undef TARGET_HARD_REGNO_NREGS
14273 #define TARGET_HARD_REGNO_NREGS riscv_hard_regno_nregs
14274 #undef TARGET_HARD_REGNO_MODE_OK
14275 #define TARGET_HARD_REGNO_MODE_OK riscv_hard_regno_mode_ok
14276
14277 #undef TARGET_MODES_TIEABLE_P
14278 #define TARGET_MODES_TIEABLE_P riscv_modes_tieable_p
14279
14280 #undef TARGET_SLOW_UNALIGNED_ACCESS
14281 #define TARGET_SLOW_UNALIGNED_ACCESS riscv_slow_unaligned_access
14282
14283 #undef TARGET_OVERLAP_OP_BY_PIECES_P
14284 #define TARGET_OVERLAP_OP_BY_PIECES_P riscv_overlap_op_by_pieces
14285
14286 #undef TARGET_SECONDARY_MEMORY_NEEDED
14287 #define TARGET_SECONDARY_MEMORY_NEEDED riscv_secondary_memory_needed
14288
14289 #undef TARGET_CAN_CHANGE_MODE_CLASS
14290 #define TARGET_CAN_CHANGE_MODE_CLASS riscv_can_change_mode_class
14291
14292 #undef TARGET_CONSTANT_ALIGNMENT
14293 #define TARGET_CONSTANT_ALIGNMENT riscv_constant_alignment
14294
14295 #undef TARGET_MERGE_DECL_ATTRIBUTES
14296 #define TARGET_MERGE_DECL_ATTRIBUTES riscv_merge_decl_attributes
14297
14298 #undef TARGET_ATTRIBUTE_TABLE
14299 #define TARGET_ATTRIBUTE_TABLE riscv_attribute_table
14300
14301 #undef TARGET_WARN_FUNC_RETURN
14302 #define TARGET_WARN_FUNC_RETURN riscv_warn_func_return
14303
14304 /* The low bit is ignored by jump instructions so is safe to use. */
14305 #undef TARGET_CUSTOM_FUNCTION_DESCRIPTORS
14306 #define TARGET_CUSTOM_FUNCTION_DESCRIPTORS 1
14307
14308 #undef TARGET_MACHINE_DEPENDENT_REORG
14309 #define TARGET_MACHINE_DEPENDENT_REORG riscv_reorg
14310
14311 #undef TARGET_NEW_ADDRESS_PROFITABLE_P
14312 #define TARGET_NEW_ADDRESS_PROFITABLE_P riscv_new_address_profitable_p
14313
14314 #undef TARGET_MANGLE_TYPE
14315 #define TARGET_MANGLE_TYPE riscv_mangle_type
14316
14317 #undef TARGET_SCALAR_MODE_SUPPORTED_P
14318 #define TARGET_SCALAR_MODE_SUPPORTED_P riscv_scalar_mode_supported_p
14319
14320 #undef TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P
14321 #define TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P \
14322 riscv_libgcc_floating_mode_supported_p
14323
14324 #undef TARGET_INIT_LIBFUNCS
14325 #define TARGET_INIT_LIBFUNCS riscv_init_libfuncs
14326
14327 #undef TARGET_C_EXCESS_PRECISION
14328 #define TARGET_C_EXCESS_PRECISION riscv_excess_precision
14329
14330 #undef TARGET_FLOATN_MODE
14331 #define TARGET_FLOATN_MODE riscv_floatn_mode
14332
14333 #undef TARGET_ASAN_SHADOW_OFFSET
14334 #define TARGET_ASAN_SHADOW_OFFSET riscv_asan_shadow_offset
14335
14336 #undef TARGET_ASAN_DYNAMIC_SHADOW_OFFSET_P
14337 #define TARGET_ASAN_DYNAMIC_SHADOW_OFFSET_P riscv_asan_dynamic_shadow_offset_p
14338
14339 #ifdef TARGET_BIG_ENDIAN_DEFAULT
14340 #undef TARGET_DEFAULT_TARGET_FLAGS
14341 #define TARGET_DEFAULT_TARGET_FLAGS (MASK_BIG_ENDIAN)
14342 #endif
14343
14344 #undef TARGET_VECTOR_MODE_SUPPORTED_P
14345 #define TARGET_VECTOR_MODE_SUPPORTED_P riscv_vector_mode_supported_p
14346
14347 #undef TARGET_VERIFY_TYPE_CONTEXT
14348 #define TARGET_VERIFY_TYPE_CONTEXT riscv_verify_type_context
14349
14350 #undef TARGET_ESTIMATED_POLY_VALUE
14351 #define TARGET_ESTIMATED_POLY_VALUE riscv_estimated_poly_value
14352
14353 #undef TARGET_VECTORIZE_GET_MASK_MODE
14354 #define TARGET_VECTORIZE_GET_MASK_MODE riscv_get_mask_mode
14355
14356 #undef TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE
14357 #define TARGET_VECTORIZE_EMPTY_MASK_IS_EXPENSIVE riscv_empty_mask_is_expensive
14358
14359 #undef TARGET_VECTOR_ALIGNMENT
14360 #define TARGET_VECTOR_ALIGNMENT riscv_vector_alignment
14361
14362 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
14363 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT riscv_support_vector_misalignment
14364
14365 #undef TARGET_DWARF_POLY_INDETERMINATE_VALUE
14366 #define TARGET_DWARF_POLY_INDETERMINATE_VALUE riscv_dwarf_poly_indeterminate_value
14367
14368 #undef TARGET_ZERO_CALL_USED_REGS
14369 #define TARGET_ZERO_CALL_USED_REGS riscv_zero_call_used_regs
14370
14371 #undef TARGET_ARRAY_MODE
14372 #define TARGET_ARRAY_MODE riscv_array_mode
14373
14374 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
14375 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE riscv_preferred_simd_mode
14376
14377 #undef TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT
14378 #define TARGET_VECTORIZE_PREFERRED_VECTOR_ALIGNMENT \
14379 riscv_vectorize_preferred_vector_alignment
14380
14381 #undef TARGET_STACK_CLASH_PROTECTION_ALLOCA_PROBE_RANGE
14382 #define TARGET_STACK_CLASH_PROTECTION_ALLOCA_PROBE_RANGE \
14383 riscv_stack_clash_protection_alloca_probe_range
14384
14385 /* Mode switching hooks. */
14386
14387 #undef TARGET_MODE_EMIT
14388 #define TARGET_MODE_EMIT riscv_emit_mode_set
14389 #undef TARGET_MODE_NEEDED
14390 #define TARGET_MODE_NEEDED riscv_mode_needed
14391 #undef TARGET_MODE_AFTER
14392 #define TARGET_MODE_AFTER riscv_mode_after
14393 #undef TARGET_MODE_ENTRY
14394 #define TARGET_MODE_ENTRY riscv_mode_entry
14395 #undef TARGET_MODE_EXIT
14396 #define TARGET_MODE_EXIT riscv_mode_exit
14397 #undef TARGET_MODE_PRIORITY
14398 #define TARGET_MODE_PRIORITY riscv_mode_priority
14399
14400 #undef TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_MODES
14401 #define TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_MODES \
14402 riscv_autovectorize_vector_modes
14403
14404 #undef TARGET_VECTORIZE_RELATED_MODE
14405 #define TARGET_VECTORIZE_RELATED_MODE riscv_vectorize_related_mode
14406
14407 #undef TARGET_VECTORIZE_VEC_PERM_CONST
14408 #define TARGET_VECTORIZE_VEC_PERM_CONST riscv_vectorize_vec_perm_const
14409
14410 #undef TARGET_FRAME_POINTER_REQUIRED
14411 #define TARGET_FRAME_POINTER_REQUIRED riscv_frame_pointer_required
14412
14413 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST
14414 #define TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST \
14415 riscv_builtin_vectorization_cost
14416
14417 #undef TARGET_VECTORIZE_CREATE_COSTS
14418 #define TARGET_VECTORIZE_CREATE_COSTS riscv_vectorize_create_costs
14419
14420 #undef TARGET_PREFERRED_ELSE_VALUE
14421 #define TARGET_PREFERRED_ELSE_VALUE riscv_preferred_else_value
14422
14423 #undef TARGET_VECTOR_MODE_SUPPORTED_ANY_TARGET_P
14424 #define TARGET_VECTOR_MODE_SUPPORTED_ANY_TARGET_P riscv_vector_mode_supported_any_target_p
14425
14426 #undef TARGET_FUNCTION_VALUE_REGNO_P
14427 #define TARGET_FUNCTION_VALUE_REGNO_P riscv_function_value_regno_p
14428
14429 #undef TARGET_GET_RAW_RESULT_MODE
14430 #define TARGET_GET_RAW_RESULT_MODE riscv_get_raw_result_mode
14431
14432 #undef TARGET_C_MODE_FOR_FLOATING_TYPE
14433 #define TARGET_C_MODE_FOR_FLOATING_TYPE riscv_c_mode_for_floating_type
14434
14435 #undef TARGET_USE_BY_PIECES_INFRASTRUCTURE_P
14436 #define TARGET_USE_BY_PIECES_INFRASTRUCTURE_P riscv_use_by_pieces_infrastructure_p
14437
14438 #undef TARGET_OPTION_VALID_VERSION_ATTRIBUTE_P
14439 #define TARGET_OPTION_VALID_VERSION_ATTRIBUTE_P \
14440 riscv_option_valid_version_attribute_p
14441
14442 #undef TARGET_COMPARE_VERSION_PRIORITY
14443 #define TARGET_COMPARE_VERSION_PRIORITY riscv_compare_version_priority
14444
14445 #undef TARGET_OPTION_FUNCTION_VERSIONS
14446 #define TARGET_OPTION_FUNCTION_VERSIONS riscv_common_function_versions
14447
14448 #undef TARGET_MANGLE_DECL_ASSEMBLER_NAME
14449 #define TARGET_MANGLE_DECL_ASSEMBLER_NAME riscv_mangle_decl_assembler_name
14450
14451 #undef TARGET_GENERATE_VERSION_DISPATCHER_BODY
14452 #define TARGET_GENERATE_VERSION_DISPATCHER_BODY \
14453 riscv_generate_version_dispatcher_body
14454
14455 #undef TARGET_GET_FUNCTION_VERSIONS_DISPATCHER
14456 #define TARGET_GET_FUNCTION_VERSIONS_DISPATCHER \
14457 riscv_get_function_versions_dispatcher
14458
14459 #undef TARGET_DOCUMENTATION_NAME
14460 #define TARGET_DOCUMENTATION_NAME "RISC-V"
14461
14462 struct gcc_target targetm = TARGET_INITIALIZER;
14463
14464 #include "gt-riscv.h"