OSDN Git Service

3aff8e7ff9315b265e6ce6163b47187729e952cb
[pf3gnuchains/gcc-fork.git] / gcc / config / arm / arm.c
1 /* Output routines for GCC for ARM.
2    Copyright (C) 1991, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3    2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Contributed by Pieter `Tiggr' Schoenmakers (rcpieter@win.tue.nl)
6    and Martin Simmons (@harleqn.co.uk).
7    More major hacks by Richard Earnshaw (rearnsha@arm.com).
8
9    This file is part of GCC.
10
11    GCC is free software; you can redistribute it and/or modify it
12    under the terms of the GNU General Public License as published
13    by the Free Software Foundation; either version 3, or (at your
14    option) any later version.
15
16    GCC is distributed in the hope that it will be useful, but WITHOUT
17    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19    License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with GCC; see the file COPYING3.  If not see
23    <http://www.gnu.org/licenses/>.  */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tm.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "obstack.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "real.h"
35 #include "insn-config.h"
36 #include "conditions.h"
37 #include "output.h"
38 #include "insn-attr.h"
39 #include "flags.h"
40 #include "reload.h"
41 #include "function.h"
42 #include "expr.h"
43 #include "optabs.h"
44 #include "toplev.h"
45 #include "recog.h"
46 #include "cgraph.h"
47 #include "ggc.h"
48 #include "except.h"
49 #include "c-pragma.h"
50 #include "integrate.h"
51 #include "tm_p.h"
52 #include "target.h"
53 #include "target-def.h"
54 #include "debug.h"
55 #include "langhooks.h"
56 #include "df.h"
57 #include "intl.h"
58 #include "libfuncs.h"
59
60 /* Forward definitions of types.  */
61 typedef struct minipool_node    Mnode;
62 typedef struct minipool_fixup   Mfix;
63
64 void (*arm_lang_output_object_attributes_hook)(void);
65
66 /* Forward function declarations.  */
67 static int arm_compute_static_chain_stack_bytes (void);
68 static arm_stack_offsets *arm_get_frame_offsets (void);
69 static void arm_add_gc_roots (void);
70 static int arm_gen_constant (enum rtx_code, enum machine_mode, rtx,
71                              HOST_WIDE_INT, rtx, rtx, int, int);
72 static unsigned bit_count (unsigned long);
73 static int arm_address_register_rtx_p (rtx, int);
74 static int arm_legitimate_index_p (enum machine_mode, rtx, RTX_CODE, int);
75 static int thumb2_legitimate_index_p (enum machine_mode, rtx, int);
76 static int thumb1_base_register_rtx_p (rtx, enum machine_mode, int);
77 static rtx arm_legitimize_address (rtx, rtx, enum machine_mode);
78 static rtx thumb_legitimize_address (rtx, rtx, enum machine_mode);
79 inline static int thumb1_index_register_rtx_p (rtx, int);
80 static bool arm_legitimate_address_p (enum machine_mode, rtx, bool);
81 static int thumb_far_jump_used_p (void);
82 static bool thumb_force_lr_save (void);
83 static int const_ok_for_op (HOST_WIDE_INT, enum rtx_code);
84 static rtx emit_sfm (int, int);
85 static unsigned arm_size_return_regs (void);
86 static bool arm_assemble_integer (rtx, unsigned int, int);
87 static const char *fp_const_from_val (REAL_VALUE_TYPE *);
88 static arm_cc get_arm_condition_code (rtx);
89 static HOST_WIDE_INT int_log2 (HOST_WIDE_INT);
90 static rtx is_jump_table (rtx);
91 static const char *output_multi_immediate (rtx *, const char *, const char *,
92                                            int, HOST_WIDE_INT);
93 static const char *shift_op (rtx, HOST_WIDE_INT *);
94 static struct machine_function *arm_init_machine_status (void);
95 static void thumb_exit (FILE *, int);
96 static rtx is_jump_table (rtx);
97 static HOST_WIDE_INT get_jump_table_size (rtx);
98 static Mnode *move_minipool_fix_forward_ref (Mnode *, Mnode *, HOST_WIDE_INT);
99 static Mnode *add_minipool_forward_ref (Mfix *);
100 static Mnode *move_minipool_fix_backward_ref (Mnode *, Mnode *, HOST_WIDE_INT);
101 static Mnode *add_minipool_backward_ref (Mfix *);
102 static void assign_minipool_offsets (Mfix *);
103 static void arm_print_value (FILE *, rtx);
104 static void dump_minipool (rtx);
105 static int arm_barrier_cost (rtx);
106 static Mfix *create_fix_barrier (Mfix *, HOST_WIDE_INT);
107 static void push_minipool_barrier (rtx, HOST_WIDE_INT);
108 static void push_minipool_fix (rtx, HOST_WIDE_INT, rtx *, enum machine_mode,
109                                rtx);
110 static void arm_reorg (void);
111 static bool note_invalid_constants (rtx, HOST_WIDE_INT, int);
112 static unsigned long arm_compute_save_reg0_reg12_mask (void);
113 static unsigned long arm_compute_save_reg_mask (void);
114 static unsigned long arm_isr_value (tree);
115 static unsigned long arm_compute_func_type (void);
116 static tree arm_handle_fndecl_attribute (tree *, tree, tree, int, bool *);
117 static tree arm_handle_pcs_attribute (tree *, tree, tree, int, bool *);
118 static tree arm_handle_isr_attribute (tree *, tree, tree, int, bool *);
119 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
120 static tree arm_handle_notshared_attribute (tree *, tree, tree, int, bool *);
121 #endif
122 static void arm_output_function_epilogue (FILE *, HOST_WIDE_INT);
123 static void arm_output_function_prologue (FILE *, HOST_WIDE_INT);
124 static void thumb1_output_function_prologue (FILE *, HOST_WIDE_INT);
125 static int arm_comp_type_attributes (const_tree, const_tree);
126 static void arm_set_default_type_attributes (tree);
127 static int arm_adjust_cost (rtx, rtx, rtx, int);
128 static int count_insns_for_constant (HOST_WIDE_INT, int);
129 static int arm_get_strip_length (int);
130 static bool arm_function_ok_for_sibcall (tree, tree);
131 static enum machine_mode arm_promote_function_mode (const_tree,
132                                                     enum machine_mode, int *,
133                                                     const_tree, int);
134 static bool arm_return_in_memory (const_tree, const_tree);
135 static rtx arm_function_value (const_tree, const_tree, bool);
136 static rtx arm_libcall_value (enum machine_mode, const_rtx);
137
138 static void arm_internal_label (FILE *, const char *, unsigned long);
139 static void arm_output_mi_thunk (FILE *, tree, HOST_WIDE_INT, HOST_WIDE_INT,
140                                  tree);
141 static bool arm_rtx_costs_1 (rtx, enum rtx_code, int*, bool);
142 static bool arm_size_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *);
143 static bool arm_slowmul_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
144 static bool arm_fastmul_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
145 static bool arm_xscale_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
146 static bool arm_9e_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
147 static bool arm_rtx_costs (rtx, int, int, int *, bool);
148 static int arm_address_cost (rtx, bool);
149 static bool arm_memory_load_p (rtx);
150 static bool arm_cirrus_insn_p (rtx);
151 static void cirrus_reorg (rtx);
152 static void arm_init_builtins (void);
153 static rtx arm_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
154 static void arm_init_iwmmxt_builtins (void);
155 static rtx safe_vector_operand (rtx, enum machine_mode);
156 static rtx arm_expand_binop_builtin (enum insn_code, tree, rtx);
157 static rtx arm_expand_unop_builtin (enum insn_code, tree, rtx, int);
158 static rtx arm_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
159 static void emit_constant_insn (rtx cond, rtx pattern);
160 static rtx emit_set_insn (rtx, rtx);
161 static int arm_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
162                                   tree, bool);
163 static rtx aapcs_allocate_return_reg (enum machine_mode, const_tree,
164                                       const_tree);
165 static int aapcs_select_return_coproc (const_tree, const_tree);
166
167 #ifdef OBJECT_FORMAT_ELF
168 static void arm_elf_asm_constructor (rtx, int) ATTRIBUTE_UNUSED;
169 static void arm_elf_asm_destructor (rtx, int) ATTRIBUTE_UNUSED;
170 #endif
171 #ifndef ARM_PE
172 static void arm_encode_section_info (tree, rtx, int);
173 #endif
174
175 static void arm_file_end (void);
176 static void arm_file_start (void);
177
178 static void arm_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
179                                         tree, int *, int);
180 static bool arm_pass_by_reference (CUMULATIVE_ARGS *,
181                                    enum machine_mode, const_tree, bool);
182 static bool arm_promote_prototypes (const_tree);
183 static bool arm_default_short_enums (void);
184 static bool arm_align_anon_bitfield (void);
185 static bool arm_return_in_msb (const_tree);
186 static bool arm_must_pass_in_stack (enum machine_mode, const_tree);
187 static bool arm_return_in_memory (const_tree, const_tree);
188 #ifdef TARGET_UNWIND_INFO
189 static void arm_unwind_emit (FILE *, rtx);
190 static bool arm_output_ttype (rtx);
191 #endif
192 static void arm_dwarf_handle_frame_unspec (const char *, rtx, int);
193
194 static tree arm_cxx_guard_type (void);
195 static bool arm_cxx_guard_mask_bit (void);
196 static tree arm_get_cookie_size (tree);
197 static bool arm_cookie_has_size (void);
198 static bool arm_cxx_cdtor_returns_this (void);
199 static bool arm_cxx_key_method_may_be_inline (void);
200 static void arm_cxx_determine_class_data_visibility (tree);
201 static bool arm_cxx_class_data_always_comdat (void);
202 static bool arm_cxx_use_aeabi_atexit (void);
203 static void arm_init_libfuncs (void);
204 static tree arm_build_builtin_va_list (void);
205 static void arm_expand_builtin_va_start (tree, rtx);
206 static tree arm_gimplify_va_arg_expr (tree, tree, gimple_seq *, gimple_seq *);
207 static bool arm_handle_option (size_t, const char *, int);
208 static void arm_target_help (void);
209 static unsigned HOST_WIDE_INT arm_shift_truncation_mask (enum machine_mode);
210 static bool arm_cannot_copy_insn_p (rtx);
211 static bool arm_tls_symbol_p (rtx x);
212 static int arm_issue_rate (void);
213 static void arm_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
214 static bool arm_allocate_stack_slots_for_args (void);
215 static const char *arm_invalid_parameter_type (const_tree t);
216 static const char *arm_invalid_return_type (const_tree t);
217 static tree arm_promoted_type (const_tree t);
218 static tree arm_convert_to_type (tree type, tree expr);
219 static bool arm_scalar_mode_supported_p (enum machine_mode);
220 static bool arm_frame_pointer_required (void);
221 static bool arm_can_eliminate (const int, const int);
222 static void arm_asm_trampoline_template (FILE *);
223 static void arm_trampoline_init (rtx, tree, rtx);
224 static rtx arm_trampoline_adjust_address (rtx);
225
226 \f
227 /* Table of machine attributes.  */
228 static const struct attribute_spec arm_attribute_table[] =
229 {
230   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
231   /* Function calls made to this symbol must be done indirectly, because
232      it may lie outside of the 26 bit addressing range of a normal function
233      call.  */
234   { "long_call",    0, 0, false, true,  true,  NULL },
235   /* Whereas these functions are always known to reside within the 26 bit
236      addressing range.  */
237   { "short_call",   0, 0, false, true,  true,  NULL },
238   /* Specify the procedure call conventions for a function.  */
239   { "pcs",          1, 1, false, true,  true,  arm_handle_pcs_attribute },
240   /* Interrupt Service Routines have special prologue and epilogue requirements.  */
241   { "isr",          0, 1, false, false, false, arm_handle_isr_attribute },
242   { "interrupt",    0, 1, false, false, false, arm_handle_isr_attribute },
243   { "naked",        0, 0, true,  false, false, arm_handle_fndecl_attribute },
244 #ifdef ARM_PE
245   /* ARM/PE has three new attributes:
246      interfacearm - ?
247      dllexport - for exporting a function/variable that will live in a dll
248      dllimport - for importing a function/variable from a dll
249
250      Microsoft allows multiple declspecs in one __declspec, separating
251      them with spaces.  We do NOT support this.  Instead, use __declspec
252      multiple times.
253   */
254   { "dllimport",    0, 0, true,  false, false, NULL },
255   { "dllexport",    0, 0, true,  false, false, NULL },
256   { "interfacearm", 0, 0, true,  false, false, arm_handle_fndecl_attribute },
257 #elif TARGET_DLLIMPORT_DECL_ATTRIBUTES
258   { "dllimport",    0, 0, false, false, false, handle_dll_attribute },
259   { "dllexport",    0, 0, false, false, false, handle_dll_attribute },
260   { "notshared",    0, 0, false, true, false, arm_handle_notshared_attribute },
261 #endif
262   { NULL,           0, 0, false, false, false, NULL }
263 };
264 \f
265 /* Initialize the GCC target structure.  */
266 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
267 #undef  TARGET_MERGE_DECL_ATTRIBUTES
268 #define TARGET_MERGE_DECL_ATTRIBUTES merge_dllimport_decl_attributes
269 #endif
270
271 #undef TARGET_LEGITIMIZE_ADDRESS
272 #define TARGET_LEGITIMIZE_ADDRESS arm_legitimize_address
273
274 #undef  TARGET_ATTRIBUTE_TABLE
275 #define TARGET_ATTRIBUTE_TABLE arm_attribute_table
276
277 #undef TARGET_ASM_FILE_START
278 #define TARGET_ASM_FILE_START arm_file_start
279 #undef TARGET_ASM_FILE_END
280 #define TARGET_ASM_FILE_END arm_file_end
281
282 #undef  TARGET_ASM_ALIGNED_SI_OP
283 #define TARGET_ASM_ALIGNED_SI_OP NULL
284 #undef  TARGET_ASM_INTEGER
285 #define TARGET_ASM_INTEGER arm_assemble_integer
286
287 #undef  TARGET_ASM_FUNCTION_PROLOGUE
288 #define TARGET_ASM_FUNCTION_PROLOGUE arm_output_function_prologue
289
290 #undef  TARGET_ASM_FUNCTION_EPILOGUE
291 #define TARGET_ASM_FUNCTION_EPILOGUE arm_output_function_epilogue
292
293 #undef  TARGET_DEFAULT_TARGET_FLAGS
294 #define TARGET_DEFAULT_TARGET_FLAGS (TARGET_DEFAULT | MASK_SCHED_PROLOG)
295 #undef  TARGET_HANDLE_OPTION
296 #define TARGET_HANDLE_OPTION arm_handle_option
297 #undef  TARGET_HELP
298 #define TARGET_HELP arm_target_help
299
300 #undef  TARGET_COMP_TYPE_ATTRIBUTES
301 #define TARGET_COMP_TYPE_ATTRIBUTES arm_comp_type_attributes
302
303 #undef  TARGET_SET_DEFAULT_TYPE_ATTRIBUTES
304 #define TARGET_SET_DEFAULT_TYPE_ATTRIBUTES arm_set_default_type_attributes
305
306 #undef  TARGET_SCHED_ADJUST_COST
307 #define TARGET_SCHED_ADJUST_COST arm_adjust_cost
308
309 #undef TARGET_ENCODE_SECTION_INFO
310 #ifdef ARM_PE
311 #define TARGET_ENCODE_SECTION_INFO  arm_pe_encode_section_info
312 #else
313 #define TARGET_ENCODE_SECTION_INFO  arm_encode_section_info
314 #endif
315
316 #undef  TARGET_STRIP_NAME_ENCODING
317 #define TARGET_STRIP_NAME_ENCODING arm_strip_name_encoding
318
319 #undef  TARGET_ASM_INTERNAL_LABEL
320 #define TARGET_ASM_INTERNAL_LABEL arm_internal_label
321
322 #undef  TARGET_FUNCTION_OK_FOR_SIBCALL
323 #define TARGET_FUNCTION_OK_FOR_SIBCALL arm_function_ok_for_sibcall
324
325 #undef  TARGET_FUNCTION_VALUE
326 #define TARGET_FUNCTION_VALUE arm_function_value
327
328 #undef  TARGET_LIBCALL_VALUE
329 #define TARGET_LIBCALL_VALUE arm_libcall_value
330
331 #undef  TARGET_ASM_OUTPUT_MI_THUNK
332 #define TARGET_ASM_OUTPUT_MI_THUNK arm_output_mi_thunk
333 #undef  TARGET_ASM_CAN_OUTPUT_MI_THUNK
334 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK default_can_output_mi_thunk_no_vcall
335
336 #undef  TARGET_RTX_COSTS
337 #define TARGET_RTX_COSTS arm_rtx_costs
338 #undef  TARGET_ADDRESS_COST
339 #define TARGET_ADDRESS_COST arm_address_cost
340
341 #undef TARGET_SHIFT_TRUNCATION_MASK
342 #define TARGET_SHIFT_TRUNCATION_MASK arm_shift_truncation_mask
343 #undef TARGET_VECTOR_MODE_SUPPORTED_P
344 #define TARGET_VECTOR_MODE_SUPPORTED_P arm_vector_mode_supported_p
345
346 #undef  TARGET_MACHINE_DEPENDENT_REORG
347 #define TARGET_MACHINE_DEPENDENT_REORG arm_reorg
348
349 #undef  TARGET_INIT_BUILTINS
350 #define TARGET_INIT_BUILTINS  arm_init_builtins
351 #undef  TARGET_EXPAND_BUILTIN
352 #define TARGET_EXPAND_BUILTIN arm_expand_builtin
353
354 #undef TARGET_INIT_LIBFUNCS
355 #define TARGET_INIT_LIBFUNCS arm_init_libfuncs
356
357 #undef TARGET_PROMOTE_FUNCTION_MODE
358 #define TARGET_PROMOTE_FUNCTION_MODE arm_promote_function_mode
359 #undef TARGET_PROMOTE_PROTOTYPES
360 #define TARGET_PROMOTE_PROTOTYPES arm_promote_prototypes
361 #undef TARGET_PASS_BY_REFERENCE
362 #define TARGET_PASS_BY_REFERENCE arm_pass_by_reference
363 #undef TARGET_ARG_PARTIAL_BYTES
364 #define TARGET_ARG_PARTIAL_BYTES arm_arg_partial_bytes
365
366 #undef  TARGET_SETUP_INCOMING_VARARGS
367 #define TARGET_SETUP_INCOMING_VARARGS arm_setup_incoming_varargs
368
369 #undef TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
370 #define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS arm_allocate_stack_slots_for_args
371
372 #undef TARGET_ASM_TRAMPOLINE_TEMPLATE
373 #define TARGET_ASM_TRAMPOLINE_TEMPLATE arm_asm_trampoline_template
374 #undef TARGET_TRAMPOLINE_INIT
375 #define TARGET_TRAMPOLINE_INIT arm_trampoline_init
376 #undef TARGET_TRAMPOLINE_ADJUST_ADDRESS
377 #define TARGET_TRAMPOLINE_ADJUST_ADDRESS arm_trampoline_adjust_address
378
379 #undef TARGET_DEFAULT_SHORT_ENUMS
380 #define TARGET_DEFAULT_SHORT_ENUMS arm_default_short_enums
381
382 #undef TARGET_ALIGN_ANON_BITFIELD
383 #define TARGET_ALIGN_ANON_BITFIELD arm_align_anon_bitfield
384
385 #undef TARGET_NARROW_VOLATILE_BITFIELD
386 #define TARGET_NARROW_VOLATILE_BITFIELD hook_bool_void_false
387
388 #undef TARGET_CXX_GUARD_TYPE
389 #define TARGET_CXX_GUARD_TYPE arm_cxx_guard_type
390
391 #undef TARGET_CXX_GUARD_MASK_BIT
392 #define TARGET_CXX_GUARD_MASK_BIT arm_cxx_guard_mask_bit
393
394 #undef TARGET_CXX_GET_COOKIE_SIZE
395 #define TARGET_CXX_GET_COOKIE_SIZE arm_get_cookie_size
396
397 #undef TARGET_CXX_COOKIE_HAS_SIZE
398 #define TARGET_CXX_COOKIE_HAS_SIZE arm_cookie_has_size
399
400 #undef TARGET_CXX_CDTOR_RETURNS_THIS
401 #define TARGET_CXX_CDTOR_RETURNS_THIS arm_cxx_cdtor_returns_this
402
403 #undef TARGET_CXX_KEY_METHOD_MAY_BE_INLINE
404 #define TARGET_CXX_KEY_METHOD_MAY_BE_INLINE arm_cxx_key_method_may_be_inline
405
406 #undef TARGET_CXX_USE_AEABI_ATEXIT
407 #define TARGET_CXX_USE_AEABI_ATEXIT arm_cxx_use_aeabi_atexit
408
409 #undef TARGET_CXX_DETERMINE_CLASS_DATA_VISIBILITY
410 #define TARGET_CXX_DETERMINE_CLASS_DATA_VISIBILITY \
411   arm_cxx_determine_class_data_visibility
412
413 #undef TARGET_CXX_CLASS_DATA_ALWAYS_COMDAT
414 #define TARGET_CXX_CLASS_DATA_ALWAYS_COMDAT arm_cxx_class_data_always_comdat
415
416 #undef TARGET_RETURN_IN_MSB
417 #define TARGET_RETURN_IN_MSB arm_return_in_msb
418
419 #undef TARGET_RETURN_IN_MEMORY
420 #define TARGET_RETURN_IN_MEMORY arm_return_in_memory
421
422 #undef TARGET_MUST_PASS_IN_STACK
423 #define TARGET_MUST_PASS_IN_STACK arm_must_pass_in_stack
424
425 #ifdef TARGET_UNWIND_INFO
426 #undef TARGET_UNWIND_EMIT
427 #define TARGET_UNWIND_EMIT arm_unwind_emit
428
429 /* EABI unwinding tables use a different format for the typeinfo tables.  */
430 #undef TARGET_ASM_TTYPE
431 #define TARGET_ASM_TTYPE arm_output_ttype
432
433 #undef TARGET_ARM_EABI_UNWINDER
434 #define TARGET_ARM_EABI_UNWINDER true
435 #endif /* TARGET_UNWIND_INFO */
436
437 #undef TARGET_DWARF_HANDLE_FRAME_UNSPEC
438 #define TARGET_DWARF_HANDLE_FRAME_UNSPEC arm_dwarf_handle_frame_unspec
439
440 #undef  TARGET_CANNOT_COPY_INSN_P
441 #define TARGET_CANNOT_COPY_INSN_P arm_cannot_copy_insn_p
442
443 #ifdef HAVE_AS_TLS
444 #undef TARGET_HAVE_TLS
445 #define TARGET_HAVE_TLS true
446 #endif
447
448 #undef TARGET_CANNOT_FORCE_CONST_MEM
449 #define TARGET_CANNOT_FORCE_CONST_MEM arm_cannot_force_const_mem
450
451 #undef TARGET_MAX_ANCHOR_OFFSET
452 #define TARGET_MAX_ANCHOR_OFFSET 4095
453
454 /* The minimum is set such that the total size of the block
455    for a particular anchor is -4088 + 1 + 4095 bytes, which is
456    divisible by eight, ensuring natural spacing of anchors.  */
457 #undef TARGET_MIN_ANCHOR_OFFSET
458 #define TARGET_MIN_ANCHOR_OFFSET -4088
459
460 #undef TARGET_SCHED_ISSUE_RATE
461 #define TARGET_SCHED_ISSUE_RATE arm_issue_rate
462
463 #undef TARGET_MANGLE_TYPE
464 #define TARGET_MANGLE_TYPE arm_mangle_type
465
466 #undef TARGET_BUILD_BUILTIN_VA_LIST
467 #define TARGET_BUILD_BUILTIN_VA_LIST arm_build_builtin_va_list
468 #undef TARGET_EXPAND_BUILTIN_VA_START
469 #define TARGET_EXPAND_BUILTIN_VA_START arm_expand_builtin_va_start
470 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
471 #define TARGET_GIMPLIFY_VA_ARG_EXPR arm_gimplify_va_arg_expr
472
473 #ifdef HAVE_AS_TLS
474 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
475 #define TARGET_ASM_OUTPUT_DWARF_DTPREL arm_output_dwarf_dtprel
476 #endif
477
478 #undef TARGET_LEGITIMATE_ADDRESS_P
479 #define TARGET_LEGITIMATE_ADDRESS_P     arm_legitimate_address_p
480
481 #undef TARGET_INVALID_PARAMETER_TYPE
482 #define TARGET_INVALID_PARAMETER_TYPE arm_invalid_parameter_type
483
484 #undef TARGET_INVALID_RETURN_TYPE
485 #define TARGET_INVALID_RETURN_TYPE arm_invalid_return_type
486
487 #undef TARGET_PROMOTED_TYPE
488 #define TARGET_PROMOTED_TYPE arm_promoted_type
489
490 #undef TARGET_CONVERT_TO_TYPE
491 #define TARGET_CONVERT_TO_TYPE arm_convert_to_type
492
493 #undef TARGET_SCALAR_MODE_SUPPORTED_P
494 #define TARGET_SCALAR_MODE_SUPPORTED_P arm_scalar_mode_supported_p
495
496 #undef TARGET_FRAME_POINTER_REQUIRED
497 #define TARGET_FRAME_POINTER_REQUIRED arm_frame_pointer_required
498
499 #undef TARGET_CAN_ELIMINATE
500 #define TARGET_CAN_ELIMINATE arm_can_eliminate
501
502 struct gcc_target targetm = TARGET_INITIALIZER;
503 \f
504 /* Obstack for minipool constant handling.  */
505 static struct obstack minipool_obstack;
506 static char *         minipool_startobj;
507
508 /* The maximum number of insns skipped which
509    will be conditionalised if possible.  */
510 static int max_insns_skipped = 5;
511
512 extern FILE * asm_out_file;
513
514 /* True if we are currently building a constant table.  */
515 int making_const_table;
516
517 /* The processor for which instructions should be scheduled.  */
518 enum processor_type arm_tune = arm_none;
519
520 /* The default processor used if not overridden by commandline.  */
521 static enum processor_type arm_default_cpu = arm_none;
522
523 /* Which floating point model to use.  */
524 enum arm_fp_model arm_fp_model;
525
526 /* Which floating point hardware is available.  */
527 enum fputype arm_fpu_arch;
528
529 /* Which floating point hardware to schedule for.  */
530 enum fputype arm_fpu_tune;
531
532 /* Whether to use floating point hardware.  */
533 enum float_abi_type arm_float_abi;
534
535 /* Which __fp16 format to use.  */
536 enum arm_fp16_format_type arm_fp16_format;
537
538 /* Which ABI to use.  */
539 enum arm_abi_type arm_abi;
540
541 /* Which thread pointer model to use.  */
542 enum arm_tp_type target_thread_pointer = TP_AUTO;
543
544 /* Used to parse -mstructure_size_boundary command line option.  */
545 int    arm_structure_size_boundary = DEFAULT_STRUCTURE_SIZE_BOUNDARY;
546
547 /* Used for Thumb call_via trampolines.  */
548 rtx thumb_call_via_label[14];
549 static int thumb_call_reg_needed;
550
551 /* Bit values used to identify processor capabilities.  */
552 #define FL_CO_PROC    (1 << 0)        /* Has external co-processor bus */
553 #define FL_ARCH3M     (1 << 1)        /* Extended multiply */
554 #define FL_MODE26     (1 << 2)        /* 26-bit mode support */
555 #define FL_MODE32     (1 << 3)        /* 32-bit mode support */
556 #define FL_ARCH4      (1 << 4)        /* Architecture rel 4 */
557 #define FL_ARCH5      (1 << 5)        /* Architecture rel 5 */
558 #define FL_THUMB      (1 << 6)        /* Thumb aware */
559 #define FL_LDSCHED    (1 << 7)        /* Load scheduling necessary */
560 #define FL_STRONG     (1 << 8)        /* StrongARM */
561 #define FL_ARCH5E     (1 << 9)        /* DSP extensions to v5 */
562 #define FL_XSCALE     (1 << 10)       /* XScale */
563 #define FL_CIRRUS     (1 << 11)       /* Cirrus/DSP.  */
564 #define FL_ARCH6      (1 << 12)       /* Architecture rel 6.  Adds
565                                          media instructions.  */
566 #define FL_VFPV2      (1 << 13)       /* Vector Floating Point V2.  */
567 #define FL_WBUF       (1 << 14)       /* Schedule for write buffer ops.
568                                          Note: ARM6 & 7 derivatives only.  */
569 #define FL_ARCH6K     (1 << 15)       /* Architecture rel 6 K extensions.  */
570 #define FL_THUMB2     (1 << 16)       /* Thumb-2.  */
571 #define FL_NOTM       (1 << 17)       /* Instructions not present in the 'M'
572                                          profile.  */
573 #define FL_DIV        (1 << 18)       /* Hardware divide.  */
574 #define FL_VFPV3      (1 << 19)       /* Vector Floating Point V3.  */
575 #define FL_NEON       (1 << 20)       /* Neon instructions.  */
576
577 #define FL_IWMMXT     (1 << 29)       /* XScale v2 or "Intel Wireless MMX technology".  */
578
579 #define FL_FOR_ARCH2    FL_NOTM
580 #define FL_FOR_ARCH3    (FL_FOR_ARCH2 | FL_MODE32)
581 #define FL_FOR_ARCH3M   (FL_FOR_ARCH3 | FL_ARCH3M)
582 #define FL_FOR_ARCH4    (FL_FOR_ARCH3M | FL_ARCH4)
583 #define FL_FOR_ARCH4T   (FL_FOR_ARCH4 | FL_THUMB)
584 #define FL_FOR_ARCH5    (FL_FOR_ARCH4 | FL_ARCH5)
585 #define FL_FOR_ARCH5T   (FL_FOR_ARCH5 | FL_THUMB)
586 #define FL_FOR_ARCH5E   (FL_FOR_ARCH5 | FL_ARCH5E)
587 #define FL_FOR_ARCH5TE  (FL_FOR_ARCH5E | FL_THUMB)
588 #define FL_FOR_ARCH5TEJ FL_FOR_ARCH5TE
589 #define FL_FOR_ARCH6    (FL_FOR_ARCH5TE | FL_ARCH6)
590 #define FL_FOR_ARCH6J   FL_FOR_ARCH6
591 #define FL_FOR_ARCH6K   (FL_FOR_ARCH6 | FL_ARCH6K)
592 #define FL_FOR_ARCH6Z   FL_FOR_ARCH6
593 #define FL_FOR_ARCH6ZK  FL_FOR_ARCH6K
594 #define FL_FOR_ARCH6T2  (FL_FOR_ARCH6 | FL_THUMB2)
595 #define FL_FOR_ARCH6M   (FL_FOR_ARCH6 & ~FL_NOTM)
596 #define FL_FOR_ARCH7    (FL_FOR_ARCH6T2 &~ FL_NOTM)
597 #define FL_FOR_ARCH7A   (FL_FOR_ARCH7 | FL_NOTM)
598 #define FL_FOR_ARCH7R   (FL_FOR_ARCH7A | FL_DIV)
599 #define FL_FOR_ARCH7M   (FL_FOR_ARCH7 | FL_DIV)
600
601 /* The bits in this mask specify which
602    instructions we are allowed to generate.  */
603 static unsigned long insn_flags = 0;
604
605 /* The bits in this mask specify which instruction scheduling options should
606    be used.  */
607 static unsigned long tune_flags = 0;
608
609 /* The following are used in the arm.md file as equivalents to bits
610    in the above two flag variables.  */
611
612 /* Nonzero if this chip supports the ARM Architecture 3M extensions.  */
613 int arm_arch3m = 0;
614
615 /* Nonzero if this chip supports the ARM Architecture 4 extensions.  */
616 int arm_arch4 = 0;
617
618 /* Nonzero if this chip supports the ARM Architecture 4t extensions.  */
619 int arm_arch4t = 0;
620
621 /* Nonzero if this chip supports the ARM Architecture 5 extensions.  */
622 int arm_arch5 = 0;
623
624 /* Nonzero if this chip supports the ARM Architecture 5E extensions.  */
625 int arm_arch5e = 0;
626
627 /* Nonzero if this chip supports the ARM Architecture 6 extensions.  */
628 int arm_arch6 = 0;
629
630 /* Nonzero if this chip supports the ARM 6K extensions.  */
631 int arm_arch6k = 0;
632
633 /* Nonzero if instructions not present in the 'M' profile can be used.  */
634 int arm_arch_notm = 0;
635
636 /* Nonzero if this chip can benefit from load scheduling.  */
637 int arm_ld_sched = 0;
638
639 /* Nonzero if this chip is a StrongARM.  */
640 int arm_tune_strongarm = 0;
641
642 /* Nonzero if this chip is a Cirrus variant.  */
643 int arm_arch_cirrus = 0;
644
645 /* Nonzero if this chip supports Intel Wireless MMX technology.  */
646 int arm_arch_iwmmxt = 0;
647
648 /* Nonzero if this chip is an XScale.  */
649 int arm_arch_xscale = 0;
650
651 /* Nonzero if tuning for XScale  */
652 int arm_tune_xscale = 0;
653
654 /* Nonzero if we want to tune for stores that access the write-buffer.
655    This typically means an ARM6 or ARM7 with MMU or MPU.  */
656 int arm_tune_wbuf = 0;
657
658 /* Nonzero if tuning for Cortex-A9.  */
659 int arm_tune_cortex_a9 = 0;
660
661 /* Nonzero if generating Thumb instructions.  */
662 int thumb_code = 0;
663
664 /* Nonzero if we should define __THUMB_INTERWORK__ in the
665    preprocessor.
666    XXX This is a bit of a hack, it's intended to help work around
667    problems in GLD which doesn't understand that armv5t code is
668    interworking clean.  */
669 int arm_cpp_interwork = 0;
670
671 /* Nonzero if chip supports Thumb 2.  */
672 int arm_arch_thumb2;
673
674 /* Nonzero if chip supports integer division instruction.  */
675 int arm_arch_hwdiv;
676
677 /* In case of a PRE_INC, POST_INC, PRE_DEC, POST_DEC memory reference, we
678    must report the mode of the memory reference from PRINT_OPERAND to
679    PRINT_OPERAND_ADDRESS.  */
680 enum machine_mode output_memory_reference_mode;
681
682 /* The register number to be used for the PIC offset register.  */
683 unsigned arm_pic_register = INVALID_REGNUM;
684
685 /* Set to 1 after arm_reorg has started.  Reset to start at the start of
686    the next function.  */
687 static int after_arm_reorg = 0;
688
689 /* The maximum number of insns to be used when loading a constant.  */
690 static int arm_constant_limit = 3;
691
692 static enum arm_pcs arm_pcs_default;
693
694 /* For an explanation of these variables, see final_prescan_insn below.  */
695 int arm_ccfsm_state;
696 /* arm_current_cc is also used for Thumb-2 cond_exec blocks.  */
697 enum arm_cond_code arm_current_cc;
698 rtx arm_target_insn;
699 int arm_target_label;
700 /* The number of conditionally executed insns, including the current insn.  */
701 int arm_condexec_count = 0;
702 /* A bitmask specifying the patterns for the IT block.
703    Zero means do not output an IT block before this insn. */
704 int arm_condexec_mask = 0;
705 /* The number of bits used in arm_condexec_mask.  */
706 int arm_condexec_masklen = 0;
707
708 /* The condition codes of the ARM, and the inverse function.  */
709 static const char * const arm_condition_codes[] =
710 {
711   "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
712   "hi", "ls", "ge", "lt", "gt", "le", "al", "nv"
713 };
714
715 #define ARM_LSL_NAME (TARGET_UNIFIED_ASM ? "lsl" : "asl")
716 #define streq(string1, string2) (strcmp (string1, string2) == 0)
717
718 #define THUMB2_WORK_REGS (0xff & ~(  (1 << THUMB_HARD_FRAME_POINTER_REGNUM) \
719                                    | (1 << SP_REGNUM) | (1 << PC_REGNUM) \
720                                    | (1 << PIC_OFFSET_TABLE_REGNUM)))
721 \f
722 /* Initialization code.  */
723
724 struct processors
725 {
726   const char *const name;
727   enum processor_type core;
728   const char *arch;
729   const unsigned long flags;
730   bool (* rtx_costs) (rtx, enum rtx_code, enum rtx_code, int *, bool);
731 };
732
733 /* Not all of these give usefully different compilation alternatives,
734    but there is no simple way of generalizing them.  */
735 static const struct processors all_cores[] =
736 {
737   /* ARM Cores */
738 #define ARM_CORE(NAME, IDENT, ARCH, FLAGS, COSTS) \
739   {NAME, arm_none, #ARCH, FLAGS | FL_FOR_ARCH##ARCH, arm_##COSTS##_rtx_costs},
740 #include "arm-cores.def"
741 #undef ARM_CORE
742   {NULL, arm_none, NULL, 0, NULL}
743 };
744
745 static const struct processors all_architectures[] =
746 {
747   /* ARM Architectures */
748   /* We don't specify rtx_costs here as it will be figured out
749      from the core.  */
750
751   {"armv2",   arm2,       "2",   FL_CO_PROC | FL_MODE26 | FL_FOR_ARCH2, NULL},
752   {"armv2a",  arm2,       "2",   FL_CO_PROC | FL_MODE26 | FL_FOR_ARCH2, NULL},
753   {"armv3",   arm6,       "3",   FL_CO_PROC | FL_MODE26 | FL_FOR_ARCH3, NULL},
754   {"armv3m",  arm7m,      "3M",  FL_CO_PROC | FL_MODE26 | FL_FOR_ARCH3M, NULL},
755   {"armv4",   arm7tdmi,   "4",   FL_CO_PROC | FL_MODE26 | FL_FOR_ARCH4, NULL},
756   /* Strictly, FL_MODE26 is a permitted option for v4t, but there are no
757      implementations that support it, so we will leave it out for now.  */
758   {"armv4t",  arm7tdmi,   "4T",  FL_CO_PROC |             FL_FOR_ARCH4T, NULL},
759   {"armv5",   arm10tdmi,  "5",   FL_CO_PROC |             FL_FOR_ARCH5, NULL},
760   {"armv5t",  arm10tdmi,  "5T",  FL_CO_PROC |             FL_FOR_ARCH5T, NULL},
761   {"armv5e",  arm1026ejs, "5E",  FL_CO_PROC |             FL_FOR_ARCH5E, NULL},
762   {"armv5te", arm1026ejs, "5TE", FL_CO_PROC |             FL_FOR_ARCH5TE, NULL},
763   {"armv6",   arm1136js,  "6",   FL_CO_PROC |             FL_FOR_ARCH6, NULL},
764   {"armv6j",  arm1136js,  "6J",  FL_CO_PROC |             FL_FOR_ARCH6J, NULL},
765   {"armv6k",  mpcore,     "6K",  FL_CO_PROC |             FL_FOR_ARCH6K, NULL},
766   {"armv6z",  arm1176jzs, "6Z",  FL_CO_PROC |             FL_FOR_ARCH6Z, NULL},
767   {"armv6zk", arm1176jzs, "6ZK", FL_CO_PROC |             FL_FOR_ARCH6ZK, NULL},
768   {"armv6t2", arm1156t2s, "6T2", FL_CO_PROC |             FL_FOR_ARCH6T2, NULL},
769   {"armv6-m", cortexm1,   "6M",                           FL_FOR_ARCH6M, NULL},
770   {"armv7",   cortexa8,   "7",   FL_CO_PROC |             FL_FOR_ARCH7, NULL},
771   {"armv7-a", cortexa8,   "7A",  FL_CO_PROC |             FL_FOR_ARCH7A, NULL},
772   {"armv7-r", cortexr4,   "7R",  FL_CO_PROC |             FL_FOR_ARCH7R, NULL},
773   {"armv7-m", cortexm3,   "7M",  FL_CO_PROC |             FL_FOR_ARCH7M, NULL},
774   {"ep9312",  ep9312,     "4T",  FL_LDSCHED | FL_CIRRUS | FL_FOR_ARCH4, NULL},
775   {"iwmmxt",  iwmmxt,     "5TE", FL_LDSCHED | FL_STRONG | FL_FOR_ARCH5TE | FL_XSCALE | FL_IWMMXT , NULL},
776   {"iwmmxt2", iwmmxt2,     "5TE", FL_LDSCHED | FL_STRONG | FL_FOR_ARCH5TE | FL_XSCALE | FL_IWMMXT , NULL},
777   {NULL, arm_none, NULL, 0 , NULL}
778 };
779
780 struct arm_cpu_select
781 {
782   const char *              string;
783   const char *              name;
784   const struct processors * processors;
785 };
786
787 /* This is a magic structure.  The 'string' field is magically filled in
788    with a pointer to the value specified by the user on the command line
789    assuming that the user has specified such a value.  */
790
791 static struct arm_cpu_select arm_select[] =
792 {
793   /* string       name            processors  */
794   { NULL,       "-mcpu=",       all_cores  },
795   { NULL,       "-march=",      all_architectures },
796   { NULL,       "-mtune=",      all_cores }
797 };
798
799 /* Defines representing the indexes into the above table.  */
800 #define ARM_OPT_SET_CPU 0
801 #define ARM_OPT_SET_ARCH 1
802 #define ARM_OPT_SET_TUNE 2
803
804 /* The name of the preprocessor macro to define for this architecture.  */
805
806 char arm_arch_name[] = "__ARM_ARCH_0UNK__";
807
808 struct fpu_desc
809 {
810   const char * name;
811   enum fputype fpu;
812 };
813
814
815 /* Available values for -mfpu=.  */
816
817 static const struct fpu_desc all_fpus[] =
818 {
819   {"fpa",               FPUTYPE_FPA},
820   {"fpe2",              FPUTYPE_FPA_EMU2},
821   {"fpe3",              FPUTYPE_FPA_EMU2},
822   {"maverick",          FPUTYPE_MAVERICK},
823   {"vfp",               FPUTYPE_VFP},
824   {"vfp3",              FPUTYPE_VFP3},
825   {"vfpv3",             FPUTYPE_VFP3},
826   {"vfpv3-d16",         FPUTYPE_VFP3D16},
827   {"neon",              FPUTYPE_NEON},
828   {"neon-fp16",         FPUTYPE_NEON_FP16}
829 };
830
831
832 /* Floating point models used by the different hardware.
833    See fputype in arm.h.  */
834
835 static const enum arm_fp_model fp_model_for_fpu[] =
836 {
837   /* No FP hardware.  */
838   ARM_FP_MODEL_UNKNOWN,         /* FPUTYPE_NONE  */
839   ARM_FP_MODEL_FPA,             /* FPUTYPE_FPA  */
840   ARM_FP_MODEL_FPA,             /* FPUTYPE_FPA_EMU2  */
841   ARM_FP_MODEL_FPA,             /* FPUTYPE_FPA_EMU3  */
842   ARM_FP_MODEL_MAVERICK,        /* FPUTYPE_MAVERICK  */
843   ARM_FP_MODEL_VFP,             /* FPUTYPE_VFP  */
844   ARM_FP_MODEL_VFP,             /* FPUTYPE_VFP3D16  */
845   ARM_FP_MODEL_VFP,             /* FPUTYPE_VFP3  */
846   ARM_FP_MODEL_VFP,             /* FPUTYPE_NEON  */
847   ARM_FP_MODEL_VFP              /* FPUTYPE_NEON_FP16  */
848 };
849
850
851 struct float_abi
852 {
853   const char * name;
854   enum float_abi_type abi_type;
855 };
856
857
858 /* Available values for -mfloat-abi=.  */
859
860 static const struct float_abi all_float_abis[] =
861 {
862   {"soft",      ARM_FLOAT_ABI_SOFT},
863   {"softfp",    ARM_FLOAT_ABI_SOFTFP},
864   {"hard",      ARM_FLOAT_ABI_HARD}
865 };
866
867
868 struct fp16_format
869 {
870   const char *name;
871   enum arm_fp16_format_type fp16_format_type;
872 };
873
874
875 /* Available values for -mfp16-format=.  */
876
877 static const struct fp16_format all_fp16_formats[] =
878 {
879   {"none",              ARM_FP16_FORMAT_NONE},
880   {"ieee",              ARM_FP16_FORMAT_IEEE},
881   {"alternative",       ARM_FP16_FORMAT_ALTERNATIVE}
882 };
883
884
885 struct abi_name
886 {
887   const char *name;
888   enum arm_abi_type abi_type;
889 };
890
891
892 /* Available values for -mabi=.  */
893
894 static const struct abi_name arm_all_abis[] =
895 {
896   {"apcs-gnu",    ARM_ABI_APCS},
897   {"atpcs",   ARM_ABI_ATPCS},
898   {"aapcs",   ARM_ABI_AAPCS},
899   {"iwmmxt",  ARM_ABI_IWMMXT},
900   {"aapcs-linux",   ARM_ABI_AAPCS_LINUX}
901 };
902
903 /* Supported TLS relocations.  */
904
905 enum tls_reloc {
906   TLS_GD32,
907   TLS_LDM32,
908   TLS_LDO32,
909   TLS_IE32,
910   TLS_LE32
911 };
912
913 /* Emit an insn that's a simple single-set.  Both the operands must be known
914    to be valid.  */
915 inline static rtx
916 emit_set_insn (rtx x, rtx y)
917 {
918   return emit_insn (gen_rtx_SET (VOIDmode, x, y));
919 }
920
921 /* Return the number of bits set in VALUE.  */
922 static unsigned
923 bit_count (unsigned long value)
924 {
925   unsigned long count = 0;
926
927   while (value)
928     {
929       count++;
930       value &= value - 1;  /* Clear the least-significant set bit.  */
931     }
932
933   return count;
934 }
935
936 /* Set up library functions unique to ARM.  */
937
938 static void
939 arm_init_libfuncs (void)
940 {
941   /* There are no special library functions unless we are using the
942      ARM BPABI.  */
943   if (!TARGET_BPABI)
944     return;
945
946   /* The functions below are described in Section 4 of the "Run-Time
947      ABI for the ARM architecture", Version 1.0.  */
948
949   /* Double-precision floating-point arithmetic.  Table 2.  */
950   set_optab_libfunc (add_optab, DFmode, "__aeabi_dadd");
951   set_optab_libfunc (sdiv_optab, DFmode, "__aeabi_ddiv");
952   set_optab_libfunc (smul_optab, DFmode, "__aeabi_dmul");
953   set_optab_libfunc (neg_optab, DFmode, "__aeabi_dneg");
954   set_optab_libfunc (sub_optab, DFmode, "__aeabi_dsub");
955
956   /* Double-precision comparisons.  Table 3.  */
957   set_optab_libfunc (eq_optab, DFmode, "__aeabi_dcmpeq");
958   set_optab_libfunc (ne_optab, DFmode, NULL);
959   set_optab_libfunc (lt_optab, DFmode, "__aeabi_dcmplt");
960   set_optab_libfunc (le_optab, DFmode, "__aeabi_dcmple");
961   set_optab_libfunc (ge_optab, DFmode, "__aeabi_dcmpge");
962   set_optab_libfunc (gt_optab, DFmode, "__aeabi_dcmpgt");
963   set_optab_libfunc (unord_optab, DFmode, "__aeabi_dcmpun");
964
965   /* Single-precision floating-point arithmetic.  Table 4.  */
966   set_optab_libfunc (add_optab, SFmode, "__aeabi_fadd");
967   set_optab_libfunc (sdiv_optab, SFmode, "__aeabi_fdiv");
968   set_optab_libfunc (smul_optab, SFmode, "__aeabi_fmul");
969   set_optab_libfunc (neg_optab, SFmode, "__aeabi_fneg");
970   set_optab_libfunc (sub_optab, SFmode, "__aeabi_fsub");
971
972   /* Single-precision comparisons.  Table 5.  */
973   set_optab_libfunc (eq_optab, SFmode, "__aeabi_fcmpeq");
974   set_optab_libfunc (ne_optab, SFmode, NULL);
975   set_optab_libfunc (lt_optab, SFmode, "__aeabi_fcmplt");
976   set_optab_libfunc (le_optab, SFmode, "__aeabi_fcmple");
977   set_optab_libfunc (ge_optab, SFmode, "__aeabi_fcmpge");
978   set_optab_libfunc (gt_optab, SFmode, "__aeabi_fcmpgt");
979   set_optab_libfunc (unord_optab, SFmode, "__aeabi_fcmpun");
980
981   /* Floating-point to integer conversions.  Table 6.  */
982   set_conv_libfunc (sfix_optab, SImode, DFmode, "__aeabi_d2iz");
983   set_conv_libfunc (ufix_optab, SImode, DFmode, "__aeabi_d2uiz");
984   set_conv_libfunc (sfix_optab, DImode, DFmode, "__aeabi_d2lz");
985   set_conv_libfunc (ufix_optab, DImode, DFmode, "__aeabi_d2ulz");
986   set_conv_libfunc (sfix_optab, SImode, SFmode, "__aeabi_f2iz");
987   set_conv_libfunc (ufix_optab, SImode, SFmode, "__aeabi_f2uiz");
988   set_conv_libfunc (sfix_optab, DImode, SFmode, "__aeabi_f2lz");
989   set_conv_libfunc (ufix_optab, DImode, SFmode, "__aeabi_f2ulz");
990
991   /* Conversions between floating types.  Table 7.  */
992   set_conv_libfunc (trunc_optab, SFmode, DFmode, "__aeabi_d2f");
993   set_conv_libfunc (sext_optab, DFmode, SFmode, "__aeabi_f2d");
994
995   /* Integer to floating-point conversions.  Table 8.  */
996   set_conv_libfunc (sfloat_optab, DFmode, SImode, "__aeabi_i2d");
997   set_conv_libfunc (ufloat_optab, DFmode, SImode, "__aeabi_ui2d");
998   set_conv_libfunc (sfloat_optab, DFmode, DImode, "__aeabi_l2d");
999   set_conv_libfunc (ufloat_optab, DFmode, DImode, "__aeabi_ul2d");
1000   set_conv_libfunc (sfloat_optab, SFmode, SImode, "__aeabi_i2f");
1001   set_conv_libfunc (ufloat_optab, SFmode, SImode, "__aeabi_ui2f");
1002   set_conv_libfunc (sfloat_optab, SFmode, DImode, "__aeabi_l2f");
1003   set_conv_libfunc (ufloat_optab, SFmode, DImode, "__aeabi_ul2f");
1004
1005   /* Long long.  Table 9.  */
1006   set_optab_libfunc (smul_optab, DImode, "__aeabi_lmul");
1007   set_optab_libfunc (sdivmod_optab, DImode, "__aeabi_ldivmod");
1008   set_optab_libfunc (udivmod_optab, DImode, "__aeabi_uldivmod");
1009   set_optab_libfunc (ashl_optab, DImode, "__aeabi_llsl");
1010   set_optab_libfunc (lshr_optab, DImode, "__aeabi_llsr");
1011   set_optab_libfunc (ashr_optab, DImode, "__aeabi_lasr");
1012   set_optab_libfunc (cmp_optab, DImode, "__aeabi_lcmp");
1013   set_optab_libfunc (ucmp_optab, DImode, "__aeabi_ulcmp");
1014
1015   /* Integer (32/32->32) division.  \S 4.3.1.  */
1016   set_optab_libfunc (sdivmod_optab, SImode, "__aeabi_idivmod");
1017   set_optab_libfunc (udivmod_optab, SImode, "__aeabi_uidivmod");
1018
1019   /* The divmod functions are designed so that they can be used for
1020      plain division, even though they return both the quotient and the
1021      remainder.  The quotient is returned in the usual location (i.e.,
1022      r0 for SImode, {r0, r1} for DImode), just as would be expected
1023      for an ordinary division routine.  Because the AAPCS calling
1024      conventions specify that all of { r0, r1, r2, r3 } are
1025      callee-saved registers, there is no need to tell the compiler
1026      explicitly that those registers are clobbered by these
1027      routines.  */
1028   set_optab_libfunc (sdiv_optab, DImode, "__aeabi_ldivmod");
1029   set_optab_libfunc (udiv_optab, DImode, "__aeabi_uldivmod");
1030
1031   /* For SImode division the ABI provides div-without-mod routines,
1032      which are faster.  */
1033   set_optab_libfunc (sdiv_optab, SImode, "__aeabi_idiv");
1034   set_optab_libfunc (udiv_optab, SImode, "__aeabi_uidiv");
1035
1036   /* We don't have mod libcalls.  Fortunately gcc knows how to use the
1037      divmod libcalls instead.  */
1038   set_optab_libfunc (smod_optab, DImode, NULL);
1039   set_optab_libfunc (umod_optab, DImode, NULL);
1040   set_optab_libfunc (smod_optab, SImode, NULL);
1041   set_optab_libfunc (umod_optab, SImode, NULL);
1042
1043   /* Half-precision float operations.  The compiler handles all operations
1044      with NULL libfuncs by converting the SFmode.  */
1045   switch (arm_fp16_format)
1046     {
1047     case ARM_FP16_FORMAT_IEEE:
1048     case ARM_FP16_FORMAT_ALTERNATIVE:
1049
1050       /* Conversions.  */
1051       set_conv_libfunc (trunc_optab, HFmode, SFmode,
1052                         (arm_fp16_format == ARM_FP16_FORMAT_IEEE
1053                          ? "__gnu_f2h_ieee"
1054                          : "__gnu_f2h_alternative"));
1055       set_conv_libfunc (sext_optab, SFmode, HFmode, 
1056                         (arm_fp16_format == ARM_FP16_FORMAT_IEEE
1057                          ? "__gnu_h2f_ieee"
1058                          : "__gnu_h2f_alternative"));
1059       
1060       /* Arithmetic.  */
1061       set_optab_libfunc (add_optab, HFmode, NULL);
1062       set_optab_libfunc (sdiv_optab, HFmode, NULL);
1063       set_optab_libfunc (smul_optab, HFmode, NULL);
1064       set_optab_libfunc (neg_optab, HFmode, NULL);
1065       set_optab_libfunc (sub_optab, HFmode, NULL);
1066
1067       /* Comparisons.  */
1068       set_optab_libfunc (eq_optab, HFmode, NULL);
1069       set_optab_libfunc (ne_optab, HFmode, NULL);
1070       set_optab_libfunc (lt_optab, HFmode, NULL);
1071       set_optab_libfunc (le_optab, HFmode, NULL);
1072       set_optab_libfunc (ge_optab, HFmode, NULL);
1073       set_optab_libfunc (gt_optab, HFmode, NULL);
1074       set_optab_libfunc (unord_optab, HFmode, NULL);
1075       break;
1076
1077     default:
1078       break;
1079     }
1080
1081   if (TARGET_AAPCS_BASED)
1082     synchronize_libfunc = init_one_libfunc ("__sync_synchronize");
1083 }
1084
1085 /* On AAPCS systems, this is the "struct __va_list".  */
1086 static GTY(()) tree va_list_type;
1087
1088 /* Return the type to use as __builtin_va_list.  */
1089 static tree
1090 arm_build_builtin_va_list (void)
1091 {
1092   tree va_list_name;
1093   tree ap_field;
1094   
1095   if (!TARGET_AAPCS_BASED)
1096     return std_build_builtin_va_list ();
1097
1098   /* AAPCS \S 7.1.4 requires that va_list be a typedef for a type
1099      defined as:
1100
1101        struct __va_list 
1102        {
1103          void *__ap;
1104        };
1105
1106      The C Library ABI further reinforces this definition in \S
1107      4.1.
1108
1109      We must follow this definition exactly.  The structure tag
1110      name is visible in C++ mangled names, and thus forms a part
1111      of the ABI.  The field name may be used by people who
1112      #include <stdarg.h>.  */
1113   /* Create the type.  */
1114   va_list_type = lang_hooks.types.make_type (RECORD_TYPE);
1115   /* Give it the required name.  */
1116   va_list_name = build_decl (BUILTINS_LOCATION,
1117                              TYPE_DECL,
1118                              get_identifier ("__va_list"),
1119                              va_list_type);
1120   DECL_ARTIFICIAL (va_list_name) = 1;
1121   TYPE_NAME (va_list_type) = va_list_name;
1122   /* Create the __ap field.  */
1123   ap_field = build_decl (BUILTINS_LOCATION,
1124                          FIELD_DECL, 
1125                          get_identifier ("__ap"),
1126                          ptr_type_node);
1127   DECL_ARTIFICIAL (ap_field) = 1;
1128   DECL_FIELD_CONTEXT (ap_field) = va_list_type;
1129   TYPE_FIELDS (va_list_type) = ap_field;
1130   /* Compute its layout.  */
1131   layout_type (va_list_type);
1132
1133   return va_list_type;
1134 }
1135
1136 /* Return an expression of type "void *" pointing to the next
1137    available argument in a variable-argument list.  VALIST is the
1138    user-level va_list object, of type __builtin_va_list.  */
1139 static tree
1140 arm_extract_valist_ptr (tree valist)
1141 {
1142   if (TREE_TYPE (valist) == error_mark_node)
1143     return error_mark_node;
1144
1145   /* On an AAPCS target, the pointer is stored within "struct
1146      va_list".  */
1147   if (TARGET_AAPCS_BASED)
1148     {
1149       tree ap_field = TYPE_FIELDS (TREE_TYPE (valist));
1150       valist = build3 (COMPONENT_REF, TREE_TYPE (ap_field), 
1151                        valist, ap_field, NULL_TREE);
1152     }
1153
1154   return valist;
1155 }
1156
1157 /* Implement TARGET_EXPAND_BUILTIN_VA_START.  */
1158 static void
1159 arm_expand_builtin_va_start (tree valist, rtx nextarg)
1160 {
1161   valist = arm_extract_valist_ptr (valist);
1162   std_expand_builtin_va_start (valist, nextarg);
1163 }
1164
1165 /* Implement TARGET_GIMPLIFY_VA_ARG_EXPR.  */
1166 static tree
1167 arm_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p, 
1168                           gimple_seq *post_p)
1169 {
1170   valist = arm_extract_valist_ptr (valist);
1171   return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
1172 }
1173
1174 /* Implement TARGET_HANDLE_OPTION.  */
1175
1176 static bool
1177 arm_handle_option (size_t code, const char *arg, int value ATTRIBUTE_UNUSED)
1178 {
1179   switch (code)
1180     {
1181     case OPT_march_:
1182       arm_select[1].string = arg;
1183       return true;
1184
1185     case OPT_mcpu_:
1186       arm_select[0].string = arg;
1187       return true;
1188
1189     case OPT_mhard_float:
1190       target_float_abi_name = "hard";
1191       return true;
1192
1193     case OPT_msoft_float:
1194       target_float_abi_name = "soft";
1195       return true;
1196
1197     case OPT_mtune_:
1198       arm_select[2].string = arg;
1199       return true;
1200
1201     default:
1202       return true;
1203     }
1204 }
1205
1206 static void
1207 arm_target_help (void)
1208 {
1209   int i;
1210   static int columns = 0;
1211   int remaining;
1212
1213   /* If we have not done so already, obtain the desired maximum width of
1214      the output.  Note - this is a duplication of the code at the start of
1215      gcc/opts.c:print_specific_help() - the two copies should probably be
1216      replaced by a single function.  */
1217   if (columns == 0)
1218     {
1219       const char *p;
1220
1221       GET_ENVIRONMENT (p, "COLUMNS");
1222       if (p != NULL)
1223         {
1224           int value = atoi (p);
1225
1226           if (value > 0)
1227             columns = value;
1228         }
1229
1230       if (columns == 0)
1231         /* Use a reasonable default.  */
1232         columns = 80;
1233     }
1234
1235   printf ("  Known ARM CPUs (for use with the -mcpu= and -mtune= options):\n");
1236
1237   /* The - 2 is because we know that the last entry in the array is NULL.  */
1238   i = ARRAY_SIZE (all_cores) - 2;
1239   gcc_assert (i > 0);
1240   printf ("    %s", all_cores[i].name);
1241   remaining = columns - (strlen (all_cores[i].name) + 4);
1242   gcc_assert (remaining >= 0);
1243
1244   while (i--)
1245     {
1246       int len = strlen (all_cores[i].name);
1247
1248       if (remaining > len + 2)
1249         {
1250           printf (", %s", all_cores[i].name);
1251           remaining -= len + 2;
1252         }
1253       else
1254         {
1255           if (remaining > 0)
1256             printf (",");
1257           printf ("\n    %s", all_cores[i].name);
1258           remaining = columns - (len + 4);
1259         }
1260     }
1261
1262   printf ("\n\n  Known ARM architectures (for use with the -march= option):\n");
1263
1264   i = ARRAY_SIZE (all_architectures) - 2;
1265   gcc_assert (i > 0);
1266   
1267   printf ("    %s", all_architectures[i].name);
1268   remaining = columns - (strlen (all_architectures[i].name) + 4);
1269   gcc_assert (remaining >= 0);
1270
1271   while (i--)
1272     {
1273       int len = strlen (all_architectures[i].name);
1274
1275       if (remaining > len + 2)
1276         {
1277           printf (", %s", all_architectures[i].name);
1278           remaining -= len + 2;
1279         }
1280       else
1281         {
1282           if (remaining > 0)
1283             printf (",");
1284           printf ("\n    %s", all_architectures[i].name);
1285           remaining = columns - (len + 4);
1286         }
1287     }
1288   printf ("\n");
1289
1290 }
1291
1292 /* Fix up any incompatible options that the user has specified.
1293    This has now turned into a maze.  */
1294 void
1295 arm_override_options (void)
1296 {
1297   unsigned i;
1298   enum processor_type target_arch_cpu = arm_none;
1299   enum processor_type selected_cpu = arm_none;
1300
1301   /* Set up the flags based on the cpu/architecture selected by the user.  */
1302   for (i = ARRAY_SIZE (arm_select); i--;)
1303     {
1304       struct arm_cpu_select * ptr = arm_select + i;
1305
1306       if (ptr->string != NULL && ptr->string[0] != '\0')
1307         {
1308           const struct processors * sel;
1309
1310           for (sel = ptr->processors; sel->name != NULL; sel++)
1311             if (streq (ptr->string, sel->name))
1312               {
1313                 /* Set the architecture define.  */
1314                 if (i != ARM_OPT_SET_TUNE)
1315                   sprintf (arm_arch_name, "__ARM_ARCH_%s__", sel->arch);
1316
1317                 /* Determine the processor core for which we should
1318                    tune code-generation.  */
1319                 if (/* -mcpu= is a sensible default.  */
1320                     i == ARM_OPT_SET_CPU
1321                     /* -mtune= overrides -mcpu= and -march=.  */
1322                     || i == ARM_OPT_SET_TUNE)
1323                   arm_tune = (enum processor_type) (sel - ptr->processors);
1324
1325                 /* Remember the CPU associated with this architecture.
1326                    If no other option is used to set the CPU type,
1327                    we'll use this to guess the most suitable tuning
1328                    options.  */
1329                 if (i == ARM_OPT_SET_ARCH)
1330                   target_arch_cpu = sel->core;
1331
1332                 if (i == ARM_OPT_SET_CPU)
1333                   selected_cpu = (enum processor_type) (sel - ptr->processors);
1334                   
1335                 if (i != ARM_OPT_SET_TUNE)
1336                   {
1337                     /* If we have been given an architecture and a processor
1338                        make sure that they are compatible.  We only generate
1339                        a warning though, and we prefer the CPU over the
1340                        architecture.  */
1341                     if (insn_flags != 0 && (insn_flags ^ sel->flags))
1342                       warning (0, "switch -mcpu=%s conflicts with -march= switch",
1343                                ptr->string);
1344
1345                     insn_flags = sel->flags;
1346                   }
1347
1348                 break;
1349               }
1350
1351           if (sel->name == NULL)
1352             error ("bad value (%s) for %s switch", ptr->string, ptr->name);
1353         }
1354     }
1355
1356   /* Guess the tuning options from the architecture if necessary.  */
1357   if (arm_tune == arm_none)
1358     arm_tune = target_arch_cpu;
1359
1360   /* If the user did not specify a processor, choose one for them.  */
1361   if (insn_flags == 0)
1362     {
1363       const struct processors * sel;
1364       unsigned int        sought;
1365
1366       selected_cpu = (enum processor_type) TARGET_CPU_DEFAULT;
1367       if (selected_cpu == arm_none)
1368         {
1369 #ifdef SUBTARGET_CPU_DEFAULT
1370           /* Use the subtarget default CPU if none was specified by
1371              configure.  */
1372           selected_cpu = (enum processor_type) SUBTARGET_CPU_DEFAULT;
1373 #endif
1374           /* Default to ARM6.  */
1375           if (selected_cpu == arm_none)
1376             selected_cpu = arm6;
1377         }
1378       sel = &all_cores[selected_cpu];
1379
1380       insn_flags = sel->flags;
1381
1382       /* Now check to see if the user has specified some command line
1383          switch that require certain abilities from the cpu.  */
1384       sought = 0;
1385
1386       if (TARGET_INTERWORK || TARGET_THUMB)
1387         {
1388           sought |= (FL_THUMB | FL_MODE32);
1389
1390           /* There are no ARM processors that support both APCS-26 and
1391              interworking.  Therefore we force FL_MODE26 to be removed
1392              from insn_flags here (if it was set), so that the search
1393              below will always be able to find a compatible processor.  */
1394           insn_flags &= ~FL_MODE26;
1395         }
1396
1397       if (sought != 0 && ((sought & insn_flags) != sought))
1398         {
1399           /* Try to locate a CPU type that supports all of the abilities
1400              of the default CPU, plus the extra abilities requested by
1401              the user.  */
1402           for (sel = all_cores; sel->name != NULL; sel++)
1403             if ((sel->flags & sought) == (sought | insn_flags))
1404               break;
1405
1406           if (sel->name == NULL)
1407             {
1408               unsigned current_bit_count = 0;
1409               const struct processors * best_fit = NULL;
1410
1411               /* Ideally we would like to issue an error message here
1412                  saying that it was not possible to find a CPU compatible
1413                  with the default CPU, but which also supports the command
1414                  line options specified by the programmer, and so they
1415                  ought to use the -mcpu=<name> command line option to
1416                  override the default CPU type.
1417
1418                  If we cannot find a cpu that has both the
1419                  characteristics of the default cpu and the given
1420                  command line options we scan the array again looking
1421                  for a best match.  */
1422               for (sel = all_cores; sel->name != NULL; sel++)
1423                 if ((sel->flags & sought) == sought)
1424                   {
1425                     unsigned count;
1426
1427                     count = bit_count (sel->flags & insn_flags);
1428
1429                     if (count >= current_bit_count)
1430                       {
1431                         best_fit = sel;
1432                         current_bit_count = count;
1433                       }
1434                   }
1435
1436               gcc_assert (best_fit);
1437               sel = best_fit;
1438             }
1439
1440           insn_flags = sel->flags;
1441         }
1442       sprintf (arm_arch_name, "__ARM_ARCH_%s__", sel->arch);
1443       arm_default_cpu = (enum processor_type) (sel - all_cores);
1444       if (arm_tune == arm_none)
1445         arm_tune = arm_default_cpu;
1446     }
1447
1448   /* The processor for which we should tune should now have been
1449      chosen.  */
1450   gcc_assert (arm_tune != arm_none);
1451
1452   tune_flags = all_cores[(int)arm_tune].flags;
1453
1454   if (target_fp16_format_name)
1455     {
1456       for (i = 0; i < ARRAY_SIZE (all_fp16_formats); i++)
1457         {
1458           if (streq (all_fp16_formats[i].name, target_fp16_format_name))
1459             {
1460               arm_fp16_format = all_fp16_formats[i].fp16_format_type;
1461               break;
1462             }
1463         }
1464       if (i == ARRAY_SIZE (all_fp16_formats))
1465         error ("invalid __fp16 format option: -mfp16-format=%s",
1466                target_fp16_format_name);
1467     }
1468   else
1469     arm_fp16_format = ARM_FP16_FORMAT_NONE;
1470
1471   if (target_abi_name)
1472     {
1473       for (i = 0; i < ARRAY_SIZE (arm_all_abis); i++)
1474         {
1475           if (streq (arm_all_abis[i].name, target_abi_name))
1476             {
1477               arm_abi = arm_all_abis[i].abi_type;
1478               break;
1479             }
1480         }
1481       if (i == ARRAY_SIZE (arm_all_abis))
1482         error ("invalid ABI option: -mabi=%s", target_abi_name);
1483     }
1484   else
1485     arm_abi = ARM_DEFAULT_ABI;
1486
1487   /* Make sure that the processor choice does not conflict with any of the
1488      other command line choices.  */
1489   if (TARGET_ARM && !(insn_flags & FL_NOTM))
1490     error ("target CPU does not support ARM mode");
1491
1492   /* BPABI targets use linker tricks to allow interworking on cores
1493      without thumb support.  */
1494   if (TARGET_INTERWORK && !((insn_flags & FL_THUMB) || TARGET_BPABI))
1495     {
1496       warning (0, "target CPU does not support interworking" );
1497       target_flags &= ~MASK_INTERWORK;
1498     }
1499
1500   if (TARGET_THUMB && !(insn_flags & FL_THUMB))
1501     {
1502       warning (0, "target CPU does not support THUMB instructions");
1503       target_flags &= ~MASK_THUMB;
1504     }
1505
1506   if (TARGET_APCS_FRAME && TARGET_THUMB)
1507     {
1508       /* warning (0, "ignoring -mapcs-frame because -mthumb was used"); */
1509       target_flags &= ~MASK_APCS_FRAME;
1510     }
1511
1512   /* Callee super interworking implies thumb interworking.  Adding
1513      this to the flags here simplifies the logic elsewhere.  */
1514   if (TARGET_THUMB && TARGET_CALLEE_INTERWORKING)
1515       target_flags |= MASK_INTERWORK;
1516
1517   /* TARGET_BACKTRACE calls leaf_function_p, which causes a crash if done
1518      from here where no function is being compiled currently.  */
1519   if ((TARGET_TPCS_FRAME || TARGET_TPCS_LEAF_FRAME) && TARGET_ARM)
1520     warning (0, "enabling backtrace support is only meaningful when compiling for the Thumb");
1521
1522   if (TARGET_ARM && TARGET_CALLEE_INTERWORKING)
1523     warning (0, "enabling callee interworking support is only meaningful when compiling for the Thumb");
1524
1525   if (TARGET_ARM && TARGET_CALLER_INTERWORKING)
1526     warning (0, "enabling caller interworking support is only meaningful when compiling for the Thumb");
1527
1528   if (TARGET_APCS_STACK && !TARGET_APCS_FRAME)
1529     {
1530       warning (0, "-mapcs-stack-check incompatible with -mno-apcs-frame");
1531       target_flags |= MASK_APCS_FRAME;
1532     }
1533
1534   if (TARGET_POKE_FUNCTION_NAME)
1535     target_flags |= MASK_APCS_FRAME;
1536
1537   if (TARGET_APCS_REENT && flag_pic)
1538     error ("-fpic and -mapcs-reent are incompatible");
1539
1540   if (TARGET_APCS_REENT)
1541     warning (0, "APCS reentrant code not supported.  Ignored");
1542
1543   /* If this target is normally configured to use APCS frames, warn if they
1544      are turned off and debugging is turned on.  */
1545   if (TARGET_ARM
1546       && write_symbols != NO_DEBUG
1547       && !TARGET_APCS_FRAME
1548       && (TARGET_DEFAULT & MASK_APCS_FRAME))
1549     warning (0, "-g with -mno-apcs-frame may not give sensible debugging");
1550
1551   if (TARGET_APCS_FLOAT)
1552     warning (0, "passing floating point arguments in fp regs not yet supported");
1553
1554   /* Initialize boolean versions of the flags, for use in the arm.md file.  */
1555   arm_arch3m = (insn_flags & FL_ARCH3M) != 0;
1556   arm_arch4 = (insn_flags & FL_ARCH4) != 0;
1557   arm_arch4t = arm_arch4 & ((insn_flags & FL_THUMB) != 0);
1558   arm_arch5 = (insn_flags & FL_ARCH5) != 0;
1559   arm_arch5e = (insn_flags & FL_ARCH5E) != 0;
1560   arm_arch6 = (insn_flags & FL_ARCH6) != 0;
1561   arm_arch6k = (insn_flags & FL_ARCH6K) != 0;
1562   arm_arch_notm = (insn_flags & FL_NOTM) != 0;
1563   arm_arch_thumb2 = (insn_flags & FL_THUMB2) != 0;
1564   arm_arch_xscale = (insn_flags & FL_XSCALE) != 0;
1565   arm_arch_cirrus = (insn_flags & FL_CIRRUS) != 0;
1566
1567   arm_ld_sched = (tune_flags & FL_LDSCHED) != 0;
1568   arm_tune_strongarm = (tune_flags & FL_STRONG) != 0;
1569   thumb_code = (TARGET_ARM == 0);
1570   arm_tune_wbuf = (tune_flags & FL_WBUF) != 0;
1571   arm_tune_xscale = (tune_flags & FL_XSCALE) != 0;
1572   arm_arch_iwmmxt = (insn_flags & FL_IWMMXT) != 0;
1573   arm_arch_hwdiv = (insn_flags & FL_DIV) != 0;
1574   arm_tune_cortex_a9 = (arm_tune == cortexa9) != 0;
1575
1576   /* If we are not using the default (ARM mode) section anchor offset
1577      ranges, then set the correct ranges now.  */
1578   if (TARGET_THUMB1)
1579     {
1580       /* Thumb-1 LDR instructions cannot have negative offsets.
1581          Permissible positive offset ranges are 5-bit (for byte loads),
1582          6-bit (for halfword loads), or 7-bit (for word loads).
1583          Empirical results suggest a 7-bit anchor range gives the best
1584          overall code size.  */
1585       targetm.min_anchor_offset = 0;
1586       targetm.max_anchor_offset = 127;
1587     }
1588   else if (TARGET_THUMB2)
1589     {
1590       /* The minimum is set such that the total size of the block
1591          for a particular anchor is 248 + 1 + 4095 bytes, which is
1592          divisible by eight, ensuring natural spacing of anchors.  */
1593       targetm.min_anchor_offset = -248;
1594       targetm.max_anchor_offset = 4095;
1595     }
1596
1597   /* V5 code we generate is completely interworking capable, so we turn off
1598      TARGET_INTERWORK here to avoid many tests later on.  */
1599
1600   /* XXX However, we must pass the right pre-processor defines to CPP
1601      or GLD can get confused.  This is a hack.  */
1602   if (TARGET_INTERWORK)
1603     arm_cpp_interwork = 1;
1604
1605   if (arm_arch5)
1606     target_flags &= ~MASK_INTERWORK;
1607
1608   if (TARGET_IWMMXT && !ARM_DOUBLEWORD_ALIGN)
1609     error ("iwmmxt requires an AAPCS compatible ABI for proper operation");
1610
1611   if (TARGET_IWMMXT_ABI && !TARGET_IWMMXT)
1612     error ("iwmmxt abi requires an iwmmxt capable cpu");
1613
1614   arm_fp_model = ARM_FP_MODEL_UNKNOWN;
1615   if (target_fpu_name == NULL && target_fpe_name != NULL)
1616     {
1617       if (streq (target_fpe_name, "2"))
1618         target_fpu_name = "fpe2";
1619       else if (streq (target_fpe_name, "3"))
1620         target_fpu_name = "fpe3";
1621       else
1622         error ("invalid floating point emulation option: -mfpe=%s",
1623                target_fpe_name);
1624     }
1625   if (target_fpu_name != NULL)
1626     {
1627       /* The user specified a FPU.  */
1628       for (i = 0; i < ARRAY_SIZE (all_fpus); i++)
1629         {
1630           if (streq (all_fpus[i].name, target_fpu_name))
1631             {
1632               arm_fpu_arch = all_fpus[i].fpu;
1633               arm_fpu_tune = arm_fpu_arch;
1634               arm_fp_model = fp_model_for_fpu[arm_fpu_arch];
1635               break;
1636             }
1637         }
1638       if (arm_fp_model == ARM_FP_MODEL_UNKNOWN)
1639         error ("invalid floating point option: -mfpu=%s", target_fpu_name);
1640     }
1641   else
1642     {
1643 #ifdef FPUTYPE_DEFAULT
1644       /* Use the default if it is specified for this platform.  */
1645       arm_fpu_arch = FPUTYPE_DEFAULT;
1646       arm_fpu_tune = FPUTYPE_DEFAULT;
1647 #else
1648       /* Pick one based on CPU type.  */
1649       /* ??? Some targets assume FPA is the default.
1650       if ((insn_flags & FL_VFP) != 0)
1651         arm_fpu_arch = FPUTYPE_VFP;
1652       else
1653       */
1654       if (arm_arch_cirrus)
1655         arm_fpu_arch = FPUTYPE_MAVERICK;
1656       else
1657         arm_fpu_arch = FPUTYPE_FPA_EMU2;
1658 #endif
1659       if (tune_flags & FL_CO_PROC && arm_fpu_arch == FPUTYPE_FPA_EMU2)
1660         arm_fpu_tune = FPUTYPE_FPA;
1661       else
1662         arm_fpu_tune = arm_fpu_arch;
1663       arm_fp_model = fp_model_for_fpu[arm_fpu_arch];
1664       gcc_assert (arm_fp_model != ARM_FP_MODEL_UNKNOWN);
1665     }
1666
1667   if (target_float_abi_name != NULL)
1668     {
1669       /* The user specified a FP ABI.  */
1670       for (i = 0; i < ARRAY_SIZE (all_float_abis); i++)
1671         {
1672           if (streq (all_float_abis[i].name, target_float_abi_name))
1673             {
1674               arm_float_abi = all_float_abis[i].abi_type;
1675               break;
1676             }
1677         }
1678       if (i == ARRAY_SIZE (all_float_abis))
1679         error ("invalid floating point abi: -mfloat-abi=%s",
1680                target_float_abi_name);
1681     }
1682   else
1683     arm_float_abi = TARGET_DEFAULT_FLOAT_ABI;
1684
1685   if (TARGET_AAPCS_BASED
1686       && (arm_fp_model == ARM_FP_MODEL_FPA))
1687     error ("FPA is unsupported in the AAPCS");
1688
1689   if (TARGET_AAPCS_BASED)
1690     {
1691       if (TARGET_CALLER_INTERWORKING)
1692         error ("AAPCS does not support -mcaller-super-interworking");
1693       else
1694         if (TARGET_CALLEE_INTERWORKING)
1695           error ("AAPCS does not support -mcallee-super-interworking");
1696     }
1697
1698   /* FPA and iWMMXt are incompatible because the insn encodings overlap.
1699      VFP and iWMMXt can theoretically coexist, but it's unlikely such silicon
1700      will ever exist.  GCC makes no attempt to support this combination.  */
1701   if (TARGET_IWMMXT && !TARGET_SOFT_FLOAT)
1702     sorry ("iWMMXt and hardware floating point");
1703
1704   /* ??? iWMMXt insn patterns need auditing for Thumb-2.  */
1705   if (TARGET_THUMB2 && TARGET_IWMMXT)
1706     sorry ("Thumb-2 iWMMXt");
1707
1708   /* __fp16 support currently assumes the core has ldrh.  */
1709   if (!arm_arch4 && arm_fp16_format != ARM_FP16_FORMAT_NONE)
1710     sorry ("__fp16 and no ldrh");
1711
1712   /* If soft-float is specified then don't use FPU.  */
1713   if (TARGET_SOFT_FLOAT)
1714     arm_fpu_arch = FPUTYPE_NONE;
1715
1716   if (TARGET_AAPCS_BASED)
1717     {
1718       if (arm_abi == ARM_ABI_IWMMXT)
1719         arm_pcs_default = ARM_PCS_AAPCS_IWMMXT;
1720       else if (arm_float_abi == ARM_FLOAT_ABI_HARD
1721                && TARGET_HARD_FLOAT
1722                && TARGET_VFP)
1723         arm_pcs_default = ARM_PCS_AAPCS_VFP;
1724       else
1725         arm_pcs_default = ARM_PCS_AAPCS;
1726     }
1727   else
1728     {
1729       if (arm_float_abi == ARM_FLOAT_ABI_HARD && TARGET_VFP)
1730         sorry ("-mfloat-abi=hard and VFP");
1731
1732       if (arm_abi == ARM_ABI_APCS)
1733         arm_pcs_default = ARM_PCS_APCS;
1734       else
1735         arm_pcs_default = ARM_PCS_ATPCS;
1736     }
1737
1738   /* For arm2/3 there is no need to do any scheduling if there is only
1739      a floating point emulator, or we are doing software floating-point.  */
1740   if ((TARGET_SOFT_FLOAT
1741        || arm_fpu_tune == FPUTYPE_FPA_EMU2
1742        || arm_fpu_tune == FPUTYPE_FPA_EMU3)
1743       && (tune_flags & FL_MODE32) == 0)
1744     flag_schedule_insns = flag_schedule_insns_after_reload = 0;
1745
1746   if (target_thread_switch)
1747     {
1748       if (strcmp (target_thread_switch, "soft") == 0)
1749         target_thread_pointer = TP_SOFT;
1750       else if (strcmp (target_thread_switch, "auto") == 0)
1751         target_thread_pointer = TP_AUTO;
1752       else if (strcmp (target_thread_switch, "cp15") == 0)
1753         target_thread_pointer = TP_CP15;
1754       else
1755         error ("invalid thread pointer option: -mtp=%s", target_thread_switch);
1756     }
1757
1758   /* Use the cp15 method if it is available.  */
1759   if (target_thread_pointer == TP_AUTO)
1760     {
1761       if (arm_arch6k && !TARGET_THUMB)
1762         target_thread_pointer = TP_CP15;
1763       else
1764         target_thread_pointer = TP_SOFT;
1765     }
1766
1767   if (TARGET_HARD_TP && TARGET_THUMB1)
1768     error ("can not use -mtp=cp15 with 16-bit Thumb");
1769
1770   /* Override the default structure alignment for AAPCS ABI.  */
1771   if (TARGET_AAPCS_BASED)
1772     arm_structure_size_boundary = 8;
1773
1774   if (structure_size_string != NULL)
1775     {
1776       int size = strtol (structure_size_string, NULL, 0);
1777
1778       if (size == 8 || size == 32
1779           || (ARM_DOUBLEWORD_ALIGN && size == 64))
1780         arm_structure_size_boundary = size;
1781       else
1782         warning (0, "structure size boundary can only be set to %s",
1783                  ARM_DOUBLEWORD_ALIGN ? "8, 32 or 64": "8 or 32");
1784     }
1785
1786   if (!TARGET_ARM && TARGET_VXWORKS_RTP && flag_pic)
1787     {
1788       error ("RTP PIC is incompatible with Thumb");
1789       flag_pic = 0;
1790     }
1791
1792   /* If stack checking is disabled, we can use r10 as the PIC register,
1793      which keeps r9 available.  The EABI specifies r9 as the PIC register.  */
1794   if (flag_pic && TARGET_SINGLE_PIC_BASE)
1795     {
1796       if (TARGET_VXWORKS_RTP)
1797         warning (0, "RTP PIC is incompatible with -msingle-pic-base");
1798       arm_pic_register = (TARGET_APCS_STACK || TARGET_AAPCS_BASED) ? 9 : 10;
1799     }
1800
1801   if (flag_pic && TARGET_VXWORKS_RTP)
1802     arm_pic_register = 9;
1803
1804   if (arm_pic_register_string != NULL)
1805     {
1806       int pic_register = decode_reg_name (arm_pic_register_string);
1807
1808       if (!flag_pic)
1809         warning (0, "-mpic-register= is useless without -fpic");
1810
1811       /* Prevent the user from choosing an obviously stupid PIC register.  */
1812       else if (pic_register < 0 || call_used_regs[pic_register]
1813                || pic_register == HARD_FRAME_POINTER_REGNUM
1814                || pic_register == STACK_POINTER_REGNUM
1815                || pic_register >= PC_REGNUM
1816                || (TARGET_VXWORKS_RTP
1817                    && (unsigned int) pic_register != arm_pic_register))
1818         error ("unable to use '%s' for PIC register", arm_pic_register_string);
1819       else
1820         arm_pic_register = pic_register;
1821     }
1822
1823   /* Enable -mfix-cortex-m3-ldrd by default for Cortex-M3 cores.  */
1824   if (fix_cm3_ldrd == 2)
1825     {
1826       if (selected_cpu == cortexm3)
1827         fix_cm3_ldrd = 1;
1828       else
1829         fix_cm3_ldrd = 0;
1830     }
1831
1832   /* ??? We might want scheduling for thumb2.  */
1833   if (TARGET_THUMB && flag_schedule_insns)
1834     {
1835       /* Don't warn since it's on by default in -O2.  */
1836       flag_schedule_insns = 0;
1837     }
1838
1839   if (optimize_size)
1840     {
1841       arm_constant_limit = 1;
1842
1843       /* If optimizing for size, bump the number of instructions that we
1844          are prepared to conditionally execute (even on a StrongARM).  */
1845       max_insns_skipped = 6;
1846     }
1847   else
1848     {
1849       /* For processors with load scheduling, it never costs more than
1850          2 cycles to load a constant, and the load scheduler may well
1851          reduce that to 1.  */
1852       if (arm_ld_sched)
1853         arm_constant_limit = 1;
1854
1855       /* On XScale the longer latency of a load makes it more difficult
1856          to achieve a good schedule, so it's faster to synthesize
1857          constants that can be done in two insns.  */
1858       if (arm_tune_xscale)
1859         arm_constant_limit = 2;
1860
1861       /* StrongARM has early execution of branches, so a sequence
1862          that is worth skipping is shorter.  */
1863       if (arm_tune_strongarm)
1864         max_insns_skipped = 3;
1865     }
1866
1867   /* Ideally we would want to use CFI directives to generate
1868      debug info.  However this also creates the .eh_frame
1869      section, so disable them until GAS can handle
1870      this properly.  See PR40521. */
1871   if (TARGET_AAPCS_BASED)
1872     flag_dwarf2_cfi_asm = 0;
1873
1874   /* Register global variables with the garbage collector.  */
1875   arm_add_gc_roots ();
1876 }
1877
1878 static void
1879 arm_add_gc_roots (void)
1880 {
1881   gcc_obstack_init(&minipool_obstack);
1882   minipool_startobj = (char *) obstack_alloc (&minipool_obstack, 0);
1883 }
1884 \f
1885 /* A table of known ARM exception types.
1886    For use with the interrupt function attribute.  */
1887
1888 typedef struct
1889 {
1890   const char *const arg;
1891   const unsigned long return_value;
1892 }
1893 isr_attribute_arg;
1894
1895 static const isr_attribute_arg isr_attribute_args [] =
1896 {
1897   { "IRQ",   ARM_FT_ISR },
1898   { "irq",   ARM_FT_ISR },
1899   { "FIQ",   ARM_FT_FIQ },
1900   { "fiq",   ARM_FT_FIQ },
1901   { "ABORT", ARM_FT_ISR },
1902   { "abort", ARM_FT_ISR },
1903   { "ABORT", ARM_FT_ISR },
1904   { "abort", ARM_FT_ISR },
1905   { "UNDEF", ARM_FT_EXCEPTION },
1906   { "undef", ARM_FT_EXCEPTION },
1907   { "SWI",   ARM_FT_EXCEPTION },
1908   { "swi",   ARM_FT_EXCEPTION },
1909   { NULL,    ARM_FT_NORMAL }
1910 };
1911
1912 /* Returns the (interrupt) function type of the current
1913    function, or ARM_FT_UNKNOWN if the type cannot be determined.  */
1914
1915 static unsigned long
1916 arm_isr_value (tree argument)
1917 {
1918   const isr_attribute_arg * ptr;
1919   const char *              arg;
1920
1921   if (!arm_arch_notm)
1922     return ARM_FT_NORMAL | ARM_FT_STACKALIGN;
1923
1924   /* No argument - default to IRQ.  */
1925   if (argument == NULL_TREE)
1926     return ARM_FT_ISR;
1927
1928   /* Get the value of the argument.  */
1929   if (TREE_VALUE (argument) == NULL_TREE
1930       || TREE_CODE (TREE_VALUE (argument)) != STRING_CST)
1931     return ARM_FT_UNKNOWN;
1932
1933   arg = TREE_STRING_POINTER (TREE_VALUE (argument));
1934
1935   /* Check it against the list of known arguments.  */
1936   for (ptr = isr_attribute_args; ptr->arg != NULL; ptr++)
1937     if (streq (arg, ptr->arg))
1938       return ptr->return_value;
1939
1940   /* An unrecognized interrupt type.  */
1941   return ARM_FT_UNKNOWN;
1942 }
1943
1944 /* Computes the type of the current function.  */
1945
1946 static unsigned long
1947 arm_compute_func_type (void)
1948 {
1949   unsigned long type = ARM_FT_UNKNOWN;
1950   tree a;
1951   tree attr;
1952
1953   gcc_assert (TREE_CODE (current_function_decl) == FUNCTION_DECL);
1954
1955   /* Decide if the current function is volatile.  Such functions
1956      never return, and many memory cycles can be saved by not storing
1957      register values that will never be needed again.  This optimization
1958      was added to speed up context switching in a kernel application.  */
1959   if (optimize > 0
1960       && (TREE_NOTHROW (current_function_decl)
1961           || !(flag_unwind_tables
1962                || (flag_exceptions && !USING_SJLJ_EXCEPTIONS)))
1963       && TREE_THIS_VOLATILE (current_function_decl))
1964     type |= ARM_FT_VOLATILE;
1965
1966   if (cfun->static_chain_decl != NULL)
1967     type |= ARM_FT_NESTED;
1968
1969   attr = DECL_ATTRIBUTES (current_function_decl);
1970
1971   a = lookup_attribute ("naked", attr);
1972   if (a != NULL_TREE)
1973     type |= ARM_FT_NAKED;
1974
1975   a = lookup_attribute ("isr", attr);
1976   if (a == NULL_TREE)
1977     a = lookup_attribute ("interrupt", attr);
1978
1979   if (a == NULL_TREE)
1980     type |= TARGET_INTERWORK ? ARM_FT_INTERWORKED : ARM_FT_NORMAL;
1981   else
1982     type |= arm_isr_value (TREE_VALUE (a));
1983
1984   return type;
1985 }
1986
1987 /* Returns the type of the current function.  */
1988
1989 unsigned long
1990 arm_current_func_type (void)
1991 {
1992   if (ARM_FUNC_TYPE (cfun->machine->func_type) == ARM_FT_UNKNOWN)
1993     cfun->machine->func_type = arm_compute_func_type ();
1994
1995   return cfun->machine->func_type;
1996 }
1997
1998 bool
1999 arm_allocate_stack_slots_for_args (void)
2000 {
2001   /* Naked functions should not allocate stack slots for arguments.  */
2002   return !IS_NAKED (arm_current_func_type ());
2003 }
2004
2005 \f
2006 /* Output assembler code for a block containing the constant parts
2007    of a trampoline, leaving space for the variable parts.
2008
2009    On the ARM, (if r8 is the static chain regnum, and remembering that
2010    referencing pc adds an offset of 8) the trampoline looks like:
2011            ldr          r8, [pc, #0]
2012            ldr          pc, [pc]
2013            .word        static chain value
2014            .word        function's address
2015    XXX FIXME: When the trampoline returns, r8 will be clobbered.  */
2016
2017 static void
2018 arm_asm_trampoline_template (FILE *f)
2019 {
2020   if (TARGET_ARM)
2021     {
2022       asm_fprintf (f, "\tldr\t%r, [%r, #0]\n", STATIC_CHAIN_REGNUM, PC_REGNUM);
2023       asm_fprintf (f, "\tldr\t%r, [%r, #0]\n", PC_REGNUM, PC_REGNUM);
2024     }
2025   else if (TARGET_THUMB2)
2026     {
2027       /* The Thumb-2 trampoline is similar to the arm implementation.
2028          Unlike 16-bit Thumb, we enter the stub in thumb mode.  */
2029       asm_fprintf (f, "\tldr.w\t%r, [%r, #4]\n",
2030                    STATIC_CHAIN_REGNUM, PC_REGNUM);
2031       asm_fprintf (f, "\tldr.w\t%r, [%r, #4]\n", PC_REGNUM, PC_REGNUM);
2032     }
2033   else
2034     {
2035       ASM_OUTPUT_ALIGN (f, 2);
2036       fprintf (f, "\t.code\t16\n");
2037       fprintf (f, ".Ltrampoline_start:\n");
2038       asm_fprintf (f, "\tpush\t{r0, r1}\n");
2039       asm_fprintf (f, "\tldr\tr0, [%r, #8]\n", PC_REGNUM);
2040       asm_fprintf (f, "\tmov\t%r, r0\n", STATIC_CHAIN_REGNUM);
2041       asm_fprintf (f, "\tldr\tr0, [%r, #8]\n", PC_REGNUM);
2042       asm_fprintf (f, "\tstr\tr0, [%r, #4]\n", SP_REGNUM);
2043       asm_fprintf (f, "\tpop\t{r0, %r}\n", PC_REGNUM);
2044     }
2045   assemble_aligned_integer (UNITS_PER_WORD, const0_rtx);
2046   assemble_aligned_integer (UNITS_PER_WORD, const0_rtx);
2047 }
2048
2049 /* Emit RTL insns to initialize the variable parts of a trampoline.  */
2050
2051 static void
2052 arm_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
2053 {
2054   rtx fnaddr, mem, a_tramp;
2055
2056   emit_block_move (m_tramp, assemble_trampoline_template (),
2057                    GEN_INT (TRAMPOLINE_SIZE), BLOCK_OP_NORMAL);
2058
2059   mem = adjust_address (m_tramp, SImode, TARGET_32BIT ? 8 : 12);
2060   emit_move_insn (mem, chain_value);
2061
2062   mem = adjust_address (m_tramp, SImode, TARGET_32BIT ? 12 : 16);
2063   fnaddr = XEXP (DECL_RTL (fndecl), 0);
2064   emit_move_insn (mem, fnaddr);
2065
2066   a_tramp = XEXP (m_tramp, 0);
2067   emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__clear_cache"),
2068                      LCT_NORMAL, VOIDmode, 2, a_tramp, Pmode,
2069                      plus_constant (a_tramp, TRAMPOLINE_SIZE), Pmode);
2070 }
2071
2072 /* Thumb trampolines should be entered in thumb mode, so set
2073    the bottom bit of the address.  */
2074
2075 static rtx
2076 arm_trampoline_adjust_address (rtx addr)
2077 {
2078   if (TARGET_THUMB)
2079     addr = expand_simple_binop (Pmode, IOR, addr, const1_rtx,
2080                                 NULL, 0, OPTAB_LIB_WIDEN);
2081   return addr;
2082 }
2083 \f
2084 /* Return 1 if it is possible to return using a single instruction.
2085    If SIBLING is non-null, this is a test for a return before a sibling
2086    call.  SIBLING is the call insn, so we can examine its register usage.  */
2087
2088 int
2089 use_return_insn (int iscond, rtx sibling)
2090 {
2091   int regno;
2092   unsigned int func_type;
2093   unsigned long saved_int_regs;
2094   unsigned HOST_WIDE_INT stack_adjust;
2095   arm_stack_offsets *offsets;
2096
2097   /* Never use a return instruction before reload has run.  */
2098   if (!reload_completed)
2099     return 0;
2100
2101   func_type = arm_current_func_type ();
2102
2103   /* Naked, volatile and stack alignment functions need special
2104      consideration.  */
2105   if (func_type & (ARM_FT_VOLATILE | ARM_FT_NAKED | ARM_FT_STACKALIGN))
2106     return 0;
2107
2108   /* So do interrupt functions that use the frame pointer and Thumb
2109      interrupt functions.  */
2110   if (IS_INTERRUPT (func_type) && (frame_pointer_needed || TARGET_THUMB))
2111     return 0;
2112
2113   offsets = arm_get_frame_offsets ();
2114   stack_adjust = offsets->outgoing_args - offsets->saved_regs;
2115
2116   /* As do variadic functions.  */
2117   if (crtl->args.pretend_args_size
2118       || cfun->machine->uses_anonymous_args
2119       /* Or if the function calls __builtin_eh_return () */
2120       || crtl->calls_eh_return
2121       /* Or if the function calls alloca */
2122       || cfun->calls_alloca
2123       /* Or if there is a stack adjustment.  However, if the stack pointer
2124          is saved on the stack, we can use a pre-incrementing stack load.  */
2125       || !(stack_adjust == 0 || (TARGET_APCS_FRAME && frame_pointer_needed
2126                                  && stack_adjust == 4)))
2127     return 0;
2128
2129   saved_int_regs = offsets->saved_regs_mask;
2130
2131   /* Unfortunately, the insn
2132
2133        ldmib sp, {..., sp, ...}
2134
2135      triggers a bug on most SA-110 based devices, such that the stack
2136      pointer won't be correctly restored if the instruction takes a
2137      page fault.  We work around this problem by popping r3 along with
2138      the other registers, since that is never slower than executing
2139      another instruction.
2140
2141      We test for !arm_arch5 here, because code for any architecture
2142      less than this could potentially be run on one of the buggy
2143      chips.  */
2144   if (stack_adjust == 4 && !arm_arch5 && TARGET_ARM)
2145     {
2146       /* Validate that r3 is a call-clobbered register (always true in
2147          the default abi) ...  */
2148       if (!call_used_regs[3])
2149         return 0;
2150
2151       /* ... that it isn't being used for a return value ... */
2152       if (arm_size_return_regs () >= (4 * UNITS_PER_WORD))
2153         return 0;
2154
2155       /* ... or for a tail-call argument ...  */
2156       if (sibling)
2157         {
2158           gcc_assert (GET_CODE (sibling) == CALL_INSN);
2159
2160           if (find_regno_fusage (sibling, USE, 3))
2161             return 0;
2162         }
2163
2164       /* ... and that there are no call-saved registers in r0-r2
2165          (always true in the default ABI).  */
2166       if (saved_int_regs & 0x7)
2167         return 0;
2168     }
2169
2170   /* Can't be done if interworking with Thumb, and any registers have been
2171      stacked.  */
2172   if (TARGET_INTERWORK && saved_int_regs != 0 && !IS_INTERRUPT(func_type))
2173     return 0;
2174
2175   /* On StrongARM, conditional returns are expensive if they aren't
2176      taken and multiple registers have been stacked.  */
2177   if (iscond && arm_tune_strongarm)
2178     {
2179       /* Conditional return when just the LR is stored is a simple
2180          conditional-load instruction, that's not expensive.  */
2181       if (saved_int_regs != 0 && saved_int_regs != (1 << LR_REGNUM))
2182         return 0;
2183
2184       if (flag_pic 
2185           && arm_pic_register != INVALID_REGNUM
2186           && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
2187         return 0;
2188     }
2189
2190   /* If there are saved registers but the LR isn't saved, then we need
2191      two instructions for the return.  */
2192   if (saved_int_regs && !(saved_int_regs & (1 << LR_REGNUM)))
2193     return 0;
2194
2195   /* Can't be done if any of the FPA regs are pushed,
2196      since this also requires an insn.  */
2197   if (TARGET_HARD_FLOAT && TARGET_FPA)
2198     for (regno = FIRST_FPA_REGNUM; regno <= LAST_FPA_REGNUM; regno++)
2199       if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
2200         return 0;
2201
2202   /* Likewise VFP regs.  */
2203   if (TARGET_HARD_FLOAT && TARGET_VFP)
2204     for (regno = FIRST_VFP_REGNUM; regno <= LAST_VFP_REGNUM; regno++)
2205       if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
2206         return 0;
2207
2208   if (TARGET_REALLY_IWMMXT)
2209     for (regno = FIRST_IWMMXT_REGNUM; regno <= LAST_IWMMXT_REGNUM; regno++)
2210       if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2211         return 0;
2212
2213   return 1;
2214 }
2215
2216 /* Return TRUE if int I is a valid immediate ARM constant.  */
2217
2218 int
2219 const_ok_for_arm (HOST_WIDE_INT i)
2220 {
2221   int lowbit;
2222
2223   /* For machines with >32 bit HOST_WIDE_INT, the bits above bit 31 must
2224      be all zero, or all one.  */
2225   if ((i & ~(unsigned HOST_WIDE_INT) 0xffffffff) != 0
2226       && ((i & ~(unsigned HOST_WIDE_INT) 0xffffffff)
2227           != ((~(unsigned HOST_WIDE_INT) 0)
2228               & ~(unsigned HOST_WIDE_INT) 0xffffffff)))
2229     return FALSE;
2230
2231   i &= (unsigned HOST_WIDE_INT) 0xffffffff;
2232
2233   /* Fast return for 0 and small values.  We must do this for zero, since
2234      the code below can't handle that one case.  */
2235   if ((i & ~(unsigned HOST_WIDE_INT) 0xff) == 0)
2236     return TRUE;
2237
2238   /* Get the number of trailing zeros.  */
2239   lowbit = ffs((int) i) - 1;
2240   
2241   /* Only even shifts are allowed in ARM mode so round down to the
2242      nearest even number.  */
2243   if (TARGET_ARM)
2244     lowbit &= ~1;
2245
2246   if ((i & ~(((unsigned HOST_WIDE_INT) 0xff) << lowbit)) == 0)
2247     return TRUE;
2248
2249   if (TARGET_ARM)
2250     {
2251       /* Allow rotated constants in ARM mode.  */
2252       if (lowbit <= 4
2253            && ((i & ~0xc000003f) == 0
2254                || (i & ~0xf000000f) == 0
2255                || (i & ~0xfc000003) == 0))
2256         return TRUE;
2257     }
2258   else
2259     {
2260       HOST_WIDE_INT v;
2261
2262       /* Allow repeated pattern.  */
2263       v = i & 0xff;
2264       v |= v << 16;
2265       if (i == v || i == (v | (v << 8)))
2266         return TRUE;
2267     }
2268
2269   return FALSE;
2270 }
2271
2272 /* Return true if I is a valid constant for the operation CODE.  */
2273 static int
2274 const_ok_for_op (HOST_WIDE_INT i, enum rtx_code code)
2275 {
2276   if (const_ok_for_arm (i))
2277     return 1;
2278
2279   switch (code)
2280     {
2281     case PLUS:
2282     case COMPARE:
2283     case EQ:
2284     case NE:
2285     case GT:
2286     case LE:
2287     case LT:
2288     case GE:
2289     case GEU:
2290     case LTU:
2291     case GTU:
2292     case LEU:
2293     case UNORDERED:
2294     case ORDERED:
2295     case UNEQ:
2296     case UNGE:
2297     case UNLT:
2298     case UNGT:
2299     case UNLE:
2300       return const_ok_for_arm (ARM_SIGN_EXTEND (-i));
2301
2302     case MINUS:         /* Should only occur with (MINUS I reg) => rsb */
2303     case XOR:
2304       return 0;
2305
2306     case IOR:
2307       if (TARGET_THUMB2)
2308         return const_ok_for_arm (ARM_SIGN_EXTEND (~i));
2309       return 0;
2310
2311     case AND:
2312       return const_ok_for_arm (ARM_SIGN_EXTEND (~i));
2313
2314     default:
2315       gcc_unreachable ();
2316     }
2317 }
2318
2319 /* Emit a sequence of insns to handle a large constant.
2320    CODE is the code of the operation required, it can be any of SET, PLUS,
2321    IOR, AND, XOR, MINUS;
2322    MODE is the mode in which the operation is being performed;
2323    VAL is the integer to operate on;
2324    SOURCE is the other operand (a register, or a null-pointer for SET);
2325    SUBTARGETS means it is safe to create scratch registers if that will
2326    either produce a simpler sequence, or we will want to cse the values.
2327    Return value is the number of insns emitted.  */
2328
2329 /* ??? Tweak this for thumb2.  */
2330 int
2331 arm_split_constant (enum rtx_code code, enum machine_mode mode, rtx insn,
2332                     HOST_WIDE_INT val, rtx target, rtx source, int subtargets)
2333 {
2334   rtx cond;
2335
2336   if (insn && GET_CODE (PATTERN (insn)) == COND_EXEC)
2337     cond = COND_EXEC_TEST (PATTERN (insn));
2338   else
2339     cond = NULL_RTX;
2340
2341   if (subtargets || code == SET
2342       || (GET_CODE (target) == REG && GET_CODE (source) == REG
2343           && REGNO (target) != REGNO (source)))
2344     {
2345       /* After arm_reorg has been called, we can't fix up expensive
2346          constants by pushing them into memory so we must synthesize
2347          them in-line, regardless of the cost.  This is only likely to
2348          be more costly on chips that have load delay slots and we are
2349          compiling without running the scheduler (so no splitting
2350          occurred before the final instruction emission).
2351
2352          Ref: gcc -O1 -mcpu=strongarm gcc.c-torture/compile/980506-2.c
2353       */
2354       if (!after_arm_reorg
2355           && !cond
2356           && (arm_gen_constant (code, mode, NULL_RTX, val, target, source,
2357                                 1, 0)
2358               > arm_constant_limit + (code != SET)))
2359         {
2360           if (code == SET)
2361             {
2362               /* Currently SET is the only monadic value for CODE, all
2363                  the rest are diadic.  */
2364               if (TARGET_USE_MOVT)
2365                 arm_emit_movpair (target, GEN_INT (val));
2366               else
2367                 emit_set_insn (target, GEN_INT (val));
2368
2369               return 1;
2370             }
2371           else
2372             {
2373               rtx temp = subtargets ? gen_reg_rtx (mode) : target;
2374
2375               if (TARGET_USE_MOVT)
2376                 arm_emit_movpair (temp, GEN_INT (val));
2377               else
2378                 emit_set_insn (temp, GEN_INT (val));
2379
2380               /* For MINUS, the value is subtracted from, since we never
2381                  have subtraction of a constant.  */
2382               if (code == MINUS)
2383                 emit_set_insn (target, gen_rtx_MINUS (mode, temp, source));
2384               else
2385                 emit_set_insn (target,
2386                                gen_rtx_fmt_ee (code, mode, source, temp));
2387               return 2;
2388             }
2389         }
2390     }
2391
2392   return arm_gen_constant (code, mode, cond, val, target, source, subtargets,
2393                            1);
2394 }
2395
2396 /* Return the number of ARM instructions required to synthesize the given
2397    constant.  */
2398 static int
2399 count_insns_for_constant (HOST_WIDE_INT remainder, int i)
2400 {
2401   HOST_WIDE_INT temp1;
2402   int num_insns = 0;
2403   do
2404     {
2405       int end;
2406
2407       if (i <= 0)
2408         i += 32;
2409       if (remainder & (3 << (i - 2)))
2410         {
2411           end = i - 8;
2412           if (end < 0)
2413             end += 32;
2414           temp1 = remainder & ((0x0ff << end)
2415                                     | ((i < end) ? (0xff >> (32 - end)) : 0));
2416           remainder &= ~temp1;
2417           num_insns++;
2418           i -= 6;
2419         }
2420       i -= 2;
2421     } while (remainder);
2422   return num_insns;
2423 }
2424
2425 /* Emit an instruction with the indicated PATTERN.  If COND is
2426    non-NULL, conditionalize the execution of the instruction on COND
2427    being true.  */
2428
2429 static void
2430 emit_constant_insn (rtx cond, rtx pattern)
2431 {
2432   if (cond)
2433     pattern = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond), pattern);
2434   emit_insn (pattern);
2435 }
2436
2437 /* As above, but extra parameter GENERATE which, if clear, suppresses
2438    RTL generation.  */
2439 /* ??? This needs more work for thumb2.  */
2440
2441 static int
2442 arm_gen_constant (enum rtx_code code, enum machine_mode mode, rtx cond,
2443                   HOST_WIDE_INT val, rtx target, rtx source, int subtargets,
2444                   int generate)
2445 {
2446   int can_invert = 0;
2447   int can_negate = 0;
2448   int can_negate_initial = 0;
2449   int can_shift = 0;
2450   int i;
2451   int num_bits_set = 0;
2452   int set_sign_bit_copies = 0;
2453   int clear_sign_bit_copies = 0;
2454   int clear_zero_bit_copies = 0;
2455   int set_zero_bit_copies = 0;
2456   int insns = 0;
2457   unsigned HOST_WIDE_INT temp1, temp2;
2458   unsigned HOST_WIDE_INT remainder = val & 0xffffffff;
2459
2460   /* Find out which operations are safe for a given CODE.  Also do a quick
2461      check for degenerate cases; these can occur when DImode operations
2462      are split.  */
2463   switch (code)
2464     {
2465     case SET:
2466       can_invert = 1;
2467       can_shift = 1;
2468       can_negate = 1;
2469       break;
2470
2471     case PLUS:
2472       can_negate = 1;
2473       can_negate_initial = 1;
2474       break;
2475
2476     case IOR:
2477       if (remainder == 0xffffffff)
2478         {
2479           if (generate)
2480             emit_constant_insn (cond,
2481                                 gen_rtx_SET (VOIDmode, target,
2482                                              GEN_INT (ARM_SIGN_EXTEND (val))));
2483           return 1;
2484         }
2485
2486       if (remainder == 0)
2487         {
2488           if (reload_completed && rtx_equal_p (target, source))
2489             return 0;
2490
2491           if (generate)
2492             emit_constant_insn (cond,
2493                                 gen_rtx_SET (VOIDmode, target, source));
2494           return 1;
2495         }
2496
2497       if (TARGET_THUMB2)
2498         can_invert = 1;
2499       break;
2500
2501     case AND:
2502       if (remainder == 0)
2503         {
2504           if (generate)
2505             emit_constant_insn (cond,
2506                                 gen_rtx_SET (VOIDmode, target, const0_rtx));
2507           return 1;
2508         }
2509       if (remainder == 0xffffffff)
2510         {
2511           if (reload_completed && rtx_equal_p (target, source))
2512             return 0;
2513           if (generate)
2514             emit_constant_insn (cond,
2515                                 gen_rtx_SET (VOIDmode, target, source));
2516           return 1;
2517         }
2518       can_invert = 1;
2519       break;
2520
2521     case XOR:
2522       if (remainder == 0)
2523         {
2524           if (reload_completed && rtx_equal_p (target, source))
2525             return 0;
2526           if (generate)
2527             emit_constant_insn (cond,
2528                                 gen_rtx_SET (VOIDmode, target, source));
2529           return 1;
2530         }
2531
2532       /* We don't know how to handle other cases yet.  */
2533       gcc_assert (remainder == 0xffffffff);
2534
2535       if (generate)
2536         emit_constant_insn (cond,
2537                             gen_rtx_SET (VOIDmode, target,
2538                                          gen_rtx_NOT (mode, source)));
2539       return 1;
2540
2541     case MINUS:
2542       /* We treat MINUS as (val - source), since (source - val) is always
2543          passed as (source + (-val)).  */
2544       if (remainder == 0)
2545         {
2546           if (generate)
2547             emit_constant_insn (cond,
2548                                 gen_rtx_SET (VOIDmode, target,
2549                                              gen_rtx_NEG (mode, source)));
2550           return 1;
2551         }
2552       if (const_ok_for_arm (val))
2553         {
2554           if (generate)
2555             emit_constant_insn (cond,
2556                                 gen_rtx_SET (VOIDmode, target,
2557                                              gen_rtx_MINUS (mode, GEN_INT (val),
2558                                                             source)));
2559           return 1;
2560         }
2561       can_negate = 1;
2562
2563       break;
2564
2565     default:
2566       gcc_unreachable ();
2567     }
2568
2569   /* If we can do it in one insn get out quickly.  */
2570   if (const_ok_for_arm (val)
2571       || (can_negate_initial && const_ok_for_arm (-val))
2572       || (can_invert && const_ok_for_arm (~val)))
2573     {
2574       if (generate)
2575         emit_constant_insn (cond,
2576                             gen_rtx_SET (VOIDmode, target,
2577                                          (source
2578                                           ? gen_rtx_fmt_ee (code, mode, source,
2579                                                             GEN_INT (val))
2580                                           : GEN_INT (val))));
2581       return 1;
2582     }
2583
2584   /* Calculate a few attributes that may be useful for specific
2585      optimizations.  */
2586   /* Count number of leading zeros.  */
2587   for (i = 31; i >= 0; i--)
2588     {
2589       if ((remainder & (1 << i)) == 0)
2590         clear_sign_bit_copies++;
2591       else
2592         break;
2593     }
2594
2595   /* Count number of leading 1's.  */
2596   for (i = 31; i >= 0; i--)
2597     {
2598       if ((remainder & (1 << i)) != 0)
2599         set_sign_bit_copies++;
2600       else
2601         break;
2602     }
2603
2604   /* Count number of trailing zero's.  */
2605   for (i = 0; i <= 31; i++)
2606     {
2607       if ((remainder & (1 << i)) == 0)
2608         clear_zero_bit_copies++;
2609       else
2610         break;
2611     }
2612
2613   /* Count number of trailing 1's.  */
2614   for (i = 0; i <= 31; i++)
2615     {
2616       if ((remainder & (1 << i)) != 0)
2617         set_zero_bit_copies++;
2618       else
2619         break;
2620     }
2621
2622   switch (code)
2623     {
2624     case SET:
2625       /* See if we can use movw.  */
2626       if (arm_arch_thumb2 && (remainder & 0xffff0000) == 0)
2627         {
2628           if (generate)
2629             emit_constant_insn (cond, gen_rtx_SET (VOIDmode, target,
2630                                                    GEN_INT (val)));
2631           return 1;
2632         }
2633
2634       /* See if we can do this by sign_extending a constant that is known
2635          to be negative.  This is a good, way of doing it, since the shift
2636          may well merge into a subsequent insn.  */
2637       if (set_sign_bit_copies > 1)
2638         {
2639           if (const_ok_for_arm
2640               (temp1 = ARM_SIGN_EXTEND (remainder
2641                                         << (set_sign_bit_copies - 1))))
2642             {
2643               if (generate)
2644                 {
2645                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2646                   emit_constant_insn (cond,
2647                                       gen_rtx_SET (VOIDmode, new_src,
2648                                                    GEN_INT (temp1)));
2649                   emit_constant_insn (cond,
2650                                       gen_ashrsi3 (target, new_src,
2651                                                    GEN_INT (set_sign_bit_copies - 1)));
2652                 }
2653               return 2;
2654             }
2655           /* For an inverted constant, we will need to set the low bits,
2656              these will be shifted out of harm's way.  */
2657           temp1 |= (1 << (set_sign_bit_copies - 1)) - 1;
2658           if (const_ok_for_arm (~temp1))
2659             {
2660               if (generate)
2661                 {
2662                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2663                   emit_constant_insn (cond,
2664                                       gen_rtx_SET (VOIDmode, new_src,
2665                                                    GEN_INT (temp1)));
2666                   emit_constant_insn (cond,
2667                                       gen_ashrsi3 (target, new_src,
2668                                                    GEN_INT (set_sign_bit_copies - 1)));
2669                 }
2670               return 2;
2671             }
2672         }
2673
2674       /* See if we can calculate the value as the difference between two
2675          valid immediates.  */
2676       if (clear_sign_bit_copies + clear_zero_bit_copies <= 16)
2677         {
2678           int topshift = clear_sign_bit_copies & ~1;
2679
2680           temp1 = ARM_SIGN_EXTEND ((remainder + (0x00800000 >> topshift))
2681                                    & (0xff000000 >> topshift));
2682
2683           /* If temp1 is zero, then that means the 9 most significant
2684              bits of remainder were 1 and we've caused it to overflow.
2685              When topshift is 0 we don't need to do anything since we
2686              can borrow from 'bit 32'.  */
2687           if (temp1 == 0 && topshift != 0)
2688             temp1 = 0x80000000 >> (topshift - 1);
2689
2690           temp2 = ARM_SIGN_EXTEND (temp1 - remainder);
2691
2692           if (const_ok_for_arm (temp2))
2693             {
2694               if (generate)
2695                 {
2696                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2697                   emit_constant_insn (cond,
2698                                       gen_rtx_SET (VOIDmode, new_src,
2699                                                    GEN_INT (temp1)));
2700                   emit_constant_insn (cond,
2701                                       gen_addsi3 (target, new_src,
2702                                                   GEN_INT (-temp2)));
2703                 }
2704
2705               return 2;
2706             }
2707         }
2708
2709       /* See if we can generate this by setting the bottom (or the top)
2710          16 bits, and then shifting these into the other half of the
2711          word.  We only look for the simplest cases, to do more would cost
2712          too much.  Be careful, however, not to generate this when the
2713          alternative would take fewer insns.  */
2714       if (val & 0xffff0000)
2715         {
2716           temp1 = remainder & 0xffff0000;
2717           temp2 = remainder & 0x0000ffff;
2718
2719           /* Overlaps outside this range are best done using other methods.  */
2720           for (i = 9; i < 24; i++)
2721             {
2722               if ((((temp2 | (temp2 << i)) & 0xffffffff) == remainder)
2723                   && !const_ok_for_arm (temp2))
2724                 {
2725                   rtx new_src = (subtargets
2726                                  ? (generate ? gen_reg_rtx (mode) : NULL_RTX)
2727                                  : target);
2728                   insns = arm_gen_constant (code, mode, cond, temp2, new_src,
2729                                             source, subtargets, generate);
2730                   source = new_src;
2731                   if (generate)
2732                     emit_constant_insn
2733                       (cond,
2734                        gen_rtx_SET
2735                        (VOIDmode, target,
2736                         gen_rtx_IOR (mode,
2737                                      gen_rtx_ASHIFT (mode, source,
2738                                                      GEN_INT (i)),
2739                                      source)));
2740                   return insns + 1;
2741                 }
2742             }
2743
2744           /* Don't duplicate cases already considered.  */
2745           for (i = 17; i < 24; i++)
2746             {
2747               if (((temp1 | (temp1 >> i)) == remainder)
2748                   && !const_ok_for_arm (temp1))
2749                 {
2750                   rtx new_src = (subtargets
2751                                  ? (generate ? gen_reg_rtx (mode) : NULL_RTX)
2752                                  : target);
2753                   insns = arm_gen_constant (code, mode, cond, temp1, new_src,
2754                                             source, subtargets, generate);
2755                   source = new_src;
2756                   if (generate)
2757                     emit_constant_insn
2758                       (cond,
2759                        gen_rtx_SET (VOIDmode, target,
2760                                     gen_rtx_IOR
2761                                     (mode,
2762                                      gen_rtx_LSHIFTRT (mode, source,
2763                                                        GEN_INT (i)),
2764                                      source)));
2765                   return insns + 1;
2766                 }
2767             }
2768         }
2769       break;
2770
2771     case IOR:
2772     case XOR:
2773       /* If we have IOR or XOR, and the constant can be loaded in a
2774          single instruction, and we can find a temporary to put it in,
2775          then this can be done in two instructions instead of 3-4.  */
2776       if (subtargets
2777           /* TARGET can't be NULL if SUBTARGETS is 0 */
2778           || (reload_completed && !reg_mentioned_p (target, source)))
2779         {
2780           if (const_ok_for_arm (ARM_SIGN_EXTEND (~val)))
2781             {
2782               if (generate)
2783                 {
2784                   rtx sub = subtargets ? gen_reg_rtx (mode) : target;
2785
2786                   emit_constant_insn (cond,
2787                                       gen_rtx_SET (VOIDmode, sub,
2788                                                    GEN_INT (val)));
2789                   emit_constant_insn (cond,
2790                                       gen_rtx_SET (VOIDmode, target,
2791                                                    gen_rtx_fmt_ee (code, mode,
2792                                                                    source, sub)));
2793                 }
2794               return 2;
2795             }
2796         }
2797
2798       if (code == XOR)
2799         break;
2800
2801       /*  Convert.
2802           x = y | constant ( which is composed of set_sign_bit_copies of leading 1s
2803                              and the remainder 0s for e.g. 0xfff00000)
2804           x = ~(~(y ashift set_sign_bit_copies) lshiftrt set_sign_bit_copies)
2805
2806           This can be done in 2 instructions by using shifts with mov or mvn.
2807           e.g. for
2808           x = x | 0xfff00000;
2809           we generate.
2810           mvn   r0, r0, asl #12
2811           mvn   r0, r0, lsr #12  */
2812       if (set_sign_bit_copies > 8
2813           && (val & (-1 << (32 - set_sign_bit_copies))) == val)
2814         {
2815           if (generate)
2816             {
2817               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
2818               rtx shift = GEN_INT (set_sign_bit_copies);
2819
2820               emit_constant_insn
2821                 (cond,
2822                  gen_rtx_SET (VOIDmode, sub,
2823                               gen_rtx_NOT (mode,
2824                                            gen_rtx_ASHIFT (mode,
2825                                                            source,
2826                                                            shift))));
2827               emit_constant_insn
2828                 (cond,
2829                  gen_rtx_SET (VOIDmode, target,
2830                               gen_rtx_NOT (mode,
2831                                            gen_rtx_LSHIFTRT (mode, sub,
2832                                                              shift))));
2833             }
2834           return 2;
2835         }
2836
2837       /* Convert
2838           x = y | constant (which has set_zero_bit_copies number of trailing ones).
2839            to
2840           x = ~((~y lshiftrt set_zero_bit_copies) ashift set_zero_bit_copies).
2841
2842           For eg. r0 = r0 | 0xfff
2843                mvn      r0, r0, lsr #12
2844                mvn      r0, r0, asl #12
2845
2846       */
2847       if (set_zero_bit_copies > 8
2848           && (remainder & ((1 << set_zero_bit_copies) - 1)) == remainder)
2849         {
2850           if (generate)
2851             {
2852               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
2853               rtx shift = GEN_INT (set_zero_bit_copies);
2854
2855               emit_constant_insn
2856                 (cond,
2857                  gen_rtx_SET (VOIDmode, sub,
2858                               gen_rtx_NOT (mode,
2859                                            gen_rtx_LSHIFTRT (mode,
2860                                                              source,
2861                                                              shift))));
2862               emit_constant_insn
2863                 (cond,
2864                  gen_rtx_SET (VOIDmode, target,
2865                               gen_rtx_NOT (mode,
2866                                            gen_rtx_ASHIFT (mode, sub,
2867                                                            shift))));
2868             }
2869           return 2;
2870         }
2871
2872       /* This will never be reached for Thumb2 because orn is a valid
2873          instruction. This is for Thumb1 and the ARM 32 bit cases.
2874
2875          x = y | constant (such that ~constant is a valid constant)
2876          Transform this to
2877          x = ~(~y & ~constant).
2878       */
2879       if (const_ok_for_arm (temp1 = ARM_SIGN_EXTEND (~val)))
2880         {
2881           if (generate)
2882             {
2883               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
2884               emit_constant_insn (cond,
2885                                   gen_rtx_SET (VOIDmode, sub,
2886                                                gen_rtx_NOT (mode, source)));
2887               source = sub;
2888               if (subtargets)
2889                 sub = gen_reg_rtx (mode);
2890               emit_constant_insn (cond,
2891                                   gen_rtx_SET (VOIDmode, sub,
2892                                                gen_rtx_AND (mode, source,
2893                                                             GEN_INT (temp1))));
2894               emit_constant_insn (cond,
2895                                   gen_rtx_SET (VOIDmode, target,
2896                                                gen_rtx_NOT (mode, sub)));
2897             }
2898           return 3;
2899         }
2900       break;
2901
2902     case AND:
2903       /* See if two shifts will do 2 or more insn's worth of work.  */
2904       if (clear_sign_bit_copies >= 16 && clear_sign_bit_copies < 24)
2905         {
2906           HOST_WIDE_INT shift_mask = ((0xffffffff
2907                                        << (32 - clear_sign_bit_copies))
2908                                       & 0xffffffff);
2909
2910           if ((remainder | shift_mask) != 0xffffffff)
2911             {
2912               if (generate)
2913                 {
2914                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2915                   insns = arm_gen_constant (AND, mode, cond,
2916                                             remainder | shift_mask,
2917                                             new_src, source, subtargets, 1);
2918                   source = new_src;
2919                 }
2920               else
2921                 {
2922                   rtx targ = subtargets ? NULL_RTX : target;
2923                   insns = arm_gen_constant (AND, mode, cond,
2924                                             remainder | shift_mask,
2925                                             targ, source, subtargets, 0);
2926                 }
2927             }
2928
2929           if (generate)
2930             {
2931               rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2932               rtx shift = GEN_INT (clear_sign_bit_copies);
2933
2934               emit_insn (gen_ashlsi3 (new_src, source, shift));
2935               emit_insn (gen_lshrsi3 (target, new_src, shift));
2936             }
2937
2938           return insns + 2;
2939         }
2940
2941       if (clear_zero_bit_copies >= 16 && clear_zero_bit_copies < 24)
2942         {
2943           HOST_WIDE_INT shift_mask = (1 << clear_zero_bit_copies) - 1;
2944
2945           if ((remainder | shift_mask) != 0xffffffff)
2946             {
2947               if (generate)
2948                 {
2949                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2950
2951                   insns = arm_gen_constant (AND, mode, cond,
2952                                             remainder | shift_mask,
2953                                             new_src, source, subtargets, 1);
2954                   source = new_src;
2955                 }
2956               else
2957                 {
2958                   rtx targ = subtargets ? NULL_RTX : target;
2959
2960                   insns = arm_gen_constant (AND, mode, cond,
2961                                             remainder | shift_mask,
2962                                             targ, source, subtargets, 0);
2963                 }
2964             }
2965
2966           if (generate)
2967             {
2968               rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
2969               rtx shift = GEN_INT (clear_zero_bit_copies);
2970
2971               emit_insn (gen_lshrsi3 (new_src, source, shift));
2972               emit_insn (gen_ashlsi3 (target, new_src, shift));
2973             }
2974
2975           return insns + 2;
2976         }
2977
2978       break;
2979
2980     default:
2981       break;
2982     }
2983
2984   for (i = 0; i < 32; i++)
2985     if (remainder & (1 << i))
2986       num_bits_set++;
2987
2988   if ((code == AND)
2989       || (code != IOR && can_invert && num_bits_set > 16))
2990     remainder = (~remainder) & 0xffffffff;
2991   else if (code == PLUS && num_bits_set > 16)
2992     remainder = (-remainder) & 0xffffffff;
2993   else
2994     {
2995       can_invert = 0;
2996       can_negate = 0;
2997     }
2998
2999   /* Now try and find a way of doing the job in either two or three
3000      instructions.
3001      We start by looking for the largest block of zeros that are aligned on
3002      a 2-bit boundary, we then fill up the temps, wrapping around to the
3003      top of the word when we drop off the bottom.
3004      In the worst case this code should produce no more than four insns.
3005      Thumb-2 constants are shifted, not rotated, so the MSB is always the
3006      best place to start.  */
3007
3008   /* ??? Use thumb2 replicated constants when the high and low halfwords are
3009      the same.  */
3010   {
3011     int best_start = 0;
3012     if (!TARGET_THUMB2)
3013       {
3014         int best_consecutive_zeros = 0;
3015
3016         for (i = 0; i < 32; i += 2)
3017           {
3018             int consecutive_zeros = 0;
3019
3020             if (!(remainder & (3 << i)))
3021               {
3022                 while ((i < 32) && !(remainder & (3 << i)))
3023                   {
3024                     consecutive_zeros += 2;
3025                     i += 2;
3026                   }
3027                 if (consecutive_zeros > best_consecutive_zeros)
3028                   {
3029                     best_consecutive_zeros = consecutive_zeros;
3030                     best_start = i - consecutive_zeros;
3031                   }
3032                 i -= 2;
3033               }
3034           }
3035
3036         /* So long as it won't require any more insns to do so, it's
3037            desirable to emit a small constant (in bits 0...9) in the last
3038            insn.  This way there is more chance that it can be combined with
3039            a later addressing insn to form a pre-indexed load or store
3040            operation.  Consider:
3041
3042                    *((volatile int *)0xe0000100) = 1;
3043                    *((volatile int *)0xe0000110) = 2;
3044
3045            We want this to wind up as:
3046
3047                     mov rA, #0xe0000000
3048                     mov rB, #1
3049                     str rB, [rA, #0x100]
3050                     mov rB, #2
3051                     str rB, [rA, #0x110]
3052
3053            rather than having to synthesize both large constants from scratch.
3054
3055            Therefore, we calculate how many insns would be required to emit
3056            the constant starting from `best_start', and also starting from
3057            zero (i.e. with bit 31 first to be output).  If `best_start' doesn't
3058            yield a shorter sequence, we may as well use zero.  */
3059         if (best_start != 0
3060             && ((((unsigned HOST_WIDE_INT) 1) << best_start) < remainder)
3061             && (count_insns_for_constant (remainder, 0) <=
3062                 count_insns_for_constant (remainder, best_start)))
3063           best_start = 0;
3064       }
3065
3066     /* Now start emitting the insns.  */
3067     i = best_start;
3068     do
3069       {
3070         int end;
3071
3072         if (i <= 0)
3073           i += 32;
3074         if (remainder & (3 << (i - 2)))
3075           {
3076             end = i - 8;
3077             if (end < 0)
3078               end += 32;
3079             temp1 = remainder & ((0x0ff << end)
3080                                  | ((i < end) ? (0xff >> (32 - end)) : 0));
3081             remainder &= ~temp1;
3082
3083             if (generate)
3084               {
3085                 rtx new_src, temp1_rtx;
3086
3087                 if (code == SET || code == MINUS)
3088                   {
3089                     new_src = (subtargets ? gen_reg_rtx (mode) : target);
3090                     if (can_invert && code != MINUS)
3091                       temp1 = ~temp1;
3092                   }
3093                 else
3094                   {
3095                     if (remainder && subtargets)
3096                       new_src = gen_reg_rtx (mode);
3097                     else
3098                       new_src = target;
3099                     if (can_invert)
3100                       temp1 = ~temp1;
3101                     else if (can_negate)
3102                       temp1 = -temp1;
3103                   }
3104
3105                 temp1 = trunc_int_for_mode (temp1, mode);
3106                 temp1_rtx = GEN_INT (temp1);
3107
3108                 if (code == SET)
3109                   ;
3110                 else if (code == MINUS)
3111                   temp1_rtx = gen_rtx_MINUS (mode, temp1_rtx, source);
3112                 else
3113                   temp1_rtx = gen_rtx_fmt_ee (code, mode, source, temp1_rtx);
3114
3115                 emit_constant_insn (cond,
3116                                     gen_rtx_SET (VOIDmode, new_src,
3117                                                  temp1_rtx));
3118                 source = new_src;
3119               }
3120
3121             if (code == SET)
3122               {
3123                 can_invert = 0;
3124                 code = PLUS;
3125               }
3126             else if (code == MINUS)
3127               code = PLUS;
3128
3129             insns++;
3130             if (TARGET_ARM)
3131               i -= 6;
3132             else
3133               i -= 7;
3134           }
3135         /* Arm allows rotates by a multiple of two. Thumb-2 allows arbitrary
3136            shifts.  */
3137         if (TARGET_ARM)
3138           i -= 2;
3139         else
3140           i--;
3141       }
3142     while (remainder);
3143   }
3144
3145   return insns;
3146 }
3147
3148 /* Canonicalize a comparison so that we are more likely to recognize it.
3149    This can be done for a few constant compares, where we can make the
3150    immediate value easier to load.  */
3151
3152 enum rtx_code
3153 arm_canonicalize_comparison (enum rtx_code code, enum machine_mode mode,
3154                              rtx * op1)
3155 {
3156   unsigned HOST_WIDE_INT i = INTVAL (*op1);
3157   unsigned HOST_WIDE_INT maxval;
3158   maxval = (((unsigned HOST_WIDE_INT) 1) << (GET_MODE_BITSIZE(mode) - 1)) - 1;
3159
3160   switch (code)
3161     {
3162     case EQ:
3163     case NE:
3164       return code;
3165
3166     case GT:
3167     case LE:
3168       if (i != maxval
3169           && (const_ok_for_arm (i + 1) || const_ok_for_arm (-(i + 1))))
3170         {
3171           *op1 = GEN_INT (i + 1);
3172           return code == GT ? GE : LT;
3173         }
3174       break;
3175
3176     case GE:
3177     case LT:
3178       if (i != ~maxval
3179           && (const_ok_for_arm (i - 1) || const_ok_for_arm (-(i - 1))))
3180         {
3181           *op1 = GEN_INT (i - 1);
3182           return code == GE ? GT : LE;
3183         }
3184       break;
3185
3186     case GTU:
3187     case LEU:
3188       if (i != ~((unsigned HOST_WIDE_INT) 0)
3189           && (const_ok_for_arm (i + 1) || const_ok_for_arm (-(i + 1))))
3190         {
3191           *op1 = GEN_INT (i + 1);
3192           return code == GTU ? GEU : LTU;
3193         }
3194       break;
3195
3196     case GEU:
3197     case LTU:
3198       if (i != 0
3199           && (const_ok_for_arm (i - 1) || const_ok_for_arm (-(i - 1))))
3200         {
3201           *op1 = GEN_INT (i - 1);
3202           return code == GEU ? GTU : LEU;
3203         }
3204       break;
3205
3206     default:
3207       gcc_unreachable ();
3208     }
3209
3210   return code;
3211 }
3212
3213
3214 /* Define how to find the value returned by a function.  */
3215
3216 static rtx
3217 arm_function_value(const_tree type, const_tree func,
3218                    bool outgoing ATTRIBUTE_UNUSED)
3219 {
3220   enum machine_mode mode;
3221   int unsignedp ATTRIBUTE_UNUSED;
3222   rtx r ATTRIBUTE_UNUSED;
3223
3224   mode = TYPE_MODE (type);
3225
3226   if (TARGET_AAPCS_BASED)
3227     return aapcs_allocate_return_reg (mode, type, func);
3228
3229   /* Promote integer types.  */
3230   if (INTEGRAL_TYPE_P (type))
3231     mode = arm_promote_function_mode (type, mode, &unsignedp, func, 1);
3232
3233   /* Promotes small structs returned in a register to full-word size
3234      for big-endian AAPCS.  */
3235   if (arm_return_in_msb (type))
3236     {
3237       HOST_WIDE_INT size = int_size_in_bytes (type);
3238       if (size % UNITS_PER_WORD != 0)
3239         {
3240           size += UNITS_PER_WORD - size % UNITS_PER_WORD;
3241           mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
3242         }
3243     }
3244
3245   return LIBCALL_VALUE (mode);
3246 }
3247
3248 static int
3249 libcall_eq (const void *p1, const void *p2)
3250 {
3251   return rtx_equal_p ((const_rtx) p1, (const_rtx) p2);
3252 }
3253
3254 static hashval_t
3255 libcall_hash (const void *p1)
3256 {
3257   return hash_rtx ((const_rtx) p1, VOIDmode, NULL, NULL, FALSE);
3258 }
3259
3260 static void
3261 add_libcall (htab_t htab, rtx libcall)
3262 {
3263   *htab_find_slot (htab, libcall, INSERT) = libcall;
3264 }
3265
3266 static bool
3267 arm_libcall_uses_aapcs_base (const_rtx libcall)
3268 {
3269   static bool init_done = false;
3270   static htab_t libcall_htab;
3271
3272   if (!init_done)
3273     {
3274       init_done = true;
3275
3276       libcall_htab = htab_create (31, libcall_hash, libcall_eq,
3277                                   NULL);
3278       add_libcall (libcall_htab,
3279                    convert_optab_libfunc (sfloat_optab, SFmode, SImode));
3280       add_libcall (libcall_htab,
3281                    convert_optab_libfunc (sfloat_optab, DFmode, SImode));
3282       add_libcall (libcall_htab,
3283                    convert_optab_libfunc (sfloat_optab, SFmode, DImode));
3284       add_libcall (libcall_htab,
3285                    convert_optab_libfunc (sfloat_optab, DFmode, DImode));
3286       
3287       add_libcall (libcall_htab,
3288                    convert_optab_libfunc (ufloat_optab, SFmode, SImode));
3289       add_libcall (libcall_htab,
3290                    convert_optab_libfunc (ufloat_optab, DFmode, SImode));
3291       add_libcall (libcall_htab,
3292                    convert_optab_libfunc (ufloat_optab, SFmode, DImode));
3293       add_libcall (libcall_htab,
3294                    convert_optab_libfunc (ufloat_optab, DFmode, DImode));
3295
3296       add_libcall (libcall_htab,
3297                    convert_optab_libfunc (sext_optab, SFmode, HFmode));
3298       add_libcall (libcall_htab,
3299                    convert_optab_libfunc (trunc_optab, HFmode, SFmode));
3300       add_libcall (libcall_htab,
3301                    convert_optab_libfunc (sfix_optab, DImode, DFmode));
3302       add_libcall (libcall_htab,
3303                    convert_optab_libfunc (ufix_optab, DImode, DFmode));
3304       add_libcall (libcall_htab,
3305                    convert_optab_libfunc (sfix_optab, DImode, SFmode));
3306       add_libcall (libcall_htab,
3307                    convert_optab_libfunc (ufix_optab, DImode, SFmode));
3308     }
3309
3310   return libcall && htab_find (libcall_htab, libcall) != NULL;
3311 }
3312
3313 rtx
3314 arm_libcall_value (enum machine_mode mode, const_rtx libcall)
3315 {
3316   if (TARGET_AAPCS_BASED && arm_pcs_default != ARM_PCS_AAPCS
3317       && GET_MODE_CLASS (mode) == MODE_FLOAT)
3318     {
3319       /* The following libcalls return their result in integer registers,
3320          even though they return a floating point value.  */
3321       if (arm_libcall_uses_aapcs_base (libcall))
3322         return gen_rtx_REG (mode, ARG_REGISTER(1));
3323
3324     }
3325
3326   return LIBCALL_VALUE (mode);
3327 }
3328
3329 /* Determine the amount of memory needed to store the possible return
3330    registers of an untyped call.  */
3331 int
3332 arm_apply_result_size (void)
3333 {
3334   int size = 16;
3335
3336   if (TARGET_32BIT)
3337     {
3338       if (TARGET_HARD_FLOAT_ABI)
3339         {
3340           if (TARGET_VFP)
3341             size += 32;
3342           if (TARGET_FPA)
3343             size += 12;
3344           if (TARGET_MAVERICK)
3345             size += 8;
3346         }
3347       if (TARGET_IWMMXT_ABI)
3348         size += 8;
3349     }
3350
3351   return size;
3352 }
3353
3354 /* Decide whether TYPE should be returned in memory (true)
3355    or in a register (false).  FNTYPE is the type of the function making
3356    the call.  */
3357 static bool
3358 arm_return_in_memory (const_tree type, const_tree fntype)
3359 {
3360   HOST_WIDE_INT size;
3361
3362   size = int_size_in_bytes (type);  /* Negative if not fixed size.  */
3363
3364   if (TARGET_AAPCS_BASED)
3365     {
3366       /* Simple, non-aggregate types (ie not including vectors and
3367          complex) are always returned in a register (or registers).
3368          We don't care about which register here, so we can short-cut
3369          some of the detail.  */
3370       if (!AGGREGATE_TYPE_P (type)
3371           && TREE_CODE (type) != VECTOR_TYPE
3372           && TREE_CODE (type) != COMPLEX_TYPE)
3373         return false;
3374
3375       /* Any return value that is no larger than one word can be
3376          returned in r0.  */
3377       if (((unsigned HOST_WIDE_INT) size) <= UNITS_PER_WORD)
3378         return false;
3379
3380       /* Check any available co-processors to see if they accept the
3381          type as a register candidate (VFP, for example, can return
3382          some aggregates in consecutive registers).  These aren't
3383          available if the call is variadic.  */
3384       if (aapcs_select_return_coproc (type, fntype) >= 0)
3385         return false;
3386
3387       /* Vector values should be returned using ARM registers, not
3388          memory (unless they're over 16 bytes, which will break since
3389          we only have four call-clobbered registers to play with).  */
3390       if (TREE_CODE (type) == VECTOR_TYPE)
3391         return (size < 0 || size > (4 * UNITS_PER_WORD));
3392
3393       /* The rest go in memory.  */
3394       return true;
3395     }
3396
3397   if (TREE_CODE (type) == VECTOR_TYPE)
3398     return (size < 0 || size > (4 * UNITS_PER_WORD));
3399
3400   if (!AGGREGATE_TYPE_P (type) &&
3401       (TREE_CODE (type) != VECTOR_TYPE))
3402     /* All simple types are returned in registers.  */
3403     return false;
3404
3405   if (arm_abi != ARM_ABI_APCS)
3406     {
3407       /* ATPCS and later return aggregate types in memory only if they are
3408          larger than a word (or are variable size).  */
3409       return (size < 0 || size > UNITS_PER_WORD);
3410     }
3411
3412   /* For the arm-wince targets we choose to be compatible with Microsoft's
3413      ARM and Thumb compilers, which always return aggregates in memory.  */
3414 #ifndef ARM_WINCE
3415   /* All structures/unions bigger than one word are returned in memory.
3416      Also catch the case where int_size_in_bytes returns -1.  In this case
3417      the aggregate is either huge or of variable size, and in either case
3418      we will want to return it via memory and not in a register.  */
3419   if (size < 0 || size > UNITS_PER_WORD)
3420     return true;
3421
3422   if (TREE_CODE (type) == RECORD_TYPE)
3423     {
3424       tree field;
3425
3426       /* For a struct the APCS says that we only return in a register
3427          if the type is 'integer like' and every addressable element
3428          has an offset of zero.  For practical purposes this means
3429          that the structure can have at most one non bit-field element
3430          and that this element must be the first one in the structure.  */
3431
3432       /* Find the first field, ignoring non FIELD_DECL things which will
3433          have been created by C++.  */
3434       for (field = TYPE_FIELDS (type);
3435            field && TREE_CODE (field) != FIELD_DECL;
3436            field = TREE_CHAIN (field))
3437         continue;
3438
3439       if (field == NULL)
3440         return false; /* An empty structure.  Allowed by an extension to ANSI C.  */
3441
3442       /* Check that the first field is valid for returning in a register.  */
3443
3444       /* ... Floats are not allowed */
3445       if (FLOAT_TYPE_P (TREE_TYPE (field)))
3446         return true;
3447
3448       /* ... Aggregates that are not themselves valid for returning in
3449          a register are not allowed.  */
3450       if (arm_return_in_memory (TREE_TYPE (field), NULL_TREE))
3451         return true;
3452
3453       /* Now check the remaining fields, if any.  Only bitfields are allowed,
3454          since they are not addressable.  */
3455       for (field = TREE_CHAIN (field);
3456            field;
3457            field = TREE_CHAIN (field))
3458         {
3459           if (TREE_CODE (field) != FIELD_DECL)
3460             continue;
3461
3462           if (!DECL_BIT_FIELD_TYPE (field))
3463             return true;
3464         }
3465
3466       return false;
3467     }
3468
3469   if (TREE_CODE (type) == UNION_TYPE)
3470     {
3471       tree field;
3472
3473       /* Unions can be returned in registers if every element is
3474          integral, or can be returned in an integer register.  */
3475       for (field = TYPE_FIELDS (type);
3476            field;
3477            field = TREE_CHAIN (field))
3478         {
3479           if (TREE_CODE (field) != FIELD_DECL)
3480             continue;
3481
3482           if (FLOAT_TYPE_P (TREE_TYPE (field)))
3483             return true;
3484
3485           if (arm_return_in_memory (TREE_TYPE (field), NULL_TREE))
3486             return true;
3487         }
3488
3489       return false;
3490     }
3491 #endif /* not ARM_WINCE */
3492
3493   /* Return all other types in memory.  */
3494   return true;
3495 }
3496
3497 /* Indicate whether or not words of a double are in big-endian order.  */
3498
3499 int
3500 arm_float_words_big_endian (void)
3501 {
3502   if (TARGET_MAVERICK)
3503     return 0;
3504
3505   /* For FPA, float words are always big-endian.  For VFP, floats words
3506      follow the memory system mode.  */
3507
3508   if (TARGET_FPA)
3509     {
3510       return 1;
3511     }
3512
3513   if (TARGET_VFP)
3514     return (TARGET_BIG_END ? 1 : 0);
3515
3516   return 1;
3517 }
3518
3519 const struct pcs_attribute_arg
3520 {
3521   const char *arg;
3522   enum arm_pcs value;
3523 } pcs_attribute_args[] =
3524   {
3525     {"aapcs", ARM_PCS_AAPCS},
3526     {"aapcs-vfp", ARM_PCS_AAPCS_VFP},
3527 #if 0
3528     /* We could recognize these, but changes would be needed elsewhere
3529      * to implement them.  */
3530     {"aapcs-iwmmxt", ARM_PCS_AAPCS_IWMMXT},
3531     {"atpcs", ARM_PCS_ATPCS},
3532     {"apcs", ARM_PCS_APCS},
3533 #endif
3534     {NULL, ARM_PCS_UNKNOWN}
3535   };
3536
3537 static enum arm_pcs
3538 arm_pcs_from_attribute (tree attr)
3539 {
3540   const struct pcs_attribute_arg *ptr;
3541   const char *arg;
3542
3543   /* Get the value of the argument.  */
3544   if (TREE_VALUE (attr) == NULL_TREE
3545       || TREE_CODE (TREE_VALUE (attr)) != STRING_CST)
3546     return ARM_PCS_UNKNOWN;
3547
3548   arg = TREE_STRING_POINTER (TREE_VALUE (attr));
3549
3550   /* Check it against the list of known arguments.  */
3551   for (ptr = pcs_attribute_args; ptr->arg != NULL; ptr++)
3552     if (streq (arg, ptr->arg))
3553       return ptr->value;
3554
3555   /* An unrecognized interrupt type.  */
3556   return ARM_PCS_UNKNOWN;
3557 }
3558
3559 /* Get the PCS variant to use for this call.  TYPE is the function's type
3560    specification, DECL is the specific declartion.  DECL may be null if
3561    the call could be indirect or if this is a library call.  */
3562 static enum arm_pcs
3563 arm_get_pcs_model (const_tree type, const_tree decl)
3564 {
3565   bool user_convention = false;
3566   enum arm_pcs user_pcs = arm_pcs_default;
3567   tree attr;
3568
3569   gcc_assert (type);
3570
3571   attr = lookup_attribute ("pcs", TYPE_ATTRIBUTES (type));
3572   if (attr)
3573     {
3574       user_pcs = arm_pcs_from_attribute (TREE_VALUE (attr));
3575       user_convention = true;
3576     }
3577
3578   if (TARGET_AAPCS_BASED)
3579     {
3580       /* Detect varargs functions.  These always use the base rules
3581          (no argument is ever a candidate for a co-processor
3582          register).  */
3583       bool base_rules = (TYPE_ARG_TYPES (type) != 0
3584                          && (TREE_VALUE (tree_last (TYPE_ARG_TYPES (type)))
3585                              != void_type_node));
3586       
3587       if (user_convention)
3588         {
3589           if (user_pcs > ARM_PCS_AAPCS_LOCAL)
3590             sorry ("Non-AAPCS derived PCS variant");
3591           else if (base_rules && user_pcs != ARM_PCS_AAPCS)
3592             error ("Variadic functions must use the base AAPCS variant");
3593         }
3594
3595       if (base_rules)
3596         return ARM_PCS_AAPCS;
3597       else if (user_convention)
3598         return user_pcs;
3599       else if (decl && flag_unit_at_a_time)
3600         {
3601           /* Local functions never leak outside this compilation unit,
3602              so we are free to use whatever conventions are
3603              appropriate.  */
3604           /* FIXME: remove CONST_CAST_TREE when cgraph is constified.  */
3605           struct cgraph_local_info *i = cgraph_local_info (CONST_CAST_TREE(decl));
3606           if (i && i->local)
3607             return ARM_PCS_AAPCS_LOCAL;
3608         }
3609     }
3610   else if (user_convention && user_pcs != arm_pcs_default)
3611     sorry ("PCS variant");
3612
3613   /* For everything else we use the target's default.  */
3614   return arm_pcs_default;
3615 }
3616
3617
3618 static void
3619 aapcs_vfp_cum_init (CUMULATIVE_ARGS *pcum  ATTRIBUTE_UNUSED,
3620                     const_tree fntype ATTRIBUTE_UNUSED,
3621                     rtx libcall ATTRIBUTE_UNUSED, 
3622                     const_tree fndecl ATTRIBUTE_UNUSED)
3623 {
3624   /* Record the unallocated VFP registers.  */
3625   pcum->aapcs_vfp_regs_free = (1 << NUM_VFP_ARG_REGS) - 1;
3626   pcum->aapcs_vfp_reg_alloc = 0;
3627 }
3628
3629 /* Walk down the type tree of TYPE counting consecutive base elements.
3630    If *MODEP is VOIDmode, then set it to the first valid floating point
3631    type.  If a non-floating point type is found, or if a floating point
3632    type that doesn't match a non-VOIDmode *MODEP is found, then return -1,
3633    otherwise return the count in the sub-tree.  */
3634 static int
3635 aapcs_vfp_sub_candidate (const_tree type, enum machine_mode *modep)
3636 {
3637   enum machine_mode mode;
3638   HOST_WIDE_INT size;
3639
3640   switch (TREE_CODE (type))
3641     {
3642     case REAL_TYPE:
3643       mode = TYPE_MODE (type);
3644       if (mode != DFmode && mode != SFmode)
3645         return -1;
3646
3647       if (*modep == VOIDmode)
3648         *modep = mode;
3649
3650       if (*modep == mode)
3651         return 1;
3652
3653       break;
3654
3655     case COMPLEX_TYPE:
3656       mode = TYPE_MODE (TREE_TYPE (type));
3657       if (mode != DFmode && mode != SFmode)
3658         return -1;
3659
3660       if (*modep == VOIDmode)
3661         *modep = mode;
3662
3663       if (*modep == mode)
3664         return 2;
3665
3666       break;
3667
3668     case VECTOR_TYPE:
3669       /* Use V2SImode and V4SImode as representatives of all 64-bit
3670          and 128-bit vector types, whether or not those modes are
3671          supported with the present options.  */
3672       size = int_size_in_bytes (type);
3673       switch (size)
3674         {
3675         case 8:
3676           mode = V2SImode;
3677           break;
3678         case 16:
3679           mode = V4SImode;
3680           break;
3681         default:
3682           return -1;
3683         }
3684
3685       if (*modep == VOIDmode)
3686         *modep = mode;
3687
3688       /* Vector modes are considered to be opaque: two vectors are
3689          equivalent for the purposes of being homogeneous aggregates
3690          if they are the same size.  */
3691       if (*modep == mode)
3692         return 1;
3693
3694       break;
3695
3696     case ARRAY_TYPE:
3697       {
3698         int count;
3699         tree index = TYPE_DOMAIN (type);
3700
3701         /* Can't handle incomplete types.  */
3702         if (!COMPLETE_TYPE_P(type))
3703           return -1;
3704
3705         count = aapcs_vfp_sub_candidate (TREE_TYPE (type), modep);
3706         if (count == -1
3707             || !index
3708             || !TYPE_MAX_VALUE (index)
3709             || !host_integerp (TYPE_MAX_VALUE (index), 1)
3710             || !TYPE_MIN_VALUE (index)
3711             || !host_integerp (TYPE_MIN_VALUE (index), 1)
3712             || count < 0)
3713           return -1;
3714
3715         count *= (1 + tree_low_cst (TYPE_MAX_VALUE (index), 1)
3716                       - tree_low_cst (TYPE_MIN_VALUE (index), 1));
3717
3718         /* There must be no padding.  */
3719         if (!host_integerp (TYPE_SIZE (type), 1)
3720             || (tree_low_cst (TYPE_SIZE (type), 1)
3721                 != count * GET_MODE_BITSIZE (*modep)))
3722           return -1;
3723
3724         return count;
3725       }
3726       
3727     case RECORD_TYPE:
3728       {
3729         int count = 0;
3730         int sub_count;
3731         tree field;
3732
3733         /* Can't handle incomplete types.  */
3734         if (!COMPLETE_TYPE_P(type))
3735           return -1;
3736
3737         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3738           {
3739             if (TREE_CODE (field) != FIELD_DECL)
3740               continue;
3741
3742             sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep);
3743             if (sub_count < 0)
3744               return -1;
3745             count += sub_count;
3746           }
3747
3748         /* There must be no padding.  */
3749         if (!host_integerp (TYPE_SIZE (type), 1)
3750             || (tree_low_cst (TYPE_SIZE (type), 1)
3751                 != count * GET_MODE_BITSIZE (*modep)))
3752           return -1;
3753
3754         return count;
3755       }
3756
3757     case UNION_TYPE:
3758     case QUAL_UNION_TYPE:
3759       {
3760         /* These aren't very interesting except in a degenerate case.  */
3761         int count = 0;
3762         int sub_count;
3763         tree field;
3764
3765         /* Can't handle incomplete types.  */
3766         if (!COMPLETE_TYPE_P(type))
3767           return -1;
3768
3769         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
3770           {
3771             if (TREE_CODE (field) != FIELD_DECL)
3772               continue;
3773
3774             sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep);
3775             if (sub_count < 0)
3776               return -1;
3777             count = count > sub_count ? count : sub_count;
3778           }
3779
3780         /* There must be no padding.  */
3781         if (!host_integerp (TYPE_SIZE (type), 1)
3782             || (tree_low_cst (TYPE_SIZE (type), 1)
3783                 != count * GET_MODE_BITSIZE (*modep)))
3784           return -1;
3785
3786         return count;
3787       }
3788
3789     default:
3790       break;
3791     }
3792
3793   return -1;
3794 }
3795
3796 static bool
3797 aapcs_vfp_is_call_or_return_candidate (enum machine_mode mode, const_tree type,
3798                                        enum machine_mode *base_mode,
3799                                        int *count)
3800 {
3801   if (GET_MODE_CLASS (mode) == MODE_FLOAT
3802       || GET_MODE_CLASS (mode) == MODE_VECTOR_INT
3803       || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
3804     {
3805       *count = 1;
3806       *base_mode = mode;
3807       return true;
3808     }
3809   else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
3810     {
3811       *count = 2;
3812       *base_mode = (mode == DCmode ? DFmode : SFmode);
3813       return true;
3814     }
3815   else if (type && (mode == BLKmode || TREE_CODE (type) == VECTOR_TYPE))
3816     {
3817       enum machine_mode aggregate_mode = VOIDmode;
3818       int ag_count = aapcs_vfp_sub_candidate (type, &aggregate_mode);
3819
3820       if (ag_count > 0 && ag_count <= 4)
3821         {
3822           *count = ag_count;
3823           *base_mode = aggregate_mode;
3824           return true;
3825         }
3826     }
3827   return false;
3828 }
3829
3830 static bool
3831 aapcs_vfp_is_return_candidate (enum arm_pcs pcs_variant,
3832                                enum machine_mode mode, const_tree type)
3833 {
3834   int count ATTRIBUTE_UNUSED;
3835   enum machine_mode ag_mode ATTRIBUTE_UNUSED;
3836
3837   if (!(pcs_variant == ARM_PCS_AAPCS_VFP
3838         || (pcs_variant == ARM_PCS_AAPCS_LOCAL
3839             && TARGET_32BIT && TARGET_VFP && TARGET_HARD_FLOAT)))
3840     return false;
3841   return aapcs_vfp_is_call_or_return_candidate (mode, type, &ag_mode, &count);
3842 }
3843
3844 static bool
3845 aapcs_vfp_is_call_candidate (CUMULATIVE_ARGS *pcum, enum machine_mode mode, 
3846                              const_tree type)
3847 {
3848   if (!(pcum->pcs_variant == ARM_PCS_AAPCS_VFP
3849         || (pcum->pcs_variant == ARM_PCS_AAPCS_LOCAL
3850             && TARGET_32BIT && TARGET_VFP && TARGET_HARD_FLOAT)))
3851     return false;
3852   return aapcs_vfp_is_call_or_return_candidate (mode, type,
3853                                                 &pcum->aapcs_vfp_rmode,
3854                                                 &pcum->aapcs_vfp_rcount);
3855 }
3856
3857 static bool
3858 aapcs_vfp_allocate (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
3859                     const_tree type  ATTRIBUTE_UNUSED)
3860 {
3861   int shift = GET_MODE_SIZE (pcum->aapcs_vfp_rmode) / GET_MODE_SIZE (SFmode);
3862   unsigned mask = (1 << (shift * pcum->aapcs_vfp_rcount)) - 1;
3863   int regno;
3864   
3865   for (regno = 0; regno < NUM_VFP_ARG_REGS; regno += shift)
3866     if (((pcum->aapcs_vfp_regs_free >> regno) & mask) == mask)
3867       {
3868         pcum->aapcs_vfp_reg_alloc = mask << regno;
3869         if (mode == BLKmode || (mode == TImode && !TARGET_NEON))
3870           {
3871             int i;
3872             int rcount = pcum->aapcs_vfp_rcount;
3873             int rshift = shift;
3874             enum machine_mode rmode = pcum->aapcs_vfp_rmode;
3875             rtx par;
3876             if (!TARGET_NEON)
3877               {
3878                 /* Avoid using unsupported vector modes.  */
3879                 if (rmode == V2SImode)
3880                   rmode = DImode;
3881                 else if (rmode == V4SImode)
3882                   {
3883                     rmode = DImode;
3884                     rcount *= 2;
3885                     rshift /= 2;
3886                   }
3887               }
3888             par = gen_rtx_PARALLEL (mode, rtvec_alloc (rcount));
3889             for (i = 0; i < rcount; i++)
3890               {
3891                 rtx tmp = gen_rtx_REG (rmode, 
3892                                        FIRST_VFP_REGNUM + regno + i * rshift);
3893                 tmp = gen_rtx_EXPR_LIST
3894                   (VOIDmode, tmp, 
3895                    GEN_INT (i * GET_MODE_SIZE (rmode)));
3896                 XVECEXP (par, 0, i) = tmp;
3897               }
3898
3899             pcum->aapcs_reg = par;
3900           }
3901         else
3902           pcum->aapcs_reg = gen_rtx_REG (mode, FIRST_VFP_REGNUM + regno);
3903         return true;
3904       }
3905   return false;
3906 }
3907
3908 static rtx
3909 aapcs_vfp_allocate_return_reg (enum arm_pcs pcs_variant ATTRIBUTE_UNUSED,
3910                                enum machine_mode mode,
3911                                const_tree type ATTRIBUTE_UNUSED)
3912 {
3913   if (!(pcs_variant == ARM_PCS_AAPCS_VFP
3914         || (pcs_variant == ARM_PCS_AAPCS_LOCAL
3915             && TARGET_32BIT && TARGET_VFP && TARGET_HARD_FLOAT)))
3916     return false;
3917   if (mode == BLKmode || (mode == TImode && !TARGET_NEON))
3918     {
3919       int count;
3920       enum machine_mode ag_mode;
3921       int i;
3922       rtx par;
3923       int shift;
3924       
3925       aapcs_vfp_is_call_or_return_candidate (mode, type, &ag_mode, &count);
3926
3927       if (!TARGET_NEON)
3928         {
3929           if (ag_mode == V2SImode)
3930             ag_mode = DImode;
3931           else if (ag_mode == V4SImode)
3932             {
3933               ag_mode = DImode;
3934               count *= 2;
3935             }
3936         }
3937       shift = GET_MODE_SIZE(ag_mode) / GET_MODE_SIZE(SFmode);
3938       par = gen_rtx_PARALLEL (mode, rtvec_alloc (count));
3939       for (i = 0; i < count; i++)
3940         {
3941           rtx tmp = gen_rtx_REG (ag_mode, FIRST_VFP_REGNUM + i * shift);
3942           tmp = gen_rtx_EXPR_LIST (VOIDmode, tmp, 
3943                                    GEN_INT (i * GET_MODE_SIZE (ag_mode)));
3944           XVECEXP (par, 0, i) = tmp;
3945         }
3946
3947       return par;
3948     }
3949
3950   return gen_rtx_REG (mode, FIRST_VFP_REGNUM);
3951 }
3952
3953 static void
3954 aapcs_vfp_advance (CUMULATIVE_ARGS *pcum  ATTRIBUTE_UNUSED,
3955                    enum machine_mode mode  ATTRIBUTE_UNUSED,
3956                    const_tree type  ATTRIBUTE_UNUSED)
3957 {
3958   pcum->aapcs_vfp_regs_free &= ~pcum->aapcs_vfp_reg_alloc;
3959   pcum->aapcs_vfp_reg_alloc = 0;
3960   return;
3961 }
3962
3963 #define AAPCS_CP(X)                             \
3964   {                                             \
3965     aapcs_ ## X ## _cum_init,                   \
3966     aapcs_ ## X ## _is_call_candidate,          \
3967     aapcs_ ## X ## _allocate,                   \
3968     aapcs_ ## X ## _is_return_candidate,        \
3969     aapcs_ ## X ## _allocate_return_reg,        \
3970     aapcs_ ## X ## _advance                     \
3971   }
3972
3973 /* Table of co-processors that can be used to pass arguments in
3974    registers.  Idealy no arugment should be a candidate for more than
3975    one co-processor table entry, but the table is processed in order
3976    and stops after the first match.  If that entry then fails to put
3977    the argument into a co-processor register, the argument will go on
3978    the stack.  */
3979 static struct 
3980 {
3981   /* Initialize co-processor related state in CUMULATIVE_ARGS structure.  */
3982   void (*cum_init) (CUMULATIVE_ARGS *, const_tree, rtx, const_tree);
3983
3984   /* Return true if an argument of mode MODE (or type TYPE if MODE is
3985      BLKmode) is a candidate for this co-processor's registers; this
3986      function should ignore any position-dependent state in
3987      CUMULATIVE_ARGS and only use call-type dependent information.  */
3988   bool (*is_call_candidate) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
3989
3990   /* Return true if the argument does get a co-processor register; it
3991      should set aapcs_reg to an RTX of the register allocated as is
3992      required for a return from FUNCTION_ARG.  */
3993   bool (*allocate) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
3994
3995   /* Return true if a result of mode MODE (or type TYPE if MODE is
3996      BLKmode) is can be returned in this co-processor's registers.  */
3997   bool (*is_return_candidate) (enum arm_pcs, enum machine_mode, const_tree);
3998
3999   /* Allocate and return an RTX element to hold the return type of a
4000      call, this routine must not fail and will only be called if
4001      is_return_candidate returned true with the same parameters.  */
4002   rtx (*allocate_return_reg) (enum arm_pcs, enum machine_mode, const_tree);
4003
4004   /* Finish processing this argument and prepare to start processing
4005      the next one.  */
4006   void (*advance) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
4007 } aapcs_cp_arg_layout[ARM_NUM_COPROC_SLOTS] =
4008   {
4009     AAPCS_CP(vfp)
4010   };
4011
4012 #undef AAPCS_CP
4013
4014 static int
4015 aapcs_select_call_coproc (CUMULATIVE_ARGS *pcum, enum machine_mode mode, 
4016                           tree type)
4017 {
4018   int i;
4019
4020   for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4021     if (aapcs_cp_arg_layout[i].is_call_candidate (pcum, mode, type))
4022       return i;
4023
4024   return -1;
4025 }
4026
4027 static int
4028 aapcs_select_return_coproc (const_tree type, const_tree fntype)
4029 {
4030   /* We aren't passed a decl, so we can't check that a call is local.
4031      However, it isn't clear that that would be a win anyway, since it
4032      might limit some tail-calling opportunities.  */
4033   enum arm_pcs pcs_variant;
4034
4035   if (fntype)
4036     {
4037       const_tree fndecl = NULL_TREE;
4038
4039       if (TREE_CODE (fntype) == FUNCTION_DECL)
4040         {
4041           fndecl = fntype;
4042           fntype = TREE_TYPE (fntype);
4043         }
4044
4045       pcs_variant = arm_get_pcs_model (fntype, fndecl);
4046     }
4047   else
4048     pcs_variant = arm_pcs_default;
4049
4050   if (pcs_variant != ARM_PCS_AAPCS)
4051     {
4052       int i;
4053
4054       for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4055         if (aapcs_cp_arg_layout[i].is_return_candidate (pcs_variant, 
4056                                                         TYPE_MODE (type),
4057                                                         type))
4058           return i;
4059     }
4060   return -1;
4061 }
4062
4063 static rtx
4064 aapcs_allocate_return_reg (enum machine_mode mode, const_tree type,
4065                            const_tree fntype)
4066 {
4067   /* We aren't passed a decl, so we can't check that a call is local.
4068      However, it isn't clear that that would be a win anyway, since it
4069      might limit some tail-calling opportunities.  */
4070   enum arm_pcs pcs_variant;
4071   int unsignedp ATTRIBUTE_UNUSED;
4072
4073   if (fntype)
4074     {
4075       const_tree fndecl = NULL_TREE;
4076
4077       if (TREE_CODE (fntype) == FUNCTION_DECL)
4078         {
4079           fndecl = fntype;
4080           fntype = TREE_TYPE (fntype);
4081         }
4082
4083       pcs_variant = arm_get_pcs_model (fntype, fndecl);
4084     }
4085   else
4086     pcs_variant = arm_pcs_default;
4087
4088   /* Promote integer types.  */
4089   if (type && INTEGRAL_TYPE_P (type))
4090     mode = arm_promote_function_mode (type, mode, &unsignedp, fntype, 1);
4091
4092   if (pcs_variant != ARM_PCS_AAPCS)
4093     {
4094       int i;
4095
4096       for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4097         if (aapcs_cp_arg_layout[i].is_return_candidate (pcs_variant, mode,
4098                                                         type))
4099           return aapcs_cp_arg_layout[i].allocate_return_reg (pcs_variant,
4100                                                              mode, type);
4101     }
4102
4103   /* Promotes small structs returned in a register to full-word size
4104      for big-endian AAPCS.  */
4105   if (type && arm_return_in_msb (type))
4106     {
4107       HOST_WIDE_INT size = int_size_in_bytes (type);
4108       if (size % UNITS_PER_WORD != 0)
4109         {
4110           size += UNITS_PER_WORD - size % UNITS_PER_WORD;
4111           mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
4112         }
4113     }
4114
4115   return gen_rtx_REG (mode, R0_REGNUM);
4116 }
4117
4118 rtx
4119 aapcs_libcall_value (enum machine_mode mode)
4120 {
4121   return aapcs_allocate_return_reg (mode, NULL_TREE, NULL_TREE);
4122 }
4123
4124 /* Lay out a function argument using the AAPCS rules.  The rule
4125    numbers referred to here are those in the AAPCS.  */
4126 static void
4127 aapcs_layout_arg (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4128                   tree type, int named)
4129 {
4130   int nregs, nregs2;
4131   int ncrn;
4132
4133   /* We only need to do this once per argument.  */
4134   if (pcum->aapcs_arg_processed)
4135     return;
4136
4137   pcum->aapcs_arg_processed = true;
4138
4139   /* Special case: if named is false then we are handling an incoming
4140      anonymous argument which is on the stack.  */
4141   if (!named)
4142     return;
4143   
4144   /* Is this a potential co-processor register candidate?  */
4145   if (pcum->pcs_variant != ARM_PCS_AAPCS)
4146     {
4147       int slot = aapcs_select_call_coproc (pcum, mode, type);
4148       pcum->aapcs_cprc_slot = slot;
4149
4150       /* We don't have to apply any of the rules from part B of the
4151          preparation phase, these are handled elsewhere in the
4152          compiler.  */
4153
4154       if (slot >= 0)
4155         {
4156           /* A Co-processor register candidate goes either in its own
4157              class of registers or on the stack.  */
4158           if (!pcum->aapcs_cprc_failed[slot])
4159             {
4160               /* C1.cp - Try to allocate the argument to co-processor
4161                  registers.  */
4162               if (aapcs_cp_arg_layout[slot].allocate (pcum, mode, type))
4163                 return;
4164
4165               /* C2.cp - Put the argument on the stack and note that we
4166                  can't assign any more candidates in this slot.  We also
4167                  need to note that we have allocated stack space, so that
4168                  we won't later try to split a non-cprc candidate between
4169                  core registers and the stack.  */
4170               pcum->aapcs_cprc_failed[slot] = true;
4171               pcum->can_split = false;
4172             }
4173
4174           /* We didn't get a register, so this argument goes on the
4175              stack.  */
4176           gcc_assert (pcum->can_split == false);
4177           return;
4178         }
4179     }
4180
4181   /* C3 - For double-word aligned arguments, round the NCRN up to the
4182      next even number.  */
4183   ncrn = pcum->aapcs_ncrn;
4184   if ((ncrn & 1) && arm_needs_doubleword_align (mode, type))
4185     ncrn++;
4186
4187   nregs = ARM_NUM_REGS2(mode, type);
4188
4189   /* Sigh, this test should really assert that nregs > 0, but a GCC
4190      extension allows empty structs and then gives them empty size; it
4191      then allows such a structure to be passed by value.  For some of
4192      the code below we have to pretend that such an argument has
4193      non-zero size so that we 'locate' it correctly either in
4194      registers or on the stack.  */
4195   gcc_assert (nregs >= 0);
4196
4197   nregs2 = nregs ? nregs : 1;
4198
4199   /* C4 - Argument fits entirely in core registers.  */
4200   if (ncrn + nregs2 <= NUM_ARG_REGS)
4201     {
4202       pcum->aapcs_reg = gen_rtx_REG (mode, ncrn);
4203       pcum->aapcs_next_ncrn = ncrn + nregs;
4204       return;
4205     }
4206
4207   /* C5 - Some core registers left and there are no arguments already
4208      on the stack: split this argument between the remaining core
4209      registers and the stack.  */
4210   if (ncrn < NUM_ARG_REGS && pcum->can_split)
4211     {
4212       pcum->aapcs_reg = gen_rtx_REG (mode, ncrn);
4213       pcum->aapcs_next_ncrn = NUM_ARG_REGS;
4214       pcum->aapcs_partial = (NUM_ARG_REGS - ncrn) * UNITS_PER_WORD;
4215       return;
4216     }
4217
4218   /* C6 - NCRN is set to 4.  */
4219   pcum->aapcs_next_ncrn = NUM_ARG_REGS;
4220
4221   /* C7,C8 - arugment goes on the stack.  We have nothing to do here.  */
4222   return;
4223 }
4224
4225 /* Initialize a variable CUM of type CUMULATIVE_ARGS
4226    for a call to a function whose data type is FNTYPE.
4227    For a library call, FNTYPE is NULL.  */
4228 void
4229 arm_init_cumulative_args (CUMULATIVE_ARGS *pcum, tree fntype,
4230                           rtx libname,
4231                           tree fndecl ATTRIBUTE_UNUSED)
4232 {
4233   /* Long call handling.  */
4234   if (fntype)
4235     pcum->pcs_variant = arm_get_pcs_model (fntype, fndecl);
4236   else
4237     pcum->pcs_variant = arm_pcs_default;
4238
4239   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4240     {
4241       if (arm_libcall_uses_aapcs_base (libname))
4242         pcum->pcs_variant = ARM_PCS_AAPCS;
4243  
4244       pcum->aapcs_ncrn = pcum->aapcs_next_ncrn = 0;
4245       pcum->aapcs_reg = NULL_RTX;
4246       pcum->aapcs_partial = 0;
4247       pcum->aapcs_arg_processed = false;
4248       pcum->aapcs_cprc_slot = -1;
4249       pcum->can_split = true;
4250
4251       if (pcum->pcs_variant != ARM_PCS_AAPCS)
4252         {
4253           int i;
4254
4255           for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4256             {
4257               pcum->aapcs_cprc_failed[i] = false;
4258               aapcs_cp_arg_layout[i].cum_init (pcum, fntype, libname, fndecl);
4259             }
4260         }
4261       return;
4262     }
4263
4264   /* Legacy ABIs */
4265
4266   /* On the ARM, the offset starts at 0.  */
4267   pcum->nregs = 0;
4268   pcum->iwmmxt_nregs = 0;
4269   pcum->can_split = true;
4270
4271   /* Varargs vectors are treated the same as long long.
4272      named_count avoids having to change the way arm handles 'named' */
4273   pcum->named_count = 0;
4274   pcum->nargs = 0;
4275
4276   if (TARGET_REALLY_IWMMXT && fntype)
4277     {
4278       tree fn_arg;
4279
4280       for (fn_arg = TYPE_ARG_TYPES (fntype);
4281            fn_arg;
4282            fn_arg = TREE_CHAIN (fn_arg))
4283         pcum->named_count += 1;
4284
4285       if (! pcum->named_count)
4286         pcum->named_count = INT_MAX;
4287     }
4288 }
4289
4290
4291 /* Return true if mode/type need doubleword alignment.  */
4292 bool
4293 arm_needs_doubleword_align (enum machine_mode mode, tree type)
4294 {
4295   return (GET_MODE_ALIGNMENT (mode) > PARM_BOUNDARY
4296           || (type && TYPE_ALIGN (type) > PARM_BOUNDARY));
4297 }
4298
4299
4300 /* Determine where to put an argument to a function.
4301    Value is zero to push the argument on the stack,
4302    or a hard register in which to store the argument.
4303
4304    MODE is the argument's machine mode.
4305    TYPE is the data type of the argument (as a tree).
4306     This is null for libcalls where that information may
4307     not be available.
4308    CUM is a variable of type CUMULATIVE_ARGS which gives info about
4309     the preceding args and about the function being called.
4310    NAMED is nonzero if this argument is a named parameter
4311     (otherwise it is an extra parameter matching an ellipsis).  */
4312
4313 rtx
4314 arm_function_arg (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4315                   tree type, int named)
4316 {
4317   int nregs;
4318
4319   /* Handle the special case quickly.  Pick an arbitrary value for op2 of
4320      a call insn (op3 of a call_value insn).  */
4321   if (mode == VOIDmode)
4322     return const0_rtx;
4323
4324   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4325     {
4326       aapcs_layout_arg (pcum, mode, type, named);
4327       return pcum->aapcs_reg;
4328     }
4329
4330   /* Varargs vectors are treated the same as long long.
4331      named_count avoids having to change the way arm handles 'named' */
4332   if (TARGET_IWMMXT_ABI
4333       && arm_vector_mode_supported_p (mode)
4334       && pcum->named_count > pcum->nargs + 1)
4335     {
4336       if (pcum->iwmmxt_nregs <= 9)
4337         return gen_rtx_REG (mode, pcum->iwmmxt_nregs + FIRST_IWMMXT_REGNUM);
4338       else
4339         {
4340           pcum->can_split = false;
4341           return NULL_RTX;
4342         }
4343     }
4344
4345   /* Put doubleword aligned quantities in even register pairs.  */
4346   if (pcum->nregs & 1
4347       && ARM_DOUBLEWORD_ALIGN
4348       && arm_needs_doubleword_align (mode, type))
4349     pcum->nregs++;
4350
4351   if (mode == VOIDmode)
4352     /* Pick an arbitrary value for operand 2 of the call insn.  */
4353     return const0_rtx;
4354
4355   /* Only allow splitting an arg between regs and memory if all preceding
4356      args were allocated to regs.  For args passed by reference we only count
4357      the reference pointer.  */
4358   if (pcum->can_split)
4359     nregs = 1;
4360   else
4361     nregs = ARM_NUM_REGS2 (mode, type);
4362
4363   if (!named || pcum->nregs + nregs > NUM_ARG_REGS)
4364     return NULL_RTX;
4365
4366   return gen_rtx_REG (mode, pcum->nregs);
4367 }
4368
4369 static int
4370 arm_arg_partial_bytes (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4371                        tree type, bool named)
4372 {
4373   int nregs = pcum->nregs;
4374
4375   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4376     {
4377       aapcs_layout_arg (pcum, mode, type, named);
4378       return pcum->aapcs_partial;
4379     }
4380
4381   if (TARGET_IWMMXT_ABI && arm_vector_mode_supported_p (mode))
4382     return 0;
4383
4384   if (NUM_ARG_REGS > nregs
4385       && (NUM_ARG_REGS < nregs + ARM_NUM_REGS2 (mode, type))
4386       && pcum->can_split)
4387     return (NUM_ARG_REGS - nregs) * UNITS_PER_WORD;
4388
4389   return 0;
4390 }
4391
4392 void
4393 arm_function_arg_advance (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4394                           tree type, bool named)
4395 {
4396   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4397     {
4398       aapcs_layout_arg (pcum, mode, type, named);
4399
4400       if (pcum->aapcs_cprc_slot >= 0)
4401         {
4402           aapcs_cp_arg_layout[pcum->aapcs_cprc_slot].advance (pcum, mode,
4403                                                               type);
4404           pcum->aapcs_cprc_slot = -1;
4405         }
4406
4407       /* Generic stuff.  */
4408       pcum->aapcs_arg_processed = false;
4409       pcum->aapcs_ncrn = pcum->aapcs_next_ncrn;
4410       pcum->aapcs_reg = NULL_RTX;
4411       pcum->aapcs_partial = 0;
4412     }
4413   else
4414     {
4415       pcum->nargs += 1;
4416       if (arm_vector_mode_supported_p (mode)
4417           && pcum->named_count > pcum->nargs
4418           && TARGET_IWMMXT_ABI)
4419         pcum->iwmmxt_nregs += 1;
4420       else
4421         pcum->nregs += ARM_NUM_REGS2 (mode, type);
4422     }
4423 }
4424
4425 /* Variable sized types are passed by reference.  This is a GCC
4426    extension to the ARM ABI.  */
4427
4428 static bool
4429 arm_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
4430                        enum machine_mode mode ATTRIBUTE_UNUSED,
4431                        const_tree type, bool named ATTRIBUTE_UNUSED)
4432 {
4433   return type && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST;
4434 }
4435 \f
4436 /* Encode the current state of the #pragma [no_]long_calls.  */
4437 typedef enum
4438 {
4439   OFF,          /* No #pragma [no_]long_calls is in effect.  */
4440   LONG,         /* #pragma long_calls is in effect.  */
4441   SHORT         /* #pragma no_long_calls is in effect.  */
4442 } arm_pragma_enum;
4443
4444 static arm_pragma_enum arm_pragma_long_calls = OFF;
4445
4446 void
4447 arm_pr_long_calls (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4448 {
4449   arm_pragma_long_calls = LONG;
4450 }
4451
4452 void
4453 arm_pr_no_long_calls (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4454 {
4455   arm_pragma_long_calls = SHORT;
4456 }
4457
4458 void
4459 arm_pr_long_calls_off (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4460 {
4461   arm_pragma_long_calls = OFF;
4462 }
4463 \f
4464 /* Handle an attribute requiring a FUNCTION_DECL;
4465    arguments as in struct attribute_spec.handler.  */
4466 static tree
4467 arm_handle_fndecl_attribute (tree *node, tree name, tree args ATTRIBUTE_UNUSED,
4468                              int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
4469 {
4470   if (TREE_CODE (*node) != FUNCTION_DECL)
4471     {
4472       warning (OPT_Wattributes, "%qE attribute only applies to functions",
4473                name);
4474       *no_add_attrs = true;
4475     }
4476
4477   return NULL_TREE;
4478 }
4479
4480 /* Handle an "interrupt" or "isr" attribute;
4481    arguments as in struct attribute_spec.handler.  */
4482 static tree
4483 arm_handle_isr_attribute (tree *node, tree name, tree args, int flags,
4484                           bool *no_add_attrs)
4485 {
4486   if (DECL_P (*node))
4487     {
4488       if (TREE_CODE (*node) != FUNCTION_DECL)
4489         {
4490           warning (OPT_Wattributes, "%qE attribute only applies to functions",
4491                    name);
4492           *no_add_attrs = true;
4493         }
4494       /* FIXME: the argument if any is checked for type attributes;
4495          should it be checked for decl ones?  */
4496     }
4497   else
4498     {
4499       if (TREE_CODE (*node) == FUNCTION_TYPE
4500           || TREE_CODE (*node) == METHOD_TYPE)
4501         {
4502           if (arm_isr_value (args) == ARM_FT_UNKNOWN)
4503             {
4504               warning (OPT_Wattributes, "%qE attribute ignored",
4505                        name);
4506               *no_add_attrs = true;
4507             }
4508         }
4509       else if (TREE_CODE (*node) == POINTER_TYPE
4510                && (TREE_CODE (TREE_TYPE (*node)) == FUNCTION_TYPE
4511                    || TREE_CODE (TREE_TYPE (*node)) == METHOD_TYPE)
4512                && arm_isr_value (args) != ARM_FT_UNKNOWN)
4513         {
4514           *node = build_variant_type_copy (*node);
4515           TREE_TYPE (*node) = build_type_attribute_variant
4516             (TREE_TYPE (*node),
4517              tree_cons (name, args, TYPE_ATTRIBUTES (TREE_TYPE (*node))));
4518           *no_add_attrs = true;
4519         }
4520       else
4521         {
4522           /* Possibly pass this attribute on from the type to a decl.  */
4523           if (flags & ((int) ATTR_FLAG_DECL_NEXT
4524                        | (int) ATTR_FLAG_FUNCTION_NEXT
4525                        | (int) ATTR_FLAG_ARRAY_NEXT))
4526             {
4527               *no_add_attrs = true;
4528               return tree_cons (name, args, NULL_TREE);
4529             }
4530           else
4531             {
4532               warning (OPT_Wattributes, "%qE attribute ignored",
4533                        name);
4534             }
4535         }
4536     }
4537
4538   return NULL_TREE;
4539 }
4540
4541 /* Handle a "pcs" attribute; arguments as in struct
4542    attribute_spec.handler.  */
4543 static tree
4544 arm_handle_pcs_attribute (tree *node ATTRIBUTE_UNUSED, tree name, tree args,
4545                           int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
4546 {
4547   if (arm_pcs_from_attribute (args) == ARM_PCS_UNKNOWN)
4548     {
4549       warning (OPT_Wattributes, "%qE attribute ignored", name);
4550       *no_add_attrs = true;
4551     }
4552   return NULL_TREE;
4553 }
4554
4555 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
4556 /* Handle the "notshared" attribute.  This attribute is another way of
4557    requesting hidden visibility.  ARM's compiler supports
4558    "__declspec(notshared)"; we support the same thing via an
4559    attribute.  */
4560
4561 static tree
4562 arm_handle_notshared_attribute (tree *node,
4563                                 tree name ATTRIBUTE_UNUSED,
4564                                 tree args ATTRIBUTE_UNUSED,
4565                                 int flags ATTRIBUTE_UNUSED,
4566                                 bool *no_add_attrs)
4567 {
4568   tree decl = TYPE_NAME (*node);
4569
4570   if (decl)
4571     {
4572       DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
4573       DECL_VISIBILITY_SPECIFIED (decl) = 1;
4574       *no_add_attrs = false;
4575     }
4576   return NULL_TREE;
4577 }
4578 #endif
4579
4580 /* Return 0 if the attributes for two types are incompatible, 1 if they
4581    are compatible, and 2 if they are nearly compatible (which causes a
4582    warning to be generated).  */
4583 static int
4584 arm_comp_type_attributes (const_tree type1, const_tree type2)
4585 {
4586   int l1, l2, s1, s2;
4587
4588   /* Check for mismatch of non-default calling convention.  */
4589   if (TREE_CODE (type1) != FUNCTION_TYPE)
4590     return 1;
4591
4592   /* Check for mismatched call attributes.  */
4593   l1 = lookup_attribute ("long_call", TYPE_ATTRIBUTES (type1)) != NULL;
4594   l2 = lookup_attribute ("long_call", TYPE_ATTRIBUTES (type2)) != NULL;
4595   s1 = lookup_attribute ("short_call", TYPE_ATTRIBUTES (type1)) != NULL;
4596   s2 = lookup_attribute ("short_call", TYPE_ATTRIBUTES (type2)) != NULL;
4597
4598   /* Only bother to check if an attribute is defined.  */
4599   if (l1 | l2 | s1 | s2)
4600     {
4601       /* If one type has an attribute, the other must have the same attribute.  */
4602       if ((l1 != l2) || (s1 != s2))
4603         return 0;
4604
4605       /* Disallow mixed attributes.  */
4606       if ((l1 & s2) || (l2 & s1))
4607         return 0;
4608     }
4609
4610   /* Check for mismatched ISR attribute.  */
4611   l1 = lookup_attribute ("isr", TYPE_ATTRIBUTES (type1)) != NULL;
4612   if (! l1)
4613     l1 = lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type1)) != NULL;
4614   l2 = lookup_attribute ("isr", TYPE_ATTRIBUTES (type2)) != NULL;
4615   if (! l2)
4616     l1 = lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type2)) != NULL;
4617   if (l1 != l2)
4618     return 0;
4619
4620   return 1;
4621 }
4622
4623 /*  Assigns default attributes to newly defined type.  This is used to
4624     set short_call/long_call attributes for function types of
4625     functions defined inside corresponding #pragma scopes.  */
4626 static void
4627 arm_set_default_type_attributes (tree type)
4628 {
4629   /* Add __attribute__ ((long_call)) to all functions, when
4630      inside #pragma long_calls or __attribute__ ((short_call)),
4631      when inside #pragma no_long_calls.  */
4632   if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE)
4633     {
4634       tree type_attr_list, attr_name;
4635       type_attr_list = TYPE_ATTRIBUTES (type);
4636
4637       if (arm_pragma_long_calls == LONG)
4638         attr_name = get_identifier ("long_call");
4639       else if (arm_pragma_long_calls == SHORT)
4640         attr_name = get_identifier ("short_call");
4641       else
4642         return;
4643
4644       type_attr_list = tree_cons (attr_name, NULL_TREE, type_attr_list);
4645       TYPE_ATTRIBUTES (type) = type_attr_list;
4646     }
4647 }
4648 \f
4649 /* Return true if DECL is known to be linked into section SECTION.  */
4650
4651 static bool
4652 arm_function_in_section_p (tree decl, section *section)
4653 {
4654   /* We can only be certain about functions defined in the same
4655      compilation unit.  */
4656   if (!TREE_STATIC (decl))
4657     return false;
4658
4659   /* Make sure that SYMBOL always binds to the definition in this
4660      compilation unit.  */
4661   if (!targetm.binds_local_p (decl))
4662     return false;
4663
4664   /* If DECL_SECTION_NAME is set, assume it is trustworthy.  */
4665   if (!DECL_SECTION_NAME (decl))
4666     {
4667       /* Make sure that we will not create a unique section for DECL.  */
4668       if (flag_function_sections || DECL_ONE_ONLY (decl))
4669         return false;
4670     }
4671
4672   return function_section (decl) == section;
4673 }
4674
4675 /* Return nonzero if a 32-bit "long_call" should be generated for
4676    a call from the current function to DECL.  We generate a long_call
4677    if the function:
4678
4679         a.  has an __attribute__((long call))
4680      or b.  is within the scope of a #pragma long_calls
4681      or c.  the -mlong-calls command line switch has been specified
4682
4683    However we do not generate a long call if the function:
4684
4685         d.  has an __attribute__ ((short_call))
4686      or e.  is inside the scope of a #pragma no_long_calls
4687      or f.  is defined in the same section as the current function.  */
4688
4689 bool
4690 arm_is_long_call_p (tree decl)
4691 {
4692   tree attrs;
4693
4694   if (!decl)
4695     return TARGET_LONG_CALLS;
4696
4697   attrs = TYPE_ATTRIBUTES (TREE_TYPE (decl));
4698   if (lookup_attribute ("short_call", attrs))
4699     return false;
4700
4701   /* For "f", be conservative, and only cater for cases in which the
4702      whole of the current function is placed in the same section.  */
4703   if (!flag_reorder_blocks_and_partition
4704       && TREE_CODE (decl) == FUNCTION_DECL
4705       && arm_function_in_section_p (decl, current_function_section ()))
4706     return false;
4707
4708   if (lookup_attribute ("long_call", attrs))
4709     return true;
4710
4711   return TARGET_LONG_CALLS;
4712 }
4713
4714 /* Return nonzero if it is ok to make a tail-call to DECL.  */
4715 static bool
4716 arm_function_ok_for_sibcall (tree decl, tree exp)
4717 {
4718   unsigned long func_type;
4719
4720   if (cfun->machine->sibcall_blocked)
4721     return false;
4722
4723   /* Never tailcall something for which we have no decl, or if we
4724      are in Thumb mode.  */
4725   if (decl == NULL || TARGET_THUMB)
4726     return false;
4727
4728   /* The PIC register is live on entry to VxWorks PLT entries, so we
4729      must make the call before restoring the PIC register.  */
4730   if (TARGET_VXWORKS_RTP && flag_pic && !targetm.binds_local_p (decl))
4731     return false;
4732
4733   /* Cannot tail-call to long calls, since these are out of range of
4734      a branch instruction.  */
4735   if (arm_is_long_call_p (decl))
4736     return false;
4737
4738   /* If we are interworking and the function is not declared static
4739      then we can't tail-call it unless we know that it exists in this
4740      compilation unit (since it might be a Thumb routine).  */
4741   if (TARGET_INTERWORK && TREE_PUBLIC (decl) && !TREE_ASM_WRITTEN (decl))
4742     return false;
4743
4744   func_type = arm_current_func_type ();
4745   /* Never tailcall from an ISR routine - it needs a special exit sequence.  */
4746   if (IS_INTERRUPT (func_type))
4747     return false;
4748
4749   if (!VOID_TYPE_P (TREE_TYPE (DECL_RESULT (cfun->decl))))
4750     {
4751       /* Check that the return value locations are the same.  For
4752          example that we aren't returning a value from the sibling in
4753          a VFP register but then need to transfer it to a core
4754          register.  */
4755       rtx a, b;
4756
4757       a = arm_function_value (TREE_TYPE (exp), decl, false);
4758       b = arm_function_value (TREE_TYPE (DECL_RESULT (cfun->decl)),
4759                               cfun->decl, false);
4760       if (!rtx_equal_p (a, b))
4761         return false;
4762     }
4763
4764   /* Never tailcall if function may be called with a misaligned SP.  */
4765   if (IS_STACKALIGN (func_type))
4766     return false;
4767
4768   /* Everything else is ok.  */
4769   return true;
4770 }
4771
4772 \f
4773 /* Addressing mode support functions.  */
4774
4775 /* Return nonzero if X is a legitimate immediate operand when compiling
4776    for PIC.  We know that X satisfies CONSTANT_P and flag_pic is true.  */
4777 int
4778 legitimate_pic_operand_p (rtx x)
4779 {
4780   if (GET_CODE (x) == SYMBOL_REF
4781       || (GET_CODE (x) == CONST
4782           && GET_CODE (XEXP (x, 0)) == PLUS
4783           && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF))
4784     return 0;
4785
4786   return 1;
4787 }
4788
4789 /* Record that the current function needs a PIC register.  Initialize
4790    cfun->machine->pic_reg if we have not already done so.  */
4791
4792 static void
4793 require_pic_register (void)
4794 {
4795   /* A lot of the logic here is made obscure by the fact that this
4796      routine gets called as part of the rtx cost estimation process.
4797      We don't want those calls to affect any assumptions about the real
4798      function; and further, we can't call entry_of_function() until we
4799      start the real expansion process.  */
4800   if (!crtl->uses_pic_offset_table)
4801     {
4802       gcc_assert (can_create_pseudo_p ());
4803       if (arm_pic_register != INVALID_REGNUM)
4804         {
4805           if (!cfun->machine->pic_reg)
4806             cfun->machine->pic_reg = gen_rtx_REG (Pmode, arm_pic_register);
4807
4808           /* Play games to avoid marking the function as needing pic
4809              if we are being called as part of the cost-estimation
4810              process.  */
4811           if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
4812             crtl->uses_pic_offset_table = 1;
4813         }
4814       else
4815         {
4816           rtx seq;
4817
4818           if (!cfun->machine->pic_reg)
4819             cfun->machine->pic_reg = gen_reg_rtx (Pmode);
4820
4821           /* Play games to avoid marking the function as needing pic
4822              if we are being called as part of the cost-estimation
4823              process.  */
4824           if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
4825             {
4826               crtl->uses_pic_offset_table = 1;
4827               start_sequence ();
4828
4829               arm_load_pic_register (0UL);
4830
4831               seq = get_insns ();
4832               end_sequence ();
4833               /* We can be called during expansion of PHI nodes, where
4834                  we can't yet emit instructions directly in the final
4835                  insn stream.  Queue the insns on the entry edge, they will
4836                  be committed after everything else is expanded.  */
4837               insert_insn_on_edge (seq, single_succ_edge (ENTRY_BLOCK_PTR));
4838             }
4839         }
4840     }
4841 }
4842
4843 rtx
4844 legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
4845 {
4846   if (GET_CODE (orig) == SYMBOL_REF
4847       || GET_CODE (orig) == LABEL_REF)
4848     {
4849       rtx pic_ref, address;
4850       rtx insn;
4851       int subregs = 0;
4852
4853       /* If this function doesn't have a pic register, create one now.  */
4854       require_pic_register ();
4855
4856       if (reg == 0)
4857         {
4858           gcc_assert (can_create_pseudo_p ());
4859           reg = gen_reg_rtx (Pmode);
4860
4861           subregs = 1;
4862         }
4863
4864       if (subregs)
4865         address = gen_reg_rtx (Pmode);
4866       else
4867         address = reg;
4868
4869       if (TARGET_ARM)
4870         emit_insn (gen_pic_load_addr_arm (address, orig));
4871       else if (TARGET_THUMB2)
4872         emit_insn (gen_pic_load_addr_thumb2 (address, orig));
4873       else /* TARGET_THUMB1 */
4874         emit_insn (gen_pic_load_addr_thumb1 (address, orig));
4875
4876       /* VxWorks does not impose a fixed gap between segments; the run-time
4877          gap can be different from the object-file gap.  We therefore can't
4878          use GOTOFF unless we are absolutely sure that the symbol is in the
4879          same segment as the GOT.  Unfortunately, the flexibility of linker
4880          scripts means that we can't be sure of that in general, so assume
4881          that GOTOFF is never valid on VxWorks.  */
4882       if ((GET_CODE (orig) == LABEL_REF
4883            || (GET_CODE (orig) == SYMBOL_REF &&
4884                SYMBOL_REF_LOCAL_P (orig)))
4885           && NEED_GOT_RELOC
4886           && !TARGET_VXWORKS_RTP)
4887         pic_ref = gen_rtx_PLUS (Pmode, cfun->machine->pic_reg, address);
4888       else
4889         {
4890           pic_ref = gen_const_mem (Pmode,
4891                                    gen_rtx_PLUS (Pmode, cfun->machine->pic_reg,
4892                                                  address));
4893         }
4894
4895       insn = emit_move_insn (reg, pic_ref);
4896
4897       /* Put a REG_EQUAL note on this insn, so that it can be optimized
4898          by loop.  */
4899       set_unique_reg_note (insn, REG_EQUAL, orig);
4900
4901       return reg;
4902     }
4903   else if (GET_CODE (orig) == CONST)
4904     {
4905       rtx base, offset;
4906
4907       if (GET_CODE (XEXP (orig, 0)) == PLUS
4908           && XEXP (XEXP (orig, 0), 0) == cfun->machine->pic_reg)
4909         return orig;
4910
4911       /* Handle the case where we have: const (UNSPEC_TLS).  */
4912       if (GET_CODE (XEXP (orig, 0)) == UNSPEC
4913           && XINT (XEXP (orig, 0), 1) == UNSPEC_TLS)
4914         return orig;
4915
4916       /* Handle the case where we have:
4917          const (plus (UNSPEC_TLS) (ADDEND)).  The ADDEND must be a
4918          CONST_INT.  */
4919       if (GET_CODE (XEXP (orig, 0)) == PLUS
4920           && GET_CODE (XEXP (XEXP (orig, 0), 0)) == UNSPEC
4921           && XINT (XEXP (XEXP (orig, 0), 0), 1) == UNSPEC_TLS)
4922         {
4923           gcc_assert (GET_CODE (XEXP (XEXP (orig, 0), 1)) == CONST_INT);
4924           return orig;
4925         }
4926
4927       if (reg == 0)
4928         {
4929           gcc_assert (can_create_pseudo_p ());
4930           reg = gen_reg_rtx (Pmode);
4931         }
4932
4933       gcc_assert (GET_CODE (XEXP (orig, 0)) == PLUS);
4934
4935       base = legitimize_pic_address (XEXP (XEXP (orig, 0), 0), Pmode, reg);
4936       offset = legitimize_pic_address (XEXP (XEXP (orig, 0), 1), Pmode,
4937                                        base == reg ? 0 : reg);
4938
4939       if (GET_CODE (offset) == CONST_INT)
4940         {
4941           /* The base register doesn't really matter, we only want to
4942              test the index for the appropriate mode.  */
4943           if (!arm_legitimate_index_p (mode, offset, SET, 0))
4944             {
4945               gcc_assert (can_create_pseudo_p ());
4946               offset = force_reg (Pmode, offset);
4947             }
4948
4949           if (GET_CODE (offset) == CONST_INT)
4950             return plus_constant (base, INTVAL (offset));
4951         }
4952
4953       if (GET_MODE_SIZE (mode) > 4
4954           && (GET_MODE_CLASS (mode) == MODE_INT
4955               || TARGET_SOFT_FLOAT))
4956         {
4957           emit_insn (gen_addsi3 (reg, base, offset));
4958           return reg;
4959         }
4960
4961       return gen_rtx_PLUS (Pmode, base, offset);
4962     }
4963
4964   return orig;
4965 }
4966
4967
4968 /* Find a spare register to use during the prolog of a function.  */
4969
4970 static int
4971 thumb_find_work_register (unsigned long pushed_regs_mask)
4972 {
4973   int reg;
4974
4975   /* Check the argument registers first as these are call-used.  The
4976      register allocation order means that sometimes r3 might be used
4977      but earlier argument registers might not, so check them all.  */
4978   for (reg = LAST_ARG_REGNUM; reg >= 0; reg --)
4979     if (!df_regs_ever_live_p (reg))
4980       return reg;
4981
4982   /* Before going on to check the call-saved registers we can try a couple
4983      more ways of deducing that r3 is available.  The first is when we are
4984      pushing anonymous arguments onto the stack and we have less than 4
4985      registers worth of fixed arguments(*).  In this case r3 will be part of
4986      the variable argument list and so we can be sure that it will be
4987      pushed right at the start of the function.  Hence it will be available
4988      for the rest of the prologue.
4989      (*): ie crtl->args.pretend_args_size is greater than 0.  */
4990   if (cfun->machine->uses_anonymous_args
4991       && crtl->args.pretend_args_size > 0)
4992     return LAST_ARG_REGNUM;
4993
4994   /* The other case is when we have fixed arguments but less than 4 registers
4995      worth.  In this case r3 might be used in the body of the function, but
4996      it is not being used to convey an argument into the function.  In theory
4997      we could just check crtl->args.size to see how many bytes are
4998      being passed in argument registers, but it seems that it is unreliable.
4999      Sometimes it will have the value 0 when in fact arguments are being
5000      passed.  (See testcase execute/20021111-1.c for an example).  So we also
5001      check the args_info.nregs field as well.  The problem with this field is
5002      that it makes no allowances for arguments that are passed to the
5003      function but which are not used.  Hence we could miss an opportunity
5004      when a function has an unused argument in r3.  But it is better to be
5005      safe than to be sorry.  */
5006   if (! cfun->machine->uses_anonymous_args
5007       && crtl->args.size >= 0
5008       && crtl->args.size <= (LAST_ARG_REGNUM * UNITS_PER_WORD)
5009       && crtl->args.info.nregs < 4)
5010     return LAST_ARG_REGNUM;
5011
5012   /* Otherwise look for a call-saved register that is going to be pushed.  */
5013   for (reg = LAST_LO_REGNUM; reg > LAST_ARG_REGNUM; reg --)
5014     if (pushed_regs_mask & (1 << reg))
5015       return reg;
5016
5017   if (TARGET_THUMB2)
5018     {
5019       /* Thumb-2 can use high regs.  */
5020       for (reg = FIRST_HI_REGNUM; reg < 15; reg ++)
5021         if (pushed_regs_mask & (1 << reg))
5022           return reg;
5023     }
5024   /* Something went wrong - thumb_compute_save_reg_mask()
5025      should have arranged for a suitable register to be pushed.  */
5026   gcc_unreachable ();
5027 }
5028
5029 static GTY(()) int pic_labelno;
5030
5031 /* Generate code to load the PIC register.  In thumb mode SCRATCH is a
5032    low register.  */
5033
5034 void
5035 arm_load_pic_register (unsigned long saved_regs ATTRIBUTE_UNUSED)
5036 {
5037   rtx l1, labelno, pic_tmp, pic_rtx, pic_reg;
5038
5039   if (crtl->uses_pic_offset_table == 0 || TARGET_SINGLE_PIC_BASE)
5040     return;
5041
5042   gcc_assert (flag_pic);
5043
5044   pic_reg = cfun->machine->pic_reg;
5045   if (TARGET_VXWORKS_RTP)
5046     {
5047       pic_rtx = gen_rtx_SYMBOL_REF (Pmode, VXWORKS_GOTT_BASE);
5048       pic_rtx = gen_rtx_CONST (Pmode, pic_rtx);
5049       emit_insn (gen_pic_load_addr_arm (pic_reg, pic_rtx));
5050
5051       emit_insn (gen_rtx_SET (Pmode, pic_reg, gen_rtx_MEM (Pmode, pic_reg)));
5052
5053       pic_tmp = gen_rtx_SYMBOL_REF (Pmode, VXWORKS_GOTT_INDEX);
5054       emit_insn (gen_pic_offset_arm (pic_reg, pic_reg, pic_tmp));
5055     }
5056   else
5057     {
5058       /* We use an UNSPEC rather than a LABEL_REF because this label
5059          never appears in the code stream.  */
5060
5061       labelno = GEN_INT (pic_labelno++);
5062       l1 = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
5063       l1 = gen_rtx_CONST (VOIDmode, l1);
5064
5065       /* On the ARM the PC register contains 'dot + 8' at the time of the
5066          addition, on the Thumb it is 'dot + 4'.  */
5067       pic_rtx = plus_constant (l1, TARGET_ARM ? 8 : 4);
5068       pic_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, pic_rtx),
5069                                 UNSPEC_GOTSYM_OFF);
5070       pic_rtx = gen_rtx_CONST (Pmode, pic_rtx);
5071
5072       if (TARGET_ARM)
5073         {
5074           emit_insn (gen_pic_load_addr_arm (pic_reg, pic_rtx));
5075           emit_insn (gen_pic_add_dot_plus_eight (pic_reg, pic_reg, labelno));
5076         }
5077       else if (TARGET_THUMB2)
5078         {
5079           /* Thumb-2 only allows very limited access to the PC.  Calculate the
5080              address in a temporary register.  */
5081           if (arm_pic_register != INVALID_REGNUM)
5082             {
5083               pic_tmp = gen_rtx_REG (SImode,
5084                                      thumb_find_work_register (saved_regs));
5085             }
5086           else
5087             {
5088               gcc_assert (can_create_pseudo_p ());
5089               pic_tmp = gen_reg_rtx (Pmode);
5090             }
5091
5092           emit_insn (gen_pic_load_addr_thumb2 (pic_reg, pic_rtx));
5093           emit_insn (gen_pic_load_dot_plus_four (pic_tmp, labelno));
5094           emit_insn (gen_addsi3 (pic_reg, pic_reg, pic_tmp));
5095         }
5096       else /* TARGET_THUMB1 */
5097         {
5098           if (arm_pic_register != INVALID_REGNUM
5099               && REGNO (pic_reg) > LAST_LO_REGNUM)
5100             {
5101               /* We will have pushed the pic register, so we should always be
5102                  able to find a work register.  */
5103               pic_tmp = gen_rtx_REG (SImode,
5104                                      thumb_find_work_register (saved_regs));
5105               emit_insn (gen_pic_load_addr_thumb1 (pic_tmp, pic_rtx));
5106               emit_insn (gen_movsi (pic_offset_table_rtx, pic_tmp));
5107             }
5108           else
5109             emit_insn (gen_pic_load_addr_thumb1 (pic_reg, pic_rtx));
5110           emit_insn (gen_pic_add_dot_plus_four (pic_reg, pic_reg, labelno));
5111         }
5112     }
5113
5114   /* Need to emit this whether or not we obey regdecls,
5115      since setjmp/longjmp can cause life info to screw up.  */
5116   emit_use (pic_reg);
5117 }
5118
5119
5120 /* Return nonzero if X is valid as an ARM state addressing register.  */
5121 static int
5122 arm_address_register_rtx_p (rtx x, int strict_p)
5123 {
5124   int regno;
5125
5126   if (GET_CODE (x) != REG)
5127     return 0;
5128
5129   regno = REGNO (x);
5130
5131   if (strict_p)
5132     return ARM_REGNO_OK_FOR_BASE_P (regno);
5133
5134   return (regno <= LAST_ARM_REGNUM
5135           || regno >= FIRST_PSEUDO_REGISTER
5136           || regno == FRAME_POINTER_REGNUM
5137           || regno == ARG_POINTER_REGNUM);
5138 }
5139
5140 /* Return TRUE if this rtx is the difference of a symbol and a label,
5141    and will reduce to a PC-relative relocation in the object file.
5142    Expressions like this can be left alone when generating PIC, rather
5143    than forced through the GOT.  */
5144 static int
5145 pcrel_constant_p (rtx x)
5146 {
5147   if (GET_CODE (x) == MINUS)
5148     return symbol_mentioned_p (XEXP (x, 0)) && label_mentioned_p (XEXP (x, 1));
5149
5150   return FALSE;
5151 }
5152
5153 /* Return nonzero if X is a valid ARM state address operand.  */
5154 int
5155 arm_legitimate_address_outer_p (enum machine_mode mode, rtx x, RTX_CODE outer,
5156                                 int strict_p)
5157 {
5158   bool use_ldrd;
5159   enum rtx_code code = GET_CODE (x);
5160
5161   if (arm_address_register_rtx_p (x, strict_p))
5162     return 1;
5163
5164   use_ldrd = (TARGET_LDRD
5165               && (mode == DImode
5166                   || (mode == DFmode && (TARGET_SOFT_FLOAT || TARGET_VFP))));
5167
5168   if (code == POST_INC || code == PRE_DEC
5169       || ((code == PRE_INC || code == POST_DEC)
5170           && (use_ldrd || GET_MODE_SIZE (mode) <= 4)))
5171     return arm_address_register_rtx_p (XEXP (x, 0), strict_p);
5172
5173   else if ((code == POST_MODIFY || code == PRE_MODIFY)
5174            && arm_address_register_rtx_p (XEXP (x, 0), strict_p)
5175            && GET_CODE (XEXP (x, 1)) == PLUS
5176            && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
5177     {
5178       rtx addend = XEXP (XEXP (x, 1), 1);
5179
5180       /* Don't allow ldrd post increment by register because it's hard
5181          to fixup invalid register choices.  */
5182       if (use_ldrd
5183           && GET_CODE (x) == POST_MODIFY
5184           && GET_CODE (addend) == REG)
5185         return 0;
5186
5187       return ((use_ldrd || GET_MODE_SIZE (mode) <= 4)
5188               && arm_legitimate_index_p (mode, addend, outer, strict_p));
5189     }
5190
5191   /* After reload constants split into minipools will have addresses
5192      from a LABEL_REF.  */
5193   else if (reload_completed
5194            && (code == LABEL_REF
5195                || (code == CONST
5196                    && GET_CODE (XEXP (x, 0)) == PLUS
5197                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
5198                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
5199     return 1;
5200
5201   else if (mode == TImode || (TARGET_NEON && VALID_NEON_STRUCT_MODE (mode)))
5202     return 0;
5203
5204   else if (code == PLUS)
5205     {
5206       rtx xop0 = XEXP (x, 0);
5207       rtx xop1 = XEXP (x, 1);
5208
5209       return ((arm_address_register_rtx_p (xop0, strict_p)
5210                && GET_CODE(xop1) == CONST_INT
5211                && arm_legitimate_index_p (mode, xop1, outer, strict_p))
5212               || (arm_address_register_rtx_p (xop1, strict_p)
5213                   && arm_legitimate_index_p (mode, xop0, outer, strict_p)));
5214     }
5215
5216 #if 0
5217   /* Reload currently can't handle MINUS, so disable this for now */
5218   else if (GET_CODE (x) == MINUS)
5219     {
5220       rtx xop0 = XEXP (x, 0);
5221       rtx xop1 = XEXP (x, 1);
5222
5223       return (arm_address_register_rtx_p (xop0, strict_p)
5224               && arm_legitimate_index_p (mode, xop1, outer, strict_p));
5225     }
5226 #endif
5227
5228   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
5229            && code == SYMBOL_REF
5230            && CONSTANT_POOL_ADDRESS_P (x)
5231            && ! (flag_pic
5232                  && symbol_mentioned_p (get_pool_constant (x))
5233                  && ! pcrel_constant_p (get_pool_constant (x))))
5234     return 1;
5235
5236   return 0;
5237 }
5238
5239 /* Return nonzero if X is a valid Thumb-2 address operand.  */
5240 static int
5241 thumb2_legitimate_address_p (enum machine_mode mode, rtx x, int strict_p)
5242 {
5243   bool use_ldrd;
5244   enum rtx_code code = GET_CODE (x);
5245   
5246   if (arm_address_register_rtx_p (x, strict_p))
5247     return 1;
5248
5249   use_ldrd = (TARGET_LDRD
5250               && (mode == DImode
5251                   || (mode == DFmode && (TARGET_SOFT_FLOAT || TARGET_VFP))));
5252
5253   if (code == POST_INC || code == PRE_DEC
5254       || ((code == PRE_INC || code == POST_DEC)
5255           && (use_ldrd || GET_MODE_SIZE (mode) <= 4)))
5256     return arm_address_register_rtx_p (XEXP (x, 0), strict_p);
5257
5258   else if ((code == POST_MODIFY || code == PRE_MODIFY)
5259            && arm_address_register_rtx_p (XEXP (x, 0), strict_p)
5260            && GET_CODE (XEXP (x, 1)) == PLUS
5261            && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
5262     {
5263       /* Thumb-2 only has autoincrement by constant.  */
5264       rtx addend = XEXP (XEXP (x, 1), 1);
5265       HOST_WIDE_INT offset;
5266
5267       if (GET_CODE (addend) != CONST_INT)
5268         return 0;
5269
5270       offset = INTVAL(addend);
5271       if (GET_MODE_SIZE (mode) <= 4)
5272         return (offset > -256 && offset < 256);
5273       
5274       return (use_ldrd && offset > -1024 && offset < 1024
5275               && (offset & 3) == 0);
5276     }
5277
5278   /* After reload constants split into minipools will have addresses
5279      from a LABEL_REF.  */
5280   else if (reload_completed
5281            && (code == LABEL_REF
5282                || (code == CONST
5283                    && GET_CODE (XEXP (x, 0)) == PLUS
5284                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
5285                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
5286     return 1;
5287
5288   else if (mode == TImode || (TARGET_NEON && VALID_NEON_STRUCT_MODE (mode)))
5289     return 0;
5290
5291   else if (code == PLUS)
5292     {
5293       rtx xop0 = XEXP (x, 0);
5294       rtx xop1 = XEXP (x, 1);
5295
5296       return ((arm_address_register_rtx_p (xop0, strict_p)
5297                && thumb2_legitimate_index_p (mode, xop1, strict_p))
5298               || (arm_address_register_rtx_p (xop1, strict_p)
5299                   && thumb2_legitimate_index_p (mode, xop0, strict_p)));
5300     }
5301
5302   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
5303            && code == SYMBOL_REF
5304            && CONSTANT_POOL_ADDRESS_P (x)
5305            && ! (flag_pic
5306                  && symbol_mentioned_p (get_pool_constant (x))
5307                  && ! pcrel_constant_p (get_pool_constant (x))))
5308     return 1;
5309
5310   return 0;
5311 }
5312
5313 /* Return nonzero if INDEX is valid for an address index operand in
5314    ARM state.  */
5315 static int
5316 arm_legitimate_index_p (enum machine_mode mode, rtx index, RTX_CODE outer,
5317                         int strict_p)
5318 {
5319   HOST_WIDE_INT range;
5320   enum rtx_code code = GET_CODE (index);
5321
5322   /* Standard coprocessor addressing modes.  */
5323   if (TARGET_HARD_FLOAT
5324       && (TARGET_FPA || TARGET_MAVERICK)
5325       && (GET_MODE_CLASS (mode) == MODE_FLOAT
5326           || (TARGET_MAVERICK && mode == DImode)))
5327     return (code == CONST_INT && INTVAL (index) < 1024
5328             && INTVAL (index) > -1024
5329             && (INTVAL (index) & 3) == 0);
5330
5331   if (TARGET_NEON
5332       && (VALID_NEON_DREG_MODE (mode) || VALID_NEON_QREG_MODE (mode)))
5333     return (code == CONST_INT
5334             && INTVAL (index) < 1016
5335             && INTVAL (index) > -1024
5336             && (INTVAL (index) & 3) == 0);
5337
5338   if (TARGET_REALLY_IWMMXT && VALID_IWMMXT_REG_MODE (mode))
5339     return (code == CONST_INT
5340             && INTVAL (index) < 1024
5341             && INTVAL (index) > -1024
5342             && (INTVAL (index) & 3) == 0);
5343
5344   if (arm_address_register_rtx_p (index, strict_p)
5345       && (GET_MODE_SIZE (mode) <= 4))
5346     return 1;
5347
5348   if (mode == DImode || mode == DFmode)
5349     {
5350       if (code == CONST_INT)
5351         {
5352           HOST_WIDE_INT val = INTVAL (index);
5353
5354           if (TARGET_LDRD)
5355             return val > -256 && val < 256;
5356           else
5357             return val > -4096 && val < 4092;
5358         }
5359
5360       return TARGET_LDRD && arm_address_register_rtx_p (index, strict_p);
5361     }
5362
5363   if (GET_MODE_SIZE (mode) <= 4
5364       && ! (arm_arch4
5365             && (mode == HImode
5366                 || mode == HFmode
5367                 || (mode == QImode && outer == SIGN_EXTEND))))
5368     {
5369       if (code == MULT)
5370         {
5371           rtx xiop0 = XEXP (index, 0);
5372           rtx xiop1 = XEXP (index, 1);
5373
5374           return ((arm_address_register_rtx_p (xiop0, strict_p)
5375                    && power_of_two_operand (xiop1, SImode))
5376                   || (arm_address_register_rtx_p (xiop1, strict_p)
5377                       && power_of_two_operand (xiop0, SImode)));
5378         }
5379       else if (code == LSHIFTRT || code == ASHIFTRT
5380                || code == ASHIFT || code == ROTATERT)
5381         {
5382           rtx op = XEXP (index, 1);
5383
5384           return (arm_address_register_rtx_p (XEXP (index, 0), strict_p)
5385                   && GET_CODE (op) == CONST_INT
5386                   && INTVAL (op) > 0
5387                   && INTVAL (op) <= 31);
5388         }
5389     }
5390
5391   /* For ARM v4 we may be doing a sign-extend operation during the
5392      load.  */
5393   if (arm_arch4)
5394     {
5395       if (mode == HImode
5396           || mode == HFmode
5397           || (outer == SIGN_EXTEND && mode == QImode))
5398         range = 256;
5399       else
5400         range = 4096;
5401     }
5402   else
5403     range = (mode == HImode || mode == HFmode) ? 4095 : 4096;
5404
5405   return (code == CONST_INT
5406           && INTVAL (index) < range
5407           && INTVAL (index) > -range);
5408 }
5409
5410 /* Return true if OP is a valid index scaling factor for Thumb-2 address
5411    index operand.  i.e. 1, 2, 4 or 8.  */
5412 static bool
5413 thumb2_index_mul_operand (rtx op)
5414 {
5415   HOST_WIDE_INT val;
5416   
5417   if (GET_CODE(op) != CONST_INT)
5418     return false;
5419
5420   val = INTVAL(op);
5421   return (val == 1 || val == 2 || val == 4 || val == 8);
5422 }
5423   
5424 /* Return nonzero if INDEX is a valid Thumb-2 address index operand.  */
5425 static int
5426 thumb2_legitimate_index_p (enum machine_mode mode, rtx index, int strict_p)
5427 {
5428   enum rtx_code code = GET_CODE (index);
5429
5430   /* ??? Combine arm and thumb2 coprocessor addressing modes.  */
5431   /* Standard coprocessor addressing modes.  */
5432   if (TARGET_HARD_FLOAT
5433       && (TARGET_FPA || TARGET_MAVERICK)
5434       && (GET_MODE_CLASS (mode) == MODE_FLOAT
5435           || (TARGET_MAVERICK && mode == DImode)))
5436     return (code == CONST_INT && INTVAL (index) < 1024
5437             && INTVAL (index) > -1024
5438             && (INTVAL (index) & 3) == 0);
5439
5440   if (TARGET_REALLY_IWMMXT && VALID_IWMMXT_REG_MODE (mode))
5441     {
5442       /* For DImode assume values will usually live in core regs
5443          and only allow LDRD addressing modes.  */
5444       if (!TARGET_LDRD || mode != DImode)
5445         return (code == CONST_INT
5446                 && INTVAL (index) < 1024
5447                 && INTVAL (index) > -1024
5448                 && (INTVAL (index) & 3) == 0);
5449     }
5450
5451   if (TARGET_NEON
5452       && (VALID_NEON_DREG_MODE (mode) || VALID_NEON_QREG_MODE (mode)))
5453     return (code == CONST_INT
5454             && INTVAL (index) < 1016
5455             && INTVAL (index) > -1024
5456             && (INTVAL (index) & 3) == 0);
5457
5458   if (arm_address_register_rtx_p (index, strict_p)
5459       && (GET_MODE_SIZE (mode) <= 4))
5460     return 1;
5461
5462   if (mode == DImode || mode == DFmode)
5463     {
5464       if (code == CONST_INT)
5465         {
5466           HOST_WIDE_INT val = INTVAL (index);
5467           /* ??? Can we assume ldrd for thumb2?  */
5468           /* Thumb-2 ldrd only has reg+const addressing modes.  */
5469           /* ldrd supports offsets of +-1020.
5470              However the ldr fallback does not.  */
5471           return val > -256 && val < 256 && (val & 3) == 0;
5472         }
5473       else
5474         return 0;
5475     }
5476
5477   if (code == MULT)
5478     {
5479       rtx xiop0 = XEXP (index, 0);
5480       rtx xiop1 = XEXP (index, 1);
5481
5482       return ((arm_address_register_rtx_p (xiop0, strict_p)
5483                && thumb2_index_mul_operand (xiop1))
5484               || (arm_address_register_rtx_p (xiop1, strict_p)
5485                   && thumb2_index_mul_operand (xiop0)));
5486     }
5487   else if (code == ASHIFT)
5488     {
5489       rtx op = XEXP (index, 1);
5490
5491       return (arm_address_register_rtx_p (XEXP (index, 0), strict_p)
5492               && GET_CODE (op) == CONST_INT
5493               && INTVAL (op) > 0
5494               && INTVAL (op) <= 3);
5495     }
5496
5497   return (code == CONST_INT
5498           && INTVAL (index) < 4096
5499           && INTVAL (index) > -256);
5500 }
5501
5502 /* Return nonzero if X is valid as a 16-bit Thumb state base register.  */
5503 static int
5504 thumb1_base_register_rtx_p (rtx x, enum machine_mode mode, int strict_p)
5505 {
5506   int regno;
5507
5508   if (GET_CODE (x) != REG)
5509     return 0;
5510
5511   regno = REGNO (x);
5512
5513   if (strict_p)
5514     return THUMB1_REGNO_MODE_OK_FOR_BASE_P (regno, mode);
5515
5516   return (regno <= LAST_LO_REGNUM
5517           || regno > LAST_VIRTUAL_REGISTER
5518           || regno == FRAME_POINTER_REGNUM
5519           || (GET_MODE_SIZE (mode) >= 4
5520               && (regno == STACK_POINTER_REGNUM
5521                   || regno >= FIRST_PSEUDO_REGISTER
5522                   || x == hard_frame_pointer_rtx
5523                   || x == arg_pointer_rtx)));
5524 }
5525
5526 /* Return nonzero if x is a legitimate index register.  This is the case
5527    for any base register that can access a QImode object.  */
5528 inline static int
5529 thumb1_index_register_rtx_p (rtx x, int strict_p)
5530 {
5531   return thumb1_base_register_rtx_p (x, QImode, strict_p);
5532 }
5533
5534 /* Return nonzero if x is a legitimate 16-bit Thumb-state address.
5535
5536    The AP may be eliminated to either the SP or the FP, so we use the
5537    least common denominator, e.g. SImode, and offsets from 0 to 64.
5538
5539    ??? Verify whether the above is the right approach.
5540
5541    ??? Also, the FP may be eliminated to the SP, so perhaps that
5542    needs special handling also.
5543
5544    ??? Look at how the mips16 port solves this problem.  It probably uses
5545    better ways to solve some of these problems.
5546
5547    Although it is not incorrect, we don't accept QImode and HImode
5548    addresses based on the frame pointer or arg pointer until the
5549    reload pass starts.  This is so that eliminating such addresses
5550    into stack based ones won't produce impossible code.  */
5551 static int
5552 thumb1_legitimate_address_p (enum machine_mode mode, rtx x, int strict_p)
5553 {
5554   /* ??? Not clear if this is right.  Experiment.  */
5555   if (GET_MODE_SIZE (mode) < 4
5556       && !(reload_in_progress || reload_completed)
5557       && (reg_mentioned_p (frame_pointer_rtx, x)
5558           || reg_mentioned_p (arg_pointer_rtx, x)
5559           || reg_mentioned_p (virtual_incoming_args_rtx, x)
5560           || reg_mentioned_p (virtual_outgoing_args_rtx, x)
5561           || reg_mentioned_p (virtual_stack_dynamic_rtx, x)
5562           || reg_mentioned_p (virtual_stack_vars_rtx, x)))
5563     return 0;
5564
5565   /* Accept any base register.  SP only in SImode or larger.  */
5566   else if (thumb1_base_register_rtx_p (x, mode, strict_p))
5567     return 1;
5568
5569   /* This is PC relative data before arm_reorg runs.  */
5570   else if (GET_MODE_SIZE (mode) >= 4 && CONSTANT_P (x)
5571            && GET_CODE (x) == SYMBOL_REF
5572            && CONSTANT_POOL_ADDRESS_P (x) && !flag_pic)
5573     return 1;
5574
5575   /* This is PC relative data after arm_reorg runs.  */
5576   else if ((GET_MODE_SIZE (mode) >= 4 || mode == HFmode)
5577            && reload_completed
5578            && (GET_CODE (x) == LABEL_REF
5579                || (GET_CODE (x) == CONST
5580                    && GET_CODE (XEXP (x, 0)) == PLUS
5581                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
5582                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
5583     return 1;
5584
5585   /* Post-inc indexing only supported for SImode and larger.  */
5586   else if (GET_CODE (x) == POST_INC && GET_MODE_SIZE (mode) >= 4
5587            && thumb1_index_register_rtx_p (XEXP (x, 0), strict_p))
5588     return 1;
5589
5590   else if (GET_CODE (x) == PLUS)
5591     {
5592       /* REG+REG address can be any two index registers.  */
5593       /* We disallow FRAME+REG addressing since we know that FRAME
5594          will be replaced with STACK, and SP relative addressing only
5595          permits SP+OFFSET.  */
5596       if (GET_MODE_SIZE (mode) <= 4
5597           && XEXP (x, 0) != frame_pointer_rtx
5598           && XEXP (x, 1) != frame_pointer_rtx
5599           && thumb1_index_register_rtx_p (XEXP (x, 0), strict_p)
5600           && thumb1_index_register_rtx_p (XEXP (x, 1), strict_p))
5601         return 1;
5602
5603       /* REG+const has 5-7 bit offset for non-SP registers.  */
5604       else if ((thumb1_index_register_rtx_p (XEXP (x, 0), strict_p)
5605                 || XEXP (x, 0) == arg_pointer_rtx)
5606                && GET_CODE (XEXP (x, 1)) == CONST_INT
5607                && thumb_legitimate_offset_p (mode, INTVAL (XEXP (x, 1))))
5608         return 1;
5609
5610       /* REG+const has 10-bit offset for SP, but only SImode and
5611          larger is supported.  */
5612       /* ??? Should probably check for DI/DFmode overflow here
5613          just like GO_IF_LEGITIMATE_OFFSET does.  */
5614       else if (GET_CODE (XEXP (x, 0)) == REG
5615                && REGNO (XEXP (x, 0)) == STACK_POINTER_REGNUM
5616                && GET_MODE_SIZE (mode) >= 4
5617                && GET_CODE (XEXP (x, 1)) == CONST_INT
5618                && INTVAL (XEXP (x, 1)) >= 0
5619                && INTVAL (XEXP (x, 1)) + GET_MODE_SIZE (mode) <= 1024
5620                && (INTVAL (XEXP (x, 1)) & 3) == 0)
5621         return 1;
5622
5623       else if (GET_CODE (XEXP (x, 0)) == REG
5624                && (REGNO (XEXP (x, 0)) == FRAME_POINTER_REGNUM
5625                    || REGNO (XEXP (x, 0)) == ARG_POINTER_REGNUM
5626                    || (REGNO (XEXP (x, 0)) >= FIRST_VIRTUAL_REGISTER
5627                        && REGNO (XEXP (x, 0)) <= LAST_VIRTUAL_REGISTER))
5628                && GET_MODE_SIZE (mode) >= 4
5629                && GET_CODE (XEXP (x, 1)) == CONST_INT
5630                && (INTVAL (XEXP (x, 1)) & 3) == 0)
5631         return 1;
5632     }
5633
5634   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
5635            && GET_MODE_SIZE (mode) == 4
5636            && GET_CODE (x) == SYMBOL_REF
5637            && CONSTANT_POOL_ADDRESS_P (x)
5638            && ! (flag_pic
5639                  && symbol_mentioned_p (get_pool_constant (x))
5640                  && ! pcrel_constant_p (get_pool_constant (x))))
5641     return 1;
5642
5643   return 0;
5644 }
5645
5646 /* Return nonzero if VAL can be used as an offset in a Thumb-state address
5647    instruction of mode MODE.  */
5648 int
5649 thumb_legitimate_offset_p (enum machine_mode mode, HOST_WIDE_INT val)
5650 {
5651   switch (GET_MODE_SIZE (mode))
5652     {
5653     case 1:
5654       return val >= 0 && val < 32;
5655
5656     case 2:
5657       return val >= 0 && val < 64 && (val & 1) == 0;
5658
5659     default:
5660       return (val >= 0
5661               && (val + GET_MODE_SIZE (mode)) <= 128
5662               && (val & 3) == 0);
5663     }
5664 }
5665
5666 bool
5667 arm_legitimate_address_p (enum machine_mode mode, rtx x, bool strict_p)
5668 {
5669   if (TARGET_ARM)
5670     return arm_legitimate_address_outer_p (mode, x, SET, strict_p);
5671   else if (TARGET_THUMB2)
5672     return thumb2_legitimate_address_p (mode, x, strict_p);
5673   else /* if (TARGET_THUMB1) */
5674     return thumb1_legitimate_address_p (mode, x, strict_p);
5675 }
5676
5677 /* Build the SYMBOL_REF for __tls_get_addr.  */
5678
5679 static GTY(()) rtx tls_get_addr_libfunc;
5680
5681 static rtx
5682 get_tls_get_addr (void)
5683 {
5684   if (!tls_get_addr_libfunc)
5685     tls_get_addr_libfunc = init_one_libfunc ("__tls_get_addr");
5686   return tls_get_addr_libfunc;
5687 }
5688
5689 static rtx
5690 arm_load_tp (rtx target)
5691 {
5692   if (!target)
5693     target = gen_reg_rtx (SImode);
5694
5695   if (TARGET_HARD_TP)
5696     {
5697       /* Can return in any reg.  */
5698       emit_insn (gen_load_tp_hard (target));
5699     }
5700   else
5701     {
5702       /* Always returned in r0.  Immediately copy the result into a pseudo,
5703          otherwise other uses of r0 (e.g. setting up function arguments) may
5704          clobber the value.  */
5705
5706       rtx tmp;
5707
5708       emit_insn (gen_load_tp_soft ());
5709
5710       tmp = gen_rtx_REG (SImode, 0);
5711       emit_move_insn (target, tmp);
5712     }
5713   return target;
5714 }
5715
5716 static rtx
5717 load_tls_operand (rtx x, rtx reg)
5718 {
5719   rtx tmp;
5720
5721   if (reg == NULL_RTX)
5722     reg = gen_reg_rtx (SImode);
5723
5724   tmp = gen_rtx_CONST (SImode, x);
5725
5726   emit_move_insn (reg, tmp);
5727
5728   return reg;
5729 }
5730
5731 static rtx
5732 arm_call_tls_get_addr (rtx x, rtx reg, rtx *valuep, int reloc)
5733 {
5734   rtx insns, label, labelno, sum;
5735
5736   start_sequence ();
5737
5738   labelno = GEN_INT (pic_labelno++);
5739   label = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
5740   label = gen_rtx_CONST (VOIDmode, label);
5741
5742   sum = gen_rtx_UNSPEC (Pmode,
5743                         gen_rtvec (4, x, GEN_INT (reloc), label,
5744                                    GEN_INT (TARGET_ARM ? 8 : 4)),
5745                         UNSPEC_TLS);
5746   reg = load_tls_operand (sum, reg);
5747
5748   if (TARGET_ARM)
5749     emit_insn (gen_pic_add_dot_plus_eight (reg, reg, labelno));
5750   else if (TARGET_THUMB2)
5751     {
5752       rtx tmp;
5753       /* Thumb-2 only allows very limited access to the PC.  Calculate
5754          the address in a temporary register.  */
5755       tmp = gen_reg_rtx (SImode);
5756       emit_insn (gen_pic_load_dot_plus_four (tmp, labelno));
5757       emit_insn (gen_addsi3(reg, reg, tmp));
5758     }
5759   else /* TARGET_THUMB1 */
5760     emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
5761
5762   *valuep = emit_library_call_value (get_tls_get_addr (), NULL_RTX, LCT_PURE, /* LCT_CONST?  */
5763                                      Pmode, 1, reg, Pmode);
5764
5765   insns = get_insns ();
5766   end_sequence ();
5767
5768   return insns;
5769 }
5770
5771 rtx
5772 legitimize_tls_address (rtx x, rtx reg)
5773 {
5774   rtx dest, tp, label, labelno, sum, insns, ret, eqv, addend;
5775   unsigned int model = SYMBOL_REF_TLS_MODEL (x);
5776
5777   switch (model)
5778     {
5779     case TLS_MODEL_GLOBAL_DYNAMIC:
5780       insns = arm_call_tls_get_addr (x, reg, &ret, TLS_GD32);
5781       dest = gen_reg_rtx (Pmode);
5782       emit_libcall_block (insns, dest, ret, x);
5783       return dest;
5784
5785     case TLS_MODEL_LOCAL_DYNAMIC:
5786       insns = arm_call_tls_get_addr (x, reg, &ret, TLS_LDM32);
5787
5788       /* Attach a unique REG_EQUIV, to allow the RTL optimizers to
5789          share the LDM result with other LD model accesses.  */
5790       eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const1_rtx),
5791                             UNSPEC_TLS);
5792       dest = gen_reg_rtx (Pmode);
5793       emit_libcall_block (insns, dest, ret, eqv);
5794
5795       /* Load the addend.  */
5796       addend = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, x, GEN_INT (TLS_LDO32)),
5797                                UNSPEC_TLS);
5798       addend = force_reg (SImode, gen_rtx_CONST (SImode, addend));
5799       return gen_rtx_PLUS (Pmode, dest, addend);
5800
5801     case TLS_MODEL_INITIAL_EXEC:
5802       labelno = GEN_INT (pic_labelno++);
5803       label = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
5804       label = gen_rtx_CONST (VOIDmode, label);
5805       sum = gen_rtx_UNSPEC (Pmode,
5806                             gen_rtvec (4, x, GEN_INT (TLS_IE32), label,
5807                                        GEN_INT (TARGET_ARM ? 8 : 4)),
5808                             UNSPEC_TLS);
5809       reg = load_tls_operand (sum, reg);
5810
5811       if (TARGET_ARM)
5812         emit_insn (gen_tls_load_dot_plus_eight (reg, reg, labelno));
5813       else if (TARGET_THUMB2)
5814         {
5815           rtx tmp;
5816           /* Thumb-2 only allows very limited access to the PC.  Calculate
5817              the address in a temporary register.  */
5818           tmp = gen_reg_rtx (SImode);
5819           emit_insn (gen_pic_load_dot_plus_four (tmp, labelno));
5820           emit_insn (gen_addsi3(reg, reg, tmp));
5821           emit_move_insn (reg, gen_const_mem (SImode, reg));
5822         }
5823       else
5824         {
5825           emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
5826           emit_move_insn (reg, gen_const_mem (SImode, reg));
5827         }
5828
5829       tp = arm_load_tp (NULL_RTX);
5830
5831       return gen_rtx_PLUS (Pmode, tp, reg);
5832
5833     case TLS_MODEL_LOCAL_EXEC:
5834       tp = arm_load_tp (NULL_RTX);
5835
5836       reg = gen_rtx_UNSPEC (Pmode,
5837                             gen_rtvec (2, x, GEN_INT (TLS_LE32)),
5838                             UNSPEC_TLS);
5839       reg = force_reg (SImode, gen_rtx_CONST (SImode, reg));
5840
5841       return gen_rtx_PLUS (Pmode, tp, reg);
5842
5843     default:
5844       abort ();
5845     }
5846 }
5847
5848 /* Try machine-dependent ways of modifying an illegitimate address
5849    to be legitimate.  If we find one, return the new, valid address.  */
5850 rtx
5851 arm_legitimize_address (rtx x, rtx orig_x, enum machine_mode mode)
5852 {
5853   if (!TARGET_ARM)
5854     {
5855       /* TODO: legitimize_address for Thumb2.  */
5856       if (TARGET_THUMB2)
5857         return x;
5858       return thumb_legitimize_address (x, orig_x, mode);
5859     }
5860
5861   if (arm_tls_symbol_p (x))
5862     return legitimize_tls_address (x, NULL_RTX);
5863
5864   if (GET_CODE (x) == PLUS)
5865     {
5866       rtx xop0 = XEXP (x, 0);
5867       rtx xop1 = XEXP (x, 1);
5868
5869       if (CONSTANT_P (xop0) && !symbol_mentioned_p (xop0))
5870         xop0 = force_reg (SImode, xop0);
5871
5872       if (CONSTANT_P (xop1) && !symbol_mentioned_p (xop1))
5873         xop1 = force_reg (SImode, xop1);
5874
5875       if (ARM_BASE_REGISTER_RTX_P (xop0)
5876           && GET_CODE (xop1) == CONST_INT)
5877         {
5878           HOST_WIDE_INT n, low_n;
5879           rtx base_reg, val;
5880           n = INTVAL (xop1);
5881
5882           /* VFP addressing modes actually allow greater offsets, but for
5883              now we just stick with the lowest common denominator.  */
5884           if (mode == DImode
5885               || ((TARGET_SOFT_FLOAT || TARGET_VFP) && mode == DFmode))
5886             {
5887               low_n = n & 0x0f;
5888               n &= ~0x0f;
5889               if (low_n > 4)
5890                 {
5891                   n += 16;
5892                   low_n -= 16;
5893                 }
5894             }
5895           else
5896             {
5897               low_n = ((mode) == TImode ? 0
5898                        : n >= 0 ? (n & 0xfff) : -((-n) & 0xfff));
5899               n -= low_n;
5900             }
5901
5902           base_reg = gen_reg_rtx (SImode);
5903           val = force_operand (plus_constant (xop0, n), NULL_RTX);
5904           emit_move_insn (base_reg, val);
5905           x = plus_constant (base_reg, low_n);
5906         }
5907       else if (xop0 != XEXP (x, 0) || xop1 != XEXP (x, 1))
5908         x = gen_rtx_PLUS (SImode, xop0, xop1);
5909     }
5910
5911   /* XXX We don't allow MINUS any more -- see comment in
5912      arm_legitimate_address_outer_p ().  */
5913   else if (GET_CODE (x) == MINUS)
5914     {
5915       rtx xop0 = XEXP (x, 0);
5916       rtx xop1 = XEXP (x, 1);
5917
5918       if (CONSTANT_P (xop0))
5919         xop0 = force_reg (SImode, xop0);
5920
5921       if (CONSTANT_P (xop1) && ! symbol_mentioned_p (xop1))
5922         xop1 = force_reg (SImode, xop1);
5923
5924       if (xop0 != XEXP (x, 0) || xop1 != XEXP (x, 1))
5925         x = gen_rtx_MINUS (SImode, xop0, xop1);
5926     }
5927
5928   /* Make sure to take full advantage of the pre-indexed addressing mode
5929      with absolute addresses which often allows for the base register to
5930      be factorized for multiple adjacent memory references, and it might
5931      even allows for the mini pool to be avoided entirely. */
5932   else if (GET_CODE (x) == CONST_INT && optimize > 0)
5933     {
5934       unsigned int bits;
5935       HOST_WIDE_INT mask, base, index;
5936       rtx base_reg;
5937
5938       /* ldr and ldrb can use a 12-bit index, ldrsb and the rest can only
5939          use a 8-bit index. So let's use a 12-bit index for SImode only and
5940          hope that arm_gen_constant will enable ldrb to use more bits. */
5941       bits = (mode == SImode) ? 12 : 8;
5942       mask = (1 << bits) - 1;
5943       base = INTVAL (x) & ~mask;
5944       index = INTVAL (x) & mask;
5945       if (bit_count (base & 0xffffffff) > (32 - bits)/2)
5946         {
5947           /* It'll most probably be more efficient to generate the base
5948              with more bits set and use a negative index instead. */
5949           base |= mask;
5950           index -= mask;
5951         }
5952       base_reg = force_reg (SImode, GEN_INT (base));
5953       x = plus_constant (base_reg, index);
5954     }
5955
5956   if (flag_pic)
5957     {
5958       /* We need to find and carefully transform any SYMBOL and LABEL
5959          references; so go back to the original address expression.  */
5960       rtx new_x = legitimize_pic_address (orig_x, mode, NULL_RTX);
5961
5962       if (new_x != orig_x)
5963         x = new_x;
5964     }
5965
5966   return x;
5967 }
5968
5969
5970 /* Try machine-dependent ways of modifying an illegitimate Thumb address
5971    to be legitimate.  If we find one, return the new, valid address.  */
5972 rtx
5973 thumb_legitimize_address (rtx x, rtx orig_x, enum machine_mode mode)
5974 {
5975   if (arm_tls_symbol_p (x))
5976     return legitimize_tls_address (x, NULL_RTX);
5977
5978   if (GET_CODE (x) == PLUS
5979       && GET_CODE (XEXP (x, 1)) == CONST_INT
5980       && (INTVAL (XEXP (x, 1)) >= 32 * GET_MODE_SIZE (mode)
5981           || INTVAL (XEXP (x, 1)) < 0))
5982     {
5983       rtx xop0 = XEXP (x, 0);
5984       rtx xop1 = XEXP (x, 1);
5985       HOST_WIDE_INT offset = INTVAL (xop1);
5986
5987       /* Try and fold the offset into a biasing of the base register and
5988          then offsetting that.  Don't do this when optimizing for space
5989          since it can cause too many CSEs.  */
5990       if (optimize_size && offset >= 0
5991           && offset < 256 + 31 * GET_MODE_SIZE (mode))
5992         {
5993           HOST_WIDE_INT delta;
5994
5995           if (offset >= 256)
5996             delta = offset - (256 - GET_MODE_SIZE (mode));
5997           else if (offset < 32 * GET_MODE_SIZE (mode) + 8)
5998             delta = 31 * GET_MODE_SIZE (mode);
5999           else
6000             delta = offset & (~31 * GET_MODE_SIZE (mode));
6001
6002           xop0 = force_operand (plus_constant (xop0, offset - delta),
6003                                 NULL_RTX);
6004           x = plus_constant (xop0, delta);
6005         }
6006       else if (offset < 0 && offset > -256)
6007         /* Small negative offsets are best done with a subtract before the
6008            dereference, forcing these into a register normally takes two
6009            instructions.  */
6010         x = force_operand (x, NULL_RTX);
6011       else
6012         {
6013           /* For the remaining cases, force the constant into a register.  */
6014           xop1 = force_reg (SImode, xop1);
6015           x = gen_rtx_PLUS (SImode, xop0, xop1);
6016         }
6017     }
6018   else if (GET_CODE (x) == PLUS
6019            && s_register_operand (XEXP (x, 1), SImode)
6020            && !s_register_operand (XEXP (x, 0), SImode))
6021     {
6022       rtx xop0 = force_operand (XEXP (x, 0), NULL_RTX);
6023
6024       x = gen_rtx_PLUS (SImode, xop0, XEXP (x, 1));
6025     }
6026
6027   if (flag_pic)
6028     {
6029       /* We need to find and carefully transform any SYMBOL and LABEL
6030          references; so go back to the original address expression.  */
6031       rtx new_x = legitimize_pic_address (orig_x, mode, NULL_RTX);
6032
6033       if (new_x != orig_x)
6034         x = new_x;
6035     }
6036
6037   return x;
6038 }
6039
6040 rtx
6041 thumb_legitimize_reload_address (rtx *x_p,
6042                                  enum machine_mode mode,
6043                                  int opnum, int type,
6044                                  int ind_levels ATTRIBUTE_UNUSED)
6045 {
6046   rtx x = *x_p;
6047
6048   if (GET_CODE (x) == PLUS
6049       && GET_MODE_SIZE (mode) < 4
6050       && REG_P (XEXP (x, 0))
6051       && XEXP (x, 0) == stack_pointer_rtx
6052       && GET_CODE (XEXP (x, 1)) == CONST_INT
6053       && !thumb_legitimate_offset_p (mode, INTVAL (XEXP (x, 1))))
6054     {
6055       rtx orig_x = x;
6056
6057       x = copy_rtx (x);
6058       push_reload (orig_x, NULL_RTX, x_p, NULL, MODE_BASE_REG_CLASS (mode),
6059                    Pmode, VOIDmode, 0, 0, opnum, (enum reload_type) type);
6060       return x;
6061     }
6062
6063   /* If both registers are hi-regs, then it's better to reload the
6064      entire expression rather than each register individually.  That
6065      only requires one reload register rather than two.  */
6066   if (GET_CODE (x) == PLUS
6067       && REG_P (XEXP (x, 0))
6068       && REG_P (XEXP (x, 1))
6069       && !REG_MODE_OK_FOR_REG_BASE_P (XEXP (x, 0), mode)
6070       && !REG_MODE_OK_FOR_REG_BASE_P (XEXP (x, 1), mode))
6071     {
6072       rtx orig_x = x;
6073
6074       x = copy_rtx (x);
6075       push_reload (orig_x, NULL_RTX, x_p, NULL, MODE_BASE_REG_CLASS (mode),
6076                    Pmode, VOIDmode, 0, 0, opnum, (enum reload_type) type);
6077       return x;
6078     }
6079
6080   return NULL;
6081 }
6082
6083 /* Test for various thread-local symbols.  */
6084
6085 /* Return TRUE if X is a thread-local symbol.  */
6086
6087 static bool
6088 arm_tls_symbol_p (rtx x)
6089 {
6090   if (! TARGET_HAVE_TLS)
6091     return false;
6092
6093   if (GET_CODE (x) != SYMBOL_REF)
6094     return false;
6095
6096   return SYMBOL_REF_TLS_MODEL (x) != 0;
6097 }
6098
6099 /* Helper for arm_tls_referenced_p.  */
6100
6101 static int
6102 arm_tls_operand_p_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
6103 {
6104   if (GET_CODE (*x) == SYMBOL_REF)
6105     return SYMBOL_REF_TLS_MODEL (*x) != 0;
6106
6107   /* Don't recurse into UNSPEC_TLS looking for TLS symbols; these are
6108      TLS offsets, not real symbol references.  */
6109   if (GET_CODE (*x) == UNSPEC
6110       && XINT (*x, 1) == UNSPEC_TLS)
6111     return -1;
6112
6113   return 0;
6114 }
6115
6116 /* Return TRUE if X contains any TLS symbol references.  */
6117
6118 bool
6119 arm_tls_referenced_p (rtx x)
6120 {
6121   if (! TARGET_HAVE_TLS)
6122     return false;
6123
6124   return for_each_rtx (&x, arm_tls_operand_p_1, NULL);
6125 }
6126
6127 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
6128
6129 bool
6130 arm_cannot_force_const_mem (rtx x)
6131 {
6132   rtx base, offset;
6133
6134   if (ARM_OFFSETS_MUST_BE_WITHIN_SECTIONS_P)
6135     {
6136       split_const (x, &base, &offset);
6137       if (GET_CODE (base) == SYMBOL_REF
6138           && !offset_within_block_p (base, INTVAL (offset)))
6139         return true;
6140     }
6141   return arm_tls_referenced_p (x);
6142 }
6143 \f
6144 #define REG_OR_SUBREG_REG(X)                                            \
6145   (GET_CODE (X) == REG                                                  \
6146    || (GET_CODE (X) == SUBREG && GET_CODE (SUBREG_REG (X)) == REG))
6147
6148 #define REG_OR_SUBREG_RTX(X)                    \
6149    (GET_CODE (X) == REG ? (X) : SUBREG_REG (X))
6150
6151 #ifndef COSTS_N_INSNS
6152 #define COSTS_N_INSNS(N) ((N) * 4 - 2)
6153 #endif
6154 static inline int
6155 thumb1_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer)
6156 {
6157   enum machine_mode mode = GET_MODE (x);
6158
6159   switch (code)
6160     {
6161     case ASHIFT:
6162     case ASHIFTRT:
6163     case LSHIFTRT:
6164     case ROTATERT:
6165     case PLUS:
6166     case MINUS:
6167     case COMPARE:
6168     case NEG:
6169     case NOT:
6170       return COSTS_N_INSNS (1);
6171
6172     case MULT:
6173       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6174         {
6175           int cycles = 0;
6176           unsigned HOST_WIDE_INT i = INTVAL (XEXP (x, 1));
6177
6178           while (i)
6179             {
6180               i >>= 2;
6181               cycles++;
6182             }
6183           return COSTS_N_INSNS (2) + cycles;
6184         }
6185       return COSTS_N_INSNS (1) + 16;
6186
6187     case SET:
6188       return (COSTS_N_INSNS (1)
6189               + 4 * ((GET_CODE (SET_SRC (x)) == MEM)
6190                      + GET_CODE (SET_DEST (x)) == MEM));
6191
6192     case CONST_INT:
6193       if (outer == SET)
6194         {
6195           if ((unsigned HOST_WIDE_INT) INTVAL (x) < 256)
6196             return 0;
6197           if (thumb_shiftable_const (INTVAL (x)))
6198             return COSTS_N_INSNS (2);
6199           return COSTS_N_INSNS (3);
6200         }
6201       else if ((outer == PLUS || outer == COMPARE)
6202                && INTVAL (x) < 256 && INTVAL (x) > -256)
6203         return 0;
6204       else if (outer == AND
6205                && INTVAL (x) < 256 && INTVAL (x) >= -256)
6206         return COSTS_N_INSNS (1);
6207       else if (outer == ASHIFT || outer == ASHIFTRT
6208                || outer == LSHIFTRT)
6209         return 0;
6210       return COSTS_N_INSNS (2);
6211
6212     case CONST:
6213     case CONST_DOUBLE:
6214     case LABEL_REF:
6215     case SYMBOL_REF:
6216       return COSTS_N_INSNS (3);
6217
6218     case UDIV:
6219     case UMOD:
6220     case DIV:
6221     case MOD:
6222       return 100;
6223
6224     case TRUNCATE:
6225       return 99;
6226
6227     case AND:
6228     case XOR:
6229     case IOR:
6230       /* XXX guess.  */
6231       return 8;
6232
6233     case MEM:
6234       /* XXX another guess.  */
6235       /* Memory costs quite a lot for the first word, but subsequent words
6236          load at the equivalent of a single insn each.  */
6237       return (10 + 4 * ((GET_MODE_SIZE (mode) - 1) / UNITS_PER_WORD)
6238               + ((GET_CODE (x) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (x))
6239                  ? 4 : 0));
6240
6241     case IF_THEN_ELSE:
6242       /* XXX a guess.  */
6243       if (GET_CODE (XEXP (x, 1)) == PC || GET_CODE (XEXP (x, 2)) == PC)
6244         return 14;
6245       return 2;
6246
6247     case ZERO_EXTEND:
6248       /* XXX still guessing.  */
6249       switch (GET_MODE (XEXP (x, 0)))
6250         {
6251         case QImode:
6252           return (1 + (mode == DImode ? 4 : 0)
6253                   + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
6254
6255         case HImode:
6256           return (4 + (mode == DImode ? 4 : 0)
6257                   + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
6258
6259         case SImode:
6260           return (1 + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
6261
6262         default:
6263           return 99;
6264         }
6265
6266     default:
6267       return 99;
6268     }
6269 }
6270
6271 static inline bool
6272 arm_rtx_costs_1 (rtx x, enum rtx_code outer, int* total, bool speed)
6273 {
6274   enum machine_mode mode = GET_MODE (x);
6275   enum rtx_code subcode;
6276   rtx operand;
6277   enum rtx_code code = GET_CODE (x);
6278   int extra_cost;
6279   *total = 0;
6280
6281   switch (code)
6282     {
6283     case MEM:
6284       /* Memory costs quite a lot for the first word, but subsequent words
6285          load at the equivalent of a single insn each.  */
6286       *total = COSTS_N_INSNS (2 + ARM_NUM_REGS (mode));
6287       return true;
6288
6289     case DIV:
6290     case MOD:
6291     case UDIV:
6292     case UMOD:
6293       if (TARGET_HARD_FLOAT && mode == SFmode)
6294         *total = COSTS_N_INSNS (2);
6295       else if (TARGET_HARD_FLOAT && mode == DFmode)
6296         *total = COSTS_N_INSNS (4);
6297       else
6298         *total = COSTS_N_INSNS (20);
6299       return false;
6300
6301     case ROTATE:
6302       if (GET_CODE (XEXP (x, 1)) == REG)
6303         *total = COSTS_N_INSNS (1); /* Need to subtract from 32 */
6304       else if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6305         *total = rtx_cost (XEXP (x, 1), code, speed);
6306
6307       /* Fall through */
6308     case ROTATERT:
6309       if (mode != SImode)
6310         {
6311           *total += COSTS_N_INSNS (4);
6312           return true;
6313         }
6314
6315       /* Fall through */
6316     case ASHIFT: case LSHIFTRT: case ASHIFTRT:
6317       *total += rtx_cost (XEXP (x, 0), code, speed);
6318       if (mode == DImode)
6319         {
6320           *total += COSTS_N_INSNS (3);
6321           return true;
6322         }
6323
6324       *total += COSTS_N_INSNS (1);
6325       /* Increase the cost of complex shifts because they aren't any faster,
6326          and reduce dual issue opportunities.  */
6327       if (arm_tune_cortex_a9
6328           && outer != SET && GET_CODE (XEXP (x, 1)) != CONST_INT)
6329         ++*total;
6330
6331       return true;
6332
6333     case MINUS:
6334       if (TARGET_THUMB2)
6335         {
6336           if (GET_MODE_CLASS (mode) == MODE_FLOAT)
6337             {
6338               if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
6339                 *total = COSTS_N_INSNS (1);
6340               else
6341                 *total = COSTS_N_INSNS (20);
6342             }
6343           else
6344             *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6345           /* Thumb2 does not have RSB, so all arguments must be
6346              registers (subtracting a constant is canonicalized as
6347              addition of the negated constant).  */
6348           return false;
6349         }
6350
6351       if (mode == DImode)
6352         {
6353           *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6354           if (GET_CODE (XEXP (x, 0)) == CONST_INT
6355               && const_ok_for_arm (INTVAL (XEXP (x, 0))))
6356             {
6357               *total += rtx_cost (XEXP (x, 1), code, speed);
6358               return true;
6359             }
6360
6361           if (GET_CODE (XEXP (x, 1)) == CONST_INT
6362               && const_ok_for_arm (INTVAL (XEXP (x, 1))))
6363             {
6364               *total += rtx_cost (XEXP (x, 0), code, speed);
6365               return true;
6366             }
6367
6368           return false;
6369         }
6370
6371       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
6372         {
6373           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
6374             {
6375               *total = COSTS_N_INSNS (1);
6376               if (GET_CODE (XEXP (x, 0)) == CONST_DOUBLE
6377                   && arm_const_double_rtx (XEXP (x, 0)))
6378                 {
6379                   *total += rtx_cost (XEXP (x, 1), code, speed);
6380                   return true;
6381                 }
6382
6383               if (GET_CODE (XEXP (x, 1)) == CONST_DOUBLE
6384                   && arm_const_double_rtx (XEXP (x, 1)))
6385                 {
6386                   *total += rtx_cost (XEXP (x, 0), code, speed);
6387                   return true;
6388                 }
6389
6390               return false;
6391             }
6392           *total = COSTS_N_INSNS (20);
6393           return false;
6394         }
6395
6396       *total = COSTS_N_INSNS (1);
6397       if (GET_CODE (XEXP (x, 0)) == CONST_INT
6398           && const_ok_for_arm (INTVAL (XEXP (x, 0))))
6399         {
6400           *total += rtx_cost (XEXP (x, 1), code, speed);
6401           return true;
6402         }
6403
6404       subcode = GET_CODE (XEXP (x, 1));
6405       if (subcode == ASHIFT || subcode == ASHIFTRT
6406           || subcode == LSHIFTRT
6407           || subcode == ROTATE || subcode == ROTATERT)
6408         {
6409           *total += rtx_cost (XEXP (x, 0), code, speed);
6410           *total += rtx_cost (XEXP (XEXP (x, 1), 0), subcode, speed);
6411           return true;
6412         }
6413
6414       /* A shift as a part of RSB costs no more than RSB itself.  */
6415       if (GET_CODE (XEXP (x, 0)) == MULT
6416           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
6417         {
6418           *total += rtx_cost (XEXP (XEXP (x, 0), 0), code, speed);
6419           *total += rtx_cost (XEXP (x, 1), code, speed);
6420           return true;
6421         }
6422
6423       if (subcode == MULT
6424           && power_of_two_operand (XEXP (XEXP (x, 1), 1), SImode))
6425         {
6426           *total += rtx_cost (XEXP (x, 0), code, speed);
6427           *total += rtx_cost (XEXP (XEXP (x, 1), 0), subcode, speed);
6428           return true;
6429         }
6430
6431       if (GET_RTX_CLASS (GET_CODE (XEXP (x, 1))) == RTX_COMPARE
6432           || GET_RTX_CLASS (GET_CODE (XEXP (x, 1))) == RTX_COMM_COMPARE)
6433         {
6434           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, speed);
6435           if (GET_CODE (XEXP (XEXP (x, 1), 0)) == REG
6436               && REGNO (XEXP (XEXP (x, 1), 0)) != CC_REGNUM)
6437             *total += COSTS_N_INSNS (1);
6438
6439           return true;
6440         }
6441
6442       /* Fall through */
6443
6444     case PLUS:
6445       if (code == PLUS && arm_arch6 && mode == SImode
6446           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
6447               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
6448         {
6449           *total = COSTS_N_INSNS (1);
6450           *total += rtx_cost (XEXP (XEXP (x, 0), 0), GET_CODE (XEXP (x, 0)),
6451                               speed);
6452           *total += rtx_cost (XEXP (x, 1), code, speed);
6453           return true;
6454         }
6455
6456       /* MLA: All arguments must be registers.  We filter out
6457          multiplication by a power of two, so that we fall down into
6458          the code below.  */
6459       if (GET_CODE (XEXP (x, 0)) == MULT
6460           && !power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
6461         {
6462           /* The cost comes from the cost of the multiply.  */
6463           return false;
6464         }
6465
6466       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
6467         {
6468           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
6469             {
6470               *total = COSTS_N_INSNS (1);
6471               if (GET_CODE (XEXP (x, 1)) == CONST_DOUBLE
6472                   && arm_const_double_rtx (XEXP (x, 1)))
6473                 {
6474                   *total += rtx_cost (XEXP (x, 0), code, speed);
6475                   return true;
6476                 }
6477
6478               return false;
6479             }
6480
6481           *total = COSTS_N_INSNS (20);
6482           return false;
6483         }
6484
6485       if (GET_RTX_CLASS (GET_CODE (XEXP (x, 0))) == RTX_COMPARE
6486           || GET_RTX_CLASS (GET_CODE (XEXP (x, 0))) == RTX_COMM_COMPARE)
6487         {
6488           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 1), code, speed);
6489           if (GET_CODE (XEXP (XEXP (x, 0), 0)) == REG
6490               && REGNO (XEXP (XEXP (x, 0), 0)) != CC_REGNUM)
6491             *total += COSTS_N_INSNS (1);
6492           return true;
6493         }
6494
6495       /* Fall through */
6496
6497     case AND: case XOR: case IOR:
6498       extra_cost = 0;
6499
6500       /* Normally the frame registers will be spilt into reg+const during
6501          reload, so it is a bad idea to combine them with other instructions,
6502          since then they might not be moved outside of loops.  As a compromise
6503          we allow integration with ops that have a constant as their second
6504          operand.  */
6505       if ((REG_OR_SUBREG_REG (XEXP (x, 0))
6506            && ARM_FRAME_RTX (REG_OR_SUBREG_RTX (XEXP (x, 0)))
6507            && GET_CODE (XEXP (x, 1)) != CONST_INT)
6508           || (REG_OR_SUBREG_REG (XEXP (x, 0))
6509               && ARM_FRAME_RTX (REG_OR_SUBREG_RTX (XEXP (x, 0)))))
6510         *total = 4;
6511
6512       if (mode == DImode)
6513         {
6514           *total += COSTS_N_INSNS (2);
6515           if (GET_CODE (XEXP (x, 1)) == CONST_INT
6516               && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
6517             {
6518               *total += rtx_cost (XEXP (x, 0), code, speed);
6519               return true;
6520             }
6521
6522           return false;
6523         }
6524
6525       *total += COSTS_N_INSNS (1);
6526       if (GET_CODE (XEXP (x, 1)) == CONST_INT
6527           && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
6528         {
6529           *total += rtx_cost (XEXP (x, 0), code, speed);
6530           return true;
6531         }
6532       subcode = GET_CODE (XEXP (x, 0));
6533       if (subcode == ASHIFT || subcode == ASHIFTRT
6534           || subcode == LSHIFTRT
6535           || subcode == ROTATE || subcode == ROTATERT)
6536         {
6537           *total += rtx_cost (XEXP (x, 1), code, speed);
6538           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, speed);
6539           return true;
6540         }
6541
6542       if (subcode == MULT
6543           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
6544         {
6545           *total += rtx_cost (XEXP (x, 1), code, speed);
6546           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, speed);
6547           return true;
6548         }
6549
6550       if (subcode == UMIN || subcode == UMAX
6551           || subcode == SMIN || subcode == SMAX)
6552         {
6553           *total = COSTS_N_INSNS (3);
6554           return true;
6555         }
6556
6557       return false;
6558
6559     case MULT:
6560       /* This should have been handled by the CPU specific routines.  */
6561       gcc_unreachable ();
6562
6563     case TRUNCATE:
6564       if (arm_arch3m && mode == SImode
6565           && GET_CODE (XEXP (x, 0)) == LSHIFTRT
6566           && GET_CODE (XEXP (XEXP (x, 0), 0)) == MULT
6567           && (GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0))
6568               == GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 1)))
6569           && (GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == ZERO_EXTEND
6570               || GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == SIGN_EXTEND))
6571         {
6572           *total = rtx_cost (XEXP (XEXP (x, 0), 0), LSHIFTRT, speed);
6573           return true;
6574         }
6575       *total = COSTS_N_INSNS (2); /* Plus the cost of the MULT */
6576       return false;
6577
6578     case NEG:
6579       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
6580         {
6581           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
6582             {
6583               *total = COSTS_N_INSNS (1);
6584               return false;
6585             }
6586           *total = COSTS_N_INSNS (2);
6587           return false;
6588         }
6589
6590       /* Fall through */
6591     case NOT:
6592       *total = COSTS_N_INSNS (ARM_NUM_REGS(mode));
6593       if (mode == SImode && code == NOT)
6594         {
6595           subcode = GET_CODE (XEXP (x, 0));
6596           if (subcode == ASHIFT || subcode == ASHIFTRT
6597               || subcode == LSHIFTRT
6598               || subcode == ROTATE || subcode == ROTATERT
6599               || (subcode == MULT
6600                   && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode)))
6601             {
6602               *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, speed);
6603               /* Register shifts cost an extra cycle.  */
6604               if (GET_CODE (XEXP (XEXP (x, 0), 1)) != CONST_INT)
6605                 *total += COSTS_N_INSNS (1) + rtx_cost (XEXP (XEXP (x, 0), 1),
6606                                                         subcode, speed);
6607               return true;
6608             }
6609         }
6610
6611       return false;
6612
6613     case IF_THEN_ELSE:
6614       if (GET_CODE (XEXP (x, 1)) == PC || GET_CODE (XEXP (x, 2)) == PC)
6615         {
6616           *total = COSTS_N_INSNS (4);
6617           return true;
6618         }
6619
6620       operand = XEXP (x, 0);
6621
6622       if (!((GET_RTX_CLASS (GET_CODE (operand)) == RTX_COMPARE
6623              || GET_RTX_CLASS (GET_CODE (operand)) == RTX_COMM_COMPARE)
6624             && GET_CODE (XEXP (operand, 0)) == REG
6625             && REGNO (XEXP (operand, 0)) == CC_REGNUM))
6626         *total += COSTS_N_INSNS (1);
6627       *total += (rtx_cost (XEXP (x, 1), code, speed)
6628                  + rtx_cost (XEXP (x, 2), code, speed));
6629       return true;
6630
6631     case NE:
6632       if (mode == SImode && XEXP (x, 1) == const0_rtx)
6633         {
6634           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, speed);
6635           return true;
6636         }
6637       goto scc_insn;
6638
6639     case GE:
6640       if ((GET_CODE (XEXP (x, 0)) != REG || REGNO (XEXP (x, 0)) != CC_REGNUM)
6641           && mode == SImode && XEXP (x, 1) == const0_rtx)
6642         {
6643           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, speed);
6644           return true;
6645         }
6646       goto scc_insn;
6647
6648     case LT:
6649       if ((GET_CODE (XEXP (x, 0)) != REG || REGNO (XEXP (x, 0)) != CC_REGNUM)
6650           && mode == SImode && XEXP (x, 1) == const0_rtx)
6651         {
6652           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, speed);
6653           return true;
6654         }
6655       goto scc_insn;
6656
6657     case EQ:
6658     case GT:
6659     case LE:
6660     case GEU:
6661     case LTU:
6662     case GTU:
6663     case LEU:
6664     case UNORDERED:
6665     case ORDERED:
6666     case UNEQ:
6667     case UNGE:
6668     case UNLT:
6669     case UNGT:
6670     case UNLE:
6671     scc_insn:
6672       /* SCC insns.  In the case where the comparison has already been
6673          performed, then they cost 2 instructions.  Otherwise they need
6674          an additional comparison before them.  */
6675       *total = COSTS_N_INSNS (2);
6676       if (GET_CODE (XEXP (x, 0)) == REG && REGNO (XEXP (x, 0)) == CC_REGNUM)
6677         {
6678           return true;
6679         }
6680
6681       /* Fall through */
6682     case COMPARE:
6683       if (GET_CODE (XEXP (x, 0)) == REG && REGNO (XEXP (x, 0)) == CC_REGNUM)
6684         {
6685           *total = 0;
6686           return true;
6687         }
6688
6689       *total += COSTS_N_INSNS (1);
6690       if (GET_CODE (XEXP (x, 1)) == CONST_INT
6691           && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
6692         {
6693           *total += rtx_cost (XEXP (x, 0), code, speed);
6694           return true;
6695         }
6696
6697       subcode = GET_CODE (XEXP (x, 0));
6698       if (subcode == ASHIFT || subcode == ASHIFTRT
6699           || subcode == LSHIFTRT
6700           || subcode == ROTATE || subcode == ROTATERT)
6701         {
6702           *total += rtx_cost (XEXP (x, 1), code, speed);
6703           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, speed);
6704           return true;
6705         }
6706
6707       if (subcode == MULT
6708           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
6709         {
6710           *total += rtx_cost (XEXP (x, 1), code, speed);
6711           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, speed);
6712           return true;
6713         }
6714       
6715       return false;
6716
6717     case UMIN:
6718     case UMAX:
6719     case SMIN:
6720     case SMAX:
6721       *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, speed);
6722       if (GET_CODE (XEXP (x, 1)) != CONST_INT
6723           || !const_ok_for_arm (INTVAL (XEXP (x, 1))))
6724         *total += rtx_cost (XEXP (x, 1), code, speed);
6725       return true;
6726
6727     case ABS:
6728       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
6729         {
6730           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
6731             {
6732               *total = COSTS_N_INSNS (1);
6733               return false;
6734             }
6735           *total = COSTS_N_INSNS (20);
6736           return false;
6737         }
6738       *total = COSTS_N_INSNS (1);
6739       if (mode == DImode)
6740         *total += COSTS_N_INSNS (3);
6741       return false;
6742
6743     case SIGN_EXTEND:
6744       if (GET_MODE_CLASS (mode) == MODE_INT)
6745         {
6746           *total = 0;
6747           if (mode == DImode)
6748             *total += COSTS_N_INSNS (1);
6749
6750           if (GET_MODE (XEXP (x, 0)) != SImode)
6751             {
6752               if (arm_arch6)
6753                 {
6754                   if (GET_CODE (XEXP (x, 0)) != MEM)
6755                     *total += COSTS_N_INSNS (1);
6756                 }
6757               else if (!arm_arch4 || GET_CODE (XEXP (x, 0)) != MEM)
6758                 *total += COSTS_N_INSNS (2);
6759             }
6760
6761           return false;
6762         }
6763
6764       /* Fall through */
6765     case ZERO_EXTEND:
6766       *total = 0;
6767       if (GET_MODE_CLASS (mode) == MODE_INT)
6768         {
6769           if (mode == DImode)
6770             *total += COSTS_N_INSNS (1);
6771
6772           if (GET_MODE (XEXP (x, 0)) != SImode)
6773             {
6774               if (arm_arch6)
6775                 {
6776                   if (GET_CODE (XEXP (x, 0)) != MEM)
6777                     *total += COSTS_N_INSNS (1);
6778                 }
6779               else if (!arm_arch4 || GET_CODE (XEXP (x, 0)) != MEM)
6780                 *total += COSTS_N_INSNS (GET_MODE (XEXP (x, 0)) == QImode ?
6781                                          1 : 2);
6782             }
6783
6784           return false;
6785         }
6786
6787       switch (GET_MODE (XEXP (x, 0)))
6788         {
6789         case V8QImode:
6790         case V4HImode:
6791         case V2SImode:
6792         case V4QImode:
6793         case V2HImode:
6794           *total = COSTS_N_INSNS (1);
6795           return false;
6796
6797         default:
6798           gcc_unreachable ();
6799         }
6800       gcc_unreachable ();
6801
6802     case ZERO_EXTRACT:
6803     case SIGN_EXTRACT:
6804       *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, speed);
6805       return true;
6806
6807     case CONST_INT:
6808       if (const_ok_for_arm (INTVAL (x))
6809           || const_ok_for_arm (~INTVAL (x)))
6810         *total = COSTS_N_INSNS (1);
6811       else
6812         *total = COSTS_N_INSNS (arm_gen_constant (SET, mode, NULL_RTX,
6813                                                   INTVAL (x), NULL_RTX,
6814                                                   NULL_RTX, 0, 0));
6815       return true;
6816
6817     case CONST:
6818     case LABEL_REF:
6819     case SYMBOL_REF:
6820       *total = COSTS_N_INSNS (3);
6821       return true;
6822
6823     case HIGH:
6824       *total = COSTS_N_INSNS (1);
6825       return true;
6826
6827     case LO_SUM:
6828       *total = COSTS_N_INSNS (1);
6829       *total += rtx_cost (XEXP (x, 0), code, speed);
6830       return true;
6831
6832     case CONST_DOUBLE:
6833       if (TARGET_HARD_FLOAT && vfp3_const_double_rtx (x))
6834         *total = COSTS_N_INSNS (1);
6835       else
6836         *total = COSTS_N_INSNS (4);
6837       return true;
6838
6839     default:
6840       *total = COSTS_N_INSNS (4);
6841       return false;
6842     }
6843 }
6844
6845 /* RTX costs when optimizing for size.  */
6846 static bool
6847 arm_size_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
6848                     int *total)
6849 {
6850   enum machine_mode mode = GET_MODE (x);
6851   if (TARGET_THUMB1)
6852     {
6853       /* XXX TBD.  For now, use the standard costs.  */
6854       *total = thumb1_rtx_costs (x, code, outer_code);
6855       return true;
6856     }
6857
6858   /* FIXME: This makes no attempt to prefer narrow Thumb-2 instructions.  */
6859   switch (code)
6860     {
6861     case MEM:
6862       /* A memory access costs 1 insn if the mode is small, or the address is
6863          a single register, otherwise it costs one insn per word.  */
6864       if (REG_P (XEXP (x, 0)))
6865         *total = COSTS_N_INSNS (1);
6866       else
6867         *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6868       return true;
6869
6870     case DIV:
6871     case MOD:
6872     case UDIV:
6873     case UMOD:
6874       /* Needs a libcall, so it costs about this.  */
6875       *total = COSTS_N_INSNS (2);
6876       return false;
6877
6878     case ROTATE:
6879       if (mode == SImode && GET_CODE (XEXP (x, 1)) == REG)
6880         {
6881           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, false);
6882           return true;
6883         }
6884       /* Fall through */
6885     case ROTATERT:
6886     case ASHIFT:
6887     case LSHIFTRT:
6888     case ASHIFTRT:
6889       if (mode == DImode && GET_CODE (XEXP (x, 1)) == CONST_INT)
6890         {
6891           *total = COSTS_N_INSNS (3) + rtx_cost (XEXP (x, 0), code, false);
6892           return true;
6893         }
6894       else if (mode == SImode)
6895         {
6896           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, false);
6897           /* Slightly disparage register shifts, but not by much.  */
6898           if (GET_CODE (XEXP (x, 1)) != CONST_INT)
6899             *total += 1 + rtx_cost (XEXP (x, 1), code, false);
6900           return true;
6901         }
6902
6903       /* Needs a libcall.  */
6904       *total = COSTS_N_INSNS (2);
6905       return false;
6906
6907     case MINUS:
6908       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT)
6909         {
6910           *total = COSTS_N_INSNS (1);
6911           return false;
6912         }
6913
6914       if (mode == SImode)
6915         {
6916           enum rtx_code subcode0 = GET_CODE (XEXP (x, 0));
6917           enum rtx_code subcode1 = GET_CODE (XEXP (x, 1));
6918
6919           if (subcode0 == ROTATE || subcode0 == ROTATERT || subcode0 == ASHIFT
6920               || subcode0 == LSHIFTRT || subcode0 == ASHIFTRT
6921               || subcode1 == ROTATE || subcode1 == ROTATERT
6922               || subcode1 == ASHIFT || subcode1 == LSHIFTRT
6923               || subcode1 == ASHIFTRT)
6924             {
6925               /* It's just the cost of the two operands.  */
6926               *total = 0;
6927               return false;
6928             }
6929
6930           *total = COSTS_N_INSNS (1);
6931           return false;
6932         }
6933
6934       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6935       return false;
6936
6937     case PLUS:
6938       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT)
6939         {
6940           *total = COSTS_N_INSNS (1);
6941           return false;
6942         }
6943
6944       /* A shift as a part of ADD costs nothing.  */
6945       if (GET_CODE (XEXP (x, 0)) == MULT
6946           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
6947         {
6948           *total = COSTS_N_INSNS (TARGET_THUMB2 ? 2 : 1);
6949           *total += rtx_cost (XEXP (XEXP (x, 0), 0), code, false);
6950           *total += rtx_cost (XEXP (x, 1), code, false);
6951           return true;
6952         }
6953
6954       /* Fall through */
6955     case AND: case XOR: case IOR:
6956       if (mode == SImode)
6957         {
6958           enum rtx_code subcode = GET_CODE (XEXP (x, 0));
6959
6960           if (subcode == ROTATE || subcode == ROTATERT || subcode == ASHIFT
6961               || subcode == LSHIFTRT || subcode == ASHIFTRT
6962               || (code == AND && subcode == NOT))
6963             {
6964               /* It's just the cost of the two operands.  */
6965               *total = 0;
6966               return false;
6967             }
6968         }
6969
6970       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6971       return false;
6972
6973     case MULT:
6974       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6975       return false;
6976
6977     case NEG:
6978       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT)
6979         {
6980           *total = COSTS_N_INSNS (1);
6981           return false;
6982         }
6983
6984       /* Fall through */
6985     case NOT:
6986       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
6987
6988       return false;
6989
6990     case IF_THEN_ELSE:
6991       *total = 0;
6992       return false;
6993
6994     case COMPARE:
6995       if (cc_register (XEXP (x, 0), VOIDmode))
6996         * total = 0;
6997       else
6998         *total = COSTS_N_INSNS (1);
6999       return false;
7000
7001     case ABS:
7002       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT)
7003         *total = COSTS_N_INSNS (1);
7004       else
7005         *total = COSTS_N_INSNS (1 + ARM_NUM_REGS (mode));
7006       return false;
7007
7008     case SIGN_EXTEND:
7009       *total = 0;
7010       if (GET_MODE_SIZE (GET_MODE (XEXP (x, 0))) < 4)
7011         {
7012           if (!(arm_arch4 && MEM_P (XEXP (x, 0))))
7013             *total += COSTS_N_INSNS (arm_arch6 ? 1 : 2);
7014         }
7015       if (mode == DImode)
7016         *total += COSTS_N_INSNS (1);
7017       return false;
7018
7019     case ZERO_EXTEND:
7020       *total = 0;
7021       if (!(arm_arch4 && MEM_P (XEXP (x, 0))))
7022         {
7023           switch (GET_MODE (XEXP (x, 0)))
7024             {
7025             case QImode:
7026               *total += COSTS_N_INSNS (1);
7027               break;
7028
7029             case HImode:
7030               *total += COSTS_N_INSNS (arm_arch6 ? 1 : 2);
7031
7032             case SImode:
7033               break;
7034
7035             default:
7036               *total += COSTS_N_INSNS (2);
7037             }
7038         }
7039
7040       if (mode == DImode)
7041         *total += COSTS_N_INSNS (1);
7042
7043       return false;
7044
7045     case CONST_INT:
7046       if (const_ok_for_arm (INTVAL (x)))
7047         /* A multiplication by a constant requires another instruction
7048            to load the constant to a register.  */
7049         *total = COSTS_N_INSNS ((outer_code == SET || outer_code == MULT)
7050                                 ? 1 : 0);
7051       else if (const_ok_for_arm (~INTVAL (x)))
7052         *total = COSTS_N_INSNS (outer_code == AND ? 0 : 1);
7053       else if (const_ok_for_arm (-INTVAL (x)))
7054         {
7055           if (outer_code == COMPARE || outer_code == PLUS
7056               || outer_code == MINUS)
7057             *total = 0;
7058           else
7059             *total = COSTS_N_INSNS (1);
7060         }
7061       else
7062         *total = COSTS_N_INSNS (2);
7063       return true;
7064
7065     case CONST:
7066     case LABEL_REF:
7067     case SYMBOL_REF:
7068       *total = COSTS_N_INSNS (2);
7069       return true;
7070
7071     case CONST_DOUBLE:
7072       *total = COSTS_N_INSNS (4);
7073       return true;
7074
7075     case HIGH:
7076     case LO_SUM:
7077       /* We prefer constant pool entries to MOVW/MOVT pairs, so bump the
7078          cost of these slightly.  */
7079       *total = COSTS_N_INSNS (1) + 1;
7080       return true;
7081
7082     default:
7083       if (mode != VOIDmode)
7084         *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7085       else
7086         *total = COSTS_N_INSNS (4); /* How knows?  */
7087       return false;
7088     }
7089 }
7090
7091 /* RTX costs when optimizing for size.  */
7092 static bool
7093 arm_rtx_costs (rtx x, int code, int outer_code, int *total,
7094                bool speed)
7095 {
7096   if (!speed)
7097     return arm_size_rtx_costs (x, (enum rtx_code) code,
7098                                (enum rtx_code) outer_code, total);
7099   else
7100     return all_cores[(int)arm_tune].rtx_costs (x, (enum rtx_code) code,
7101                                                (enum rtx_code) outer_code,
7102                                                total, speed);
7103 }
7104
7105 /* RTX costs for cores with a slow MUL implementation.  Thumb-2 is not
7106    supported on any "slowmul" cores, so it can be ignored.  */
7107
7108 static bool
7109 arm_slowmul_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
7110                        int *total, bool speed)
7111 {
7112   enum machine_mode mode = GET_MODE (x);
7113
7114   if (TARGET_THUMB)
7115     {
7116       *total = thumb1_rtx_costs (x, code, outer_code);
7117       return true;
7118     }
7119
7120   switch (code)
7121     {
7122     case MULT:
7123       if (GET_MODE_CLASS (mode) == MODE_FLOAT
7124           || mode == DImode)
7125         {
7126           *total = COSTS_N_INSNS (20);
7127           return false;
7128         }
7129
7130       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7131         {
7132           unsigned HOST_WIDE_INT i = (INTVAL (XEXP (x, 1))
7133                                       & (unsigned HOST_WIDE_INT) 0xffffffff);
7134           int cost, const_ok = const_ok_for_arm (i);
7135           int j, booth_unit_size;
7136
7137           /* Tune as appropriate.  */
7138           cost = const_ok ? 4 : 8;
7139           booth_unit_size = 2;
7140           for (j = 0; i && j < 32; j += booth_unit_size)
7141             {
7142               i >>= booth_unit_size;
7143               cost++;
7144             }
7145
7146           *total = COSTS_N_INSNS (cost);
7147           *total += rtx_cost (XEXP (x, 0), code, speed);
7148           return true;
7149         }
7150
7151       *total = COSTS_N_INSNS (20);
7152       return false;
7153
7154     default:
7155       return arm_rtx_costs_1 (x, outer_code, total, speed);;
7156     }
7157 }
7158
7159
7160 /* RTX cost for cores with a fast multiply unit (M variants).  */
7161
7162 static bool
7163 arm_fastmul_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
7164                        int *total, bool speed)
7165 {
7166   enum machine_mode mode = GET_MODE (x);
7167
7168   if (TARGET_THUMB1)
7169     {
7170       *total = thumb1_rtx_costs (x, code, outer_code);
7171       return true;
7172     }
7173
7174   /* ??? should thumb2 use different costs?  */
7175   switch (code)
7176     {
7177     case MULT:
7178       /* There is no point basing this on the tuning, since it is always the
7179          fast variant if it exists at all.  */
7180       if (mode == DImode
7181           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
7182           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
7183               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
7184         {
7185           *total = COSTS_N_INSNS(2);
7186           return false;
7187         }
7188
7189
7190       if (mode == DImode)
7191         {
7192           *total = COSTS_N_INSNS (5);
7193           return false;
7194         }
7195
7196       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7197         {
7198           unsigned HOST_WIDE_INT i = (INTVAL (XEXP (x, 1))
7199                                       & (unsigned HOST_WIDE_INT) 0xffffffff);
7200           int cost, const_ok = const_ok_for_arm (i);
7201           int j, booth_unit_size;
7202
7203           /* Tune as appropriate.  */
7204           cost = const_ok ? 4 : 8;
7205           booth_unit_size = 8;
7206           for (j = 0; i && j < 32; j += booth_unit_size)
7207             {
7208               i >>= booth_unit_size;
7209               cost++;
7210             }
7211
7212           *total = COSTS_N_INSNS(cost);
7213           return false;
7214         }
7215
7216       if (mode == SImode)
7217         {
7218           *total = COSTS_N_INSNS (4);
7219           return false;
7220         }
7221
7222       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7223         {
7224           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
7225             {
7226               *total = COSTS_N_INSNS (1);
7227               return false;
7228             }
7229         }
7230
7231       /* Requires a lib call */
7232       *total = COSTS_N_INSNS (20);
7233       return false;
7234
7235     default:
7236       return arm_rtx_costs_1 (x, outer_code, total, speed);
7237     }
7238 }
7239
7240
7241 /* RTX cost for XScale CPUs.  Thumb-2 is not supported on any xscale cores,
7242    so it can be ignored.  */
7243
7244 static bool
7245 arm_xscale_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code, int *total, bool speed)
7246 {
7247   enum machine_mode mode = GET_MODE (x);
7248
7249   if (TARGET_THUMB)
7250     {
7251       *total = thumb1_rtx_costs (x, code, outer_code);
7252       return true;
7253     }
7254
7255   switch (code)
7256     {
7257     case COMPARE:
7258       if (GET_CODE (XEXP (x, 0)) != MULT)
7259         return arm_rtx_costs_1 (x, outer_code, total, speed);
7260
7261       /* A COMPARE of a MULT is slow on XScale; the muls instruction
7262          will stall until the multiplication is complete.  */
7263       *total = COSTS_N_INSNS (3);
7264       return false;
7265
7266     case MULT:
7267       /* There is no point basing this on the tuning, since it is always the
7268          fast variant if it exists at all.  */
7269       if (mode == DImode
7270           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
7271           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
7272               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
7273         {
7274           *total = COSTS_N_INSNS (2);
7275           return false;
7276         }
7277
7278
7279       if (mode == DImode)
7280         {
7281           *total = COSTS_N_INSNS (5);
7282           return false;
7283         }
7284
7285       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7286         {
7287           /* If operand 1 is a constant we can more accurately
7288              calculate the cost of the multiply.  The multiplier can
7289              retire 15 bits on the first cycle and a further 12 on the
7290              second.  We do, of course, have to load the constant into
7291              a register first.  */
7292           unsigned HOST_WIDE_INT i = INTVAL (XEXP (x, 1));
7293           /* There's a general overhead of one cycle.  */
7294           int cost = 1;
7295           unsigned HOST_WIDE_INT masked_const;
7296
7297           if (i & 0x80000000)
7298             i = ~i;
7299
7300           i &= (unsigned HOST_WIDE_INT) 0xffffffff;
7301
7302           masked_const = i & 0xffff8000;
7303           if (masked_const != 0)
7304             {
7305               cost++;
7306               masked_const = i & 0xf8000000;
7307               if (masked_const != 0)
7308                 cost++;
7309             }
7310           *total = COSTS_N_INSNS (cost);
7311           return false;
7312         }
7313
7314       if (mode == SImode)
7315         {
7316           *total = COSTS_N_INSNS (3);
7317           return false;
7318         }
7319
7320       /* Requires a lib call */
7321       *total = COSTS_N_INSNS (20);
7322       return false;
7323
7324     default:
7325       return arm_rtx_costs_1 (x, outer_code, total, speed);
7326     }
7327 }
7328
7329
7330 /* RTX costs for 9e (and later) cores.  */
7331
7332 static bool
7333 arm_9e_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
7334                   int *total, bool speed)
7335 {
7336   enum machine_mode mode = GET_MODE (x);
7337
7338   if (TARGET_THUMB1)
7339     {
7340       switch (code)
7341         {
7342         case MULT:
7343           *total = COSTS_N_INSNS (3);
7344           return true;
7345
7346         default:
7347           *total = thumb1_rtx_costs (x, code, outer_code);
7348           return true;
7349         }
7350     }
7351
7352   switch (code)
7353     {
7354     case MULT:
7355       /* There is no point basing this on the tuning, since it is always the
7356          fast variant if it exists at all.  */
7357       if (mode == DImode
7358           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
7359           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
7360               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
7361         {
7362           *total = COSTS_N_INSNS (2);
7363           return false;
7364         }
7365
7366
7367       if (mode == DImode)
7368         {
7369           *total = COSTS_N_INSNS (5);
7370           return false;
7371         }
7372
7373       if (mode == SImode)
7374         {
7375           *total = COSTS_N_INSNS (2);
7376           return false;
7377         }
7378
7379       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7380         {
7381           if (TARGET_HARD_FLOAT && (mode == SFmode || mode == DFmode))
7382             {
7383               *total = COSTS_N_INSNS (1);
7384               return false;
7385             }
7386         }
7387
7388       *total = COSTS_N_INSNS (20);
7389       return false;
7390
7391     default:
7392       return arm_rtx_costs_1 (x, outer_code, total, speed);
7393     }
7394 }
7395 /* All address computations that can be done are free, but rtx cost returns
7396    the same for practically all of them.  So we weight the different types
7397    of address here in the order (most pref first):
7398    PRE/POST_INC/DEC, SHIFT or NON-INT sum, INT sum, REG, MEM or LABEL.  */
7399 static inline int
7400 arm_arm_address_cost (rtx x)
7401 {
7402   enum rtx_code c  = GET_CODE (x);
7403
7404   if (c == PRE_INC || c == PRE_DEC || c == POST_INC || c == POST_DEC)
7405     return 0;
7406   if (c == MEM || c == LABEL_REF || c == SYMBOL_REF)
7407     return 10;
7408
7409   if (c == PLUS)
7410     {
7411       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7412         return 2;
7413
7414       if (ARITHMETIC_P (XEXP (x, 0)) || ARITHMETIC_P (XEXP (x, 1)))
7415         return 3;
7416
7417       return 4;
7418     }
7419
7420   return 6;
7421 }
7422
7423 static inline int
7424 arm_thumb_address_cost (rtx x)
7425 {
7426   enum rtx_code c  = GET_CODE (x);
7427
7428   if (c == REG)
7429     return 1;
7430   if (c == PLUS
7431       && GET_CODE (XEXP (x, 0)) == REG
7432       && GET_CODE (XEXP (x, 1)) == CONST_INT)
7433     return 1;
7434
7435   return 2;
7436 }
7437
7438 static int
7439 arm_address_cost (rtx x, bool speed ATTRIBUTE_UNUSED)
7440 {
7441   return TARGET_32BIT ? arm_arm_address_cost (x) : arm_thumb_address_cost (x);
7442 }
7443
7444 static int
7445 arm_adjust_cost (rtx insn, rtx link, rtx dep, int cost)
7446 {
7447   rtx i_pat, d_pat;
7448
7449   /* Some true dependencies can have a higher cost depending
7450      on precisely how certain input operands are used.  */
7451   if (arm_tune_xscale
7452       && REG_NOTE_KIND (link) == 0
7453       && recog_memoized (insn) >= 0
7454       && recog_memoized (dep) >= 0)
7455     {
7456       int shift_opnum = get_attr_shift (insn);
7457       enum attr_type attr_type = get_attr_type (dep);
7458
7459       /* If nonzero, SHIFT_OPNUM contains the operand number of a shifted
7460          operand for INSN.  If we have a shifted input operand and the
7461          instruction we depend on is another ALU instruction, then we may
7462          have to account for an additional stall.  */
7463       if (shift_opnum != 0
7464           && (attr_type == TYPE_ALU_SHIFT || attr_type == TYPE_ALU_SHIFT_REG))
7465         {
7466           rtx shifted_operand;
7467           int opno;
7468
7469           /* Get the shifted operand.  */
7470           extract_insn (insn);
7471           shifted_operand = recog_data.operand[shift_opnum];
7472
7473           /* Iterate over all the operands in DEP.  If we write an operand
7474              that overlaps with SHIFTED_OPERAND, then we have increase the
7475              cost of this dependency.  */
7476           extract_insn (dep);
7477           preprocess_constraints ();
7478           for (opno = 0; opno < recog_data.n_operands; opno++)
7479             {
7480               /* We can ignore strict inputs.  */
7481               if (recog_data.operand_type[opno] == OP_IN)
7482                 continue;
7483
7484               if (reg_overlap_mentioned_p (recog_data.operand[opno],
7485                                            shifted_operand))
7486                 return 2;
7487             }
7488         }
7489     }
7490
7491   /* XXX This is not strictly true for the FPA.  */
7492   if (REG_NOTE_KIND (link) == REG_DEP_ANTI
7493       || REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
7494     return 0;
7495
7496   /* Call insns don't incur a stall, even if they follow a load.  */
7497   if (REG_NOTE_KIND (link) == 0
7498       && GET_CODE (insn) == CALL_INSN)
7499     return 1;
7500
7501   if ((i_pat = single_set (insn)) != NULL
7502       && GET_CODE (SET_SRC (i_pat)) == MEM
7503       && (d_pat = single_set (dep)) != NULL
7504       && GET_CODE (SET_DEST (d_pat)) == MEM)
7505     {
7506       rtx src_mem = XEXP (SET_SRC (i_pat), 0);
7507       /* This is a load after a store, there is no conflict if the load reads
7508          from a cached area.  Assume that loads from the stack, and from the
7509          constant pool are cached, and that others will miss.  This is a
7510          hack.  */
7511
7512       if ((GET_CODE (src_mem) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (src_mem))
7513           || reg_mentioned_p (stack_pointer_rtx, src_mem)
7514           || reg_mentioned_p (frame_pointer_rtx, src_mem)
7515           || reg_mentioned_p (hard_frame_pointer_rtx, src_mem))
7516         return 1;
7517     }
7518
7519   return cost;
7520 }
7521
7522 static int fp_consts_inited = 0;
7523
7524 /* Only zero is valid for VFP.  Other values are also valid for FPA.  */
7525 static const char * const strings_fp[8] =
7526 {
7527   "0",   "1",   "2",   "3",
7528   "4",   "5",   "0.5", "10"
7529 };
7530
7531 static REAL_VALUE_TYPE values_fp[8];
7532
7533 static void
7534 init_fp_table (void)
7535 {
7536   int i;
7537   REAL_VALUE_TYPE r;
7538
7539   if (TARGET_VFP)
7540     fp_consts_inited = 1;
7541   else
7542     fp_consts_inited = 8;
7543
7544   for (i = 0; i < fp_consts_inited; i++)
7545     {
7546       r = REAL_VALUE_ATOF (strings_fp[i], DFmode);
7547       values_fp[i] = r;
7548     }
7549 }
7550
7551 /* Return TRUE if rtx X is a valid immediate FP constant.  */
7552 int
7553 arm_const_double_rtx (rtx x)
7554 {
7555   REAL_VALUE_TYPE r;
7556   int i;
7557
7558   if (!fp_consts_inited)
7559     init_fp_table ();
7560
7561   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
7562   if (REAL_VALUE_MINUS_ZERO (r))
7563     return 0;
7564
7565   for (i = 0; i < fp_consts_inited; i++)
7566     if (REAL_VALUES_EQUAL (r, values_fp[i]))
7567       return 1;
7568
7569   return 0;
7570 }
7571
7572 /* Return TRUE if rtx X is a valid immediate FPA constant.  */
7573 int
7574 neg_const_double_rtx_ok_for_fpa (rtx x)
7575 {
7576   REAL_VALUE_TYPE r;
7577   int i;
7578
7579   if (!fp_consts_inited)
7580     init_fp_table ();
7581
7582   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
7583   r = REAL_VALUE_NEGATE (r);
7584   if (REAL_VALUE_MINUS_ZERO (r))
7585     return 0;
7586
7587   for (i = 0; i < 8; i++)
7588     if (REAL_VALUES_EQUAL (r, values_fp[i]))
7589       return 1;
7590
7591   return 0;
7592 }
7593
7594
7595 /* VFPv3 has a fairly wide range of representable immediates, formed from
7596    "quarter-precision" floating-point values. These can be evaluated using this
7597    formula (with ^ for exponentiation):
7598
7599      -1^s * n * 2^-r
7600
7601    Where 's' is a sign bit (0/1), 'n' and 'r' are integers such that
7602    16 <= n <= 31 and 0 <= r <= 7.
7603
7604    These values are mapped onto an 8-bit integer ABCDEFGH s.t.
7605
7606      - A (most-significant) is the sign bit.
7607      - BCD are the exponent (encoded as r XOR 3).
7608      - EFGH are the mantissa (encoded as n - 16).
7609 */
7610
7611 /* Return an integer index for a VFPv3 immediate operand X suitable for the
7612    fconst[sd] instruction, or -1 if X isn't suitable.  */
7613 static int
7614 vfp3_const_double_index (rtx x)
7615 {
7616   REAL_VALUE_TYPE r, m;
7617   int sign, exponent;
7618   unsigned HOST_WIDE_INT mantissa, mant_hi;
7619   unsigned HOST_WIDE_INT mask;
7620   HOST_WIDE_INT m1, m2;
7621   int point_pos = 2 * HOST_BITS_PER_WIDE_INT - 1;
7622
7623   if (!TARGET_VFP3 || GET_CODE (x) != CONST_DOUBLE)
7624     return -1;
7625
7626   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
7627
7628   /* We can't represent these things, so detect them first.  */
7629   if (REAL_VALUE_ISINF (r) || REAL_VALUE_ISNAN (r) || REAL_VALUE_MINUS_ZERO (r))
7630     return -1;
7631
7632   /* Extract sign, exponent and mantissa.  */
7633   sign = REAL_VALUE_NEGATIVE (r) ? 1 : 0;
7634   r = REAL_VALUE_ABS (r);
7635   exponent = REAL_EXP (&r);
7636   /* For the mantissa, we expand into two HOST_WIDE_INTS, apart from the
7637      highest (sign) bit, with a fixed binary point at bit point_pos.
7638      WARNING: If there's ever a VFP version which uses more than 2 * H_W_I - 1
7639      bits for the mantissa, this may fail (low bits would be lost).  */
7640   real_ldexp (&m, &r, point_pos - exponent);
7641   REAL_VALUE_TO_INT (&m1, &m2, m);
7642   mantissa = m1;
7643   mant_hi = m2;
7644
7645   /* If there are bits set in the low part of the mantissa, we can't
7646      represent this value.  */
7647   if (mantissa != 0)
7648     return -1;
7649
7650   /* Now make it so that mantissa contains the most-significant bits, and move
7651      the point_pos to indicate that the least-significant bits have been
7652      discarded.  */
7653   point_pos -= HOST_BITS_PER_WIDE_INT;
7654   mantissa = mant_hi;
7655
7656   /* We can permit four significant bits of mantissa only, plus a high bit
7657      which is always 1.  */
7658   mask = ((unsigned HOST_WIDE_INT)1 << (point_pos - 5)) - 1;
7659   if ((mantissa & mask) != 0)
7660     return -1;
7661
7662   /* Now we know the mantissa is in range, chop off the unneeded bits.  */
7663   mantissa >>= point_pos - 5;
7664
7665   /* The mantissa may be zero. Disallow that case. (It's possible to load the
7666      floating-point immediate zero with Neon using an integer-zero load, but
7667      that case is handled elsewhere.)  */
7668   if (mantissa == 0)
7669     return -1;
7670
7671   gcc_assert (mantissa >= 16 && mantissa <= 31);
7672
7673   /* The value of 5 here would be 4 if GCC used IEEE754-like encoding (where
7674      normalized significands are in the range [1, 2). (Our mantissa is shifted
7675      left 4 places at this point relative to normalized IEEE754 values).  GCC
7676      internally uses [0.5, 1) (see real.c), so the exponent returned from
7677      REAL_EXP must be altered.  */
7678   exponent = 5 - exponent;
7679
7680   if (exponent < 0 || exponent > 7)
7681     return -1;
7682
7683   /* Sign, mantissa and exponent are now in the correct form to plug into the
7684      formula described in the comment above.  */
7685   return (sign << 7) | ((exponent ^ 3) << 4) | (mantissa - 16);
7686 }
7687
7688 /* Return TRUE if rtx X is a valid immediate VFPv3 constant.  */
7689 int
7690 vfp3_const_double_rtx (rtx x)
7691 {
7692   if (!TARGET_VFP3)
7693     return 0;
7694
7695   return vfp3_const_double_index (x) != -1;
7696 }
7697
7698 /* Recognize immediates which can be used in various Neon instructions. Legal
7699    immediates are described by the following table (for VMVN variants, the
7700    bitwise inverse of the constant shown is recognized. In either case, VMOV
7701    is output and the correct instruction to use for a given constant is chosen
7702    by the assembler). The constant shown is replicated across all elements of
7703    the destination vector.
7704
7705    insn elems variant constant (binary)
7706    ---- ----- ------- -----------------
7707    vmov  i32     0    00000000 00000000 00000000 abcdefgh
7708    vmov  i32     1    00000000 00000000 abcdefgh 00000000
7709    vmov  i32     2    00000000 abcdefgh 00000000 00000000
7710    vmov  i32     3    abcdefgh 00000000 00000000 00000000
7711    vmov  i16     4    00000000 abcdefgh
7712    vmov  i16     5    abcdefgh 00000000
7713    vmvn  i32     6    00000000 00000000 00000000 abcdefgh
7714    vmvn  i32     7    00000000 00000000 abcdefgh 00000000
7715    vmvn  i32     8    00000000 abcdefgh 00000000 00000000
7716    vmvn  i32     9    abcdefgh 00000000 00000000 00000000
7717    vmvn  i16    10    00000000 abcdefgh
7718    vmvn  i16    11    abcdefgh 00000000
7719    vmov  i32    12    00000000 00000000 abcdefgh 11111111
7720    vmvn  i32    13    00000000 00000000 abcdefgh 11111111
7721    vmov  i32    14    00000000 abcdefgh 11111111 11111111
7722    vmvn  i32    15    00000000 abcdefgh 11111111 11111111
7723    vmov   i8    16    abcdefgh
7724    vmov  i64    17    aaaaaaaa bbbbbbbb cccccccc dddddddd
7725                       eeeeeeee ffffffff gggggggg hhhhhhhh
7726    vmov  f32    18    aBbbbbbc defgh000 00000000 00000000
7727
7728    For case 18, B = !b. Representable values are exactly those accepted by
7729    vfp3_const_double_index, but are output as floating-point numbers rather
7730    than indices.
7731
7732    Variants 0-5 (inclusive) may also be used as immediates for the second
7733    operand of VORR/VBIC instructions.
7734
7735    The INVERSE argument causes the bitwise inverse of the given operand to be
7736    recognized instead (used for recognizing legal immediates for the VAND/VORN
7737    pseudo-instructions). If INVERSE is true, the value placed in *MODCONST is
7738    *not* inverted (i.e. the pseudo-instruction forms vand/vorn should still be
7739    output, rather than the real insns vbic/vorr).
7740
7741    INVERSE makes no difference to the recognition of float vectors.
7742
7743    The return value is the variant of immediate as shown in the above table, or
7744    -1 if the given value doesn't match any of the listed patterns.
7745 */
7746 static int
7747 neon_valid_immediate (rtx op, enum machine_mode mode, int inverse,
7748                       rtx *modconst, int *elementwidth)
7749 {
7750 #define CHECK(STRIDE, ELSIZE, CLASS, TEST)      \
7751   matches = 1;                                  \
7752   for (i = 0; i < idx; i += (STRIDE))           \
7753     if (!(TEST))                                \
7754       matches = 0;                              \
7755   if (matches)                                  \
7756     {                                           \
7757       immtype = (CLASS);                        \
7758       elsize = (ELSIZE);                        \
7759       break;                                    \
7760     }
7761
7762   unsigned int i, elsize = 0, idx = 0, n_elts = CONST_VECTOR_NUNITS (op);
7763   unsigned int innersize = GET_MODE_SIZE (GET_MODE_INNER (mode));
7764   unsigned char bytes[16];
7765   int immtype = -1, matches;
7766   unsigned int invmask = inverse ? 0xff : 0;
7767
7768   /* Vectors of float constants.  */
7769   if (GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
7770     {
7771       rtx el0 = CONST_VECTOR_ELT (op, 0);
7772       REAL_VALUE_TYPE r0;
7773
7774       if (!vfp3_const_double_rtx (el0))
7775         return -1;
7776
7777       REAL_VALUE_FROM_CONST_DOUBLE (r0, el0);
7778
7779       for (i = 1; i < n_elts; i++)
7780         {
7781           rtx elt = CONST_VECTOR_ELT (op, i);
7782           REAL_VALUE_TYPE re;
7783
7784           REAL_VALUE_FROM_CONST_DOUBLE (re, elt);
7785
7786           if (!REAL_VALUES_EQUAL (r0, re))
7787             return -1;
7788         }
7789
7790       if (modconst)
7791         *modconst = CONST_VECTOR_ELT (op, 0);
7792
7793       if (elementwidth)
7794         *elementwidth = 0;
7795
7796       return 18;
7797     }
7798
7799   /* Splat vector constant out into a byte vector.  */
7800   for (i = 0; i < n_elts; i++)
7801     {
7802       rtx el = CONST_VECTOR_ELT (op, i);
7803       unsigned HOST_WIDE_INT elpart;
7804       unsigned int part, parts;
7805
7806       if (GET_CODE (el) == CONST_INT)
7807         {
7808           elpart = INTVAL (el);
7809           parts = 1;
7810         }
7811       else if (GET_CODE (el) == CONST_DOUBLE)
7812         {
7813           elpart = CONST_DOUBLE_LOW (el);
7814           parts = 2;
7815         }
7816       else
7817         gcc_unreachable ();
7818
7819       for (part = 0; part < parts; part++)
7820         {
7821           unsigned int byte;
7822           for (byte = 0; byte < innersize; byte++)
7823             {
7824               bytes[idx++] = (elpart & 0xff) ^ invmask;
7825               elpart >>= BITS_PER_UNIT;
7826             }
7827           if (GET_CODE (el) == CONST_DOUBLE)
7828             elpart = CONST_DOUBLE_HIGH (el);
7829         }
7830     }
7831
7832   /* Sanity check.  */
7833   gcc_assert (idx == GET_MODE_SIZE (mode));
7834
7835   do
7836     {
7837       CHECK (4, 32, 0, bytes[i] == bytes[0] && bytes[i + 1] == 0
7838                        && bytes[i + 2] == 0 && bytes[i + 3] == 0);
7839
7840       CHECK (4, 32, 1, bytes[i] == 0 && bytes[i + 1] == bytes[1]
7841                        && bytes[i + 2] == 0 && bytes[i + 3] == 0);
7842
7843       CHECK (4, 32, 2, bytes[i] == 0 && bytes[i + 1] == 0
7844                        && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0);
7845
7846       CHECK (4, 32, 3, bytes[i] == 0 && bytes[i + 1] == 0
7847                        && bytes[i + 2] == 0 && bytes[i + 3] == bytes[3]);
7848
7849       CHECK (2, 16, 4, bytes[i] == bytes[0] && bytes[i + 1] == 0);
7850
7851       CHECK (2, 16, 5, bytes[i] == 0 && bytes[i + 1] == bytes[1]);
7852
7853       CHECK (4, 32, 6, bytes[i] == bytes[0] && bytes[i + 1] == 0xff
7854                        && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
7855
7856       CHECK (4, 32, 7, bytes[i] == 0xff && bytes[i + 1] == bytes[1]
7857                        && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
7858
7859       CHECK (4, 32, 8, bytes[i] == 0xff && bytes[i + 1] == 0xff
7860                        && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0xff);
7861
7862       CHECK (4, 32, 9, bytes[i] == 0xff && bytes[i + 1] == 0xff
7863                        && bytes[i + 2] == 0xff && bytes[i + 3] == bytes[3]);
7864
7865       CHECK (2, 16, 10, bytes[i] == bytes[0] && bytes[i + 1] == 0xff);
7866
7867       CHECK (2, 16, 11, bytes[i] == 0xff && bytes[i + 1] == bytes[1]);
7868
7869       CHECK (4, 32, 12, bytes[i] == 0xff && bytes[i + 1] == bytes[1]
7870                         && bytes[i + 2] == 0 && bytes[i + 3] == 0);
7871
7872       CHECK (4, 32, 13, bytes[i] == 0 && bytes[i + 1] == bytes[1]
7873                         && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
7874
7875       CHECK (4, 32, 14, bytes[i] == 0xff && bytes[i + 1] == 0xff
7876                         && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0);
7877
7878       CHECK (4, 32, 15, bytes[i] == 0 && bytes[i + 1] == 0
7879                         && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0xff);
7880
7881       CHECK (1, 8, 16, bytes[i] == bytes[0]);
7882
7883       CHECK (1, 64, 17, (bytes[i] == 0 || bytes[i] == 0xff)
7884                         && bytes[i] == bytes[(i + 8) % idx]);
7885     }
7886   while (0);
7887
7888   if (immtype == -1)
7889     return -1;
7890
7891   if (elementwidth)
7892     *elementwidth = elsize;
7893
7894   if (modconst)
7895     {
7896       unsigned HOST_WIDE_INT imm = 0;
7897
7898       /* Un-invert bytes of recognized vector, if necessary.  */
7899       if (invmask != 0)
7900         for (i = 0; i < idx; i++)
7901           bytes[i] ^= invmask;
7902
7903       if (immtype == 17)
7904         {
7905           /* FIXME: Broken on 32-bit H_W_I hosts.  */
7906           gcc_assert (sizeof (HOST_WIDE_INT) == 8);
7907
7908           for (i = 0; i < 8; i++)
7909             imm |= (unsigned HOST_WIDE_INT) (bytes[i] ? 0xff : 0)
7910                    << (i * BITS_PER_UNIT);
7911
7912           *modconst = GEN_INT (imm);
7913         }
7914       else
7915         {
7916           unsigned HOST_WIDE_INT imm = 0;
7917
7918           for (i = 0; i < elsize / BITS_PER_UNIT; i++)
7919             imm |= (unsigned HOST_WIDE_INT) bytes[i] << (i * BITS_PER_UNIT);
7920
7921           *modconst = GEN_INT (imm);
7922         }
7923     }
7924
7925   return immtype;
7926 #undef CHECK
7927 }
7928
7929 /* Return TRUE if rtx X is legal for use as either a Neon VMOV (or, implicitly,
7930    VMVN) immediate. Write back width per element to *ELEMENTWIDTH (or zero for
7931    float elements), and a modified constant (whatever should be output for a
7932    VMOV) in *MODCONST.  */
7933
7934 int
7935 neon_immediate_valid_for_move (rtx op, enum machine_mode mode,
7936                                rtx *modconst, int *elementwidth)
7937 {
7938   rtx tmpconst;
7939   int tmpwidth;
7940   int retval = neon_valid_immediate (op, mode, 0, &tmpconst, &tmpwidth);
7941
7942   if (retval == -1)
7943     return 0;
7944
7945   if (modconst)
7946     *modconst = tmpconst;
7947
7948   if (elementwidth)
7949     *elementwidth = tmpwidth;
7950
7951   return 1;
7952 }
7953
7954 /* Return TRUE if rtx X is legal for use in a VORR or VBIC instruction.  If
7955    the immediate is valid, write a constant suitable for using as an operand
7956    to VORR/VBIC/VAND/VORN to *MODCONST and the corresponding element width to
7957    *ELEMENTWIDTH. See neon_valid_immediate for description of INVERSE.  */
7958
7959 int
7960 neon_immediate_valid_for_logic (rtx op, enum machine_mode mode, int inverse,
7961                                 rtx *modconst, int *elementwidth)
7962 {
7963   rtx tmpconst;
7964   int tmpwidth;
7965   int retval = neon_valid_immediate (op, mode, inverse, &tmpconst, &tmpwidth);
7966
7967   if (retval < 0 || retval > 5)
7968     return 0;
7969
7970   if (modconst)
7971     *modconst = tmpconst;
7972
7973   if (elementwidth)
7974     *elementwidth = tmpwidth;
7975
7976   return 1;
7977 }
7978
7979 /* Return a string suitable for output of Neon immediate logic operation
7980    MNEM.  */
7981
7982 char *
7983 neon_output_logic_immediate (const char *mnem, rtx *op2, enum machine_mode mode,
7984                              int inverse, int quad)
7985 {
7986   int width, is_valid;
7987   static char templ[40];
7988
7989   is_valid = neon_immediate_valid_for_logic (*op2, mode, inverse, op2, &width);
7990
7991   gcc_assert (is_valid != 0);
7992
7993   if (quad)
7994     sprintf (templ, "%s.i%d\t%%q0, %%2", mnem, width);
7995   else
7996     sprintf (templ, "%s.i%d\t%%P0, %%2", mnem, width);
7997
7998   return templ;
7999 }
8000
8001 /* Output a sequence of pairwise operations to implement a reduction.
8002    NOTE: We do "too much work" here, because pairwise operations work on two
8003    registers-worth of operands in one go. Unfortunately we can't exploit those
8004    extra calculations to do the full operation in fewer steps, I don't think.
8005    Although all vector elements of the result but the first are ignored, we
8006    actually calculate the same result in each of the elements. An alternative
8007    such as initially loading a vector with zero to use as each of the second
8008    operands would use up an additional register and take an extra instruction,
8009    for no particular gain.  */
8010
8011 void
8012 neon_pairwise_reduce (rtx op0, rtx op1, enum machine_mode mode,
8013                       rtx (*reduc) (rtx, rtx, rtx))
8014 {
8015   enum machine_mode inner = GET_MODE_INNER (mode);
8016   unsigned int i, parts = GET_MODE_SIZE (mode) / GET_MODE_SIZE (inner);
8017   rtx tmpsum = op1;
8018
8019   for (i = parts / 2; i >= 1; i /= 2)
8020     {
8021       rtx dest = (i == 1) ? op0 : gen_reg_rtx (mode);
8022       emit_insn (reduc (dest, tmpsum, tmpsum));
8023       tmpsum = dest;
8024     }
8025 }
8026
8027 /* Initialize a vector with non-constant elements.  FIXME: We can do better
8028    than the current implementation (building a vector on the stack and then
8029    loading it) in many cases.  See rs6000.c.  */
8030
8031 void
8032 neon_expand_vector_init (rtx target, rtx vals)
8033 {
8034   enum machine_mode mode = GET_MODE (target);
8035   enum machine_mode inner = GET_MODE_INNER (mode);
8036   unsigned int i, n_elts = GET_MODE_NUNITS (mode);
8037   rtx mem;
8038
8039   gcc_assert (VECTOR_MODE_P (mode));
8040
8041   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode), 0);
8042   for (i = 0; i < n_elts; i++)
8043     emit_move_insn (adjust_address_nv (mem, inner, i * GET_MODE_SIZE (inner)),
8044                    XVECEXP (vals, 0, i));
8045
8046   emit_move_insn (target, mem);
8047 }
8048
8049 /* Ensure OPERAND lies between LOW (inclusive) and HIGH (exclusive).  Raise
8050    ERR if it doesn't.  FIXME: NEON bounds checks occur late in compilation, so
8051    reported source locations are bogus.  */
8052
8053 static void
8054 bounds_check (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high,
8055               const char *err)
8056 {
8057   HOST_WIDE_INT lane;
8058
8059   gcc_assert (GET_CODE (operand) == CONST_INT);
8060
8061   lane = INTVAL (operand);
8062
8063   if (lane < low || lane >= high)
8064     error (err);
8065 }
8066
8067 /* Bounds-check lanes.  */
8068
8069 void
8070 neon_lane_bounds (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high)
8071 {
8072   bounds_check (operand, low, high, "lane out of range");
8073 }
8074
8075 /* Bounds-check constants.  */
8076
8077 void
8078 neon_const_bounds (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high)
8079 {
8080   bounds_check (operand, low, high, "constant out of range");
8081 }
8082
8083 HOST_WIDE_INT
8084 neon_element_bits (enum machine_mode mode)
8085 {
8086   if (mode == DImode)
8087     return GET_MODE_BITSIZE (mode);
8088   else
8089     return GET_MODE_BITSIZE (GET_MODE_INNER (mode));
8090 }
8091
8092 \f
8093 /* Predicates for `match_operand' and `match_operator'.  */
8094
8095 /* Return nonzero if OP is a valid Cirrus memory address pattern.  */
8096 int
8097 cirrus_memory_offset (rtx op)
8098 {
8099   /* Reject eliminable registers.  */
8100   if (! (reload_in_progress || reload_completed)
8101       && (   reg_mentioned_p (frame_pointer_rtx, op)
8102           || reg_mentioned_p (arg_pointer_rtx, op)
8103           || reg_mentioned_p (virtual_incoming_args_rtx, op)
8104           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
8105           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
8106           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
8107     return 0;
8108
8109   if (GET_CODE (op) == MEM)
8110     {
8111       rtx ind;
8112
8113       ind = XEXP (op, 0);
8114
8115       /* Match: (mem (reg)).  */
8116       if (GET_CODE (ind) == REG)
8117         return 1;
8118
8119       /* Match:
8120          (mem (plus (reg)
8121                     (const))).  */
8122       if (GET_CODE (ind) == PLUS
8123           && GET_CODE (XEXP (ind, 0)) == REG
8124           && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
8125           && GET_CODE (XEXP (ind, 1)) == CONST_INT)
8126         return 1;
8127     }
8128
8129   return 0;
8130 }
8131
8132 /* Return TRUE if OP is a valid coprocessor memory address pattern.
8133    WB is true if full writeback address modes are allowed and is false
8134    if limited writeback address modes (POST_INC and PRE_DEC) are
8135    allowed.  */
8136
8137 int
8138 arm_coproc_mem_operand (rtx op, bool wb)
8139 {
8140   rtx ind;
8141
8142   /* Reject eliminable registers.  */
8143   if (! (reload_in_progress || reload_completed)
8144       && (   reg_mentioned_p (frame_pointer_rtx, op)
8145           || reg_mentioned_p (arg_pointer_rtx, op)
8146           || reg_mentioned_p (virtual_incoming_args_rtx, op)
8147           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
8148           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
8149           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
8150     return FALSE;
8151
8152   /* Constants are converted into offsets from labels.  */
8153   if (GET_CODE (op) != MEM)
8154     return FALSE;
8155
8156   ind = XEXP (op, 0);
8157
8158   if (reload_completed
8159       && (GET_CODE (ind) == LABEL_REF
8160           || (GET_CODE (ind) == CONST
8161               && GET_CODE (XEXP (ind, 0)) == PLUS
8162               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
8163               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
8164     return TRUE;
8165
8166   /* Match: (mem (reg)).  */
8167   if (GET_CODE (ind) == REG)
8168     return arm_address_register_rtx_p (ind, 0);
8169
8170   /* Autoincremment addressing modes.  POST_INC and PRE_DEC are
8171      acceptable in any case (subject to verification by
8172      arm_address_register_rtx_p).  We need WB to be true to accept
8173      PRE_INC and POST_DEC.  */
8174   if (GET_CODE (ind) == POST_INC
8175       || GET_CODE (ind) == PRE_DEC
8176       || (wb
8177           && (GET_CODE (ind) == PRE_INC
8178               || GET_CODE (ind) == POST_DEC)))
8179     return arm_address_register_rtx_p (XEXP (ind, 0), 0);
8180
8181   if (wb
8182       && (GET_CODE (ind) == POST_MODIFY || GET_CODE (ind) == PRE_MODIFY)
8183       && arm_address_register_rtx_p (XEXP (ind, 0), 0)
8184       && GET_CODE (XEXP (ind, 1)) == PLUS
8185       && rtx_equal_p (XEXP (XEXP (ind, 1), 0), XEXP (ind, 0)))
8186     ind = XEXP (ind, 1);
8187
8188   /* Match:
8189      (plus (reg)
8190            (const)).  */
8191   if (GET_CODE (ind) == PLUS
8192       && GET_CODE (XEXP (ind, 0)) == REG
8193       && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
8194       && GET_CODE (XEXP (ind, 1)) == CONST_INT
8195       && INTVAL (XEXP (ind, 1)) > -1024
8196       && INTVAL (XEXP (ind, 1)) <  1024
8197       && (INTVAL (XEXP (ind, 1)) & 3) == 0)
8198     return TRUE;
8199
8200   return FALSE;
8201 }
8202
8203 /* Return TRUE if OP is a memory operand which we can load or store a vector
8204    to/from. TYPE is one of the following values:
8205     0 - Vector load/stor (vldr)
8206     1 - Core registers (ldm)
8207     2 - Element/structure loads (vld1)
8208  */
8209 int
8210 neon_vector_mem_operand (rtx op, int type)
8211 {
8212   rtx ind;
8213
8214   /* Reject eliminable registers.  */
8215   if (! (reload_in_progress || reload_completed)
8216       && (   reg_mentioned_p (frame_pointer_rtx, op)
8217           || reg_mentioned_p (arg_pointer_rtx, op)
8218           || reg_mentioned_p (virtual_incoming_args_rtx, op)
8219           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
8220           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
8221           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
8222     return FALSE;
8223
8224   /* Constants are converted into offsets from labels.  */
8225   if (GET_CODE (op) != MEM)
8226     return FALSE;
8227
8228   ind = XEXP (op, 0);
8229
8230   if (reload_completed
8231       && (GET_CODE (ind) == LABEL_REF
8232           || (GET_CODE (ind) == CONST
8233               && GET_CODE (XEXP (ind, 0)) == PLUS
8234               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
8235               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
8236     return TRUE;
8237
8238   /* Match: (mem (reg)).  */
8239   if (GET_CODE (ind) == REG)
8240     return arm_address_register_rtx_p (ind, 0);
8241
8242   /* Allow post-increment with Neon registers.  */
8243   if (type != 1 && (GET_CODE (ind) == POST_INC || GET_CODE (ind) == PRE_DEC))
8244     return arm_address_register_rtx_p (XEXP (ind, 0), 0);
8245
8246   /* FIXME: vld1 allows register post-modify.  */
8247
8248   /* Match:
8249      (plus (reg)
8250           (const)).  */
8251   if (type == 0
8252       && GET_CODE (ind) == PLUS
8253       && GET_CODE (XEXP (ind, 0)) == REG
8254       && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
8255       && GET_CODE (XEXP (ind, 1)) == CONST_INT
8256       && INTVAL (XEXP (ind, 1)) > -1024
8257       && INTVAL (XEXP (ind, 1)) < 1016
8258       && (INTVAL (XEXP (ind, 1)) & 3) == 0)
8259     return TRUE;
8260
8261   return FALSE;
8262 }
8263
8264 /* Return TRUE if OP is a mem suitable for loading/storing a Neon struct
8265    type.  */
8266 int
8267 neon_struct_mem_operand (rtx op)
8268 {
8269   rtx ind;
8270
8271   /* Reject eliminable registers.  */
8272   if (! (reload_in_progress || reload_completed)
8273       && (   reg_mentioned_p (frame_pointer_rtx, op)
8274           || reg_mentioned_p (arg_pointer_rtx, op)
8275           || reg_mentioned_p (virtual_incoming_args_rtx, op)
8276           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
8277           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
8278           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
8279     return FALSE;
8280
8281   /* Constants are converted into offsets from labels.  */
8282   if (GET_CODE (op) != MEM)
8283     return FALSE;
8284
8285   ind = XEXP (op, 0);
8286
8287   if (reload_completed
8288       && (GET_CODE (ind) == LABEL_REF
8289           || (GET_CODE (ind) == CONST
8290               && GET_CODE (XEXP (ind, 0)) == PLUS
8291               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
8292               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
8293     return TRUE;
8294
8295   /* Match: (mem (reg)).  */
8296   if (GET_CODE (ind) == REG)
8297     return arm_address_register_rtx_p (ind, 0);
8298
8299   return FALSE;
8300 }
8301
8302 /* Return true if X is a register that will be eliminated later on.  */
8303 int
8304 arm_eliminable_register (rtx x)
8305 {
8306   return REG_P (x) && (REGNO (x) == FRAME_POINTER_REGNUM
8307                        || REGNO (x) == ARG_POINTER_REGNUM
8308                        || (REGNO (x) >= FIRST_VIRTUAL_REGISTER
8309                            && REGNO (x) <= LAST_VIRTUAL_REGISTER));
8310 }
8311
8312 /* Return GENERAL_REGS if a scratch register required to reload x to/from
8313    coprocessor registers.  Otherwise return NO_REGS.  */
8314
8315 enum reg_class
8316 coproc_secondary_reload_class (enum machine_mode mode, rtx x, bool wb)
8317 {
8318   if (mode == HFmode)
8319     {
8320       if (s_register_operand (x, mode) || neon_vector_mem_operand (x, 2))
8321         return NO_REGS;
8322       return GENERAL_REGS;
8323     }
8324
8325   if (TARGET_NEON
8326       && (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
8327           || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
8328       && neon_vector_mem_operand (x, 0))
8329      return NO_REGS;
8330
8331   if (arm_coproc_mem_operand (x, wb) || s_register_operand (x, mode))
8332     return NO_REGS;
8333
8334   return GENERAL_REGS;
8335 }
8336
8337 /* Values which must be returned in the most-significant end of the return
8338    register.  */
8339
8340 static bool
8341 arm_return_in_msb (const_tree valtype)
8342 {
8343   return (TARGET_AAPCS_BASED
8344           && BYTES_BIG_ENDIAN
8345           && (AGGREGATE_TYPE_P (valtype)
8346               || TREE_CODE (valtype) == COMPLEX_TYPE));
8347 }
8348
8349 /* Returns TRUE if INSN is an "LDR REG, ADDR" instruction.
8350    Use by the Cirrus Maverick code which has to workaround
8351    a hardware bug triggered by such instructions.  */
8352 static bool
8353 arm_memory_load_p (rtx insn)
8354 {
8355   rtx body, lhs, rhs;;
8356
8357   if (insn == NULL_RTX || GET_CODE (insn) != INSN)
8358     return false;
8359
8360   body = PATTERN (insn);
8361
8362   if (GET_CODE (body) != SET)
8363     return false;
8364
8365   lhs = XEXP (body, 0);
8366   rhs = XEXP (body, 1);
8367
8368   lhs = REG_OR_SUBREG_RTX (lhs);
8369
8370   /* If the destination is not a general purpose
8371      register we do not have to worry.  */
8372   if (GET_CODE (lhs) != REG
8373       || REGNO_REG_CLASS (REGNO (lhs)) != GENERAL_REGS)
8374     return false;
8375
8376   /* As well as loads from memory we also have to react
8377      to loads of invalid constants which will be turned
8378      into loads from the minipool.  */
8379   return (GET_CODE (rhs) == MEM
8380           || GET_CODE (rhs) == SYMBOL_REF
8381           || note_invalid_constants (insn, -1, false));
8382 }
8383
8384 /* Return TRUE if INSN is a Cirrus instruction.  */
8385 static bool
8386 arm_cirrus_insn_p (rtx insn)
8387 {
8388   enum attr_cirrus attr;
8389
8390   /* get_attr cannot accept USE or CLOBBER.  */
8391   if (!insn
8392       || GET_CODE (insn) != INSN
8393       || GET_CODE (PATTERN (insn)) == USE
8394       || GET_CODE (PATTERN (insn)) == CLOBBER)
8395     return 0;
8396
8397   attr = get_attr_cirrus (insn);
8398
8399   return attr != CIRRUS_NOT;
8400 }
8401
8402 /* Cirrus reorg for invalid instruction combinations.  */
8403 static void
8404 cirrus_reorg (rtx first)
8405 {
8406   enum attr_cirrus attr;
8407   rtx body = PATTERN (first);
8408   rtx t;
8409   int nops;
8410
8411   /* Any branch must be followed by 2 non Cirrus instructions.  */
8412   if (GET_CODE (first) == JUMP_INSN && GET_CODE (body) != RETURN)
8413     {
8414       nops = 0;
8415       t = next_nonnote_insn (first);
8416
8417       if (arm_cirrus_insn_p (t))
8418         ++ nops;
8419
8420       if (arm_cirrus_insn_p (next_nonnote_insn (t)))
8421         ++ nops;
8422
8423       while (nops --)
8424         emit_insn_after (gen_nop (), first);
8425
8426       return;
8427     }
8428
8429   /* (float (blah)) is in parallel with a clobber.  */
8430   if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0) > 0)
8431     body = XVECEXP (body, 0, 0);
8432
8433   if (GET_CODE (body) == SET)
8434     {
8435       rtx lhs = XEXP (body, 0), rhs = XEXP (body, 1);
8436
8437       /* cfldrd, cfldr64, cfstrd, cfstr64 must
8438          be followed by a non Cirrus insn.  */
8439       if (get_attr_cirrus (first) == CIRRUS_DOUBLE)
8440         {
8441           if (arm_cirrus_insn_p (next_nonnote_insn (first)))
8442             emit_insn_after (gen_nop (), first);
8443
8444           return;
8445         }
8446       else if (arm_memory_load_p (first))
8447         {
8448           unsigned int arm_regno;
8449
8450           /* Any ldr/cfmvdlr, ldr/cfmvdhr, ldr/cfmvsr, ldr/cfmv64lr,
8451              ldr/cfmv64hr combination where the Rd field is the same
8452              in both instructions must be split with a non Cirrus
8453              insn.  Example:
8454
8455              ldr r0, blah
8456              nop
8457              cfmvsr mvf0, r0.  */
8458
8459           /* Get Arm register number for ldr insn.  */
8460           if (GET_CODE (lhs) == REG)
8461             arm_regno = REGNO (lhs);
8462           else
8463             {
8464               gcc_assert (GET_CODE (rhs) == REG);
8465               arm_regno = REGNO (rhs);
8466             }
8467
8468           /* Next insn.  */
8469           first = next_nonnote_insn (first);
8470
8471           if (! arm_cirrus_insn_p (first))
8472             return;
8473
8474           body = PATTERN (first);
8475
8476           /* (float (blah)) is in parallel with a clobber.  */
8477           if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0))
8478             body = XVECEXP (body, 0, 0);
8479
8480           if (GET_CODE (body) == FLOAT)
8481             body = XEXP (body, 0);
8482
8483           if (get_attr_cirrus (first) == CIRRUS_MOVE
8484               && GET_CODE (XEXP (body, 1)) == REG
8485               && arm_regno == REGNO (XEXP (body, 1)))
8486             emit_insn_after (gen_nop (), first);
8487
8488           return;
8489         }
8490     }
8491
8492   /* get_attr cannot accept USE or CLOBBER.  */
8493   if (!first
8494       || GET_CODE (first) != INSN
8495       || GET_CODE (PATTERN (first)) == USE
8496       || GET_CODE (PATTERN (first)) == CLOBBER)
8497     return;
8498
8499   attr = get_attr_cirrus (first);
8500
8501   /* Any coprocessor compare instruction (cfcmps, cfcmpd, ...)
8502      must be followed by a non-coprocessor instruction.  */
8503   if (attr == CIRRUS_COMPARE)
8504     {
8505       nops = 0;
8506
8507       t = next_nonnote_insn (first);
8508
8509       if (arm_cirrus_insn_p (t))
8510         ++ nops;
8511
8512       if (arm_cirrus_insn_p (next_nonnote_insn (t)))
8513         ++ nops;
8514
8515       while (nops --)
8516         emit_insn_after (gen_nop (), first);
8517
8518       return;
8519     }
8520 }
8521
8522 /* Return TRUE if X references a SYMBOL_REF.  */
8523 int
8524 symbol_mentioned_p (rtx x)
8525 {
8526   const char * fmt;
8527   int i;
8528
8529   if (GET_CODE (x) == SYMBOL_REF)
8530     return 1;
8531
8532   /* UNSPEC_TLS entries for a symbol include the SYMBOL_REF, but they
8533      are constant offsets, not symbols.  */
8534   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
8535     return 0;
8536
8537   fmt = GET_RTX_FORMAT (GET_CODE (x));
8538
8539   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8540     {
8541       if (fmt[i] == 'E')
8542         {
8543           int j;
8544
8545           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8546             if (symbol_mentioned_p (XVECEXP (x, i, j)))
8547               return 1;
8548         }
8549       else if (fmt[i] == 'e' && symbol_mentioned_p (XEXP (x, i)))
8550         return 1;
8551     }
8552
8553   return 0;
8554 }
8555
8556 /* Return TRUE if X references a LABEL_REF.  */
8557 int
8558 label_mentioned_p (rtx x)
8559 {
8560   const char * fmt;
8561   int i;
8562
8563   if (GET_CODE (x) == LABEL_REF)
8564     return 1;
8565
8566   /* UNSPEC_TLS entries for a symbol include a LABEL_REF for the referencing
8567      instruction, but they are constant offsets, not symbols.  */
8568   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
8569     return 0;
8570
8571   fmt = GET_RTX_FORMAT (GET_CODE (x));
8572   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8573     {
8574       if (fmt[i] == 'E')
8575         {
8576           int j;
8577
8578           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
8579             if (label_mentioned_p (XVECEXP (x, i, j)))
8580               return 1;
8581         }
8582       else if (fmt[i] == 'e' && label_mentioned_p (XEXP (x, i)))
8583         return 1;
8584     }
8585
8586   return 0;
8587 }
8588
8589 int
8590 tls_mentioned_p (rtx x)
8591 {
8592   switch (GET_CODE (x))
8593     {
8594     case CONST:
8595       return tls_mentioned_p (XEXP (x, 0));
8596
8597     case UNSPEC:
8598       if (XINT (x, 1) == UNSPEC_TLS)
8599         return 1;
8600
8601     default:
8602       return 0;
8603     }
8604 }
8605
8606 /* Must not copy a SET whose source operand is PC-relative.  */
8607
8608 static bool
8609 arm_cannot_copy_insn_p (rtx insn)
8610 {
8611   rtx pat = PATTERN (insn);
8612
8613   if (GET_CODE (pat) == SET)
8614     {
8615       rtx rhs = SET_SRC (pat);
8616
8617       if (GET_CODE (rhs) == UNSPEC
8618           && XINT (rhs, 1) == UNSPEC_PIC_BASE)
8619         return TRUE;
8620
8621       if (GET_CODE (rhs) == MEM
8622           && GET_CODE (XEXP (rhs, 0)) == UNSPEC
8623           && XINT (XEXP (rhs, 0), 1) == UNSPEC_PIC_BASE)
8624         return TRUE;
8625     }
8626
8627   return FALSE;
8628 }
8629
8630 enum rtx_code
8631 minmax_code (rtx x)
8632 {
8633   enum rtx_code code = GET_CODE (x);
8634
8635   switch (code)
8636     {
8637     case SMAX:
8638       return GE;
8639     case SMIN:
8640       return LE;
8641     case UMIN:
8642       return LEU;
8643     case UMAX:
8644       return GEU;
8645     default:
8646       gcc_unreachable ();
8647     }
8648 }
8649
8650 /* Return 1 if memory locations are adjacent.  */
8651 int
8652 adjacent_mem_locations (rtx a, rtx b)
8653 {
8654   /* We don't guarantee to preserve the order of these memory refs.  */
8655   if (volatile_refs_p (a) || volatile_refs_p (b))
8656     return 0;
8657
8658   if ((GET_CODE (XEXP (a, 0)) == REG
8659        || (GET_CODE (XEXP (a, 0)) == PLUS
8660            && GET_CODE (XEXP (XEXP (a, 0), 1)) == CONST_INT))
8661       && (GET_CODE (XEXP (b, 0)) == REG
8662           || (GET_CODE (XEXP (b, 0)) == PLUS
8663               && GET_CODE (XEXP (XEXP (b, 0), 1)) == CONST_INT)))
8664     {
8665       HOST_WIDE_INT val0 = 0, val1 = 0;
8666       rtx reg0, reg1;
8667       int val_diff;
8668
8669       if (GET_CODE (XEXP (a, 0)) == PLUS)
8670         {
8671           reg0 = XEXP (XEXP (a, 0), 0);
8672           val0 = INTVAL (XEXP (XEXP (a, 0), 1));
8673         }
8674       else
8675         reg0 = XEXP (a, 0);
8676
8677       if (GET_CODE (XEXP (b, 0)) == PLUS)
8678         {
8679           reg1 = XEXP (XEXP (b, 0), 0);
8680           val1 = INTVAL (XEXP (XEXP (b, 0), 1));
8681         }
8682       else
8683         reg1 = XEXP (b, 0);
8684
8685       /* Don't accept any offset that will require multiple
8686          instructions to handle, since this would cause the
8687          arith_adjacentmem pattern to output an overlong sequence.  */
8688       if (!const_ok_for_op (val0, PLUS) || !const_ok_for_op (val1, PLUS))
8689         return 0;
8690
8691       /* Don't allow an eliminable register: register elimination can make
8692          the offset too large.  */
8693       if (arm_eliminable_register (reg0))
8694         return 0;
8695
8696       val_diff = val1 - val0;
8697
8698       if (arm_ld_sched)
8699         {
8700           /* If the target has load delay slots, then there's no benefit
8701              to using an ldm instruction unless the offset is zero and
8702              we are optimizing for size.  */
8703           return (optimize_size && (REGNO (reg0) == REGNO (reg1))
8704                   && (val0 == 0 || val1 == 0 || val0 == 4 || val1 == 4)
8705                   && (val_diff == 4 || val_diff == -4));
8706         }
8707
8708       return ((REGNO (reg0) == REGNO (reg1))
8709               && (val_diff == 4 || val_diff == -4));
8710     }
8711
8712   return 0;
8713 }
8714
8715 int
8716 load_multiple_sequence (rtx *operands, int nops, int *regs, int *base,
8717                         HOST_WIDE_INT *load_offset)
8718 {
8719   int unsorted_regs[4];
8720   HOST_WIDE_INT unsorted_offsets[4];
8721   int order[4];
8722   int base_reg = -1;
8723   int i;
8724
8725   /* Can only handle 2, 3, or 4 insns at present,
8726      though could be easily extended if required.  */
8727   gcc_assert (nops >= 2 && nops <= 4);
8728
8729   memset (order, 0, 4 * sizeof (int));
8730
8731   /* Loop over the operands and check that the memory references are
8732      suitable (i.e. immediate offsets from the same base register).  At
8733      the same time, extract the target register, and the memory
8734      offsets.  */
8735   for (i = 0; i < nops; i++)
8736     {
8737       rtx reg;
8738       rtx offset;
8739
8740       /* Convert a subreg of a mem into the mem itself.  */
8741       if (GET_CODE (operands[nops + i]) == SUBREG)
8742         operands[nops + i] = alter_subreg (operands + (nops + i));
8743
8744       gcc_assert (GET_CODE (operands[nops + i]) == MEM);
8745
8746       /* Don't reorder volatile memory references; it doesn't seem worth
8747          looking for the case where the order is ok anyway.  */
8748       if (MEM_VOLATILE_P (operands[nops + i]))
8749         return 0;
8750
8751       offset = const0_rtx;
8752
8753       if ((GET_CODE (reg = XEXP (operands[nops + i], 0)) == REG
8754            || (GET_CODE (reg) == SUBREG
8755                && GET_CODE (reg = SUBREG_REG (reg)) == REG))
8756           || (GET_CODE (XEXP (operands[nops + i], 0)) == PLUS
8757               && ((GET_CODE (reg = XEXP (XEXP (operands[nops + i], 0), 0))
8758                    == REG)
8759                   || (GET_CODE (reg) == SUBREG
8760                       && GET_CODE (reg = SUBREG_REG (reg)) == REG))
8761               && (GET_CODE (offset = XEXP (XEXP (operands[nops + i], 0), 1))
8762                   == CONST_INT)))
8763         {
8764           if (i == 0)
8765             {
8766               base_reg = REGNO (reg);
8767               unsorted_regs[0] = (GET_CODE (operands[i]) == REG
8768                                   ? REGNO (operands[i])
8769                                   : REGNO (SUBREG_REG (operands[i])));
8770               order[0] = 0;
8771             }
8772           else
8773             {
8774               if (base_reg != (int) REGNO (reg))
8775                 /* Not addressed from the same base register.  */
8776                 return 0;
8777
8778               unsorted_regs[i] = (GET_CODE (operands[i]) == REG
8779                                   ? REGNO (operands[i])
8780                                   : REGNO (SUBREG_REG (operands[i])));
8781               if (unsorted_regs[i] < unsorted_regs[order[0]])
8782                 order[0] = i;
8783             }
8784
8785           /* If it isn't an integer register, or if it overwrites the
8786              base register but isn't the last insn in the list, then
8787              we can't do this.  */
8788           if (unsorted_regs[i] < 0 || unsorted_regs[i] > 14
8789               || (i != nops - 1 && unsorted_regs[i] == base_reg))
8790             return 0;
8791
8792           unsorted_offsets[i] = INTVAL (offset);
8793         }
8794       else
8795         /* Not a suitable memory address.  */
8796         return 0;
8797     }
8798
8799   /* All the useful information has now been extracted from the
8800      operands into unsorted_regs and unsorted_offsets; additionally,
8801      order[0] has been set to the lowest numbered register in the
8802      list.  Sort the registers into order, and check that the memory
8803      offsets are ascending and adjacent.  */
8804
8805   for (i = 1; i < nops; i++)
8806     {
8807       int j;
8808
8809       order[i] = order[i - 1];
8810       for (j = 0; j < nops; j++)
8811         if (unsorted_regs[j] > unsorted_regs[order[i - 1]]
8812             && (order[i] == order[i - 1]
8813                 || unsorted_regs[j] < unsorted_regs[order[i]]))
8814           order[i] = j;
8815
8816       /* Have we found a suitable register? if not, one must be used more
8817          than once.  */
8818       if (order[i] == order[i - 1])
8819         return 0;
8820
8821       /* Is the memory address adjacent and ascending? */
8822       if (unsorted_offsets[order[i]] != unsorted_offsets[order[i - 1]] + 4)
8823         return 0;
8824     }
8825
8826   if (base)
8827     {
8828       *base = base_reg;
8829
8830       for (i = 0; i < nops; i++)
8831         regs[i] = unsorted_regs[order[i]];
8832
8833       *load_offset = unsorted_offsets[order[0]];
8834     }
8835
8836   if (unsorted_offsets[order[0]] == 0)
8837     return 1; /* ldmia */
8838
8839   if (TARGET_ARM && unsorted_offsets[order[0]] == 4)
8840     return 2; /* ldmib */
8841
8842   if (TARGET_ARM && unsorted_offsets[order[nops - 1]] == 0)
8843     return 3; /* ldmda */
8844
8845   if (unsorted_offsets[order[nops - 1]] == -4)
8846     return 4; /* ldmdb */
8847
8848   /* For ARM8,9 & StrongARM, 2 ldr instructions are faster than an ldm
8849      if the offset isn't small enough.  The reason 2 ldrs are faster
8850      is because these ARMs are able to do more than one cache access
8851      in a single cycle.  The ARM9 and StrongARM have Harvard caches,
8852      whilst the ARM8 has a double bandwidth cache.  This means that
8853      these cores can do both an instruction fetch and a data fetch in
8854      a single cycle, so the trick of calculating the address into a
8855      scratch register (one of the result regs) and then doing a load
8856      multiple actually becomes slower (and no smaller in code size).
8857      That is the transformation
8858
8859         ldr     rd1, [rbase + offset]
8860         ldr     rd2, [rbase + offset + 4]
8861
8862      to
8863
8864         add     rd1, rbase, offset
8865         ldmia   rd1, {rd1, rd2}
8866
8867      produces worse code -- '3 cycles + any stalls on rd2' instead of
8868      '2 cycles + any stalls on rd2'.  On ARMs with only one cache
8869      access per cycle, the first sequence could never complete in less
8870      than 6 cycles, whereas the ldm sequence would only take 5 and
8871      would make better use of sequential accesses if not hitting the
8872      cache.
8873
8874      We cheat here and test 'arm_ld_sched' which we currently know to
8875      only be true for the ARM8, ARM9 and StrongARM.  If this ever
8876      changes, then the test below needs to be reworked.  */
8877   if (nops == 2 && arm_ld_sched)
8878     return 0;
8879
8880   /* Can't do it without setting up the offset, only do this if it takes
8881      no more than one insn.  */
8882   return (const_ok_for_arm (unsorted_offsets[order[0]])
8883           || const_ok_for_arm (-unsorted_offsets[order[0]])) ? 5 : 0;
8884 }
8885
8886 const char *
8887 emit_ldm_seq (rtx *operands, int nops)
8888 {
8889   int regs[4];
8890   int base_reg;
8891   HOST_WIDE_INT offset;
8892   char buf[100];
8893   int i;
8894
8895   switch (load_multiple_sequence (operands, nops, regs, &base_reg, &offset))
8896     {
8897     case 1:
8898       strcpy (buf, "ldm%(ia%)\t");
8899       break;
8900
8901     case 2:
8902       strcpy (buf, "ldm%(ib%)\t");
8903       break;
8904
8905     case 3:
8906       strcpy (buf, "ldm%(da%)\t");
8907       break;
8908
8909     case 4:
8910       strcpy (buf, "ldm%(db%)\t");
8911       break;
8912
8913     case 5:
8914       if (offset >= 0)
8915         sprintf (buf, "add%%?\t%s%s, %s%s, #%ld", REGISTER_PREFIX,
8916                  reg_names[regs[0]], REGISTER_PREFIX, reg_names[base_reg],
8917                  (long) offset);
8918       else
8919         sprintf (buf, "sub%%?\t%s%s, %s%s, #%ld", REGISTER_PREFIX,
8920                  reg_names[regs[0]], REGISTER_PREFIX, reg_names[base_reg],
8921                  (long) -offset);
8922       output_asm_insn (buf, operands);
8923       base_reg = regs[0];
8924       strcpy (buf, "ldm%(ia%)\t");
8925       break;
8926
8927     default:
8928       gcc_unreachable ();
8929     }
8930
8931   sprintf (buf + strlen (buf), "%s%s, {%s%s", REGISTER_PREFIX,
8932            reg_names[base_reg], REGISTER_PREFIX, reg_names[regs[0]]);
8933
8934   for (i = 1; i < nops; i++)
8935     sprintf (buf + strlen (buf), ", %s%s", REGISTER_PREFIX,
8936              reg_names[regs[i]]);
8937
8938   strcat (buf, "}\t%@ phole ldm");
8939
8940   output_asm_insn (buf, operands);
8941   return "";
8942 }
8943
8944 int
8945 store_multiple_sequence (rtx *operands, int nops, int *regs, int *base,
8946                          HOST_WIDE_INT * load_offset)
8947 {
8948   int unsorted_regs[4];
8949   HOST_WIDE_INT unsorted_offsets[4];
8950   int order[4];
8951   int base_reg = -1;
8952   int i;
8953
8954   /* Can only handle 2, 3, or 4 insns at present, though could be easily
8955      extended if required.  */
8956   gcc_assert (nops >= 2 && nops <= 4);
8957
8958   memset (order, 0, 4 * sizeof (int));
8959
8960   /* Loop over the operands and check that the memory references are
8961      suitable (i.e. immediate offsets from the same base register).  At
8962      the same time, extract the target register, and the memory
8963      offsets.  */
8964   for (i = 0; i < nops; i++)
8965     {
8966       rtx reg;
8967       rtx offset;
8968
8969       /* Convert a subreg of a mem into the mem itself.  */
8970       if (GET_CODE (operands[nops + i]) == SUBREG)
8971         operands[nops + i] = alter_subreg (operands + (nops + i));
8972
8973       gcc_assert (GET_CODE (operands[nops + i]) == MEM);
8974
8975       /* Don't reorder volatile memory references; it doesn't seem worth
8976          looking for the case where the order is ok anyway.  */
8977       if (MEM_VOLATILE_P (operands[nops + i]))
8978         return 0;
8979
8980       offset = const0_rtx;
8981
8982       if ((GET_CODE (reg = XEXP (operands[nops + i], 0)) == REG
8983            || (GET_CODE (reg) == SUBREG
8984                && GET_CODE (reg = SUBREG_REG (reg)) == REG))
8985           || (GET_CODE (XEXP (operands[nops + i], 0)) == PLUS
8986               && ((GET_CODE (reg = XEXP (XEXP (operands[nops + i], 0), 0))
8987                    == REG)
8988                   || (GET_CODE (reg) == SUBREG
8989                       && GET_CODE (reg = SUBREG_REG (reg)) == REG))
8990               && (GET_CODE (offset = XEXP (XEXP (operands[nops + i], 0), 1))
8991                   == CONST_INT)))
8992         {
8993           if (i == 0)
8994             {
8995               base_reg = REGNO (reg);
8996               unsorted_regs[0] = (GET_CODE (operands[i]) == REG
8997                                   ? REGNO (operands[i])
8998                                   : REGNO (SUBREG_REG (operands[i])));
8999               order[0] = 0;
9000             }
9001           else
9002             {
9003               if (base_reg != (int) REGNO (reg))
9004                 /* Not addressed from the same base register.  */
9005                 return 0;
9006
9007               unsorted_regs[i] = (GET_CODE (operands[i]) == REG
9008                                   ? REGNO (operands[i])
9009                                   : REGNO (SUBREG_REG (operands[i])));
9010               if (unsorted_regs[i] < unsorted_regs[order[0]])
9011                 order[0] = i;
9012             }
9013
9014           /* If it isn't an integer register, then we can't do this.  */
9015           if (unsorted_regs[i] < 0 || unsorted_regs[i] > 14)
9016             return 0;
9017
9018           unsorted_offsets[i] = INTVAL (offset);
9019         }
9020       else
9021         /* Not a suitable memory address.  */
9022         return 0;
9023     }
9024
9025   /* All the useful information has now been extracted from the
9026      operands into unsorted_regs and unsorted_offsets; additionally,
9027      order[0] has been set to the lowest numbered register in the
9028      list.  Sort the registers into order, and check that the memory
9029      offsets are ascending and adjacent.  */
9030
9031   for (i = 1; i < nops; i++)
9032     {
9033       int j;
9034
9035       order[i] = order[i - 1];
9036       for (j = 0; j < nops; j++)
9037         if (unsorted_regs[j] > unsorted_regs[order[i - 1]]
9038             && (order[i] == order[i - 1]
9039                 || unsorted_regs[j] < unsorted_regs[order[i]]))
9040           order[i] = j;
9041
9042       /* Have we found a suitable register? if not, one must be used more
9043          than once.  */
9044       if (order[i] == order[i - 1])
9045         return 0;
9046
9047       /* Is the memory address adjacent and ascending? */
9048       if (unsorted_offsets[order[i]] != unsorted_offsets[order[i - 1]] + 4)
9049         return 0;
9050     }
9051
9052   if (base)
9053     {
9054       *base = base_reg;
9055
9056       for (i = 0; i < nops; i++)
9057         regs[i] = unsorted_regs[order[i]];
9058
9059       *load_offset = unsorted_offsets[order[0]];
9060     }
9061
9062   if (unsorted_offsets[order[0]] == 0)
9063     return 1; /* stmia */
9064
9065   if (unsorted_offsets[order[0]] == 4)
9066     return 2; /* stmib */
9067
9068   if (unsorted_offsets[order[nops - 1]] == 0)
9069     return 3; /* stmda */
9070
9071   if (unsorted_offsets[order[nops - 1]] == -4)
9072     return 4; /* stmdb */
9073
9074   return 0;
9075 }
9076
9077 const char *
9078 emit_stm_seq (rtx *operands, int nops)
9079 {
9080   int regs[4];
9081   int base_reg;
9082   HOST_WIDE_INT offset;
9083   char buf[100];
9084   int i;
9085
9086   switch (store_multiple_sequence (operands, nops, regs, &base_reg, &offset))
9087     {
9088     case 1:
9089       strcpy (buf, "stm%(ia%)\t");
9090       break;
9091
9092     case 2:
9093       strcpy (buf, "stm%(ib%)\t");
9094       break;
9095
9096     case 3:
9097       strcpy (buf, "stm%(da%)\t");
9098       break;
9099
9100     case 4:
9101       strcpy (buf, "stm%(db%)\t");
9102       break;
9103
9104     default:
9105       gcc_unreachable ();
9106     }
9107
9108   sprintf (buf + strlen (buf), "%s%s, {%s%s", REGISTER_PREFIX,
9109            reg_names[base_reg], REGISTER_PREFIX, reg_names[regs[0]]);
9110
9111   for (i = 1; i < nops; i++)
9112     sprintf (buf + strlen (buf), ", %s%s", REGISTER_PREFIX,
9113              reg_names[regs[i]]);
9114
9115   strcat (buf, "}\t%@ phole stm");
9116
9117   output_asm_insn (buf, operands);
9118   return "";
9119 }
9120 \f
9121 /* Routines for use in generating RTL.  */
9122
9123 rtx
9124 arm_gen_load_multiple (int base_regno, int count, rtx from, int up,
9125                        int write_back, rtx basemem, HOST_WIDE_INT *offsetp)
9126 {
9127   HOST_WIDE_INT offset = *offsetp;
9128   int i = 0, j;
9129   rtx result;
9130   int sign = up ? 1 : -1;
9131   rtx mem, addr;
9132
9133   /* XScale has load-store double instructions, but they have stricter
9134      alignment requirements than load-store multiple, so we cannot
9135      use them.
9136
9137      For XScale ldm requires 2 + NREGS cycles to complete and blocks
9138      the pipeline until completion.
9139
9140         NREGS           CYCLES
9141           1               3
9142           2               4
9143           3               5
9144           4               6
9145
9146      An ldr instruction takes 1-3 cycles, but does not block the
9147      pipeline.
9148
9149         NREGS           CYCLES
9150           1              1-3
9151           2              2-6
9152           3              3-9
9153           4              4-12
9154
9155      Best case ldr will always win.  However, the more ldr instructions
9156      we issue, the less likely we are to be able to schedule them well.
9157      Using ldr instructions also increases code size.
9158
9159      As a compromise, we use ldr for counts of 1 or 2 regs, and ldm
9160      for counts of 3 or 4 regs.  */
9161   if (arm_tune_xscale && count <= 2 && ! optimize_size)
9162     {
9163       rtx seq;
9164
9165       start_sequence ();
9166
9167       for (i = 0; i < count; i++)
9168         {
9169           addr = plus_constant (from, i * 4 * sign);
9170           mem = adjust_automodify_address (basemem, SImode, addr, offset);
9171           emit_move_insn (gen_rtx_REG (SImode, base_regno + i), mem);
9172           offset += 4 * sign;
9173         }
9174
9175       if (write_back)
9176         {
9177           emit_move_insn (from, plus_constant (from, count * 4 * sign));
9178           *offsetp = offset;
9179         }
9180
9181       seq = get_insns ();
9182       end_sequence ();
9183
9184       return seq;
9185     }
9186
9187   result = gen_rtx_PARALLEL (VOIDmode,
9188                              rtvec_alloc (count + (write_back ? 1 : 0)));
9189   if (write_back)
9190     {
9191       XVECEXP (result, 0, 0)
9192         = gen_rtx_SET (VOIDmode, from, plus_constant (from, count * 4 * sign));
9193       i = 1;
9194       count++;
9195     }
9196
9197   for (j = 0; i < count; i++, j++)
9198     {
9199       addr = plus_constant (from, j * 4 * sign);
9200       mem = adjust_automodify_address_nv (basemem, SImode, addr, offset);
9201       XVECEXP (result, 0, i)
9202         = gen_rtx_SET (VOIDmode, gen_rtx_REG (SImode, base_regno + j), mem);
9203       offset += 4 * sign;
9204     }
9205
9206   if (write_back)
9207     *offsetp = offset;
9208
9209   return result;
9210 }
9211
9212 rtx
9213 arm_gen_store_multiple (int base_regno, int count, rtx to, int up,
9214                         int write_back, rtx basemem, HOST_WIDE_INT *offsetp)
9215 {
9216   HOST_WIDE_INT offset = *offsetp;
9217   int i = 0, j;
9218   rtx result;
9219   int sign = up ? 1 : -1;
9220   rtx mem, addr;
9221
9222   /* See arm_gen_load_multiple for discussion of
9223      the pros/cons of ldm/stm usage for XScale.  */
9224   if (arm_tune_xscale && count <= 2 && ! optimize_size)
9225     {
9226       rtx seq;
9227
9228       start_sequence ();
9229
9230       for (i = 0; i < count; i++)
9231         {
9232           addr = plus_constant (to, i * 4 * sign);
9233           mem = adjust_automodify_address (basemem, SImode, addr, offset);
9234           emit_move_insn (mem, gen_rtx_REG (SImode, base_regno + i));
9235           offset += 4 * sign;
9236         }
9237
9238       if (write_back)
9239         {
9240           emit_move_insn (to, plus_constant (to, count * 4 * sign));
9241           *offsetp = offset;
9242         }
9243
9244       seq = get_insns ();
9245       end_sequence ();
9246
9247       return seq;
9248     }
9249
9250   result = gen_rtx_PARALLEL (VOIDmode,
9251                              rtvec_alloc (count + (write_back ? 1 : 0)));
9252   if (write_back)
9253     {
9254       XVECEXP (result, 0, 0)
9255         = gen_rtx_SET (VOIDmode, to,
9256                        plus_constant (to, count * 4 * sign));
9257       i = 1;
9258       count++;
9259     }
9260
9261   for (j = 0; i < count; i++, j++)
9262     {
9263       addr = plus_constant (to, j * 4 * sign);
9264       mem = adjust_automodify_address_nv (basemem, SImode, addr, offset);
9265       XVECEXP (result, 0, i)
9266         = gen_rtx_SET (VOIDmode, mem, gen_rtx_REG (SImode, base_regno + j));
9267       offset += 4 * sign;
9268     }
9269
9270   if (write_back)
9271     *offsetp = offset;
9272
9273   return result;
9274 }
9275
9276 int
9277 arm_gen_movmemqi (rtx *operands)
9278 {
9279   HOST_WIDE_INT in_words_to_go, out_words_to_go, last_bytes;
9280   HOST_WIDE_INT srcoffset, dstoffset;
9281   int i;
9282   rtx src, dst, srcbase, dstbase;
9283   rtx part_bytes_reg = NULL;
9284   rtx mem;
9285
9286   if (GET_CODE (operands[2]) != CONST_INT
9287       || GET_CODE (operands[3]) != CONST_INT
9288       || INTVAL (operands[2]) > 64
9289       || INTVAL (operands[3]) & 3)
9290     return 0;
9291
9292   dstbase = operands[0];
9293   srcbase = operands[1];
9294
9295   dst = copy_to_mode_reg (SImode, XEXP (dstbase, 0));
9296   src = copy_to_mode_reg (SImode, XEXP (srcbase, 0));
9297
9298   in_words_to_go = ARM_NUM_INTS (INTVAL (operands[2]));
9299   out_words_to_go = INTVAL (operands[2]) / 4;
9300   last_bytes = INTVAL (operands[2]) & 3;
9301   dstoffset = srcoffset = 0;
9302
9303   if (out_words_to_go != in_words_to_go && ((in_words_to_go - 1) & 3) != 0)
9304     part_bytes_reg = gen_rtx_REG (SImode, (in_words_to_go - 1) & 3);
9305
9306   for (i = 0; in_words_to_go >= 2; i+=4)
9307     {
9308       if (in_words_to_go > 4)
9309         emit_insn (arm_gen_load_multiple (0, 4, src, TRUE, TRUE,
9310                                           srcbase, &srcoffset));
9311       else
9312         emit_insn (arm_gen_load_multiple (0, in_words_to_go, src, TRUE,
9313                                           FALSE, srcbase, &srcoffset));
9314
9315       if (out_words_to_go)
9316         {
9317           if (out_words_to_go > 4)
9318             emit_insn (arm_gen_store_multiple (0, 4, dst, TRUE, TRUE,
9319                                                dstbase, &dstoffset));
9320           else if (out_words_to_go != 1)
9321             emit_insn (arm_gen_store_multiple (0, out_words_to_go,
9322                                                dst, TRUE,
9323                                                (last_bytes == 0
9324                                                 ? FALSE : TRUE),
9325                                                dstbase, &dstoffset));
9326           else
9327             {
9328               mem = adjust_automodify_address (dstbase, SImode, dst, dstoffset);
9329               emit_move_insn (mem, gen_rtx_REG (SImode, 0));
9330               if (last_bytes != 0)
9331                 {
9332                   emit_insn (gen_addsi3 (dst, dst, GEN_INT (4)));
9333                   dstoffset += 4;
9334                 }
9335             }
9336         }
9337
9338       in_words_to_go -= in_words_to_go < 4 ? in_words_to_go : 4;
9339       out_words_to_go -= out_words_to_go < 4 ? out_words_to_go : 4;
9340     }
9341
9342   /* OUT_WORDS_TO_GO will be zero here if there are byte stores to do.  */
9343   if (out_words_to_go)
9344     {
9345       rtx sreg;
9346
9347       mem = adjust_automodify_address (srcbase, SImode, src, srcoffset);
9348       sreg = copy_to_reg (mem);
9349
9350       mem = adjust_automodify_address (dstbase, SImode, dst, dstoffset);
9351       emit_move_insn (mem, sreg);
9352       in_words_to_go--;
9353
9354       gcc_assert (!in_words_to_go);     /* Sanity check */
9355     }
9356
9357   if (in_words_to_go)
9358     {
9359       gcc_assert (in_words_to_go > 0);
9360
9361       mem = adjust_automodify_address (srcbase, SImode, src, srcoffset);
9362       part_bytes_reg = copy_to_mode_reg (SImode, mem);
9363     }
9364
9365   gcc_assert (!last_bytes || part_bytes_reg);
9366
9367   if (BYTES_BIG_ENDIAN && last_bytes)
9368     {
9369       rtx tmp = gen_reg_rtx (SImode);
9370
9371       /* The bytes we want are in the top end of the word.  */
9372       emit_insn (gen_lshrsi3 (tmp, part_bytes_reg,
9373                               GEN_INT (8 * (4 - last_bytes))));
9374       part_bytes_reg = tmp;
9375
9376       while (last_bytes)
9377         {
9378           mem = adjust_automodify_address (dstbase, QImode,
9379                                            plus_constant (dst, last_bytes - 1),
9380                                            dstoffset + last_bytes - 1);
9381           emit_move_insn (mem, gen_lowpart (QImode, part_bytes_reg));
9382
9383           if (--last_bytes)
9384             {
9385               tmp = gen_reg_rtx (SImode);
9386               emit_insn (gen_lshrsi3 (tmp, part_bytes_reg, GEN_INT (8)));
9387               part_bytes_reg = tmp;
9388             }
9389         }
9390
9391     }
9392   else
9393     {
9394       if (last_bytes > 1)
9395         {
9396           mem = adjust_automodify_address (dstbase, HImode, dst, dstoffset);
9397           emit_move_insn (mem, gen_lowpart (HImode, part_bytes_reg));
9398           last_bytes -= 2;
9399           if (last_bytes)
9400             {
9401               rtx tmp = gen_reg_rtx (SImode);
9402               emit_insn (gen_addsi3 (dst, dst, const2_rtx));
9403               emit_insn (gen_lshrsi3 (tmp, part_bytes_reg, GEN_INT (16)));
9404               part_bytes_reg = tmp;
9405               dstoffset += 2;
9406             }
9407         }
9408
9409       if (last_bytes)
9410         {
9411           mem = adjust_automodify_address (dstbase, QImode, dst, dstoffset);
9412           emit_move_insn (mem, gen_lowpart (QImode, part_bytes_reg));
9413         }
9414     }
9415
9416   return 1;
9417 }
9418
9419 /* Select a dominance comparison mode if possible for a test of the general
9420    form (OP (COND_OR (X) (Y)) (const_int 0)).  We support three forms.
9421    COND_OR == DOM_CC_X_AND_Y => (X && Y)
9422    COND_OR == DOM_CC_NX_OR_Y => ((! X) || Y)
9423    COND_OR == DOM_CC_X_OR_Y => (X || Y)
9424    In all cases OP will be either EQ or NE, but we don't need to know which
9425    here.  If we are unable to support a dominance comparison we return
9426    CC mode.  This will then fail to match for the RTL expressions that
9427    generate this call.  */
9428 enum machine_mode
9429 arm_select_dominance_cc_mode (rtx x, rtx y, HOST_WIDE_INT cond_or)
9430 {
9431   enum rtx_code cond1, cond2;
9432   int swapped = 0;
9433
9434   /* Currently we will probably get the wrong result if the individual
9435      comparisons are not simple.  This also ensures that it is safe to
9436      reverse a comparison if necessary.  */
9437   if ((arm_select_cc_mode (cond1 = GET_CODE (x), XEXP (x, 0), XEXP (x, 1))
9438        != CCmode)
9439       || (arm_select_cc_mode (cond2 = GET_CODE (y), XEXP (y, 0), XEXP (y, 1))
9440           != CCmode))
9441     return CCmode;
9442
9443   /* The if_then_else variant of this tests the second condition if the
9444      first passes, but is true if the first fails.  Reverse the first
9445      condition to get a true "inclusive-or" expression.  */
9446   if (cond_or == DOM_CC_NX_OR_Y)
9447     cond1 = reverse_condition (cond1);
9448
9449   /* If the comparisons are not equal, and one doesn't dominate the other,
9450      then we can't do this.  */
9451   if (cond1 != cond2
9452       && !comparison_dominates_p (cond1, cond2)
9453       && (swapped = 1, !comparison_dominates_p (cond2, cond1)))
9454     return CCmode;
9455
9456   if (swapped)
9457     {
9458       enum rtx_code temp = cond1;
9459       cond1 = cond2;
9460       cond2 = temp;
9461     }
9462
9463   switch (cond1)
9464     {
9465     case EQ:
9466       if (cond_or == DOM_CC_X_AND_Y)
9467         return CC_DEQmode;
9468
9469       switch (cond2)
9470         {
9471         case EQ: return CC_DEQmode;
9472         case LE: return CC_DLEmode;
9473         case LEU: return CC_DLEUmode;
9474         case GE: return CC_DGEmode;
9475         case GEU: return CC_DGEUmode;
9476         default: gcc_unreachable ();
9477         }
9478
9479     case LT:
9480       if (cond_or == DOM_CC_X_AND_Y)
9481         return CC_DLTmode;
9482
9483       switch (cond2)
9484         {
9485         case  LT:
9486             return CC_DLTmode;
9487         case LE:
9488           return CC_DLEmode;
9489         case NE:
9490           return CC_DNEmode;
9491         default:
9492           gcc_unreachable ();
9493         }
9494
9495     case GT:
9496       if (cond_or == DOM_CC_X_AND_Y)
9497         return CC_DGTmode;
9498
9499       switch (cond2)
9500         {
9501         case GT:
9502           return CC_DGTmode;
9503         case GE:
9504           return CC_DGEmode;
9505         case NE:
9506           return CC_DNEmode;
9507         default:
9508           gcc_unreachable ();
9509         }
9510
9511     case LTU:
9512       if (cond_or == DOM_CC_X_AND_Y)
9513         return CC_DLTUmode;
9514
9515       switch (cond2)
9516         {
9517         case LTU:
9518           return CC_DLTUmode;
9519         case LEU:
9520           return CC_DLEUmode;
9521         case NE:
9522           return CC_DNEmode;
9523         default:
9524           gcc_unreachable ();
9525         }
9526
9527     case GTU:
9528       if (cond_or == DOM_CC_X_AND_Y)
9529         return CC_DGTUmode;
9530
9531       switch (cond2)
9532         {
9533         case GTU:
9534           return CC_DGTUmode;
9535         case GEU:
9536           return CC_DGEUmode;
9537         case NE:
9538           return CC_DNEmode;
9539         default:
9540           gcc_unreachable ();
9541         }
9542
9543     /* The remaining cases only occur when both comparisons are the
9544        same.  */
9545     case NE:
9546       gcc_assert (cond1 == cond2);
9547       return CC_DNEmode;
9548
9549     case LE:
9550       gcc_assert (cond1 == cond2);
9551       return CC_DLEmode;
9552
9553     case GE:
9554       gcc_assert (cond1 == cond2);
9555       return CC_DGEmode;
9556
9557     case LEU:
9558       gcc_assert (cond1 == cond2);
9559       return CC_DLEUmode;
9560
9561     case GEU:
9562       gcc_assert (cond1 == cond2);
9563       return CC_DGEUmode;
9564
9565     default:
9566       gcc_unreachable ();
9567     }
9568 }
9569
9570 enum machine_mode
9571 arm_select_cc_mode (enum rtx_code op, rtx x, rtx y)
9572 {
9573   /* All floating point compares return CCFP if it is an equality
9574      comparison, and CCFPE otherwise.  */
9575   if (GET_MODE_CLASS (GET_MODE (x)) == MODE_FLOAT)
9576     {
9577       switch (op)
9578         {
9579         case EQ:
9580         case NE:
9581         case UNORDERED:
9582         case ORDERED:
9583         case UNLT:
9584         case UNLE:
9585         case UNGT:
9586         case UNGE:
9587         case UNEQ:
9588         case LTGT:
9589           return CCFPmode;
9590
9591         case LT:
9592         case LE:
9593         case GT:
9594         case GE:
9595           if (TARGET_HARD_FLOAT && TARGET_MAVERICK)
9596             return CCFPmode;
9597           return CCFPEmode;
9598
9599         default:
9600           gcc_unreachable ();
9601         }
9602     }
9603
9604   /* A compare with a shifted operand.  Because of canonicalization, the
9605      comparison will have to be swapped when we emit the assembler.  */
9606   if (GET_MODE (y) == SImode 
9607       && (REG_P (y) || (GET_CODE (y) == SUBREG))
9608       && (GET_CODE (x) == ASHIFT || GET_CODE (x) == ASHIFTRT
9609           || GET_CODE (x) == LSHIFTRT || GET_CODE (x) == ROTATE
9610           || GET_CODE (x) == ROTATERT))
9611     return CC_SWPmode;
9612
9613   /* This operation is performed swapped, but since we only rely on the Z
9614      flag we don't need an additional mode.  */
9615   if (GET_MODE (y) == SImode 
9616       && (REG_P (y) || (GET_CODE (y) == SUBREG))
9617       && GET_CODE (x) == NEG
9618       && (op == EQ || op == NE))
9619     return CC_Zmode;
9620
9621   /* This is a special case that is used by combine to allow a
9622      comparison of a shifted byte load to be split into a zero-extend
9623      followed by a comparison of the shifted integer (only valid for
9624      equalities and unsigned inequalities).  */
9625   if (GET_MODE (x) == SImode
9626       && GET_CODE (x) == ASHIFT
9627       && GET_CODE (XEXP (x, 1)) == CONST_INT && INTVAL (XEXP (x, 1)) == 24
9628       && GET_CODE (XEXP (x, 0)) == SUBREG
9629       && GET_CODE (SUBREG_REG (XEXP (x, 0))) == MEM
9630       && GET_MODE (SUBREG_REG (XEXP (x, 0))) == QImode
9631       && (op == EQ || op == NE
9632           || op == GEU || op == GTU || op == LTU || op == LEU)
9633       && GET_CODE (y) == CONST_INT)
9634     return CC_Zmode;
9635
9636   /* A construct for a conditional compare, if the false arm contains
9637      0, then both conditions must be true, otherwise either condition
9638      must be true.  Not all conditions are possible, so CCmode is
9639      returned if it can't be done.  */
9640   if (GET_CODE (x) == IF_THEN_ELSE
9641       && (XEXP (x, 2) == const0_rtx
9642           || XEXP (x, 2) == const1_rtx)
9643       && COMPARISON_P (XEXP (x, 0))
9644       && COMPARISON_P (XEXP (x, 1)))
9645     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
9646                                          INTVAL (XEXP (x, 2)));
9647
9648   /* Alternate canonicalizations of the above.  These are somewhat cleaner.  */
9649   if (GET_CODE (x) == AND
9650       && COMPARISON_P (XEXP (x, 0))
9651       && COMPARISON_P (XEXP (x, 1)))
9652     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
9653                                          DOM_CC_X_AND_Y);
9654
9655   if (GET_CODE (x) == IOR
9656       && COMPARISON_P (XEXP (x, 0))
9657       && COMPARISON_P (XEXP (x, 1)))
9658     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
9659                                          DOM_CC_X_OR_Y);
9660
9661   /* An operation (on Thumb) where we want to test for a single bit.
9662      This is done by shifting that bit up into the top bit of a
9663      scratch register; we can then branch on the sign bit.  */
9664   if (TARGET_THUMB1
9665       && GET_MODE (x) == SImode
9666       && (op == EQ || op == NE)
9667       && GET_CODE (x) == ZERO_EXTRACT
9668       && XEXP (x, 1) == const1_rtx)
9669     return CC_Nmode;
9670
9671   /* An operation that sets the condition codes as a side-effect, the
9672      V flag is not set correctly, so we can only use comparisons where
9673      this doesn't matter.  (For LT and GE we can use "mi" and "pl"
9674      instead.)  */
9675   /* ??? Does the ZERO_EXTRACT case really apply to thumb2?  */
9676   if (GET_MODE (x) == SImode
9677       && y == const0_rtx
9678       && (op == EQ || op == NE || op == LT || op == GE)
9679       && (GET_CODE (x) == PLUS || GET_CODE (x) == MINUS
9680           || GET_CODE (x) == AND || GET_CODE (x) == IOR
9681           || GET_CODE (x) == XOR || GET_CODE (x) == MULT
9682           || GET_CODE (x) == NOT || GET_CODE (x) == NEG
9683           || GET_CODE (x) == LSHIFTRT
9684           || GET_CODE (x) == ASHIFT || GET_CODE (x) == ASHIFTRT
9685           || GET_CODE (x) == ROTATERT
9686           || (TARGET_32BIT && GET_CODE (x) == ZERO_EXTRACT)))
9687     return CC_NOOVmode;
9688
9689   if (GET_MODE (x) == QImode && (op == EQ || op == NE))
9690     return CC_Zmode;
9691
9692   if (GET_MODE (x) == SImode && (op == LTU || op == GEU)
9693       && GET_CODE (x) == PLUS
9694       && (rtx_equal_p (XEXP (x, 0), y) || rtx_equal_p (XEXP (x, 1), y)))
9695     return CC_Cmode;
9696
9697   return CCmode;
9698 }
9699
9700 /* X and Y are two things to compare using CODE.  Emit the compare insn and
9701    return the rtx for register 0 in the proper mode.  FP means this is a
9702    floating point compare: I don't think that it is needed on the arm.  */
9703 rtx
9704 arm_gen_compare_reg (enum rtx_code code, rtx x, rtx y)
9705 {
9706   enum machine_mode mode = SELECT_CC_MODE (code, x, y);
9707   rtx cc_reg = gen_rtx_REG (mode, CC_REGNUM);
9708
9709   emit_set_insn (cc_reg, gen_rtx_COMPARE (mode, x, y));
9710
9711   return cc_reg;
9712 }
9713
9714 /* Generate a sequence of insns that will generate the correct return
9715    address mask depending on the physical architecture that the program
9716    is running on.  */
9717 rtx
9718 arm_gen_return_addr_mask (void)
9719 {
9720   rtx reg = gen_reg_rtx (Pmode);
9721
9722   emit_insn (gen_return_addr_mask (reg));
9723   return reg;
9724 }
9725
9726 void
9727 arm_reload_in_hi (rtx *operands)
9728 {
9729   rtx ref = operands[1];
9730   rtx base, scratch;
9731   HOST_WIDE_INT offset = 0;
9732
9733   if (GET_CODE (ref) == SUBREG)
9734     {
9735       offset = SUBREG_BYTE (ref);
9736       ref = SUBREG_REG (ref);
9737     }
9738
9739   if (GET_CODE (ref) == REG)
9740     {
9741       /* We have a pseudo which has been spilt onto the stack; there
9742          are two cases here: the first where there is a simple
9743          stack-slot replacement and a second where the stack-slot is
9744          out of range, or is used as a subreg.  */
9745       if (reg_equiv_mem[REGNO (ref)])
9746         {
9747           ref = reg_equiv_mem[REGNO (ref)];
9748           base = find_replacement (&XEXP (ref, 0));
9749         }
9750       else
9751         /* The slot is out of range, or was dressed up in a SUBREG.  */
9752         base = reg_equiv_address[REGNO (ref)];
9753     }
9754   else
9755     base = find_replacement (&XEXP (ref, 0));
9756
9757   /* Handle the case where the address is too complex to be offset by 1.  */
9758   if (GET_CODE (base) == MINUS
9759       || (GET_CODE (base) == PLUS && GET_CODE (XEXP (base, 1)) != CONST_INT))
9760     {
9761       rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
9762
9763       emit_set_insn (base_plus, base);
9764       base = base_plus;
9765     }
9766   else if (GET_CODE (base) == PLUS)
9767     {
9768       /* The addend must be CONST_INT, or we would have dealt with it above.  */
9769       HOST_WIDE_INT hi, lo;
9770
9771       offset += INTVAL (XEXP (base, 1));
9772       base = XEXP (base, 0);
9773
9774       /* Rework the address into a legal sequence of insns.  */
9775       /* Valid range for lo is -4095 -> 4095 */
9776       lo = (offset >= 0
9777             ? (offset & 0xfff)
9778             : -((-offset) & 0xfff));
9779
9780       /* Corner case, if lo is the max offset then we would be out of range
9781          once we have added the additional 1 below, so bump the msb into the
9782          pre-loading insn(s).  */
9783       if (lo == 4095)
9784         lo &= 0x7ff;
9785
9786       hi = ((((offset - lo) & (HOST_WIDE_INT) 0xffffffff)
9787              ^ (HOST_WIDE_INT) 0x80000000)
9788             - (HOST_WIDE_INT) 0x80000000);
9789
9790       gcc_assert (hi + lo == offset);
9791
9792       if (hi != 0)
9793         {
9794           rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
9795
9796           /* Get the base address; addsi3 knows how to handle constants
9797              that require more than one insn.  */
9798           emit_insn (gen_addsi3 (base_plus, base, GEN_INT (hi)));
9799           base = base_plus;
9800           offset = lo;
9801         }
9802     }
9803
9804   /* Operands[2] may overlap operands[0] (though it won't overlap
9805      operands[1]), that's why we asked for a DImode reg -- so we can
9806      use the bit that does not overlap.  */
9807   if (REGNO (operands[2]) == REGNO (operands[0]))
9808     scratch = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
9809   else
9810     scratch = gen_rtx_REG (SImode, REGNO (operands[2]));
9811
9812   emit_insn (gen_zero_extendqisi2 (scratch,
9813                                    gen_rtx_MEM (QImode,
9814                                                 plus_constant (base,
9815                                                                offset))));
9816   emit_insn (gen_zero_extendqisi2 (gen_rtx_SUBREG (SImode, operands[0], 0),
9817                                    gen_rtx_MEM (QImode,
9818                                                 plus_constant (base,
9819                                                                offset + 1))));
9820   if (!BYTES_BIG_ENDIAN)
9821     emit_set_insn (gen_rtx_SUBREG (SImode, operands[0], 0),
9822                    gen_rtx_IOR (SImode,
9823                                 gen_rtx_ASHIFT
9824                                 (SImode,
9825                                  gen_rtx_SUBREG (SImode, operands[0], 0),
9826                                  GEN_INT (8)),
9827                                 scratch));
9828   else
9829     emit_set_insn (gen_rtx_SUBREG (SImode, operands[0], 0),
9830                    gen_rtx_IOR (SImode,
9831                                 gen_rtx_ASHIFT (SImode, scratch,
9832                                                 GEN_INT (8)),
9833                                 gen_rtx_SUBREG (SImode, operands[0], 0)));
9834 }
9835
9836 /* Handle storing a half-word to memory during reload by synthesizing as two
9837    byte stores.  Take care not to clobber the input values until after we
9838    have moved them somewhere safe.  This code assumes that if the DImode
9839    scratch in operands[2] overlaps either the input value or output address
9840    in some way, then that value must die in this insn (we absolutely need
9841    two scratch registers for some corner cases).  */
9842 void
9843 arm_reload_out_hi (rtx *operands)
9844 {
9845   rtx ref = operands[0];
9846   rtx outval = operands[1];
9847   rtx base, scratch;
9848   HOST_WIDE_INT offset = 0;
9849
9850   if (GET_CODE (ref) == SUBREG)
9851     {
9852       offset = SUBREG_BYTE (ref);
9853       ref = SUBREG_REG (ref);
9854     }
9855
9856   if (GET_CODE (ref) == REG)
9857     {
9858       /* We have a pseudo which has been spilt onto the stack; there
9859          are two cases here: the first where there is a simple
9860          stack-slot replacement and a second where the stack-slot is
9861          out of range, or is used as a subreg.  */
9862       if (reg_equiv_mem[REGNO (ref)])
9863         {
9864           ref = reg_equiv_mem[REGNO (ref)];
9865           base = find_replacement (&XEXP (ref, 0));
9866         }
9867       else
9868         /* The slot is out of range, or was dressed up in a SUBREG.  */
9869         base = reg_equiv_address[REGNO (ref)];
9870     }
9871   else
9872     base = find_replacement (&XEXP (ref, 0));
9873
9874   scratch = gen_rtx_REG (SImode, REGNO (operands[2]));
9875
9876   /* Handle the case where the address is too complex to be offset by 1.  */
9877   if (GET_CODE (base) == MINUS
9878       || (GET_CODE (base) == PLUS && GET_CODE (XEXP (base, 1)) != CONST_INT))
9879     {
9880       rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
9881
9882       /* Be careful not to destroy OUTVAL.  */
9883       if (reg_overlap_mentioned_p (base_plus, outval))
9884         {
9885           /* Updating base_plus might destroy outval, see if we can
9886              swap the scratch and base_plus.  */
9887           if (!reg_overlap_mentioned_p (scratch, outval))
9888             {
9889               rtx tmp = scratch;
9890               scratch = base_plus;
9891               base_plus = tmp;
9892             }
9893           else
9894             {
9895               rtx scratch_hi = gen_rtx_REG (HImode, REGNO (operands[2]));
9896
9897               /* Be conservative and copy OUTVAL into the scratch now,
9898                  this should only be necessary if outval is a subreg
9899                  of something larger than a word.  */
9900               /* XXX Might this clobber base?  I can't see how it can,
9901                  since scratch is known to overlap with OUTVAL, and
9902                  must be wider than a word.  */
9903               emit_insn (gen_movhi (scratch_hi, outval));
9904               outval = scratch_hi;
9905             }
9906         }
9907
9908       emit_set_insn (base_plus, base);
9909       base = base_plus;
9910     }
9911   else if (GET_CODE (base) == PLUS)
9912     {
9913       /* The addend must be CONST_INT, or we would have dealt with it above.  */
9914       HOST_WIDE_INT hi, lo;
9915
9916       offset += INTVAL (XEXP (base, 1));
9917       base = XEXP (base, 0);
9918
9919       /* Rework the address into a legal sequence of insns.  */
9920       /* Valid range for lo is -4095 -> 4095 */
9921       lo = (offset >= 0
9922             ? (offset & 0xfff)
9923             : -((-offset) & 0xfff));
9924
9925       /* Corner case, if lo is the max offset then we would be out of range
9926          once we have added the additional 1 below, so bump the msb into the
9927          pre-loading insn(s).  */
9928       if (lo == 4095)
9929         lo &= 0x7ff;
9930
9931       hi = ((((offset - lo) & (HOST_WIDE_INT) 0xffffffff)
9932              ^ (HOST_WIDE_INT) 0x80000000)
9933             - (HOST_WIDE_INT) 0x80000000);
9934
9935       gcc_assert (hi + lo == offset);
9936
9937       if (hi != 0)
9938         {
9939           rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
9940
9941           /* Be careful not to destroy OUTVAL.  */
9942           if (reg_overlap_mentioned_p (base_plus, outval))
9943             {
9944               /* Updating base_plus might destroy outval, see if we
9945                  can swap the scratch and base_plus.  */
9946               if (!reg_overlap_mentioned_p (scratch, outval))
9947                 {
9948                   rtx tmp = scratch;
9949                   scratch = base_plus;
9950                   base_plus = tmp;
9951                 }
9952               else
9953                 {
9954                   rtx scratch_hi = gen_rtx_REG (HImode, REGNO (operands[2]));
9955
9956                   /* Be conservative and copy outval into scratch now,
9957                      this should only be necessary if outval is a
9958                      subreg of something larger than a word.  */
9959                   /* XXX Might this clobber base?  I can't see how it
9960                      can, since scratch is known to overlap with
9961                      outval.  */
9962                   emit_insn (gen_movhi (scratch_hi, outval));
9963                   outval = scratch_hi;
9964                 }
9965             }
9966
9967           /* Get the base address; addsi3 knows how to handle constants
9968              that require more than one insn.  */
9969           emit_insn (gen_addsi3 (base_plus, base, GEN_INT (hi)));
9970           base = base_plus;
9971           offset = lo;
9972         }
9973     }
9974
9975   if (BYTES_BIG_ENDIAN)
9976     {
9977       emit_insn (gen_movqi (gen_rtx_MEM (QImode,
9978                                          plus_constant (base, offset + 1)),
9979                             gen_lowpart (QImode, outval)));
9980       emit_insn (gen_lshrsi3 (scratch,
9981                               gen_rtx_SUBREG (SImode, outval, 0),
9982                               GEN_INT (8)));
9983       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (base, offset)),
9984                             gen_lowpart (QImode, scratch)));
9985     }
9986   else
9987     {
9988       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (base, offset)),
9989                             gen_lowpart (QImode, outval)));
9990       emit_insn (gen_lshrsi3 (scratch,
9991                               gen_rtx_SUBREG (SImode, outval, 0),
9992                               GEN_INT (8)));
9993       emit_insn (gen_movqi (gen_rtx_MEM (QImode,
9994                                          plus_constant (base, offset + 1)),
9995                             gen_lowpart (QImode, scratch)));
9996     }
9997 }
9998
9999 /* Return true if a type must be passed in memory. For AAPCS, small aggregates
10000    (padded to the size of a word) should be passed in a register.  */
10001
10002 static bool
10003 arm_must_pass_in_stack (enum machine_mode mode, const_tree type)
10004 {
10005   if (TARGET_AAPCS_BASED)
10006     return must_pass_in_stack_var_size (mode, type);
10007   else
10008     return must_pass_in_stack_var_size_or_pad (mode, type);
10009 }
10010
10011
10012 /* For use by FUNCTION_ARG_PADDING (MODE, TYPE).
10013    Return true if an argument passed on the stack should be padded upwards,
10014    i.e. if the least-significant byte has useful data.
10015    For legacy APCS ABIs we use the default.  For AAPCS based ABIs small
10016    aggregate types are placed in the lowest memory address.  */
10017
10018 bool
10019 arm_pad_arg_upward (enum machine_mode mode, const_tree type)
10020 {
10021   if (!TARGET_AAPCS_BASED)
10022     return DEFAULT_FUNCTION_ARG_PADDING(mode, type) == upward;
10023
10024   if (type && BYTES_BIG_ENDIAN && INTEGRAL_TYPE_P (type))
10025     return false;
10026
10027   return true;
10028 }
10029
10030
10031 /* Similarly, for use by BLOCK_REG_PADDING (MODE, TYPE, FIRST).
10032    For non-AAPCS, return !BYTES_BIG_ENDIAN if the least significant
10033    byte of the register has useful data, and return the opposite if the
10034    most significant byte does.
10035    For AAPCS, small aggregates and small complex types are always padded
10036    upwards.  */
10037
10038 bool
10039 arm_pad_reg_upward (enum machine_mode mode ATTRIBUTE_UNUSED,
10040                     tree type, int first ATTRIBUTE_UNUSED)
10041 {
10042   if (TARGET_AAPCS_BASED
10043       && BYTES_BIG_ENDIAN
10044       && (AGGREGATE_TYPE_P (type) || TREE_CODE (type) == COMPLEX_TYPE)
10045       && int_size_in_bytes (type) <= 4)
10046     return true;
10047
10048   /* Otherwise, use default padding.  */
10049   return !BYTES_BIG_ENDIAN;
10050 }
10051
10052 \f
10053 /* Print a symbolic form of X to the debug file, F.  */
10054 static void
10055 arm_print_value (FILE *f, rtx x)
10056 {
10057   switch (GET_CODE (x))
10058     {
10059     case CONST_INT:
10060       fprintf (f, HOST_WIDE_INT_PRINT_HEX, INTVAL (x));
10061       return;
10062
10063     case CONST_DOUBLE:
10064       fprintf (f, "<0x%lx,0x%lx>", (long)XWINT (x, 2), (long)XWINT (x, 3));
10065       return;
10066
10067     case CONST_VECTOR:
10068       {
10069         int i;
10070
10071         fprintf (f, "<");
10072         for (i = 0; i < CONST_VECTOR_NUNITS (x); i++)
10073           {
10074             fprintf (f, HOST_WIDE_INT_PRINT_HEX, INTVAL (CONST_VECTOR_ELT (x, i)));
10075             if (i < (CONST_VECTOR_NUNITS (x) - 1))
10076               fputc (',', f);
10077           }
10078         fprintf (f, ">");
10079       }
10080       return;
10081
10082     case CONST_STRING:
10083       fprintf (f, "\"%s\"", XSTR (x, 0));
10084       return;
10085
10086     case SYMBOL_REF:
10087       fprintf (f, "`%s'", XSTR (x, 0));
10088       return;
10089
10090     case LABEL_REF:
10091       fprintf (f, "L%d", INSN_UID (XEXP (x, 0)));
10092       return;
10093
10094     case CONST:
10095       arm_print_value (f, XEXP (x, 0));
10096       return;
10097
10098     case PLUS:
10099       arm_print_value (f, XEXP (x, 0));
10100       fprintf (f, "+");
10101       arm_print_value (f, XEXP (x, 1));
10102       return;
10103
10104     case PC:
10105       fprintf (f, "pc");
10106       return;
10107
10108     default:
10109       fprintf (f, "????");
10110       return;
10111     }
10112 }
10113 \f
10114 /* Routines for manipulation of the constant pool.  */
10115
10116 /* Arm instructions cannot load a large constant directly into a
10117    register; they have to come from a pc relative load.  The constant
10118    must therefore be placed in the addressable range of the pc
10119    relative load.  Depending on the precise pc relative load
10120    instruction the range is somewhere between 256 bytes and 4k.  This
10121    means that we often have to dump a constant inside a function, and
10122    generate code to branch around it.
10123
10124    It is important to minimize this, since the branches will slow
10125    things down and make the code larger.
10126
10127    Normally we can hide the table after an existing unconditional
10128    branch so that there is no interruption of the flow, but in the
10129    worst case the code looks like this:
10130
10131         ldr     rn, L1
10132         ...
10133         b       L2
10134         align
10135         L1:     .long value
10136         L2:
10137         ...
10138
10139         ldr     rn, L3
10140         ...
10141         b       L4
10142         align
10143         L3:     .long value
10144         L4:
10145         ...
10146
10147    We fix this by performing a scan after scheduling, which notices
10148    which instructions need to have their operands fetched from the
10149    constant table and builds the table.
10150
10151    The algorithm starts by building a table of all the constants that
10152    need fixing up and all the natural barriers in the function (places
10153    where a constant table can be dropped without breaking the flow).
10154    For each fixup we note how far the pc-relative replacement will be
10155    able to reach and the offset of the instruction into the function.
10156
10157    Having built the table we then group the fixes together to form
10158    tables that are as large as possible (subject to addressing
10159    constraints) and emit each table of constants after the last
10160    barrier that is within range of all the instructions in the group.
10161    If a group does not contain a barrier, then we forcibly create one
10162    by inserting a jump instruction into the flow.  Once the table has
10163    been inserted, the insns are then modified to reference the
10164    relevant entry in the pool.
10165
10166    Possible enhancements to the algorithm (not implemented) are:
10167
10168    1) For some processors and object formats, there may be benefit in
10169    aligning the pools to the start of cache lines; this alignment
10170    would need to be taken into account when calculating addressability
10171    of a pool.  */
10172
10173 /* These typedefs are located at the start of this file, so that
10174    they can be used in the prototypes there.  This comment is to
10175    remind readers of that fact so that the following structures
10176    can be understood more easily.
10177
10178      typedef struct minipool_node    Mnode;
10179      typedef struct minipool_fixup   Mfix;  */
10180
10181 struct minipool_node
10182 {
10183   /* Doubly linked chain of entries.  */
10184   Mnode * next;
10185   Mnode * prev;
10186   /* The maximum offset into the code that this entry can be placed.  While
10187      pushing fixes for forward references, all entries are sorted in order
10188      of increasing max_address.  */
10189   HOST_WIDE_INT max_address;
10190   /* Similarly for an entry inserted for a backwards ref.  */
10191   HOST_WIDE_INT min_address;
10192   /* The number of fixes referencing this entry.  This can become zero
10193      if we "unpush" an entry.  In this case we ignore the entry when we
10194      come to emit the code.  */
10195   int refcount;
10196   /* The offset from the start of the minipool.  */
10197   HOST_WIDE_INT offset;
10198   /* The value in table.  */
10199   rtx value;
10200   /* The mode of value.  */
10201   enum machine_mode mode;
10202   /* The size of the value.  With iWMMXt enabled
10203      sizes > 4 also imply an alignment of 8-bytes.  */
10204   int fix_size;
10205 };
10206
10207 struct minipool_fixup
10208 {
10209   Mfix *            next;
10210   rtx               insn;
10211   HOST_WIDE_INT     address;
10212   rtx *             loc;
10213   enum machine_mode mode;
10214   int               fix_size;
10215   rtx               value;
10216   Mnode *           minipool;
10217   HOST_WIDE_INT     forwards;
10218   HOST_WIDE_INT     backwards;
10219 };
10220
10221 /* Fixes less than a word need padding out to a word boundary.  */
10222 #define MINIPOOL_FIX_SIZE(mode) \
10223   (GET_MODE_SIZE ((mode)) >= 4 ? GET_MODE_SIZE ((mode)) : 4)
10224
10225 static Mnode *  minipool_vector_head;
10226 static Mnode *  minipool_vector_tail;
10227 static rtx      minipool_vector_label;
10228 static int      minipool_pad;
10229
10230 /* The linked list of all minipool fixes required for this function.  */
10231 Mfix *          minipool_fix_head;
10232 Mfix *          minipool_fix_tail;
10233 /* The fix entry for the current minipool, once it has been placed.  */
10234 Mfix *          minipool_barrier;
10235
10236 /* Determines if INSN is the start of a jump table.  Returns the end
10237    of the TABLE or NULL_RTX.  */
10238 static rtx
10239 is_jump_table (rtx insn)
10240 {
10241   rtx table;
10242
10243   if (GET_CODE (insn) == JUMP_INSN
10244       && JUMP_LABEL (insn) != NULL
10245       && ((table = next_real_insn (JUMP_LABEL (insn)))
10246           == next_real_insn (insn))
10247       && table != NULL
10248       && GET_CODE (table) == JUMP_INSN
10249       && (GET_CODE (PATTERN (table)) == ADDR_VEC
10250           || GET_CODE (PATTERN (table)) == ADDR_DIFF_VEC))
10251     return table;
10252
10253   return NULL_RTX;
10254 }
10255
10256 #ifndef JUMP_TABLES_IN_TEXT_SECTION
10257 #define JUMP_TABLES_IN_TEXT_SECTION 0
10258 #endif
10259
10260 static HOST_WIDE_INT
10261 get_jump_table_size (rtx insn)
10262 {
10263   /* ADDR_VECs only take room if read-only data does into the text
10264      section.  */
10265   if (JUMP_TABLES_IN_TEXT_SECTION || readonly_data_section == text_section)
10266     {
10267       rtx body = PATTERN (insn);
10268       int elt = GET_CODE (body) == ADDR_DIFF_VEC ? 1 : 0;
10269       HOST_WIDE_INT size;
10270       HOST_WIDE_INT modesize;
10271
10272       modesize = GET_MODE_SIZE (GET_MODE (body));
10273       size = modesize * XVECLEN (body, elt);
10274       switch (modesize)
10275         {
10276         case 1:
10277           /* Round up size  of TBB table to a halfword boundary.  */
10278           size = (size + 1) & ~(HOST_WIDE_INT)1;
10279           break;
10280         case 2:
10281           /* No padding necessary for TBH.  */
10282           break;
10283         case 4:
10284           /* Add two bytes for alignment on Thumb.  */
10285           if (TARGET_THUMB)
10286             size += 2;
10287           break;
10288         default:
10289           gcc_unreachable ();
10290         }
10291       return size;
10292     }
10293
10294   return 0;
10295 }
10296
10297 /* Move a minipool fix MP from its current location to before MAX_MP.
10298    If MAX_MP is NULL, then MP doesn't need moving, but the addressing
10299    constraints may need updating.  */
10300 static Mnode *
10301 move_minipool_fix_forward_ref (Mnode *mp, Mnode *max_mp,
10302                                HOST_WIDE_INT max_address)
10303 {
10304   /* The code below assumes these are different.  */
10305   gcc_assert (mp != max_mp);
10306
10307   if (max_mp == NULL)
10308     {
10309       if (max_address < mp->max_address)
10310         mp->max_address = max_address;
10311     }
10312   else
10313     {
10314       if (max_address > max_mp->max_address - mp->fix_size)
10315         mp->max_address = max_mp->max_address - mp->fix_size;
10316       else
10317         mp->max_address = max_address;
10318
10319       /* Unlink MP from its current position.  Since max_mp is non-null,
10320        mp->prev must be non-null.  */
10321       mp->prev->next = mp->next;
10322       if (mp->next != NULL)
10323         mp->next->prev = mp->prev;
10324       else
10325         minipool_vector_tail = mp->prev;
10326
10327       /* Re-insert it before MAX_MP.  */
10328       mp->next = max_mp;
10329       mp->prev = max_mp->prev;
10330       max_mp->prev = mp;
10331
10332       if (mp->prev != NULL)
10333         mp->prev->next = mp;
10334       else
10335         minipool_vector_head = mp;
10336     }
10337
10338   /* Save the new entry.  */
10339   max_mp = mp;
10340
10341   /* Scan over the preceding entries and adjust their addresses as
10342      required.  */
10343   while (mp->prev != NULL
10344          && mp->prev->max_address > mp->max_address - mp->prev->fix_size)
10345     {
10346       mp->prev->max_address = mp->max_address - mp->prev->fix_size;
10347       mp = mp->prev;
10348     }
10349
10350   return max_mp;
10351 }
10352
10353 /* Add a constant to the minipool for a forward reference.  Returns the
10354    node added or NULL if the constant will not fit in this pool.  */
10355 static Mnode *
10356 add_minipool_forward_ref (Mfix *fix)
10357 {
10358   /* If set, max_mp is the first pool_entry that has a lower
10359      constraint than the one we are trying to add.  */
10360   Mnode *       max_mp = NULL;
10361   HOST_WIDE_INT max_address = fix->address + fix->forwards - minipool_pad;
10362   Mnode *       mp;
10363
10364   /* If the minipool starts before the end of FIX->INSN then this FIX
10365      can not be placed into the current pool.  Furthermore, adding the
10366      new constant pool entry may cause the pool to start FIX_SIZE bytes
10367      earlier.  */
10368   if (minipool_vector_head &&
10369       (fix->address + get_attr_length (fix->insn)
10370        >= minipool_vector_head->max_address - fix->fix_size))
10371     return NULL;
10372
10373   /* Scan the pool to see if a constant with the same value has
10374      already been added.  While we are doing this, also note the
10375      location where we must insert the constant if it doesn't already
10376      exist.  */
10377   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
10378     {
10379       if (GET_CODE (fix->value) == GET_CODE (mp->value)
10380           && fix->mode == mp->mode
10381           && (GET_CODE (fix->value) != CODE_LABEL
10382               || (CODE_LABEL_NUMBER (fix->value)
10383                   == CODE_LABEL_NUMBER (mp->value)))
10384           && rtx_equal_p (fix->value, mp->value))
10385         {
10386           /* More than one fix references this entry.  */
10387           mp->refcount++;
10388           return move_minipool_fix_forward_ref (mp, max_mp, max_address);
10389         }
10390
10391       /* Note the insertion point if necessary.  */
10392       if (max_mp == NULL
10393           && mp->max_address > max_address)
10394         max_mp = mp;
10395
10396       /* If we are inserting an 8-bytes aligned quantity and
10397          we have not already found an insertion point, then
10398          make sure that all such 8-byte aligned quantities are
10399          placed at the start of the pool.  */
10400       if (ARM_DOUBLEWORD_ALIGN
10401           && max_mp == NULL
10402           && fix->fix_size >= 8
10403           && mp->fix_size < 8)
10404         {
10405           max_mp = mp;
10406           max_address = mp->max_address;
10407         }
10408     }
10409
10410   /* The value is not currently in the minipool, so we need to create
10411      a new entry for it.  If MAX_MP is NULL, the entry will be put on
10412      the end of the list since the placement is less constrained than
10413      any existing entry.  Otherwise, we insert the new fix before
10414      MAX_MP and, if necessary, adjust the constraints on the other
10415      entries.  */
10416   mp = XNEW (Mnode);
10417   mp->fix_size = fix->fix_size;
10418   mp->mode = fix->mode;
10419   mp->value = fix->value;
10420   mp->refcount = 1;
10421   /* Not yet required for a backwards ref.  */
10422   mp->min_address = -65536;
10423
10424   if (max_mp == NULL)
10425     {
10426       mp->max_address = max_address;
10427       mp->next = NULL;
10428       mp->prev = minipool_vector_tail;
10429
10430       if (mp->prev == NULL)
10431         {
10432           minipool_vector_head = mp;
10433           minipool_vector_label = gen_label_rtx ();
10434         }
10435       else
10436         mp->prev->next = mp;
10437
10438       minipool_vector_tail = mp;
10439     }
10440   else
10441     {
10442       if (max_address > max_mp->max_address - mp->fix_size)
10443         mp->max_address = max_mp->max_address - mp->fix_size;
10444       else
10445         mp->max_address = max_address;
10446
10447       mp->next = max_mp;
10448       mp->prev = max_mp->prev;
10449       max_mp->prev = mp;
10450       if (mp->prev != NULL)
10451         mp->prev->next = mp;
10452       else
10453         minipool_vector_head = mp;
10454     }
10455
10456   /* Save the new entry.  */
10457   max_mp = mp;
10458
10459   /* Scan over the preceding entries and adjust their addresses as
10460      required.  */
10461   while (mp->prev != NULL
10462          && mp->prev->max_address > mp->max_address - mp->prev->fix_size)
10463     {
10464       mp->prev->max_address = mp->max_address - mp->prev->fix_size;
10465       mp = mp->prev;
10466     }
10467
10468   return max_mp;
10469 }
10470
10471 static Mnode *
10472 move_minipool_fix_backward_ref (Mnode *mp, Mnode *min_mp,
10473                                 HOST_WIDE_INT  min_address)
10474 {
10475   HOST_WIDE_INT offset;
10476
10477   /* The code below assumes these are different.  */
10478   gcc_assert (mp != min_mp);
10479
10480   if (min_mp == NULL)
10481     {
10482       if (min_address > mp->min_address)
10483         mp->min_address = min_address;
10484     }
10485   else
10486     {
10487       /* We will adjust this below if it is too loose.  */
10488       mp->min_address = min_address;
10489
10490       /* Unlink MP from its current position.  Since min_mp is non-null,
10491          mp->next must be non-null.  */
10492       mp->next->prev = mp->prev;
10493       if (mp->prev != NULL)
10494         mp->prev->next = mp->next;
10495       else
10496         minipool_vector_head = mp->next;
10497
10498       /* Reinsert it after MIN_MP.  */
10499       mp->prev = min_mp;
10500       mp->next = min_mp->next;
10501       min_mp->next = mp;
10502       if (mp->next != NULL)
10503         mp->next->prev = mp;
10504       else
10505         minipool_vector_tail = mp;
10506     }
10507
10508   min_mp = mp;
10509
10510   offset = 0;
10511   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
10512     {
10513       mp->offset = offset;
10514       if (mp->refcount > 0)
10515         offset += mp->fix_size;
10516
10517       if (mp->next && mp->next->min_address < mp->min_address + mp->fix_size)
10518         mp->next->min_address = mp->min_address + mp->fix_size;
10519     }
10520
10521   return min_mp;
10522 }
10523
10524 /* Add a constant to the minipool for a backward reference.  Returns the
10525    node added or NULL if the constant will not fit in this pool.
10526
10527    Note that the code for insertion for a backwards reference can be
10528    somewhat confusing because the calculated offsets for each fix do
10529    not take into account the size of the pool (which is still under
10530    construction.  */
10531 static Mnode *
10532 add_minipool_backward_ref (Mfix *fix)
10533 {
10534   /* If set, min_mp is the last pool_entry that has a lower constraint
10535      than the one we are trying to add.  */
10536   Mnode *min_mp = NULL;
10537   /* This can be negative, since it is only a constraint.  */
10538   HOST_WIDE_INT  min_address = fix->address - fix->backwards;
10539   Mnode *mp;
10540
10541   /* If we can't reach the current pool from this insn, or if we can't
10542      insert this entry at the end of the pool without pushing other
10543      fixes out of range, then we don't try.  This ensures that we
10544      can't fail later on.  */
10545   if (min_address >= minipool_barrier->address
10546       || (minipool_vector_tail->min_address + fix->fix_size
10547           >= minipool_barrier->address))
10548     return NULL;
10549
10550   /* Scan the pool to see if a constant with the same value has
10551      already been added.  While we are doing this, also note the
10552      location where we must insert the constant if it doesn't already
10553      exist.  */
10554   for (mp = minipool_vector_tail; mp != NULL; mp = mp->prev)
10555     {
10556       if (GET_CODE (fix->value) == GET_CODE (mp->value)
10557           && fix->mode == mp->mode
10558           && (GET_CODE (fix->value) != CODE_LABEL
10559               || (CODE_LABEL_NUMBER (fix->value)
10560                   == CODE_LABEL_NUMBER (mp->value)))
10561           && rtx_equal_p (fix->value, mp->value)
10562           /* Check that there is enough slack to move this entry to the
10563              end of the table (this is conservative).  */
10564           && (mp->max_address
10565               > (minipool_barrier->address
10566                  + minipool_vector_tail->offset
10567                  + minipool_vector_tail->fix_size)))
10568         {
10569           mp->refcount++;
10570           return move_minipool_fix_backward_ref (mp, min_mp, min_address);
10571         }
10572
10573       if (min_mp != NULL)
10574         mp->min_address += fix->fix_size;
10575       else
10576         {
10577           /* Note the insertion point if necessary.  */
10578           if (mp->min_address < min_address)
10579             {
10580               /* For now, we do not allow the insertion of 8-byte alignment
10581                  requiring nodes anywhere but at the start of the pool.  */
10582               if (ARM_DOUBLEWORD_ALIGN
10583                   && fix->fix_size >= 8 && mp->fix_size < 8)
10584                 return NULL;
10585               else
10586                 min_mp = mp;
10587             }
10588           else if (mp->max_address
10589                    < minipool_barrier->address + mp->offset + fix->fix_size)
10590             {
10591               /* Inserting before this entry would push the fix beyond
10592                  its maximum address (which can happen if we have
10593                  re-located a forwards fix); force the new fix to come
10594                  after it.  */
10595               if (ARM_DOUBLEWORD_ALIGN
10596                   && fix->fix_size >= 8 && mp->fix_size < 8)
10597                 return NULL;
10598               else
10599                 {
10600                   min_mp = mp;
10601                   min_address = mp->min_address + fix->fix_size;
10602                 }
10603             }
10604           /* Do not insert a non-8-byte aligned quantity before 8-byte
10605              aligned quantities.  */
10606           else if (ARM_DOUBLEWORD_ALIGN
10607                    && fix->fix_size < 8
10608                    && mp->fix_size >= 8)
10609             {
10610               min_mp = mp;
10611               min_address = mp->min_address + fix->fix_size;
10612             }
10613         }
10614     }
10615
10616   /* We need to create a new entry.  */
10617   mp = XNEW (Mnode);
10618   mp->fix_size = fix->fix_size;
10619   mp->mode = fix->mode;
10620   mp->value = fix->value;
10621   mp->refcount = 1;
10622   mp->max_address = minipool_barrier->address + 65536;
10623
10624   mp->min_address = min_address;
10625
10626   if (min_mp == NULL)
10627     {
10628       mp->prev = NULL;
10629       mp->next = minipool_vector_head;
10630
10631       if (mp->next == NULL)
10632         {
10633           minipool_vector_tail = mp;
10634           minipool_vector_label = gen_label_rtx ();
10635         }
10636       else
10637         mp->next->prev = mp;
10638
10639       minipool_vector_head = mp;
10640     }
10641   else
10642     {
10643       mp->next = min_mp->next;
10644       mp->prev = min_mp;
10645       min_mp->next = mp;
10646
10647       if (mp->next != NULL)
10648         mp->next->prev = mp;
10649       else
10650         minipool_vector_tail = mp;
10651     }
10652
10653   /* Save the new entry.  */
10654   min_mp = mp;
10655
10656   if (mp->prev)
10657     mp = mp->prev;
10658   else
10659     mp->offset = 0;
10660
10661   /* Scan over the following entries and adjust their offsets.  */
10662   while (mp->next != NULL)
10663     {
10664       if (mp->next->min_address < mp->min_address + mp->fix_size)
10665         mp->next->min_address = mp->min_address + mp->fix_size;
10666
10667       if (mp->refcount)
10668         mp->next->offset = mp->offset + mp->fix_size;
10669       else
10670         mp->next->offset = mp->offset;
10671
10672       mp = mp->next;
10673     }
10674
10675   return min_mp;
10676 }
10677
10678 static void
10679 assign_minipool_offsets (Mfix *barrier)
10680 {
10681   HOST_WIDE_INT offset = 0;
10682   Mnode *mp;
10683
10684   minipool_barrier = barrier;
10685
10686   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
10687     {
10688       mp->offset = offset;
10689
10690       if (mp->refcount > 0)
10691         offset += mp->fix_size;
10692     }
10693 }
10694
10695 /* Output the literal table */
10696 static void
10697 dump_minipool (rtx scan)
10698 {
10699   Mnode * mp;
10700   Mnode * nmp;
10701   int align64 = 0;
10702
10703   if (ARM_DOUBLEWORD_ALIGN)
10704     for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
10705       if (mp->refcount > 0 && mp->fix_size >= 8)
10706         {
10707           align64 = 1;
10708           break;
10709         }
10710
10711   if (dump_file)
10712     fprintf (dump_file,
10713              ";; Emitting minipool after insn %u; address %ld; align %d (bytes)\n",
10714              INSN_UID (scan), (unsigned long) minipool_barrier->address, align64 ? 8 : 4);
10715
10716   scan = emit_label_after (gen_label_rtx (), scan);
10717   scan = emit_insn_after (align64 ? gen_align_8 () : gen_align_4 (), scan);
10718   scan = emit_label_after (minipool_vector_label, scan);
10719
10720   for (mp = minipool_vector_head; mp != NULL; mp = nmp)
10721     {
10722       if (mp->refcount > 0)
10723         {
10724           if (dump_file)
10725             {
10726               fprintf (dump_file,
10727                        ";;  Offset %u, min %ld, max %ld ",
10728                        (unsigned) mp->offset, (unsigned long) mp->min_address,
10729                        (unsigned long) mp->max_address);
10730               arm_print_value (dump_file, mp->value);
10731               fputc ('\n', dump_file);
10732             }
10733
10734           switch (mp->fix_size)
10735             {
10736 #ifdef HAVE_consttable_1
10737             case 1:
10738               scan = emit_insn_after (gen_consttable_1 (mp->value), scan);
10739               break;
10740
10741 #endif
10742 #ifdef HAVE_consttable_2
10743             case 2:
10744               scan = emit_insn_after (gen_consttable_2 (mp->value), scan);
10745               break;
10746
10747 #endif
10748 #ifdef HAVE_consttable_4
10749             case 4:
10750               scan = emit_insn_after (gen_consttable_4 (mp->value), scan);
10751               break;
10752
10753 #endif
10754 #ifdef HAVE_consttable_8
10755             case 8:
10756               scan = emit_insn_after (gen_consttable_8 (mp->value), scan);
10757               break;
10758
10759 #endif
10760 #ifdef HAVE_consttable_16
10761             case 16:
10762               scan = emit_insn_after (gen_consttable_16 (mp->value), scan);
10763               break;
10764
10765 #endif
10766             default:
10767               gcc_unreachable ();
10768             }
10769         }
10770
10771       nmp = mp->next;
10772       free (mp);
10773     }
10774
10775   minipool_vector_head = minipool_vector_tail = NULL;
10776   scan = emit_insn_after (gen_consttable_end (), scan);
10777   scan = emit_barrier_after (scan);
10778 }
10779
10780 /* Return the cost of forcibly inserting a barrier after INSN.  */
10781 static int
10782 arm_barrier_cost (rtx insn)
10783 {
10784   /* Basing the location of the pool on the loop depth is preferable,
10785      but at the moment, the basic block information seems to be
10786      corrupt by this stage of the compilation.  */
10787   int base_cost = 50;
10788   rtx next = next_nonnote_insn (insn);
10789
10790   if (next != NULL && GET_CODE (next) == CODE_LABEL)
10791     base_cost -= 20;
10792
10793   switch (GET_CODE (insn))
10794     {
10795     case CODE_LABEL:
10796       /* It will always be better to place the table before the label, rather
10797          than after it.  */
10798       return 50;
10799
10800     case INSN:
10801     case CALL_INSN:
10802       return base_cost;
10803
10804     case JUMP_INSN:
10805       return base_cost - 10;
10806
10807     default:
10808       return base_cost + 10;
10809     }
10810 }
10811
10812 /* Find the best place in the insn stream in the range
10813    (FIX->address,MAX_ADDRESS) to forcibly insert a minipool barrier.
10814    Create the barrier by inserting a jump and add a new fix entry for
10815    it.  */
10816 static Mfix *
10817 create_fix_barrier (Mfix *fix, HOST_WIDE_INT max_address)
10818 {
10819   HOST_WIDE_INT count = 0;
10820   rtx barrier;
10821   rtx from = fix->insn;
10822   /* The instruction after which we will insert the jump.  */
10823   rtx selected = NULL;
10824   int selected_cost;
10825   /* The address at which the jump instruction will be placed.  */
10826   HOST_WIDE_INT selected_address;
10827   Mfix * new_fix;
10828   HOST_WIDE_INT max_count = max_address - fix->address;
10829   rtx label = gen_label_rtx ();
10830
10831   selected_cost = arm_barrier_cost (from);
10832   selected_address = fix->address;
10833
10834   while (from && count < max_count)
10835     {
10836       rtx tmp;
10837       int new_cost;
10838
10839       /* This code shouldn't have been called if there was a natural barrier
10840          within range.  */
10841       gcc_assert (GET_CODE (from) != BARRIER);
10842
10843       /* Count the length of this insn.  */
10844       count += get_attr_length (from);
10845
10846       /* If there is a jump table, add its length.  */
10847       tmp = is_jump_table (from);
10848       if (tmp != NULL)
10849         {
10850           count += get_jump_table_size (tmp);
10851
10852           /* Jump tables aren't in a basic block, so base the cost on
10853              the dispatch insn.  If we select this location, we will
10854              still put the pool after the table.  */
10855           new_cost = arm_barrier_cost (from);
10856
10857           if (count < max_count 
10858               && (!selected || new_cost <= selected_cost))
10859             {
10860               selected = tmp;
10861               selected_cost = new_cost;
10862               selected_address = fix->address + count;
10863             }
10864
10865           /* Continue after the dispatch table.  */
10866           from = NEXT_INSN (tmp);
10867           continue;
10868         }
10869
10870       new_cost = arm_barrier_cost (from);
10871
10872       if (count < max_count
10873           && (!selected || new_cost <= selected_cost))
10874         {
10875           selected = from;
10876           selected_cost = new_cost;
10877           selected_address = fix->address + count;
10878         }
10879
10880       from = NEXT_INSN (from);
10881     }
10882
10883   /* Make sure that we found a place to insert the jump.  */
10884   gcc_assert (selected);
10885
10886   /* Create a new JUMP_INSN that branches around a barrier.  */
10887   from = emit_jump_insn_after (gen_jump (label), selected);
10888   JUMP_LABEL (from) = label;
10889   barrier = emit_barrier_after (from);
10890   emit_label_after (label, barrier);
10891
10892   /* Create a minipool barrier entry for the new barrier.  */
10893   new_fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* new_fix));
10894   new_fix->insn = barrier;
10895   new_fix->address = selected_address;
10896   new_fix->next = fix->next;
10897   fix->next = new_fix;
10898
10899   return new_fix;
10900 }
10901
10902 /* Record that there is a natural barrier in the insn stream at
10903    ADDRESS.  */
10904 static void
10905 push_minipool_barrier (rtx insn, HOST_WIDE_INT address)
10906 {
10907   Mfix * fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* fix));
10908
10909   fix->insn = insn;
10910   fix->address = address;
10911
10912   fix->next = NULL;
10913   if (minipool_fix_head != NULL)
10914     minipool_fix_tail->next = fix;
10915   else
10916     minipool_fix_head = fix;
10917
10918   minipool_fix_tail = fix;
10919 }
10920
10921 /* Record INSN, which will need fixing up to load a value from the
10922    minipool.  ADDRESS is the offset of the insn since the start of the
10923    function; LOC is a pointer to the part of the insn which requires
10924    fixing; VALUE is the constant that must be loaded, which is of type
10925    MODE.  */
10926 static void
10927 push_minipool_fix (rtx insn, HOST_WIDE_INT address, rtx *loc,
10928                    enum machine_mode mode, rtx value)
10929 {
10930   Mfix * fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* fix));
10931
10932   fix->insn = insn;
10933   fix->address = address;
10934   fix->loc = loc;
10935   fix->mode = mode;
10936   fix->fix_size = MINIPOOL_FIX_SIZE (mode);
10937   fix->value = value;
10938   fix->forwards = get_attr_pool_range (insn);
10939   fix->backwards = get_attr_neg_pool_range (insn);
10940   fix->minipool = NULL;
10941
10942   /* If an insn doesn't have a range defined for it, then it isn't
10943      expecting to be reworked by this code.  Better to stop now than
10944      to generate duff assembly code.  */
10945   gcc_assert (fix->forwards || fix->backwards);
10946
10947   /* If an entry requires 8-byte alignment then assume all constant pools
10948      require 4 bytes of padding.  Trying to do this later on a per-pool
10949      basis is awkward because existing pool entries have to be modified.  */
10950   if (ARM_DOUBLEWORD_ALIGN && fix->fix_size >= 8)
10951     minipool_pad = 4;
10952
10953   if (dump_file)
10954     {
10955       fprintf (dump_file,
10956                ";; %smode fixup for i%d; addr %lu, range (%ld,%ld): ",
10957                GET_MODE_NAME (mode),
10958                INSN_UID (insn), (unsigned long) address,
10959                -1 * (long)fix->backwards, (long)fix->forwards);
10960       arm_print_value (dump_file, fix->value);
10961       fprintf (dump_file, "\n");
10962     }
10963
10964   /* Add it to the chain of fixes.  */
10965   fix->next = NULL;
10966
10967   if (minipool_fix_head != NULL)
10968     minipool_fix_tail->next = fix;
10969   else
10970     minipool_fix_head = fix;
10971
10972   minipool_fix_tail = fix;
10973 }
10974
10975 /* Return the cost of synthesizing a 64-bit constant VAL inline.
10976    Returns the number of insns needed, or 99 if we don't know how to
10977    do it.  */
10978 int
10979 arm_const_double_inline_cost (rtx val)
10980 {
10981   rtx lowpart, highpart;
10982   enum machine_mode mode;
10983
10984   mode = GET_MODE (val);
10985
10986   if (mode == VOIDmode)
10987     mode = DImode;
10988
10989   gcc_assert (GET_MODE_SIZE (mode) == 8);
10990
10991   lowpart = gen_lowpart (SImode, val);
10992   highpart = gen_highpart_mode (SImode, mode, val);
10993
10994   gcc_assert (GET_CODE (lowpart) == CONST_INT);
10995   gcc_assert (GET_CODE (highpart) == CONST_INT);
10996
10997   return (arm_gen_constant (SET, SImode, NULL_RTX, INTVAL (lowpart),
10998                             NULL_RTX, NULL_RTX, 0, 0)
10999           + arm_gen_constant (SET, SImode, NULL_RTX, INTVAL (highpart),
11000                               NULL_RTX, NULL_RTX, 0, 0));
11001 }
11002
11003 /* Return true if it is worthwhile to split a 64-bit constant into two
11004    32-bit operations.  This is the case if optimizing for size, or
11005    if we have load delay slots, or if one 32-bit part can be done with
11006    a single data operation.  */
11007 bool
11008 arm_const_double_by_parts (rtx val)
11009 {
11010   enum machine_mode mode = GET_MODE (val);
11011   rtx part;
11012
11013   if (optimize_size || arm_ld_sched)
11014     return true;
11015
11016   if (mode == VOIDmode)
11017     mode = DImode;
11018
11019   part = gen_highpart_mode (SImode, mode, val);
11020
11021   gcc_assert (GET_CODE (part) == CONST_INT);
11022
11023   if (const_ok_for_arm (INTVAL (part))
11024       || const_ok_for_arm (~INTVAL (part)))
11025     return true;
11026
11027   part = gen_lowpart (SImode, val);
11028
11029   gcc_assert (GET_CODE (part) == CONST_INT);
11030
11031   if (const_ok_for_arm (INTVAL (part))
11032       || const_ok_for_arm (~INTVAL (part)))
11033     return true;
11034
11035   return false;
11036 }
11037
11038 /* Scan INSN and note any of its operands that need fixing.
11039    If DO_PUSHES is false we do not actually push any of the fixups
11040    needed.  The function returns TRUE if any fixups were needed/pushed.
11041    This is used by arm_memory_load_p() which needs to know about loads
11042    of constants that will be converted into minipool loads.  */
11043 static bool
11044 note_invalid_constants (rtx insn, HOST_WIDE_INT address, int do_pushes)
11045 {
11046   bool result = false;
11047   int opno;
11048
11049   extract_insn (insn);
11050
11051   if (!constrain_operands (1))
11052     fatal_insn_not_found (insn);
11053
11054   if (recog_data.n_alternatives == 0)
11055     return false;
11056
11057   /* Fill in recog_op_alt with information about the constraints of
11058      this insn.  */
11059   preprocess_constraints ();
11060
11061   for (opno = 0; opno < recog_data.n_operands; opno++)
11062     {
11063       /* Things we need to fix can only occur in inputs.  */
11064       if (recog_data.operand_type[opno] != OP_IN)
11065         continue;
11066
11067       /* If this alternative is a memory reference, then any mention
11068          of constants in this alternative is really to fool reload
11069          into allowing us to accept one there.  We need to fix them up
11070          now so that we output the right code.  */
11071       if (recog_op_alt[opno][which_alternative].memory_ok)
11072         {
11073           rtx op = recog_data.operand[opno];
11074
11075           if (CONSTANT_P (op))
11076             {
11077               if (do_pushes)
11078                 push_minipool_fix (insn, address, recog_data.operand_loc[opno],
11079                                    recog_data.operand_mode[opno], op);
11080               result = true;
11081             }
11082           else if (GET_CODE (op) == MEM
11083                    && GET_CODE (XEXP (op, 0)) == SYMBOL_REF
11084                    && CONSTANT_POOL_ADDRESS_P (XEXP (op, 0)))
11085             {
11086               if (do_pushes)
11087                 {
11088                   rtx cop = avoid_constant_pool_reference (op);
11089
11090                   /* Casting the address of something to a mode narrower
11091                      than a word can cause avoid_constant_pool_reference()
11092                      to return the pool reference itself.  That's no good to
11093                      us here.  Lets just hope that we can use the
11094                      constant pool value directly.  */
11095                   if (op == cop)
11096                     cop = get_pool_constant (XEXP (op, 0));
11097
11098                   push_minipool_fix (insn, address,
11099                                      recog_data.operand_loc[opno],
11100                                      recog_data.operand_mode[opno], cop);
11101                 }
11102
11103               result = true;
11104             }
11105         }
11106     }
11107
11108   return result;
11109 }
11110
11111 /* Gcc puts the pool in the wrong place for ARM, since we can only
11112    load addresses a limited distance around the pc.  We do some
11113    special munging to move the constant pool values to the correct
11114    point in the code.  */
11115 static void
11116 arm_reorg (void)
11117 {
11118   rtx insn;
11119   HOST_WIDE_INT address = 0;
11120   Mfix * fix;
11121
11122   minipool_fix_head = minipool_fix_tail = NULL;
11123
11124   /* The first insn must always be a note, or the code below won't
11125      scan it properly.  */
11126   insn = get_insns ();
11127   gcc_assert (GET_CODE (insn) == NOTE);
11128   minipool_pad = 0;
11129
11130   /* Scan all the insns and record the operands that will need fixing.  */
11131   for (insn = next_nonnote_insn (insn); insn; insn = next_nonnote_insn (insn))
11132     {
11133       if (TARGET_CIRRUS_FIX_INVALID_INSNS
11134           && (arm_cirrus_insn_p (insn)
11135               || GET_CODE (insn) == JUMP_INSN
11136               || arm_memory_load_p (insn)))
11137         cirrus_reorg (insn);
11138
11139       if (GET_CODE (insn) == BARRIER)
11140         push_minipool_barrier (insn, address);
11141       else if (INSN_P (insn))
11142         {
11143           rtx table;
11144
11145           note_invalid_constants (insn, address, true);
11146           address += get_attr_length (insn);
11147
11148           /* If the insn is a vector jump, add the size of the table
11149              and skip the table.  */
11150           if ((table = is_jump_table (insn)) != NULL)
11151             {
11152               address += get_jump_table_size (table);
11153               insn = table;
11154             }
11155         }
11156     }
11157
11158   fix = minipool_fix_head;
11159
11160   /* Now scan the fixups and perform the required changes.  */
11161   while (fix)
11162     {
11163       Mfix * ftmp;
11164       Mfix * fdel;
11165       Mfix *  last_added_fix;
11166       Mfix * last_barrier = NULL;
11167       Mfix * this_fix;
11168
11169       /* Skip any further barriers before the next fix.  */
11170       while (fix && GET_CODE (fix->insn) == BARRIER)
11171         fix = fix->next;
11172
11173       /* No more fixes.  */
11174       if (fix == NULL)
11175         break;
11176
11177       last_added_fix = NULL;
11178
11179       for (ftmp = fix; ftmp; ftmp = ftmp->next)
11180         {
11181           if (GET_CODE (ftmp->insn) == BARRIER)
11182             {
11183               if (ftmp->address >= minipool_vector_head->max_address)
11184                 break;
11185
11186               last_barrier = ftmp;
11187             }
11188           else if ((ftmp->minipool = add_minipool_forward_ref (ftmp)) == NULL)
11189             break;
11190
11191           last_added_fix = ftmp;  /* Keep track of the last fix added.  */
11192         }
11193
11194       /* If we found a barrier, drop back to that; any fixes that we
11195          could have reached but come after the barrier will now go in
11196          the next mini-pool.  */
11197       if (last_barrier != NULL)
11198         {
11199           /* Reduce the refcount for those fixes that won't go into this
11200              pool after all.  */
11201           for (fdel = last_barrier->next;
11202                fdel && fdel != ftmp;
11203                fdel = fdel->next)
11204             {
11205               fdel->minipool->refcount--;
11206               fdel->minipool = NULL;
11207             }
11208
11209           ftmp = last_barrier;
11210         }
11211       else
11212         {
11213           /* ftmp is first fix that we can't fit into this pool and
11214              there no natural barriers that we could use.  Insert a
11215              new barrier in the code somewhere between the previous
11216              fix and this one, and arrange to jump around it.  */
11217           HOST_WIDE_INT max_address;
11218
11219           /* The last item on the list of fixes must be a barrier, so
11220              we can never run off the end of the list of fixes without
11221              last_barrier being set.  */
11222           gcc_assert (ftmp);
11223
11224           max_address = minipool_vector_head->max_address;
11225           /* Check that there isn't another fix that is in range that
11226              we couldn't fit into this pool because the pool was
11227              already too large: we need to put the pool before such an
11228              instruction.  The pool itself may come just after the
11229              fix because create_fix_barrier also allows space for a
11230              jump instruction.  */
11231           if (ftmp->address < max_address)
11232             max_address = ftmp->address + 1;
11233
11234           last_barrier = create_fix_barrier (last_added_fix, max_address);
11235         }
11236
11237       assign_minipool_offsets (last_barrier);
11238
11239       while (ftmp)
11240         {
11241           if (GET_CODE (ftmp->insn) != BARRIER
11242               && ((ftmp->minipool = add_minipool_backward_ref (ftmp))
11243                   == NULL))
11244             break;
11245
11246           ftmp = ftmp->next;
11247         }
11248
11249       /* Scan over the fixes we have identified for this pool, fixing them
11250          up and adding the constants to the pool itself.  */
11251       for (this_fix = fix; this_fix && ftmp != this_fix;
11252            this_fix = this_fix->next)
11253         if (GET_CODE (this_fix->insn) != BARRIER)
11254           {
11255             rtx addr
11256               = plus_constant (gen_rtx_LABEL_REF (VOIDmode,
11257                                                   minipool_vector_label),
11258                                this_fix->minipool->offset);
11259             *this_fix->loc = gen_rtx_MEM (this_fix->mode, addr);
11260           }
11261
11262       dump_minipool (last_barrier->insn);
11263       fix = ftmp;
11264     }
11265
11266   /* From now on we must synthesize any constants that we can't handle
11267      directly.  This can happen if the RTL gets split during final
11268      instruction generation.  */
11269   after_arm_reorg = 1;
11270
11271   /* Free the minipool memory.  */
11272   obstack_free (&minipool_obstack, minipool_startobj);
11273 }
11274 \f
11275 /* Routines to output assembly language.  */
11276
11277 /* If the rtx is the correct value then return the string of the number.
11278    In this way we can ensure that valid double constants are generated even
11279    when cross compiling.  */
11280 const char *
11281 fp_immediate_constant (rtx x)
11282 {
11283   REAL_VALUE_TYPE r;
11284   int i;
11285
11286   if (!fp_consts_inited)
11287     init_fp_table ();
11288
11289   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
11290   for (i = 0; i < 8; i++)
11291     if (REAL_VALUES_EQUAL (r, values_fp[i]))
11292       return strings_fp[i];
11293
11294   gcc_unreachable ();
11295 }
11296
11297 /* As for fp_immediate_constant, but value is passed directly, not in rtx.  */
11298 static const char *
11299 fp_const_from_val (REAL_VALUE_TYPE *r)
11300 {
11301   int i;
11302
11303   if (!fp_consts_inited)
11304     init_fp_table ();
11305
11306   for (i = 0; i < 8; i++)
11307     if (REAL_VALUES_EQUAL (*r, values_fp[i]))
11308       return strings_fp[i];
11309
11310   gcc_unreachable ();
11311 }
11312
11313 /* Output the operands of a LDM/STM instruction to STREAM.
11314    MASK is the ARM register set mask of which only bits 0-15 are important.
11315    REG is the base register, either the frame pointer or the stack pointer,
11316    INSTR is the possibly suffixed load or store instruction.
11317    RFE is nonzero if the instruction should also copy spsr to cpsr.  */
11318
11319 static void
11320 print_multi_reg (FILE *stream, const char *instr, unsigned reg,
11321                  unsigned long mask, int rfe)
11322 {
11323   unsigned i;
11324   bool not_first = FALSE;
11325
11326   gcc_assert (!rfe || (mask & (1 << PC_REGNUM)));
11327   fputc ('\t', stream);
11328   asm_fprintf (stream, instr, reg);
11329   fputc ('{', stream);
11330
11331   for (i = 0; i <= LAST_ARM_REGNUM; i++)
11332     if (mask & (1 << i))
11333       {
11334         if (not_first)
11335           fprintf (stream, ", ");
11336
11337         asm_fprintf (stream, "%r", i);
11338         not_first = TRUE;
11339       }
11340
11341   if (rfe)
11342     fprintf (stream, "}^\n");
11343   else
11344     fprintf (stream, "}\n");
11345 }
11346
11347
11348 /* Output a FLDMD instruction to STREAM.
11349    BASE if the register containing the address.
11350    REG and COUNT specify the register range.
11351    Extra registers may be added to avoid hardware bugs.
11352
11353    We output FLDMD even for ARMv5 VFP implementations.  Although
11354    FLDMD is technically not supported until ARMv6, it is believed
11355    that all VFP implementations support its use in this context.  */
11356
11357 static void
11358 vfp_output_fldmd (FILE * stream, unsigned int base, int reg, int count)
11359 {
11360   int i;
11361
11362   /* Workaround ARM10 VFPr1 bug.  */
11363   if (count == 2 && !arm_arch6)
11364     {
11365       if (reg == 15)
11366         reg--;
11367       count++;
11368     }
11369
11370   /* FLDMD may not load more than 16 doubleword registers at a time. Split the
11371      load into multiple parts if we have to handle more than 16 registers.  */
11372   if (count > 16)
11373     {
11374       vfp_output_fldmd (stream, base, reg, 16);
11375       vfp_output_fldmd (stream, base, reg + 16, count - 16);
11376       return;
11377     }
11378
11379   fputc ('\t', stream);
11380   asm_fprintf (stream, "fldmfdd\t%r!, {", base);
11381
11382   for (i = reg; i < reg + count; i++)
11383     {
11384       if (i > reg)
11385         fputs (", ", stream);
11386       asm_fprintf (stream, "d%d", i);
11387     }
11388   fputs ("}\n", stream);
11389
11390 }
11391
11392
11393 /* Output the assembly for a store multiple.  */
11394
11395 const char *
11396 vfp_output_fstmd (rtx * operands)
11397 {
11398   char pattern[100];
11399   int p;
11400   int base;
11401   int i;
11402
11403   strcpy (pattern, "fstmfdd\t%m0!, {%P1");
11404   p = strlen (pattern);
11405
11406   gcc_assert (GET_CODE (operands[1]) == REG);
11407
11408   base = (REGNO (operands[1]) - FIRST_VFP_REGNUM) / 2;
11409   for (i = 1; i < XVECLEN (operands[2], 0); i++)
11410     {
11411       p += sprintf (&pattern[p], ", d%d", base + i);
11412     }
11413   strcpy (&pattern[p], "}");
11414
11415   output_asm_insn (pattern, operands);
11416   return "";
11417 }
11418
11419
11420 /* Emit RTL to save block of VFP register pairs to the stack.  Returns the
11421    number of bytes pushed.  */
11422
11423 static int
11424 vfp_emit_fstmd (int base_reg, int count)
11425 {
11426   rtx par;
11427   rtx dwarf;
11428   rtx tmp, reg;
11429   int i;
11430
11431   /* Workaround ARM10 VFPr1 bug.  Data corruption can occur when exactly two
11432      register pairs are stored by a store multiple insn.  We avoid this
11433      by pushing an extra pair.  */
11434   if (count == 2 && !arm_arch6)
11435     {
11436       if (base_reg == LAST_VFP_REGNUM - 3)
11437         base_reg -= 2;
11438       count++;
11439     }
11440
11441   /* FSTMD may not store more than 16 doubleword registers at once.  Split
11442      larger stores into multiple parts (up to a maximum of two, in
11443      practice).  */
11444   if (count > 16)
11445     {
11446       int saved;
11447       /* NOTE: base_reg is an internal register number, so each D register
11448          counts as 2.  */
11449       saved = vfp_emit_fstmd (base_reg + 32, count - 16);
11450       saved += vfp_emit_fstmd (base_reg, 16);
11451       return saved;
11452     }
11453
11454   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (count));
11455   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (count + 1));
11456
11457   reg = gen_rtx_REG (DFmode, base_reg);
11458   base_reg += 2;
11459
11460   XVECEXP (par, 0, 0)
11461     = gen_rtx_SET (VOIDmode,
11462                    gen_frame_mem (BLKmode,
11463                                   gen_rtx_PRE_DEC (BLKmode,
11464                                                    stack_pointer_rtx)),
11465                    gen_rtx_UNSPEC (BLKmode,
11466                                    gen_rtvec (1, reg),
11467                                    UNSPEC_PUSH_MULT));
11468
11469   tmp = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
11470                      plus_constant (stack_pointer_rtx, -(count * 8)));
11471   RTX_FRAME_RELATED_P (tmp) = 1;
11472   XVECEXP (dwarf, 0, 0) = tmp;
11473
11474   tmp = gen_rtx_SET (VOIDmode,
11475                      gen_frame_mem (DFmode, stack_pointer_rtx),
11476                      reg);
11477   RTX_FRAME_RELATED_P (tmp) = 1;
11478   XVECEXP (dwarf, 0, 1) = tmp;
11479
11480   for (i = 1; i < count; i++)
11481     {
11482       reg = gen_rtx_REG (DFmode, base_reg);
11483       base_reg += 2;
11484       XVECEXP (par, 0, i) = gen_rtx_USE (VOIDmode, reg);
11485
11486       tmp = gen_rtx_SET (VOIDmode,
11487                          gen_frame_mem (DFmode,
11488                                         plus_constant (stack_pointer_rtx,
11489                                                        i * 8)),
11490                          reg);
11491       RTX_FRAME_RELATED_P (tmp) = 1;
11492       XVECEXP (dwarf, 0, i + 1) = tmp;
11493     }
11494
11495   par = emit_insn (par);
11496   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
11497   RTX_FRAME_RELATED_P (par) = 1;
11498
11499   return count * 8;
11500 }
11501
11502 /* Emit a call instruction with pattern PAT.  ADDR is the address of
11503    the call target.  */
11504
11505 void
11506 arm_emit_call_insn (rtx pat, rtx addr)
11507 {
11508   rtx insn;
11509
11510   insn = emit_call_insn (pat);
11511
11512   /* The PIC register is live on entry to VxWorks PIC PLT entries.
11513      If the call might use such an entry, add a use of the PIC register
11514      to the instruction's CALL_INSN_FUNCTION_USAGE.  */
11515   if (TARGET_VXWORKS_RTP
11516       && flag_pic
11517       && GET_CODE (addr) == SYMBOL_REF
11518       && (SYMBOL_REF_DECL (addr)
11519           ? !targetm.binds_local_p (SYMBOL_REF_DECL (addr))
11520           : !SYMBOL_REF_LOCAL_P (addr)))
11521     {
11522       require_pic_register ();
11523       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), cfun->machine->pic_reg);
11524     }
11525 }
11526
11527 /* Output a 'call' insn.  */
11528 const char *
11529 output_call (rtx *operands)
11530 {
11531   gcc_assert (!arm_arch5); /* Patterns should call blx <reg> directly.  */
11532
11533   /* Handle calls to lr using ip (which may be clobbered in subr anyway).  */
11534   if (REGNO (operands[0]) == LR_REGNUM)
11535     {
11536       operands[0] = gen_rtx_REG (SImode, IP_REGNUM);
11537       output_asm_insn ("mov%?\t%0, %|lr", operands);
11538     }
11539
11540   output_asm_insn ("mov%?\t%|lr, %|pc", operands);
11541
11542   if (TARGET_INTERWORK || arm_arch4t)
11543     output_asm_insn ("bx%?\t%0", operands);
11544   else
11545     output_asm_insn ("mov%?\t%|pc, %0", operands);
11546
11547   return "";
11548 }
11549
11550 /* Output a 'call' insn that is a reference in memory.  */
11551 const char *
11552 output_call_mem (rtx *operands)
11553 {
11554   if (TARGET_INTERWORK && !arm_arch5)
11555     {
11556       output_asm_insn ("ldr%?\t%|ip, %0", operands);
11557       output_asm_insn ("mov%?\t%|lr, %|pc", operands);
11558       output_asm_insn ("bx%?\t%|ip", operands);
11559     }
11560   else if (regno_use_in (LR_REGNUM, operands[0]))
11561     {
11562       /* LR is used in the memory address.  We load the address in the
11563          first instruction.  It's safe to use IP as the target of the
11564          load since the call will kill it anyway.  */
11565       output_asm_insn ("ldr%?\t%|ip, %0", operands);
11566       if (arm_arch5)
11567         output_asm_insn ("blx%?\t%|ip", operands);
11568       else
11569         {
11570           output_asm_insn ("mov%?\t%|lr, %|pc", operands);
11571           if (arm_arch4t)
11572             output_asm_insn ("bx%?\t%|ip", operands);
11573           else
11574             output_asm_insn ("mov%?\t%|pc, %|ip", operands);
11575         }
11576     }
11577   else
11578     {
11579       output_asm_insn ("mov%?\t%|lr, %|pc", operands);
11580       output_asm_insn ("ldr%?\t%|pc, %0", operands);
11581     }
11582
11583   return "";
11584 }
11585
11586
11587 /* Output a move from arm registers to an fpa registers.
11588    OPERANDS[0] is an fpa register.
11589    OPERANDS[1] is the first registers of an arm register pair.  */
11590 const char *
11591 output_mov_long_double_fpa_from_arm (rtx *operands)
11592 {
11593   int arm_reg0 = REGNO (operands[1]);
11594   rtx ops[3];
11595
11596   gcc_assert (arm_reg0 != IP_REGNUM);
11597
11598   ops[0] = gen_rtx_REG (SImode, arm_reg0);
11599   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
11600   ops[2] = gen_rtx_REG (SImode, 2 + arm_reg0);
11601
11602   output_asm_insn ("stm%(fd%)\t%|sp!, {%0, %1, %2}", ops);
11603   output_asm_insn ("ldf%?e\t%0, [%|sp], #12", operands);
11604
11605   return "";
11606 }
11607
11608 /* Output a move from an fpa register to arm registers.
11609    OPERANDS[0] is the first registers of an arm register pair.
11610    OPERANDS[1] is an fpa register.  */
11611 const char *
11612 output_mov_long_double_arm_from_fpa (rtx *operands)
11613 {
11614   int arm_reg0 = REGNO (operands[0]);
11615   rtx ops[3];
11616
11617   gcc_assert (arm_reg0 != IP_REGNUM);
11618
11619   ops[0] = gen_rtx_REG (SImode, arm_reg0);
11620   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
11621   ops[2] = gen_rtx_REG (SImode, 2 + arm_reg0);
11622
11623   output_asm_insn ("stf%?e\t%1, [%|sp, #-12]!", operands);
11624   output_asm_insn ("ldm%(fd%)\t%|sp!, {%0, %1, %2}", ops);
11625   return "";
11626 }
11627
11628 /* Output a move from arm registers to arm registers of a long double
11629    OPERANDS[0] is the destination.
11630    OPERANDS[1] is the source.  */
11631 const char *
11632 output_mov_long_double_arm_from_arm (rtx *operands)
11633 {
11634   /* We have to be careful here because the two might overlap.  */
11635   int dest_start = REGNO (operands[0]);
11636   int src_start = REGNO (operands[1]);
11637   rtx ops[2];
11638   int i;
11639
11640   if (dest_start < src_start)
11641     {
11642       for (i = 0; i < 3; i++)
11643         {
11644           ops[0] = gen_rtx_REG (SImode, dest_start + i);
11645           ops[1] = gen_rtx_REG (SImode, src_start + i);
11646           output_asm_insn ("mov%?\t%0, %1", ops);
11647         }
11648     }
11649   else
11650     {
11651       for (i = 2; i >= 0; i--)
11652         {
11653           ops[0] = gen_rtx_REG (SImode, dest_start + i);
11654           ops[1] = gen_rtx_REG (SImode, src_start + i);
11655           output_asm_insn ("mov%?\t%0, %1", ops);
11656         }
11657     }
11658
11659   return "";
11660 }
11661
11662 void
11663 arm_emit_movpair (rtx dest, rtx src)
11664  {
11665   /* If the src is an immediate, simplify it.  */
11666   if (CONST_INT_P (src))
11667     {
11668       HOST_WIDE_INT val = INTVAL (src);
11669       emit_set_insn (dest, GEN_INT (val & 0x0000ffff));
11670       if ((val >> 16) & 0x0000ffff)
11671         emit_set_insn (gen_rtx_ZERO_EXTRACT (SImode, dest, GEN_INT (16),
11672                                              GEN_INT (16)),
11673                        GEN_INT ((val >> 16) & 0x0000ffff));
11674       return;
11675     }
11676    emit_set_insn (dest, gen_rtx_HIGH (SImode, src));
11677    emit_set_insn (dest, gen_rtx_LO_SUM (SImode, dest, src));
11678  }
11679
11680 /* Output a move from arm registers to an fpa registers.
11681    OPERANDS[0] is an fpa register.
11682    OPERANDS[1] is the first registers of an arm register pair.  */
11683 const char *
11684 output_mov_double_fpa_from_arm (rtx *operands)
11685 {
11686   int arm_reg0 = REGNO (operands[1]);
11687   rtx ops[2];
11688
11689   gcc_assert (arm_reg0 != IP_REGNUM);
11690
11691   ops[0] = gen_rtx_REG (SImode, arm_reg0);
11692   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
11693   output_asm_insn ("stm%(fd%)\t%|sp!, {%0, %1}", ops);
11694   output_asm_insn ("ldf%?d\t%0, [%|sp], #8", operands);
11695   return "";
11696 }
11697
11698 /* Output a move from an fpa register to arm registers.
11699    OPERANDS[0] is the first registers of an arm register pair.
11700    OPERANDS[1] is an fpa register.  */
11701 const char *
11702 output_mov_double_arm_from_fpa (rtx *operands)
11703 {
11704   int arm_reg0 = REGNO (operands[0]);
11705   rtx ops[2];
11706
11707   gcc_assert (arm_reg0 != IP_REGNUM);
11708
11709   ops[0] = gen_rtx_REG (SImode, arm_reg0);
11710   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
11711   output_asm_insn ("stf%?d\t%1, [%|sp, #-8]!", operands);
11712   output_asm_insn ("ldm%(fd%)\t%|sp!, {%0, %1}", ops);
11713   return "";
11714 }
11715
11716 /* Output a move between double words.
11717    It must be REG<-REG, REG<-CONST_DOUBLE, REG<-CONST_INT, REG<-MEM
11718    or MEM<-REG and all MEMs must be offsettable addresses.  */
11719 const char *
11720 output_move_double (rtx *operands)
11721 {
11722   enum rtx_code code0 = GET_CODE (operands[0]);
11723   enum rtx_code code1 = GET_CODE (operands[1]);
11724   rtx otherops[3];
11725
11726   if (code0 == REG)
11727     {
11728       unsigned int reg0 = REGNO (operands[0]);
11729
11730       otherops[0] = gen_rtx_REG (SImode, 1 + reg0);
11731
11732       gcc_assert (code1 == MEM);  /* Constraints should ensure this.  */
11733
11734       switch (GET_CODE (XEXP (operands[1], 0)))
11735         {
11736         case REG:
11737           if (TARGET_LDRD
11738               && !(fix_cm3_ldrd && reg0 == REGNO(XEXP (operands[1], 0))))
11739             output_asm_insn ("ldr%(d%)\t%0, [%m1]", operands);
11740           else
11741             output_asm_insn ("ldm%(ia%)\t%m1, %M0", operands);
11742           break;
11743
11744         case PRE_INC:
11745           gcc_assert (TARGET_LDRD);
11746           output_asm_insn ("ldr%(d%)\t%0, [%m1, #8]!", operands);
11747           break;
11748
11749         case PRE_DEC:
11750           if (TARGET_LDRD)
11751             output_asm_insn ("ldr%(d%)\t%0, [%m1, #-8]!", operands);
11752           else
11753             output_asm_insn ("ldm%(db%)\t%m1!, %M0", operands);
11754           break;
11755
11756         case POST_INC:
11757           if (TARGET_LDRD)
11758             output_asm_insn ("ldr%(d%)\t%0, [%m1], #8", operands);
11759           else
11760             output_asm_insn ("ldm%(ia%)\t%m1!, %M0", operands);
11761           break;
11762
11763         case POST_DEC:
11764           gcc_assert (TARGET_LDRD);
11765           output_asm_insn ("ldr%(d%)\t%0, [%m1], #-8", operands);
11766           break;
11767
11768         case PRE_MODIFY:
11769         case POST_MODIFY:
11770           /* Autoicrement addressing modes should never have overlapping
11771              base and destination registers, and overlapping index registers
11772              are already prohibited, so this doesn't need to worry about
11773              fix_cm3_ldrd.  */
11774           otherops[0] = operands[0];
11775           otherops[1] = XEXP (XEXP (XEXP (operands[1], 0), 1), 0);
11776           otherops[2] = XEXP (XEXP (XEXP (operands[1], 0), 1), 1);
11777
11778           if (GET_CODE (XEXP (operands[1], 0)) == PRE_MODIFY)
11779             {
11780               if (reg_overlap_mentioned_p (otherops[0], otherops[2]))
11781                 {
11782                   /* Registers overlap so split out the increment.  */
11783                   output_asm_insn ("add%?\t%1, %1, %2", otherops);
11784                   output_asm_insn ("ldr%(d%)\t%0, [%1] @split", otherops);
11785                 }
11786               else
11787                 {
11788                   /* Use a single insn if we can.
11789                      FIXME: IWMMXT allows offsets larger than ldrd can
11790                      handle, fix these up with a pair of ldr.  */
11791                   if (TARGET_THUMB2
11792                       || GET_CODE (otherops[2]) != CONST_INT
11793                       || (INTVAL (otherops[2]) > -256
11794                           && INTVAL (otherops[2]) < 256))
11795                     output_asm_insn ("ldr%(d%)\t%0, [%1, %2]!", otherops);
11796                   else
11797                     {
11798                       output_asm_insn ("ldr%?\t%0, [%1, %2]!", otherops);
11799                       output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
11800                     }
11801                 }
11802             }
11803           else
11804             {
11805               /* Use a single insn if we can.
11806                  FIXME: IWMMXT allows offsets larger than ldrd can handle,
11807                  fix these up with a pair of ldr.  */
11808               if (TARGET_THUMB2
11809                   || GET_CODE (otherops[2]) != CONST_INT
11810                   || (INTVAL (otherops[2]) > -256
11811                       && INTVAL (otherops[2]) < 256))
11812                 output_asm_insn ("ldr%(d%)\t%0, [%1], %2", otherops);
11813               else
11814                 {
11815                   output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
11816                   output_asm_insn ("ldr%?\t%0, [%1], %2", otherops);
11817                 }
11818             }
11819           break;
11820
11821         case LABEL_REF:
11822         case CONST:
11823           /* We might be able to use ldrd %0, %1 here.  However the range is
11824              different to ldr/adr, and it is broken on some ARMv7-M
11825              implementations.  */
11826           /* Use the second register of the pair to avoid problematic
11827              overlap.  */
11828           otherops[1] = operands[1];
11829           output_asm_insn ("adr%?\t%0, %1", otherops);
11830           operands[1] = otherops[0];
11831           if (TARGET_LDRD)
11832             output_asm_insn ("ldr%(d%)\t%0, [%1]", operands);
11833           else
11834             output_asm_insn ("ldm%(ia%)\t%1, %M0", operands);
11835           break;
11836
11837           /* ??? This needs checking for thumb2.  */
11838         default:
11839           if (arm_add_operand (XEXP (XEXP (operands[1], 0), 1),
11840                                GET_MODE (XEXP (XEXP (operands[1], 0), 1))))
11841             {
11842               otherops[0] = operands[0];
11843               otherops[1] = XEXP (XEXP (operands[1], 0), 0);
11844               otherops[2] = XEXP (XEXP (operands[1], 0), 1);
11845
11846               if (GET_CODE (XEXP (operands[1], 0)) == PLUS)
11847                 {
11848                   if (GET_CODE (otherops[2]) == CONST_INT && !TARGET_LDRD)
11849                     {
11850                       switch ((int) INTVAL (otherops[2]))
11851                         {
11852                         case -8:
11853                           output_asm_insn ("ldm%(db%)\t%1, %M0", otherops);
11854                           return "";
11855                         case -4:
11856                           if (TARGET_THUMB2)
11857                             break;
11858                           output_asm_insn ("ldm%(da%)\t%1, %M0", otherops);
11859                           return "";
11860                         case 4:
11861                           if (TARGET_THUMB2)
11862                             break;
11863                           output_asm_insn ("ldm%(ib%)\t%1, %M0", otherops);
11864                           return "";
11865                         }
11866                     }
11867                   otherops[0] = gen_rtx_REG(SImode, REGNO(operands[0]) + 1);
11868                   operands[1] = otherops[0];
11869                   if (TARGET_LDRD
11870                       && (GET_CODE (otherops[2]) == REG
11871                           || TARGET_THUMB2
11872                           || (GET_CODE (otherops[2]) == CONST_INT
11873                               && INTVAL (otherops[2]) > -256
11874                               && INTVAL (otherops[2]) < 256)))
11875                     {
11876                       if (reg_overlap_mentioned_p (operands[0],
11877                                                    otherops[2]))
11878                         {
11879                           rtx tmp;
11880                           /* Swap base and index registers over to
11881                              avoid a conflict.  */
11882                           tmp = otherops[1];
11883                           otherops[1] = otherops[2];
11884                           otherops[2] = tmp;
11885                         }
11886                       /* If both registers conflict, it will usually
11887                          have been fixed by a splitter.  */
11888                       if (reg_overlap_mentioned_p (operands[0], otherops[2])
11889                           || (fix_cm3_ldrd && reg0 == REGNO (otherops[1])))
11890                         {
11891                           output_asm_insn ("add%?\t%0, %1, %2", otherops);
11892                           output_asm_insn ("ldr%(d%)\t%0, [%1]", operands);
11893                         }
11894                       else
11895                         {
11896                           otherops[0] = operands[0];
11897                           output_asm_insn ("ldr%(d%)\t%0, [%1, %2]", otherops);
11898                         }
11899                       return "";
11900                     }
11901
11902                   if (GET_CODE (otherops[2]) == CONST_INT)
11903                     {
11904                       if (!(const_ok_for_arm (INTVAL (otherops[2]))))
11905                         output_asm_insn ("sub%?\t%0, %1, #%n2", otherops);
11906                       else
11907                         output_asm_insn ("add%?\t%0, %1, %2", otherops);
11908                     }
11909                   else
11910                     output_asm_insn ("add%?\t%0, %1, %2", otherops);
11911                 }
11912               else
11913                 output_asm_insn ("sub%?\t%0, %1, %2", otherops);
11914
11915               if (TARGET_LDRD)
11916                 return "ldr%(d%)\t%0, [%1]";
11917
11918               return "ldm%(ia%)\t%1, %M0";
11919             }
11920           else
11921             {
11922               otherops[1] = adjust_address (operands[1], SImode, 4);
11923               /* Take care of overlapping base/data reg.  */
11924               if (reg_mentioned_p (operands[0], operands[1]))
11925                 {
11926                   output_asm_insn ("ldr%?\t%0, %1", otherops);
11927                   output_asm_insn ("ldr%?\t%0, %1", operands);
11928                 }
11929               else
11930                 {
11931                   output_asm_insn ("ldr%?\t%0, %1", operands);
11932                   output_asm_insn ("ldr%?\t%0, %1", otherops);
11933                 }
11934             }
11935         }
11936     }
11937   else
11938     {
11939       /* Constraints should ensure this.  */
11940       gcc_assert (code0 == MEM && code1 == REG);
11941       gcc_assert (REGNO (operands[1]) != IP_REGNUM);
11942
11943       switch (GET_CODE (XEXP (operands[0], 0)))
11944         {
11945         case REG:
11946           if (TARGET_LDRD)
11947             output_asm_insn ("str%(d%)\t%1, [%m0]", operands);
11948           else
11949             output_asm_insn ("stm%(ia%)\t%m0, %M1", operands);
11950           break;
11951
11952         case PRE_INC:
11953           gcc_assert (TARGET_LDRD);
11954           output_asm_insn ("str%(d%)\t%1, [%m0, #8]!", operands);
11955           break;
11956
11957         case PRE_DEC:
11958           if (TARGET_LDRD)
11959             output_asm_insn ("str%(d%)\t%1, [%m0, #-8]!", operands);
11960           else
11961             output_asm_insn ("stm%(db%)\t%m0!, %M1", operands);
11962           break;
11963
11964         case POST_INC:
11965           if (TARGET_LDRD)
11966             output_asm_insn ("str%(d%)\t%1, [%m0], #8", operands);
11967           else
11968             output_asm_insn ("stm%(ia%)\t%m0!, %M1", operands);
11969           break;
11970
11971         case POST_DEC:
11972           gcc_assert (TARGET_LDRD);
11973           output_asm_insn ("str%(d%)\t%1, [%m0], #-8", operands);
11974           break;
11975
11976         case PRE_MODIFY:
11977         case POST_MODIFY:
11978           otherops[0] = operands[1];
11979           otherops[1] = XEXP (XEXP (XEXP (operands[0], 0), 1), 0);
11980           otherops[2] = XEXP (XEXP (XEXP (operands[0], 0), 1), 1);
11981
11982           /* IWMMXT allows offsets larger than ldrd can handle,
11983              fix these up with a pair of ldr.  */
11984           if (!TARGET_THUMB2
11985               && GET_CODE (otherops[2]) == CONST_INT
11986               && (INTVAL(otherops[2]) <= -256
11987                   || INTVAL(otherops[2]) >= 256))
11988             {
11989               if (GET_CODE (XEXP (operands[0], 0)) == PRE_MODIFY)
11990                 {
11991                   output_asm_insn ("ldr%?\t%0, [%1, %2]!", otherops);
11992                   output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
11993                 }
11994               else
11995                 {
11996                   output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
11997                   output_asm_insn ("ldr%?\t%0, [%1], %2", otherops);
11998                 }
11999             }
12000           else if (GET_CODE (XEXP (operands[0], 0)) == PRE_MODIFY)
12001             output_asm_insn ("str%(d%)\t%0, [%1, %2]!", otherops);
12002           else
12003             output_asm_insn ("str%(d%)\t%0, [%1], %2", otherops);
12004           break;
12005
12006         case PLUS:
12007           otherops[2] = XEXP (XEXP (operands[0], 0), 1);
12008           if (GET_CODE (otherops[2]) == CONST_INT && !TARGET_LDRD)
12009             {
12010               switch ((int) INTVAL (XEXP (XEXP (operands[0], 0), 1)))
12011                 {
12012                 case -8:
12013                   output_asm_insn ("stm%(db%)\t%m0, %M1", operands);
12014                   return "";
12015
12016                 case -4:
12017                   if (TARGET_THUMB2)
12018                     break;
12019                   output_asm_insn ("stm%(da%)\t%m0, %M1", operands);
12020                   return "";
12021
12022                 case 4:
12023                   if (TARGET_THUMB2)
12024                     break;
12025                   output_asm_insn ("stm%(ib%)\t%m0, %M1", operands);
12026                   return "";
12027                 }
12028             }
12029           if (TARGET_LDRD
12030               && (GET_CODE (otherops[2]) == REG
12031                   || TARGET_THUMB2
12032                   || (GET_CODE (otherops[2]) == CONST_INT
12033                       && INTVAL (otherops[2]) > -256
12034                       && INTVAL (otherops[2]) < 256)))
12035             {
12036               otherops[0] = operands[1];
12037               otherops[1] = XEXP (XEXP (operands[0], 0), 0);
12038               output_asm_insn ("str%(d%)\t%0, [%1, %2]", otherops);
12039               return "";
12040             }
12041           /* Fall through */
12042
12043         default:
12044           otherops[0] = adjust_address (operands[0], SImode, 4);
12045           otherops[1] = operands[1];
12046           output_asm_insn ("str%?\t%1, %0", operands);
12047           output_asm_insn ("str%?\t%H1, %0", otherops);
12048         }
12049     }
12050
12051   return "";
12052 }
12053
12054 /* Output a move, load or store for quad-word vectors in ARM registers.  Only
12055    handles MEMs accepted by neon_vector_mem_operand with TYPE=1.  */
12056
12057 const char *
12058 output_move_quad (rtx *operands)
12059 {
12060   if (REG_P (operands[0]))
12061     {
12062       /* Load, or reg->reg move.  */
12063
12064       if (MEM_P (operands[1]))
12065         {
12066           switch (GET_CODE (XEXP (operands[1], 0)))
12067             {
12068             case REG:
12069               output_asm_insn ("ldm%(ia%)\t%m1, %M0", operands);
12070               break;
12071
12072             case LABEL_REF:
12073             case CONST:
12074               output_asm_insn ("adr%?\t%0, %1", operands);
12075               output_asm_insn ("ldm%(ia%)\t%0, %M0", operands);
12076               break;
12077
12078             default:
12079               gcc_unreachable ();
12080             }
12081         }
12082       else
12083         {
12084           rtx ops[2];
12085           int dest, src, i;
12086
12087           gcc_assert (REG_P (operands[1]));
12088
12089           dest = REGNO (operands[0]);
12090           src = REGNO (operands[1]);
12091
12092           /* This seems pretty dumb, but hopefully GCC won't try to do it
12093              very often.  */
12094           if (dest < src)
12095             for (i = 0; i < 4; i++)
12096               {
12097                 ops[0] = gen_rtx_REG (SImode, dest + i);
12098                 ops[1] = gen_rtx_REG (SImode, src + i);
12099                 output_asm_insn ("mov%?\t%0, %1", ops);
12100               }
12101           else
12102             for (i = 3; i >= 0; i--)
12103               {
12104                 ops[0] = gen_rtx_REG (SImode, dest + i);
12105                 ops[1] = gen_rtx_REG (SImode, src + i);
12106                 output_asm_insn ("mov%?\t%0, %1", ops);
12107               }
12108         }
12109     }
12110   else
12111     {
12112       gcc_assert (MEM_P (operands[0]));
12113       gcc_assert (REG_P (operands[1]));
12114       gcc_assert (!reg_overlap_mentioned_p (operands[1], operands[0]));
12115
12116       switch (GET_CODE (XEXP (operands[0], 0)))
12117         {
12118         case REG:
12119           output_asm_insn ("stm%(ia%)\t%m0, %M1", operands);
12120           break;
12121
12122         default:
12123           gcc_unreachable ();
12124         }
12125     }
12126
12127   return "";
12128 }
12129
12130 /* Output a VFP load or store instruction.  */
12131
12132 const char *
12133 output_move_vfp (rtx *operands)
12134 {
12135   rtx reg, mem, addr, ops[2];
12136   int load = REG_P (operands[0]);
12137   int dp = GET_MODE_SIZE (GET_MODE (operands[0])) == 8;
12138   int integer_p = GET_MODE_CLASS (GET_MODE (operands[0])) == MODE_INT;
12139   const char *templ;
12140   char buff[50];
12141   enum machine_mode mode;
12142
12143   reg = operands[!load];
12144   mem = operands[load];
12145
12146   mode = GET_MODE (reg);
12147
12148   gcc_assert (REG_P (reg));
12149   gcc_assert (IS_VFP_REGNUM (REGNO (reg)));
12150   gcc_assert (mode == SFmode
12151               || mode == DFmode
12152               || mode == SImode
12153               || mode == DImode
12154               || (TARGET_NEON && VALID_NEON_DREG_MODE (mode)));
12155   gcc_assert (MEM_P (mem));
12156
12157   addr = XEXP (mem, 0);
12158
12159   switch (GET_CODE (addr))
12160     {
12161     case PRE_DEC:
12162       templ = "f%smdb%c%%?\t%%0!, {%%%s1}%s";
12163       ops[0] = XEXP (addr, 0);
12164       ops[1] = reg;
12165       break;
12166
12167     case POST_INC:
12168       templ = "f%smia%c%%?\t%%0!, {%%%s1}%s";
12169       ops[0] = XEXP (addr, 0);
12170       ops[1] = reg;
12171       break;
12172
12173     default:
12174       templ = "f%s%c%%?\t%%%s0, %%1%s";
12175       ops[0] = reg;
12176       ops[1] = mem;
12177       break;
12178     }
12179
12180   sprintf (buff, templ,
12181            load ? "ld" : "st",
12182            dp ? 'd' : 's',
12183            dp ? "P" : "",
12184            integer_p ? "\t%@ int" : "");
12185   output_asm_insn (buff, ops);
12186
12187   return "";
12188 }
12189
12190 /* Output a Neon quad-word load or store, or a load or store for
12191    larger structure modes.
12192
12193    WARNING: The ordering of elements is weird in big-endian mode,
12194    because we use VSTM, as required by the EABI.  GCC RTL defines
12195    element ordering based on in-memory order.  This can be differ
12196    from the architectural ordering of elements within a NEON register.
12197    The intrinsics defined in arm_neon.h use the NEON register element
12198    ordering, not the GCC RTL element ordering.
12199
12200    For example, the in-memory ordering of a big-endian a quadword
12201    vector with 16-bit elements when stored from register pair {d0,d1}
12202    will be (lowest address first, d0[N] is NEON register element N):
12203
12204      [d0[3], d0[2], d0[1], d0[0], d1[7], d1[6], d1[5], d1[4]]
12205
12206    When necessary, quadword registers (dN, dN+1) are moved to ARM
12207    registers from rN in the order:
12208
12209      dN -> (rN+1, rN), dN+1 -> (rN+3, rN+2)
12210
12211    So that STM/LDM can be used on vectors in ARM registers, and the
12212    same memory layout will result as if VSTM/VLDM were used.  */
12213
12214 const char *
12215 output_move_neon (rtx *operands)
12216 {
12217   rtx reg, mem, addr, ops[2];
12218   int regno, load = REG_P (operands[0]);
12219   const char *templ;
12220   char buff[50];
12221   enum machine_mode mode;
12222
12223   reg = operands[!load];
12224   mem = operands[load];
12225
12226   mode = GET_MODE (reg);
12227
12228   gcc_assert (REG_P (reg));
12229   regno = REGNO (reg);
12230   gcc_assert (VFP_REGNO_OK_FOR_DOUBLE (regno)
12231               || NEON_REGNO_OK_FOR_QUAD (regno));
12232   gcc_assert (VALID_NEON_DREG_MODE (mode)
12233               || VALID_NEON_QREG_MODE (mode)
12234               || VALID_NEON_STRUCT_MODE (mode));
12235   gcc_assert (MEM_P (mem));
12236
12237   addr = XEXP (mem, 0);
12238
12239   /* Strip off const from addresses like (const (plus (...))).  */
12240   if (GET_CODE (addr) == CONST && GET_CODE (XEXP (addr, 0)) == PLUS)
12241     addr = XEXP (addr, 0);
12242
12243   switch (GET_CODE (addr))
12244     {
12245     case POST_INC:
12246       templ = "v%smia%%?\t%%0!, %%h1";
12247       ops[0] = XEXP (addr, 0);
12248       ops[1] = reg;
12249       break;
12250
12251     case PRE_DEC:
12252       /* FIXME: We should be using vld1/vst1 here in BE mode?  */
12253       templ = "v%smdb%%?\t%%0!, %%h1";
12254       ops[0] = XEXP (addr, 0);
12255       ops[1] = reg;
12256       break;
12257     
12258     case POST_MODIFY:
12259       /* FIXME: Not currently enabled in neon_vector_mem_operand.  */
12260       gcc_unreachable ();
12261
12262     case LABEL_REF:
12263     case PLUS:
12264       {
12265         int nregs = HARD_REGNO_NREGS (REGNO (reg), mode) / 2;
12266         int i;
12267         int overlap = -1;
12268         for (i = 0; i < nregs; i++)
12269           {
12270             /* We're only using DImode here because it's a convenient size.  */
12271             ops[0] = gen_rtx_REG (DImode, REGNO (reg) + 2 * i);
12272             ops[1] = adjust_address (mem, SImode, 8 * i);
12273             if (reg_overlap_mentioned_p (ops[0], mem))
12274               {
12275                 gcc_assert (overlap == -1);
12276                 overlap = i;
12277               }
12278             else
12279               {
12280                 sprintf (buff, "v%sr%%?\t%%P0, %%1", load ? "ld" : "st");
12281                 output_asm_insn (buff, ops);
12282               }
12283           }
12284         if (overlap != -1)
12285           {
12286             ops[0] = gen_rtx_REG (DImode, REGNO (reg) + 2 * overlap);
12287             ops[1] = adjust_address (mem, SImode, 8 * overlap);
12288             sprintf (buff, "v%sr%%?\t%%P0, %%1", load ? "ld" : "st");
12289             output_asm_insn (buff, ops);
12290           }
12291
12292         return "";
12293       }
12294
12295     default:
12296       templ = "v%smia%%?\t%%m0, %%h1";
12297       ops[0] = mem;
12298       ops[1] = reg;
12299     }
12300
12301   sprintf (buff, templ, load ? "ld" : "st");
12302   output_asm_insn (buff, ops);
12303
12304   return "";
12305 }
12306
12307 /* Output an ADD r, s, #n where n may be too big for one instruction.
12308    If adding zero to one register, output nothing.  */
12309 const char *
12310 output_add_immediate (rtx *operands)
12311 {
12312   HOST_WIDE_INT n = INTVAL (operands[2]);
12313
12314   if (n != 0 || REGNO (operands[0]) != REGNO (operands[1]))
12315     {
12316       if (n < 0)
12317         output_multi_immediate (operands,
12318                                 "sub%?\t%0, %1, %2", "sub%?\t%0, %0, %2", 2,
12319                                 -n);
12320       else
12321         output_multi_immediate (operands,
12322                                 "add%?\t%0, %1, %2", "add%?\t%0, %0, %2", 2,
12323                                 n);
12324     }
12325
12326   return "";
12327 }
12328
12329 /* Output a multiple immediate operation.
12330    OPERANDS is the vector of operands referred to in the output patterns.
12331    INSTR1 is the output pattern to use for the first constant.
12332    INSTR2 is the output pattern to use for subsequent constants.
12333    IMMED_OP is the index of the constant slot in OPERANDS.
12334    N is the constant value.  */
12335 static const char *
12336 output_multi_immediate (rtx *operands, const char *instr1, const char *instr2,
12337                         int immed_op, HOST_WIDE_INT n)
12338 {
12339 #if HOST_BITS_PER_WIDE_INT > 32
12340   n &= 0xffffffff;
12341 #endif
12342
12343   if (n == 0)
12344     {
12345       /* Quick and easy output.  */
12346       operands[immed_op] = const0_rtx;
12347       output_asm_insn (instr1, operands);
12348     }
12349   else
12350     {
12351       int i;
12352       const char * instr = instr1;
12353
12354       /* Note that n is never zero here (which would give no output).  */
12355       for (i = 0; i < 32; i += 2)
12356         {
12357           if (n & (3 << i))
12358             {
12359               operands[immed_op] = GEN_INT (n & (255 << i));
12360               output_asm_insn (instr, operands);
12361               instr = instr2;
12362               i += 6;
12363             }
12364         }
12365     }
12366
12367   return "";
12368 }
12369
12370 /* Return the name of a shifter operation.  */
12371 static const char *
12372 arm_shift_nmem(enum rtx_code code)
12373 {
12374   switch (code)
12375     {
12376     case ASHIFT:
12377       return ARM_LSL_NAME;
12378
12379     case ASHIFTRT:
12380       return "asr";
12381
12382     case LSHIFTRT:
12383       return "lsr";
12384
12385     case ROTATERT:
12386       return "ror";
12387
12388     default:
12389       abort();
12390     }
12391 }
12392
12393 /* Return the appropriate ARM instruction for the operation code.
12394    The returned result should not be overwritten.  OP is the rtx of the
12395    operation.  SHIFT_FIRST_ARG is TRUE if the first argument of the operator
12396    was shifted.  */
12397 const char *
12398 arithmetic_instr (rtx op, int shift_first_arg)
12399 {
12400   switch (GET_CODE (op))
12401     {
12402     case PLUS:
12403       return "add";
12404
12405     case MINUS:
12406       return shift_first_arg ? "rsb" : "sub";
12407
12408     case IOR:
12409       return "orr";
12410
12411     case XOR:
12412       return "eor";
12413
12414     case AND:
12415       return "and";
12416
12417     case ASHIFT:
12418     case ASHIFTRT:
12419     case LSHIFTRT:
12420     case ROTATERT:
12421       return arm_shift_nmem(GET_CODE(op));
12422
12423     default:
12424       gcc_unreachable ();
12425     }
12426 }
12427
12428 /* Ensure valid constant shifts and return the appropriate shift mnemonic
12429    for the operation code.  The returned result should not be overwritten.
12430    OP is the rtx code of the shift.
12431    On exit, *AMOUNTP will be -1 if the shift is by a register, or a constant
12432    shift.  */
12433 static const char *
12434 shift_op (rtx op, HOST_WIDE_INT *amountp)
12435 {
12436   const char * mnem;
12437   enum rtx_code code = GET_CODE (op);
12438
12439   switch (GET_CODE (XEXP (op, 1)))
12440     {
12441     case REG:
12442     case SUBREG:
12443       *amountp = -1;
12444       break;
12445
12446     case CONST_INT:
12447       *amountp = INTVAL (XEXP (op, 1));
12448       break;
12449
12450     default:
12451       gcc_unreachable ();
12452     }
12453
12454   switch (code)
12455     {
12456     case ROTATE:
12457       gcc_assert (*amountp != -1);
12458       *amountp = 32 - *amountp;
12459       code = ROTATERT;
12460
12461       /* Fall through.  */
12462
12463     case ASHIFT:
12464     case ASHIFTRT:
12465     case LSHIFTRT:
12466     case ROTATERT:
12467       mnem = arm_shift_nmem(code);
12468       break;
12469
12470     case MULT:
12471       /* We never have to worry about the amount being other than a
12472          power of 2, since this case can never be reloaded from a reg.  */
12473       gcc_assert (*amountp != -1);
12474       *amountp = int_log2 (*amountp);
12475       return ARM_LSL_NAME;
12476
12477     default:
12478       gcc_unreachable ();
12479     }
12480
12481   if (*amountp != -1)
12482     {
12483       /* This is not 100% correct, but follows from the desire to merge
12484          multiplication by a power of 2 with the recognizer for a
12485          shift.  >=32 is not a valid shift for "lsl", so we must try and
12486          output a shift that produces the correct arithmetical result.
12487          Using lsr #32 is identical except for the fact that the carry bit
12488          is not set correctly if we set the flags; but we never use the
12489          carry bit from such an operation, so we can ignore that.  */
12490       if (code == ROTATERT)
12491         /* Rotate is just modulo 32.  */
12492         *amountp &= 31;
12493       else if (*amountp != (*amountp & 31))
12494         {
12495           if (code == ASHIFT)
12496             mnem = "lsr";
12497           *amountp = 32;
12498         }
12499
12500       /* Shifts of 0 are no-ops.  */
12501       if (*amountp == 0)
12502         return NULL;
12503     }
12504
12505   return mnem;
12506 }
12507
12508 /* Obtain the shift from the POWER of two.  */
12509
12510 static HOST_WIDE_INT
12511 int_log2 (HOST_WIDE_INT power)
12512 {
12513   HOST_WIDE_INT shift = 0;
12514
12515   while ((((HOST_WIDE_INT) 1 << shift) & power) == 0)
12516     {
12517       gcc_assert (shift <= 31);
12518       shift++;
12519     }
12520
12521   return shift;
12522 }
12523
12524 /* Output a .ascii pseudo-op, keeping track of lengths.  This is
12525    because /bin/as is horribly restrictive.  The judgement about
12526    whether or not each character is 'printable' (and can be output as
12527    is) or not (and must be printed with an octal escape) must be made
12528    with reference to the *host* character set -- the situation is
12529    similar to that discussed in the comments above pp_c_char in
12530    c-pretty-print.c.  */
12531
12532 #define MAX_ASCII_LEN 51
12533
12534 void
12535 output_ascii_pseudo_op (FILE *stream, const unsigned char *p, int len)
12536 {
12537   int i;
12538   int len_so_far = 0;
12539
12540   fputs ("\t.ascii\t\"", stream);
12541
12542   for (i = 0; i < len; i++)
12543     {
12544       int c = p[i];
12545
12546       if (len_so_far >= MAX_ASCII_LEN)
12547         {
12548           fputs ("\"\n\t.ascii\t\"", stream);
12549           len_so_far = 0;
12550         }
12551
12552       if (ISPRINT (c))
12553         {
12554           if (c == '\\' || c == '\"')
12555             {
12556               putc ('\\', stream);
12557               len_so_far++;
12558             }
12559           putc (c, stream);
12560           len_so_far++;
12561         }
12562       else
12563         {
12564           fprintf (stream, "\\%03o", c);
12565           len_so_far += 4;
12566         }
12567     }
12568
12569   fputs ("\"\n", stream);
12570 }
12571 \f
12572 /* Compute the register save mask for registers 0 through 12
12573    inclusive.  This code is used by arm_compute_save_reg_mask.  */
12574
12575 static unsigned long
12576 arm_compute_save_reg0_reg12_mask (void)
12577 {
12578   unsigned long func_type = arm_current_func_type ();
12579   unsigned long save_reg_mask = 0;
12580   unsigned int reg;
12581
12582   if (IS_INTERRUPT (func_type))
12583     {
12584       unsigned int max_reg;
12585       /* Interrupt functions must not corrupt any registers,
12586          even call clobbered ones.  If this is a leaf function
12587          we can just examine the registers used by the RTL, but
12588          otherwise we have to assume that whatever function is
12589          called might clobber anything, and so we have to save
12590          all the call-clobbered registers as well.  */
12591       if (ARM_FUNC_TYPE (func_type) == ARM_FT_FIQ)
12592         /* FIQ handlers have registers r8 - r12 banked, so
12593            we only need to check r0 - r7, Normal ISRs only
12594            bank r14 and r15, so we must check up to r12.
12595            r13 is the stack pointer which is always preserved,
12596            so we do not need to consider it here.  */
12597         max_reg = 7;
12598       else
12599         max_reg = 12;
12600
12601       for (reg = 0; reg <= max_reg; reg++)
12602         if (df_regs_ever_live_p (reg)
12603             || (! current_function_is_leaf && call_used_regs[reg]))
12604           save_reg_mask |= (1 << reg);
12605
12606       /* Also save the pic base register if necessary.  */
12607       if (flag_pic
12608           && !TARGET_SINGLE_PIC_BASE
12609           && arm_pic_register != INVALID_REGNUM
12610           && crtl->uses_pic_offset_table)
12611         save_reg_mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
12612     }
12613   else
12614     {
12615       /* In the normal case we only need to save those registers
12616          which are call saved and which are used by this function.  */
12617       for (reg = 0; reg <= 11; reg++)
12618         if (df_regs_ever_live_p (reg) && ! call_used_regs[reg])
12619           save_reg_mask |= (1 << reg);
12620
12621       /* Handle the frame pointer as a special case.  */
12622       if (frame_pointer_needed)
12623         save_reg_mask |= 1 << HARD_FRAME_POINTER_REGNUM;
12624
12625       /* If we aren't loading the PIC register,
12626          don't stack it even though it may be live.  */
12627       if (flag_pic
12628           && !TARGET_SINGLE_PIC_BASE
12629           && arm_pic_register != INVALID_REGNUM
12630           && (df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM)
12631               || crtl->uses_pic_offset_table))
12632         save_reg_mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
12633
12634       /* The prologue will copy SP into R0, so save it.  */
12635       if (IS_STACKALIGN (func_type))
12636         save_reg_mask |= 1;
12637     }
12638
12639   /* Save registers so the exception handler can modify them.  */
12640   if (crtl->calls_eh_return)
12641     {
12642       unsigned int i;
12643
12644       for (i = 0; ; i++)
12645         {
12646           reg = EH_RETURN_DATA_REGNO (i);
12647           if (reg == INVALID_REGNUM)
12648             break;
12649           save_reg_mask |= 1 << reg;
12650         }
12651     }
12652
12653   return save_reg_mask;
12654 }
12655
12656
12657 /* Compute the number of bytes used to store the static chain register on the 
12658    stack, above the stack frame. We need to know this accurately to get the
12659    alignment of the rest of the stack frame correct. */
12660
12661 static int arm_compute_static_chain_stack_bytes (void)
12662 {
12663   unsigned long func_type = arm_current_func_type ();
12664   int static_chain_stack_bytes = 0;
12665
12666   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM &&
12667       IS_NESTED (func_type) &&
12668       df_regs_ever_live_p (3) && crtl->args.pretend_args_size == 0)
12669     static_chain_stack_bytes = 4;
12670
12671   return static_chain_stack_bytes;
12672 }
12673
12674
12675 /* Compute a bit mask of which registers need to be
12676    saved on the stack for the current function.
12677    This is used by arm_get_frame_offsets, which may add extra registers.  */
12678
12679 static unsigned long
12680 arm_compute_save_reg_mask (void)
12681 {
12682   unsigned int save_reg_mask = 0;
12683   unsigned long func_type = arm_current_func_type ();
12684   unsigned int reg;
12685
12686   if (IS_NAKED (func_type))
12687     /* This should never really happen.  */
12688     return 0;
12689
12690   /* If we are creating a stack frame, then we must save the frame pointer,
12691      IP (which will hold the old stack pointer), LR and the PC.  */
12692   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
12693     save_reg_mask |=
12694       (1 << ARM_HARD_FRAME_POINTER_REGNUM)
12695       | (1 << IP_REGNUM)
12696       | (1 << LR_REGNUM)
12697       | (1 << PC_REGNUM);
12698
12699   /* Volatile functions do not return, so there
12700      is no need to save any other registers.  */
12701   if (IS_VOLATILE (func_type))
12702     return save_reg_mask;
12703
12704   save_reg_mask |= arm_compute_save_reg0_reg12_mask ();
12705
12706   /* Decide if we need to save the link register.
12707      Interrupt routines have their own banked link register,
12708      so they never need to save it.
12709      Otherwise if we do not use the link register we do not need to save
12710      it.  If we are pushing other registers onto the stack however, we
12711      can save an instruction in the epilogue by pushing the link register
12712      now and then popping it back into the PC.  This incurs extra memory
12713      accesses though, so we only do it when optimizing for size, and only
12714      if we know that we will not need a fancy return sequence.  */
12715   if (df_regs_ever_live_p (LR_REGNUM)
12716       || (save_reg_mask
12717           && optimize_size
12718           && ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL
12719           && !crtl->calls_eh_return))
12720     save_reg_mask |= 1 << LR_REGNUM;
12721
12722   if (cfun->machine->lr_save_eliminated)
12723     save_reg_mask &= ~ (1 << LR_REGNUM);
12724
12725   if (TARGET_REALLY_IWMMXT
12726       && ((bit_count (save_reg_mask)
12727            + ARM_NUM_INTS (crtl->args.pretend_args_size +
12728                            arm_compute_static_chain_stack_bytes())
12729            ) % 2) != 0)
12730     {
12731       /* The total number of registers that are going to be pushed
12732          onto the stack is odd.  We need to ensure that the stack
12733          is 64-bit aligned before we start to save iWMMXt registers,
12734          and also before we start to create locals.  (A local variable
12735          might be a double or long long which we will load/store using
12736          an iWMMXt instruction).  Therefore we need to push another
12737          ARM register, so that the stack will be 64-bit aligned.  We
12738          try to avoid using the arg registers (r0 -r3) as they might be
12739          used to pass values in a tail call.  */
12740       for (reg = 4; reg <= 12; reg++)
12741         if ((save_reg_mask & (1 << reg)) == 0)
12742           break;
12743
12744       if (reg <= 12)
12745         save_reg_mask |= (1 << reg);
12746       else
12747         {
12748           cfun->machine->sibcall_blocked = 1;
12749           save_reg_mask |= (1 << 3);
12750         }
12751     }
12752
12753   /* We may need to push an additional register for use initializing the
12754      PIC base register.  */
12755   if (TARGET_THUMB2 && IS_NESTED (func_type) && flag_pic
12756       && (save_reg_mask & THUMB2_WORK_REGS) == 0)
12757     {
12758       reg = thumb_find_work_register (1 << 4);
12759       if (!call_used_regs[reg])
12760         save_reg_mask |= (1 << reg);
12761     }
12762
12763   return save_reg_mask;
12764 }
12765
12766
12767 /* Compute a bit mask of which registers need to be
12768    saved on the stack for the current function.  */
12769 static unsigned long
12770 thumb1_compute_save_reg_mask (void)
12771 {
12772   unsigned long mask;
12773   unsigned reg;
12774
12775   mask = 0;
12776   for (reg = 0; reg < 12; reg ++)
12777     if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
12778       mask |= 1 << reg;
12779
12780   if (flag_pic
12781       && !TARGET_SINGLE_PIC_BASE
12782       && arm_pic_register != INVALID_REGNUM
12783       && crtl->uses_pic_offset_table)
12784     mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
12785
12786   /* See if we might need r11 for calls to _interwork_r11_call_via_rN().  */
12787   if (!frame_pointer_needed && CALLER_INTERWORKING_SLOT_SIZE > 0)
12788     mask |= 1 << ARM_HARD_FRAME_POINTER_REGNUM;
12789
12790   /* LR will also be pushed if any lo regs are pushed.  */
12791   if (mask & 0xff || thumb_force_lr_save ())
12792     mask |= (1 << LR_REGNUM);
12793
12794   /* Make sure we have a low work register if we need one.
12795      We will need one if we are going to push a high register,
12796      but we are not currently intending to push a low register.  */
12797   if ((mask & 0xff) == 0
12798       && ((mask & 0x0f00) || TARGET_BACKTRACE))
12799     {
12800       /* Use thumb_find_work_register to choose which register
12801          we will use.  If the register is live then we will
12802          have to push it.  Use LAST_LO_REGNUM as our fallback
12803          choice for the register to select.  */
12804       reg = thumb_find_work_register (1 << LAST_LO_REGNUM);
12805       /* Make sure the register returned by thumb_find_work_register is
12806          not part of the return value.  */
12807       if (reg * UNITS_PER_WORD <= (unsigned) arm_size_return_regs ())
12808         reg = LAST_LO_REGNUM;
12809
12810       if (! call_used_regs[reg])
12811         mask |= 1 << reg;
12812     }
12813
12814   /* The 504 below is 8 bytes less than 512 because there are two possible
12815      alignment words.  We can't tell here if they will be present or not so we
12816      have to play it safe and assume that they are. */
12817   if ((CALLER_INTERWORKING_SLOT_SIZE +
12818        ROUND_UP_WORD (get_frame_size ()) +
12819        crtl->outgoing_args_size) >= 504)
12820     {
12821       /* This is the same as the code in thumb1_expand_prologue() which
12822          determines which register to use for stack decrement. */
12823       for (reg = LAST_ARG_REGNUM + 1; reg <= LAST_LO_REGNUM; reg++)
12824         if (mask & (1 << reg))
12825           break;
12826
12827       if (reg > LAST_LO_REGNUM)
12828         {
12829           /* Make sure we have a register available for stack decrement. */
12830           mask |= 1 << LAST_LO_REGNUM;
12831         }
12832     }
12833
12834   return mask;
12835 }
12836
12837
12838 /* Return the number of bytes required to save VFP registers.  */
12839 static int
12840 arm_get_vfp_saved_size (void)
12841 {
12842   unsigned int regno;
12843   int count;
12844   int saved;
12845
12846   saved = 0;
12847   /* Space for saved VFP registers.  */
12848   if (TARGET_HARD_FLOAT && TARGET_VFP)
12849     {
12850       count = 0;
12851       for (regno = FIRST_VFP_REGNUM;
12852            regno < LAST_VFP_REGNUM;
12853            regno += 2)
12854         {
12855           if ((!df_regs_ever_live_p (regno) || call_used_regs[regno])
12856               && (!df_regs_ever_live_p (regno + 1) || call_used_regs[regno + 1]))
12857             {
12858               if (count > 0)
12859                 {
12860                   /* Workaround ARM10 VFPr1 bug.  */
12861                   if (count == 2 && !arm_arch6)
12862                     count++;
12863                   saved += count * 8;
12864                 }
12865               count = 0;
12866             }
12867           else
12868             count++;
12869         }
12870       if (count > 0)
12871         {
12872           if (count == 2 && !arm_arch6)
12873             count++;
12874           saved += count * 8;
12875         }
12876     }
12877   return saved;
12878 }
12879
12880
12881 /* Generate a function exit sequence.  If REALLY_RETURN is false, then do
12882    everything bar the final return instruction.  */
12883 const char *
12884 output_return_instruction (rtx operand, int really_return, int reverse)
12885 {
12886   char conditional[10];
12887   char instr[100];
12888   unsigned reg;
12889   unsigned long live_regs_mask;
12890   unsigned long func_type;
12891   arm_stack_offsets *offsets;
12892
12893   func_type = arm_current_func_type ();
12894
12895   if (IS_NAKED (func_type))
12896     return "";
12897
12898   if (IS_VOLATILE (func_type) && TARGET_ABORT_NORETURN)
12899     {
12900       /* If this function was declared non-returning, and we have
12901          found a tail call, then we have to trust that the called
12902          function won't return.  */
12903       if (really_return)
12904         {
12905           rtx ops[2];
12906
12907           /* Otherwise, trap an attempted return by aborting.  */
12908           ops[0] = operand;
12909           ops[1] = gen_rtx_SYMBOL_REF (Pmode, NEED_PLT_RELOC ? "abort(PLT)"
12910                                        : "abort");
12911           assemble_external_libcall (ops[1]);
12912           output_asm_insn (reverse ? "bl%D0\t%a1" : "bl%d0\t%a1", ops);
12913         }
12914
12915       return "";
12916     }
12917
12918   gcc_assert (!cfun->calls_alloca || really_return);
12919
12920   sprintf (conditional, "%%?%%%c0", reverse ? 'D' : 'd');
12921
12922   cfun->machine->return_used_this_function = 1;
12923
12924   offsets = arm_get_frame_offsets ();
12925   live_regs_mask = offsets->saved_regs_mask;
12926
12927   if (live_regs_mask)
12928     {
12929       const char * return_reg;
12930
12931       /* If we do not have any special requirements for function exit
12932          (e.g. interworking) then we can load the return address
12933          directly into the PC.  Otherwise we must load it into LR.  */
12934       if (really_return
12935           && (IS_INTERRUPT (func_type) || !TARGET_INTERWORK))
12936         return_reg = reg_names[PC_REGNUM];
12937       else
12938         return_reg = reg_names[LR_REGNUM];
12939
12940       if ((live_regs_mask & (1 << IP_REGNUM)) == (1 << IP_REGNUM))
12941         {
12942           /* There are three possible reasons for the IP register
12943              being saved.  1) a stack frame was created, in which case
12944              IP contains the old stack pointer, or 2) an ISR routine
12945              corrupted it, or 3) it was saved to align the stack on
12946              iWMMXt.  In case 1, restore IP into SP, otherwise just
12947              restore IP.  */
12948           if (frame_pointer_needed)
12949             {
12950               live_regs_mask &= ~ (1 << IP_REGNUM);
12951               live_regs_mask |=   (1 << SP_REGNUM);
12952             }
12953           else
12954             gcc_assert (IS_INTERRUPT (func_type) || TARGET_REALLY_IWMMXT);
12955         }
12956
12957       /* On some ARM architectures it is faster to use LDR rather than
12958          LDM to load a single register.  On other architectures, the
12959          cost is the same.  In 26 bit mode, or for exception handlers,
12960          we have to use LDM to load the PC so that the CPSR is also
12961          restored.  */
12962       for (reg = 0; reg <= LAST_ARM_REGNUM; reg++)
12963         if (live_regs_mask == (1U << reg))
12964           break;
12965
12966       if (reg <= LAST_ARM_REGNUM
12967           && (reg != LR_REGNUM
12968               || ! really_return
12969               || ! IS_INTERRUPT (func_type)))
12970         {
12971           sprintf (instr, "ldr%s\t%%|%s, [%%|sp], #4", conditional,
12972                    (reg == LR_REGNUM) ? return_reg : reg_names[reg]);
12973         }
12974       else
12975         {
12976           char *p;
12977           int first = 1;
12978
12979           /* Generate the load multiple instruction to restore the
12980              registers.  Note we can get here, even if
12981              frame_pointer_needed is true, but only if sp already
12982              points to the base of the saved core registers.  */
12983           if (live_regs_mask & (1 << SP_REGNUM))
12984             {
12985               unsigned HOST_WIDE_INT stack_adjust;
12986
12987               stack_adjust = offsets->outgoing_args - offsets->saved_regs;
12988               gcc_assert (stack_adjust == 0 || stack_adjust == 4);
12989
12990               if (stack_adjust && arm_arch5 && TARGET_ARM)
12991                 if (TARGET_UNIFIED_ASM)
12992                   sprintf (instr, "ldmib%s\t%%|sp, {", conditional);
12993                 else
12994                   sprintf (instr, "ldm%sib\t%%|sp, {", conditional);
12995               else
12996                 {
12997                   /* If we can't use ldmib (SA110 bug),
12998                      then try to pop r3 instead.  */
12999                   if (stack_adjust)
13000                     live_regs_mask |= 1 << 3;
13001                   
13002                   if (TARGET_UNIFIED_ASM)
13003                     sprintf (instr, "ldmfd%s\t%%|sp, {", conditional);
13004                   else
13005                     sprintf (instr, "ldm%sfd\t%%|sp, {", conditional);
13006                 }
13007             }
13008           else
13009             if (TARGET_UNIFIED_ASM)
13010               sprintf (instr, "pop%s\t{", conditional);
13011             else
13012               sprintf (instr, "ldm%sfd\t%%|sp!, {", conditional);
13013
13014           p = instr + strlen (instr);
13015
13016           for (reg = 0; reg <= SP_REGNUM; reg++)
13017             if (live_regs_mask & (1 << reg))
13018               {
13019                 int l = strlen (reg_names[reg]);
13020
13021                 if (first)
13022                   first = 0;
13023                 else
13024                   {
13025                     memcpy (p, ", ", 2);
13026                     p += 2;
13027                   }
13028
13029                 memcpy (p, "%|", 2);
13030                 memcpy (p + 2, reg_names[reg], l);
13031                 p += l + 2;
13032               }
13033
13034           if (live_regs_mask & (1 << LR_REGNUM))
13035             {
13036               sprintf (p, "%s%%|%s}", first ? "" : ", ", return_reg);
13037               /* If returning from an interrupt, restore the CPSR.  */
13038               if (IS_INTERRUPT (func_type))
13039                 strcat (p, "^");
13040             }
13041           else
13042             strcpy (p, "}");
13043         }
13044
13045       output_asm_insn (instr, & operand);
13046
13047       /* See if we need to generate an extra instruction to
13048          perform the actual function return.  */
13049       if (really_return
13050           && func_type != ARM_FT_INTERWORKED
13051           && (live_regs_mask & (1 << LR_REGNUM)) != 0)
13052         {
13053           /* The return has already been handled
13054              by loading the LR into the PC.  */
13055           really_return = 0;
13056         }
13057     }
13058
13059   if (really_return)
13060     {
13061       switch ((int) ARM_FUNC_TYPE (func_type))
13062         {
13063         case ARM_FT_ISR:
13064         case ARM_FT_FIQ:
13065           /* ??? This is wrong for unified assembly syntax.  */
13066           sprintf (instr, "sub%ss\t%%|pc, %%|lr, #4", conditional);
13067           break;
13068
13069         case ARM_FT_INTERWORKED:
13070           sprintf (instr, "bx%s\t%%|lr", conditional);
13071           break;
13072
13073         case ARM_FT_EXCEPTION:
13074           /* ??? This is wrong for unified assembly syntax.  */
13075           sprintf (instr, "mov%ss\t%%|pc, %%|lr", conditional);
13076           break;
13077
13078         default:
13079           /* Use bx if it's available.  */
13080           if (arm_arch5 || arm_arch4t)
13081             sprintf (instr, "bx%s\t%%|lr", conditional);
13082           else
13083             sprintf (instr, "mov%s\t%%|pc, %%|lr", conditional);
13084           break;
13085         }
13086
13087       output_asm_insn (instr, & operand);
13088     }
13089
13090   return "";
13091 }
13092
13093 /* Write the function name into the code section, directly preceding
13094    the function prologue.
13095
13096    Code will be output similar to this:
13097      t0
13098          .ascii "arm_poke_function_name", 0
13099          .align
13100      t1
13101          .word 0xff000000 + (t1 - t0)
13102      arm_poke_function_name
13103          mov     ip, sp
13104          stmfd   sp!, {fp, ip, lr, pc}
13105          sub     fp, ip, #4
13106
13107    When performing a stack backtrace, code can inspect the value
13108    of 'pc' stored at 'fp' + 0.  If the trace function then looks
13109    at location pc - 12 and the top 8 bits are set, then we know
13110    that there is a function name embedded immediately preceding this
13111    location and has length ((pc[-3]) & 0xff000000).
13112
13113    We assume that pc is declared as a pointer to an unsigned long.
13114
13115    It is of no benefit to output the function name if we are assembling
13116    a leaf function.  These function types will not contain a stack
13117    backtrace structure, therefore it is not possible to determine the
13118    function name.  */
13119 void
13120 arm_poke_function_name (FILE *stream, const char *name)
13121 {
13122   unsigned long alignlength;
13123   unsigned long length;
13124   rtx           x;
13125
13126   length      = strlen (name) + 1;
13127   alignlength = ROUND_UP_WORD (length);
13128
13129   ASM_OUTPUT_ASCII (stream, name, length);
13130   ASM_OUTPUT_ALIGN (stream, 2);
13131   x = GEN_INT ((unsigned HOST_WIDE_INT) 0xff000000 + alignlength);
13132   assemble_aligned_integer (UNITS_PER_WORD, x);
13133 }
13134
13135 /* Place some comments into the assembler stream
13136    describing the current function.  */
13137 static void
13138 arm_output_function_prologue (FILE *f, HOST_WIDE_INT frame_size)
13139 {
13140   unsigned long func_type;
13141
13142   if (TARGET_THUMB1)
13143     {
13144       thumb1_output_function_prologue (f, frame_size);
13145       return;
13146     }
13147
13148   /* Sanity check.  */
13149   gcc_assert (!arm_ccfsm_state && !arm_target_insn);
13150
13151   func_type = arm_current_func_type ();
13152
13153   switch ((int) ARM_FUNC_TYPE (func_type))
13154     {
13155     default:
13156     case ARM_FT_NORMAL:
13157       break;
13158     case ARM_FT_INTERWORKED:
13159       asm_fprintf (f, "\t%@ Function supports interworking.\n");
13160       break;
13161     case ARM_FT_ISR:
13162       asm_fprintf (f, "\t%@ Interrupt Service Routine.\n");
13163       break;
13164     case ARM_FT_FIQ:
13165       asm_fprintf (f, "\t%@ Fast Interrupt Service Routine.\n");
13166       break;
13167     case ARM_FT_EXCEPTION:
13168       asm_fprintf (f, "\t%@ ARM Exception Handler.\n");
13169       break;
13170     }
13171
13172   if (IS_NAKED (func_type))
13173     asm_fprintf (f, "\t%@ Naked Function: prologue and epilogue provided by programmer.\n");
13174
13175   if (IS_VOLATILE (func_type))
13176     asm_fprintf (f, "\t%@ Volatile: function does not return.\n");
13177
13178   if (IS_NESTED (func_type))
13179     asm_fprintf (f, "\t%@ Nested: function declared inside another function.\n");
13180   if (IS_STACKALIGN (func_type))
13181     asm_fprintf (f, "\t%@ Stack Align: May be called with mis-aligned SP.\n");
13182
13183   asm_fprintf (f, "\t%@ args = %d, pretend = %d, frame = %wd\n",
13184                crtl->args.size,
13185                crtl->args.pretend_args_size, frame_size);
13186
13187   asm_fprintf (f, "\t%@ frame_needed = %d, uses_anonymous_args = %d\n",
13188                frame_pointer_needed,
13189                cfun->machine->uses_anonymous_args);
13190
13191   if (cfun->machine->lr_save_eliminated)
13192     asm_fprintf (f, "\t%@ link register save eliminated.\n");
13193
13194   if (crtl->calls_eh_return)
13195     asm_fprintf (f, "\t@ Calls __builtin_eh_return.\n");
13196
13197 }
13198
13199 const char *
13200 arm_output_epilogue (rtx sibling)
13201 {
13202   int reg;
13203   unsigned long saved_regs_mask;
13204   unsigned long func_type;
13205   /* Floats_offset is the offset from the "virtual" frame.  In an APCS
13206      frame that is $fp + 4 for a non-variadic function.  */
13207   int floats_offset = 0;
13208   rtx operands[3];
13209   FILE * f = asm_out_file;
13210   unsigned int lrm_count = 0;
13211   int really_return = (sibling == NULL);
13212   int start_reg;
13213   arm_stack_offsets *offsets;
13214
13215   /* If we have already generated the return instruction
13216      then it is futile to generate anything else.  */
13217   if (use_return_insn (FALSE, sibling) && 
13218       (cfun->machine->return_used_this_function != 0))
13219     return "";
13220
13221   func_type = arm_current_func_type ();
13222
13223   if (IS_NAKED (func_type))
13224     /* Naked functions don't have epilogues.  */
13225     return "";
13226
13227   if (IS_VOLATILE (func_type) && TARGET_ABORT_NORETURN)
13228     {
13229       rtx op;
13230
13231       /* A volatile function should never return.  Call abort.  */
13232       op = gen_rtx_SYMBOL_REF (Pmode, NEED_PLT_RELOC ? "abort(PLT)" : "abort");
13233       assemble_external_libcall (op);
13234       output_asm_insn ("bl\t%a0", &op);
13235
13236       return "";
13237     }
13238
13239   /* If we are throwing an exception, then we really must be doing a
13240      return, so we can't tail-call.  */
13241   gcc_assert (!crtl->calls_eh_return || really_return);
13242
13243   offsets = arm_get_frame_offsets ();
13244   saved_regs_mask = offsets->saved_regs_mask;
13245
13246   if (TARGET_IWMMXT)
13247     lrm_count = bit_count (saved_regs_mask);
13248
13249   floats_offset = offsets->saved_args;
13250   /* Compute how far away the floats will be.  */
13251   for (reg = 0; reg <= LAST_ARM_REGNUM; reg++)
13252     if (saved_regs_mask & (1 << reg))
13253       floats_offset += 4;
13254
13255   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
13256     {
13257       /* This variable is for the Virtual Frame Pointer, not VFP regs.  */
13258       int vfp_offset = offsets->frame;
13259
13260       if (arm_fpu_arch == FPUTYPE_FPA_EMU2)
13261         {
13262           for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
13263             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13264               {
13265                 floats_offset += 12;
13266                 asm_fprintf (f, "\tldfe\t%r, [%r, #-%d]\n",
13267                              reg, FP_REGNUM, floats_offset - vfp_offset);
13268               }
13269         }
13270       else
13271         {
13272           start_reg = LAST_FPA_REGNUM;
13273
13274           for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
13275             {
13276               if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13277                 {
13278                   floats_offset += 12;
13279
13280                   /* We can't unstack more than four registers at once.  */
13281                   if (start_reg - reg == 3)
13282                     {
13283                       asm_fprintf (f, "\tlfm\t%r, 4, [%r, #-%d]\n",
13284                                    reg, FP_REGNUM, floats_offset - vfp_offset);
13285                       start_reg = reg - 1;
13286                     }
13287                 }
13288               else
13289                 {
13290                   if (reg != start_reg)
13291                     asm_fprintf (f, "\tlfm\t%r, %d, [%r, #-%d]\n",
13292                                  reg + 1, start_reg - reg,
13293                                  FP_REGNUM, floats_offset - vfp_offset);
13294                   start_reg = reg - 1;
13295                 }
13296             }
13297
13298           /* Just in case the last register checked also needs unstacking.  */
13299           if (reg != start_reg)
13300             asm_fprintf (f, "\tlfm\t%r, %d, [%r, #-%d]\n",
13301                          reg + 1, start_reg - reg,
13302                          FP_REGNUM, floats_offset - vfp_offset);
13303         }
13304
13305       if (TARGET_HARD_FLOAT && TARGET_VFP)
13306         {
13307           int saved_size;
13308
13309           /* The fldmd insns do not have base+offset addressing
13310              modes, so we use IP to hold the address.  */
13311           saved_size = arm_get_vfp_saved_size ();
13312
13313           if (saved_size > 0)
13314             {
13315               floats_offset += saved_size;
13316               asm_fprintf (f, "\tsub\t%r, %r, #%d\n", IP_REGNUM,
13317                            FP_REGNUM, floats_offset - vfp_offset);
13318             }
13319           start_reg = FIRST_VFP_REGNUM;
13320           for (reg = FIRST_VFP_REGNUM; reg < LAST_VFP_REGNUM; reg += 2)
13321             {
13322               if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
13323                   && (!df_regs_ever_live_p (reg + 1) || call_used_regs[reg + 1]))
13324                 {
13325                   if (start_reg != reg)
13326                     vfp_output_fldmd (f, IP_REGNUM,
13327                                       (start_reg - FIRST_VFP_REGNUM) / 2,
13328                                       (reg - start_reg) / 2);
13329                   start_reg = reg + 2;
13330                 }
13331             }
13332           if (start_reg != reg)
13333             vfp_output_fldmd (f, IP_REGNUM,
13334                               (start_reg - FIRST_VFP_REGNUM) / 2,
13335                               (reg - start_reg) / 2);
13336         }
13337
13338       if (TARGET_IWMMXT)
13339         {
13340           /* The frame pointer is guaranteed to be non-double-word aligned.
13341              This is because it is set to (old_stack_pointer - 4) and the
13342              old_stack_pointer was double word aligned.  Thus the offset to
13343              the iWMMXt registers to be loaded must also be non-double-word
13344              sized, so that the resultant address *is* double-word aligned.
13345              We can ignore floats_offset since that was already included in
13346              the live_regs_mask.  */
13347           lrm_count += (lrm_count % 2 ? 2 : 1);
13348
13349           for (reg = LAST_IWMMXT_REGNUM; reg >= FIRST_IWMMXT_REGNUM; reg--)
13350             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13351               {
13352                 asm_fprintf (f, "\twldrd\t%r, [%r, #-%d]\n",
13353                              reg, FP_REGNUM, lrm_count * 4);
13354                 lrm_count += 2;
13355               }
13356         }
13357
13358       /* saved_regs_mask should contain the IP, which at the time of stack
13359          frame generation actually contains the old stack pointer.  So a
13360          quick way to unwind the stack is just pop the IP register directly
13361          into the stack pointer.  */
13362       gcc_assert (saved_regs_mask & (1 << IP_REGNUM));
13363       saved_regs_mask &= ~ (1 << IP_REGNUM);
13364       saved_regs_mask |=   (1 << SP_REGNUM);
13365
13366       /* There are two registers left in saved_regs_mask - LR and PC.  We
13367          only need to restore the LR register (the return address), but to
13368          save time we can load it directly into the PC, unless we need a
13369          special function exit sequence, or we are not really returning.  */
13370       if (really_return
13371           && ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL
13372           && !crtl->calls_eh_return)
13373         /* Delete the LR from the register mask, so that the LR on
13374            the stack is loaded into the PC in the register mask.  */
13375         saved_regs_mask &= ~ (1 << LR_REGNUM);
13376       else
13377         saved_regs_mask &= ~ (1 << PC_REGNUM);
13378
13379       /* We must use SP as the base register, because SP is one of the
13380          registers being restored.  If an interrupt or page fault
13381          happens in the ldm instruction, the SP might or might not
13382          have been restored.  That would be bad, as then SP will no
13383          longer indicate the safe area of stack, and we can get stack
13384          corruption.  Using SP as the base register means that it will
13385          be reset correctly to the original value, should an interrupt
13386          occur.  If the stack pointer already points at the right
13387          place, then omit the subtraction.  */
13388       if (offsets->outgoing_args != (1 + (int) bit_count (saved_regs_mask))
13389           || cfun->calls_alloca)
13390         asm_fprintf (f, "\tsub\t%r, %r, #%d\n", SP_REGNUM, FP_REGNUM,
13391                      4 * bit_count (saved_regs_mask));
13392       print_multi_reg (f, "ldmfd\t%r, ", SP_REGNUM, saved_regs_mask, 0);
13393
13394       if (IS_INTERRUPT (func_type))
13395         /* Interrupt handlers will have pushed the
13396            IP onto the stack, so restore it now.  */
13397         print_multi_reg (f, "ldmfd\t%r!, ", SP_REGNUM, 1 << IP_REGNUM, 0);
13398     }
13399   else
13400     {
13401       /* This branch is executed for ARM mode (non-apcs frames) and
13402          Thumb-2 mode. Frame layout is essentially the same for those
13403          cases, except that in ARM mode frame pointer points to the
13404          first saved register, while in Thumb-2 mode the frame pointer points
13405          to the last saved register.
13406
13407          It is possible to make frame pointer point to last saved
13408          register in both cases, and remove some conditionals below.
13409          That means that fp setup in prologue would be just "mov fp, sp"
13410          and sp restore in epilogue would be just "mov sp, fp", whereas
13411          now we have to use add/sub in those cases. However, the value
13412          of that would be marginal, as both mov and add/sub are 32-bit
13413          in ARM mode, and it would require extra conditionals
13414          in arm_expand_prologue to distingish ARM-apcs-frame case
13415          (where frame pointer is required to point at first register)
13416          and ARM-non-apcs-frame. Therefore, such change is postponed
13417          until real need arise.  */
13418       unsigned HOST_WIDE_INT amount;
13419       int rfe;
13420       /* Restore stack pointer if necessary.  */
13421       if (TARGET_ARM && frame_pointer_needed)
13422         {
13423           operands[0] = stack_pointer_rtx;
13424           operands[1] = hard_frame_pointer_rtx;
13425           
13426           operands[2] = GEN_INT (offsets->frame - offsets->saved_regs);
13427           output_add_immediate (operands);
13428         }
13429       else
13430         {
13431           if (frame_pointer_needed)
13432             {
13433               /* For Thumb-2 restore sp from the frame pointer.
13434                  Operand restrictions mean we have to incrememnt FP, then copy
13435                  to SP.  */
13436               amount = offsets->locals_base - offsets->saved_regs;
13437               operands[0] = hard_frame_pointer_rtx;
13438             }
13439           else
13440             {
13441               unsigned long count;
13442               operands[0] = stack_pointer_rtx;
13443               amount = offsets->outgoing_args - offsets->saved_regs;
13444               /* pop call clobbered registers if it avoids a
13445                  separate stack adjustment.  */
13446               count = offsets->saved_regs - offsets->saved_args;
13447               if (optimize_size
13448                   && count != 0
13449                   && !crtl->calls_eh_return
13450                   && bit_count(saved_regs_mask) * 4 == count
13451                   && !IS_INTERRUPT (func_type)
13452                   && !crtl->tail_call_emit)
13453                 {
13454                   unsigned long mask;
13455                   mask = (1 << (arm_size_return_regs() / 4)) - 1;
13456                   mask ^= 0xf;
13457                   mask &= ~saved_regs_mask;
13458                   reg = 0;
13459                   while (bit_count (mask) * 4 > amount)
13460                     {
13461                       while ((mask & (1 << reg)) == 0)
13462                         reg++;
13463                       mask &= ~(1 << reg);
13464                     }
13465                   if (bit_count (mask) * 4 == amount) {
13466                       amount = 0;
13467                       saved_regs_mask |= mask;
13468                   }
13469                 }
13470             }
13471           
13472           if (amount)
13473             {
13474               operands[1] = operands[0];
13475               operands[2] = GEN_INT (amount);
13476               output_add_immediate (operands);
13477             }
13478           if (frame_pointer_needed)
13479             asm_fprintf (f, "\tmov\t%r, %r\n",
13480                          SP_REGNUM, HARD_FRAME_POINTER_REGNUM);
13481         }
13482
13483       if (arm_fpu_arch == FPUTYPE_FPA_EMU2)
13484         {
13485           for (reg = FIRST_FPA_REGNUM; reg <= LAST_FPA_REGNUM; reg++)
13486             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13487               asm_fprintf (f, "\tldfe\t%r, [%r], #12\n",
13488                            reg, SP_REGNUM);
13489         }
13490       else
13491         {
13492           start_reg = FIRST_FPA_REGNUM;
13493
13494           for (reg = FIRST_FPA_REGNUM; reg <= LAST_FPA_REGNUM; reg++)
13495             {
13496               if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13497                 {
13498                   if (reg - start_reg == 3)
13499                     {
13500                       asm_fprintf (f, "\tlfmfd\t%r, 4, [%r]!\n",
13501                                    start_reg, SP_REGNUM);
13502                       start_reg = reg + 1;
13503                     }
13504                 }
13505               else
13506                 {
13507                   if (reg != start_reg)
13508                     asm_fprintf (f, "\tlfmfd\t%r, %d, [%r]!\n",
13509                                  start_reg, reg - start_reg,
13510                                  SP_REGNUM);
13511
13512                   start_reg = reg + 1;
13513                 }
13514             }
13515
13516           /* Just in case the last register checked also needs unstacking.  */
13517           if (reg != start_reg)
13518             asm_fprintf (f, "\tlfmfd\t%r, %d, [%r]!\n",
13519                          start_reg, reg - start_reg, SP_REGNUM);
13520         }
13521
13522       if (TARGET_HARD_FLOAT && TARGET_VFP)
13523         {
13524           start_reg = FIRST_VFP_REGNUM;
13525           for (reg = FIRST_VFP_REGNUM; reg < LAST_VFP_REGNUM; reg += 2)
13526             {
13527               if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
13528                   && (!df_regs_ever_live_p (reg + 1) || call_used_regs[reg + 1]))
13529                 {
13530                   if (start_reg != reg)
13531                     vfp_output_fldmd (f, SP_REGNUM,
13532                                       (start_reg - FIRST_VFP_REGNUM) / 2,
13533                                       (reg - start_reg) / 2);
13534                   start_reg = reg + 2;
13535                 }
13536             }
13537           if (start_reg != reg)
13538             vfp_output_fldmd (f, SP_REGNUM,
13539                               (start_reg - FIRST_VFP_REGNUM) / 2,
13540                               (reg - start_reg) / 2);
13541         }
13542       if (TARGET_IWMMXT)
13543         for (reg = FIRST_IWMMXT_REGNUM; reg <= LAST_IWMMXT_REGNUM; reg++)
13544           if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
13545             asm_fprintf (f, "\twldrd\t%r, [%r], #8\n", reg, SP_REGNUM);
13546
13547       /* If we can, restore the LR into the PC.  */
13548       if (ARM_FUNC_TYPE (func_type) != ARM_FT_INTERWORKED
13549           && (TARGET_ARM || ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL)
13550           && !IS_STACKALIGN (func_type)
13551           && really_return
13552           && crtl->args.pretend_args_size == 0
13553           && saved_regs_mask & (1 << LR_REGNUM)
13554           && !crtl->calls_eh_return)
13555         {
13556           saved_regs_mask &= ~ (1 << LR_REGNUM);
13557           saved_regs_mask |=   (1 << PC_REGNUM);
13558           rfe = IS_INTERRUPT (func_type);
13559         }
13560       else
13561         rfe = 0;
13562
13563       /* Load the registers off the stack.  If we only have one register
13564          to load use the LDR instruction - it is faster.  For Thumb-2
13565          always use pop and the assembler will pick the best instruction.*/
13566       if (TARGET_ARM && saved_regs_mask == (1 << LR_REGNUM)
13567           && !IS_INTERRUPT(func_type))
13568         {
13569           asm_fprintf (f, "\tldr\t%r, [%r], #4\n", LR_REGNUM, SP_REGNUM);
13570         }
13571       else if (saved_regs_mask)
13572         {
13573           if (saved_regs_mask & (1 << SP_REGNUM))
13574             /* Note - write back to the stack register is not enabled
13575                (i.e. "ldmfd sp!...").  We know that the stack pointer is
13576                in the list of registers and if we add writeback the
13577                instruction becomes UNPREDICTABLE.  */
13578             print_multi_reg (f, "ldmfd\t%r, ", SP_REGNUM, saved_regs_mask,
13579                              rfe);
13580           else if (TARGET_ARM)
13581             print_multi_reg (f, "ldmfd\t%r!, ", SP_REGNUM, saved_regs_mask,
13582                              rfe);
13583           else
13584             print_multi_reg (f, "pop\t", SP_REGNUM, saved_regs_mask, 0);
13585         }
13586
13587       if (crtl->args.pretend_args_size)
13588         {
13589           /* Unwind the pre-pushed regs.  */
13590           operands[0] = operands[1] = stack_pointer_rtx;
13591           operands[2] = GEN_INT (crtl->args.pretend_args_size);
13592           output_add_immediate (operands);
13593         }
13594     }
13595
13596   /* We may have already restored PC directly from the stack.  */
13597   if (!really_return || saved_regs_mask & (1 << PC_REGNUM))
13598     return "";
13599
13600   /* Stack adjustment for exception handler.  */
13601   if (crtl->calls_eh_return)
13602     asm_fprintf (f, "\tadd\t%r, %r, %r\n", SP_REGNUM, SP_REGNUM,
13603                  ARM_EH_STACKADJ_REGNUM);
13604
13605   /* Generate the return instruction.  */
13606   switch ((int) ARM_FUNC_TYPE (func_type))
13607     {
13608     case ARM_FT_ISR:
13609     case ARM_FT_FIQ:
13610       asm_fprintf (f, "\tsubs\t%r, %r, #4\n", PC_REGNUM, LR_REGNUM);
13611       break;
13612
13613     case ARM_FT_EXCEPTION:
13614       asm_fprintf (f, "\tmovs\t%r, %r\n", PC_REGNUM, LR_REGNUM);
13615       break;
13616
13617     case ARM_FT_INTERWORKED:
13618       asm_fprintf (f, "\tbx\t%r\n", LR_REGNUM);
13619       break;
13620
13621     default:
13622       if (IS_STACKALIGN (func_type))
13623         {
13624           /* See comment in arm_expand_prologue.  */
13625           asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, 0);
13626         }
13627       if (arm_arch5 || arm_arch4t)
13628         asm_fprintf (f, "\tbx\t%r\n", LR_REGNUM);
13629       else
13630         asm_fprintf (f, "\tmov\t%r, %r\n", PC_REGNUM, LR_REGNUM);
13631       break;
13632     }
13633
13634   return "";
13635 }
13636
13637 static void
13638 arm_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
13639                               HOST_WIDE_INT frame_size ATTRIBUTE_UNUSED)
13640 {
13641   arm_stack_offsets *offsets;
13642
13643   if (TARGET_THUMB1)
13644     {
13645       int regno;
13646
13647       /* Emit any call-via-reg trampolines that are needed for v4t support
13648          of call_reg and call_value_reg type insns.  */
13649       for (regno = 0; regno < LR_REGNUM; regno++)
13650         {
13651           rtx label = cfun->machine->call_via[regno];
13652
13653           if (label != NULL)
13654             {
13655               switch_to_section (function_section (current_function_decl));
13656               targetm.asm_out.internal_label (asm_out_file, "L",
13657                                               CODE_LABEL_NUMBER (label));
13658               asm_fprintf (asm_out_file, "\tbx\t%r\n", regno);
13659             }
13660         }
13661
13662       /* ??? Probably not safe to set this here, since it assumes that a
13663          function will be emitted as assembly immediately after we generate
13664          RTL for it.  This does not happen for inline functions.  */
13665       cfun->machine->return_used_this_function = 0;
13666     }
13667   else /* TARGET_32BIT */
13668     {
13669       /* We need to take into account any stack-frame rounding.  */
13670       offsets = arm_get_frame_offsets ();
13671
13672       gcc_assert (!use_return_insn (FALSE, NULL)
13673                   || (cfun->machine->return_used_this_function != 0)
13674                   || offsets->saved_regs == offsets->outgoing_args
13675                   || frame_pointer_needed);
13676
13677       /* Reset the ARM-specific per-function variables.  */
13678       after_arm_reorg = 0;
13679     }
13680 }
13681
13682 /* Generate and emit an insn that we will recognize as a push_multi.
13683    Unfortunately, since this insn does not reflect very well the actual
13684    semantics of the operation, we need to annotate the insn for the benefit
13685    of DWARF2 frame unwind information.  */
13686 static rtx
13687 emit_multi_reg_push (unsigned long mask)
13688 {
13689   int num_regs = 0;
13690   int num_dwarf_regs;
13691   int i, j;
13692   rtx par;
13693   rtx dwarf;
13694   int dwarf_par_index;
13695   rtx tmp, reg;
13696
13697   for (i = 0; i <= LAST_ARM_REGNUM; i++)
13698     if (mask & (1 << i))
13699       num_regs++;
13700
13701   gcc_assert (num_regs && num_regs <= 16);
13702
13703   /* We don't record the PC in the dwarf frame information.  */
13704   num_dwarf_regs = num_regs;
13705   if (mask & (1 << PC_REGNUM))
13706     num_dwarf_regs--;
13707
13708   /* For the body of the insn we are going to generate an UNSPEC in
13709      parallel with several USEs.  This allows the insn to be recognized
13710      by the push_multi pattern in the arm.md file.  The insn looks
13711      something like this:
13712
13713        (parallel [
13714            (set (mem:BLK (pre_dec:BLK (reg:SI sp)))
13715                 (unspec:BLK [(reg:SI r4)] UNSPEC_PUSH_MULT))
13716            (use (reg:SI 11 fp))
13717            (use (reg:SI 12 ip))
13718            (use (reg:SI 14 lr))
13719            (use (reg:SI 15 pc))
13720         ])
13721
13722      For the frame note however, we try to be more explicit and actually
13723      show each register being stored into the stack frame, plus a (single)
13724      decrement of the stack pointer.  We do it this way in order to be
13725      friendly to the stack unwinding code, which only wants to see a single
13726      stack decrement per instruction.  The RTL we generate for the note looks
13727      something like this:
13728
13729       (sequence [
13730            (set (reg:SI sp) (plus:SI (reg:SI sp) (const_int -20)))
13731            (set (mem:SI (reg:SI sp)) (reg:SI r4))
13732            (set (mem:SI (plus:SI (reg:SI sp) (const_int 4))) (reg:SI fp))
13733            (set (mem:SI (plus:SI (reg:SI sp) (const_int 8))) (reg:SI ip))
13734            (set (mem:SI (plus:SI (reg:SI sp) (const_int 12))) (reg:SI lr))
13735         ])
13736
13737       This sequence is used both by the code to support stack unwinding for
13738       exceptions handlers and the code to generate dwarf2 frame debugging.  */
13739
13740   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num_regs));
13741   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (num_dwarf_regs + 1));
13742   dwarf_par_index = 1;
13743
13744   for (i = 0; i <= LAST_ARM_REGNUM; i++)
13745     {
13746       if (mask & (1 << i))
13747         {
13748           reg = gen_rtx_REG (SImode, i);
13749
13750           XVECEXP (par, 0, 0)
13751             = gen_rtx_SET (VOIDmode,
13752                            gen_frame_mem (BLKmode,
13753                                           gen_rtx_PRE_DEC (BLKmode,
13754                                                            stack_pointer_rtx)),
13755                            gen_rtx_UNSPEC (BLKmode,
13756                                            gen_rtvec (1, reg),
13757                                            UNSPEC_PUSH_MULT));
13758
13759           if (i != PC_REGNUM)
13760             {
13761               tmp = gen_rtx_SET (VOIDmode,
13762                                  gen_frame_mem (SImode, stack_pointer_rtx),
13763                                  reg);
13764               RTX_FRAME_RELATED_P (tmp) = 1;
13765               XVECEXP (dwarf, 0, dwarf_par_index) = tmp;
13766               dwarf_par_index++;
13767             }
13768
13769           break;
13770         }
13771     }
13772
13773   for (j = 1, i++; j < num_regs; i++)
13774     {
13775       if (mask & (1 << i))
13776         {
13777           reg = gen_rtx_REG (SImode, i);
13778
13779           XVECEXP (par, 0, j) = gen_rtx_USE (VOIDmode, reg);
13780
13781           if (i != PC_REGNUM)
13782             {
13783               tmp
13784                 = gen_rtx_SET (VOIDmode,
13785                                gen_frame_mem (SImode,
13786                                               plus_constant (stack_pointer_rtx,
13787                                                              4 * j)),
13788                                reg);
13789               RTX_FRAME_RELATED_P (tmp) = 1;
13790               XVECEXP (dwarf, 0, dwarf_par_index++) = tmp;
13791             }
13792
13793           j++;
13794         }
13795     }
13796
13797   par = emit_insn (par);
13798
13799   tmp = gen_rtx_SET (VOIDmode,
13800                      stack_pointer_rtx,
13801                      plus_constant (stack_pointer_rtx, -4 * num_regs));
13802   RTX_FRAME_RELATED_P (tmp) = 1;
13803   XVECEXP (dwarf, 0, 0) = tmp;
13804
13805   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
13806
13807   return par;
13808 }
13809
13810 /* Calculate the size of the return value that is passed in registers.  */
13811 static unsigned
13812 arm_size_return_regs (void)
13813 {
13814   enum machine_mode mode;
13815
13816   if (crtl->return_rtx != 0)
13817     mode = GET_MODE (crtl->return_rtx);
13818   else
13819     mode = DECL_MODE (DECL_RESULT (current_function_decl));
13820
13821   return GET_MODE_SIZE (mode);
13822 }
13823
13824 static rtx
13825 emit_sfm (int base_reg, int count)
13826 {
13827   rtx par;
13828   rtx dwarf;
13829   rtx tmp, reg;
13830   int i;
13831
13832   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (count));
13833   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (count + 1));
13834
13835   reg = gen_rtx_REG (XFmode, base_reg++);
13836
13837   XVECEXP (par, 0, 0)
13838     = gen_rtx_SET (VOIDmode,
13839                    gen_frame_mem (BLKmode,
13840                                   gen_rtx_PRE_DEC (BLKmode,
13841                                                    stack_pointer_rtx)),
13842                    gen_rtx_UNSPEC (BLKmode,
13843                                    gen_rtvec (1, reg),
13844                                    UNSPEC_PUSH_MULT));
13845   tmp = gen_rtx_SET (VOIDmode,
13846                      gen_frame_mem (XFmode, stack_pointer_rtx), reg);
13847   RTX_FRAME_RELATED_P (tmp) = 1;
13848   XVECEXP (dwarf, 0, 1) = tmp;
13849
13850   for (i = 1; i < count; i++)
13851     {
13852       reg = gen_rtx_REG (XFmode, base_reg++);
13853       XVECEXP (par, 0, i) = gen_rtx_USE (VOIDmode, reg);
13854
13855       tmp = gen_rtx_SET (VOIDmode,
13856                          gen_frame_mem (XFmode,
13857                                         plus_constant (stack_pointer_rtx,
13858                                                        i * 12)),
13859                          reg);
13860       RTX_FRAME_RELATED_P (tmp) = 1;
13861       XVECEXP (dwarf, 0, i + 1) = tmp;
13862     }
13863
13864   tmp = gen_rtx_SET (VOIDmode,
13865                      stack_pointer_rtx,
13866                      plus_constant (stack_pointer_rtx, -12 * count));
13867
13868   RTX_FRAME_RELATED_P (tmp) = 1;
13869   XVECEXP (dwarf, 0, 0) = tmp;
13870
13871   par = emit_insn (par);
13872   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
13873
13874   return par;
13875 }
13876
13877
13878 /* Return true if the current function needs to save/restore LR.  */
13879
13880 static bool
13881 thumb_force_lr_save (void)
13882 {
13883   return !cfun->machine->lr_save_eliminated
13884          && (!leaf_function_p ()
13885              || thumb_far_jump_used_p ()
13886              || df_regs_ever_live_p (LR_REGNUM));
13887 }
13888
13889
13890 /* Compute the distance from register FROM to register TO.
13891    These can be the arg pointer (26), the soft frame pointer (25),
13892    the stack pointer (13) or the hard frame pointer (11).
13893    In thumb mode r7 is used as the soft frame pointer, if needed.
13894    Typical stack layout looks like this:
13895
13896        old stack pointer -> |    |
13897                              ----
13898                             |    | \
13899                             |    |   saved arguments for
13900                             |    |   vararg functions
13901                             |    | /
13902                               --
13903    hard FP & arg pointer -> |    | \
13904                             |    |   stack
13905                             |    |   frame
13906                             |    | /
13907                               --
13908                             |    | \
13909                             |    |   call saved
13910                             |    |   registers
13911       soft frame pointer -> |    | /
13912                               --
13913                             |    | \
13914                             |    |   local
13915                             |    |   variables
13916      locals base pointer -> |    | /
13917                               --
13918                             |    | \
13919                             |    |   outgoing
13920                             |    |   arguments
13921    current stack pointer -> |    | /
13922                               --
13923
13924   For a given function some or all of these stack components
13925   may not be needed, giving rise to the possibility of
13926   eliminating some of the registers.
13927
13928   The values returned by this function must reflect the behavior
13929   of arm_expand_prologue() and arm_compute_save_reg_mask().
13930
13931   The sign of the number returned reflects the direction of stack
13932   growth, so the values are positive for all eliminations except
13933   from the soft frame pointer to the hard frame pointer.
13934
13935   SFP may point just inside the local variables block to ensure correct
13936   alignment.  */
13937
13938
13939 /* Calculate stack offsets.  These are used to calculate register elimination
13940    offsets and in prologue/epilogue code.  Also calculates which registers
13941    should be saved.  */
13942
13943 static arm_stack_offsets *
13944 arm_get_frame_offsets (void)
13945 {
13946   struct arm_stack_offsets *offsets;
13947   unsigned long func_type;
13948   int leaf;
13949   int saved;
13950   int core_saved;
13951   HOST_WIDE_INT frame_size;
13952   int i;
13953
13954   offsets = &cfun->machine->stack_offsets;
13955
13956   /* We need to know if we are a leaf function.  Unfortunately, it
13957      is possible to be called after start_sequence has been called,
13958      which causes get_insns to return the insns for the sequence,
13959      not the function, which will cause leaf_function_p to return
13960      the incorrect result.
13961
13962      to know about leaf functions once reload has completed, and the
13963      frame size cannot be changed after that time, so we can safely
13964      use the cached value.  */
13965
13966   if (reload_completed)
13967     return offsets;
13968
13969   /* Initially this is the size of the local variables.  It will translated
13970      into an offset once we have determined the size of preceding data.  */
13971   frame_size = ROUND_UP_WORD (get_frame_size ());
13972
13973   leaf = leaf_function_p ();
13974
13975   /* Space for variadic functions.  */
13976   offsets->saved_args = crtl->args.pretend_args_size;
13977
13978   /* In Thumb mode this is incorrect, but never used.  */
13979   offsets->frame = offsets->saved_args + (frame_pointer_needed ? 4 : 0) +
13980                    arm_compute_static_chain_stack_bytes();
13981
13982   if (TARGET_32BIT)
13983     {
13984       unsigned int regno;
13985
13986       offsets->saved_regs_mask = arm_compute_save_reg_mask ();
13987       core_saved = bit_count (offsets->saved_regs_mask) * 4;
13988       saved = core_saved;
13989
13990       /* We know that SP will be doubleword aligned on entry, and we must
13991          preserve that condition at any subroutine call.  We also require the
13992          soft frame pointer to be doubleword aligned.  */
13993
13994       if (TARGET_REALLY_IWMMXT)
13995         {
13996           /* Check for the call-saved iWMMXt registers.  */
13997           for (regno = FIRST_IWMMXT_REGNUM;
13998                regno <= LAST_IWMMXT_REGNUM;
13999                regno++)
14000             if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
14001               saved += 8;
14002         }
14003
14004       func_type = arm_current_func_type ();
14005       if (! IS_VOLATILE (func_type))
14006         {
14007           /* Space for saved FPA registers.  */
14008           for (regno = FIRST_FPA_REGNUM; regno <= LAST_FPA_REGNUM; regno++)
14009             if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
14010             saved += 12;
14011
14012           /* Space for saved VFP registers.  */
14013           if (TARGET_HARD_FLOAT && TARGET_VFP)
14014             saved += arm_get_vfp_saved_size ();
14015         }
14016     }
14017   else /* TARGET_THUMB1 */
14018     {
14019       offsets->saved_regs_mask = thumb1_compute_save_reg_mask ();
14020       core_saved = bit_count (offsets->saved_regs_mask) * 4;
14021       saved = core_saved;
14022       if (TARGET_BACKTRACE)
14023         saved += 16;
14024     }
14025
14026   /* Saved registers include the stack frame.  */
14027   offsets->saved_regs = offsets->saved_args + saved +
14028                         arm_compute_static_chain_stack_bytes();
14029   offsets->soft_frame = offsets->saved_regs + CALLER_INTERWORKING_SLOT_SIZE;
14030   /* A leaf function does not need any stack alignment if it has nothing
14031      on the stack.  */
14032   if (leaf && frame_size == 0)
14033     {
14034       offsets->outgoing_args = offsets->soft_frame;
14035       offsets->locals_base = offsets->soft_frame;
14036       return offsets;
14037     }
14038
14039   /* Ensure SFP has the correct alignment.  */
14040   if (ARM_DOUBLEWORD_ALIGN
14041       && (offsets->soft_frame & 7))
14042     {
14043       offsets->soft_frame += 4;
14044       /* Try to align stack by pushing an extra reg.  Don't bother doing this
14045          when there is a stack frame as the alignment will be rolled into
14046          the normal stack adjustment.  */
14047       if (frame_size + crtl->outgoing_args_size == 0)
14048         {
14049           int reg = -1;
14050
14051           /* If it is safe to use r3, then do so.  This sometimes 
14052              generates better code on Thumb-2 by avoiding the need to
14053              use 32-bit push/pop instructions.  */
14054           if (!crtl->tail_call_emit
14055               && arm_size_return_regs () <= 12)
14056             {
14057               reg = 3;
14058             }
14059           else
14060             for (i = 4; i <= (TARGET_THUMB1 ? LAST_LO_REGNUM : 11); i++)
14061               {
14062                 if ((offsets->saved_regs_mask & (1 << i)) == 0)
14063                   {
14064                     reg = i;
14065                     break;
14066                   }
14067               }
14068
14069           if (reg != -1)
14070             {
14071               offsets->saved_regs += 4;
14072               offsets->saved_regs_mask |= (1 << reg);
14073             }
14074         }
14075     }
14076
14077   offsets->locals_base = offsets->soft_frame + frame_size;
14078   offsets->outgoing_args = (offsets->locals_base
14079                             + crtl->outgoing_args_size);
14080
14081   if (ARM_DOUBLEWORD_ALIGN)
14082     {
14083       /* Ensure SP remains doubleword aligned.  */
14084       if (offsets->outgoing_args & 7)
14085         offsets->outgoing_args += 4;
14086       gcc_assert (!(offsets->outgoing_args & 7));
14087     }
14088
14089   return offsets;
14090 }
14091
14092
14093 /* Calculate the relative offsets for the different stack pointers.  Positive
14094    offsets are in the direction of stack growth.  */
14095
14096 HOST_WIDE_INT
14097 arm_compute_initial_elimination_offset (unsigned int from, unsigned int to)
14098 {
14099   arm_stack_offsets *offsets;
14100
14101   offsets = arm_get_frame_offsets ();
14102
14103   /* OK, now we have enough information to compute the distances.
14104      There must be an entry in these switch tables for each pair
14105      of registers in ELIMINABLE_REGS, even if some of the entries
14106      seem to be redundant or useless.  */
14107   switch (from)
14108     {
14109     case ARG_POINTER_REGNUM:
14110       switch (to)
14111         {
14112         case THUMB_HARD_FRAME_POINTER_REGNUM:
14113           return 0;
14114
14115         case FRAME_POINTER_REGNUM:
14116           /* This is the reverse of the soft frame pointer
14117              to hard frame pointer elimination below.  */
14118           return offsets->soft_frame - offsets->saved_args;
14119
14120         case ARM_HARD_FRAME_POINTER_REGNUM:
14121           /* This is only non-zero in the case where the static chain register
14122              is stored above the frame.  */
14123           return offsets->frame - offsets->saved_args - 4;
14124
14125         case STACK_POINTER_REGNUM:
14126           /* If nothing has been pushed on the stack at all
14127              then this will return -4.  This *is* correct!  */
14128           return offsets->outgoing_args - (offsets->saved_args + 4);
14129
14130         default:
14131           gcc_unreachable ();
14132         }
14133       gcc_unreachable ();
14134
14135     case FRAME_POINTER_REGNUM:
14136       switch (to)
14137         {
14138         case THUMB_HARD_FRAME_POINTER_REGNUM:
14139           return 0;
14140
14141         case ARM_HARD_FRAME_POINTER_REGNUM:
14142           /* The hard frame pointer points to the top entry in the
14143              stack frame.  The soft frame pointer to the bottom entry
14144              in the stack frame.  If there is no stack frame at all,
14145              then they are identical.  */
14146
14147           return offsets->frame - offsets->soft_frame;
14148
14149         case STACK_POINTER_REGNUM:
14150           return offsets->outgoing_args - offsets->soft_frame;
14151
14152         default:
14153           gcc_unreachable ();
14154         }
14155       gcc_unreachable ();
14156
14157     default:
14158       /* You cannot eliminate from the stack pointer.
14159          In theory you could eliminate from the hard frame
14160          pointer to the stack pointer, but this will never
14161          happen, since if a stack frame is not needed the
14162          hard frame pointer will never be used.  */
14163       gcc_unreachable ();
14164     }
14165 }
14166
14167 /* Given FROM and TO register numbers, say whether this elimination is
14168    allowed.  Frame pointer elimination is automatically handled.
14169
14170    All eliminations are permissible.  Note that ARG_POINTER_REGNUM and
14171    HARD_FRAME_POINTER_REGNUM are in fact the same thing.  If we need a frame
14172    pointer, we must eliminate FRAME_POINTER_REGNUM into
14173    HARD_FRAME_POINTER_REGNUM and not into STACK_POINTER_REGNUM or
14174    ARG_POINTER_REGNUM.  */
14175
14176 bool
14177 arm_can_eliminate (const int from, const int to)
14178 {
14179   return ((to == FRAME_POINTER_REGNUM && from == ARG_POINTER_REGNUM) ? false :
14180           (to == STACK_POINTER_REGNUM && frame_pointer_needed) ? false :
14181           (to == ARM_HARD_FRAME_POINTER_REGNUM && TARGET_THUMB) ? false :
14182           (to == THUMB_HARD_FRAME_POINTER_REGNUM && TARGET_ARM) ? false :
14183            true);
14184 }
14185
14186 /* Emit RTL to save coprocessor registers on function entry.  Returns the
14187    number of bytes pushed.  */
14188
14189 static int
14190 arm_save_coproc_regs(void)
14191 {
14192   int saved_size = 0;
14193   unsigned reg;
14194   unsigned start_reg;
14195   rtx insn;
14196
14197   for (reg = LAST_IWMMXT_REGNUM; reg >= FIRST_IWMMXT_REGNUM; reg--)
14198     if (df_regs_ever_live_p (reg) && ! call_used_regs[reg])
14199       {
14200         insn = gen_rtx_PRE_DEC (V2SImode, stack_pointer_rtx);
14201         insn = gen_rtx_MEM (V2SImode, insn);
14202         insn = emit_set_insn (insn, gen_rtx_REG (V2SImode, reg));
14203         RTX_FRAME_RELATED_P (insn) = 1;
14204         saved_size += 8;
14205       }
14206
14207   /* Save any floating point call-saved registers used by this
14208      function.  */
14209   if (arm_fpu_arch == FPUTYPE_FPA_EMU2)
14210     {
14211       for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
14212         if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
14213           {
14214             insn = gen_rtx_PRE_DEC (XFmode, stack_pointer_rtx);
14215             insn = gen_rtx_MEM (XFmode, insn);
14216             insn = emit_set_insn (insn, gen_rtx_REG (XFmode, reg));
14217             RTX_FRAME_RELATED_P (insn) = 1;
14218             saved_size += 12;
14219           }
14220     }
14221   else
14222     {
14223       start_reg = LAST_FPA_REGNUM;
14224
14225       for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
14226         {
14227           if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
14228             {
14229               if (start_reg - reg == 3)
14230                 {
14231                   insn = emit_sfm (reg, 4);
14232                   RTX_FRAME_RELATED_P (insn) = 1;
14233                   saved_size += 48;
14234                   start_reg = reg - 1;
14235                 }
14236             }
14237           else
14238             {
14239               if (start_reg != reg)
14240                 {
14241                   insn = emit_sfm (reg + 1, start_reg - reg);
14242                   RTX_FRAME_RELATED_P (insn) = 1;
14243                   saved_size += (start_reg - reg) * 12;
14244                 }
14245               start_reg = reg - 1;
14246             }
14247         }
14248
14249       if (start_reg != reg)
14250         {
14251           insn = emit_sfm (reg + 1, start_reg - reg);
14252           saved_size += (start_reg - reg) * 12;
14253           RTX_FRAME_RELATED_P (insn) = 1;
14254         }
14255     }
14256   if (TARGET_HARD_FLOAT && TARGET_VFP)
14257     {
14258       start_reg = FIRST_VFP_REGNUM;
14259
14260       for (reg = FIRST_VFP_REGNUM; reg < LAST_VFP_REGNUM; reg += 2)
14261         {
14262           if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
14263               && (!df_regs_ever_live_p (reg + 1) || call_used_regs[reg + 1]))
14264             {
14265               if (start_reg != reg)
14266                 saved_size += vfp_emit_fstmd (start_reg,
14267                                               (reg - start_reg) / 2);
14268               start_reg = reg + 2;
14269             }
14270         }
14271       if (start_reg != reg)
14272         saved_size += vfp_emit_fstmd (start_reg,
14273                                       (reg - start_reg) / 2);
14274     }
14275   return saved_size;
14276 }
14277
14278
14279 /* Set the Thumb frame pointer from the stack pointer.  */
14280
14281 static void
14282 thumb_set_frame_pointer (arm_stack_offsets *offsets)
14283 {
14284   HOST_WIDE_INT amount;
14285   rtx insn, dwarf;
14286
14287   amount = offsets->outgoing_args - offsets->locals_base;
14288   if (amount < 1024)
14289     insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
14290                                   stack_pointer_rtx, GEN_INT (amount)));
14291   else
14292     {
14293       emit_insn (gen_movsi (hard_frame_pointer_rtx, GEN_INT (amount)));
14294       /* Thumb-2 RTL patterns expect sp as the first input.  Thumb-1
14295          expects the first two operands to be the same.  */
14296       if (TARGET_THUMB2)
14297         {
14298           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
14299                                         stack_pointer_rtx,
14300                                         hard_frame_pointer_rtx));
14301         }
14302       else
14303         {
14304           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
14305                                         hard_frame_pointer_rtx,
14306                                         stack_pointer_rtx));
14307         }
14308       dwarf = gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
14309                            plus_constant (stack_pointer_rtx, amount));
14310       RTX_FRAME_RELATED_P (dwarf) = 1;
14311       add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
14312     }
14313
14314   RTX_FRAME_RELATED_P (insn) = 1;
14315 }
14316
14317 /* Generate the prologue instructions for entry into an ARM or Thumb-2
14318    function.  */
14319 void
14320 arm_expand_prologue (void)
14321 {
14322   rtx amount;
14323   rtx insn;
14324   rtx ip_rtx;
14325   unsigned long live_regs_mask;
14326   unsigned long func_type;
14327   int fp_offset = 0;
14328   int saved_pretend_args = 0;
14329   int saved_regs = 0;
14330   unsigned HOST_WIDE_INT args_to_push;
14331   arm_stack_offsets *offsets;
14332
14333   func_type = arm_current_func_type ();
14334
14335   /* Naked functions don't have prologues.  */
14336   if (IS_NAKED (func_type))
14337     return;
14338
14339   /* Make a copy of c_f_p_a_s as we may need to modify it locally.  */
14340   args_to_push = crtl->args.pretend_args_size;
14341
14342   /* Compute which register we will have to save onto the stack.  */
14343   offsets = arm_get_frame_offsets ();
14344   live_regs_mask = offsets->saved_regs_mask;
14345
14346   ip_rtx = gen_rtx_REG (SImode, IP_REGNUM);
14347
14348   if (IS_STACKALIGN (func_type))
14349     {
14350       rtx dwarf;
14351       rtx r0;
14352       rtx r1;
14353       /* Handle a word-aligned stack pointer.  We generate the following:
14354
14355           mov r0, sp
14356           bic r1, r0, #7
14357           mov sp, r1
14358           <save and restore r0 in normal prologue/epilogue>
14359           mov sp, r0
14360           bx lr
14361
14362          The unwinder doesn't need to know about the stack realignment.
14363          Just tell it we saved SP in r0.  */
14364       gcc_assert (TARGET_THUMB2 && !arm_arch_notm && args_to_push == 0);
14365
14366       r0 = gen_rtx_REG (SImode, 0);
14367       r1 = gen_rtx_REG (SImode, 1);
14368       /* Use a real rtvec rather than NULL_RTVEC so the rest of the
14369          compiler won't choke.  */
14370       dwarf = gen_rtx_UNSPEC (SImode, rtvec_alloc (0), UNSPEC_STACK_ALIGN);
14371       dwarf = gen_rtx_SET (VOIDmode, r0, dwarf);
14372       insn = gen_movsi (r0, stack_pointer_rtx);
14373       RTX_FRAME_RELATED_P (insn) = 1;
14374       add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
14375       emit_insn (insn);
14376       emit_insn (gen_andsi3 (r1, r0, GEN_INT (~(HOST_WIDE_INT)7)));
14377       emit_insn (gen_movsi (stack_pointer_rtx, r1));
14378     }
14379
14380   /* For APCS frames, if IP register is clobbered
14381      when creating frame, save that register in a special
14382      way.  */
14383   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
14384     {
14385       if (IS_INTERRUPT (func_type))
14386         {
14387           /* Interrupt functions must not corrupt any registers.
14388              Creating a frame pointer however, corrupts the IP
14389              register, so we must push it first.  */
14390           insn = emit_multi_reg_push (1 << IP_REGNUM);
14391
14392           /* Do not set RTX_FRAME_RELATED_P on this insn.
14393              The dwarf stack unwinding code only wants to see one
14394              stack decrement per function, and this is not it.  If
14395              this instruction is labeled as being part of the frame
14396              creation sequence then dwarf2out_frame_debug_expr will
14397              die when it encounters the assignment of IP to FP
14398              later on, since the use of SP here establishes SP as
14399              the CFA register and not IP.
14400
14401              Anyway this instruction is not really part of the stack
14402              frame creation although it is part of the prologue.  */
14403         }
14404       else if (IS_NESTED (func_type))
14405         {
14406           /* The Static chain register is the same as the IP register
14407              used as a scratch register during stack frame creation.
14408              To get around this need to find somewhere to store IP
14409              whilst the frame is being created.  We try the following
14410              places in order:
14411
14412                1. The last argument register.
14413                2. A slot on the stack above the frame.  (This only
14414                   works if the function is not a varargs function).
14415                3. Register r3, after pushing the argument registers
14416                   onto the stack.
14417
14418              Note - we only need to tell the dwarf2 backend about the SP
14419              adjustment in the second variant; the static chain register
14420              doesn't need to be unwound, as it doesn't contain a value
14421              inherited from the caller.  */
14422
14423           if (df_regs_ever_live_p (3) == false)
14424             insn = emit_set_insn (gen_rtx_REG (SImode, 3), ip_rtx);
14425           else if (args_to_push == 0)
14426             {
14427               rtx dwarf;
14428
14429               gcc_assert(arm_compute_static_chain_stack_bytes() == 4);
14430               saved_regs += 4;
14431
14432               insn = gen_rtx_PRE_DEC (SImode, stack_pointer_rtx);
14433               insn = emit_set_insn (gen_frame_mem (SImode, insn), ip_rtx);
14434               fp_offset = 4;
14435
14436               /* Just tell the dwarf backend that we adjusted SP.  */
14437               dwarf = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
14438                                    plus_constant (stack_pointer_rtx,
14439                                                   -fp_offset));
14440               RTX_FRAME_RELATED_P (insn) = 1;
14441               add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
14442             }
14443           else
14444             {
14445               /* Store the args on the stack.  */
14446               if (cfun->machine->uses_anonymous_args)
14447                 insn = emit_multi_reg_push
14448                   ((0xf0 >> (args_to_push / 4)) & 0xf);
14449               else
14450                 insn = emit_insn
14451                   (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
14452                                GEN_INT (- args_to_push)));
14453
14454               RTX_FRAME_RELATED_P (insn) = 1;
14455
14456               saved_pretend_args = 1;
14457               fp_offset = args_to_push;
14458               args_to_push = 0;
14459
14460               /* Now reuse r3 to preserve IP.  */
14461               emit_set_insn (gen_rtx_REG (SImode, 3), ip_rtx);
14462             }
14463         }
14464
14465       insn = emit_set_insn (ip_rtx,
14466                             plus_constant (stack_pointer_rtx, fp_offset));
14467       RTX_FRAME_RELATED_P (insn) = 1;
14468     }
14469
14470   if (args_to_push)
14471     {
14472       /* Push the argument registers, or reserve space for them.  */
14473       if (cfun->machine->uses_anonymous_args)
14474         insn = emit_multi_reg_push
14475           ((0xf0 >> (args_to_push / 4)) & 0xf);
14476       else
14477         insn = emit_insn
14478           (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
14479                        GEN_INT (- args_to_push)));
14480       RTX_FRAME_RELATED_P (insn) = 1;
14481     }
14482
14483   /* If this is an interrupt service routine, and the link register
14484      is going to be pushed, and we're not generating extra
14485      push of IP (needed when frame is needed and frame layout if apcs),
14486      subtracting four from LR now will mean that the function return
14487      can be done with a single instruction.  */
14488   if ((func_type == ARM_FT_ISR || func_type == ARM_FT_FIQ)
14489       && (live_regs_mask & (1 << LR_REGNUM)) != 0
14490       && !(frame_pointer_needed && TARGET_APCS_FRAME)
14491       && TARGET_ARM)
14492     {
14493       rtx lr = gen_rtx_REG (SImode, LR_REGNUM);
14494       
14495       emit_set_insn (lr, plus_constant (lr, -4));
14496     }
14497
14498   if (live_regs_mask)
14499     {
14500       saved_regs += bit_count (live_regs_mask) * 4;
14501       if (optimize_size && !frame_pointer_needed
14502           && saved_regs == offsets->saved_regs - offsets->saved_args)
14503         {
14504           /* If no coprocessor registers are being pushed and we don't have
14505              to worry about a frame pointer then push extra registers to
14506              create the stack frame.  This is done is a way that does not
14507              alter the frame layout, so is independent of the epilogue.  */
14508           int n;
14509           int frame;
14510           n = 0;
14511           while (n < 8 && (live_regs_mask & (1 << n)) == 0)
14512             n++;
14513           frame = offsets->outgoing_args - (offsets->saved_args + saved_regs);
14514           if (frame && n * 4 >= frame)
14515             {
14516               n = frame / 4;
14517               live_regs_mask |= (1 << n) - 1;
14518               saved_regs += frame;
14519             }
14520         }
14521       insn = emit_multi_reg_push (live_regs_mask);
14522       RTX_FRAME_RELATED_P (insn) = 1;
14523     }
14524
14525   if (! IS_VOLATILE (func_type))
14526     saved_regs += arm_save_coproc_regs ();
14527
14528   if (frame_pointer_needed && TARGET_ARM)
14529     {
14530       /* Create the new frame pointer.  */
14531       if (TARGET_APCS_FRAME)
14532         {
14533           insn = GEN_INT (-(4 + args_to_push + fp_offset));
14534           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx, ip_rtx, insn));
14535           RTX_FRAME_RELATED_P (insn) = 1;
14536
14537           if (IS_NESTED (func_type))
14538             {
14539               /* Recover the static chain register.  */
14540               if (!df_regs_ever_live_p (3)
14541                   || saved_pretend_args)
14542                 insn = gen_rtx_REG (SImode, 3);
14543               else /* if (crtl->args.pretend_args_size == 0) */
14544                 {
14545                   insn = plus_constant (hard_frame_pointer_rtx, 4);
14546                   insn = gen_frame_mem (SImode, insn);
14547                 }
14548               emit_set_insn (ip_rtx, insn);
14549               /* Add a USE to stop propagate_one_insn() from barfing.  */
14550               emit_insn (gen_prologue_use (ip_rtx));
14551             }
14552         }
14553       else
14554         {
14555           insn = GEN_INT (saved_regs - 4);
14556           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
14557                                         stack_pointer_rtx, insn));
14558           RTX_FRAME_RELATED_P (insn) = 1;
14559         }
14560     }
14561
14562   if (offsets->outgoing_args != offsets->saved_args + saved_regs)
14563     {
14564       /* This add can produce multiple insns for a large constant, so we
14565          need to get tricky.  */
14566       rtx last = get_last_insn ();
14567
14568       amount = GEN_INT (offsets->saved_args + saved_regs
14569                         - offsets->outgoing_args);
14570
14571       insn = emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
14572                                     amount));
14573       do
14574         {
14575           last = last ? NEXT_INSN (last) : get_insns ();
14576           RTX_FRAME_RELATED_P (last) = 1;
14577         }
14578       while (last != insn);
14579
14580       /* If the frame pointer is needed, emit a special barrier that
14581          will prevent the scheduler from moving stores to the frame
14582          before the stack adjustment.  */
14583       if (frame_pointer_needed)
14584         insn = emit_insn (gen_stack_tie (stack_pointer_rtx,
14585                                          hard_frame_pointer_rtx));
14586     }
14587
14588
14589   if (frame_pointer_needed && TARGET_THUMB2)
14590     thumb_set_frame_pointer (offsets);
14591
14592   if (flag_pic && arm_pic_register != INVALID_REGNUM)
14593     {
14594       unsigned long mask;
14595
14596       mask = live_regs_mask;
14597       mask &= THUMB2_WORK_REGS;
14598       if (!IS_NESTED (func_type))
14599         mask |= (1 << IP_REGNUM);
14600       arm_load_pic_register (mask);
14601     }
14602
14603   /* If we are profiling, make sure no instructions are scheduled before
14604      the call to mcount.  Similarly if the user has requested no
14605      scheduling in the prolog.  Similarly if we want non-call exceptions
14606      using the EABI unwinder, to prevent faulting instructions from being
14607      swapped with a stack adjustment.  */
14608   if (crtl->profile || !TARGET_SCHED_PROLOG
14609       || (ARM_EABI_UNWIND_TABLES && flag_non_call_exceptions))
14610     emit_insn (gen_blockage ());
14611
14612   /* If the link register is being kept alive, with the return address in it,
14613      then make sure that it does not get reused by the ce2 pass.  */
14614   if ((live_regs_mask & (1 << LR_REGNUM)) == 0)
14615     cfun->machine->lr_save_eliminated = 1;
14616 }
14617 \f
14618 /* Print condition code to STREAM.  Helper function for arm_print_operand.  */
14619 static void
14620 arm_print_condition (FILE *stream)
14621 {
14622   if (arm_ccfsm_state == 3 || arm_ccfsm_state == 4)
14623     {
14624       /* Branch conversion is not implemented for Thumb-2.  */
14625       if (TARGET_THUMB)
14626         {
14627           output_operand_lossage ("predicated Thumb instruction");
14628           return;
14629         }
14630       if (current_insn_predicate != NULL)
14631         {
14632           output_operand_lossage
14633             ("predicated instruction in conditional sequence");
14634           return;
14635         }
14636
14637       fputs (arm_condition_codes[arm_current_cc], stream);
14638     }
14639   else if (current_insn_predicate)
14640     {
14641       enum arm_cond_code code;
14642
14643       if (TARGET_THUMB1)
14644         {
14645           output_operand_lossage ("predicated Thumb instruction");
14646           return;
14647         }
14648
14649       code = get_arm_condition_code (current_insn_predicate);
14650       fputs (arm_condition_codes[code], stream);
14651     }
14652 }
14653
14654
14655 /* If CODE is 'd', then the X is a condition operand and the instruction
14656    should only be executed if the condition is true.
14657    if CODE is 'D', then the X is a condition operand and the instruction
14658    should only be executed if the condition is false: however, if the mode
14659    of the comparison is CCFPEmode, then always execute the instruction -- we
14660    do this because in these circumstances !GE does not necessarily imply LT;
14661    in these cases the instruction pattern will take care to make sure that
14662    an instruction containing %d will follow, thereby undoing the effects of
14663    doing this instruction unconditionally.
14664    If CODE is 'N' then X is a floating point operand that must be negated
14665    before output.
14666    If CODE is 'B' then output a bitwise inverted value of X (a const int).
14667    If X is a REG and CODE is `M', output a ldm/stm style multi-reg.  */
14668 void
14669 arm_print_operand (FILE *stream, rtx x, int code)
14670 {
14671   switch (code)
14672     {
14673     case '@':
14674       fputs (ASM_COMMENT_START, stream);
14675       return;
14676
14677     case '_':
14678       fputs (user_label_prefix, stream);
14679       return;
14680
14681     case '|':
14682       fputs (REGISTER_PREFIX, stream);
14683       return;
14684
14685     case '?':
14686       arm_print_condition (stream);
14687       return;
14688
14689     case '(':
14690       /* Nothing in unified syntax, otherwise the current condition code.  */
14691       if (!TARGET_UNIFIED_ASM)
14692         arm_print_condition (stream);
14693       break;
14694
14695     case ')':
14696       /* The current condition code in unified syntax, otherwise nothing.  */
14697       if (TARGET_UNIFIED_ASM)
14698         arm_print_condition (stream);
14699       break;
14700   
14701     case '.':
14702       /* The current condition code for a condition code setting instruction.
14703          Preceded by 's' in unified syntax, otherwise followed by 's'.  */
14704       if (TARGET_UNIFIED_ASM)
14705         {
14706           fputc('s', stream);
14707           arm_print_condition (stream);
14708         }
14709       else
14710         {
14711           arm_print_condition (stream);
14712           fputc('s', stream);
14713         }
14714       return;
14715
14716     case '!':
14717       /* If the instruction is conditionally executed then print
14718          the current condition code, otherwise print 's'.  */
14719       gcc_assert (TARGET_THUMB2 && TARGET_UNIFIED_ASM);
14720       if (current_insn_predicate)
14721         arm_print_condition (stream);
14722       else
14723         fputc('s', stream);
14724       break;
14725
14726     /* %# is a "break" sequence. It doesn't output anything, but is used to
14727        separate e.g. operand numbers from following text, if that text consists
14728        of further digits which we don't want to be part of the operand
14729        number.  */
14730     case '#':
14731       return;
14732
14733     case 'N':
14734       {
14735         REAL_VALUE_TYPE r;
14736         REAL_VALUE_FROM_CONST_DOUBLE (r, x);
14737         r = REAL_VALUE_NEGATE (r);
14738         fprintf (stream, "%s", fp_const_from_val (&r));
14739       }
14740       return;
14741
14742     /* An integer or symbol address without a preceding # sign.  */
14743     case 'c':
14744       switch (GET_CODE (x))
14745         {
14746         case CONST_INT:
14747           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (x));
14748           break;
14749
14750         case SYMBOL_REF:
14751           output_addr_const (stream, x);
14752           break;
14753
14754         default:
14755           gcc_unreachable ();
14756         }
14757       return;
14758
14759     case 'B':
14760       if (GET_CODE (x) == CONST_INT)
14761         {
14762           HOST_WIDE_INT val;
14763           val = ARM_SIGN_EXTEND (~INTVAL (x));
14764           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, val);
14765         }
14766       else
14767         {
14768           putc ('~', stream);
14769           output_addr_const (stream, x);
14770         }
14771       return;
14772
14773     case 'L':
14774       /* The low 16 bits of an immediate constant.  */
14775       fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL(x) & 0xffff);
14776       return;
14777
14778     case 'i':
14779       fprintf (stream, "%s", arithmetic_instr (x, 1));
14780       return;
14781
14782     /* Truncate Cirrus shift counts.  */
14783     case 's':
14784       if (GET_CODE (x) == CONST_INT)
14785         {
14786           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 0x3f);
14787           return;
14788         }
14789       arm_print_operand (stream, x, 0);
14790       return;
14791
14792     case 'I':
14793       fprintf (stream, "%s", arithmetic_instr (x, 0));
14794       return;
14795
14796     case 'S':
14797       {
14798         HOST_WIDE_INT val;
14799         const char *shift;
14800
14801         if (!shift_operator (x, SImode))
14802           {
14803             output_operand_lossage ("invalid shift operand");
14804             break;
14805           }
14806
14807         shift = shift_op (x, &val);
14808
14809         if (shift)
14810           {
14811             fprintf (stream, ", %s ", shift);
14812             if (val == -1)
14813               arm_print_operand (stream, XEXP (x, 1), 0);
14814             else
14815               fprintf (stream, "#" HOST_WIDE_INT_PRINT_DEC, val);
14816           }
14817       }
14818       return;
14819
14820       /* An explanation of the 'Q', 'R' and 'H' register operands:
14821
14822          In a pair of registers containing a DI or DF value the 'Q'
14823          operand returns the register number of the register containing
14824          the least significant part of the value.  The 'R' operand returns
14825          the register number of the register containing the most
14826          significant part of the value.
14827
14828          The 'H' operand returns the higher of the two register numbers.
14829          On a run where WORDS_BIG_ENDIAN is true the 'H' operand is the
14830          same as the 'Q' operand, since the most significant part of the
14831          value is held in the lower number register.  The reverse is true
14832          on systems where WORDS_BIG_ENDIAN is false.
14833
14834          The purpose of these operands is to distinguish between cases
14835          where the endian-ness of the values is important (for example
14836          when they are added together), and cases where the endian-ness
14837          is irrelevant, but the order of register operations is important.
14838          For example when loading a value from memory into a register
14839          pair, the endian-ness does not matter.  Provided that the value
14840          from the lower memory address is put into the lower numbered
14841          register, and the value from the higher address is put into the
14842          higher numbered register, the load will work regardless of whether
14843          the value being loaded is big-wordian or little-wordian.  The
14844          order of the two register loads can matter however, if the address
14845          of the memory location is actually held in one of the registers
14846          being overwritten by the load.  */
14847     case 'Q':
14848       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
14849         {
14850           output_operand_lossage ("invalid operand for code '%c'", code);
14851           return;
14852         }
14853
14854       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 1 : 0));
14855       return;
14856
14857     case 'R':
14858       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
14859         {
14860           output_operand_lossage ("invalid operand for code '%c'", code);
14861           return;
14862         }
14863
14864       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 0 : 1));
14865       return;
14866
14867     case 'H':
14868       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
14869         {
14870           output_operand_lossage ("invalid operand for code '%c'", code);
14871           return;
14872         }
14873
14874       asm_fprintf (stream, "%r", REGNO (x) + 1);
14875       return;
14876
14877     case 'J':
14878       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
14879         {
14880           output_operand_lossage ("invalid operand for code '%c'", code);
14881           return;
14882         }
14883
14884       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 3 : 2));
14885       return;
14886
14887     case 'K':
14888       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
14889         {
14890           output_operand_lossage ("invalid operand for code '%c'", code);
14891           return;
14892         }
14893
14894       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 2 : 3));
14895       return;
14896
14897     case 'm':
14898       asm_fprintf (stream, "%r",
14899                    GET_CODE (XEXP (x, 0)) == REG
14900                    ? REGNO (XEXP (x, 0)) : REGNO (XEXP (XEXP (x, 0), 0)));
14901       return;
14902
14903     case 'M':
14904       asm_fprintf (stream, "{%r-%r}",
14905                    REGNO (x),
14906                    REGNO (x) + ARM_NUM_REGS (GET_MODE (x)) - 1);
14907       return;
14908
14909     /* Like 'M', but writing doubleword vector registers, for use by Neon
14910        insns.  */
14911     case 'h':
14912       {
14913         int regno = (REGNO (x) - FIRST_VFP_REGNUM) / 2;
14914         int numregs = ARM_NUM_REGS (GET_MODE (x)) / 2;
14915         if (numregs == 1)
14916           asm_fprintf (stream, "{d%d}", regno);
14917         else
14918           asm_fprintf (stream, "{d%d-d%d}", regno, regno + numregs - 1);
14919       }
14920       return;
14921
14922     case 'd':
14923       /* CONST_TRUE_RTX means always -- that's the default.  */
14924       if (x == const_true_rtx)
14925         return;
14926
14927       if (!COMPARISON_P (x))
14928         {
14929           output_operand_lossage ("invalid operand for code '%c'", code);
14930           return;
14931         }
14932
14933       fputs (arm_condition_codes[get_arm_condition_code (x)],
14934              stream);
14935       return;
14936
14937     case 'D':
14938       /* CONST_TRUE_RTX means not always -- i.e. never.  We shouldn't ever
14939          want to do that.  */
14940       if (x == const_true_rtx)
14941         {
14942           output_operand_lossage ("instruction never executed");
14943           return;
14944         }
14945       if (!COMPARISON_P (x))
14946         {
14947           output_operand_lossage ("invalid operand for code '%c'", code);
14948           return;
14949         }
14950
14951       fputs (arm_condition_codes[ARM_INVERSE_CONDITION_CODE
14952                                  (get_arm_condition_code (x))],
14953              stream);
14954       return;
14955
14956     /* Cirrus registers can be accessed in a variety of ways:
14957          single floating point (f)
14958          double floating point (d)
14959          32bit integer         (fx)
14960          64bit integer         (dx).  */
14961     case 'W':                   /* Cirrus register in F mode.  */
14962     case 'X':                   /* Cirrus register in D mode.  */
14963     case 'Y':                   /* Cirrus register in FX mode.  */
14964     case 'Z':                   /* Cirrus register in DX mode.  */
14965       gcc_assert (GET_CODE (x) == REG
14966                   && REGNO_REG_CLASS (REGNO (x)) == CIRRUS_REGS);
14967
14968       fprintf (stream, "mv%s%s",
14969                code == 'W' ? "f"
14970                : code == 'X' ? "d"
14971                : code == 'Y' ? "fx" : "dx", reg_names[REGNO (x)] + 2);
14972
14973       return;
14974
14975     /* Print cirrus register in the mode specified by the register's mode.  */
14976     case 'V':
14977       {
14978         int mode = GET_MODE (x);
14979
14980         if (GET_CODE (x) != REG || REGNO_REG_CLASS (REGNO (x)) != CIRRUS_REGS)
14981           {
14982             output_operand_lossage ("invalid operand for code '%c'", code);
14983             return;
14984           }
14985
14986         fprintf (stream, "mv%s%s",
14987                  mode == DFmode ? "d"
14988                  : mode == SImode ? "fx"
14989                  : mode == DImode ? "dx"
14990                  : "f", reg_names[REGNO (x)] + 2);
14991
14992         return;
14993       }
14994
14995     case 'U':
14996       if (GET_CODE (x) != REG
14997           || REGNO (x) < FIRST_IWMMXT_GR_REGNUM
14998           || REGNO (x) > LAST_IWMMXT_GR_REGNUM)
14999         /* Bad value for wCG register number.  */
15000         {
15001           output_operand_lossage ("invalid operand for code '%c'", code);
15002           return;
15003         }
15004
15005       else
15006         fprintf (stream, "%d", REGNO (x) - FIRST_IWMMXT_GR_REGNUM);
15007       return;
15008
15009       /* Print an iWMMXt control register name.  */
15010     case 'w':
15011       if (GET_CODE (x) != CONST_INT
15012           || INTVAL (x) < 0
15013           || INTVAL (x) >= 16)
15014         /* Bad value for wC register number.  */
15015         {
15016           output_operand_lossage ("invalid operand for code '%c'", code);
15017           return;
15018         }
15019
15020       else
15021         {
15022           static const char * wc_reg_names [16] =
15023             {
15024               "wCID",  "wCon",  "wCSSF", "wCASF",
15025               "wC4",   "wC5",   "wC6",   "wC7",
15026               "wCGR0", "wCGR1", "wCGR2", "wCGR3",
15027               "wC12",  "wC13",  "wC14",  "wC15"
15028             };
15029
15030           fprintf (stream, wc_reg_names [INTVAL (x)]);
15031         }
15032       return;
15033
15034     /* Print a VFP/Neon double precision or quad precision register name.  */
15035     case 'P':
15036     case 'q':
15037       {
15038         int mode = GET_MODE (x);
15039         int is_quad = (code == 'q');
15040         int regno;
15041
15042         if (GET_MODE_SIZE (mode) != (is_quad ? 16 : 8))
15043           {
15044             output_operand_lossage ("invalid operand for code '%c'", code);
15045             return;
15046           }
15047
15048         if (GET_CODE (x) != REG
15049             || !IS_VFP_REGNUM (REGNO (x)))
15050           {
15051             output_operand_lossage ("invalid operand for code '%c'", code);
15052             return;
15053           }
15054
15055         regno = REGNO (x);
15056         if ((is_quad && !NEON_REGNO_OK_FOR_QUAD (regno))
15057             || (!is_quad && !VFP_REGNO_OK_FOR_DOUBLE (regno)))
15058           {
15059             output_operand_lossage ("invalid operand for code '%c'", code);
15060             return;
15061           }
15062
15063         fprintf (stream, "%c%d", is_quad ? 'q' : 'd',
15064           (regno - FIRST_VFP_REGNUM) >> (is_quad ? 2 : 1));
15065       }
15066       return;
15067
15068     /* These two codes print the low/high doubleword register of a Neon quad
15069        register, respectively.  For pair-structure types, can also print
15070        low/high quadword registers.  */
15071     case 'e':
15072     case 'f':
15073       {
15074         int mode = GET_MODE (x);
15075         int regno;
15076
15077         if ((GET_MODE_SIZE (mode) != 16
15078              && GET_MODE_SIZE (mode) != 32) || GET_CODE (x) != REG)
15079           {
15080             output_operand_lossage ("invalid operand for code '%c'", code);
15081             return;
15082           }
15083
15084         regno = REGNO (x);
15085         if (!NEON_REGNO_OK_FOR_QUAD (regno))
15086           {
15087             output_operand_lossage ("invalid operand for code '%c'", code);
15088             return;
15089           }
15090
15091         if (GET_MODE_SIZE (mode) == 16)
15092           fprintf (stream, "d%d", ((regno - FIRST_VFP_REGNUM) >> 1)
15093                                   + (code == 'f' ? 1 : 0));
15094         else
15095           fprintf (stream, "q%d", ((regno - FIRST_VFP_REGNUM) >> 2)
15096                                   + (code == 'f' ? 1 : 0));
15097       }
15098       return;
15099
15100     /* Print a VFPv3 floating-point constant, represented as an integer
15101        index.  */
15102     case 'G':
15103       {
15104         int index = vfp3_const_double_index (x);
15105         gcc_assert (index != -1);
15106         fprintf (stream, "%d", index);
15107       }
15108       return;
15109
15110     /* Print bits representing opcode features for Neon.
15111
15112        Bit 0 is 1 for signed, 0 for unsigned.  Floats count as signed
15113        and polynomials as unsigned.
15114
15115        Bit 1 is 1 for floats and polynomials, 0 for ordinary integers.
15116
15117        Bit 2 is 1 for rounding functions, 0 otherwise.  */
15118
15119     /* Identify the type as 's', 'u', 'p' or 'f'.  */
15120     case 'T':
15121       {
15122         HOST_WIDE_INT bits = INTVAL (x);
15123         fputc ("uspf"[bits & 3], stream);
15124       }
15125       return;
15126
15127     /* Likewise, but signed and unsigned integers are both 'i'.  */
15128     case 'F':
15129       {
15130         HOST_WIDE_INT bits = INTVAL (x);
15131         fputc ("iipf"[bits & 3], stream);
15132       }
15133       return;
15134
15135     /* As for 'T', but emit 'u' instead of 'p'.  */
15136     case 't':
15137       {
15138         HOST_WIDE_INT bits = INTVAL (x);
15139         fputc ("usuf"[bits & 3], stream);
15140       }
15141       return;
15142
15143     /* Bit 2: rounding (vs none).  */
15144     case 'O':
15145       {
15146         HOST_WIDE_INT bits = INTVAL (x);
15147         fputs ((bits & 4) != 0 ? "r" : "", stream);
15148       }
15149       return;
15150
15151     /* Memory operand for vld1/vst1 instruction.  */
15152     case 'A':
15153       {
15154         rtx addr;
15155         bool postinc = FALSE;
15156         gcc_assert (GET_CODE (x) == MEM);
15157         addr = XEXP (x, 0);
15158         if (GET_CODE (addr) == POST_INC)
15159           {
15160             postinc = 1;
15161             addr = XEXP (addr, 0);
15162           }
15163         asm_fprintf (stream, "[%r]", REGNO (addr));
15164         if (postinc)
15165           fputs("!", stream);
15166       }
15167       return;
15168
15169     /* Register specifier for vld1.16/vst1.16.  Translate the S register
15170        number into a D register number and element index.  */
15171     case 'z':
15172       {
15173         int mode = GET_MODE (x);
15174         int regno;
15175
15176         if (GET_MODE_SIZE (mode) != 2 || GET_CODE (x) != REG)
15177           {
15178             output_operand_lossage ("invalid operand for code '%c'", code);
15179             return;
15180           }
15181
15182         regno = REGNO (x);
15183         if (!VFP_REGNO_OK_FOR_SINGLE (regno))
15184           {
15185             output_operand_lossage ("invalid operand for code '%c'", code);
15186             return;
15187           }
15188
15189         regno = regno - FIRST_VFP_REGNUM;
15190         fprintf (stream, "d%d[%d]", regno/2, ((regno % 2) ? 2 : 0));
15191       }
15192       return;
15193       
15194     default:
15195       if (x == 0)
15196         {
15197           output_operand_lossage ("missing operand");
15198           return;
15199         }
15200
15201       switch (GET_CODE (x))
15202         {
15203         case REG:
15204           asm_fprintf (stream, "%r", REGNO (x));
15205           break;
15206
15207         case MEM:
15208           output_memory_reference_mode = GET_MODE (x);
15209           output_address (XEXP (x, 0));
15210           break;
15211
15212         case CONST_DOUBLE:
15213           if (TARGET_NEON)
15214             {
15215               char fpstr[20];
15216               real_to_decimal (fpstr, CONST_DOUBLE_REAL_VALUE (x),
15217                                sizeof (fpstr), 0, 1);
15218               fprintf (stream, "#%s", fpstr);
15219             }
15220           else
15221             fprintf (stream, "#%s", fp_immediate_constant (x));
15222           break;
15223
15224         default:
15225           gcc_assert (GET_CODE (x) != NEG);
15226           fputc ('#', stream);
15227           if (GET_CODE (x) == HIGH)
15228             {
15229               fputs (":lower16:", stream);
15230               x = XEXP (x, 0);
15231             }
15232             
15233           output_addr_const (stream, x);
15234           break;
15235         }
15236     }
15237 }
15238 \f
15239 /* Target hook for assembling integer objects.  The ARM version needs to
15240    handle word-sized values specially.  */
15241 static bool
15242 arm_assemble_integer (rtx x, unsigned int size, int aligned_p)
15243 {
15244   enum machine_mode mode;
15245
15246   if (size == UNITS_PER_WORD && aligned_p)
15247     {
15248       fputs ("\t.word\t", asm_out_file);
15249       output_addr_const (asm_out_file, x);
15250
15251       /* Mark symbols as position independent.  We only do this in the
15252          .text segment, not in the .data segment.  */
15253       if (NEED_GOT_RELOC && flag_pic && making_const_table &&
15254           (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF))
15255         {
15256           /* See legitimize_pic_address for an explanation of the
15257              TARGET_VXWORKS_RTP check.  */
15258           if (TARGET_VXWORKS_RTP
15259               || (GET_CODE (x) == SYMBOL_REF && !SYMBOL_REF_LOCAL_P (x)))
15260             fputs ("(GOT)", asm_out_file);
15261           else
15262             fputs ("(GOTOFF)", asm_out_file);
15263         }
15264       fputc ('\n', asm_out_file);
15265       return true;
15266     }
15267
15268   mode = GET_MODE (x);
15269
15270   if (arm_vector_mode_supported_p (mode))
15271     {
15272       int i, units;
15273
15274       gcc_assert (GET_CODE (x) == CONST_VECTOR);
15275
15276       units = CONST_VECTOR_NUNITS (x);
15277       size = GET_MODE_SIZE (GET_MODE_INNER (mode));
15278
15279       if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT)
15280         for (i = 0; i < units; i++)
15281           {
15282             rtx elt = CONST_VECTOR_ELT (x, i);
15283             assemble_integer
15284               (elt, size, i == 0 ? BIGGEST_ALIGNMENT : size * BITS_PER_UNIT, 1);
15285           }
15286       else
15287         for (i = 0; i < units; i++)
15288           {
15289             rtx elt = CONST_VECTOR_ELT (x, i);
15290             REAL_VALUE_TYPE rval;
15291
15292             REAL_VALUE_FROM_CONST_DOUBLE (rval, elt);
15293
15294             assemble_real
15295               (rval, GET_MODE_INNER (mode),
15296               i == 0 ? BIGGEST_ALIGNMENT : size * BITS_PER_UNIT);
15297           }
15298
15299       return true;
15300     }
15301
15302   return default_assemble_integer (x, size, aligned_p);
15303 }
15304
15305 static void
15306 arm_elf_asm_cdtor (rtx symbol, int priority, bool is_ctor)
15307 {
15308   section *s;
15309
15310   if (!TARGET_AAPCS_BASED)
15311     {
15312       (is_ctor ? 
15313        default_named_section_asm_out_constructor 
15314        : default_named_section_asm_out_destructor) (symbol, priority);
15315       return;
15316     }
15317
15318   /* Put these in the .init_array section, using a special relocation.  */
15319   if (priority != DEFAULT_INIT_PRIORITY)
15320     {
15321       char buf[18];
15322       sprintf (buf, "%s.%.5u", 
15323                is_ctor ? ".init_array" : ".fini_array",
15324                priority);
15325       s = get_section (buf, SECTION_WRITE, NULL_TREE);
15326     }
15327   else if (is_ctor)
15328     s = ctors_section;
15329   else
15330     s = dtors_section;
15331
15332   switch_to_section (s);
15333   assemble_align (POINTER_SIZE);
15334   fputs ("\t.word\t", asm_out_file);
15335   output_addr_const (asm_out_file, symbol);
15336   fputs ("(target1)\n", asm_out_file);
15337 }
15338
15339 /* Add a function to the list of static constructors.  */
15340
15341 static void
15342 arm_elf_asm_constructor (rtx symbol, int priority)
15343 {
15344   arm_elf_asm_cdtor (symbol, priority, /*is_ctor=*/true);
15345 }
15346
15347 /* Add a function to the list of static destructors.  */
15348
15349 static void
15350 arm_elf_asm_destructor (rtx symbol, int priority)
15351 {
15352   arm_elf_asm_cdtor (symbol, priority, /*is_ctor=*/false);
15353 }
15354 \f
15355 /* A finite state machine takes care of noticing whether or not instructions
15356    can be conditionally executed, and thus decrease execution time and code
15357    size by deleting branch instructions.  The fsm is controlled by
15358    final_prescan_insn, and controls the actions of ASM_OUTPUT_OPCODE.  */
15359
15360 /* The state of the fsm controlling condition codes are:
15361    0: normal, do nothing special
15362    1: make ASM_OUTPUT_OPCODE not output this instruction
15363    2: make ASM_OUTPUT_OPCODE not output this instruction
15364    3: make instructions conditional
15365    4: make instructions conditional
15366
15367    State transitions (state->state by whom under condition):
15368    0 -> 1 final_prescan_insn if the `target' is a label
15369    0 -> 2 final_prescan_insn if the `target' is an unconditional branch
15370    1 -> 3 ASM_OUTPUT_OPCODE after not having output the conditional branch
15371    2 -> 4 ASM_OUTPUT_OPCODE after not having output the conditional branch
15372    3 -> 0 (*targetm.asm_out.internal_label) if the `target' label is reached
15373           (the target label has CODE_LABEL_NUMBER equal to arm_target_label).
15374    4 -> 0 final_prescan_insn if the `target' unconditional branch is reached
15375           (the target insn is arm_target_insn).
15376
15377    If the jump clobbers the conditions then we use states 2 and 4.
15378
15379    A similar thing can be done with conditional return insns.
15380
15381    XXX In case the `target' is an unconditional branch, this conditionalising
15382    of the instructions always reduces code size, but not always execution
15383    time.  But then, I want to reduce the code size to somewhere near what
15384    /bin/cc produces.  */
15385
15386 /* In addition to this, state is maintained for Thumb-2 COND_EXEC
15387    instructions.  When a COND_EXEC instruction is seen the subsequent
15388    instructions are scanned so that multiple conditional instructions can be
15389    combined into a single IT block.  arm_condexec_count and arm_condexec_mask
15390    specify the length and true/false mask for the IT block.  These will be
15391    decremented/zeroed by arm_asm_output_opcode as the insns are output.  */
15392
15393 /* Returns the index of the ARM condition code string in
15394    `arm_condition_codes'.  COMPARISON should be an rtx like
15395    `(eq (...) (...))'.  */
15396 static enum arm_cond_code
15397 get_arm_condition_code (rtx comparison)
15398 {
15399   enum machine_mode mode = GET_MODE (XEXP (comparison, 0));
15400   enum arm_cond_code code;
15401   enum rtx_code comp_code = GET_CODE (comparison);
15402
15403   if (GET_MODE_CLASS (mode) != MODE_CC)
15404     mode = SELECT_CC_MODE (comp_code, XEXP (comparison, 0),
15405                            XEXP (comparison, 1));
15406
15407   switch (mode)
15408     {
15409     case CC_DNEmode: code = ARM_NE; goto dominance;
15410     case CC_DEQmode: code = ARM_EQ; goto dominance;
15411     case CC_DGEmode: code = ARM_GE; goto dominance;
15412     case CC_DGTmode: code = ARM_GT; goto dominance;
15413     case CC_DLEmode: code = ARM_LE; goto dominance;
15414     case CC_DLTmode: code = ARM_LT; goto dominance;
15415     case CC_DGEUmode: code = ARM_CS; goto dominance;
15416     case CC_DGTUmode: code = ARM_HI; goto dominance;
15417     case CC_DLEUmode: code = ARM_LS; goto dominance;
15418     case CC_DLTUmode: code = ARM_CC;
15419
15420     dominance:
15421       gcc_assert (comp_code == EQ || comp_code == NE);
15422
15423       if (comp_code == EQ)
15424         return ARM_INVERSE_CONDITION_CODE (code);
15425       return code;
15426
15427     case CC_NOOVmode:
15428       switch (comp_code)
15429         {
15430         case NE: return ARM_NE;
15431         case EQ: return ARM_EQ;
15432         case GE: return ARM_PL;
15433         case LT: return ARM_MI;
15434         default: gcc_unreachable ();
15435         }
15436
15437     case CC_Zmode:
15438       switch (comp_code)
15439         {
15440         case NE: return ARM_NE;
15441         case EQ: return ARM_EQ;
15442         default: gcc_unreachable ();
15443         }
15444
15445     case CC_Nmode:
15446       switch (comp_code)
15447         {
15448         case NE: return ARM_MI;
15449         case EQ: return ARM_PL;
15450         default: gcc_unreachable ();
15451         }
15452
15453     case CCFPEmode:
15454     case CCFPmode:
15455       /* These encodings assume that AC=1 in the FPA system control
15456          byte.  This allows us to handle all cases except UNEQ and
15457          LTGT.  */
15458       switch (comp_code)
15459         {
15460         case GE: return ARM_GE;
15461         case GT: return ARM_GT;
15462         case LE: return ARM_LS;
15463         case LT: return ARM_MI;
15464         case NE: return ARM_NE;
15465         case EQ: return ARM_EQ;
15466         case ORDERED: return ARM_VC;
15467         case UNORDERED: return ARM_VS;
15468         case UNLT: return ARM_LT;
15469         case UNLE: return ARM_LE;
15470         case UNGT: return ARM_HI;
15471         case UNGE: return ARM_PL;
15472           /* UNEQ and LTGT do not have a representation.  */
15473         case UNEQ: /* Fall through.  */
15474         case LTGT: /* Fall through.  */
15475         default: gcc_unreachable ();
15476         }
15477
15478     case CC_SWPmode:
15479       switch (comp_code)
15480         {
15481         case NE: return ARM_NE;
15482         case EQ: return ARM_EQ;
15483         case GE: return ARM_LE;
15484         case GT: return ARM_LT;
15485         case LE: return ARM_GE;
15486         case LT: return ARM_GT;
15487         case GEU: return ARM_LS;
15488         case GTU: return ARM_CC;
15489         case LEU: return ARM_CS;
15490         case LTU: return ARM_HI;
15491         default: gcc_unreachable ();
15492         }
15493
15494     case CC_Cmode:
15495       switch (comp_code)
15496       {
15497       case LTU: return ARM_CS;
15498       case GEU: return ARM_CC;
15499       default: gcc_unreachable ();
15500       }
15501
15502     case CCmode:
15503       switch (comp_code)
15504         {
15505         case NE: return ARM_NE;
15506         case EQ: return ARM_EQ;
15507         case GE: return ARM_GE;
15508         case GT: return ARM_GT;
15509         case LE: return ARM_LE;
15510         case LT: return ARM_LT;
15511         case GEU: return ARM_CS;
15512         case GTU: return ARM_HI;
15513         case LEU: return ARM_LS;
15514         case LTU: return ARM_CC;
15515         default: gcc_unreachable ();
15516         }
15517
15518     default: gcc_unreachable ();
15519     }
15520 }
15521
15522 /* Tell arm_asm_output_opcode to output IT blocks for conditionally executed
15523    instructions.  */
15524 void
15525 thumb2_final_prescan_insn (rtx insn)
15526 {
15527   rtx first_insn = insn;
15528   rtx body = PATTERN (insn);
15529   rtx predicate;
15530   enum arm_cond_code code;
15531   int n;
15532   int mask;
15533
15534   /* Remove the previous insn from the count of insns to be output.  */
15535   if (arm_condexec_count)
15536       arm_condexec_count--;
15537
15538   /* Nothing to do if we are already inside a conditional block.  */
15539   if (arm_condexec_count)
15540     return;
15541
15542   if (GET_CODE (body) != COND_EXEC)
15543     return;
15544
15545   /* Conditional jumps are implemented directly.  */
15546   if (GET_CODE (insn) == JUMP_INSN)
15547     return;
15548
15549   predicate = COND_EXEC_TEST (body);
15550   arm_current_cc = get_arm_condition_code (predicate);
15551
15552   n = get_attr_ce_count (insn);
15553   arm_condexec_count = 1;
15554   arm_condexec_mask = (1 << n) - 1;
15555   arm_condexec_masklen = n;
15556   /* See if subsequent instructions can be combined into the same block.  */
15557   for (;;)
15558     {
15559       insn = next_nonnote_insn (insn);
15560
15561       /* Jumping into the middle of an IT block is illegal, so a label or
15562          barrier terminates the block.  */
15563       if (GET_CODE (insn) != INSN && GET_CODE(insn) != JUMP_INSN)
15564         break;
15565
15566       body = PATTERN (insn);
15567       /* USE and CLOBBER aren't really insns, so just skip them.  */
15568       if (GET_CODE (body) == USE
15569           || GET_CODE (body) == CLOBBER)
15570         continue;
15571
15572       /* ??? Recognize conditional jumps, and combine them with IT blocks.  */
15573       if (GET_CODE (body) != COND_EXEC)
15574         break;
15575       /* Allow up to 4 conditionally executed instructions in a block.  */
15576       n = get_attr_ce_count (insn);
15577       if (arm_condexec_masklen + n > 4)
15578         break;
15579
15580       predicate = COND_EXEC_TEST (body);
15581       code = get_arm_condition_code (predicate);
15582       mask = (1 << n) - 1;
15583       if (arm_current_cc == code)
15584         arm_condexec_mask |= (mask << arm_condexec_masklen);
15585       else if (arm_current_cc != ARM_INVERSE_CONDITION_CODE(code))
15586         break;
15587
15588       arm_condexec_count++;
15589       arm_condexec_masklen += n;
15590
15591       /* A jump must be the last instruction in a conditional block.  */
15592       if (GET_CODE(insn) == JUMP_INSN)
15593         break;
15594     }
15595   /* Restore recog_data (getting the attributes of other insns can
15596      destroy this array, but final.c assumes that it remains intact
15597      across this call).  */
15598   extract_constrain_insn_cached (first_insn);
15599 }
15600
15601 void
15602 arm_final_prescan_insn (rtx insn)
15603 {
15604   /* BODY will hold the body of INSN.  */
15605   rtx body = PATTERN (insn);
15606
15607   /* This will be 1 if trying to repeat the trick, and things need to be
15608      reversed if it appears to fail.  */
15609   int reverse = 0;
15610
15611   /* If we start with a return insn, we only succeed if we find another one.  */
15612   int seeking_return = 0;
15613
15614   /* START_INSN will hold the insn from where we start looking.  This is the
15615      first insn after the following code_label if REVERSE is true.  */
15616   rtx start_insn = insn;
15617
15618   /* If in state 4, check if the target branch is reached, in order to
15619      change back to state 0.  */
15620   if (arm_ccfsm_state == 4)
15621     {
15622       if (insn == arm_target_insn)
15623         {
15624           arm_target_insn = NULL;
15625           arm_ccfsm_state = 0;
15626         }
15627       return;
15628     }
15629
15630   /* If in state 3, it is possible to repeat the trick, if this insn is an
15631      unconditional branch to a label, and immediately following this branch
15632      is the previous target label which is only used once, and the label this
15633      branch jumps to is not too far off.  */
15634   if (arm_ccfsm_state == 3)
15635     {
15636       if (simplejump_p (insn))
15637         {
15638           start_insn = next_nonnote_insn (start_insn);
15639           if (GET_CODE (start_insn) == BARRIER)
15640             {
15641               /* XXX Isn't this always a barrier?  */
15642               start_insn = next_nonnote_insn (start_insn);
15643             }
15644           if (GET_CODE (start_insn) == CODE_LABEL
15645               && CODE_LABEL_NUMBER (start_insn) == arm_target_label
15646               && LABEL_NUSES (start_insn) == 1)
15647             reverse = TRUE;
15648           else
15649             return;
15650         }
15651       else if (GET_CODE (body) == RETURN)
15652         {
15653           start_insn = next_nonnote_insn (start_insn);
15654           if (GET_CODE (start_insn) == BARRIER)
15655             start_insn = next_nonnote_insn (start_insn);
15656           if (GET_CODE (start_insn) == CODE_LABEL
15657               && CODE_LABEL_NUMBER (start_insn) == arm_target_label
15658               && LABEL_NUSES (start_insn) == 1)
15659             {
15660               reverse = TRUE;
15661               seeking_return = 1;
15662             }
15663           else
15664             return;
15665         }
15666       else
15667         return;
15668     }
15669
15670   gcc_assert (!arm_ccfsm_state || reverse);
15671   if (GET_CODE (insn) != JUMP_INSN)
15672     return;
15673
15674   /* This jump might be paralleled with a clobber of the condition codes
15675      the jump should always come first */
15676   if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0) > 0)
15677     body = XVECEXP (body, 0, 0);
15678
15679   if (reverse
15680       || (GET_CODE (body) == SET && GET_CODE (SET_DEST (body)) == PC
15681           && GET_CODE (SET_SRC (body)) == IF_THEN_ELSE))
15682     {
15683       int insns_skipped;
15684       int fail = FALSE, succeed = FALSE;
15685       /* Flag which part of the IF_THEN_ELSE is the LABEL_REF.  */
15686       int then_not_else = TRUE;
15687       rtx this_insn = start_insn, label = 0;
15688
15689       /* Register the insn jumped to.  */
15690       if (reverse)
15691         {
15692           if (!seeking_return)
15693             label = XEXP (SET_SRC (body), 0);
15694         }
15695       else if (GET_CODE (XEXP (SET_SRC (body), 1)) == LABEL_REF)
15696         label = XEXP (XEXP (SET_SRC (body), 1), 0);
15697       else if (GET_CODE (XEXP (SET_SRC (body), 2)) == LABEL_REF)
15698         {
15699           label = XEXP (XEXP (SET_SRC (body), 2), 0);
15700           then_not_else = FALSE;
15701         }
15702       else if (GET_CODE (XEXP (SET_SRC (body), 1)) == RETURN)
15703         seeking_return = 1;
15704       else if (GET_CODE (XEXP (SET_SRC (body), 2)) == RETURN)
15705         {
15706           seeking_return = 1;
15707           then_not_else = FALSE;
15708         }
15709       else
15710         gcc_unreachable ();
15711
15712       /* See how many insns this branch skips, and what kind of insns.  If all
15713          insns are okay, and the label or unconditional branch to the same
15714          label is not too far away, succeed.  */
15715       for (insns_skipped = 0;
15716            !fail && !succeed && insns_skipped++ < max_insns_skipped;)
15717         {
15718           rtx scanbody;
15719
15720           this_insn = next_nonnote_insn (this_insn);
15721           if (!this_insn)
15722             break;
15723
15724           switch (GET_CODE (this_insn))
15725             {
15726             case CODE_LABEL:
15727               /* Succeed if it is the target label, otherwise fail since
15728                  control falls in from somewhere else.  */
15729               if (this_insn == label)
15730                 {
15731                   arm_ccfsm_state = 1;
15732                   succeed = TRUE;
15733                 }
15734               else
15735                 fail = TRUE;
15736               break;
15737
15738             case BARRIER:
15739               /* Succeed if the following insn is the target label.
15740                  Otherwise fail.
15741                  If return insns are used then the last insn in a function
15742                  will be a barrier.  */
15743               this_insn = next_nonnote_insn (this_insn);
15744               if (this_insn && this_insn == label)
15745                 {
15746                   arm_ccfsm_state = 1;
15747                   succeed = TRUE;
15748                 }
15749               else
15750                 fail = TRUE;
15751               break;
15752
15753             case CALL_INSN:
15754               /* The AAPCS says that conditional calls should not be
15755                  used since they make interworking inefficient (the
15756                  linker can't transform BL<cond> into BLX).  That's
15757                  only a problem if the machine has BLX.  */
15758               if (arm_arch5)
15759                 {
15760                   fail = TRUE;
15761                   break;
15762                 }
15763
15764               /* Succeed if the following insn is the target label, or
15765                  if the following two insns are a barrier and the
15766                  target label.  */
15767               this_insn = next_nonnote_insn (this_insn);
15768               if (this_insn && GET_CODE (this_insn) == BARRIER)
15769                 this_insn = next_nonnote_insn (this_insn);
15770
15771               if (this_insn && this_insn == label
15772                   && insns_skipped < max_insns_skipped)
15773                 {
15774                   arm_ccfsm_state = 1;
15775                   succeed = TRUE;
15776                 }
15777               else
15778                 fail = TRUE;
15779               break;
15780
15781             case JUMP_INSN:
15782               /* If this is an unconditional branch to the same label, succeed.
15783                  If it is to another label, do nothing.  If it is conditional,
15784                  fail.  */
15785               /* XXX Probably, the tests for SET and the PC are
15786                  unnecessary.  */
15787
15788               scanbody = PATTERN (this_insn);
15789               if (GET_CODE (scanbody) == SET
15790                   && GET_CODE (SET_DEST (scanbody)) == PC)
15791                 {
15792                   if (GET_CODE (SET_SRC (scanbody)) == LABEL_REF
15793                       && XEXP (SET_SRC (scanbody), 0) == label && !reverse)
15794                     {
15795                       arm_ccfsm_state = 2;
15796                       succeed = TRUE;
15797                     }
15798                   else if (GET_CODE (SET_SRC (scanbody)) == IF_THEN_ELSE)
15799                     fail = TRUE;
15800                 }
15801               /* Fail if a conditional return is undesirable (e.g. on a
15802                  StrongARM), but still allow this if optimizing for size.  */
15803               else if (GET_CODE (scanbody) == RETURN
15804                        && !use_return_insn (TRUE, NULL)
15805                        && !optimize_size)
15806                 fail = TRUE;
15807               else if (GET_CODE (scanbody) == RETURN
15808                        && seeking_return)
15809                 {
15810                   arm_ccfsm_state = 2;
15811                   succeed = TRUE;
15812                 }
15813               else if (GET_CODE (scanbody) == PARALLEL)
15814                 {
15815                   switch (get_attr_conds (this_insn))
15816                     {
15817                     case CONDS_NOCOND:
15818                       break;
15819                     default:
15820                       fail = TRUE;
15821                       break;
15822                     }
15823                 }
15824               else
15825                 fail = TRUE;    /* Unrecognized jump (e.g. epilogue).  */
15826
15827               break;
15828
15829             case INSN:
15830               /* Instructions using or affecting the condition codes make it
15831                  fail.  */
15832               scanbody = PATTERN (this_insn);
15833               if (!(GET_CODE (scanbody) == SET
15834                     || GET_CODE (scanbody) == PARALLEL)
15835                   || get_attr_conds (this_insn) != CONDS_NOCOND)
15836                 fail = TRUE;
15837
15838               /* A conditional cirrus instruction must be followed by
15839                  a non Cirrus instruction.  However, since we
15840                  conditionalize instructions in this function and by
15841                  the time we get here we can't add instructions
15842                  (nops), because shorten_branches() has already been
15843                  called, we will disable conditionalizing Cirrus
15844                  instructions to be safe.  */
15845               if (GET_CODE (scanbody) != USE
15846                   && GET_CODE (scanbody) != CLOBBER
15847                   && get_attr_cirrus (this_insn) != CIRRUS_NOT)
15848                 fail = TRUE;
15849               break;
15850
15851             default:
15852               break;
15853             }
15854         }
15855       if (succeed)
15856         {
15857           if ((!seeking_return) && (arm_ccfsm_state == 1 || reverse))
15858             arm_target_label = CODE_LABEL_NUMBER (label);
15859           else
15860             {
15861               gcc_assert (seeking_return || arm_ccfsm_state == 2);
15862
15863               while (this_insn && GET_CODE (PATTERN (this_insn)) == USE)
15864                 {
15865                   this_insn = next_nonnote_insn (this_insn);
15866                   gcc_assert (!this_insn
15867                               || (GET_CODE (this_insn) != BARRIER
15868                                   && GET_CODE (this_insn) != CODE_LABEL));
15869                 }
15870               if (!this_insn)
15871                 {
15872                   /* Oh, dear! we ran off the end.. give up.  */
15873                   extract_constrain_insn_cached (insn);
15874                   arm_ccfsm_state = 0;
15875                   arm_target_insn = NULL;
15876                   return;
15877                 }
15878               arm_target_insn = this_insn;
15879             }
15880
15881           /* If REVERSE is true, ARM_CURRENT_CC needs to be inverted from
15882              what it was.  */
15883           if (!reverse)
15884             arm_current_cc = get_arm_condition_code (XEXP (SET_SRC (body), 0));
15885
15886           if (reverse || then_not_else)
15887             arm_current_cc = ARM_INVERSE_CONDITION_CODE (arm_current_cc);
15888         }
15889
15890       /* Restore recog_data (getting the attributes of other insns can
15891          destroy this array, but final.c assumes that it remains intact
15892          across this call.  */
15893       extract_constrain_insn_cached (insn);
15894     }
15895 }
15896
15897 /* Output IT instructions.  */
15898 void
15899 thumb2_asm_output_opcode (FILE * stream)
15900 {
15901   char buff[5];
15902   int n;
15903
15904   if (arm_condexec_mask)
15905     {
15906       for (n = 0; n < arm_condexec_masklen; n++)
15907         buff[n] = (arm_condexec_mask & (1 << n)) ? 't' : 'e';
15908       buff[n] = 0;
15909       asm_fprintf(stream, "i%s\t%s\n\t", buff,
15910                   arm_condition_codes[arm_current_cc]);
15911       arm_condexec_mask = 0;
15912     }
15913 }
15914
15915 /* Returns true if REGNO is a valid register
15916    for holding a quantity of type MODE.  */
15917 int
15918 arm_hard_regno_mode_ok (unsigned int regno, enum machine_mode mode)
15919 {
15920   if (GET_MODE_CLASS (mode) == MODE_CC)
15921     return (regno == CC_REGNUM
15922             || (TARGET_HARD_FLOAT && TARGET_VFP
15923                 && regno == VFPCC_REGNUM));
15924
15925   if (TARGET_THUMB1)
15926     /* For the Thumb we only allow values bigger than SImode in
15927        registers 0 - 6, so that there is always a second low
15928        register available to hold the upper part of the value.
15929        We probably we ought to ensure that the register is the
15930        start of an even numbered register pair.  */
15931     return (ARM_NUM_REGS (mode) < 2) || (regno < LAST_LO_REGNUM);
15932
15933   if (TARGET_HARD_FLOAT && TARGET_MAVERICK
15934       && IS_CIRRUS_REGNUM (regno))
15935     /* We have outlawed SI values in Cirrus registers because they
15936        reside in the lower 32 bits, but SF values reside in the
15937        upper 32 bits.  This causes gcc all sorts of grief.  We can't
15938        even split the registers into pairs because Cirrus SI values
15939        get sign extended to 64bits-- aldyh.  */
15940     return (GET_MODE_CLASS (mode) == MODE_FLOAT) || (mode == DImode);
15941
15942   if (TARGET_HARD_FLOAT && TARGET_VFP
15943       && IS_VFP_REGNUM (regno))
15944     {
15945       if (mode == SFmode || mode == SImode)
15946         return VFP_REGNO_OK_FOR_SINGLE (regno);
15947
15948       if (mode == DFmode)
15949         return VFP_REGNO_OK_FOR_DOUBLE (regno);
15950
15951       /* VFP registers can hold HFmode values, but there is no point in
15952          putting them there unless we have the NEON extensions for
15953          loading/storing them, too.  */
15954       if (mode == HFmode)
15955         return TARGET_NEON_FP16 && VFP_REGNO_OK_FOR_SINGLE (regno);
15956
15957       if (TARGET_NEON)
15958         return (VALID_NEON_DREG_MODE (mode) && VFP_REGNO_OK_FOR_DOUBLE (regno))
15959                || (VALID_NEON_QREG_MODE (mode)
15960                    && NEON_REGNO_OK_FOR_QUAD (regno))
15961                || (mode == TImode && NEON_REGNO_OK_FOR_NREGS (regno, 2))
15962                || (mode == EImode && NEON_REGNO_OK_FOR_NREGS (regno, 3))
15963                || (mode == OImode && NEON_REGNO_OK_FOR_NREGS (regno, 4))
15964                || (mode == CImode && NEON_REGNO_OK_FOR_NREGS (regno, 6))
15965                || (mode == XImode && NEON_REGNO_OK_FOR_NREGS (regno, 8));
15966
15967       return FALSE;
15968     }
15969
15970   if (TARGET_REALLY_IWMMXT)
15971     {
15972       if (IS_IWMMXT_GR_REGNUM (regno))
15973         return mode == SImode;
15974
15975       if (IS_IWMMXT_REGNUM (regno))
15976         return VALID_IWMMXT_REG_MODE (mode);
15977     }
15978   
15979   /* We allow almost any value to be stored in the general registers.
15980      Restrict doubleword quantities to even register pairs so that we can
15981      use ldrd.  Do not allow very large Neon structure opaque modes in
15982      general registers; they would use too many.  */
15983   if (regno <= LAST_ARM_REGNUM)
15984     return !(TARGET_LDRD && GET_MODE_SIZE (mode) > 4 && (regno & 1) != 0)
15985       && ARM_NUM_REGS (mode) <= 4;
15986
15987   if (regno == FRAME_POINTER_REGNUM
15988       || regno == ARG_POINTER_REGNUM)
15989     /* We only allow integers in the fake hard registers.  */
15990     return GET_MODE_CLASS (mode) == MODE_INT;
15991
15992   /* The only registers left are the FPA registers
15993      which we only allow to hold FP values.  */
15994   return (TARGET_HARD_FLOAT && TARGET_FPA
15995           && GET_MODE_CLASS (mode) == MODE_FLOAT
15996           && regno >= FIRST_FPA_REGNUM
15997           && regno <= LAST_FPA_REGNUM);
15998 }
15999
16000 /* For efficiency and historical reasons LO_REGS, HI_REGS and CC_REGS are
16001    not used in arm mode.  */
16002
16003 enum reg_class
16004 arm_regno_class (int regno)
16005 {
16006   if (TARGET_THUMB1)
16007     {
16008       if (regno == STACK_POINTER_REGNUM)
16009         return STACK_REG;
16010       if (regno == CC_REGNUM)
16011         return CC_REG;
16012       if (regno < 8)
16013         return LO_REGS;
16014       return HI_REGS;
16015     }
16016
16017   if (TARGET_THUMB2 && regno < 8)
16018     return LO_REGS;
16019
16020   if (   regno <= LAST_ARM_REGNUM
16021       || regno == FRAME_POINTER_REGNUM
16022       || regno == ARG_POINTER_REGNUM)
16023     return TARGET_THUMB2 ? HI_REGS : GENERAL_REGS;
16024
16025   if (regno == CC_REGNUM || regno == VFPCC_REGNUM)
16026     return TARGET_THUMB2 ? CC_REG : NO_REGS;
16027
16028   if (IS_CIRRUS_REGNUM (regno))
16029     return CIRRUS_REGS;
16030
16031   if (IS_VFP_REGNUM (regno))
16032     {
16033       if (regno <= D7_VFP_REGNUM)
16034         return VFP_D0_D7_REGS;
16035       else if (regno <= LAST_LO_VFP_REGNUM)
16036         return VFP_LO_REGS;
16037       else
16038         return VFP_HI_REGS;
16039     }
16040
16041   if (IS_IWMMXT_REGNUM (regno))
16042     return IWMMXT_REGS;
16043
16044   if (IS_IWMMXT_GR_REGNUM (regno))
16045     return IWMMXT_GR_REGS;
16046
16047   return FPA_REGS;
16048 }
16049
16050 /* Handle a special case when computing the offset
16051    of an argument from the frame pointer.  */
16052 int
16053 arm_debugger_arg_offset (int value, rtx addr)
16054 {
16055   rtx insn;
16056
16057   /* We are only interested if dbxout_parms() failed to compute the offset.  */
16058   if (value != 0)
16059     return 0;
16060
16061   /* We can only cope with the case where the address is held in a register.  */
16062   if (GET_CODE (addr) != REG)
16063     return 0;
16064
16065   /* If we are using the frame pointer to point at the argument, then
16066      an offset of 0 is correct.  */
16067   if (REGNO (addr) == (unsigned) HARD_FRAME_POINTER_REGNUM)
16068     return 0;
16069
16070   /* If we are using the stack pointer to point at the
16071      argument, then an offset of 0 is correct.  */
16072   /* ??? Check this is consistent with thumb2 frame layout.  */
16073   if ((TARGET_THUMB || !frame_pointer_needed)
16074       && REGNO (addr) == SP_REGNUM)
16075     return 0;
16076
16077   /* Oh dear.  The argument is pointed to by a register rather
16078      than being held in a register, or being stored at a known
16079      offset from the frame pointer.  Since GDB only understands
16080      those two kinds of argument we must translate the address
16081      held in the register into an offset from the frame pointer.
16082      We do this by searching through the insns for the function
16083      looking to see where this register gets its value.  If the
16084      register is initialized from the frame pointer plus an offset
16085      then we are in luck and we can continue, otherwise we give up.
16086
16087      This code is exercised by producing debugging information
16088      for a function with arguments like this:
16089
16090            double func (double a, double b, int c, double d) {return d;}
16091
16092      Without this code the stab for parameter 'd' will be set to
16093      an offset of 0 from the frame pointer, rather than 8.  */
16094
16095   /* The if() statement says:
16096
16097      If the insn is a normal instruction
16098      and if the insn is setting the value in a register
16099      and if the register being set is the register holding the address of the argument
16100      and if the address is computing by an addition
16101      that involves adding to a register
16102      which is the frame pointer
16103      a constant integer
16104
16105      then...  */
16106
16107   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
16108     {
16109       if (   GET_CODE (insn) == INSN
16110           && GET_CODE (PATTERN (insn)) == SET
16111           && REGNO    (XEXP (PATTERN (insn), 0)) == REGNO (addr)
16112           && GET_CODE (XEXP (PATTERN (insn), 1)) == PLUS
16113           && GET_CODE (XEXP (XEXP (PATTERN (insn), 1), 0)) == REG
16114           && REGNO    (XEXP (XEXP (PATTERN (insn), 1), 0)) == (unsigned) HARD_FRAME_POINTER_REGNUM
16115           && GET_CODE (XEXP (XEXP (PATTERN (insn), 1), 1)) == CONST_INT
16116              )
16117         {
16118           value = INTVAL (XEXP (XEXP (PATTERN (insn), 1), 1));
16119
16120           break;
16121         }
16122     }
16123
16124   if (value == 0)
16125     {
16126       debug_rtx (addr);
16127       warning (0, "unable to compute real location of stacked parameter");
16128       value = 8; /* XXX magic hack */
16129     }
16130
16131   return value;
16132 }
16133 \f
16134 #define def_mbuiltin(MASK, NAME, TYPE, CODE)                            \
16135   do                                                                    \
16136     {                                                                   \
16137       if ((MASK) & insn_flags)                                          \
16138         add_builtin_function ((NAME), (TYPE), (CODE),                   \
16139                              BUILT_IN_MD, NULL, NULL_TREE);             \
16140     }                                                                   \
16141   while (0)
16142
16143 struct builtin_description
16144 {
16145   const unsigned int       mask;
16146   const enum insn_code     icode;
16147   const char * const       name;
16148   const enum arm_builtins  code;
16149   const enum rtx_code      comparison;
16150   const unsigned int       flag;
16151 };
16152
16153 static const struct builtin_description bdesc_2arg[] =
16154 {
16155 #define IWMMXT_BUILTIN(code, string, builtin) \
16156   { FL_IWMMXT, CODE_FOR_##code, "__builtin_arm_" string, \
16157     ARM_BUILTIN_##builtin, UNKNOWN, 0 },
16158
16159   IWMMXT_BUILTIN (addv8qi3, "waddb", WADDB)
16160   IWMMXT_BUILTIN (addv4hi3, "waddh", WADDH)
16161   IWMMXT_BUILTIN (addv2si3, "waddw", WADDW)
16162   IWMMXT_BUILTIN (subv8qi3, "wsubb", WSUBB)
16163   IWMMXT_BUILTIN (subv4hi3, "wsubh", WSUBH)
16164   IWMMXT_BUILTIN (subv2si3, "wsubw", WSUBW)
16165   IWMMXT_BUILTIN (ssaddv8qi3, "waddbss", WADDSSB)
16166   IWMMXT_BUILTIN (ssaddv4hi3, "waddhss", WADDSSH)
16167   IWMMXT_BUILTIN (ssaddv2si3, "waddwss", WADDSSW)
16168   IWMMXT_BUILTIN (sssubv8qi3, "wsubbss", WSUBSSB)
16169   IWMMXT_BUILTIN (sssubv4hi3, "wsubhss", WSUBSSH)
16170   IWMMXT_BUILTIN (sssubv2si3, "wsubwss", WSUBSSW)
16171   IWMMXT_BUILTIN (usaddv8qi3, "waddbus", WADDUSB)
16172   IWMMXT_BUILTIN (usaddv4hi3, "waddhus", WADDUSH)
16173   IWMMXT_BUILTIN (usaddv2si3, "waddwus", WADDUSW)
16174   IWMMXT_BUILTIN (ussubv8qi3, "wsubbus", WSUBUSB)
16175   IWMMXT_BUILTIN (ussubv4hi3, "wsubhus", WSUBUSH)
16176   IWMMXT_BUILTIN (ussubv2si3, "wsubwus", WSUBUSW)
16177   IWMMXT_BUILTIN (mulv4hi3, "wmulul", WMULUL)
16178   IWMMXT_BUILTIN (smulv4hi3_highpart, "wmulsm", WMULSM)
16179   IWMMXT_BUILTIN (umulv4hi3_highpart, "wmulum", WMULUM)
16180   IWMMXT_BUILTIN (eqv8qi3, "wcmpeqb", WCMPEQB)
16181   IWMMXT_BUILTIN (eqv4hi3, "wcmpeqh", WCMPEQH)
16182   IWMMXT_BUILTIN (eqv2si3, "wcmpeqw", WCMPEQW)
16183   IWMMXT_BUILTIN (gtuv8qi3, "wcmpgtub", WCMPGTUB)
16184   IWMMXT_BUILTIN (gtuv4hi3, "wcmpgtuh", WCMPGTUH)
16185   IWMMXT_BUILTIN (gtuv2si3, "wcmpgtuw", WCMPGTUW)
16186   IWMMXT_BUILTIN (gtv8qi3, "wcmpgtsb", WCMPGTSB)
16187   IWMMXT_BUILTIN (gtv4hi3, "wcmpgtsh", WCMPGTSH)
16188   IWMMXT_BUILTIN (gtv2si3, "wcmpgtsw", WCMPGTSW)
16189   IWMMXT_BUILTIN (umaxv8qi3, "wmaxub", WMAXUB)
16190   IWMMXT_BUILTIN (smaxv8qi3, "wmaxsb", WMAXSB)
16191   IWMMXT_BUILTIN (umaxv4hi3, "wmaxuh", WMAXUH)
16192   IWMMXT_BUILTIN (smaxv4hi3, "wmaxsh", WMAXSH)
16193   IWMMXT_BUILTIN (umaxv2si3, "wmaxuw", WMAXUW)
16194   IWMMXT_BUILTIN (smaxv2si3, "wmaxsw", WMAXSW)
16195   IWMMXT_BUILTIN (uminv8qi3, "wminub", WMINUB)
16196   IWMMXT_BUILTIN (sminv8qi3, "wminsb", WMINSB)
16197   IWMMXT_BUILTIN (uminv4hi3, "wminuh", WMINUH)
16198   IWMMXT_BUILTIN (sminv4hi3, "wminsh", WMINSH)
16199   IWMMXT_BUILTIN (uminv2si3, "wminuw", WMINUW)
16200   IWMMXT_BUILTIN (sminv2si3, "wminsw", WMINSW)
16201   IWMMXT_BUILTIN (iwmmxt_anddi3, "wand", WAND)
16202   IWMMXT_BUILTIN (iwmmxt_nanddi3, "wandn", WANDN)
16203   IWMMXT_BUILTIN (iwmmxt_iordi3, "wor", WOR)
16204   IWMMXT_BUILTIN (iwmmxt_xordi3, "wxor", WXOR)
16205   IWMMXT_BUILTIN (iwmmxt_uavgv8qi3, "wavg2b", WAVG2B)
16206   IWMMXT_BUILTIN (iwmmxt_uavgv4hi3, "wavg2h", WAVG2H)
16207   IWMMXT_BUILTIN (iwmmxt_uavgrndv8qi3, "wavg2br", WAVG2BR)
16208   IWMMXT_BUILTIN (iwmmxt_uavgrndv4hi3, "wavg2hr", WAVG2HR)
16209   IWMMXT_BUILTIN (iwmmxt_wunpckilb, "wunpckilb", WUNPCKILB)
16210   IWMMXT_BUILTIN (iwmmxt_wunpckilh, "wunpckilh", WUNPCKILH)
16211   IWMMXT_BUILTIN (iwmmxt_wunpckilw, "wunpckilw", WUNPCKILW)
16212   IWMMXT_BUILTIN (iwmmxt_wunpckihb, "wunpckihb", WUNPCKIHB)
16213   IWMMXT_BUILTIN (iwmmxt_wunpckihh, "wunpckihh", WUNPCKIHH)
16214   IWMMXT_BUILTIN (iwmmxt_wunpckihw, "wunpckihw", WUNPCKIHW)
16215   IWMMXT_BUILTIN (iwmmxt_wmadds, "wmadds", WMADDS)
16216   IWMMXT_BUILTIN (iwmmxt_wmaddu, "wmaddu", WMADDU)
16217
16218 #define IWMMXT_BUILTIN2(code, builtin) \
16219   { FL_IWMMXT, CODE_FOR_##code, NULL, ARM_BUILTIN_##builtin, UNKNOWN, 0 },
16220
16221   IWMMXT_BUILTIN2 (iwmmxt_wpackhss, WPACKHSS)
16222   IWMMXT_BUILTIN2 (iwmmxt_wpackwss, WPACKWSS)
16223   IWMMXT_BUILTIN2 (iwmmxt_wpackdss, WPACKDSS)
16224   IWMMXT_BUILTIN2 (iwmmxt_wpackhus, WPACKHUS)
16225   IWMMXT_BUILTIN2 (iwmmxt_wpackwus, WPACKWUS)
16226   IWMMXT_BUILTIN2 (iwmmxt_wpackdus, WPACKDUS)
16227   IWMMXT_BUILTIN2 (ashlv4hi3_di,    WSLLH)
16228   IWMMXT_BUILTIN2 (ashlv4hi3_iwmmxt, WSLLHI)
16229   IWMMXT_BUILTIN2 (ashlv2si3_di,    WSLLW)
16230   IWMMXT_BUILTIN2 (ashlv2si3_iwmmxt, WSLLWI)
16231   IWMMXT_BUILTIN2 (ashldi3_di,      WSLLD)
16232   IWMMXT_BUILTIN2 (ashldi3_iwmmxt,  WSLLDI)
16233   IWMMXT_BUILTIN2 (lshrv4hi3_di,    WSRLH)
16234   IWMMXT_BUILTIN2 (lshrv4hi3_iwmmxt, WSRLHI)
16235   IWMMXT_BUILTIN2 (lshrv2si3_di,    WSRLW)
16236   IWMMXT_BUILTIN2 (lshrv2si3_iwmmxt, WSRLWI)
16237   IWMMXT_BUILTIN2 (lshrdi3_di,      WSRLD)
16238   IWMMXT_BUILTIN2 (lshrdi3_iwmmxt,  WSRLDI)
16239   IWMMXT_BUILTIN2 (ashrv4hi3_di,    WSRAH)
16240   IWMMXT_BUILTIN2 (ashrv4hi3_iwmmxt, WSRAHI)
16241   IWMMXT_BUILTIN2 (ashrv2si3_di,    WSRAW)
16242   IWMMXT_BUILTIN2 (ashrv2si3_iwmmxt, WSRAWI)
16243   IWMMXT_BUILTIN2 (ashrdi3_di,      WSRAD)
16244   IWMMXT_BUILTIN2 (ashrdi3_iwmmxt,  WSRADI)
16245   IWMMXT_BUILTIN2 (rorv4hi3_di,     WRORH)
16246   IWMMXT_BUILTIN2 (rorv4hi3,        WRORHI)
16247   IWMMXT_BUILTIN2 (rorv2si3_di,     WRORW)
16248   IWMMXT_BUILTIN2 (rorv2si3,        WRORWI)
16249   IWMMXT_BUILTIN2 (rordi3_di,       WRORD)
16250   IWMMXT_BUILTIN2 (rordi3,          WRORDI)
16251   IWMMXT_BUILTIN2 (iwmmxt_wmacuz,   WMACUZ)
16252   IWMMXT_BUILTIN2 (iwmmxt_wmacsz,   WMACSZ)
16253 };
16254
16255 static const struct builtin_description bdesc_1arg[] =
16256 {
16257   IWMMXT_BUILTIN (iwmmxt_tmovmskb, "tmovmskb", TMOVMSKB)
16258   IWMMXT_BUILTIN (iwmmxt_tmovmskh, "tmovmskh", TMOVMSKH)
16259   IWMMXT_BUILTIN (iwmmxt_tmovmskw, "tmovmskw", TMOVMSKW)
16260   IWMMXT_BUILTIN (iwmmxt_waccb, "waccb", WACCB)
16261   IWMMXT_BUILTIN (iwmmxt_wacch, "wacch", WACCH)
16262   IWMMXT_BUILTIN (iwmmxt_waccw, "waccw", WACCW)
16263   IWMMXT_BUILTIN (iwmmxt_wunpckehub, "wunpckehub", WUNPCKEHUB)
16264   IWMMXT_BUILTIN (iwmmxt_wunpckehuh, "wunpckehuh", WUNPCKEHUH)
16265   IWMMXT_BUILTIN (iwmmxt_wunpckehuw, "wunpckehuw", WUNPCKEHUW)
16266   IWMMXT_BUILTIN (iwmmxt_wunpckehsb, "wunpckehsb", WUNPCKEHSB)
16267   IWMMXT_BUILTIN (iwmmxt_wunpckehsh, "wunpckehsh", WUNPCKEHSH)
16268   IWMMXT_BUILTIN (iwmmxt_wunpckehsw, "wunpckehsw", WUNPCKEHSW)
16269   IWMMXT_BUILTIN (iwmmxt_wunpckelub, "wunpckelub", WUNPCKELUB)
16270   IWMMXT_BUILTIN (iwmmxt_wunpckeluh, "wunpckeluh", WUNPCKELUH)
16271   IWMMXT_BUILTIN (iwmmxt_wunpckeluw, "wunpckeluw", WUNPCKELUW)
16272   IWMMXT_BUILTIN (iwmmxt_wunpckelsb, "wunpckelsb", WUNPCKELSB)
16273   IWMMXT_BUILTIN (iwmmxt_wunpckelsh, "wunpckelsh", WUNPCKELSH)
16274   IWMMXT_BUILTIN (iwmmxt_wunpckelsw, "wunpckelsw", WUNPCKELSW)
16275 };
16276
16277 /* Set up all the iWMMXt builtins.  This is
16278    not called if TARGET_IWMMXT is zero.  */
16279
16280 static void
16281 arm_init_iwmmxt_builtins (void)
16282 {
16283   const struct builtin_description * d;
16284   size_t i;
16285   tree endlink = void_list_node;
16286
16287   tree V2SI_type_node = build_vector_type_for_mode (intSI_type_node, V2SImode);
16288   tree V4HI_type_node = build_vector_type_for_mode (intHI_type_node, V4HImode);
16289   tree V8QI_type_node = build_vector_type_for_mode (intQI_type_node, V8QImode);
16290
16291   tree int_ftype_int
16292     = build_function_type (integer_type_node,
16293                            tree_cons (NULL_TREE, integer_type_node, endlink));
16294   tree v8qi_ftype_v8qi_v8qi_int
16295     = build_function_type (V8QI_type_node,
16296                            tree_cons (NULL_TREE, V8QI_type_node,
16297                                       tree_cons (NULL_TREE, V8QI_type_node,
16298                                                  tree_cons (NULL_TREE,
16299                                                             integer_type_node,
16300                                                             endlink))));
16301   tree v4hi_ftype_v4hi_int
16302     = build_function_type (V4HI_type_node,
16303                            tree_cons (NULL_TREE, V4HI_type_node,
16304                                       tree_cons (NULL_TREE, integer_type_node,
16305                                                  endlink)));
16306   tree v2si_ftype_v2si_int
16307     = build_function_type (V2SI_type_node,
16308                            tree_cons (NULL_TREE, V2SI_type_node,
16309                                       tree_cons (NULL_TREE, integer_type_node,
16310                                                  endlink)));
16311   tree v2si_ftype_di_di
16312     = build_function_type (V2SI_type_node,
16313                            tree_cons (NULL_TREE, long_long_integer_type_node,
16314                                       tree_cons (NULL_TREE, long_long_integer_type_node,
16315                                                  endlink)));
16316   tree di_ftype_di_int
16317     = build_function_type (long_long_integer_type_node,
16318                            tree_cons (NULL_TREE, long_long_integer_type_node,
16319                                       tree_cons (NULL_TREE, integer_type_node,
16320                                                  endlink)));
16321   tree di_ftype_di_int_int
16322     = build_function_type (long_long_integer_type_node,
16323                            tree_cons (NULL_TREE, long_long_integer_type_node,
16324                                       tree_cons (NULL_TREE, integer_type_node,
16325                                                  tree_cons (NULL_TREE,
16326                                                             integer_type_node,
16327                                                             endlink))));
16328   tree int_ftype_v8qi
16329     = build_function_type (integer_type_node,
16330                            tree_cons (NULL_TREE, V8QI_type_node,
16331                                       endlink));
16332   tree int_ftype_v4hi
16333     = build_function_type (integer_type_node,
16334                            tree_cons (NULL_TREE, V4HI_type_node,
16335                                       endlink));
16336   tree int_ftype_v2si
16337     = build_function_type (integer_type_node,
16338                            tree_cons (NULL_TREE, V2SI_type_node,
16339                                       endlink));
16340   tree int_ftype_v8qi_int
16341     = build_function_type (integer_type_node,
16342                            tree_cons (NULL_TREE, V8QI_type_node,
16343                                       tree_cons (NULL_TREE, integer_type_node,
16344                                                  endlink)));
16345   tree int_ftype_v4hi_int
16346     = build_function_type (integer_type_node,
16347                            tree_cons (NULL_TREE, V4HI_type_node,
16348                                       tree_cons (NULL_TREE, integer_type_node,
16349                                                  endlink)));
16350   tree int_ftype_v2si_int
16351     = build_function_type (integer_type_node,
16352                            tree_cons (NULL_TREE, V2SI_type_node,
16353                                       tree_cons (NULL_TREE, integer_type_node,
16354                                                  endlink)));
16355   tree v8qi_ftype_v8qi_int_int
16356     = build_function_type (V8QI_type_node,
16357                            tree_cons (NULL_TREE, V8QI_type_node,
16358                                       tree_cons (NULL_TREE, integer_type_node,
16359                                                  tree_cons (NULL_TREE,
16360                                                             integer_type_node,
16361                                                             endlink))));
16362   tree v4hi_ftype_v4hi_int_int
16363     = build_function_type (V4HI_type_node,
16364                            tree_cons (NULL_TREE, V4HI_type_node,
16365                                       tree_cons (NULL_TREE, integer_type_node,
16366                                                  tree_cons (NULL_TREE,
16367                                                             integer_type_node,
16368                                                             endlink))));
16369   tree v2si_ftype_v2si_int_int
16370     = build_function_type (V2SI_type_node,
16371                            tree_cons (NULL_TREE, V2SI_type_node,
16372                                       tree_cons (NULL_TREE, integer_type_node,
16373                                                  tree_cons (NULL_TREE,
16374                                                             integer_type_node,
16375                                                             endlink))));
16376   /* Miscellaneous.  */
16377   tree v8qi_ftype_v4hi_v4hi
16378     = build_function_type (V8QI_type_node,
16379                            tree_cons (NULL_TREE, V4HI_type_node,
16380                                       tree_cons (NULL_TREE, V4HI_type_node,
16381                                                  endlink)));
16382   tree v4hi_ftype_v2si_v2si
16383     = build_function_type (V4HI_type_node,
16384                            tree_cons (NULL_TREE, V2SI_type_node,
16385                                       tree_cons (NULL_TREE, V2SI_type_node,
16386                                                  endlink)));
16387   tree v2si_ftype_v4hi_v4hi
16388     = build_function_type (V2SI_type_node,
16389                            tree_cons (NULL_TREE, V4HI_type_node,
16390                                       tree_cons (NULL_TREE, V4HI_type_node,
16391                                                  endlink)));
16392   tree v2si_ftype_v8qi_v8qi
16393     = build_function_type (V2SI_type_node,
16394                            tree_cons (NULL_TREE, V8QI_type_node,
16395                                       tree_cons (NULL_TREE, V8QI_type_node,
16396                                                  endlink)));
16397   tree v4hi_ftype_v4hi_di
16398     = build_function_type (V4HI_type_node,
16399                            tree_cons (NULL_TREE, V4HI_type_node,
16400                                       tree_cons (NULL_TREE,
16401                                                  long_long_integer_type_node,
16402                                                  endlink)));
16403   tree v2si_ftype_v2si_di
16404     = build_function_type (V2SI_type_node,
16405                            tree_cons (NULL_TREE, V2SI_type_node,
16406                                       tree_cons (NULL_TREE,
16407                                                  long_long_integer_type_node,
16408                                                  endlink)));
16409   tree void_ftype_int_int
16410     = build_function_type (void_type_node,
16411                            tree_cons (NULL_TREE, integer_type_node,
16412                                       tree_cons (NULL_TREE, integer_type_node,
16413                                                  endlink)));
16414   tree di_ftype_void
16415     = build_function_type (long_long_unsigned_type_node, endlink);
16416   tree di_ftype_v8qi
16417     = build_function_type (long_long_integer_type_node,
16418                            tree_cons (NULL_TREE, V8QI_type_node,
16419                                       endlink));
16420   tree di_ftype_v4hi
16421     = build_function_type (long_long_integer_type_node,
16422                            tree_cons (NULL_TREE, V4HI_type_node,
16423                                       endlink));
16424   tree di_ftype_v2si
16425     = build_function_type (long_long_integer_type_node,
16426                            tree_cons (NULL_TREE, V2SI_type_node,
16427                                       endlink));
16428   tree v2si_ftype_v4hi
16429     = build_function_type (V2SI_type_node,
16430                            tree_cons (NULL_TREE, V4HI_type_node,
16431                                       endlink));
16432   tree v4hi_ftype_v8qi
16433     = build_function_type (V4HI_type_node,
16434                            tree_cons (NULL_TREE, V8QI_type_node,
16435                                       endlink));
16436
16437   tree di_ftype_di_v4hi_v4hi
16438     = build_function_type (long_long_unsigned_type_node,
16439                            tree_cons (NULL_TREE,
16440                                       long_long_unsigned_type_node,
16441                                       tree_cons (NULL_TREE, V4HI_type_node,
16442                                                  tree_cons (NULL_TREE,
16443                                                             V4HI_type_node,
16444                                                             endlink))));
16445
16446   tree di_ftype_v4hi_v4hi
16447     = build_function_type (long_long_unsigned_type_node,
16448                            tree_cons (NULL_TREE, V4HI_type_node,
16449                                       tree_cons (NULL_TREE, V4HI_type_node,
16450                                                  endlink)));
16451
16452   /* Normal vector binops.  */
16453   tree v8qi_ftype_v8qi_v8qi
16454     = build_function_type (V8QI_type_node,
16455                            tree_cons (NULL_TREE, V8QI_type_node,
16456                                       tree_cons (NULL_TREE, V8QI_type_node,
16457                                                  endlink)));
16458   tree v4hi_ftype_v4hi_v4hi
16459     = build_function_type (V4HI_type_node,
16460                            tree_cons (NULL_TREE, V4HI_type_node,
16461                                       tree_cons (NULL_TREE, V4HI_type_node,
16462                                                  endlink)));
16463   tree v2si_ftype_v2si_v2si
16464     = build_function_type (V2SI_type_node,
16465                            tree_cons (NULL_TREE, V2SI_type_node,
16466                                       tree_cons (NULL_TREE, V2SI_type_node,
16467                                                  endlink)));
16468   tree di_ftype_di_di
16469     = build_function_type (long_long_unsigned_type_node,
16470                            tree_cons (NULL_TREE, long_long_unsigned_type_node,
16471                                       tree_cons (NULL_TREE,
16472                                                  long_long_unsigned_type_node,
16473                                                  endlink)));
16474
16475   /* Add all builtins that are more or less simple operations on two
16476      operands.  */
16477   for (i = 0, d = bdesc_2arg; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
16478     {
16479       /* Use one of the operands; the target can have a different mode for
16480          mask-generating compares.  */
16481       enum machine_mode mode;
16482       tree type;
16483
16484       if (d->name == 0)
16485         continue;
16486
16487       mode = insn_data[d->icode].operand[1].mode;
16488
16489       switch (mode)
16490         {
16491         case V8QImode:
16492           type = v8qi_ftype_v8qi_v8qi;
16493           break;
16494         case V4HImode:
16495           type = v4hi_ftype_v4hi_v4hi;
16496           break;
16497         case V2SImode:
16498           type = v2si_ftype_v2si_v2si;
16499           break;
16500         case DImode:
16501           type = di_ftype_di_di;
16502           break;
16503
16504         default:
16505           gcc_unreachable ();
16506         }
16507
16508       def_mbuiltin (d->mask, d->name, type, d->code);
16509     }
16510
16511   /* Add the remaining MMX insns with somewhat more complicated types.  */
16512   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wzero", di_ftype_void, ARM_BUILTIN_WZERO);
16513   def_mbuiltin (FL_IWMMXT, "__builtin_arm_setwcx", void_ftype_int_int, ARM_BUILTIN_SETWCX);
16514   def_mbuiltin (FL_IWMMXT, "__builtin_arm_getwcx", int_ftype_int, ARM_BUILTIN_GETWCX);
16515
16516   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsllh", v4hi_ftype_v4hi_di, ARM_BUILTIN_WSLLH);
16517   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsllw", v2si_ftype_v2si_di, ARM_BUILTIN_WSLLW);
16518   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wslld", di_ftype_di_di, ARM_BUILTIN_WSLLD);
16519   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsllhi", v4hi_ftype_v4hi_int, ARM_BUILTIN_WSLLHI);
16520   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsllwi", v2si_ftype_v2si_int, ARM_BUILTIN_WSLLWI);
16521   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wslldi", di_ftype_di_int, ARM_BUILTIN_WSLLDI);
16522
16523   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrlh", v4hi_ftype_v4hi_di, ARM_BUILTIN_WSRLH);
16524   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrlw", v2si_ftype_v2si_di, ARM_BUILTIN_WSRLW);
16525   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrld", di_ftype_di_di, ARM_BUILTIN_WSRLD);
16526   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrlhi", v4hi_ftype_v4hi_int, ARM_BUILTIN_WSRLHI);
16527   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrlwi", v2si_ftype_v2si_int, ARM_BUILTIN_WSRLWI);
16528   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrldi", di_ftype_di_int, ARM_BUILTIN_WSRLDI);
16529
16530   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrah", v4hi_ftype_v4hi_di, ARM_BUILTIN_WSRAH);
16531   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsraw", v2si_ftype_v2si_di, ARM_BUILTIN_WSRAW);
16532   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrad", di_ftype_di_di, ARM_BUILTIN_WSRAD);
16533   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrahi", v4hi_ftype_v4hi_int, ARM_BUILTIN_WSRAHI);
16534   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsrawi", v2si_ftype_v2si_int, ARM_BUILTIN_WSRAWI);
16535   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsradi", di_ftype_di_int, ARM_BUILTIN_WSRADI);
16536
16537   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrorh", v4hi_ftype_v4hi_di, ARM_BUILTIN_WRORH);
16538   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrorw", v2si_ftype_v2si_di, ARM_BUILTIN_WRORW);
16539   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrord", di_ftype_di_di, ARM_BUILTIN_WRORD);
16540   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrorhi", v4hi_ftype_v4hi_int, ARM_BUILTIN_WRORHI);
16541   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrorwi", v2si_ftype_v2si_int, ARM_BUILTIN_WRORWI);
16542   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wrordi", di_ftype_di_int, ARM_BUILTIN_WRORDI);
16543
16544   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wshufh", v4hi_ftype_v4hi_int, ARM_BUILTIN_WSHUFH);
16545
16546   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsadb", v2si_ftype_v8qi_v8qi, ARM_BUILTIN_WSADB);
16547   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsadh", v2si_ftype_v4hi_v4hi, ARM_BUILTIN_WSADH);
16548   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsadbz", v2si_ftype_v8qi_v8qi, ARM_BUILTIN_WSADBZ);
16549   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wsadhz", v2si_ftype_v4hi_v4hi, ARM_BUILTIN_WSADHZ);
16550
16551   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmsb", int_ftype_v8qi_int, ARM_BUILTIN_TEXTRMSB);
16552   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmsh", int_ftype_v4hi_int, ARM_BUILTIN_TEXTRMSH);
16553   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmsw", int_ftype_v2si_int, ARM_BUILTIN_TEXTRMSW);
16554   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmub", int_ftype_v8qi_int, ARM_BUILTIN_TEXTRMUB);
16555   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmuh", int_ftype_v4hi_int, ARM_BUILTIN_TEXTRMUH);
16556   def_mbuiltin (FL_IWMMXT, "__builtin_arm_textrmuw", int_ftype_v2si_int, ARM_BUILTIN_TEXTRMUW);
16557   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tinsrb", v8qi_ftype_v8qi_int_int, ARM_BUILTIN_TINSRB);
16558   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tinsrh", v4hi_ftype_v4hi_int_int, ARM_BUILTIN_TINSRH);
16559   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tinsrw", v2si_ftype_v2si_int_int, ARM_BUILTIN_TINSRW);
16560
16561   def_mbuiltin (FL_IWMMXT, "__builtin_arm_waccb", di_ftype_v8qi, ARM_BUILTIN_WACCB);
16562   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wacch", di_ftype_v4hi, ARM_BUILTIN_WACCH);
16563   def_mbuiltin (FL_IWMMXT, "__builtin_arm_waccw", di_ftype_v2si, ARM_BUILTIN_WACCW);
16564
16565   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmovmskb", int_ftype_v8qi, ARM_BUILTIN_TMOVMSKB);
16566   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmovmskh", int_ftype_v4hi, ARM_BUILTIN_TMOVMSKH);
16567   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmovmskw", int_ftype_v2si, ARM_BUILTIN_TMOVMSKW);
16568
16569   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackhss", v8qi_ftype_v4hi_v4hi, ARM_BUILTIN_WPACKHSS);
16570   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackhus", v8qi_ftype_v4hi_v4hi, ARM_BUILTIN_WPACKHUS);
16571   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackwus", v4hi_ftype_v2si_v2si, ARM_BUILTIN_WPACKWUS);
16572   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackwss", v4hi_ftype_v2si_v2si, ARM_BUILTIN_WPACKWSS);
16573   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackdus", v2si_ftype_di_di, ARM_BUILTIN_WPACKDUS);
16574   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wpackdss", v2si_ftype_di_di, ARM_BUILTIN_WPACKDSS);
16575
16576   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehub", v4hi_ftype_v8qi, ARM_BUILTIN_WUNPCKEHUB);
16577   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehuh", v2si_ftype_v4hi, ARM_BUILTIN_WUNPCKEHUH);
16578   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehuw", di_ftype_v2si, ARM_BUILTIN_WUNPCKEHUW);
16579   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehsb", v4hi_ftype_v8qi, ARM_BUILTIN_WUNPCKEHSB);
16580   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehsh", v2si_ftype_v4hi, ARM_BUILTIN_WUNPCKEHSH);
16581   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckehsw", di_ftype_v2si, ARM_BUILTIN_WUNPCKEHSW);
16582   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckelub", v4hi_ftype_v8qi, ARM_BUILTIN_WUNPCKELUB);
16583   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckeluh", v2si_ftype_v4hi, ARM_BUILTIN_WUNPCKELUH);
16584   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckeluw", di_ftype_v2si, ARM_BUILTIN_WUNPCKELUW);
16585   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckelsb", v4hi_ftype_v8qi, ARM_BUILTIN_WUNPCKELSB);
16586   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckelsh", v2si_ftype_v4hi, ARM_BUILTIN_WUNPCKELSH);
16587   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wunpckelsw", di_ftype_v2si, ARM_BUILTIN_WUNPCKELSW);
16588
16589   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wmacs", di_ftype_di_v4hi_v4hi, ARM_BUILTIN_WMACS);
16590   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wmacsz", di_ftype_v4hi_v4hi, ARM_BUILTIN_WMACSZ);
16591   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wmacu", di_ftype_di_v4hi_v4hi, ARM_BUILTIN_WMACU);
16592   def_mbuiltin (FL_IWMMXT, "__builtin_arm_wmacuz", di_ftype_v4hi_v4hi, ARM_BUILTIN_WMACUZ);
16593
16594   def_mbuiltin (FL_IWMMXT, "__builtin_arm_walign", v8qi_ftype_v8qi_v8qi_int, ARM_BUILTIN_WALIGN);
16595   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmia", di_ftype_di_int_int, ARM_BUILTIN_TMIA);
16596   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmiaph", di_ftype_di_int_int, ARM_BUILTIN_TMIAPH);
16597   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmiabb", di_ftype_di_int_int, ARM_BUILTIN_TMIABB);
16598   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmiabt", di_ftype_di_int_int, ARM_BUILTIN_TMIABT);
16599   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmiatb", di_ftype_di_int_int, ARM_BUILTIN_TMIATB);
16600   def_mbuiltin (FL_IWMMXT, "__builtin_arm_tmiatt", di_ftype_di_int_int, ARM_BUILTIN_TMIATT);
16601 }
16602
16603 static void
16604 arm_init_tls_builtins (void)
16605 {
16606   tree ftype, decl;
16607
16608   ftype = build_function_type (ptr_type_node, void_list_node);
16609   decl = add_builtin_function ("__builtin_thread_pointer", ftype,
16610                                ARM_BUILTIN_THREAD_POINTER, BUILT_IN_MD,
16611                                NULL, NULL_TREE);
16612   TREE_NOTHROW (decl) = 1;
16613   TREE_READONLY (decl) = 1;
16614 }
16615
16616 enum neon_builtin_type_bits {
16617   T_V8QI  = 0x0001,
16618   T_V4HI  = 0x0002,
16619   T_V2SI  = 0x0004,
16620   T_V2SF  = 0x0008,
16621   T_DI    = 0x0010,
16622   T_V16QI = 0x0020,
16623   T_V8HI  = 0x0040,
16624   T_V4SI  = 0x0080,
16625   T_V4SF  = 0x0100,
16626   T_V2DI  = 0x0200,
16627   T_TI    = 0x0400,
16628   T_EI    = 0x0800,
16629   T_OI    = 0x1000
16630 };
16631
16632 #define v8qi_UP  T_V8QI
16633 #define v4hi_UP  T_V4HI
16634 #define v2si_UP  T_V2SI
16635 #define v2sf_UP  T_V2SF
16636 #define di_UP    T_DI
16637 #define v16qi_UP T_V16QI
16638 #define v8hi_UP  T_V8HI
16639 #define v4si_UP  T_V4SI
16640 #define v4sf_UP  T_V4SF
16641 #define v2di_UP  T_V2DI
16642 #define ti_UP    T_TI
16643 #define ei_UP    T_EI
16644 #define oi_UP    T_OI
16645
16646 #define UP(X) X##_UP
16647
16648 #define T_MAX 13
16649
16650 typedef enum {
16651   NEON_BINOP,
16652   NEON_TERNOP,
16653   NEON_UNOP,
16654   NEON_GETLANE,
16655   NEON_SETLANE,
16656   NEON_CREATE,
16657   NEON_DUP,
16658   NEON_DUPLANE,
16659   NEON_COMBINE,
16660   NEON_SPLIT,
16661   NEON_LANEMUL,
16662   NEON_LANEMULL,
16663   NEON_LANEMULH,
16664   NEON_LANEMAC,
16665   NEON_SCALARMUL,
16666   NEON_SCALARMULL,
16667   NEON_SCALARMULH,
16668   NEON_SCALARMAC,
16669   NEON_CONVERT,
16670   NEON_FIXCONV,
16671   NEON_SELECT,
16672   NEON_RESULTPAIR,
16673   NEON_REINTERP,
16674   NEON_VTBL,
16675   NEON_VTBX,
16676   NEON_LOAD1,
16677   NEON_LOAD1LANE,
16678   NEON_STORE1,
16679   NEON_STORE1LANE,
16680   NEON_LOADSTRUCT,
16681   NEON_LOADSTRUCTLANE,
16682   NEON_STORESTRUCT,
16683   NEON_STORESTRUCTLANE,
16684   NEON_LOGICBINOP,
16685   NEON_SHIFTINSERT,
16686   NEON_SHIFTIMM,
16687   NEON_SHIFTACC
16688 } neon_itype;
16689
16690 typedef struct {
16691   const char *name;
16692   const neon_itype itype;
16693   const int bits;
16694   const enum insn_code codes[T_MAX];
16695   const unsigned int num_vars;
16696   unsigned int base_fcode;
16697 } neon_builtin_datum;
16698
16699 #define CF(N,X) CODE_FOR_neon_##N##X
16700
16701 #define VAR1(T, N, A) \
16702   #N, NEON_##T, UP (A), { CF (N, A) }, 1, 0
16703 #define VAR2(T, N, A, B) \
16704   #N, NEON_##T, UP (A) | UP (B), { CF (N, A), CF (N, B) }, 2, 0
16705 #define VAR3(T, N, A, B, C) \
16706   #N, NEON_##T, UP (A) | UP (B) | UP (C), \
16707   { CF (N, A), CF (N, B), CF (N, C) }, 3, 0
16708 #define VAR4(T, N, A, B, C, D) \
16709   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D), \
16710   { CF (N, A), CF (N, B), CF (N, C), CF (N, D) }, 4, 0
16711 #define VAR5(T, N, A, B, C, D, E) \
16712   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E), \
16713   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E) }, 5, 0
16714 #define VAR6(T, N, A, B, C, D, E, F) \
16715   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E) | UP (F), \
16716   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E), CF (N, F) }, 6, 0
16717 #define VAR7(T, N, A, B, C, D, E, F, G) \
16718   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E) | UP (F) | UP (G), \
16719   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E), CF (N, F), \
16720     CF (N, G) }, 7, 0
16721 #define VAR8(T, N, A, B, C, D, E, F, G, H) \
16722   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E) | UP (F) | UP (G) \
16723                 | UP (H), \
16724   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E), CF (N, F), \
16725     CF (N, G), CF (N, H) }, 8, 0
16726 #define VAR9(T, N, A, B, C, D, E, F, G, H, I) \
16727   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E) | UP (F) | UP (G) \
16728                 | UP (H) | UP (I), \
16729   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E), CF (N, F), \
16730     CF (N, G), CF (N, H), CF (N, I) }, 9, 0
16731 #define VAR10(T, N, A, B, C, D, E, F, G, H, I, J) \
16732   #N, NEON_##T, UP (A) | UP (B) | UP (C) | UP (D) | UP (E) | UP (F) | UP (G) \
16733                 | UP (H) | UP (I) | UP (J), \
16734   { CF (N, A), CF (N, B), CF (N, C), CF (N, D), CF (N, E), CF (N, F), \
16735     CF (N, G), CF (N, H), CF (N, I), CF (N, J) }, 10, 0
16736
16737 /* The mode entries in the following table correspond to the "key" type of the
16738    instruction variant, i.e. equivalent to that which would be specified after
16739    the assembler mnemonic, which usually refers to the last vector operand.
16740    (Signed/unsigned/polynomial types are not differentiated between though, and
16741    are all mapped onto the same mode for a given element size.) The modes
16742    listed per instruction should be the same as those defined for that
16743    instruction's pattern in neon.md.
16744    WARNING: Variants should be listed in the same increasing order as
16745    neon_builtin_type_bits.  */
16746
16747 static neon_builtin_datum neon_builtin_data[] =
16748 {
16749   { VAR10 (BINOP, vadd,
16750            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16751   { VAR3 (BINOP, vaddl, v8qi, v4hi, v2si) },
16752   { VAR3 (BINOP, vaddw, v8qi, v4hi, v2si) },
16753   { VAR6 (BINOP, vhadd, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16754   { VAR8 (BINOP, vqadd, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16755   { VAR3 (BINOP, vaddhn, v8hi, v4si, v2di) },
16756   { VAR8 (BINOP, vmul, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16757   { VAR8 (TERNOP, vmla, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16758   { VAR3 (TERNOP, vmlal, v8qi, v4hi, v2si) },
16759   { VAR8 (TERNOP, vmls, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16760   { VAR3 (TERNOP, vmlsl, v8qi, v4hi, v2si) },
16761   { VAR4 (BINOP, vqdmulh, v4hi, v2si, v8hi, v4si) },
16762   { VAR2 (TERNOP, vqdmlal, v4hi, v2si) },
16763   { VAR2 (TERNOP, vqdmlsl, v4hi, v2si) },
16764   { VAR3 (BINOP, vmull, v8qi, v4hi, v2si) },
16765   { VAR2 (SCALARMULL, vmull_n, v4hi, v2si) },
16766   { VAR2 (LANEMULL, vmull_lane, v4hi, v2si) },
16767   { VAR2 (SCALARMULL, vqdmull_n, v4hi, v2si) },
16768   { VAR2 (LANEMULL, vqdmull_lane, v4hi, v2si) },
16769   { VAR4 (SCALARMULH, vqdmulh_n, v4hi, v2si, v8hi, v4si) },
16770   { VAR4 (LANEMULH, vqdmulh_lane, v4hi, v2si, v8hi, v4si) },
16771   { VAR2 (BINOP, vqdmull, v4hi, v2si) },
16772   { VAR8 (BINOP, vshl, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16773   { VAR8 (BINOP, vqshl, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16774   { VAR8 (SHIFTIMM, vshr_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16775   { VAR3 (SHIFTIMM, vshrn_n, v8hi, v4si, v2di) },
16776   { VAR3 (SHIFTIMM, vqshrn_n, v8hi, v4si, v2di) },
16777   { VAR3 (SHIFTIMM, vqshrun_n, v8hi, v4si, v2di) },
16778   { VAR8 (SHIFTIMM, vshl_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16779   { VAR8 (SHIFTIMM, vqshl_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16780   { VAR8 (SHIFTIMM, vqshlu_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16781   { VAR3 (SHIFTIMM, vshll_n, v8qi, v4hi, v2si) },
16782   { VAR8 (SHIFTACC, vsra_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16783   { VAR10 (BINOP, vsub,
16784            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16785   { VAR3 (BINOP, vsubl, v8qi, v4hi, v2si) },
16786   { VAR3 (BINOP, vsubw, v8qi, v4hi, v2si) },
16787   { VAR8 (BINOP, vqsub, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16788   { VAR6 (BINOP, vhsub, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16789   { VAR3 (BINOP, vsubhn, v8hi, v4si, v2di) },
16790   { VAR8 (BINOP, vceq, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16791   { VAR8 (BINOP, vcge, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16792   { VAR8 (BINOP, vcgt, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16793   { VAR2 (BINOP, vcage, v2sf, v4sf) },
16794   { VAR2 (BINOP, vcagt, v2sf, v4sf) },
16795   { VAR6 (BINOP, vtst, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16796   { VAR8 (BINOP, vabd, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16797   { VAR3 (BINOP, vabdl, v8qi, v4hi, v2si) },
16798   { VAR6 (TERNOP, vaba, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16799   { VAR3 (TERNOP, vabal, v8qi, v4hi, v2si) },
16800   { VAR8 (BINOP, vmax, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16801   { VAR8 (BINOP, vmin, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16802   { VAR4 (BINOP, vpadd, v8qi, v4hi, v2si, v2sf) },
16803   { VAR6 (UNOP, vpaddl, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16804   { VAR6 (BINOP, vpadal, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16805   { VAR4 (BINOP, vpmax, v8qi, v4hi, v2si, v2sf) },
16806   { VAR4 (BINOP, vpmin, v8qi, v4hi, v2si, v2sf) },
16807   { VAR2 (BINOP, vrecps, v2sf, v4sf) },
16808   { VAR2 (BINOP, vrsqrts, v2sf, v4sf) },
16809   { VAR8 (SHIFTINSERT, vsri_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16810   { VAR8 (SHIFTINSERT, vsli_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di) },
16811   { VAR8 (UNOP, vabs, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16812   { VAR6 (UNOP, vqabs, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16813   { VAR8 (UNOP, vneg, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16814   { VAR6 (UNOP, vqneg, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16815   { VAR6 (UNOP, vcls, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16816   { VAR6 (UNOP, vclz, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16817   { VAR2 (UNOP, vcnt, v8qi, v16qi) },
16818   { VAR4 (UNOP, vrecpe, v2si, v2sf, v4si, v4sf) },
16819   { VAR4 (UNOP, vrsqrte, v2si, v2sf, v4si, v4sf) },
16820   { VAR6 (UNOP, vmvn, v8qi, v4hi, v2si, v16qi, v8hi, v4si) },
16821   /* FIXME: vget_lane supports more variants than this!  */
16822   { VAR10 (GETLANE, vget_lane,
16823            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16824   { VAR10 (SETLANE, vset_lane,
16825            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16826   { VAR5 (CREATE, vcreate, v8qi, v4hi, v2si, v2sf, di) },
16827   { VAR10 (DUP, vdup_n,
16828            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16829   { VAR10 (DUPLANE, vdup_lane,
16830            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16831   { VAR5 (COMBINE, vcombine, v8qi, v4hi, v2si, v2sf, di) },
16832   { VAR5 (SPLIT, vget_high, v16qi, v8hi, v4si, v4sf, v2di) },
16833   { VAR5 (SPLIT, vget_low, v16qi, v8hi, v4si, v4sf, v2di) },
16834   { VAR3 (UNOP, vmovn, v8hi, v4si, v2di) },
16835   { VAR3 (UNOP, vqmovn, v8hi, v4si, v2di) },
16836   { VAR3 (UNOP, vqmovun, v8hi, v4si, v2di) },
16837   { VAR3 (UNOP, vmovl, v8qi, v4hi, v2si) },
16838   { VAR6 (LANEMUL, vmul_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16839   { VAR6 (LANEMAC, vmla_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16840   { VAR2 (LANEMAC, vmlal_lane, v4hi, v2si) },
16841   { VAR2 (LANEMAC, vqdmlal_lane, v4hi, v2si) },
16842   { VAR6 (LANEMAC, vmls_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16843   { VAR2 (LANEMAC, vmlsl_lane, v4hi, v2si) },
16844   { VAR2 (LANEMAC, vqdmlsl_lane, v4hi, v2si) },
16845   { VAR6 (SCALARMUL, vmul_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16846   { VAR6 (SCALARMAC, vmla_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16847   { VAR2 (SCALARMAC, vmlal_n, v4hi, v2si) },
16848   { VAR2 (SCALARMAC, vqdmlal_n, v4hi, v2si) },
16849   { VAR6 (SCALARMAC, vmls_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16850   { VAR2 (SCALARMAC, vmlsl_n, v4hi, v2si) },
16851   { VAR2 (SCALARMAC, vqdmlsl_n, v4hi, v2si) },
16852   { VAR10 (BINOP, vext,
16853            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16854   { VAR8 (UNOP, vrev64, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16855   { VAR4 (UNOP, vrev32, v8qi, v4hi, v16qi, v8hi) },
16856   { VAR2 (UNOP, vrev16, v8qi, v16qi) },
16857   { VAR4 (CONVERT, vcvt, v2si, v2sf, v4si, v4sf) },
16858   { VAR4 (FIXCONV, vcvt_n, v2si, v2sf, v4si, v4sf) },
16859   { VAR10 (SELECT, vbsl,
16860            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16861   { VAR1 (VTBL, vtbl1, v8qi) },
16862   { VAR1 (VTBL, vtbl2, v8qi) },
16863   { VAR1 (VTBL, vtbl3, v8qi) },
16864   { VAR1 (VTBL, vtbl4, v8qi) },
16865   { VAR1 (VTBX, vtbx1, v8qi) },
16866   { VAR1 (VTBX, vtbx2, v8qi) },
16867   { VAR1 (VTBX, vtbx3, v8qi) },
16868   { VAR1 (VTBX, vtbx4, v8qi) },
16869   { VAR8 (RESULTPAIR, vtrn, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16870   { VAR8 (RESULTPAIR, vzip, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16871   { VAR8 (RESULTPAIR, vuzp, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf) },
16872   { VAR5 (REINTERP, vreinterpretv8qi, v8qi, v4hi, v2si, v2sf, di) },
16873   { VAR5 (REINTERP, vreinterpretv4hi, v8qi, v4hi, v2si, v2sf, di) },
16874   { VAR5 (REINTERP, vreinterpretv2si, v8qi, v4hi, v2si, v2sf, di) },
16875   { VAR5 (REINTERP, vreinterpretv2sf, v8qi, v4hi, v2si, v2sf, di) },
16876   { VAR5 (REINTERP, vreinterpretdi, v8qi, v4hi, v2si, v2sf, di) },
16877   { VAR5 (REINTERP, vreinterpretv16qi, v16qi, v8hi, v4si, v4sf, v2di) },
16878   { VAR5 (REINTERP, vreinterpretv8hi, v16qi, v8hi, v4si, v4sf, v2di) },
16879   { VAR5 (REINTERP, vreinterpretv4si, v16qi, v8hi, v4si, v4sf, v2di) },
16880   { VAR5 (REINTERP, vreinterpretv4sf, v16qi, v8hi, v4si, v4sf, v2di) },
16881   { VAR5 (REINTERP, vreinterpretv2di, v16qi, v8hi, v4si, v4sf, v2di) },
16882   { VAR10 (LOAD1, vld1,
16883            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16884   { VAR10 (LOAD1LANE, vld1_lane,
16885            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16886   { VAR10 (LOAD1, vld1_dup,
16887            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16888   { VAR10 (STORE1, vst1,
16889            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16890   { VAR10 (STORE1LANE, vst1_lane,
16891            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16892   { VAR9 (LOADSTRUCT,
16893           vld2, v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16894   { VAR7 (LOADSTRUCTLANE, vld2_lane,
16895           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16896   { VAR5 (LOADSTRUCT, vld2_dup, v8qi, v4hi, v2si, v2sf, di) },
16897   { VAR9 (STORESTRUCT, vst2,
16898           v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16899   { VAR7 (STORESTRUCTLANE, vst2_lane,
16900           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16901   { VAR9 (LOADSTRUCT,
16902           vld3, v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16903   { VAR7 (LOADSTRUCTLANE, vld3_lane,
16904           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16905   { VAR5 (LOADSTRUCT, vld3_dup, v8qi, v4hi, v2si, v2sf, di) },
16906   { VAR9 (STORESTRUCT, vst3,
16907           v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16908   { VAR7 (STORESTRUCTLANE, vst3_lane,
16909           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16910   { VAR9 (LOADSTRUCT, vld4,
16911           v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16912   { VAR7 (LOADSTRUCTLANE, vld4_lane,
16913           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16914   { VAR5 (LOADSTRUCT, vld4_dup, v8qi, v4hi, v2si, v2sf, di) },
16915   { VAR9 (STORESTRUCT, vst4,
16916           v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf) },
16917   { VAR7 (STORESTRUCTLANE, vst4_lane,
16918           v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf) },
16919   { VAR10 (LOGICBINOP, vand,
16920            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16921   { VAR10 (LOGICBINOP, vorr,
16922            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16923   { VAR10 (BINOP, veor,
16924            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16925   { VAR10 (LOGICBINOP, vbic,
16926            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) },
16927   { VAR10 (LOGICBINOP, vorn,
16928            v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di) }
16929 };
16930
16931 #undef CF
16932 #undef VAR1
16933 #undef VAR2
16934 #undef VAR3
16935 #undef VAR4
16936 #undef VAR5
16937 #undef VAR6
16938 #undef VAR7
16939 #undef VAR8
16940 #undef VAR9
16941 #undef VAR10
16942
16943 static void
16944 arm_init_neon_builtins (void)
16945 {
16946   unsigned int i, fcode = ARM_BUILTIN_NEON_BASE;
16947
16948   tree neon_intQI_type_node;
16949   tree neon_intHI_type_node;
16950   tree neon_polyQI_type_node;
16951   tree neon_polyHI_type_node;
16952   tree neon_intSI_type_node;
16953   tree neon_intDI_type_node;
16954   tree neon_float_type_node;
16955
16956   tree intQI_pointer_node;
16957   tree intHI_pointer_node;
16958   tree intSI_pointer_node;
16959   tree intDI_pointer_node;
16960   tree float_pointer_node;
16961
16962   tree const_intQI_node;
16963   tree const_intHI_node;
16964   tree const_intSI_node;
16965   tree const_intDI_node;
16966   tree const_float_node;
16967
16968   tree const_intQI_pointer_node;
16969   tree const_intHI_pointer_node;
16970   tree const_intSI_pointer_node;
16971   tree const_intDI_pointer_node;
16972   tree const_float_pointer_node;
16973
16974   tree V8QI_type_node;
16975   tree V4HI_type_node;
16976   tree V2SI_type_node;
16977   tree V2SF_type_node;
16978   tree V16QI_type_node;
16979   tree V8HI_type_node;
16980   tree V4SI_type_node;
16981   tree V4SF_type_node;
16982   tree V2DI_type_node;
16983
16984   tree intUQI_type_node;
16985   tree intUHI_type_node;
16986   tree intUSI_type_node;
16987   tree intUDI_type_node;
16988
16989   tree intEI_type_node;
16990   tree intOI_type_node;
16991   tree intCI_type_node;
16992   tree intXI_type_node;
16993
16994   tree V8QI_pointer_node;
16995   tree V4HI_pointer_node;
16996   tree V2SI_pointer_node;
16997   tree V2SF_pointer_node;
16998   tree V16QI_pointer_node;
16999   tree V8HI_pointer_node;
17000   tree V4SI_pointer_node;
17001   tree V4SF_pointer_node;
17002   tree V2DI_pointer_node;
17003
17004   tree void_ftype_pv8qi_v8qi_v8qi;
17005   tree void_ftype_pv4hi_v4hi_v4hi;
17006   tree void_ftype_pv2si_v2si_v2si;
17007   tree void_ftype_pv2sf_v2sf_v2sf;
17008   tree void_ftype_pdi_di_di;
17009   tree void_ftype_pv16qi_v16qi_v16qi;
17010   tree void_ftype_pv8hi_v8hi_v8hi;
17011   tree void_ftype_pv4si_v4si_v4si;
17012   tree void_ftype_pv4sf_v4sf_v4sf;
17013   tree void_ftype_pv2di_v2di_v2di;
17014
17015   tree reinterp_ftype_dreg[5][5];
17016   tree reinterp_ftype_qreg[5][5];
17017   tree dreg_types[5], qreg_types[5];
17018
17019   /* Create distinguished type nodes for NEON vector element types,
17020      and pointers to values of such types, so we can detect them later.  */
17021   neon_intQI_type_node = make_signed_type (GET_MODE_PRECISION (QImode));
17022   neon_intHI_type_node = make_signed_type (GET_MODE_PRECISION (HImode));
17023   neon_polyQI_type_node = make_signed_type (GET_MODE_PRECISION (QImode));
17024   neon_polyHI_type_node = make_signed_type (GET_MODE_PRECISION (HImode));
17025   neon_intSI_type_node = make_signed_type (GET_MODE_PRECISION (SImode));
17026   neon_intDI_type_node = make_signed_type (GET_MODE_PRECISION (DImode));
17027   neon_float_type_node = make_node (REAL_TYPE);
17028   TYPE_PRECISION (neon_float_type_node) = FLOAT_TYPE_SIZE;
17029   layout_type (neon_float_type_node);
17030
17031   /* Define typedefs which exactly correspond to the modes we are basing vector
17032      types on.  If you change these names you'll need to change
17033      the table used by arm_mangle_type too.  */
17034   (*lang_hooks.types.register_builtin_type) (neon_intQI_type_node,
17035                                              "__builtin_neon_qi");
17036   (*lang_hooks.types.register_builtin_type) (neon_intHI_type_node,
17037                                              "__builtin_neon_hi");
17038   (*lang_hooks.types.register_builtin_type) (neon_intSI_type_node,
17039                                              "__builtin_neon_si");
17040   (*lang_hooks.types.register_builtin_type) (neon_float_type_node,
17041                                              "__builtin_neon_sf");
17042   (*lang_hooks.types.register_builtin_type) (neon_intDI_type_node,
17043                                              "__builtin_neon_di");
17044   (*lang_hooks.types.register_builtin_type) (neon_polyQI_type_node,
17045                                              "__builtin_neon_poly8");
17046   (*lang_hooks.types.register_builtin_type) (neon_polyHI_type_node,
17047                                              "__builtin_neon_poly16");
17048
17049   intQI_pointer_node = build_pointer_type (neon_intQI_type_node);
17050   intHI_pointer_node = build_pointer_type (neon_intHI_type_node);
17051   intSI_pointer_node = build_pointer_type (neon_intSI_type_node);
17052   intDI_pointer_node = build_pointer_type (neon_intDI_type_node);
17053   float_pointer_node = build_pointer_type (neon_float_type_node);
17054
17055   /* Next create constant-qualified versions of the above types.  */
17056   const_intQI_node = build_qualified_type (neon_intQI_type_node,
17057                                            TYPE_QUAL_CONST);
17058   const_intHI_node = build_qualified_type (neon_intHI_type_node,
17059                                            TYPE_QUAL_CONST);
17060   const_intSI_node = build_qualified_type (neon_intSI_type_node,
17061                                            TYPE_QUAL_CONST);
17062   const_intDI_node = build_qualified_type (neon_intDI_type_node,
17063                                            TYPE_QUAL_CONST);
17064   const_float_node = build_qualified_type (neon_float_type_node,
17065                                            TYPE_QUAL_CONST);
17066
17067   const_intQI_pointer_node = build_pointer_type (const_intQI_node);
17068   const_intHI_pointer_node = build_pointer_type (const_intHI_node);
17069   const_intSI_pointer_node = build_pointer_type (const_intSI_node);
17070   const_intDI_pointer_node = build_pointer_type (const_intDI_node);
17071   const_float_pointer_node = build_pointer_type (const_float_node);
17072
17073   /* Now create vector types based on our NEON element types.  */
17074   /* 64-bit vectors.  */
17075   V8QI_type_node =
17076     build_vector_type_for_mode (neon_intQI_type_node, V8QImode);
17077   V4HI_type_node =
17078     build_vector_type_for_mode (neon_intHI_type_node, V4HImode);
17079   V2SI_type_node =
17080     build_vector_type_for_mode (neon_intSI_type_node, V2SImode);
17081   V2SF_type_node =
17082     build_vector_type_for_mode (neon_float_type_node, V2SFmode);
17083   /* 128-bit vectors.  */
17084   V16QI_type_node =
17085     build_vector_type_for_mode (neon_intQI_type_node, V16QImode);
17086   V8HI_type_node =
17087     build_vector_type_for_mode (neon_intHI_type_node, V8HImode);
17088   V4SI_type_node =
17089     build_vector_type_for_mode (neon_intSI_type_node, V4SImode);
17090   V4SF_type_node =
17091     build_vector_type_for_mode (neon_float_type_node, V4SFmode);
17092   V2DI_type_node =
17093     build_vector_type_for_mode (neon_intDI_type_node, V2DImode);
17094
17095   /* Unsigned integer types for various mode sizes.  */
17096   intUQI_type_node = make_unsigned_type (GET_MODE_PRECISION (QImode));
17097   intUHI_type_node = make_unsigned_type (GET_MODE_PRECISION (HImode));
17098   intUSI_type_node = make_unsigned_type (GET_MODE_PRECISION (SImode));
17099   intUDI_type_node = make_unsigned_type (GET_MODE_PRECISION (DImode));
17100
17101   (*lang_hooks.types.register_builtin_type) (intUQI_type_node,
17102                                              "__builtin_neon_uqi");
17103   (*lang_hooks.types.register_builtin_type) (intUHI_type_node,
17104                                              "__builtin_neon_uhi");
17105   (*lang_hooks.types.register_builtin_type) (intUSI_type_node,
17106                                              "__builtin_neon_usi");
17107   (*lang_hooks.types.register_builtin_type) (intUDI_type_node,
17108                                              "__builtin_neon_udi");
17109
17110   /* Opaque integer types for structures of vectors.  */
17111   intEI_type_node = make_signed_type (GET_MODE_PRECISION (EImode));
17112   intOI_type_node = make_signed_type (GET_MODE_PRECISION (OImode));
17113   intCI_type_node = make_signed_type (GET_MODE_PRECISION (CImode));
17114   intXI_type_node = make_signed_type (GET_MODE_PRECISION (XImode));
17115
17116   (*lang_hooks.types.register_builtin_type) (intTI_type_node,
17117                                              "__builtin_neon_ti");
17118   (*lang_hooks.types.register_builtin_type) (intEI_type_node,
17119                                              "__builtin_neon_ei");
17120   (*lang_hooks.types.register_builtin_type) (intOI_type_node,
17121                                              "__builtin_neon_oi");
17122   (*lang_hooks.types.register_builtin_type) (intCI_type_node,
17123                                              "__builtin_neon_ci");
17124   (*lang_hooks.types.register_builtin_type) (intXI_type_node,
17125                                              "__builtin_neon_xi");
17126
17127   /* Pointers to vector types.  */
17128   V8QI_pointer_node = build_pointer_type (V8QI_type_node);
17129   V4HI_pointer_node = build_pointer_type (V4HI_type_node);
17130   V2SI_pointer_node = build_pointer_type (V2SI_type_node);
17131   V2SF_pointer_node = build_pointer_type (V2SF_type_node);
17132   V16QI_pointer_node = build_pointer_type (V16QI_type_node);
17133   V8HI_pointer_node = build_pointer_type (V8HI_type_node);
17134   V4SI_pointer_node = build_pointer_type (V4SI_type_node);
17135   V4SF_pointer_node = build_pointer_type (V4SF_type_node);
17136   V2DI_pointer_node = build_pointer_type (V2DI_type_node);
17137
17138   /* Operations which return results as pairs.  */
17139   void_ftype_pv8qi_v8qi_v8qi =
17140     build_function_type_list (void_type_node, V8QI_pointer_node, V8QI_type_node,
17141                               V8QI_type_node, NULL);
17142   void_ftype_pv4hi_v4hi_v4hi =
17143     build_function_type_list (void_type_node, V4HI_pointer_node, V4HI_type_node,
17144                               V4HI_type_node, NULL);
17145   void_ftype_pv2si_v2si_v2si =
17146     build_function_type_list (void_type_node, V2SI_pointer_node, V2SI_type_node,
17147                               V2SI_type_node, NULL);
17148   void_ftype_pv2sf_v2sf_v2sf =
17149     build_function_type_list (void_type_node, V2SF_pointer_node, V2SF_type_node,
17150                               V2SF_type_node, NULL);
17151   void_ftype_pdi_di_di =
17152     build_function_type_list (void_type_node, intDI_pointer_node,
17153                               neon_intDI_type_node, neon_intDI_type_node, NULL);
17154   void_ftype_pv16qi_v16qi_v16qi =
17155     build_function_type_list (void_type_node, V16QI_pointer_node,
17156                               V16QI_type_node, V16QI_type_node, NULL);
17157   void_ftype_pv8hi_v8hi_v8hi =
17158     build_function_type_list (void_type_node, V8HI_pointer_node, V8HI_type_node,
17159                               V8HI_type_node, NULL);
17160   void_ftype_pv4si_v4si_v4si =
17161     build_function_type_list (void_type_node, V4SI_pointer_node, V4SI_type_node,
17162                               V4SI_type_node, NULL);
17163   void_ftype_pv4sf_v4sf_v4sf =
17164     build_function_type_list (void_type_node, V4SF_pointer_node, V4SF_type_node,
17165                               V4SF_type_node, NULL);
17166   void_ftype_pv2di_v2di_v2di =
17167     build_function_type_list (void_type_node, V2DI_pointer_node, V2DI_type_node,
17168                               V2DI_type_node, NULL);
17169
17170   dreg_types[0] = V8QI_type_node;
17171   dreg_types[1] = V4HI_type_node;
17172   dreg_types[2] = V2SI_type_node;
17173   dreg_types[3] = V2SF_type_node;
17174   dreg_types[4] = neon_intDI_type_node;
17175
17176   qreg_types[0] = V16QI_type_node;
17177   qreg_types[1] = V8HI_type_node;
17178   qreg_types[2] = V4SI_type_node;
17179   qreg_types[3] = V4SF_type_node;
17180   qreg_types[4] = V2DI_type_node;
17181
17182   for (i = 0; i < 5; i++)
17183     {
17184       int j;
17185       for (j = 0; j < 5; j++)
17186         {
17187           reinterp_ftype_dreg[i][j]
17188             = build_function_type_list (dreg_types[i], dreg_types[j], NULL);
17189           reinterp_ftype_qreg[i][j]
17190             = build_function_type_list (qreg_types[i], qreg_types[j], NULL);
17191         }
17192     }
17193
17194   for (i = 0; i < ARRAY_SIZE (neon_builtin_data); i++)
17195     {
17196       neon_builtin_datum *d = &neon_builtin_data[i];
17197       unsigned int j, codeidx = 0;
17198
17199       d->base_fcode = fcode;
17200
17201       for (j = 0; j < T_MAX; j++)
17202         {
17203           const char* const modenames[] = {
17204             "v8qi", "v4hi", "v2si", "v2sf", "di",
17205             "v16qi", "v8hi", "v4si", "v4sf", "v2di"
17206           };
17207           char namebuf[60];
17208           tree ftype = NULL;
17209           enum insn_code icode;
17210           int is_load = 0, is_store = 0;
17211
17212           if ((d->bits & (1 << j)) == 0)
17213             continue;
17214
17215           icode = d->codes[codeidx++];
17216
17217           switch (d->itype)
17218             {
17219             case NEON_LOAD1:
17220             case NEON_LOAD1LANE:
17221             case NEON_LOADSTRUCT:
17222             case NEON_LOADSTRUCTLANE:
17223               is_load = 1;
17224               /* Fall through.  */
17225             case NEON_STORE1:
17226             case NEON_STORE1LANE:
17227             case NEON_STORESTRUCT:
17228             case NEON_STORESTRUCTLANE:
17229               if (!is_load)
17230                 is_store = 1;
17231               /* Fall through.  */
17232             case NEON_UNOP:
17233             case NEON_BINOP:
17234             case NEON_LOGICBINOP:
17235             case NEON_SHIFTINSERT:
17236             case NEON_TERNOP:
17237             case NEON_GETLANE:
17238             case NEON_SETLANE:
17239             case NEON_CREATE:
17240             case NEON_DUP:
17241             case NEON_DUPLANE:
17242             case NEON_SHIFTIMM:
17243             case NEON_SHIFTACC:
17244             case NEON_COMBINE:
17245             case NEON_SPLIT:
17246             case NEON_CONVERT:
17247             case NEON_FIXCONV:
17248             case NEON_LANEMUL:
17249             case NEON_LANEMULL:
17250             case NEON_LANEMULH:
17251             case NEON_LANEMAC:
17252             case NEON_SCALARMUL:
17253             case NEON_SCALARMULL:
17254             case NEON_SCALARMULH:
17255             case NEON_SCALARMAC:
17256             case NEON_SELECT:
17257             case NEON_VTBL:
17258             case NEON_VTBX:
17259               {
17260                 int k;
17261                 tree return_type = void_type_node, args = void_list_node;
17262
17263                 /* Build a function type directly from the insn_data for this
17264                    builtin.  The build_function_type() function takes care of
17265                    removing duplicates for us.  */
17266                 for (k = insn_data[icode].n_operands - 1; k >= 0; k--)
17267                   {
17268                     tree eltype;
17269
17270                     if (is_load && k == 1)
17271                       {
17272                         /* Neon load patterns always have the memory operand
17273                            (a SImode pointer) in the operand 1 position.  We
17274                            want a const pointer to the element type in that
17275                            position.  */
17276                         gcc_assert (insn_data[icode].operand[k].mode == SImode);
17277
17278                         switch (1 << j)
17279                           {
17280                           case T_V8QI:
17281                           case T_V16QI:
17282                             eltype = const_intQI_pointer_node;
17283                             break;
17284
17285                           case T_V4HI:
17286                           case T_V8HI:
17287                             eltype = const_intHI_pointer_node;
17288                             break;
17289
17290                           case T_V2SI:
17291                           case T_V4SI:
17292                             eltype = const_intSI_pointer_node;
17293                             break;
17294
17295                           case T_V2SF:
17296                           case T_V4SF:
17297                             eltype = const_float_pointer_node;
17298                             break;
17299
17300                           case T_DI:
17301                           case T_V2DI:
17302                             eltype = const_intDI_pointer_node;
17303                             break;
17304
17305                           default: gcc_unreachable ();
17306                           }
17307                       }
17308                     else if (is_store && k == 0)
17309                       {
17310                         /* Similarly, Neon store patterns use operand 0 as
17311                            the memory location to store to (a SImode pointer).
17312                            Use a pointer to the element type of the store in
17313                            that position.  */
17314                         gcc_assert (insn_data[icode].operand[k].mode == SImode);
17315
17316                         switch (1 << j)
17317                           {
17318                           case T_V8QI:
17319                           case T_V16QI:
17320                             eltype = intQI_pointer_node;
17321                             break;
17322
17323                           case T_V4HI:
17324                           case T_V8HI:
17325                             eltype = intHI_pointer_node;
17326                             break;
17327
17328                           case T_V2SI:
17329                           case T_V4SI:
17330                             eltype = intSI_pointer_node;
17331                             break;
17332
17333                           case T_V2SF:
17334                           case T_V4SF:
17335                             eltype = float_pointer_node;
17336                             break;
17337
17338                           case T_DI:
17339                           case T_V2DI:
17340                             eltype = intDI_pointer_node;
17341                             break;
17342
17343                           default: gcc_unreachable ();
17344                           }
17345                       }
17346                     else
17347                       {
17348                         switch (insn_data[icode].operand[k].mode)
17349                           {
17350                           case VOIDmode: eltype = void_type_node; break;
17351                           /* Scalars.  */
17352                           case QImode: eltype = neon_intQI_type_node; break;
17353                           case HImode: eltype = neon_intHI_type_node; break;
17354                           case SImode: eltype = neon_intSI_type_node; break;
17355                           case SFmode: eltype = neon_float_type_node; break;
17356                           case DImode: eltype = neon_intDI_type_node; break;
17357                           case TImode: eltype = intTI_type_node; break;
17358                           case EImode: eltype = intEI_type_node; break;
17359                           case OImode: eltype = intOI_type_node; break;
17360                           case CImode: eltype = intCI_type_node; break;
17361                           case XImode: eltype = intXI_type_node; break;
17362                           /* 64-bit vectors.  */
17363                           case V8QImode: eltype = V8QI_type_node; break;
17364                           case V4HImode: eltype = V4HI_type_node; break;
17365                           case V2SImode: eltype = V2SI_type_node; break;
17366                           case V2SFmode: eltype = V2SF_type_node; break;
17367                           /* 128-bit vectors.  */
17368                           case V16QImode: eltype = V16QI_type_node; break;
17369                           case V8HImode: eltype = V8HI_type_node; break;
17370                           case V4SImode: eltype = V4SI_type_node; break;
17371                           case V4SFmode: eltype = V4SF_type_node; break;
17372                           case V2DImode: eltype = V2DI_type_node; break;
17373                           default: gcc_unreachable ();
17374                           }
17375                       }
17376
17377                     if (k == 0 && !is_store)
17378                       return_type = eltype;
17379                     else
17380                       args = tree_cons (NULL_TREE, eltype, args);
17381                   }
17382
17383                 ftype = build_function_type (return_type, args);
17384               }
17385               break;
17386
17387             case NEON_RESULTPAIR:
17388               {
17389                 switch (insn_data[icode].operand[1].mode)
17390                   {
17391                   case V8QImode: ftype = void_ftype_pv8qi_v8qi_v8qi; break;
17392                   case V4HImode: ftype = void_ftype_pv4hi_v4hi_v4hi; break;
17393                   case V2SImode: ftype = void_ftype_pv2si_v2si_v2si; break;
17394                   case V2SFmode: ftype = void_ftype_pv2sf_v2sf_v2sf; break;
17395                   case DImode: ftype = void_ftype_pdi_di_di; break;
17396                   case V16QImode: ftype = void_ftype_pv16qi_v16qi_v16qi; break;
17397                   case V8HImode: ftype = void_ftype_pv8hi_v8hi_v8hi; break;
17398                   case V4SImode: ftype = void_ftype_pv4si_v4si_v4si; break;
17399                   case V4SFmode: ftype = void_ftype_pv4sf_v4sf_v4sf; break;
17400                   case V2DImode: ftype = void_ftype_pv2di_v2di_v2di; break;
17401                   default: gcc_unreachable ();
17402                   }
17403               }
17404               break;
17405
17406             case NEON_REINTERP:
17407               {
17408                 /* We iterate over 5 doubleword types, then 5 quadword
17409                    types.  */
17410                 int rhs = j % 5;
17411                 switch (insn_data[icode].operand[0].mode)
17412                   {
17413                   case V8QImode: ftype = reinterp_ftype_dreg[0][rhs]; break;
17414                   case V4HImode: ftype = reinterp_ftype_dreg[1][rhs]; break;
17415                   case V2SImode: ftype = reinterp_ftype_dreg[2][rhs]; break;
17416                   case V2SFmode: ftype = reinterp_ftype_dreg[3][rhs]; break;
17417                   case DImode: ftype = reinterp_ftype_dreg[4][rhs]; break;
17418                   case V16QImode: ftype = reinterp_ftype_qreg[0][rhs]; break;
17419                   case V8HImode: ftype = reinterp_ftype_qreg[1][rhs]; break;
17420                   case V4SImode: ftype = reinterp_ftype_qreg[2][rhs]; break;
17421                   case V4SFmode: ftype = reinterp_ftype_qreg[3][rhs]; break;
17422                   case V2DImode: ftype = reinterp_ftype_qreg[4][rhs]; break;
17423                   default: gcc_unreachable ();
17424                   }
17425               }
17426               break;
17427
17428             default:
17429               gcc_unreachable ();
17430             }
17431
17432           gcc_assert (ftype != NULL);
17433
17434           sprintf (namebuf, "__builtin_neon_%s%s", d->name, modenames[j]);
17435
17436           add_builtin_function (namebuf, ftype, fcode++, BUILT_IN_MD, NULL,
17437                                 NULL_TREE);
17438         }
17439     }
17440 }
17441
17442 static void
17443 arm_init_fp16_builtins (void)
17444 {
17445   tree fp16_type = make_node (REAL_TYPE);
17446   TYPE_PRECISION (fp16_type) = 16;
17447   layout_type (fp16_type);
17448   (*lang_hooks.types.register_builtin_type) (fp16_type, "__fp16");
17449 }
17450
17451 static void
17452 arm_init_builtins (void)
17453 {
17454   arm_init_tls_builtins ();
17455
17456   if (TARGET_REALLY_IWMMXT)
17457     arm_init_iwmmxt_builtins ();
17458
17459   if (TARGET_NEON)
17460     arm_init_neon_builtins ();
17461
17462   if (arm_fp16_format)
17463     arm_init_fp16_builtins ();
17464 }
17465
17466 /* Implement TARGET_INVALID_PARAMETER_TYPE.  */
17467
17468 static const char *
17469 arm_invalid_parameter_type (const_tree t)
17470 {
17471   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
17472     return N_("function parameters cannot have __fp16 type");
17473   return NULL;
17474 }
17475
17476 /* Implement TARGET_INVALID_PARAMETER_TYPE.  */
17477
17478 static const char *
17479 arm_invalid_return_type (const_tree t)
17480 {
17481   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
17482     return N_("functions cannot return __fp16 type");
17483   return NULL;
17484 }
17485
17486 /* Implement TARGET_PROMOTED_TYPE.  */
17487
17488 static tree
17489 arm_promoted_type (const_tree t)
17490 {
17491   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
17492     return float_type_node;
17493   return NULL_TREE;
17494 }
17495
17496 /* Implement TARGET_CONVERT_TO_TYPE.
17497    Specifically, this hook implements the peculiarity of the ARM
17498    half-precision floating-point C semantics that requires conversions between
17499    __fp16 to or from double to do an intermediate conversion to float.  */
17500
17501 static tree
17502 arm_convert_to_type (tree type, tree expr)
17503 {
17504   tree fromtype = TREE_TYPE (expr);
17505   if (!SCALAR_FLOAT_TYPE_P (fromtype) || !SCALAR_FLOAT_TYPE_P (type))
17506     return NULL_TREE;
17507   if ((TYPE_PRECISION (fromtype) == 16 && TYPE_PRECISION (type) > 32)
17508       || (TYPE_PRECISION (type) == 16 && TYPE_PRECISION (fromtype) > 32))
17509     return convert (type, convert (float_type_node, expr));
17510   return NULL_TREE;
17511 }
17512
17513 /* Implement TARGET_SCALAR_MODE_SUPPORTED_P.
17514    This simply adds HFmode as a supported mode; even though we don't
17515    implement arithmetic on this type directly, it's supported by
17516    optabs conversions, much the way the double-word arithmetic is
17517    special-cased in the default hook.  */
17518
17519 static bool
17520 arm_scalar_mode_supported_p (enum machine_mode mode)
17521 {
17522   if (mode == HFmode)
17523     return (arm_fp16_format != ARM_FP16_FORMAT_NONE);
17524   else
17525     return default_scalar_mode_supported_p (mode);
17526 }
17527
17528 /* Errors in the source file can cause expand_expr to return const0_rtx
17529    where we expect a vector.  To avoid crashing, use one of the vector
17530    clear instructions.  */
17531
17532 static rtx
17533 safe_vector_operand (rtx x, enum machine_mode mode)
17534 {
17535   if (x != const0_rtx)
17536     return x;
17537   x = gen_reg_rtx (mode);
17538
17539   emit_insn (gen_iwmmxt_clrdi (mode == DImode ? x
17540                                : gen_rtx_SUBREG (DImode, x, 0)));
17541   return x;
17542 }
17543
17544 /* Subroutine of arm_expand_builtin to take care of binop insns.  */
17545
17546 static rtx
17547 arm_expand_binop_builtin (enum insn_code icode,
17548                           tree exp, rtx target)
17549 {
17550   rtx pat;
17551   tree arg0 = CALL_EXPR_ARG (exp, 0);
17552   tree arg1 = CALL_EXPR_ARG (exp, 1);
17553   rtx op0 = expand_normal (arg0);
17554   rtx op1 = expand_normal (arg1);
17555   enum machine_mode tmode = insn_data[icode].operand[0].mode;
17556   enum machine_mode mode0 = insn_data[icode].operand[1].mode;
17557   enum machine_mode mode1 = insn_data[icode].operand[2].mode;
17558
17559   if (VECTOR_MODE_P (mode0))
17560     op0 = safe_vector_operand (op0, mode0);
17561   if (VECTOR_MODE_P (mode1))
17562     op1 = safe_vector_operand (op1, mode1);
17563
17564   if (! target
17565       || GET_MODE (target) != tmode
17566       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
17567     target = gen_reg_rtx (tmode);
17568
17569   gcc_assert (GET_MODE (op0) == mode0 && GET_MODE (op1) == mode1);
17570
17571   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
17572     op0 = copy_to_mode_reg (mode0, op0);
17573   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
17574     op1 = copy_to_mode_reg (mode1, op1);
17575
17576   pat = GEN_FCN (icode) (target, op0, op1);
17577   if (! pat)
17578     return 0;
17579   emit_insn (pat);
17580   return target;
17581 }
17582
17583 /* Subroutine of arm_expand_builtin to take care of unop insns.  */
17584
17585 static rtx
17586 arm_expand_unop_builtin (enum insn_code icode,
17587                          tree exp, rtx target, int do_load)
17588 {
17589   rtx pat;
17590   tree arg0 = CALL_EXPR_ARG (exp, 0);
17591   rtx op0 = expand_normal (arg0);
17592   enum machine_mode tmode = insn_data[icode].operand[0].mode;
17593   enum machine_mode mode0 = insn_data[icode].operand[1].mode;
17594
17595   if (! target
17596       || GET_MODE (target) != tmode
17597       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
17598     target = gen_reg_rtx (tmode);
17599   if (do_load)
17600     op0 = gen_rtx_MEM (mode0, copy_to_mode_reg (Pmode, op0));
17601   else
17602     {
17603       if (VECTOR_MODE_P (mode0))
17604         op0 = safe_vector_operand (op0, mode0);
17605
17606       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
17607         op0 = copy_to_mode_reg (mode0, op0);
17608     }
17609
17610   pat = GEN_FCN (icode) (target, op0);
17611   if (! pat)
17612     return 0;
17613   emit_insn (pat);
17614   return target;
17615 }
17616
17617 static int
17618 neon_builtin_compare (const void *a, const void *b)
17619 {
17620   const neon_builtin_datum *const key = (const neon_builtin_datum *) a;
17621   const neon_builtin_datum *const memb = (const neon_builtin_datum *) b;
17622   unsigned int soughtcode = key->base_fcode;
17623
17624   if (soughtcode >= memb->base_fcode
17625       && soughtcode < memb->base_fcode + memb->num_vars)
17626     return 0;
17627   else if (soughtcode < memb->base_fcode)
17628     return -1;
17629   else
17630     return 1;
17631 }
17632
17633 static enum insn_code
17634 locate_neon_builtin_icode (int fcode, neon_itype *itype)
17635 {
17636   neon_builtin_datum key, *found;
17637   int idx;
17638
17639   key.base_fcode = fcode;
17640   found = (neon_builtin_datum *)
17641     bsearch (&key, &neon_builtin_data[0], ARRAY_SIZE (neon_builtin_data),
17642                    sizeof (neon_builtin_data[0]), neon_builtin_compare);
17643   gcc_assert (found);
17644   idx = fcode - (int) found->base_fcode;
17645   gcc_assert (idx >= 0 && idx < T_MAX && idx < (int)found->num_vars);
17646
17647   if (itype)
17648     *itype = found->itype;
17649
17650   return found->codes[idx];
17651 }
17652
17653 typedef enum {
17654   NEON_ARG_COPY_TO_REG,
17655   NEON_ARG_CONSTANT,
17656   NEON_ARG_STOP
17657 } builtin_arg;
17658
17659 #define NEON_MAX_BUILTIN_ARGS 5
17660
17661 /* Expand a Neon builtin.  */
17662 static rtx
17663 arm_expand_neon_args (rtx target, int icode, int have_retval,
17664                       tree exp, ...)
17665 {
17666   va_list ap;
17667   rtx pat;
17668   tree arg[NEON_MAX_BUILTIN_ARGS];
17669   rtx op[NEON_MAX_BUILTIN_ARGS];
17670   enum machine_mode tmode = insn_data[icode].operand[0].mode;
17671   enum machine_mode mode[NEON_MAX_BUILTIN_ARGS];
17672   int argc = 0;
17673
17674   if (have_retval
17675       && (!target
17676           || GET_MODE (target) != tmode
17677           || !(*insn_data[icode].operand[0].predicate) (target, tmode)))
17678     target = gen_reg_rtx (tmode);
17679
17680   va_start (ap, exp);
17681
17682   for (;;)
17683     {
17684       builtin_arg thisarg = (builtin_arg) va_arg (ap, int);
17685
17686       if (thisarg == NEON_ARG_STOP)
17687         break;
17688       else
17689         {
17690           arg[argc] = CALL_EXPR_ARG (exp, argc);
17691           op[argc] = expand_normal (arg[argc]);
17692           mode[argc] = insn_data[icode].operand[argc + have_retval].mode;
17693
17694           switch (thisarg)
17695             {
17696             case NEON_ARG_COPY_TO_REG:
17697               /*gcc_assert (GET_MODE (op[argc]) == mode[argc]);*/
17698               if (!(*insn_data[icode].operand[argc + have_retval].predicate)
17699                      (op[argc], mode[argc]))
17700                 op[argc] = copy_to_mode_reg (mode[argc], op[argc]);
17701               break;
17702
17703             case NEON_ARG_CONSTANT:
17704               /* FIXME: This error message is somewhat unhelpful.  */
17705               if (!(*insn_data[icode].operand[argc + have_retval].predicate)
17706                     (op[argc], mode[argc]))
17707                 error ("argument must be a constant");
17708               break;
17709
17710             case NEON_ARG_STOP:
17711               gcc_unreachable ();
17712             }
17713
17714           argc++;
17715         }
17716     }
17717
17718   va_end (ap);
17719
17720   if (have_retval)
17721     switch (argc)
17722       {
17723       case 1:
17724         pat = GEN_FCN (icode) (target, op[0]);
17725         break;
17726
17727       case 2:
17728         pat = GEN_FCN (icode) (target, op[0], op[1]);
17729         break;
17730
17731       case 3:
17732         pat = GEN_FCN (icode) (target, op[0], op[1], op[2]);
17733         break;
17734
17735       case 4:
17736         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3]);
17737         break;
17738
17739       case 5:
17740         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3], op[4]);
17741         break;
17742
17743       default:
17744         gcc_unreachable ();
17745       }
17746   else
17747     switch (argc)
17748       {
17749       case 1:
17750         pat = GEN_FCN (icode) (op[0]);
17751         break;
17752
17753       case 2:
17754         pat = GEN_FCN (icode) (op[0], op[1]);
17755         break;
17756
17757       case 3:
17758         pat = GEN_FCN (icode) (op[0], op[1], op[2]);
17759         break;
17760
17761       case 4:
17762         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3]);
17763         break;
17764
17765       case 5:
17766         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3], op[4]);
17767         break;
17768
17769       default:
17770         gcc_unreachable ();
17771       }
17772
17773   if (!pat)
17774     return 0;
17775
17776   emit_insn (pat);
17777
17778   return target;
17779 }
17780
17781 /* Expand a Neon builtin. These are "special" because they don't have symbolic
17782    constants defined per-instruction or per instruction-variant. Instead, the
17783    required info is looked up in the table neon_builtin_data.  */
17784 static rtx
17785 arm_expand_neon_builtin (int fcode, tree exp, rtx target)
17786 {
17787   neon_itype itype;
17788   enum insn_code icode = locate_neon_builtin_icode (fcode, &itype);
17789
17790   switch (itype)
17791     {
17792     case NEON_UNOP:
17793     case NEON_CONVERT:
17794     case NEON_DUPLANE:
17795       return arm_expand_neon_args (target, icode, 1, exp,
17796         NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT, NEON_ARG_STOP);
17797
17798     case NEON_BINOP:
17799     case NEON_SETLANE:
17800     case NEON_SCALARMUL:
17801     case NEON_SCALARMULL:
17802     case NEON_SCALARMULH:
17803     case NEON_SHIFTINSERT:
17804     case NEON_LOGICBINOP:
17805       return arm_expand_neon_args (target, icode, 1, exp,
17806         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
17807         NEON_ARG_STOP);
17808
17809     case NEON_TERNOP:
17810       return arm_expand_neon_args (target, icode, 1, exp,
17811         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
17812         NEON_ARG_CONSTANT, NEON_ARG_STOP);
17813
17814     case NEON_GETLANE:
17815     case NEON_FIXCONV:
17816     case NEON_SHIFTIMM:
17817       return arm_expand_neon_args (target, icode, 1, exp,
17818         NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT, NEON_ARG_CONSTANT,
17819         NEON_ARG_STOP);
17820
17821     case NEON_CREATE:
17822       return arm_expand_neon_args (target, icode, 1, exp,
17823         NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
17824
17825     case NEON_DUP:
17826     case NEON_SPLIT:
17827     case NEON_REINTERP:
17828       return arm_expand_neon_args (target, icode, 1, exp,
17829         NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
17830
17831     case NEON_COMBINE:
17832     case NEON_VTBL:
17833       return arm_expand_neon_args (target, icode, 1, exp,
17834         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
17835
17836     case NEON_RESULTPAIR:
17837       return arm_expand_neon_args (target, icode, 0, exp,
17838         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
17839         NEON_ARG_STOP);
17840
17841     case NEON_LANEMUL:
17842     case NEON_LANEMULL:
17843     case NEON_LANEMULH:
17844       return arm_expand_neon_args (target, icode, 1, exp,
17845         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
17846         NEON_ARG_CONSTANT, NEON_ARG_STOP);
17847
17848     case NEON_LANEMAC:
17849       return arm_expand_neon_args (target, icode, 1, exp,
17850         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
17851         NEON_ARG_CONSTANT, NEON_ARG_CONSTANT, NEON_ARG_STOP);
17852
17853     case NEON_SHIFTACC:
17854       return arm_expand_neon_args (target, icode, 1, exp,
17855         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
17856         NEON_ARG_CONSTANT, NEON_ARG_STOP);
17857
17858     case NEON_SCALARMAC:
17859       return arm_expand_neon_args (target, icode, 1, exp,
17860         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
17861         NEON_ARG_CONSTANT, NEON_ARG_STOP);
17862
17863     case NEON_SELECT:
17864     case NEON_VTBX:
17865       return arm_expand_neon_args (target, icode, 1, exp,
17866         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
17867         NEON_ARG_STOP);
17868
17869     case NEON_LOAD1:
17870     case NEON_LOADSTRUCT:
17871       return arm_expand_neon_args (target, icode, 1, exp,
17872         NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
17873
17874     case NEON_LOAD1LANE:
17875     case NEON_LOADSTRUCTLANE:
17876       return arm_expand_neon_args (target, icode, 1, exp,
17877         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
17878         NEON_ARG_STOP);
17879
17880     case NEON_STORE1:
17881     case NEON_STORESTRUCT:
17882       return arm_expand_neon_args (target, icode, 0, exp,
17883         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
17884
17885     case NEON_STORE1LANE:
17886     case NEON_STORESTRUCTLANE:
17887       return arm_expand_neon_args (target, icode, 0, exp,
17888         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
17889         NEON_ARG_STOP);
17890     }
17891
17892   gcc_unreachable ();
17893 }
17894
17895 /* Emit code to reinterpret one Neon type as another, without altering bits.  */
17896 void
17897 neon_reinterpret (rtx dest, rtx src)
17898 {
17899   emit_move_insn (dest, gen_lowpart (GET_MODE (dest), src));
17900 }
17901
17902 /* Emit code to place a Neon pair result in memory locations (with equal
17903    registers).  */
17904 void
17905 neon_emit_pair_result_insn (enum machine_mode mode,
17906                             rtx (*intfn) (rtx, rtx, rtx, rtx), rtx destaddr,
17907                             rtx op1, rtx op2)
17908 {
17909   rtx mem = gen_rtx_MEM (mode, destaddr);
17910   rtx tmp1 = gen_reg_rtx (mode);
17911   rtx tmp2 = gen_reg_rtx (mode);
17912
17913   emit_insn (intfn (tmp1, op1, tmp2, op2));
17914
17915   emit_move_insn (mem, tmp1);
17916   mem = adjust_address (mem, mode, GET_MODE_SIZE (mode));
17917   emit_move_insn (mem, tmp2);
17918 }
17919
17920 /* Set up operands for a register copy from src to dest, taking care not to
17921    clobber registers in the process.
17922    FIXME: This has rather high polynomial complexity (O(n^3)?) but shouldn't
17923    be called with a large N, so that should be OK.  */
17924
17925 void
17926 neon_disambiguate_copy (rtx *operands, rtx *dest, rtx *src, unsigned int count)
17927 {
17928   unsigned int copied = 0, opctr = 0;
17929   unsigned int done = (1 << count) - 1;
17930   unsigned int i, j;
17931
17932   while (copied != done)
17933     {
17934       for (i = 0; i < count; i++)
17935         {
17936           int good = 1;
17937
17938           for (j = 0; good && j < count; j++)
17939             if (i != j && (copied & (1 << j)) == 0
17940                 && reg_overlap_mentioned_p (src[j], dest[i]))
17941               good = 0;
17942
17943           if (good)
17944             {
17945               operands[opctr++] = dest[i];
17946               operands[opctr++] = src[i];
17947               copied |= 1 << i;
17948             }
17949         }
17950     }
17951
17952   gcc_assert (opctr == count * 2);
17953 }
17954
17955 /* Expand an expression EXP that calls a built-in function,
17956    with result going to TARGET if that's convenient
17957    (and in mode MODE if that's convenient).
17958    SUBTARGET may be used as the target for computing one of EXP's operands.
17959    IGNORE is nonzero if the value is to be ignored.  */
17960
17961 static rtx
17962 arm_expand_builtin (tree exp,
17963                     rtx target,
17964                     rtx subtarget ATTRIBUTE_UNUSED,
17965                     enum machine_mode mode ATTRIBUTE_UNUSED,
17966                     int ignore ATTRIBUTE_UNUSED)
17967 {
17968   const struct builtin_description * d;
17969   enum insn_code    icode;
17970   tree              fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
17971   tree              arg0;
17972   tree              arg1;
17973   tree              arg2;
17974   rtx               op0;
17975   rtx               op1;
17976   rtx               op2;
17977   rtx               pat;
17978   int               fcode = DECL_FUNCTION_CODE (fndecl);
17979   size_t            i;
17980   enum machine_mode tmode;
17981   enum machine_mode mode0;
17982   enum machine_mode mode1;
17983   enum machine_mode mode2;
17984
17985   if (fcode >= ARM_BUILTIN_NEON_BASE)
17986     return arm_expand_neon_builtin (fcode, exp, target);
17987
17988   switch (fcode)
17989     {
17990     case ARM_BUILTIN_TEXTRMSB:
17991     case ARM_BUILTIN_TEXTRMUB:
17992     case ARM_BUILTIN_TEXTRMSH:
17993     case ARM_BUILTIN_TEXTRMUH:
17994     case ARM_BUILTIN_TEXTRMSW:
17995     case ARM_BUILTIN_TEXTRMUW:
17996       icode = (fcode == ARM_BUILTIN_TEXTRMSB ? CODE_FOR_iwmmxt_textrmsb
17997                : fcode == ARM_BUILTIN_TEXTRMUB ? CODE_FOR_iwmmxt_textrmub
17998                : fcode == ARM_BUILTIN_TEXTRMSH ? CODE_FOR_iwmmxt_textrmsh
17999                : fcode == ARM_BUILTIN_TEXTRMUH ? CODE_FOR_iwmmxt_textrmuh
18000                : CODE_FOR_iwmmxt_textrmw);
18001
18002       arg0 = CALL_EXPR_ARG (exp, 0);
18003       arg1 = CALL_EXPR_ARG (exp, 1);
18004       op0 = expand_normal (arg0);
18005       op1 = expand_normal (arg1);
18006       tmode = insn_data[icode].operand[0].mode;
18007       mode0 = insn_data[icode].operand[1].mode;
18008       mode1 = insn_data[icode].operand[2].mode;
18009
18010       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
18011         op0 = copy_to_mode_reg (mode0, op0);
18012       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
18013         {
18014           /* @@@ better error message */
18015           error ("selector must be an immediate");
18016           return gen_reg_rtx (tmode);
18017         }
18018       if (target == 0
18019           || GET_MODE (target) != tmode
18020           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
18021         target = gen_reg_rtx (tmode);
18022       pat = GEN_FCN (icode) (target, op0, op1);
18023       if (! pat)
18024         return 0;
18025       emit_insn (pat);
18026       return target;
18027
18028     case ARM_BUILTIN_TINSRB:
18029     case ARM_BUILTIN_TINSRH:
18030     case ARM_BUILTIN_TINSRW:
18031       icode = (fcode == ARM_BUILTIN_TINSRB ? CODE_FOR_iwmmxt_tinsrb
18032                : fcode == ARM_BUILTIN_TINSRH ? CODE_FOR_iwmmxt_tinsrh
18033                : CODE_FOR_iwmmxt_tinsrw);
18034       arg0 = CALL_EXPR_ARG (exp, 0);
18035       arg1 = CALL_EXPR_ARG (exp, 1);
18036       arg2 = CALL_EXPR_ARG (exp, 2);
18037       op0 = expand_normal (arg0);
18038       op1 = expand_normal (arg1);
18039       op2 = expand_normal (arg2);
18040       tmode = insn_data[icode].operand[0].mode;
18041       mode0 = insn_data[icode].operand[1].mode;
18042       mode1 = insn_data[icode].operand[2].mode;
18043       mode2 = insn_data[icode].operand[3].mode;
18044
18045       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
18046         op0 = copy_to_mode_reg (mode0, op0);
18047       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
18048         op1 = copy_to_mode_reg (mode1, op1);
18049       if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
18050         {
18051           /* @@@ better error message */
18052           error ("selector must be an immediate");
18053           return const0_rtx;
18054         }
18055       if (target == 0
18056           || GET_MODE (target) != tmode
18057           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
18058         target = gen_reg_rtx (tmode);
18059       pat = GEN_FCN (icode) (target, op0, op1, op2);
18060       if (! pat)
18061         return 0;
18062       emit_insn (pat);
18063       return target;
18064
18065     case ARM_BUILTIN_SETWCX:
18066       arg0 = CALL_EXPR_ARG (exp, 0);
18067       arg1 = CALL_EXPR_ARG (exp, 1);
18068       op0 = force_reg (SImode, expand_normal (arg0));
18069       op1 = expand_normal (arg1);
18070       emit_insn (gen_iwmmxt_tmcr (op1, op0));
18071       return 0;
18072
18073     case ARM_BUILTIN_GETWCX:
18074       arg0 = CALL_EXPR_ARG (exp, 0);
18075       op0 = expand_normal (arg0);
18076       target = gen_reg_rtx (SImode);
18077       emit_insn (gen_iwmmxt_tmrc (target, op0));
18078       return target;
18079
18080     case ARM_BUILTIN_WSHUFH:
18081       icode = CODE_FOR_iwmmxt_wshufh;
18082       arg0 = CALL_EXPR_ARG (exp, 0);
18083       arg1 = CALL_EXPR_ARG (exp, 1);
18084       op0 = expand_normal (arg0);
18085       op1 = expand_normal (arg1);
18086       tmode = insn_data[icode].operand[0].mode;
18087       mode1 = insn_data[icode].operand[1].mode;
18088       mode2 = insn_data[icode].operand[2].mode;
18089
18090       if (! (*insn_data[icode].operand[1].predicate) (op0, mode1))
18091         op0 = copy_to_mode_reg (mode1, op0);
18092       if (! (*insn_data[icode].operand[2].predicate) (op1, mode2))
18093         {
18094           /* @@@ better error message */
18095           error ("mask must be an immediate");
18096           return const0_rtx;
18097         }
18098       if (target == 0
18099           || GET_MODE (target) != tmode
18100           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
18101         target = gen_reg_rtx (tmode);
18102       pat = GEN_FCN (icode) (target, op0, op1);
18103       if (! pat)
18104         return 0;
18105       emit_insn (pat);
18106       return target;
18107
18108     case ARM_BUILTIN_WSADB:
18109       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadb, exp, target);
18110     case ARM_BUILTIN_WSADH:
18111       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadh, exp, target);
18112     case ARM_BUILTIN_WSADBZ:
18113       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadbz, exp, target);
18114     case ARM_BUILTIN_WSADHZ:
18115       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadhz, exp, target);
18116
18117       /* Several three-argument builtins.  */
18118     case ARM_BUILTIN_WMACS:
18119     case ARM_BUILTIN_WMACU:
18120     case ARM_BUILTIN_WALIGN:
18121     case ARM_BUILTIN_TMIA:
18122     case ARM_BUILTIN_TMIAPH:
18123     case ARM_BUILTIN_TMIATT:
18124     case ARM_BUILTIN_TMIATB:
18125     case ARM_BUILTIN_TMIABT:
18126     case ARM_BUILTIN_TMIABB:
18127       icode = (fcode == ARM_BUILTIN_WMACS ? CODE_FOR_iwmmxt_wmacs
18128                : fcode == ARM_BUILTIN_WMACU ? CODE_FOR_iwmmxt_wmacu
18129                : fcode == ARM_BUILTIN_TMIA ? CODE_FOR_iwmmxt_tmia
18130                : fcode == ARM_BUILTIN_TMIAPH ? CODE_FOR_iwmmxt_tmiaph
18131                : fcode == ARM_BUILTIN_TMIABB ? CODE_FOR_iwmmxt_tmiabb
18132                : fcode == ARM_BUILTIN_TMIABT ? CODE_FOR_iwmmxt_tmiabt
18133                : fcode == ARM_BUILTIN_TMIATB ? CODE_FOR_iwmmxt_tmiatb
18134                : fcode == ARM_BUILTIN_TMIATT ? CODE_FOR_iwmmxt_tmiatt
18135                : CODE_FOR_iwmmxt_walign);
18136       arg0 = CALL_EXPR_ARG (exp, 0);
18137       arg1 = CALL_EXPR_ARG (exp, 1);
18138       arg2 = CALL_EXPR_ARG (exp, 2);
18139       op0 = expand_normal (arg0);
18140       op1 = expand_normal (arg1);
18141       op2 = expand_normal (arg2);
18142       tmode = insn_data[icode].operand[0].mode;
18143       mode0 = insn_data[icode].operand[1].mode;
18144       mode1 = insn_data[icode].operand[2].mode;
18145       mode2 = insn_data[icode].operand[3].mode;
18146
18147       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
18148         op0 = copy_to_mode_reg (mode0, op0);
18149       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
18150         op1 = copy_to_mode_reg (mode1, op1);
18151       if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
18152         op2 = copy_to_mode_reg (mode2, op2);
18153       if (target == 0
18154           || GET_MODE (target) != tmode
18155           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
18156         target = gen_reg_rtx (tmode);
18157       pat = GEN_FCN (icode) (target, op0, op1, op2);
18158       if (! pat)
18159         return 0;
18160       emit_insn (pat);
18161       return target;
18162
18163     case ARM_BUILTIN_WZERO:
18164       target = gen_reg_rtx (DImode);
18165       emit_insn (gen_iwmmxt_clrdi (target));
18166       return target;
18167
18168     case ARM_BUILTIN_THREAD_POINTER:
18169       return arm_load_tp (target);
18170
18171     default:
18172       break;
18173     }
18174
18175   for (i = 0, d = bdesc_2arg; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
18176     if (d->code == (const enum arm_builtins) fcode)
18177       return arm_expand_binop_builtin (d->icode, exp, target);
18178
18179   for (i = 0, d = bdesc_1arg; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
18180     if (d->code == (const enum arm_builtins) fcode)
18181       return arm_expand_unop_builtin (d->icode, exp, target, 0);
18182
18183   /* @@@ Should really do something sensible here.  */
18184   return NULL_RTX;
18185 }
18186 \f
18187 /* Return the number (counting from 0) of
18188    the least significant set bit in MASK.  */
18189
18190 inline static int
18191 number_of_first_bit_set (unsigned mask)
18192 {
18193   int bit;
18194
18195   for (bit = 0;
18196        (mask & (1 << bit)) == 0;
18197        ++bit)
18198     continue;
18199
18200   return bit;
18201 }
18202
18203 /* Emit code to push or pop registers to or from the stack.  F is the
18204    assembly file.  MASK is the registers to push or pop.  PUSH is
18205    nonzero if we should push, and zero if we should pop.  For debugging
18206    output, if pushing, adjust CFA_OFFSET by the amount of space added
18207    to the stack.  REAL_REGS should have the same number of bits set as
18208    MASK, and will be used instead (in the same order) to describe which
18209    registers were saved - this is used to mark the save slots when we
18210    push high registers after moving them to low registers.  */
18211 static void
18212 thumb_pushpop (FILE *f, unsigned long mask, int push, int *cfa_offset,
18213                unsigned long real_regs)
18214 {
18215   int regno;
18216   int lo_mask = mask & 0xFF;
18217   int pushed_words = 0;
18218
18219   gcc_assert (mask);
18220
18221   if (lo_mask == 0 && !push && (mask & (1 << PC_REGNUM)))
18222     {
18223       /* Special case.  Do not generate a POP PC statement here, do it in
18224          thumb_exit() */
18225       thumb_exit (f, -1);
18226       return;
18227     }
18228
18229   if (ARM_EABI_UNWIND_TABLES && push)
18230     {
18231       fprintf (f, "\t.save\t{");
18232       for (regno = 0; regno < 15; regno++)
18233         {
18234           if (real_regs & (1 << regno))
18235             {
18236               if (real_regs & ((1 << regno) -1))
18237                 fprintf (f, ", ");
18238               asm_fprintf (f, "%r", regno);
18239             }
18240         }
18241       fprintf (f, "}\n");
18242     }
18243
18244   fprintf (f, "\t%s\t{", push ? "push" : "pop");
18245
18246   /* Look at the low registers first.  */
18247   for (regno = 0; regno <= LAST_LO_REGNUM; regno++, lo_mask >>= 1)
18248     {
18249       if (lo_mask & 1)
18250         {
18251           asm_fprintf (f, "%r", regno);
18252
18253           if ((lo_mask & ~1) != 0)
18254             fprintf (f, ", ");
18255
18256           pushed_words++;
18257         }
18258     }
18259
18260   if (push && (mask & (1 << LR_REGNUM)))
18261     {
18262       /* Catch pushing the LR.  */
18263       if (mask & 0xFF)
18264         fprintf (f, ", ");
18265
18266       asm_fprintf (f, "%r", LR_REGNUM);
18267
18268       pushed_words++;
18269     }
18270   else if (!push && (mask & (1 << PC_REGNUM)))
18271     {
18272       /* Catch popping the PC.  */
18273       if (TARGET_INTERWORK || TARGET_BACKTRACE
18274           || crtl->calls_eh_return)
18275         {
18276           /* The PC is never poped directly, instead
18277              it is popped into r3 and then BX is used.  */
18278           fprintf (f, "}\n");
18279
18280           thumb_exit (f, -1);
18281
18282           return;
18283         }
18284       else
18285         {
18286           if (mask & 0xFF)
18287             fprintf (f, ", ");
18288
18289           asm_fprintf (f, "%r", PC_REGNUM);
18290         }
18291     }
18292
18293   fprintf (f, "}\n");
18294
18295   if (push && pushed_words && dwarf2out_do_frame ())
18296     {
18297       char *l = dwarf2out_cfi_label (false);
18298       int pushed_mask = real_regs;
18299
18300       *cfa_offset += pushed_words * 4;
18301       dwarf2out_def_cfa (l, SP_REGNUM, *cfa_offset);
18302
18303       pushed_words = 0;
18304       pushed_mask = real_regs;
18305       for (regno = 0; regno <= 14; regno++, pushed_mask >>= 1)
18306         {
18307           if (pushed_mask & 1)
18308             dwarf2out_reg_save (l, regno, 4 * pushed_words++ - *cfa_offset);
18309         }
18310     }
18311 }
18312
18313 /* Generate code to return from a thumb function.
18314    If 'reg_containing_return_addr' is -1, then the return address is
18315    actually on the stack, at the stack pointer.  */
18316 static void
18317 thumb_exit (FILE *f, int reg_containing_return_addr)
18318 {
18319   unsigned regs_available_for_popping;
18320   unsigned regs_to_pop;
18321   int pops_needed;
18322   unsigned available;
18323   unsigned required;
18324   int mode;
18325   int size;
18326   int restore_a4 = FALSE;
18327
18328   /* Compute the registers we need to pop.  */
18329   regs_to_pop = 0;
18330   pops_needed = 0;
18331
18332   if (reg_containing_return_addr == -1)
18333     {
18334       regs_to_pop |= 1 << LR_REGNUM;
18335       ++pops_needed;
18336     }
18337
18338   if (TARGET_BACKTRACE)
18339     {
18340       /* Restore the (ARM) frame pointer and stack pointer.  */
18341       regs_to_pop |= (1 << ARM_HARD_FRAME_POINTER_REGNUM) | (1 << SP_REGNUM);
18342       pops_needed += 2;
18343     }
18344
18345   /* If there is nothing to pop then just emit the BX instruction and
18346      return.  */
18347   if (pops_needed == 0)
18348     {
18349       if (crtl->calls_eh_return)
18350         asm_fprintf (f, "\tadd\t%r, %r\n", SP_REGNUM, ARM_EH_STACKADJ_REGNUM);
18351
18352       asm_fprintf (f, "\tbx\t%r\n", reg_containing_return_addr);
18353       return;
18354     }
18355   /* Otherwise if we are not supporting interworking and we have not created
18356      a backtrace structure and the function was not entered in ARM mode then
18357      just pop the return address straight into the PC.  */
18358   else if (!TARGET_INTERWORK
18359            && !TARGET_BACKTRACE
18360            && !is_called_in_ARM_mode (current_function_decl)
18361            && !crtl->calls_eh_return)
18362     {
18363       asm_fprintf (f, "\tpop\t{%r}\n", PC_REGNUM);
18364       return;
18365     }
18366
18367   /* Find out how many of the (return) argument registers we can corrupt.  */
18368   regs_available_for_popping = 0;
18369
18370   /* If returning via __builtin_eh_return, the bottom three registers
18371      all contain information needed for the return.  */
18372   if (crtl->calls_eh_return)
18373     size = 12;
18374   else
18375     {
18376       /* If we can deduce the registers used from the function's
18377          return value.  This is more reliable that examining
18378          df_regs_ever_live_p () because that will be set if the register is
18379          ever used in the function, not just if the register is used
18380          to hold a return value.  */
18381
18382       if (crtl->return_rtx != 0)
18383         mode = GET_MODE (crtl->return_rtx);
18384       else
18385         mode = DECL_MODE (DECL_RESULT (current_function_decl));
18386
18387       size = GET_MODE_SIZE (mode);
18388
18389       if (size == 0)
18390         {
18391           /* In a void function we can use any argument register.
18392              In a function that returns a structure on the stack
18393              we can use the second and third argument registers.  */
18394           if (mode == VOIDmode)
18395             regs_available_for_popping =
18396               (1 << ARG_REGISTER (1))
18397               | (1 << ARG_REGISTER (2))
18398               | (1 << ARG_REGISTER (3));
18399           else
18400             regs_available_for_popping =
18401               (1 << ARG_REGISTER (2))
18402               | (1 << ARG_REGISTER (3));
18403         }
18404       else if (size <= 4)
18405         regs_available_for_popping =
18406           (1 << ARG_REGISTER (2))
18407           | (1 << ARG_REGISTER (3));
18408       else if (size <= 8)
18409         regs_available_for_popping =
18410           (1 << ARG_REGISTER (3));
18411     }
18412
18413   /* Match registers to be popped with registers into which we pop them.  */
18414   for (available = regs_available_for_popping,
18415        required  = regs_to_pop;
18416        required != 0 && available != 0;
18417        available &= ~(available & - available),
18418        required  &= ~(required  & - required))
18419     -- pops_needed;
18420
18421   /* If we have any popping registers left over, remove them.  */
18422   if (available > 0)
18423     regs_available_for_popping &= ~available;
18424
18425   /* Otherwise if we need another popping register we can use
18426      the fourth argument register.  */
18427   else if (pops_needed)
18428     {
18429       /* If we have not found any free argument registers and
18430          reg a4 contains the return address, we must move it.  */
18431       if (regs_available_for_popping == 0
18432           && reg_containing_return_addr == LAST_ARG_REGNUM)
18433         {
18434           asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM, LAST_ARG_REGNUM);
18435           reg_containing_return_addr = LR_REGNUM;
18436         }
18437       else if (size > 12)
18438         {
18439           /* Register a4 is being used to hold part of the return value,
18440              but we have dire need of a free, low register.  */
18441           restore_a4 = TRUE;
18442
18443           asm_fprintf (f, "\tmov\t%r, %r\n",IP_REGNUM, LAST_ARG_REGNUM);
18444         }
18445
18446       if (reg_containing_return_addr != LAST_ARG_REGNUM)
18447         {
18448           /* The fourth argument register is available.  */
18449           regs_available_for_popping |= 1 << LAST_ARG_REGNUM;
18450
18451           --pops_needed;
18452         }
18453     }
18454
18455   /* Pop as many registers as we can.  */
18456   thumb_pushpop (f, regs_available_for_popping, FALSE, NULL,
18457                  regs_available_for_popping);
18458
18459   /* Process the registers we popped.  */
18460   if (reg_containing_return_addr == -1)
18461     {
18462       /* The return address was popped into the lowest numbered register.  */
18463       regs_to_pop &= ~(1 << LR_REGNUM);
18464
18465       reg_containing_return_addr =
18466         number_of_first_bit_set (regs_available_for_popping);
18467
18468       /* Remove this register for the mask of available registers, so that
18469          the return address will not be corrupted by further pops.  */
18470       regs_available_for_popping &= ~(1 << reg_containing_return_addr);
18471     }
18472
18473   /* If we popped other registers then handle them here.  */
18474   if (regs_available_for_popping)
18475     {
18476       int frame_pointer;
18477
18478       /* Work out which register currently contains the frame pointer.  */
18479       frame_pointer = number_of_first_bit_set (regs_available_for_popping);
18480
18481       /* Move it into the correct place.  */
18482       asm_fprintf (f, "\tmov\t%r, %r\n",
18483                    ARM_HARD_FRAME_POINTER_REGNUM, frame_pointer);
18484
18485       /* (Temporarily) remove it from the mask of popped registers.  */
18486       regs_available_for_popping &= ~(1 << frame_pointer);
18487       regs_to_pop &= ~(1 << ARM_HARD_FRAME_POINTER_REGNUM);
18488
18489       if (regs_available_for_popping)
18490         {
18491           int stack_pointer;
18492
18493           /* We popped the stack pointer as well,
18494              find the register that contains it.  */
18495           stack_pointer = number_of_first_bit_set (regs_available_for_popping);
18496
18497           /* Move it into the stack register.  */
18498           asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, stack_pointer);
18499
18500           /* At this point we have popped all necessary registers, so
18501              do not worry about restoring regs_available_for_popping
18502              to its correct value:
18503
18504              assert (pops_needed == 0)
18505              assert (regs_available_for_popping == (1 << frame_pointer))
18506              assert (regs_to_pop == (1 << STACK_POINTER))  */
18507         }
18508       else
18509         {
18510           /* Since we have just move the popped value into the frame
18511              pointer, the popping register is available for reuse, and
18512              we know that we still have the stack pointer left to pop.  */
18513           regs_available_for_popping |= (1 << frame_pointer);
18514         }
18515     }
18516
18517   /* If we still have registers left on the stack, but we no longer have
18518      any registers into which we can pop them, then we must move the return
18519      address into the link register and make available the register that
18520      contained it.  */
18521   if (regs_available_for_popping == 0 && pops_needed > 0)
18522     {
18523       regs_available_for_popping |= 1 << reg_containing_return_addr;
18524
18525       asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM,
18526                    reg_containing_return_addr);
18527
18528       reg_containing_return_addr = LR_REGNUM;
18529     }
18530
18531   /* If we have registers left on the stack then pop some more.
18532      We know that at most we will want to pop FP and SP.  */
18533   if (pops_needed > 0)
18534     {
18535       int  popped_into;
18536       int  move_to;
18537
18538       thumb_pushpop (f, regs_available_for_popping, FALSE, NULL,
18539                      regs_available_for_popping);
18540
18541       /* We have popped either FP or SP.
18542          Move whichever one it is into the correct register.  */
18543       popped_into = number_of_first_bit_set (regs_available_for_popping);
18544       move_to     = number_of_first_bit_set (regs_to_pop);
18545
18546       asm_fprintf (f, "\tmov\t%r, %r\n", move_to, popped_into);
18547
18548       regs_to_pop &= ~(1 << move_to);
18549
18550       --pops_needed;
18551     }
18552
18553   /* If we still have not popped everything then we must have only
18554      had one register available to us and we are now popping the SP.  */
18555   if (pops_needed > 0)
18556     {
18557       int  popped_into;
18558
18559       thumb_pushpop (f, regs_available_for_popping, FALSE, NULL,
18560                      regs_available_for_popping);
18561
18562       popped_into = number_of_first_bit_set (regs_available_for_popping);
18563
18564       asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, popped_into);
18565       /*
18566         assert (regs_to_pop == (1 << STACK_POINTER))
18567         assert (pops_needed == 1)
18568       */
18569     }
18570
18571   /* If necessary restore the a4 register.  */
18572   if (restore_a4)
18573     {
18574       if (reg_containing_return_addr != LR_REGNUM)
18575         {
18576           asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM, LAST_ARG_REGNUM);
18577           reg_containing_return_addr = LR_REGNUM;
18578         }
18579
18580       asm_fprintf (f, "\tmov\t%r, %r\n", LAST_ARG_REGNUM, IP_REGNUM);
18581     }
18582
18583   if (crtl->calls_eh_return)
18584     asm_fprintf (f, "\tadd\t%r, %r\n", SP_REGNUM, ARM_EH_STACKADJ_REGNUM);
18585
18586   /* Return to caller.  */
18587   asm_fprintf (f, "\tbx\t%r\n", reg_containing_return_addr);
18588 }
18589
18590 \f
18591 void
18592 thumb1_final_prescan_insn (rtx insn)
18593 {
18594   if (flag_print_asm_name)
18595     asm_fprintf (asm_out_file, "%@ 0x%04x\n",
18596                  INSN_ADDRESSES (INSN_UID (insn)));
18597 }
18598
18599 int
18600 thumb_shiftable_const (unsigned HOST_WIDE_INT val)
18601 {
18602   unsigned HOST_WIDE_INT mask = 0xff;
18603   int i;
18604
18605   val = val & (unsigned HOST_WIDE_INT)0xffffffffu;
18606   if (val == 0) /* XXX */
18607     return 0;
18608
18609   for (i = 0; i < 25; i++)
18610     if ((val & (mask << i)) == val)
18611       return 1;
18612
18613   return 0;
18614 }
18615
18616 /* Returns nonzero if the current function contains,
18617    or might contain a far jump.  */
18618 static int
18619 thumb_far_jump_used_p (void)
18620 {
18621   rtx insn;
18622
18623   /* This test is only important for leaf functions.  */
18624   /* assert (!leaf_function_p ()); */
18625
18626   /* If we have already decided that far jumps may be used,
18627      do not bother checking again, and always return true even if
18628      it turns out that they are not being used.  Once we have made
18629      the decision that far jumps are present (and that hence the link
18630      register will be pushed onto the stack) we cannot go back on it.  */
18631   if (cfun->machine->far_jump_used)
18632     return 1;
18633
18634   /* If this function is not being called from the prologue/epilogue
18635      generation code then it must be being called from the
18636      INITIAL_ELIMINATION_OFFSET macro.  */
18637   if (!(ARM_DOUBLEWORD_ALIGN || reload_completed))
18638     {
18639       /* In this case we know that we are being asked about the elimination
18640          of the arg pointer register.  If that register is not being used,
18641          then there are no arguments on the stack, and we do not have to
18642          worry that a far jump might force the prologue to push the link
18643          register, changing the stack offsets.  In this case we can just
18644          return false, since the presence of far jumps in the function will
18645          not affect stack offsets.
18646
18647          If the arg pointer is live (or if it was live, but has now been
18648          eliminated and so set to dead) then we do have to test to see if
18649          the function might contain a far jump.  This test can lead to some
18650          false negatives, since before reload is completed, then length of
18651          branch instructions is not known, so gcc defaults to returning their
18652          longest length, which in turn sets the far jump attribute to true.
18653
18654          A false negative will not result in bad code being generated, but it
18655          will result in a needless push and pop of the link register.  We
18656          hope that this does not occur too often.
18657
18658          If we need doubleword stack alignment this could affect the other
18659          elimination offsets so we can't risk getting it wrong.  */
18660       if (df_regs_ever_live_p (ARG_POINTER_REGNUM))
18661         cfun->machine->arg_pointer_live = 1;
18662       else if (!cfun->machine->arg_pointer_live)
18663         return 0;
18664     }
18665
18666   /* Check to see if the function contains a branch
18667      insn with the far jump attribute set.  */
18668   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
18669     {
18670       if (GET_CODE (insn) == JUMP_INSN
18671           /* Ignore tablejump patterns.  */
18672           && GET_CODE (PATTERN (insn)) != ADDR_VEC
18673           && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
18674           && get_attr_far_jump (insn) == FAR_JUMP_YES
18675           )
18676         {
18677           /* Record the fact that we have decided that
18678              the function does use far jumps.  */
18679           cfun->machine->far_jump_used = 1;
18680           return 1;
18681         }
18682     }
18683
18684   return 0;
18685 }
18686
18687 /* Return nonzero if FUNC must be entered in ARM mode.  */
18688 int
18689 is_called_in_ARM_mode (tree func)
18690 {
18691   gcc_assert (TREE_CODE (func) == FUNCTION_DECL);
18692
18693   /* Ignore the problem about functions whose address is taken.  */
18694   if (TARGET_CALLEE_INTERWORKING && TREE_PUBLIC (func))
18695     return TRUE;
18696
18697 #ifdef ARM_PE
18698   return lookup_attribute ("interfacearm", DECL_ATTRIBUTES (func)) != NULL_TREE;
18699 #else
18700   return FALSE;
18701 #endif
18702 }
18703
18704 /* The bits which aren't usefully expanded as rtl.  */
18705 const char *
18706 thumb_unexpanded_epilogue (void)
18707 {
18708   arm_stack_offsets *offsets;
18709   int regno;
18710   unsigned long live_regs_mask = 0;
18711   int high_regs_pushed = 0;
18712   int had_to_push_lr;
18713   int size;
18714
18715   if (cfun->machine->return_used_this_function != 0)
18716     return "";
18717
18718   if (IS_NAKED (arm_current_func_type ()))
18719     return "";
18720
18721   offsets = arm_get_frame_offsets ();
18722   live_regs_mask = offsets->saved_regs_mask;
18723   high_regs_pushed = bit_count (live_regs_mask & 0x0f00);
18724
18725   /* If we can deduce the registers used from the function's return value.
18726      This is more reliable that examining df_regs_ever_live_p () because that
18727      will be set if the register is ever used in the function, not just if
18728      the register is used to hold a return value.  */
18729   size = arm_size_return_regs ();
18730
18731   /* The prolog may have pushed some high registers to use as
18732      work registers.  e.g. the testsuite file:
18733      gcc/testsuite/gcc/gcc.c-torture/execute/complex-2.c
18734      compiles to produce:
18735         push    {r4, r5, r6, r7, lr}
18736         mov     r7, r9
18737         mov     r6, r8
18738         push    {r6, r7}
18739      as part of the prolog.  We have to undo that pushing here.  */
18740
18741   if (high_regs_pushed)
18742     {
18743       unsigned long mask = live_regs_mask & 0xff;
18744       int next_hi_reg;
18745
18746       /* The available low registers depend on the size of the value we are
18747          returning.  */
18748       if (size <= 12)
18749         mask |=  1 << 3;
18750       if (size <= 8)
18751         mask |= 1 << 2;
18752
18753       if (mask == 0)
18754         /* Oh dear!  We have no low registers into which we can pop
18755            high registers!  */
18756         internal_error
18757           ("no low registers available for popping high registers");
18758
18759       for (next_hi_reg = 8; next_hi_reg < 13; next_hi_reg++)
18760         if (live_regs_mask & (1 << next_hi_reg))
18761           break;
18762
18763       while (high_regs_pushed)
18764         {
18765           /* Find lo register(s) into which the high register(s) can
18766              be popped.  */
18767           for (regno = 0; regno <= LAST_LO_REGNUM; regno++)
18768             {
18769               if (mask & (1 << regno))
18770                 high_regs_pushed--;
18771               if (high_regs_pushed == 0)
18772                 break;
18773             }
18774
18775           mask &= (2 << regno) - 1;     /* A noop if regno == 8 */
18776
18777           /* Pop the values into the low register(s).  */
18778           thumb_pushpop (asm_out_file, mask, 0, NULL, mask);
18779
18780           /* Move the value(s) into the high registers.  */
18781           for (regno = 0; regno <= LAST_LO_REGNUM; regno++)
18782             {
18783               if (mask & (1 << regno))
18784                 {
18785                   asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", next_hi_reg,
18786                                regno);
18787
18788                   for (next_hi_reg++; next_hi_reg < 13; next_hi_reg++)
18789                     if (live_regs_mask & (1 << next_hi_reg))
18790                       break;
18791                 }
18792             }
18793         }
18794       live_regs_mask &= ~0x0f00;
18795     }
18796
18797   had_to_push_lr = (live_regs_mask & (1 << LR_REGNUM)) != 0;
18798   live_regs_mask &= 0xff;
18799
18800   if (crtl->args.pretend_args_size == 0 || TARGET_BACKTRACE)
18801     {
18802       /* Pop the return address into the PC.  */
18803       if (had_to_push_lr)
18804         live_regs_mask |= 1 << PC_REGNUM;
18805
18806       /* Either no argument registers were pushed or a backtrace
18807          structure was created which includes an adjusted stack
18808          pointer, so just pop everything.  */
18809       if (live_regs_mask)
18810         thumb_pushpop (asm_out_file, live_regs_mask, FALSE, NULL,
18811                        live_regs_mask);
18812
18813       /* We have either just popped the return address into the
18814          PC or it is was kept in LR for the entire function.  */
18815       if (!had_to_push_lr)
18816         thumb_exit (asm_out_file, LR_REGNUM);
18817     }
18818   else
18819     {
18820       /* Pop everything but the return address.  */
18821       if (live_regs_mask)
18822         thumb_pushpop (asm_out_file, live_regs_mask, FALSE, NULL,
18823                        live_regs_mask);
18824
18825       if (had_to_push_lr)
18826         {
18827           if (size > 12)
18828             {
18829               /* We have no free low regs, so save one.  */
18830               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", IP_REGNUM,
18831                            LAST_ARG_REGNUM);
18832             }
18833
18834           /* Get the return address into a temporary register.  */
18835           thumb_pushpop (asm_out_file, 1 << LAST_ARG_REGNUM, 0, NULL,
18836                          1 << LAST_ARG_REGNUM);
18837
18838           if (size > 12)
18839             {
18840               /* Move the return address to lr.  */
18841               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", LR_REGNUM,
18842                            LAST_ARG_REGNUM);
18843               /* Restore the low register.  */
18844               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", LAST_ARG_REGNUM,
18845                            IP_REGNUM);
18846               regno = LR_REGNUM;
18847             }
18848           else
18849             regno = LAST_ARG_REGNUM;
18850         }
18851       else
18852         regno = LR_REGNUM;
18853
18854       /* Remove the argument registers that were pushed onto the stack.  */
18855       asm_fprintf (asm_out_file, "\tadd\t%r, %r, #%d\n",
18856                    SP_REGNUM, SP_REGNUM,
18857                    crtl->args.pretend_args_size);
18858
18859       thumb_exit (asm_out_file, regno);
18860     }
18861
18862   return "";
18863 }
18864
18865 /* Functions to save and restore machine-specific function data.  */
18866 static struct machine_function *
18867 arm_init_machine_status (void)
18868 {
18869   struct machine_function *machine;
18870   machine = (machine_function *) ggc_alloc_cleared (sizeof (machine_function));
18871
18872 #if ARM_FT_UNKNOWN != 0
18873   machine->func_type = ARM_FT_UNKNOWN;
18874 #endif
18875   return machine;
18876 }
18877
18878 /* Return an RTX indicating where the return address to the
18879    calling function can be found.  */
18880 rtx
18881 arm_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
18882 {
18883   if (count != 0)
18884     return NULL_RTX;
18885
18886   return get_hard_reg_initial_val (Pmode, LR_REGNUM);
18887 }
18888
18889 /* Do anything needed before RTL is emitted for each function.  */
18890 void
18891 arm_init_expanders (void)
18892 {
18893   /* Arrange to initialize and mark the machine per-function status.  */
18894   init_machine_status = arm_init_machine_status;
18895
18896   /* This is to stop the combine pass optimizing away the alignment
18897      adjustment of va_arg.  */
18898   /* ??? It is claimed that this should not be necessary.  */
18899   if (cfun)
18900     mark_reg_pointer (arg_pointer_rtx, PARM_BOUNDARY);
18901 }
18902
18903
18904 /* Like arm_compute_initial_elimination offset.  Simpler because there
18905    isn't an ABI specified frame pointer for Thumb.  Instead, we set it
18906    to point at the base of the local variables after static stack
18907    space for a function has been allocated.  */
18908
18909 HOST_WIDE_INT
18910 thumb_compute_initial_elimination_offset (unsigned int from, unsigned int to)
18911 {
18912   arm_stack_offsets *offsets;
18913
18914   offsets = arm_get_frame_offsets ();
18915
18916   switch (from)
18917     {
18918     case ARG_POINTER_REGNUM:
18919       switch (to)
18920         {
18921         case STACK_POINTER_REGNUM:
18922           return offsets->outgoing_args - offsets->saved_args;
18923
18924         case FRAME_POINTER_REGNUM:
18925           return offsets->soft_frame - offsets->saved_args;
18926
18927         case ARM_HARD_FRAME_POINTER_REGNUM:
18928           return offsets->saved_regs - offsets->saved_args;
18929
18930         case THUMB_HARD_FRAME_POINTER_REGNUM:
18931           return offsets->locals_base - offsets->saved_args;
18932
18933         default:
18934           gcc_unreachable ();
18935         }
18936       break;
18937
18938     case FRAME_POINTER_REGNUM:
18939       switch (to)
18940         {
18941         case STACK_POINTER_REGNUM:
18942           return offsets->outgoing_args - offsets->soft_frame;
18943
18944         case ARM_HARD_FRAME_POINTER_REGNUM:
18945           return offsets->saved_regs - offsets->soft_frame;
18946
18947         case THUMB_HARD_FRAME_POINTER_REGNUM:
18948           return offsets->locals_base - offsets->soft_frame;
18949
18950         default:
18951           gcc_unreachable ();
18952         }
18953       break;
18954
18955     default:
18956       gcc_unreachable ();
18957     }
18958 }
18959
18960 /* Generate the rest of a function's prologue.  */
18961 void
18962 thumb1_expand_prologue (void)
18963 {
18964   rtx insn, dwarf;
18965
18966   HOST_WIDE_INT amount;
18967   arm_stack_offsets *offsets;
18968   unsigned long func_type;
18969   int regno;
18970   unsigned long live_regs_mask;
18971
18972   func_type = arm_current_func_type ();
18973
18974   /* Naked functions don't have prologues.  */
18975   if (IS_NAKED (func_type))
18976     return;
18977
18978   if (IS_INTERRUPT (func_type))
18979     {
18980       error ("interrupt Service Routines cannot be coded in Thumb mode");
18981       return;
18982     }
18983
18984   offsets = arm_get_frame_offsets ();
18985   live_regs_mask = offsets->saved_regs_mask;
18986   /* Load the pic register before setting the frame pointer,
18987      so we can use r7 as a temporary work register.  */
18988   if (flag_pic && arm_pic_register != INVALID_REGNUM)
18989     arm_load_pic_register (live_regs_mask);
18990
18991   if (!frame_pointer_needed && CALLER_INTERWORKING_SLOT_SIZE > 0)
18992     emit_move_insn (gen_rtx_REG (Pmode, ARM_HARD_FRAME_POINTER_REGNUM),
18993                     stack_pointer_rtx);
18994
18995   amount = offsets->outgoing_args - offsets->saved_regs;
18996   if (amount)
18997     {
18998       if (amount < 512)
18999         {
19000           insn = emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
19001                                         GEN_INT (- amount)));
19002           RTX_FRAME_RELATED_P (insn) = 1;
19003         }
19004       else
19005         {
19006           rtx reg;
19007
19008           /* The stack decrement is too big for an immediate value in a single
19009              insn.  In theory we could issue multiple subtracts, but after
19010              three of them it becomes more space efficient to place the full
19011              value in the constant pool and load into a register.  (Also the
19012              ARM debugger really likes to see only one stack decrement per
19013              function).  So instead we look for a scratch register into which
19014              we can load the decrement, and then we subtract this from the
19015              stack pointer.  Unfortunately on the thumb the only available
19016              scratch registers are the argument registers, and we cannot use
19017              these as they may hold arguments to the function.  Instead we
19018              attempt to locate a call preserved register which is used by this
19019              function.  If we can find one, then we know that it will have
19020              been pushed at the start of the prologue and so we can corrupt
19021              it now.  */
19022           for (regno = LAST_ARG_REGNUM + 1; regno <= LAST_LO_REGNUM; regno++)
19023             if (live_regs_mask & (1 << regno))
19024               break;
19025
19026           gcc_assert(regno <= LAST_LO_REGNUM);
19027
19028           reg = gen_rtx_REG (SImode, regno);
19029
19030           emit_insn (gen_movsi (reg, GEN_INT (- amount)));
19031
19032           insn = emit_insn (gen_addsi3 (stack_pointer_rtx,
19033                                         stack_pointer_rtx, reg));
19034           RTX_FRAME_RELATED_P (insn) = 1;
19035           dwarf = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
19036                                plus_constant (stack_pointer_rtx,
19037                                               -amount));
19038           RTX_FRAME_RELATED_P (dwarf) = 1;
19039           add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
19040         }
19041     }
19042
19043   if (frame_pointer_needed)
19044     thumb_set_frame_pointer (offsets);
19045
19046   /* If we are profiling, make sure no instructions are scheduled before
19047      the call to mcount.  Similarly if the user has requested no
19048      scheduling in the prolog.  Similarly if we want non-call exceptions
19049      using the EABI unwinder, to prevent faulting instructions from being
19050      swapped with a stack adjustment.  */
19051   if (crtl->profile || !TARGET_SCHED_PROLOG
19052       || (ARM_EABI_UNWIND_TABLES && flag_non_call_exceptions))
19053     emit_insn (gen_blockage ());
19054
19055   cfun->machine->lr_save_eliminated = !thumb_force_lr_save ();
19056   if (live_regs_mask & 0xff)
19057     cfun->machine->lr_save_eliminated = 0;
19058 }
19059
19060
19061 void
19062 thumb1_expand_epilogue (void)
19063 {
19064   HOST_WIDE_INT amount;
19065   arm_stack_offsets *offsets;
19066   int regno;
19067
19068   /* Naked functions don't have prologues.  */
19069   if (IS_NAKED (arm_current_func_type ()))
19070     return;
19071
19072   offsets = arm_get_frame_offsets ();
19073   amount = offsets->outgoing_args - offsets->saved_regs;
19074
19075   if (frame_pointer_needed)
19076     {
19077       emit_insn (gen_movsi (stack_pointer_rtx, hard_frame_pointer_rtx));
19078       amount = offsets->locals_base - offsets->saved_regs;
19079     }
19080
19081   gcc_assert (amount >= 0);
19082   if (amount)
19083     {
19084       if (amount < 512)
19085         emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
19086                                GEN_INT (amount)));
19087       else
19088         {
19089           /* r3 is always free in the epilogue.  */
19090           rtx reg = gen_rtx_REG (SImode, LAST_ARG_REGNUM);
19091
19092           emit_insn (gen_movsi (reg, GEN_INT (amount)));
19093           emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx, reg));
19094         }
19095     }
19096
19097   /* Emit a USE (stack_pointer_rtx), so that
19098      the stack adjustment will not be deleted.  */
19099   emit_insn (gen_prologue_use (stack_pointer_rtx));
19100
19101   if (crtl->profile || !TARGET_SCHED_PROLOG)
19102     emit_insn (gen_blockage ());
19103
19104   /* Emit a clobber for each insn that will be restored in the epilogue,
19105      so that flow2 will get register lifetimes correct.  */
19106   for (regno = 0; regno < 13; regno++)
19107     if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
19108       emit_clobber (gen_rtx_REG (SImode, regno));
19109
19110   if (! df_regs_ever_live_p (LR_REGNUM))
19111     emit_use (gen_rtx_REG (SImode, LR_REGNUM));
19112 }
19113
19114 static void
19115 thumb1_output_function_prologue (FILE *f, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
19116 {
19117   arm_stack_offsets *offsets;
19118   unsigned long live_regs_mask = 0;
19119   unsigned long l_mask;
19120   unsigned high_regs_pushed = 0;
19121   int cfa_offset = 0;
19122   int regno;
19123
19124   if (IS_NAKED (arm_current_func_type ()))
19125     return;
19126
19127   if (is_called_in_ARM_mode (current_function_decl))
19128     {
19129       const char * name;
19130
19131       gcc_assert (GET_CODE (DECL_RTL (current_function_decl)) == MEM);
19132       gcc_assert (GET_CODE (XEXP (DECL_RTL (current_function_decl), 0))
19133                   == SYMBOL_REF);
19134       name = XSTR  (XEXP (DECL_RTL (current_function_decl), 0), 0);
19135
19136       /* Generate code sequence to switch us into Thumb mode.  */
19137       /* The .code 32 directive has already been emitted by
19138          ASM_DECLARE_FUNCTION_NAME.  */
19139       asm_fprintf (f, "\torr\t%r, %r, #1\n", IP_REGNUM, PC_REGNUM);
19140       asm_fprintf (f, "\tbx\t%r\n", IP_REGNUM);
19141
19142       /* Generate a label, so that the debugger will notice the
19143          change in instruction sets.  This label is also used by
19144          the assembler to bypass the ARM code when this function
19145          is called from a Thumb encoded function elsewhere in the
19146          same file.  Hence the definition of STUB_NAME here must
19147          agree with the definition in gas/config/tc-arm.c.  */
19148
19149 #define STUB_NAME ".real_start_of"
19150
19151       fprintf (f, "\t.code\t16\n");
19152 #ifdef ARM_PE
19153       if (arm_dllexport_name_p (name))
19154         name = arm_strip_name_encoding (name);
19155 #endif
19156       asm_fprintf (f, "\t.globl %s%U%s\n", STUB_NAME, name);
19157       fprintf (f, "\t.thumb_func\n");
19158       asm_fprintf (f, "%s%U%s:\n", STUB_NAME, name);
19159     }
19160
19161   if (crtl->args.pretend_args_size)
19162     {
19163       /* Output unwind directive for the stack adjustment.  */
19164       if (ARM_EABI_UNWIND_TABLES)
19165         fprintf (f, "\t.pad #%d\n",
19166                  crtl->args.pretend_args_size);
19167
19168       if (cfun->machine->uses_anonymous_args)
19169         {
19170           int num_pushes;
19171
19172           fprintf (f, "\tpush\t{");
19173
19174           num_pushes = ARM_NUM_INTS (crtl->args.pretend_args_size);
19175
19176           for (regno = LAST_ARG_REGNUM + 1 - num_pushes;
19177                regno <= LAST_ARG_REGNUM;
19178                regno++)
19179             asm_fprintf (f, "%r%s", regno,
19180                          regno == LAST_ARG_REGNUM ? "" : ", ");
19181
19182           fprintf (f, "}\n");
19183         }
19184       else
19185         asm_fprintf (f, "\tsub\t%r, %r, #%d\n",
19186                      SP_REGNUM, SP_REGNUM,
19187                      crtl->args.pretend_args_size);
19188
19189       /* We don't need to record the stores for unwinding (would it
19190          help the debugger any if we did?), but record the change in
19191          the stack pointer.  */
19192       if (dwarf2out_do_frame ())
19193         {
19194           char *l = dwarf2out_cfi_label (false);
19195
19196           cfa_offset = cfa_offset + crtl->args.pretend_args_size;
19197           dwarf2out_def_cfa (l, SP_REGNUM, cfa_offset);
19198         }
19199     }
19200
19201   /* Get the registers we are going to push.  */
19202   offsets = arm_get_frame_offsets ();
19203   live_regs_mask = offsets->saved_regs_mask;
19204   /* Extract a mask of the ones we can give to the Thumb's push instruction.  */
19205   l_mask = live_regs_mask & 0x40ff;
19206   /* Then count how many other high registers will need to be pushed.  */
19207   high_regs_pushed = bit_count (live_regs_mask & 0x0f00);
19208
19209   if (TARGET_BACKTRACE)
19210     {
19211       unsigned offset;
19212       unsigned work_register;
19213
19214       /* We have been asked to create a stack backtrace structure.
19215          The code looks like this:
19216
19217          0   .align 2
19218          0   func:
19219          0     sub   SP, #16         Reserve space for 4 registers.
19220          2     push  {R7}            Push low registers.
19221          4     add   R7, SP, #20     Get the stack pointer before the push.
19222          6     str   R7, [SP, #8]    Store the stack pointer (before reserving the space).
19223          8     mov   R7, PC          Get hold of the start of this code plus 12.
19224         10     str   R7, [SP, #16]   Store it.
19225         12     mov   R7, FP          Get hold of the current frame pointer.
19226         14     str   R7, [SP, #4]    Store it.
19227         16     mov   R7, LR          Get hold of the current return address.
19228         18     str   R7, [SP, #12]   Store it.
19229         20     add   R7, SP, #16     Point at the start of the backtrace structure.
19230         22     mov   FP, R7          Put this value into the frame pointer.  */
19231
19232       work_register = thumb_find_work_register (live_regs_mask);
19233
19234       if (ARM_EABI_UNWIND_TABLES)
19235         asm_fprintf (f, "\t.pad #16\n");
19236
19237       asm_fprintf
19238         (f, "\tsub\t%r, %r, #16\t%@ Create stack backtrace structure\n",
19239          SP_REGNUM, SP_REGNUM);
19240
19241       if (dwarf2out_do_frame ())
19242         {
19243           char *l = dwarf2out_cfi_label (false);
19244
19245           cfa_offset = cfa_offset + 16;
19246           dwarf2out_def_cfa (l, SP_REGNUM, cfa_offset);
19247         }
19248
19249       if (l_mask)
19250         {
19251           thumb_pushpop (f, l_mask, 1, &cfa_offset, l_mask);
19252           offset = bit_count (l_mask) * UNITS_PER_WORD;
19253         }
19254       else
19255         offset = 0;
19256
19257       asm_fprintf (f, "\tadd\t%r, %r, #%d\n", work_register, SP_REGNUM,
19258                    offset + 16 + crtl->args.pretend_args_size);
19259
19260       asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19261                    offset + 4);
19262
19263       /* Make sure that the instruction fetching the PC is in the right place
19264          to calculate "start of backtrace creation code + 12".  */
19265       if (l_mask)
19266         {
19267           asm_fprintf (f, "\tmov\t%r, %r\n", work_register, PC_REGNUM);
19268           asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19269                        offset + 12);
19270           asm_fprintf (f, "\tmov\t%r, %r\n", work_register,
19271                        ARM_HARD_FRAME_POINTER_REGNUM);
19272           asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19273                        offset);
19274         }
19275       else
19276         {
19277           asm_fprintf (f, "\tmov\t%r, %r\n", work_register,
19278                        ARM_HARD_FRAME_POINTER_REGNUM);
19279           asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19280                        offset);
19281           asm_fprintf (f, "\tmov\t%r, %r\n", work_register, PC_REGNUM);
19282           asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19283                        offset + 12);
19284         }
19285
19286       asm_fprintf (f, "\tmov\t%r, %r\n", work_register, LR_REGNUM);
19287       asm_fprintf (f, "\tstr\t%r, [%r, #%d]\n", work_register, SP_REGNUM,
19288                    offset + 8);
19289       asm_fprintf (f, "\tadd\t%r, %r, #%d\n", work_register, SP_REGNUM,
19290                    offset + 12);
19291       asm_fprintf (f, "\tmov\t%r, %r\t\t%@ Backtrace structure created\n",
19292                    ARM_HARD_FRAME_POINTER_REGNUM, work_register);
19293     }
19294   /* Optimization:  If we are not pushing any low registers but we are going
19295      to push some high registers then delay our first push.  This will just
19296      be a push of LR and we can combine it with the push of the first high
19297      register.  */
19298   else if ((l_mask & 0xff) != 0
19299            || (high_regs_pushed == 0 && l_mask))
19300     thumb_pushpop (f, l_mask, 1, &cfa_offset, l_mask);
19301
19302   if (high_regs_pushed)
19303     {
19304       unsigned pushable_regs;
19305       unsigned next_hi_reg;
19306
19307       for (next_hi_reg = 12; next_hi_reg > LAST_LO_REGNUM; next_hi_reg--)
19308         if (live_regs_mask & (1 << next_hi_reg))
19309           break;
19310
19311       pushable_regs = l_mask & 0xff;
19312
19313       if (pushable_regs == 0)
19314         pushable_regs = 1 << thumb_find_work_register (live_regs_mask);
19315
19316       while (high_regs_pushed > 0)
19317         {
19318           unsigned long real_regs_mask = 0;
19319
19320           for (regno = LAST_LO_REGNUM; regno >= 0; regno --)
19321             {
19322               if (pushable_regs & (1 << regno))
19323                 {
19324                   asm_fprintf (f, "\tmov\t%r, %r\n", regno, next_hi_reg);
19325
19326                   high_regs_pushed --;
19327                   real_regs_mask |= (1 << next_hi_reg);
19328
19329                   if (high_regs_pushed)
19330                     {
19331                       for (next_hi_reg --; next_hi_reg > LAST_LO_REGNUM;
19332                            next_hi_reg --)
19333                         if (live_regs_mask & (1 << next_hi_reg))
19334                           break;
19335                     }
19336                   else
19337                     {
19338                       pushable_regs &= ~((1 << regno) - 1);
19339                       break;
19340                     }
19341                 }
19342             }
19343
19344           /* If we had to find a work register and we have not yet
19345              saved the LR then add it to the list of regs to push.  */
19346           if (l_mask == (1 << LR_REGNUM))
19347             {
19348               thumb_pushpop (f, pushable_regs | (1 << LR_REGNUM),
19349                              1, &cfa_offset,
19350                              real_regs_mask | (1 << LR_REGNUM));
19351               l_mask = 0;
19352             }
19353           else
19354             thumb_pushpop (f, pushable_regs, 1, &cfa_offset, real_regs_mask);
19355         }
19356     }
19357 }
19358
19359 /* Handle the case of a double word load into a low register from
19360    a computed memory address.  The computed address may involve a
19361    register which is overwritten by the load.  */
19362 const char *
19363 thumb_load_double_from_address (rtx *operands)
19364 {
19365   rtx addr;
19366   rtx base;
19367   rtx offset;
19368   rtx arg1;
19369   rtx arg2;
19370
19371   gcc_assert (GET_CODE (operands[0]) == REG);
19372   gcc_assert (GET_CODE (operands[1]) == MEM);
19373
19374   /* Get the memory address.  */
19375   addr = XEXP (operands[1], 0);
19376
19377   /* Work out how the memory address is computed.  */
19378   switch (GET_CODE (addr))
19379     {
19380     case REG:
19381       operands[2] = adjust_address (operands[1], SImode, 4);
19382
19383       if (REGNO (operands[0]) == REGNO (addr))
19384         {
19385           output_asm_insn ("ldr\t%H0, %2", operands);
19386           output_asm_insn ("ldr\t%0, %1", operands);
19387         }
19388       else
19389         {
19390           output_asm_insn ("ldr\t%0, %1", operands);
19391           output_asm_insn ("ldr\t%H0, %2", operands);
19392         }
19393       break;
19394
19395     case CONST:
19396       /* Compute <address> + 4 for the high order load.  */
19397       operands[2] = adjust_address (operands[1], SImode, 4);
19398
19399       output_asm_insn ("ldr\t%0, %1", operands);
19400       output_asm_insn ("ldr\t%H0, %2", operands);
19401       break;
19402
19403     case PLUS:
19404       arg1   = XEXP (addr, 0);
19405       arg2   = XEXP (addr, 1);
19406
19407       if (CONSTANT_P (arg1))
19408         base = arg2, offset = arg1;
19409       else
19410         base = arg1, offset = arg2;
19411
19412       gcc_assert (GET_CODE (base) == REG);
19413
19414       /* Catch the case of <address> = <reg> + <reg> */
19415       if (GET_CODE (offset) == REG)
19416         {
19417           int reg_offset = REGNO (offset);
19418           int reg_base   = REGNO (base);
19419           int reg_dest   = REGNO (operands[0]);
19420
19421           /* Add the base and offset registers together into the
19422              higher destination register.  */
19423           asm_fprintf (asm_out_file, "\tadd\t%r, %r, %r",
19424                        reg_dest + 1, reg_base, reg_offset);
19425
19426           /* Load the lower destination register from the address in
19427              the higher destination register.  */
19428           asm_fprintf (asm_out_file, "\tldr\t%r, [%r, #0]",
19429                        reg_dest, reg_dest + 1);
19430
19431           /* Load the higher destination register from its own address
19432              plus 4.  */
19433           asm_fprintf (asm_out_file, "\tldr\t%r, [%r, #4]",
19434                        reg_dest + 1, reg_dest + 1);
19435         }
19436       else
19437         {
19438           /* Compute <address> + 4 for the high order load.  */
19439           operands[2] = adjust_address (operands[1], SImode, 4);
19440
19441           /* If the computed address is held in the low order register
19442              then load the high order register first, otherwise always
19443              load the low order register first.  */
19444           if (REGNO (operands[0]) == REGNO (base))
19445             {
19446               output_asm_insn ("ldr\t%H0, %2", operands);
19447               output_asm_insn ("ldr\t%0, %1", operands);
19448             }
19449           else
19450             {
19451               output_asm_insn ("ldr\t%0, %1", operands);
19452               output_asm_insn ("ldr\t%H0, %2", operands);
19453             }
19454         }
19455       break;
19456
19457     case LABEL_REF:
19458       /* With no registers to worry about we can just load the value
19459          directly.  */
19460       operands[2] = adjust_address (operands[1], SImode, 4);
19461
19462       output_asm_insn ("ldr\t%H0, %2", operands);
19463       output_asm_insn ("ldr\t%0, %1", operands);
19464       break;
19465
19466     default:
19467       gcc_unreachable ();
19468     }
19469
19470   return "";
19471 }
19472
19473 const char *
19474 thumb_output_move_mem_multiple (int n, rtx *operands)
19475 {
19476   rtx tmp;
19477
19478   switch (n)
19479     {
19480     case 2:
19481       if (REGNO (operands[4]) > REGNO (operands[5]))
19482         {
19483           tmp = operands[4];
19484           operands[4] = operands[5];
19485           operands[5] = tmp;
19486         }
19487       output_asm_insn ("ldmia\t%1!, {%4, %5}", operands);
19488       output_asm_insn ("stmia\t%0!, {%4, %5}", operands);
19489       break;
19490
19491     case 3:
19492       if (REGNO (operands[4]) > REGNO (operands[5]))
19493         {
19494           tmp = operands[4];
19495           operands[4] = operands[5];
19496           operands[5] = tmp;
19497         }
19498       if (REGNO (operands[5]) > REGNO (operands[6]))
19499         {
19500           tmp = operands[5];
19501           operands[5] = operands[6];
19502           operands[6] = tmp;
19503         }
19504       if (REGNO (operands[4]) > REGNO (operands[5]))
19505         {
19506           tmp = operands[4];
19507           operands[4] = operands[5];
19508           operands[5] = tmp;
19509         }
19510
19511       output_asm_insn ("ldmia\t%1!, {%4, %5, %6}", operands);
19512       output_asm_insn ("stmia\t%0!, {%4, %5, %6}", operands);
19513       break;
19514
19515     default:
19516       gcc_unreachable ();
19517     }
19518
19519   return "";
19520 }
19521
19522 /* Output a call-via instruction for thumb state.  */
19523 const char *
19524 thumb_call_via_reg (rtx reg)
19525 {
19526   int regno = REGNO (reg);
19527   rtx *labelp;
19528
19529   gcc_assert (regno < LR_REGNUM);
19530
19531   /* If we are in the normal text section we can use a single instance
19532      per compilation unit.  If we are doing function sections, then we need
19533      an entry per section, since we can't rely on reachability.  */
19534   if (in_section == text_section)
19535     {
19536       thumb_call_reg_needed = 1;
19537
19538       if (thumb_call_via_label[regno] == NULL)
19539         thumb_call_via_label[regno] = gen_label_rtx ();
19540       labelp = thumb_call_via_label + regno;
19541     }
19542   else
19543     {
19544       if (cfun->machine->call_via[regno] == NULL)
19545         cfun->machine->call_via[regno] = gen_label_rtx ();
19546       labelp = cfun->machine->call_via + regno;
19547     }
19548
19549   output_asm_insn ("bl\t%a0", labelp);
19550   return "";
19551 }
19552
19553 /* Routines for generating rtl.  */
19554 void
19555 thumb_expand_movmemqi (rtx *operands)
19556 {
19557   rtx out = copy_to_mode_reg (SImode, XEXP (operands[0], 0));
19558   rtx in  = copy_to_mode_reg (SImode, XEXP (operands[1], 0));
19559   HOST_WIDE_INT len = INTVAL (operands[2]);
19560   HOST_WIDE_INT offset = 0;
19561
19562   while (len >= 12)
19563     {
19564       emit_insn (gen_movmem12b (out, in, out, in));
19565       len -= 12;
19566     }
19567
19568   if (len >= 8)
19569     {
19570       emit_insn (gen_movmem8b (out, in, out, in));
19571       len -= 8;
19572     }
19573
19574   if (len >= 4)
19575     {
19576       rtx reg = gen_reg_rtx (SImode);
19577       emit_insn (gen_movsi (reg, gen_rtx_MEM (SImode, in)));
19578       emit_insn (gen_movsi (gen_rtx_MEM (SImode, out), reg));
19579       len -= 4;
19580       offset += 4;
19581     }
19582
19583   if (len >= 2)
19584     {
19585       rtx reg = gen_reg_rtx (HImode);
19586       emit_insn (gen_movhi (reg, gen_rtx_MEM (HImode,
19587                                               plus_constant (in, offset))));
19588       emit_insn (gen_movhi (gen_rtx_MEM (HImode, plus_constant (out, offset)),
19589                             reg));
19590       len -= 2;
19591       offset += 2;
19592     }
19593
19594   if (len)
19595     {
19596       rtx reg = gen_reg_rtx (QImode);
19597       emit_insn (gen_movqi (reg, gen_rtx_MEM (QImode,
19598                                               plus_constant (in, offset))));
19599       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (out, offset)),
19600                             reg));
19601     }
19602 }
19603
19604 void
19605 thumb_reload_out_hi (rtx *operands)
19606 {
19607   emit_insn (gen_thumb_movhi_clobber (operands[0], operands[1], operands[2]));
19608 }
19609
19610 /* Handle reading a half-word from memory during reload.  */
19611 void
19612 thumb_reload_in_hi (rtx *operands ATTRIBUTE_UNUSED)
19613 {
19614   gcc_unreachable ();
19615 }
19616
19617 /* Return the length of a function name prefix
19618     that starts with the character 'c'.  */
19619 static int
19620 arm_get_strip_length (int c)
19621 {
19622   switch (c)
19623     {
19624     ARM_NAME_ENCODING_LENGTHS
19625       default: return 0;
19626     }
19627 }
19628
19629 /* Return a pointer to a function's name with any
19630    and all prefix encodings stripped from it.  */
19631 const char *
19632 arm_strip_name_encoding (const char *name)
19633 {
19634   int skip;
19635
19636   while ((skip = arm_get_strip_length (* name)))
19637     name += skip;
19638
19639   return name;
19640 }
19641
19642 /* If there is a '*' anywhere in the name's prefix, then
19643    emit the stripped name verbatim, otherwise prepend an
19644    underscore if leading underscores are being used.  */
19645 void
19646 arm_asm_output_labelref (FILE *stream, const char *name)
19647 {
19648   int skip;
19649   int verbatim = 0;
19650
19651   while ((skip = arm_get_strip_length (* name)))
19652     {
19653       verbatim |= (*name == '*');
19654       name += skip;
19655     }
19656
19657   if (verbatim)
19658     fputs (name, stream);
19659   else
19660     asm_fprintf (stream, "%U%s", name);
19661 }
19662
19663 static void
19664 arm_file_start (void)
19665 {
19666   int val;
19667
19668   if (TARGET_UNIFIED_ASM)
19669     asm_fprintf (asm_out_file, "\t.syntax unified\n");
19670
19671   if (TARGET_BPABI)
19672     {
19673       const char *fpu_name;
19674       if (arm_select[0].string)
19675         asm_fprintf (asm_out_file, "\t.cpu %s\n", arm_select[0].string);
19676       else if (arm_select[1].string)
19677         asm_fprintf (asm_out_file, "\t.arch %s\n", arm_select[1].string);
19678       else
19679         asm_fprintf (asm_out_file, "\t.cpu %s\n",
19680                      all_cores[arm_default_cpu].name);
19681
19682       if (TARGET_SOFT_FLOAT)
19683         {
19684           if (TARGET_VFP)
19685             fpu_name = "softvfp";
19686           else
19687             fpu_name = "softfpa";
19688         }
19689       else
19690         {
19691           int set_float_abi_attributes = 0;
19692           switch (arm_fpu_arch)
19693             {
19694             case FPUTYPE_FPA:
19695               fpu_name = "fpa";
19696               break;
19697             case FPUTYPE_FPA_EMU2:
19698               fpu_name = "fpe2";
19699               break;
19700             case FPUTYPE_FPA_EMU3:
19701               fpu_name = "fpe3";
19702               break;
19703             case FPUTYPE_MAVERICK:
19704               fpu_name = "maverick";
19705               break;
19706             case FPUTYPE_VFP:
19707               fpu_name = "vfp";
19708               set_float_abi_attributes = 1;
19709               break;
19710             case FPUTYPE_VFP3D16:
19711               fpu_name = "vfpv3-d16";
19712               set_float_abi_attributes = 1;
19713               break;
19714             case FPUTYPE_VFP3:
19715               fpu_name = "vfpv3";
19716               set_float_abi_attributes = 1;
19717               break;
19718             case FPUTYPE_NEON:
19719               fpu_name = "neon";
19720               set_float_abi_attributes = 1;
19721               break;
19722             case FPUTYPE_NEON_FP16:
19723               fpu_name = "neon-fp16";
19724               set_float_abi_attributes = 1;
19725               break;
19726             default:
19727               abort();
19728             }
19729           if (set_float_abi_attributes)
19730             {
19731               if (TARGET_HARD_FLOAT)
19732                 asm_fprintf (asm_out_file, "\t.eabi_attribute 27, 3\n");
19733               if (TARGET_HARD_FLOAT_ABI)
19734                 asm_fprintf (asm_out_file, "\t.eabi_attribute 28, 1\n");
19735             }
19736         }
19737       asm_fprintf (asm_out_file, "\t.fpu %s\n", fpu_name);
19738
19739       /* Some of these attributes only apply when the corresponding features
19740          are used.  However we don't have any easy way of figuring this out.
19741          Conservatively record the setting that would have been used.  */
19742
19743       /* Tag_ABI_FP_rounding.  */
19744       if (flag_rounding_math)
19745         asm_fprintf (asm_out_file, "\t.eabi_attribute 19, 1\n");
19746       if (!flag_unsafe_math_optimizations)
19747         {
19748           /* Tag_ABI_FP_denomal.  */
19749           asm_fprintf (asm_out_file, "\t.eabi_attribute 20, 1\n");
19750           /* Tag_ABI_FP_exceptions.  */
19751           asm_fprintf (asm_out_file, "\t.eabi_attribute 21, 1\n");
19752         }
19753       /* Tag_ABI_FP_user_exceptions.  */
19754       if (flag_signaling_nans)
19755         asm_fprintf (asm_out_file, "\t.eabi_attribute 22, 1\n");
19756       /* Tag_ABI_FP_number_model.  */
19757       asm_fprintf (asm_out_file, "\t.eabi_attribute 23, %d\n", 
19758                    flag_finite_math_only ? 1 : 3);
19759
19760       /* Tag_ABI_align8_needed.  */
19761       asm_fprintf (asm_out_file, "\t.eabi_attribute 24, 1\n");
19762       /* Tag_ABI_align8_preserved.  */
19763       asm_fprintf (asm_out_file, "\t.eabi_attribute 25, 1\n");
19764       /* Tag_ABI_enum_size.  */
19765       asm_fprintf (asm_out_file, "\t.eabi_attribute 26, %d\n",
19766                    flag_short_enums ? 1 : 2);
19767
19768       /* Tag_ABI_optimization_goals.  */
19769       if (optimize_size)
19770         val = 4;
19771       else if (optimize >= 2)
19772         val = 2;
19773       else if (optimize)
19774         val = 1;
19775       else
19776         val = 6;
19777       asm_fprintf (asm_out_file, "\t.eabi_attribute 30, %d\n", val);
19778
19779       /* Tag_ABI_FP_16bit_format.  */
19780       if (arm_fp16_format)
19781         asm_fprintf (asm_out_file, "\t.eabi_attribute 38, %d\n",
19782                      (int)arm_fp16_format);
19783
19784       if (arm_lang_output_object_attributes_hook)
19785         arm_lang_output_object_attributes_hook();
19786     }
19787   default_file_start();
19788 }
19789
19790 static void
19791 arm_file_end (void)
19792 {
19793   int regno;
19794
19795   if (NEED_INDICATE_EXEC_STACK)
19796     /* Add .note.GNU-stack.  */
19797     file_end_indicate_exec_stack ();
19798
19799   if (! thumb_call_reg_needed)
19800     return;
19801
19802   switch_to_section (text_section);
19803   asm_fprintf (asm_out_file, "\t.code 16\n");
19804   ASM_OUTPUT_ALIGN (asm_out_file, 1);
19805
19806   for (regno = 0; regno < LR_REGNUM; regno++)
19807     {
19808       rtx label = thumb_call_via_label[regno];
19809
19810       if (label != 0)
19811         {
19812           targetm.asm_out.internal_label (asm_out_file, "L",
19813                                           CODE_LABEL_NUMBER (label));
19814           asm_fprintf (asm_out_file, "\tbx\t%r\n", regno);
19815         }
19816     }
19817 }
19818
19819 #ifndef ARM_PE
19820 /* Symbols in the text segment can be accessed without indirecting via the
19821    constant pool; it may take an extra binary operation, but this is still
19822    faster than indirecting via memory.  Don't do this when not optimizing,
19823    since we won't be calculating al of the offsets necessary to do this
19824    simplification.  */
19825
19826 static void
19827 arm_encode_section_info (tree decl, rtx rtl, int first)
19828 {
19829   if (optimize > 0 && TREE_CONSTANT (decl))
19830     SYMBOL_REF_FLAG (XEXP (rtl, 0)) = 1;
19831
19832   default_encode_section_info (decl, rtl, first);
19833 }
19834 #endif /* !ARM_PE */
19835
19836 static void
19837 arm_internal_label (FILE *stream, const char *prefix, unsigned long labelno)
19838 {
19839   if (arm_ccfsm_state == 3 && (unsigned) arm_target_label == labelno
19840       && !strcmp (prefix, "L"))
19841     {
19842       arm_ccfsm_state = 0;
19843       arm_target_insn = NULL;
19844     }
19845   default_internal_label (stream, prefix, labelno);
19846 }
19847
19848 /* Output code to add DELTA to the first argument, and then jump
19849    to FUNCTION.  Used for C++ multiple inheritance.  */
19850 static void
19851 arm_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
19852                      HOST_WIDE_INT delta,
19853                      HOST_WIDE_INT vcall_offset ATTRIBUTE_UNUSED,
19854                      tree function)
19855 {
19856   static int thunk_label = 0;
19857   char label[256];
19858   char labelpc[256];
19859   int mi_delta = delta;
19860   const char *const mi_op = mi_delta < 0 ? "sub" : "add";
19861   int shift = 0;
19862   int this_regno = (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function)
19863                     ? 1 : 0);
19864   if (mi_delta < 0)
19865     mi_delta = - mi_delta;
19866
19867   if (TARGET_THUMB1)
19868     {
19869       int labelno = thunk_label++;
19870       ASM_GENERATE_INTERNAL_LABEL (label, "LTHUMBFUNC", labelno);
19871       /* Thunks are entered in arm mode when avaiable.  */
19872       if (TARGET_THUMB1_ONLY)
19873         {
19874           /* push r3 so we can use it as a temporary.  */
19875           /* TODO: Omit this save if r3 is not used.  */
19876           fputs ("\tpush {r3}\n", file);
19877           fputs ("\tldr\tr3, ", file);
19878         }
19879       else
19880         {
19881           fputs ("\tldr\tr12, ", file);
19882         }
19883       assemble_name (file, label);
19884       fputc ('\n', file);
19885       if (flag_pic)
19886         {
19887           /* If we are generating PIC, the ldr instruction below loads
19888              "(target - 7) - .LTHUNKPCn" into r12.  The pc reads as
19889              the address of the add + 8, so we have:
19890
19891              r12 = (target - 7) - .LTHUNKPCn + (.LTHUNKPCn + 8)
19892                  = target + 1.
19893
19894              Note that we have "+ 1" because some versions of GNU ld
19895              don't set the low bit of the result for R_ARM_REL32
19896              relocations against thumb function symbols.
19897              On ARMv6M this is +4, not +8.  */
19898           ASM_GENERATE_INTERNAL_LABEL (labelpc, "LTHUNKPC", labelno);
19899           assemble_name (file, labelpc);
19900           fputs (":\n", file);
19901           if (TARGET_THUMB1_ONLY)
19902             {
19903               /* This is 2 insns after the start of the thunk, so we know it
19904                  is 4-byte aligned.  */
19905               fputs ("\tadd\tr3, pc, r3\n", file);
19906               fputs ("\tmov r12, r3\n", file);
19907             }
19908           else
19909             fputs ("\tadd\tr12, pc, r12\n", file);
19910         }
19911       else if (TARGET_THUMB1_ONLY)
19912         fputs ("\tmov r12, r3\n", file);
19913     }
19914   if (TARGET_THUMB1_ONLY)
19915     {
19916       if (mi_delta > 255)
19917         {
19918           fputs ("\tldr\tr3, ", file);
19919           assemble_name (file, label);
19920           fputs ("+4\n", file);
19921           asm_fprintf (file, "\t%s\t%r, %r, r3\n",
19922                        mi_op, this_regno, this_regno);
19923         }
19924       else if (mi_delta != 0)
19925         {
19926           asm_fprintf (file, "\t%s\t%r, %r, #%d\n",
19927                        mi_op, this_regno, this_regno,
19928                        mi_delta);
19929         }
19930     }
19931   else
19932     {
19933       /* TODO: Use movw/movt for large constants when available.  */
19934       while (mi_delta != 0)
19935         {
19936           if ((mi_delta & (3 << shift)) == 0)
19937             shift += 2;
19938           else
19939             {
19940               asm_fprintf (file, "\t%s\t%r, %r, #%d\n",
19941                            mi_op, this_regno, this_regno,
19942                            mi_delta & (0xff << shift));
19943               mi_delta &= ~(0xff << shift);
19944               shift += 8;
19945             }
19946         }
19947     }
19948   if (TARGET_THUMB1)
19949     {
19950       if (TARGET_THUMB1_ONLY)
19951         fputs ("\tpop\t{r3}\n", file);
19952
19953       fprintf (file, "\tbx\tr12\n");
19954       ASM_OUTPUT_ALIGN (file, 2);
19955       assemble_name (file, label);
19956       fputs (":\n", file);
19957       if (flag_pic)
19958         {
19959           /* Output ".word .LTHUNKn-7-.LTHUNKPCn".  */
19960           rtx tem = XEXP (DECL_RTL (function), 0);
19961           tem = gen_rtx_PLUS (GET_MODE (tem), tem, GEN_INT (-7));
19962           tem = gen_rtx_MINUS (GET_MODE (tem),
19963                                tem,
19964                                gen_rtx_SYMBOL_REF (Pmode,
19965                                                    ggc_strdup (labelpc)));
19966           assemble_integer (tem, 4, BITS_PER_WORD, 1);
19967         }
19968       else
19969         /* Output ".word .LTHUNKn".  */
19970         assemble_integer (XEXP (DECL_RTL (function), 0), 4, BITS_PER_WORD, 1);
19971
19972       if (TARGET_THUMB1_ONLY && mi_delta > 255)
19973         assemble_integer (GEN_INT(mi_delta), 4, BITS_PER_WORD, 1);
19974     }
19975   else
19976     {
19977       fputs ("\tb\t", file);
19978       assemble_name (file, XSTR (XEXP (DECL_RTL (function), 0), 0));
19979       if (NEED_PLT_RELOC)
19980         fputs ("(PLT)", file);
19981       fputc ('\n', file);
19982     }
19983 }
19984
19985 int
19986 arm_emit_vector_const (FILE *file, rtx x)
19987 {
19988   int i;
19989   const char * pattern;
19990
19991   gcc_assert (GET_CODE (x) == CONST_VECTOR);
19992
19993   switch (GET_MODE (x))
19994     {
19995     case V2SImode: pattern = "%08x"; break;
19996     case V4HImode: pattern = "%04x"; break;
19997     case V8QImode: pattern = "%02x"; break;
19998     default:       gcc_unreachable ();
19999     }
20000
20001   fprintf (file, "0x");
20002   for (i = CONST_VECTOR_NUNITS (x); i--;)
20003     {
20004       rtx element;
20005
20006       element = CONST_VECTOR_ELT (x, i);
20007       fprintf (file, pattern, INTVAL (element));
20008     }
20009
20010   return 1;
20011 }
20012
20013 /* Emit a fp16 constant appropriately padded to occupy a 4-byte word.
20014    HFmode constant pool entries are actually loaded with ldr.  */
20015 void
20016 arm_emit_fp16_const (rtx c)
20017 {
20018   REAL_VALUE_TYPE r;
20019   long bits;
20020
20021   REAL_VALUE_FROM_CONST_DOUBLE (r, c);
20022   bits = real_to_target (NULL, &r, HFmode);
20023   if (WORDS_BIG_ENDIAN)
20024     assemble_zeros (2);
20025   assemble_integer (GEN_INT (bits), 2, BITS_PER_WORD, 1);
20026   if (!WORDS_BIG_ENDIAN)
20027     assemble_zeros (2);
20028 }
20029
20030 const char *
20031 arm_output_load_gr (rtx *operands)
20032 {
20033   rtx reg;
20034   rtx offset;
20035   rtx wcgr;
20036   rtx sum;
20037
20038   if (GET_CODE (operands [1]) != MEM
20039       || GET_CODE (sum = XEXP (operands [1], 0)) != PLUS
20040       || GET_CODE (reg = XEXP (sum, 0)) != REG
20041       || GET_CODE (offset = XEXP (sum, 1)) != CONST_INT
20042       || ((INTVAL (offset) < 1024) && (INTVAL (offset) > -1024)))
20043     return "wldrw%?\t%0, %1";
20044
20045   /* Fix up an out-of-range load of a GR register.  */
20046   output_asm_insn ("str%?\t%0, [sp, #-4]!\t@ Start of GR load expansion", & reg);
20047   wcgr = operands[0];
20048   operands[0] = reg;
20049   output_asm_insn ("ldr%?\t%0, %1", operands);
20050
20051   operands[0] = wcgr;
20052   operands[1] = reg;
20053   output_asm_insn ("tmcr%?\t%0, %1", operands);
20054   output_asm_insn ("ldr%?\t%0, [sp], #4\t@ End of GR load expansion", & reg);
20055
20056   return "";
20057 }
20058
20059 /* Worker function for TARGET_SETUP_INCOMING_VARARGS.
20060
20061    On the ARM, PRETEND_SIZE is set in order to have the prologue push the last
20062    named arg and all anonymous args onto the stack.
20063    XXX I know the prologue shouldn't be pushing registers, but it is faster
20064    that way.  */
20065
20066 static void
20067 arm_setup_incoming_varargs (CUMULATIVE_ARGS *pcum,
20068                             enum machine_mode mode,
20069                             tree type,
20070                             int *pretend_size,
20071                             int second_time ATTRIBUTE_UNUSED)
20072 {
20073   int nregs;
20074   
20075   cfun->machine->uses_anonymous_args = 1;
20076   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
20077     {
20078       nregs = pcum->aapcs_ncrn;
20079       if ((nregs & 1) && arm_needs_doubleword_align (mode, type))
20080         nregs++;
20081     }
20082   else
20083     nregs = pcum->nregs;
20084   
20085   if (nregs < NUM_ARG_REGS)
20086     *pretend_size = (NUM_ARG_REGS - nregs) * UNITS_PER_WORD;
20087 }
20088
20089 /* Return nonzero if the CONSUMER instruction (a store) does not need
20090    PRODUCER's value to calculate the address.  */
20091
20092 int
20093 arm_no_early_store_addr_dep (rtx producer, rtx consumer)
20094 {
20095   rtx value = PATTERN (producer);
20096   rtx addr = PATTERN (consumer);
20097
20098   if (GET_CODE (value) == COND_EXEC)
20099     value = COND_EXEC_CODE (value);
20100   if (GET_CODE (value) == PARALLEL)
20101     value = XVECEXP (value, 0, 0);
20102   value = XEXP (value, 0);
20103   if (GET_CODE (addr) == COND_EXEC)
20104     addr = COND_EXEC_CODE (addr);
20105   if (GET_CODE (addr) == PARALLEL)
20106     addr = XVECEXP (addr, 0, 0);
20107   addr = XEXP (addr, 0);
20108
20109   return !reg_overlap_mentioned_p (value, addr);
20110 }
20111
20112 /* Return nonzero if the CONSUMER instruction (an ALU op) does not
20113    have an early register shift value or amount dependency on the
20114    result of PRODUCER.  */
20115
20116 int
20117 arm_no_early_alu_shift_dep (rtx producer, rtx consumer)
20118 {
20119   rtx value = PATTERN (producer);
20120   rtx op = PATTERN (consumer);
20121   rtx early_op;
20122
20123   if (GET_CODE (value) == COND_EXEC)
20124     value = COND_EXEC_CODE (value);
20125   if (GET_CODE (value) == PARALLEL)
20126     value = XVECEXP (value, 0, 0);
20127   value = XEXP (value, 0);
20128   if (GET_CODE (op) == COND_EXEC)
20129     op = COND_EXEC_CODE (op);
20130   if (GET_CODE (op) == PARALLEL)
20131     op = XVECEXP (op, 0, 0);
20132   op = XEXP (op, 1);
20133
20134   early_op = XEXP (op, 0);
20135   /* This is either an actual independent shift, or a shift applied to
20136      the first operand of another operation.  We want the whole shift
20137      operation.  */
20138   if (GET_CODE (early_op) == REG)
20139     early_op = op;
20140
20141   return !reg_overlap_mentioned_p (value, early_op);
20142 }
20143
20144 /* Return nonzero if the CONSUMER instruction (an ALU op) does not
20145    have an early register shift value dependency on the result of
20146    PRODUCER.  */
20147
20148 int
20149 arm_no_early_alu_shift_value_dep (rtx producer, rtx consumer)
20150 {
20151   rtx value = PATTERN (producer);
20152   rtx op = PATTERN (consumer);
20153   rtx early_op;
20154
20155   if (GET_CODE (value) == COND_EXEC)
20156     value = COND_EXEC_CODE (value);
20157   if (GET_CODE (value) == PARALLEL)
20158     value = XVECEXP (value, 0, 0);
20159   value = XEXP (value, 0);
20160   if (GET_CODE (op) == COND_EXEC)
20161     op = COND_EXEC_CODE (op);
20162   if (GET_CODE (op) == PARALLEL)
20163     op = XVECEXP (op, 0, 0);
20164   op = XEXP (op, 1);
20165
20166   early_op = XEXP (op, 0);
20167
20168   /* This is either an actual independent shift, or a shift applied to
20169      the first operand of another operation.  We want the value being
20170      shifted, in either case.  */
20171   if (GET_CODE (early_op) != REG)
20172     early_op = XEXP (early_op, 0);
20173
20174   return !reg_overlap_mentioned_p (value, early_op);
20175 }
20176
20177 /* Return nonzero if the CONSUMER (a mul or mac op) does not
20178    have an early register mult dependency on the result of
20179    PRODUCER.  */
20180
20181 int
20182 arm_no_early_mul_dep (rtx producer, rtx consumer)
20183 {
20184   rtx value = PATTERN (producer);
20185   rtx op = PATTERN (consumer);
20186
20187   if (GET_CODE (value) == COND_EXEC)
20188     value = COND_EXEC_CODE (value);
20189   if (GET_CODE (value) == PARALLEL)
20190     value = XVECEXP (value, 0, 0);
20191   value = XEXP (value, 0);
20192   if (GET_CODE (op) == COND_EXEC)
20193     op = COND_EXEC_CODE (op);
20194   if (GET_CODE (op) == PARALLEL)
20195     op = XVECEXP (op, 0, 0);
20196   op = XEXP (op, 1);
20197
20198   if (GET_CODE (op) == PLUS || GET_CODE (op) == MINUS)
20199     {
20200       if (GET_CODE (XEXP (op, 0)) == MULT)
20201         return !reg_overlap_mentioned_p (value, XEXP (op, 0));
20202       else
20203         return !reg_overlap_mentioned_p (value, XEXP (op, 1));
20204     }
20205
20206   return 0;
20207 }
20208
20209 /* We can't rely on the caller doing the proper promotion when
20210    using APCS or ATPCS.  */
20211
20212 static bool
20213 arm_promote_prototypes (const_tree t ATTRIBUTE_UNUSED)
20214 {
20215     return !TARGET_AAPCS_BASED;
20216 }
20217
20218 static enum machine_mode
20219 arm_promote_function_mode (const_tree type ATTRIBUTE_UNUSED,
20220                            enum machine_mode mode,
20221                            int *punsignedp ATTRIBUTE_UNUSED,
20222                            const_tree fntype ATTRIBUTE_UNUSED,
20223                            int for_return ATTRIBUTE_UNUSED)
20224 {
20225   if (GET_MODE_CLASS (mode) == MODE_INT
20226       && GET_MODE_SIZE (mode) < 4)
20227     return SImode;
20228
20229   return mode;
20230 }
20231
20232 /* AAPCS based ABIs use short enums by default.  */
20233
20234 static bool
20235 arm_default_short_enums (void)
20236 {
20237   return TARGET_AAPCS_BASED && arm_abi != ARM_ABI_AAPCS_LINUX;
20238 }
20239
20240
20241 /* AAPCS requires that anonymous bitfields affect structure alignment.  */
20242
20243 static bool
20244 arm_align_anon_bitfield (void)
20245 {
20246   return TARGET_AAPCS_BASED;
20247 }
20248
20249
20250 /* The generic C++ ABI says 64-bit (long long).  The EABI says 32-bit.  */
20251
20252 static tree
20253 arm_cxx_guard_type (void)
20254 {
20255   return TARGET_AAPCS_BASED ? integer_type_node : long_long_integer_type_node;
20256 }
20257
20258 /* Return non-zero if the consumer (a multiply-accumulate instruction)
20259    has an accumulator dependency on the result of the producer (a
20260    multiplication instruction) and no other dependency on that result.  */
20261 int
20262 arm_mac_accumulator_is_mul_result (rtx producer, rtx consumer)
20263 {
20264   rtx mul = PATTERN (producer);
20265   rtx mac = PATTERN (consumer);
20266   rtx mul_result;
20267   rtx mac_op0, mac_op1, mac_acc;
20268
20269   if (GET_CODE (mul) == COND_EXEC)
20270     mul = COND_EXEC_CODE (mul);
20271   if (GET_CODE (mac) == COND_EXEC)
20272     mac = COND_EXEC_CODE (mac);
20273
20274   /* Check that mul is of the form (set (...) (mult ...))
20275      and mla is of the form (set (...) (plus (mult ...) (...))).  */
20276   if ((GET_CODE (mul) != SET || GET_CODE (XEXP (mul, 1)) != MULT)
20277       || (GET_CODE (mac) != SET || GET_CODE (XEXP (mac, 1)) != PLUS
20278           || GET_CODE (XEXP (XEXP (mac, 1), 0)) != MULT))
20279     return 0;
20280
20281   mul_result = XEXP (mul, 0);
20282   mac_op0 = XEXP (XEXP (XEXP (mac, 1), 0), 0);
20283   mac_op1 = XEXP (XEXP (XEXP (mac, 1), 0), 1);
20284   mac_acc = XEXP (XEXP (mac, 1), 1);
20285
20286   return (reg_overlap_mentioned_p (mul_result, mac_acc)
20287           && !reg_overlap_mentioned_p (mul_result, mac_op0)
20288           && !reg_overlap_mentioned_p (mul_result, mac_op1));
20289 }
20290
20291
20292 /* The EABI says test the least significant bit of a guard variable.  */
20293
20294 static bool
20295 arm_cxx_guard_mask_bit (void)
20296 {
20297   return TARGET_AAPCS_BASED;
20298 }
20299
20300
20301 /* The EABI specifies that all array cookies are 8 bytes long.  */
20302
20303 static tree
20304 arm_get_cookie_size (tree type)
20305 {
20306   tree size;
20307
20308   if (!TARGET_AAPCS_BASED)
20309     return default_cxx_get_cookie_size (type);
20310
20311   size = build_int_cst (sizetype, 8);
20312   return size;
20313 }
20314
20315
20316 /* The EABI says that array cookies should also contain the element size.  */
20317
20318 static bool
20319 arm_cookie_has_size (void)
20320 {
20321   return TARGET_AAPCS_BASED;
20322 }
20323
20324
20325 /* The EABI says constructors and destructors should return a pointer to
20326    the object constructed/destroyed.  */
20327
20328 static bool
20329 arm_cxx_cdtor_returns_this (void)
20330 {
20331   return TARGET_AAPCS_BASED;
20332 }
20333
20334 /* The EABI says that an inline function may never be the key
20335    method.  */
20336
20337 static bool
20338 arm_cxx_key_method_may_be_inline (void)
20339 {
20340   return !TARGET_AAPCS_BASED;
20341 }
20342
20343 static void
20344 arm_cxx_determine_class_data_visibility (tree decl)
20345 {
20346   if (!TARGET_AAPCS_BASED
20347       || !TARGET_DLLIMPORT_DECL_ATTRIBUTES)
20348     return;
20349
20350   /* In general, \S 3.2.5.5 of the ARM EABI requires that class data
20351      is exported.  However, on systems without dynamic vague linkage,
20352      \S 3.2.5.6 says that COMDAT class data has hidden linkage.  */
20353   if (!TARGET_ARM_DYNAMIC_VAGUE_LINKAGE_P && DECL_COMDAT (decl))
20354     DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
20355   else
20356     DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
20357   DECL_VISIBILITY_SPECIFIED (decl) = 1;
20358 }
20359
20360 static bool
20361 arm_cxx_class_data_always_comdat (void)
20362 {
20363   /* \S 3.2.5.4 of the ARM C++ ABI says that class data only have
20364      vague linkage if the class has no key function.  */
20365   return !TARGET_AAPCS_BASED;
20366 }
20367
20368
20369 /* The EABI says __aeabi_atexit should be used to register static
20370    destructors.  */
20371
20372 static bool
20373 arm_cxx_use_aeabi_atexit (void)
20374 {
20375   return TARGET_AAPCS_BASED;
20376 }
20377
20378
20379 void
20380 arm_set_return_address (rtx source, rtx scratch)
20381 {
20382   arm_stack_offsets *offsets;
20383   HOST_WIDE_INT delta;
20384   rtx addr;
20385   unsigned long saved_regs;
20386
20387   offsets = arm_get_frame_offsets ();
20388   saved_regs = offsets->saved_regs_mask;
20389
20390   if ((saved_regs & (1 << LR_REGNUM)) == 0)
20391     emit_move_insn (gen_rtx_REG (Pmode, LR_REGNUM), source);
20392   else
20393     {
20394       if (frame_pointer_needed)
20395         addr = plus_constant(hard_frame_pointer_rtx, -4);
20396       else
20397         {
20398           /* LR will be the first saved register.  */
20399           delta = offsets->outgoing_args - (offsets->frame + 4);
20400
20401
20402           if (delta >= 4096)
20403             {
20404               emit_insn (gen_addsi3 (scratch, stack_pointer_rtx,
20405                                      GEN_INT (delta & ~4095)));
20406               addr = scratch;
20407               delta &= 4095;
20408             }
20409           else
20410             addr = stack_pointer_rtx;
20411
20412           addr = plus_constant (addr, delta);
20413         }
20414       emit_move_insn (gen_frame_mem (Pmode, addr), source);
20415     }
20416 }
20417
20418
20419 void
20420 thumb_set_return_address (rtx source, rtx scratch)
20421 {
20422   arm_stack_offsets *offsets;
20423   HOST_WIDE_INT delta;
20424   HOST_WIDE_INT limit;
20425   int reg;
20426   rtx addr;
20427   unsigned long mask;
20428
20429   emit_use (source);
20430
20431   offsets = arm_get_frame_offsets ();
20432   mask = offsets->saved_regs_mask;
20433   if (mask & (1 << LR_REGNUM))
20434     {
20435       limit = 1024;
20436       /* Find the saved regs.  */
20437       if (frame_pointer_needed)
20438         {
20439           delta = offsets->soft_frame - offsets->saved_args;
20440           reg = THUMB_HARD_FRAME_POINTER_REGNUM;
20441           if (TARGET_THUMB1)
20442             limit = 128;
20443         }
20444       else
20445         {
20446           delta = offsets->outgoing_args - offsets->saved_args;
20447           reg = SP_REGNUM;
20448         }
20449       /* Allow for the stack frame.  */
20450       if (TARGET_THUMB1 && TARGET_BACKTRACE)
20451         delta -= 16;
20452       /* The link register is always the first saved register.  */
20453       delta -= 4;
20454
20455       /* Construct the address.  */
20456       addr = gen_rtx_REG (SImode, reg);
20457       if (delta > limit)
20458         {
20459           emit_insn (gen_movsi (scratch, GEN_INT (delta)));
20460           emit_insn (gen_addsi3 (scratch, scratch, stack_pointer_rtx));
20461           addr = scratch;
20462         }
20463       else
20464         addr = plus_constant (addr, delta);
20465
20466       emit_move_insn (gen_frame_mem (Pmode, addr), source);
20467     }
20468   else
20469     emit_move_insn (gen_rtx_REG (Pmode, LR_REGNUM), source);
20470 }
20471
20472 /* Implements target hook vector_mode_supported_p.  */
20473 bool
20474 arm_vector_mode_supported_p (enum machine_mode mode)
20475 {
20476   /* Neon also supports V2SImode, etc. listed in the clause below.  */
20477   if (TARGET_NEON && (mode == V2SFmode || mode == V4SImode || mode == V8HImode
20478       || mode == V16QImode || mode == V4SFmode || mode == V2DImode))
20479     return true;
20480
20481   if ((TARGET_NEON || TARGET_IWMMXT)
20482       && ((mode == V2SImode)
20483           || (mode == V4HImode)
20484           || (mode == V8QImode)))
20485     return true;
20486
20487   return false;
20488 }
20489
20490 /* Implement TARGET_SHIFT_TRUNCATION_MASK.  SImode shifts use normal
20491    ARM insns and therefore guarantee that the shift count is modulo 256.
20492    DImode shifts (those implemented by lib1funcs.asm or by optabs.c)
20493    guarantee no particular behavior for out-of-range counts.  */
20494
20495 static unsigned HOST_WIDE_INT
20496 arm_shift_truncation_mask (enum machine_mode mode)
20497 {
20498   return mode == SImode ? 255 : 0;
20499 }
20500
20501
20502 /* Map internal gcc register numbers to DWARF2 register numbers.  */
20503
20504 unsigned int
20505 arm_dbx_register_number (unsigned int regno)
20506 {
20507   if (regno < 16)
20508     return regno;
20509
20510   /* TODO: Legacy targets output FPA regs as registers 16-23 for backwards
20511      compatibility.  The EABI defines them as registers 96-103.  */
20512   if (IS_FPA_REGNUM (regno))
20513     return (TARGET_AAPCS_BASED ? 96 : 16) + regno - FIRST_FPA_REGNUM;
20514
20515   /* FIXME: VFPv3 register numbering.  */
20516   if (IS_VFP_REGNUM (regno))
20517     return 64 + regno - FIRST_VFP_REGNUM;
20518
20519   if (IS_IWMMXT_GR_REGNUM (regno))
20520     return 104 + regno - FIRST_IWMMXT_GR_REGNUM;
20521
20522   if (IS_IWMMXT_REGNUM (regno))
20523     return 112 + regno - FIRST_IWMMXT_REGNUM;
20524
20525   gcc_unreachable ();
20526 }
20527
20528
20529 #ifdef TARGET_UNWIND_INFO
20530 /* Emit unwind directives for a store-multiple instruction or stack pointer
20531    push during alignment.
20532    These should only ever be generated by the function prologue code, so
20533    expect them to have a particular form.  */
20534
20535 static void
20536 arm_unwind_emit_sequence (FILE * asm_out_file, rtx p)
20537 {
20538   int i;
20539   HOST_WIDE_INT offset;
20540   HOST_WIDE_INT nregs;
20541   int reg_size;
20542   unsigned reg;
20543   unsigned lastreg;
20544   rtx e;
20545
20546   e = XVECEXP (p, 0, 0);
20547   if (GET_CODE (e) != SET)
20548     abort ();
20549
20550   /* First insn will adjust the stack pointer.  */
20551   if (GET_CODE (e) != SET
20552       || GET_CODE (XEXP (e, 0)) != REG
20553       || REGNO (XEXP (e, 0)) != SP_REGNUM
20554       || GET_CODE (XEXP (e, 1)) != PLUS)
20555     abort ();
20556
20557   offset = -INTVAL (XEXP (XEXP (e, 1), 1));
20558   nregs = XVECLEN (p, 0) - 1;
20559
20560   reg = REGNO (XEXP (XVECEXP (p, 0, 1), 1));
20561   if (reg < 16)
20562     {
20563       /* The function prologue may also push pc, but not annotate it as it is
20564          never restored.  We turn this into a stack pointer adjustment.  */
20565       if (nregs * 4 == offset - 4)
20566         {
20567           fprintf (asm_out_file, "\t.pad #4\n");
20568           offset -= 4;
20569         }
20570       reg_size = 4;
20571       fprintf (asm_out_file, "\t.save {");
20572     }
20573   else if (IS_VFP_REGNUM (reg))
20574     {
20575       reg_size = 8;
20576       fprintf (asm_out_file, "\t.vsave {");
20577     }
20578   else if (reg >= FIRST_FPA_REGNUM && reg <= LAST_FPA_REGNUM)
20579     {
20580       /* FPA registers are done differently.  */
20581       asm_fprintf (asm_out_file, "\t.save %r, %wd\n", reg, nregs);
20582       return;
20583     }
20584   else
20585     /* Unknown register type.  */
20586     abort ();
20587
20588   /* If the stack increment doesn't match the size of the saved registers,
20589      something has gone horribly wrong.  */
20590   if (offset != nregs * reg_size)
20591     abort ();
20592
20593   offset = 0;
20594   lastreg = 0;
20595   /* The remaining insns will describe the stores.  */
20596   for (i = 1; i <= nregs; i++)
20597     {
20598       /* Expect (set (mem <addr>) (reg)).
20599          Where <addr> is (reg:SP) or (plus (reg:SP) (const_int)).  */
20600       e = XVECEXP (p, 0, i);
20601       if (GET_CODE (e) != SET
20602           || GET_CODE (XEXP (e, 0)) != MEM
20603           || GET_CODE (XEXP (e, 1)) != REG)
20604         abort ();
20605
20606       reg = REGNO (XEXP (e, 1));
20607       if (reg < lastreg)
20608         abort ();
20609
20610       if (i != 1)
20611         fprintf (asm_out_file, ", ");
20612       /* We can't use %r for vfp because we need to use the
20613          double precision register names.  */
20614       if (IS_VFP_REGNUM (reg))
20615         asm_fprintf (asm_out_file, "d%d", (reg - FIRST_VFP_REGNUM) / 2);
20616       else
20617         asm_fprintf (asm_out_file, "%r", reg);
20618
20619 #ifdef ENABLE_CHECKING
20620       /* Check that the addresses are consecutive.  */
20621       e = XEXP (XEXP (e, 0), 0);
20622       if (GET_CODE (e) == PLUS)
20623         {
20624           offset += reg_size;
20625           if (GET_CODE (XEXP (e, 0)) != REG
20626               || REGNO (XEXP (e, 0)) != SP_REGNUM
20627               || GET_CODE (XEXP (e, 1)) != CONST_INT
20628               || offset != INTVAL (XEXP (e, 1)))
20629             abort ();
20630         }
20631       else if (i != 1
20632                || GET_CODE (e) != REG
20633                || REGNO (e) != SP_REGNUM)
20634         abort ();
20635 #endif
20636     }
20637   fprintf (asm_out_file, "}\n");
20638 }
20639
20640 /*  Emit unwind directives for a SET.  */
20641
20642 static void
20643 arm_unwind_emit_set (FILE * asm_out_file, rtx p)
20644 {
20645   rtx e0;
20646   rtx e1;
20647   unsigned reg;
20648
20649   e0 = XEXP (p, 0);
20650   e1 = XEXP (p, 1);
20651   switch (GET_CODE (e0))
20652     {
20653     case MEM:
20654       /* Pushing a single register.  */
20655       if (GET_CODE (XEXP (e0, 0)) != PRE_DEC
20656           || GET_CODE (XEXP (XEXP (e0, 0), 0)) != REG
20657           || REGNO (XEXP (XEXP (e0, 0), 0)) != SP_REGNUM)
20658         abort ();
20659
20660       asm_fprintf (asm_out_file, "\t.save ");
20661       if (IS_VFP_REGNUM (REGNO (e1)))
20662         asm_fprintf(asm_out_file, "{d%d}\n",
20663                     (REGNO (e1) - FIRST_VFP_REGNUM) / 2);
20664       else
20665         asm_fprintf(asm_out_file, "{%r}\n", REGNO (e1));
20666       break;
20667
20668     case REG:
20669       if (REGNO (e0) == SP_REGNUM)
20670         {
20671           /* A stack increment.  */
20672           if (GET_CODE (e1) != PLUS
20673               || GET_CODE (XEXP (e1, 0)) != REG
20674               || REGNO (XEXP (e1, 0)) != SP_REGNUM
20675               || GET_CODE (XEXP (e1, 1)) != CONST_INT)
20676             abort ();
20677
20678           asm_fprintf (asm_out_file, "\t.pad #%wd\n",
20679                        -INTVAL (XEXP (e1, 1)));
20680         }
20681       else if (REGNO (e0) == HARD_FRAME_POINTER_REGNUM)
20682         {
20683           HOST_WIDE_INT offset;
20684
20685           if (GET_CODE (e1) == PLUS)
20686             {
20687               if (GET_CODE (XEXP (e1, 0)) != REG
20688                   || GET_CODE (XEXP (e1, 1)) != CONST_INT)
20689                 abort ();
20690               reg = REGNO (XEXP (e1, 0));
20691               offset = INTVAL (XEXP (e1, 1));
20692               asm_fprintf (asm_out_file, "\t.setfp %r, %r, #%wd\n",
20693                            HARD_FRAME_POINTER_REGNUM, reg,
20694                            INTVAL (XEXP (e1, 1)));
20695             }
20696           else if (GET_CODE (e1) == REG)
20697             {
20698               reg = REGNO (e1);
20699               asm_fprintf (asm_out_file, "\t.setfp %r, %r\n",
20700                            HARD_FRAME_POINTER_REGNUM, reg);
20701             }
20702           else
20703             abort ();
20704         }
20705       else if (GET_CODE (e1) == REG && REGNO (e1) == SP_REGNUM)
20706         {
20707           /* Move from sp to reg.  */
20708           asm_fprintf (asm_out_file, "\t.movsp %r\n", REGNO (e0));
20709         }
20710      else if (GET_CODE (e1) == PLUS
20711               && GET_CODE (XEXP (e1, 0)) == REG
20712               && REGNO (XEXP (e1, 0)) == SP_REGNUM
20713               && GET_CODE (XEXP (e1, 1)) == CONST_INT)
20714         {
20715           /* Set reg to offset from sp.  */
20716           asm_fprintf (asm_out_file, "\t.movsp %r, #%d\n",
20717                        REGNO (e0), (int)INTVAL(XEXP (e1, 1)));
20718         }
20719       else if (GET_CODE (e1) == UNSPEC && XINT (e1, 1) == UNSPEC_STACK_ALIGN)
20720         {
20721           /* Stack pointer save before alignment.  */
20722           reg = REGNO (e0);
20723           asm_fprintf (asm_out_file, "\t.unwind_raw 0, 0x%x @ vsp = r%d\n",
20724                        reg + 0x90, reg);
20725         }
20726       else
20727         abort ();
20728       break;
20729
20730     default:
20731       abort ();
20732     }
20733 }
20734
20735
20736 /* Emit unwind directives for the given insn.  */
20737
20738 static void
20739 arm_unwind_emit (FILE * asm_out_file, rtx insn)
20740 {
20741   rtx pat;
20742
20743   if (!ARM_EABI_UNWIND_TABLES)
20744     return;
20745
20746   if (!(flag_unwind_tables || crtl->uses_eh_lsda)
20747       && (TREE_NOTHROW (current_function_decl)
20748           || crtl->all_throwers_are_sibcalls))
20749     return;
20750
20751   if (GET_CODE (insn) == NOTE || !RTX_FRAME_RELATED_P (insn))
20752     return;
20753
20754   pat = find_reg_note (insn, REG_FRAME_RELATED_EXPR, NULL_RTX);
20755   if (pat)
20756     pat = XEXP (pat, 0);
20757   else
20758     pat = PATTERN (insn);
20759
20760   switch (GET_CODE (pat))
20761     {
20762     case SET:
20763       arm_unwind_emit_set (asm_out_file, pat);
20764       break;
20765
20766     case SEQUENCE:
20767       /* Store multiple.  */
20768       arm_unwind_emit_sequence (asm_out_file, pat);
20769       break;
20770
20771     default:
20772       abort();
20773     }
20774 }
20775
20776
20777 /* Output a reference from a function exception table to the type_info
20778    object X.  The EABI specifies that the symbol should be relocated by
20779    an R_ARM_TARGET2 relocation.  */
20780
20781 static bool
20782 arm_output_ttype (rtx x)
20783 {
20784   fputs ("\t.word\t", asm_out_file);
20785   output_addr_const (asm_out_file, x);
20786   /* Use special relocations for symbol references.  */
20787   if (GET_CODE (x) != CONST_INT)
20788     fputs ("(TARGET2)", asm_out_file);
20789   fputc ('\n', asm_out_file);
20790
20791   return TRUE;
20792 }
20793 #endif /* TARGET_UNWIND_INFO */
20794
20795
20796 /* Handle UNSPEC DWARF call frame instructions.  These are needed for dynamic
20797    stack alignment.  */
20798
20799 static void
20800 arm_dwarf_handle_frame_unspec (const char *label, rtx pattern, int index)
20801 {
20802   rtx unspec = SET_SRC (pattern);
20803   gcc_assert (GET_CODE (unspec) == UNSPEC);
20804
20805   switch (index)
20806     {
20807     case UNSPEC_STACK_ALIGN:
20808       /* ??? We should set the CFA = (SP & ~7).  At this point we haven't
20809          put anything on the stack, so hopefully it won't matter.
20810          CFA = SP will be correct after alignment.  */
20811       dwarf2out_reg_save_reg (label, stack_pointer_rtx,
20812                               SET_DEST (pattern));
20813       break;
20814     default:
20815       gcc_unreachable ();
20816     }
20817 }
20818
20819
20820 /* Output unwind directives for the start/end of a function.  */
20821
20822 void
20823 arm_output_fn_unwind (FILE * f, bool prologue)
20824 {
20825   if (!ARM_EABI_UNWIND_TABLES)
20826     return;
20827
20828   if (prologue)
20829     fputs ("\t.fnstart\n", f);
20830   else
20831     {
20832       /* If this function will never be unwound, then mark it as such.
20833          The came condition is used in arm_unwind_emit to suppress
20834          the frame annotations.  */
20835       if (!(flag_unwind_tables || crtl->uses_eh_lsda)
20836           && (TREE_NOTHROW (current_function_decl)
20837               || crtl->all_throwers_are_sibcalls))
20838         fputs("\t.cantunwind\n", f);
20839
20840       fputs ("\t.fnend\n", f);
20841     }
20842 }
20843
20844 static bool
20845 arm_emit_tls_decoration (FILE *fp, rtx x)
20846 {
20847   enum tls_reloc reloc;
20848   rtx val;
20849
20850   val = XVECEXP (x, 0, 0);
20851   reloc = (enum tls_reloc) INTVAL (XVECEXP (x, 0, 1));
20852
20853   output_addr_const (fp, val);
20854
20855   switch (reloc)
20856     {
20857     case TLS_GD32:
20858       fputs ("(tlsgd)", fp);
20859       break;
20860     case TLS_LDM32:
20861       fputs ("(tlsldm)", fp);
20862       break;
20863     case TLS_LDO32:
20864       fputs ("(tlsldo)", fp);
20865       break;
20866     case TLS_IE32:
20867       fputs ("(gottpoff)", fp);
20868       break;
20869     case TLS_LE32:
20870       fputs ("(tpoff)", fp);
20871       break;
20872     default:
20873       gcc_unreachable ();
20874     }
20875
20876   switch (reloc)
20877     {
20878     case TLS_GD32:
20879     case TLS_LDM32:
20880     case TLS_IE32:
20881       fputs (" + (. - ", fp);
20882       output_addr_const (fp, XVECEXP (x, 0, 2));
20883       fputs (" - ", fp);
20884       output_addr_const (fp, XVECEXP (x, 0, 3));
20885       fputc (')', fp);
20886       break;
20887     default:
20888       break;
20889     }
20890
20891   return TRUE;
20892 }
20893
20894 /* ARM implementation of TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
20895
20896 static void
20897 arm_output_dwarf_dtprel (FILE *file, int size, rtx x)
20898 {
20899   gcc_assert (size == 4);
20900   fputs ("\t.word\t", file);
20901   output_addr_const (file, x);
20902   fputs ("(tlsldo)", file);
20903 }
20904
20905 bool
20906 arm_output_addr_const_extra (FILE *fp, rtx x)
20907 {
20908   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
20909     return arm_emit_tls_decoration (fp, x);
20910   else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PIC_LABEL)
20911     {
20912       char label[256];
20913       int labelno = INTVAL (XVECEXP (x, 0, 0));
20914
20915       ASM_GENERATE_INTERNAL_LABEL (label, "LPIC", labelno);
20916       assemble_name_raw (fp, label);
20917
20918       return TRUE;
20919     }
20920   else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_GOTSYM_OFF)
20921     {
20922       assemble_name (fp, "_GLOBAL_OFFSET_TABLE_");
20923       if (GOT_PCREL)
20924         fputs ("+.", fp);
20925       fputs ("-(", fp);
20926       output_addr_const (fp, XVECEXP (x, 0, 0));
20927       fputc (')', fp);
20928       return TRUE;
20929     }
20930   else if (GET_CODE (x) == CONST_VECTOR)
20931     return arm_emit_vector_const (fp, x);
20932
20933   return FALSE;
20934 }
20935
20936 /* Output assembly for a shift instruction.
20937    SET_FLAGS determines how the instruction modifies the condition codes.
20938    0 - Do not set condition codes.
20939    1 - Set condition codes.
20940    2 - Use smallest instruction.  */
20941 const char *
20942 arm_output_shift(rtx * operands, int set_flags)
20943 {
20944   char pattern[100];
20945   static const char flag_chars[3] = {'?', '.', '!'};
20946   const char *shift;
20947   HOST_WIDE_INT val;
20948   char c;
20949   
20950   c = flag_chars[set_flags];
20951   if (TARGET_UNIFIED_ASM)
20952     {
20953       shift = shift_op(operands[3], &val);
20954       if (shift)
20955         {
20956           if (val != -1)
20957             operands[2] = GEN_INT(val);
20958           sprintf (pattern, "%s%%%c\t%%0, %%1, %%2", shift, c);
20959         }
20960       else
20961         sprintf (pattern, "mov%%%c\t%%0, %%1", c);
20962     }
20963   else
20964     sprintf (pattern, "mov%%%c\t%%0, %%1%%S3", c);
20965   output_asm_insn (pattern, operands);
20966   return "";
20967 }
20968
20969 /* Output a Thumb-1 casesi dispatch sequence.  */
20970 const char *
20971 thumb1_output_casesi (rtx *operands)
20972 {
20973   rtx diff_vec = PATTERN (next_real_insn (operands[0]));
20974   addr_diff_vec_flags flags;
20975
20976   gcc_assert (GET_CODE (diff_vec) == ADDR_DIFF_VEC);
20977
20978   flags = ADDR_DIFF_VEC_FLAGS (diff_vec);
20979
20980   switch (GET_MODE(diff_vec))
20981     {
20982     case QImode:
20983       return (ADDR_DIFF_VEC_FLAGS (diff_vec).offset_unsigned ? 
20984               "bl\t%___gnu_thumb1_case_uqi" : "bl\t%___gnu_thumb1_case_sqi");
20985     case HImode:
20986       return (ADDR_DIFF_VEC_FLAGS (diff_vec).offset_unsigned ? 
20987               "bl\t%___gnu_thumb1_case_uhi" : "bl\t%___gnu_thumb1_case_shi");
20988     case SImode:
20989       return "bl\t%___gnu_thumb1_case_si";
20990     default:
20991       gcc_unreachable ();
20992     }
20993 }
20994
20995 /* Output a Thumb-2 casesi instruction.  */
20996 const char *
20997 thumb2_output_casesi (rtx *operands)
20998 {
20999   rtx diff_vec = PATTERN (next_real_insn (operands[2]));
21000
21001   gcc_assert (GET_CODE (diff_vec) == ADDR_DIFF_VEC);
21002
21003   output_asm_insn ("cmp\t%0, %1", operands);
21004   output_asm_insn ("bhi\t%l3", operands);
21005   switch (GET_MODE(diff_vec))
21006     {
21007     case QImode:
21008       return "tbb\t[%|pc, %0]";
21009     case HImode:
21010       return "tbh\t[%|pc, %0, lsl #1]";
21011     case SImode:
21012       if (flag_pic)
21013         {
21014           output_asm_insn ("adr\t%4, %l2", operands);
21015           output_asm_insn ("ldr\t%5, [%4, %0, lsl #2]", operands);
21016           output_asm_insn ("add\t%4, %4, %5", operands);
21017           return "bx\t%4";
21018         }
21019       else
21020         {
21021           output_asm_insn ("adr\t%4, %l2", operands);
21022           return "ldr\t%|pc, [%4, %0, lsl #2]";
21023         }
21024     default:
21025       gcc_unreachable ();
21026     }
21027 }
21028
21029 /* Most ARM cores are single issue, but some newer ones can dual issue.
21030    The scheduler descriptions rely on this being correct.  */
21031 static int
21032 arm_issue_rate (void)
21033 {
21034   switch (arm_tune)
21035     {
21036     case cortexr4:
21037     case cortexr4f:
21038     case cortexa8:
21039     case cortexa9:
21040       return 2;
21041
21042     default:
21043       return 1;
21044     }
21045 }
21046
21047 /* A table and a function to perform ARM-specific name mangling for
21048    NEON vector types in order to conform to the AAPCS (see "Procedure
21049    Call Standard for the ARM Architecture", Appendix A).  To qualify
21050    for emission with the mangled names defined in that document, a
21051    vector type must not only be of the correct mode but also be
21052    composed of NEON vector element types (e.g. __builtin_neon_qi).  */
21053 typedef struct
21054 {
21055   enum machine_mode mode;
21056   const char *element_type_name;
21057   const char *aapcs_name;
21058 } arm_mangle_map_entry;
21059
21060 static arm_mangle_map_entry arm_mangle_map[] = {
21061   /* 64-bit containerized types.  */
21062   { V8QImode,  "__builtin_neon_qi",     "15__simd64_int8_t" },
21063   { V8QImode,  "__builtin_neon_uqi",    "16__simd64_uint8_t" },
21064   { V4HImode,  "__builtin_neon_hi",     "16__simd64_int16_t" },
21065   { V4HImode,  "__builtin_neon_uhi",    "17__simd64_uint16_t" },
21066   { V2SImode,  "__builtin_neon_si",     "16__simd64_int32_t" },
21067   { V2SImode,  "__builtin_neon_usi",    "17__simd64_uint32_t" },
21068   { V2SFmode,  "__builtin_neon_sf",     "18__simd64_float32_t" },
21069   { V8QImode,  "__builtin_neon_poly8",  "16__simd64_poly8_t" },
21070   { V4HImode,  "__builtin_neon_poly16", "17__simd64_poly16_t" },
21071   /* 128-bit containerized types.  */
21072   { V16QImode, "__builtin_neon_qi",     "16__simd128_int8_t" },
21073   { V16QImode, "__builtin_neon_uqi",    "17__simd128_uint8_t" },
21074   { V8HImode,  "__builtin_neon_hi",     "17__simd128_int16_t" },
21075   { V8HImode,  "__builtin_neon_uhi",    "18__simd128_uint16_t" },
21076   { V4SImode,  "__builtin_neon_si",     "17__simd128_int32_t" },
21077   { V4SImode,  "__builtin_neon_usi",    "18__simd128_uint32_t" },
21078   { V4SFmode,  "__builtin_neon_sf",     "19__simd128_float32_t" },
21079   { V16QImode, "__builtin_neon_poly8",  "17__simd128_poly8_t" },
21080   { V8HImode,  "__builtin_neon_poly16", "18__simd128_poly16_t" },
21081   { VOIDmode, NULL, NULL }
21082 };
21083
21084 const char *
21085 arm_mangle_type (const_tree type)
21086 {
21087   arm_mangle_map_entry *pos = arm_mangle_map;
21088
21089   /* The ARM ABI documents (10th October 2008) say that "__va_list"
21090      has to be managled as if it is in the "std" namespace.  */
21091   if (TARGET_AAPCS_BASED 
21092       && lang_hooks.types_compatible_p (CONST_CAST_TREE (type), va_list_type))
21093     {
21094       static bool warned;
21095       if (!warned && warn_psabi)
21096         {
21097           warned = true;
21098           inform (input_location,
21099                   "the mangling of %<va_list%> has changed in GCC 4.4");
21100         }
21101       return "St9__va_list";
21102     }
21103
21104   /* Half-precision float.  */
21105   if (TREE_CODE (type) == REAL_TYPE && TYPE_PRECISION (type) == 16)
21106     return "Dh";
21107
21108   if (TREE_CODE (type) != VECTOR_TYPE)
21109     return NULL;
21110
21111   /* Check the mode of the vector type, and the name of the vector
21112      element type, against the table.  */
21113   while (pos->mode != VOIDmode)
21114     {
21115       tree elt_type = TREE_TYPE (type);
21116
21117       if (pos->mode == TYPE_MODE (type)
21118           && TREE_CODE (TYPE_NAME (elt_type)) == TYPE_DECL
21119           && !strcmp (IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (elt_type))),
21120                       pos->element_type_name))
21121         return pos->aapcs_name;
21122
21123       pos++;
21124     }
21125
21126   /* Use the default mangling for unrecognized (possibly user-defined)
21127      vector types.  */
21128   return NULL;
21129 }
21130
21131 /* Order of allocation of core registers for Thumb: this allocation is
21132    written over the corresponding initial entries of the array
21133    initialized with REG_ALLOC_ORDER.  We allocate all low registers
21134    first.  Saving and restoring a low register is usually cheaper than
21135    using a call-clobbered high register.  */
21136
21137 static const int thumb_core_reg_alloc_order[] =
21138 {
21139    3,  2,  1,  0,  4,  5,  6,  7,
21140   14, 12,  8,  9, 10, 11, 13, 15
21141 };
21142
21143 /* Adjust register allocation order when compiling for Thumb.  */
21144
21145 void
21146 arm_order_regs_for_local_alloc (void)
21147 {
21148   const int arm_reg_alloc_order[] = REG_ALLOC_ORDER;
21149   memcpy(reg_alloc_order, arm_reg_alloc_order, sizeof (reg_alloc_order));
21150   if (TARGET_THUMB)
21151     memcpy (reg_alloc_order, thumb_core_reg_alloc_order,
21152             sizeof (thumb_core_reg_alloc_order));
21153 }
21154
21155 /* Set default optimization options.  */
21156 void
21157 arm_optimization_options (int level, int size ATTRIBUTE_UNUSED)
21158 {
21159   /* Enable section anchors by default at -O1 or higher.
21160      Use 2 to distinguish from an explicit -fsection-anchors
21161      given on the command line.  */
21162   if (level > 0)
21163     flag_section_anchors = 2;
21164 }
21165
21166 /* Implement TARGET_FRAME_POINTER_REQUIRED.  */
21167
21168 bool
21169 arm_frame_pointer_required (void)
21170 {
21171   return (cfun->has_nonlocal_label
21172           || SUBTARGET_FRAME_POINTER_REQUIRED
21173           || (TARGET_ARM && TARGET_APCS_FRAME && ! leaf_function_p ()));
21174 }
21175
21176 #include "gt-arm.h"