OSDN Git Service

Fix -O0 -fschedule-insns2 ICE.
[pf3gnuchains/gcc-fork.git] / gcc / config / ia64 / ia64.c
1 /* Definitions of target machine for GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
3    Free Software Foundation, Inc.
4    Contributed by James E. Wilson <wilson@cygnus.com> and
5                   David Mosberger <davidm@hpl.hp.com>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "regs.h"
31 #include "hard-reg-set.h"
32 #include "real.h"
33 #include "insn-config.h"
34 #include "conditions.h"
35 #include "output.h"
36 #include "insn-attr.h"
37 #include "flags.h"
38 #include "recog.h"
39 #include "expr.h"
40 #include "optabs.h"
41 #include "except.h"
42 #include "function.h"
43 #include "ggc.h"
44 #include "basic-block.h"
45 #include "toplev.h"
46 #include "sched-int.h"
47 #include "timevar.h"
48 #include "target.h"
49 #include "target-def.h"
50 #include "tm_p.h"
51 #include "hashtab.h"
52 #include "langhooks.h"
53 #include "cfglayout.h"
54 #include "tree-gimple.h"
55 #include "intl.h"
56
57 /* This is used for communication between ASM_OUTPUT_LABEL and
58    ASM_OUTPUT_LABELREF.  */
59 int ia64_asm_output_label = 0;
60
61 /* Define the information needed to generate branch and scc insns.  This is
62    stored from the compare operation.  */
63 struct rtx_def * ia64_compare_op0;
64 struct rtx_def * ia64_compare_op1;
65
66 /* Register names for ia64_expand_prologue.  */
67 static const char * const ia64_reg_numbers[96] =
68 { "r32", "r33", "r34", "r35", "r36", "r37", "r38", "r39",
69   "r40", "r41", "r42", "r43", "r44", "r45", "r46", "r47",
70   "r48", "r49", "r50", "r51", "r52", "r53", "r54", "r55",
71   "r56", "r57", "r58", "r59", "r60", "r61", "r62", "r63",
72   "r64", "r65", "r66", "r67", "r68", "r69", "r70", "r71",
73   "r72", "r73", "r74", "r75", "r76", "r77", "r78", "r79",
74   "r80", "r81", "r82", "r83", "r84", "r85", "r86", "r87",
75   "r88", "r89", "r90", "r91", "r92", "r93", "r94", "r95",
76   "r96", "r97", "r98", "r99", "r100","r101","r102","r103",
77   "r104","r105","r106","r107","r108","r109","r110","r111",
78   "r112","r113","r114","r115","r116","r117","r118","r119",
79   "r120","r121","r122","r123","r124","r125","r126","r127"};
80
81 /* ??? These strings could be shared with REGISTER_NAMES.  */
82 static const char * const ia64_input_reg_names[8] =
83 { "in0",  "in1",  "in2",  "in3",  "in4",  "in5",  "in6",  "in7" };
84
85 /* ??? These strings could be shared with REGISTER_NAMES.  */
86 static const char * const ia64_local_reg_names[80] =
87 { "loc0", "loc1", "loc2", "loc3", "loc4", "loc5", "loc6", "loc7",
88   "loc8", "loc9", "loc10","loc11","loc12","loc13","loc14","loc15",
89   "loc16","loc17","loc18","loc19","loc20","loc21","loc22","loc23",
90   "loc24","loc25","loc26","loc27","loc28","loc29","loc30","loc31",
91   "loc32","loc33","loc34","loc35","loc36","loc37","loc38","loc39",
92   "loc40","loc41","loc42","loc43","loc44","loc45","loc46","loc47",
93   "loc48","loc49","loc50","loc51","loc52","loc53","loc54","loc55",
94   "loc56","loc57","loc58","loc59","loc60","loc61","loc62","loc63",
95   "loc64","loc65","loc66","loc67","loc68","loc69","loc70","loc71",
96   "loc72","loc73","loc74","loc75","loc76","loc77","loc78","loc79" };
97
98 /* ??? These strings could be shared with REGISTER_NAMES.  */
99 static const char * const ia64_output_reg_names[8] =
100 { "out0", "out1", "out2", "out3", "out4", "out5", "out6", "out7" };
101
102 /* Which cpu are we scheduling for.  */
103 enum processor_type ia64_tune = PROCESSOR_ITANIUM2;
104
105 /* Determines whether we run our final scheduling pass or not.  We always
106    avoid the normal second scheduling pass.  */
107 static int ia64_flag_schedule_insns2;
108
109 /* Determines whether we run variable tracking in machine dependent
110    reorganization.  */
111 static int ia64_flag_var_tracking;
112
113 /* Variables which are this size or smaller are put in the sdata/sbss
114    sections.  */
115
116 unsigned int ia64_section_threshold;
117
118 /* The following variable is used by the DFA insn scheduler.  The value is
119    TRUE if we do insn bundling instead of insn scheduling.  */
120 int bundling_p = 0;
121
122 /* Structure to be filled in by ia64_compute_frame_size with register
123    save masks and offsets for the current function.  */
124
125 struct ia64_frame_info
126 {
127   HOST_WIDE_INT total_size;     /* size of the stack frame, not including
128                                    the caller's scratch area.  */
129   HOST_WIDE_INT spill_cfa_off;  /* top of the reg spill area from the cfa.  */
130   HOST_WIDE_INT spill_size;     /* size of the gr/br/fr spill area.  */
131   HOST_WIDE_INT extra_spill_size;  /* size of spill area for others.  */
132   HARD_REG_SET mask;            /* mask of saved registers.  */
133   unsigned int gr_used_mask;    /* mask of registers in use as gr spill
134                                    registers or long-term scratches.  */
135   int n_spilled;                /* number of spilled registers.  */
136   int reg_fp;                   /* register for fp.  */
137   int reg_save_b0;              /* save register for b0.  */
138   int reg_save_pr;              /* save register for prs.  */
139   int reg_save_ar_pfs;          /* save register for ar.pfs.  */
140   int reg_save_ar_unat;         /* save register for ar.unat.  */
141   int reg_save_ar_lc;           /* save register for ar.lc.  */
142   int reg_save_gp;              /* save register for gp.  */
143   int n_input_regs;             /* number of input registers used.  */
144   int n_local_regs;             /* number of local registers used.  */
145   int n_output_regs;            /* number of output registers used.  */
146   int n_rotate_regs;            /* number of rotating registers used.  */
147
148   char need_regstk;             /* true if a .regstk directive needed.  */
149   char initialized;             /* true if the data is finalized.  */
150 };
151
152 /* Current frame information calculated by ia64_compute_frame_size.  */
153 static struct ia64_frame_info current_frame_info;
154 \f
155 static int ia64_first_cycle_multipass_dfa_lookahead (void);
156 static void ia64_dependencies_evaluation_hook (rtx, rtx);
157 static void ia64_init_dfa_pre_cycle_insn (void);
158 static rtx ia64_dfa_pre_cycle_insn (void);
159 static int ia64_first_cycle_multipass_dfa_lookahead_guard (rtx);
160 static int ia64_dfa_new_cycle (FILE *, int, rtx, int, int, int *);
161 static rtx gen_tls_get_addr (void);
162 static rtx gen_thread_pointer (void);
163 static int find_gr_spill (int);
164 static int next_scratch_gr_reg (void);
165 static void mark_reg_gr_used_mask (rtx, void *);
166 static void ia64_compute_frame_size (HOST_WIDE_INT);
167 static void setup_spill_pointers (int, rtx, HOST_WIDE_INT);
168 static void finish_spill_pointers (void);
169 static rtx spill_restore_mem (rtx, HOST_WIDE_INT);
170 static void do_spill (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT, rtx);
171 static void do_restore (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT);
172 static rtx gen_movdi_x (rtx, rtx, rtx);
173 static rtx gen_fr_spill_x (rtx, rtx, rtx);
174 static rtx gen_fr_restore_x (rtx, rtx, rtx);
175
176 static enum machine_mode hfa_element_mode (tree, bool);
177 static void ia64_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
178                                          tree, int *, int);
179 static bool ia64_pass_by_reference (CUMULATIVE_ARGS *, enum machine_mode,
180                                     tree, bool);
181 static int ia64_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
182                                    tree, bool);
183 static bool ia64_function_ok_for_sibcall (tree, tree);
184 static bool ia64_return_in_memory (tree, tree);
185 static bool ia64_rtx_costs (rtx, int, int, int *);
186 static void fix_range (const char *);
187 static bool ia64_handle_option (size_t, const char *, int);
188 static struct machine_function * ia64_init_machine_status (void);
189 static void emit_insn_group_barriers (FILE *);
190 static void emit_all_insn_group_barriers (FILE *);
191 static void final_emit_insn_group_barriers (FILE *);
192 static void emit_predicate_relation_info (void);
193 static void ia64_reorg (void);
194 static bool ia64_in_small_data_p (tree);
195 static void process_epilogue (void);
196 static int process_set (FILE *, rtx);
197
198 static bool ia64_assemble_integer (rtx, unsigned int, int);
199 static void ia64_output_function_prologue (FILE *, HOST_WIDE_INT);
200 static void ia64_output_function_epilogue (FILE *, HOST_WIDE_INT);
201 static void ia64_output_function_end_prologue (FILE *);
202
203 static int ia64_issue_rate (void);
204 static int ia64_adjust_cost (rtx, rtx, rtx, int);
205 static void ia64_sched_init (FILE *, int, int);
206 static void ia64_sched_finish (FILE *, int);
207 static int ia64_dfa_sched_reorder (FILE *, int, rtx *, int *, int, int);
208 static int ia64_sched_reorder (FILE *, int, rtx *, int *, int);
209 static int ia64_sched_reorder2 (FILE *, int, rtx *, int *, int);
210 static int ia64_variable_issue (FILE *, int, rtx, int);
211
212 static struct bundle_state *get_free_bundle_state (void);
213 static void free_bundle_state (struct bundle_state *);
214 static void initiate_bundle_states (void);
215 static void finish_bundle_states (void);
216 static unsigned bundle_state_hash (const void *);
217 static int bundle_state_eq_p (const void *, const void *);
218 static int insert_bundle_state (struct bundle_state *);
219 static void initiate_bundle_state_table (void);
220 static void finish_bundle_state_table (void);
221 static int try_issue_nops (struct bundle_state *, int);
222 static int try_issue_insn (struct bundle_state *, rtx);
223 static void issue_nops_and_insn (struct bundle_state *, int, rtx, int, int);
224 static int get_max_pos (state_t);
225 static int get_template (state_t, int);
226
227 static rtx get_next_important_insn (rtx, rtx);
228 static void bundling (FILE *, int, rtx, rtx);
229
230 static void ia64_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
231                                   HOST_WIDE_INT, tree);
232 static void ia64_file_start (void);
233
234 static void ia64_select_rtx_section (enum machine_mode, rtx,
235                                      unsigned HOST_WIDE_INT);
236 static void ia64_output_dwarf_dtprel (FILE *, int, rtx)
237      ATTRIBUTE_UNUSED;
238 static void ia64_rwreloc_select_section (tree, int, unsigned HOST_WIDE_INT)
239      ATTRIBUTE_UNUSED;
240 static void ia64_rwreloc_unique_section (tree, int)
241      ATTRIBUTE_UNUSED;
242 static void ia64_rwreloc_select_rtx_section (enum machine_mode, rtx,
243                                              unsigned HOST_WIDE_INT)
244      ATTRIBUTE_UNUSED;
245 static unsigned int ia64_section_type_flags (tree, const char *, int);
246 static void ia64_hpux_add_extern_decl (tree decl)
247      ATTRIBUTE_UNUSED;
248 static void ia64_hpux_file_end (void)
249      ATTRIBUTE_UNUSED;
250 static void ia64_init_libfuncs (void)
251      ATTRIBUTE_UNUSED;
252 static void ia64_hpux_init_libfuncs (void)
253      ATTRIBUTE_UNUSED;
254 static void ia64_sysv4_init_libfuncs (void)
255      ATTRIBUTE_UNUSED;
256 static void ia64_vms_init_libfuncs (void)
257      ATTRIBUTE_UNUSED;
258
259 static tree ia64_handle_model_attribute (tree *, tree, tree, int, bool *);
260 static void ia64_encode_section_info (tree, rtx, int);
261 static rtx ia64_struct_value_rtx (tree, int);
262 static tree ia64_gimplify_va_arg (tree, tree, tree *, tree *);
263 static bool ia64_scalar_mode_supported_p (enum machine_mode mode);
264 static bool ia64_vector_mode_supported_p (enum machine_mode mode);
265 static bool ia64_cannot_force_const_mem (rtx);
266 static const char *ia64_mangle_fundamental_type (tree);
267 static const char *ia64_invalid_conversion (tree, tree);
268 static const char *ia64_invalid_unary_op (int, tree);
269 static const char *ia64_invalid_binary_op (int, tree, tree);
270 \f
271 /* Table of valid machine attributes.  */
272 static const struct attribute_spec ia64_attribute_table[] =
273 {
274   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
275   { "syscall_linkage", 0, 0, false, true,  true,  NULL },
276   { "model",           1, 1, true, false, false, ia64_handle_model_attribute },
277   { NULL,              0, 0, false, false, false, NULL }
278 };
279
280 /* Initialize the GCC target structure.  */
281 #undef TARGET_ATTRIBUTE_TABLE
282 #define TARGET_ATTRIBUTE_TABLE ia64_attribute_table
283
284 #undef TARGET_INIT_BUILTINS
285 #define TARGET_INIT_BUILTINS ia64_init_builtins
286
287 #undef TARGET_EXPAND_BUILTIN
288 #define TARGET_EXPAND_BUILTIN ia64_expand_builtin
289
290 #undef TARGET_ASM_BYTE_OP
291 #define TARGET_ASM_BYTE_OP "\tdata1\t"
292 #undef TARGET_ASM_ALIGNED_HI_OP
293 #define TARGET_ASM_ALIGNED_HI_OP "\tdata2\t"
294 #undef TARGET_ASM_ALIGNED_SI_OP
295 #define TARGET_ASM_ALIGNED_SI_OP "\tdata4\t"
296 #undef TARGET_ASM_ALIGNED_DI_OP
297 #define TARGET_ASM_ALIGNED_DI_OP "\tdata8\t"
298 #undef TARGET_ASM_UNALIGNED_HI_OP
299 #define TARGET_ASM_UNALIGNED_HI_OP "\tdata2.ua\t"
300 #undef TARGET_ASM_UNALIGNED_SI_OP
301 #define TARGET_ASM_UNALIGNED_SI_OP "\tdata4.ua\t"
302 #undef TARGET_ASM_UNALIGNED_DI_OP
303 #define TARGET_ASM_UNALIGNED_DI_OP "\tdata8.ua\t"
304 #undef TARGET_ASM_INTEGER
305 #define TARGET_ASM_INTEGER ia64_assemble_integer
306
307 #undef TARGET_ASM_FUNCTION_PROLOGUE
308 #define TARGET_ASM_FUNCTION_PROLOGUE ia64_output_function_prologue
309 #undef TARGET_ASM_FUNCTION_END_PROLOGUE
310 #define TARGET_ASM_FUNCTION_END_PROLOGUE ia64_output_function_end_prologue
311 #undef TARGET_ASM_FUNCTION_EPILOGUE
312 #define TARGET_ASM_FUNCTION_EPILOGUE ia64_output_function_epilogue
313
314 #undef TARGET_IN_SMALL_DATA_P
315 #define TARGET_IN_SMALL_DATA_P  ia64_in_small_data_p
316
317 #undef TARGET_SCHED_ADJUST_COST
318 #define TARGET_SCHED_ADJUST_COST ia64_adjust_cost
319 #undef TARGET_SCHED_ISSUE_RATE
320 #define TARGET_SCHED_ISSUE_RATE ia64_issue_rate
321 #undef TARGET_SCHED_VARIABLE_ISSUE
322 #define TARGET_SCHED_VARIABLE_ISSUE ia64_variable_issue
323 #undef TARGET_SCHED_INIT
324 #define TARGET_SCHED_INIT ia64_sched_init
325 #undef TARGET_SCHED_FINISH
326 #define TARGET_SCHED_FINISH ia64_sched_finish
327 #undef TARGET_SCHED_REORDER
328 #define TARGET_SCHED_REORDER ia64_sched_reorder
329 #undef TARGET_SCHED_REORDER2
330 #define TARGET_SCHED_REORDER2 ia64_sched_reorder2
331
332 #undef TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK
333 #define TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK ia64_dependencies_evaluation_hook
334
335 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
336 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD ia64_first_cycle_multipass_dfa_lookahead
337
338 #undef TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN
339 #define TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN ia64_init_dfa_pre_cycle_insn
340 #undef TARGET_SCHED_DFA_PRE_CYCLE_INSN
341 #define TARGET_SCHED_DFA_PRE_CYCLE_INSN ia64_dfa_pre_cycle_insn
342
343 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
344 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD\
345   ia64_first_cycle_multipass_dfa_lookahead_guard
346
347 #undef TARGET_SCHED_DFA_NEW_CYCLE
348 #define TARGET_SCHED_DFA_NEW_CYCLE ia64_dfa_new_cycle
349
350 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
351 #define TARGET_FUNCTION_OK_FOR_SIBCALL ia64_function_ok_for_sibcall
352 #undef TARGET_PASS_BY_REFERENCE
353 #define TARGET_PASS_BY_REFERENCE ia64_pass_by_reference
354 #undef TARGET_ARG_PARTIAL_BYTES
355 #define TARGET_ARG_PARTIAL_BYTES ia64_arg_partial_bytes
356
357 #undef TARGET_ASM_OUTPUT_MI_THUNK
358 #define TARGET_ASM_OUTPUT_MI_THUNK ia64_output_mi_thunk
359 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
360 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
361
362 #undef TARGET_ASM_FILE_START
363 #define TARGET_ASM_FILE_START ia64_file_start
364
365 #undef TARGET_RTX_COSTS
366 #define TARGET_RTX_COSTS ia64_rtx_costs
367 #undef TARGET_ADDRESS_COST
368 #define TARGET_ADDRESS_COST hook_int_rtx_0
369
370 #undef TARGET_MACHINE_DEPENDENT_REORG
371 #define TARGET_MACHINE_DEPENDENT_REORG ia64_reorg
372
373 #undef TARGET_ENCODE_SECTION_INFO
374 #define TARGET_ENCODE_SECTION_INFO ia64_encode_section_info
375
376 #undef  TARGET_SECTION_TYPE_FLAGS
377 #define TARGET_SECTION_TYPE_FLAGS  ia64_section_type_flags
378
379 #ifdef HAVE_AS_TLS
380 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
381 #define TARGET_ASM_OUTPUT_DWARF_DTPREL ia64_output_dwarf_dtprel
382 #endif
383
384 /* ??? ABI doesn't allow us to define this.  */
385 #if 0
386 #undef TARGET_PROMOTE_FUNCTION_ARGS
387 #define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_tree_true
388 #endif
389
390 /* ??? ABI doesn't allow us to define this.  */
391 #if 0
392 #undef TARGET_PROMOTE_FUNCTION_RETURN
393 #define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_tree_true
394 #endif
395
396 /* ??? Investigate.  */
397 #if 0
398 #undef TARGET_PROMOTE_PROTOTYPES
399 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
400 #endif
401
402 #undef TARGET_STRUCT_VALUE_RTX
403 #define TARGET_STRUCT_VALUE_RTX ia64_struct_value_rtx
404 #undef TARGET_RETURN_IN_MEMORY
405 #define TARGET_RETURN_IN_MEMORY ia64_return_in_memory
406 #undef TARGET_SETUP_INCOMING_VARARGS
407 #define TARGET_SETUP_INCOMING_VARARGS ia64_setup_incoming_varargs
408 #undef TARGET_STRICT_ARGUMENT_NAMING
409 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
410 #undef TARGET_MUST_PASS_IN_STACK
411 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
412
413 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
414 #define TARGET_GIMPLIFY_VA_ARG_EXPR ia64_gimplify_va_arg
415
416 #undef TARGET_UNWIND_EMIT
417 #define TARGET_UNWIND_EMIT process_for_unwind_directive
418
419 #undef TARGET_SCALAR_MODE_SUPPORTED_P
420 #define TARGET_SCALAR_MODE_SUPPORTED_P ia64_scalar_mode_supported_p
421 #undef TARGET_VECTOR_MODE_SUPPORTED_P
422 #define TARGET_VECTOR_MODE_SUPPORTED_P ia64_vector_mode_supported_p
423
424 /* ia64 architecture manual 4.4.7: ... reads, writes, and flushes may occur
425    in an order different from the specified program order.  */
426 #undef TARGET_RELAXED_ORDERING
427 #define TARGET_RELAXED_ORDERING true
428
429 #undef TARGET_DEFAULT_TARGET_FLAGS
430 #define TARGET_DEFAULT_TARGET_FLAGS (TARGET_DEFAULT | TARGET_CPU_DEFAULT)
431 #undef TARGET_HANDLE_OPTION
432 #define TARGET_HANDLE_OPTION ia64_handle_option
433
434 #undef TARGET_CANNOT_FORCE_CONST_MEM
435 #define TARGET_CANNOT_FORCE_CONST_MEM ia64_cannot_force_const_mem
436
437 #undef TARGET_MANGLE_FUNDAMENTAL_TYPE
438 #define TARGET_MANGLE_FUNDAMENTAL_TYPE ia64_mangle_fundamental_type
439
440 #undef TARGET_INVALID_CONVERSION
441 #define TARGET_INVALID_CONVERSION ia64_invalid_conversion
442 #undef TARGET_INVALID_UNARY_OP
443 #define TARGET_INVALID_UNARY_OP ia64_invalid_unary_op
444 #undef TARGET_INVALID_BINARY_OP
445 #define TARGET_INVALID_BINARY_OP ia64_invalid_binary_op
446
447 struct gcc_target targetm = TARGET_INITIALIZER;
448 \f
449 typedef enum
450   {
451     ADDR_AREA_NORMAL,   /* normal address area */
452     ADDR_AREA_SMALL     /* addressable by "addl" (-2MB < addr < 2MB) */
453   }
454 ia64_addr_area;
455
456 static GTY(()) tree small_ident1;
457 static GTY(()) tree small_ident2;
458
459 static void
460 init_idents (void)
461 {
462   if (small_ident1 == 0)
463     {
464       small_ident1 = get_identifier ("small");
465       small_ident2 = get_identifier ("__small__");
466     }
467 }
468
469 /* Retrieve the address area that has been chosen for the given decl.  */
470
471 static ia64_addr_area
472 ia64_get_addr_area (tree decl)
473 {
474   tree model_attr;
475
476   model_attr = lookup_attribute ("model", DECL_ATTRIBUTES (decl));
477   if (model_attr)
478     {
479       tree id;
480
481       init_idents ();
482       id = TREE_VALUE (TREE_VALUE (model_attr));
483       if (id == small_ident1 || id == small_ident2)
484         return ADDR_AREA_SMALL;
485     }
486   return ADDR_AREA_NORMAL;
487 }
488
489 static tree
490 ia64_handle_model_attribute (tree *node, tree name, tree args,
491                              int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
492 {
493   ia64_addr_area addr_area = ADDR_AREA_NORMAL;
494   ia64_addr_area area;
495   tree arg, decl = *node;
496
497   init_idents ();
498   arg = TREE_VALUE (args);
499   if (arg == small_ident1 || arg == small_ident2)
500     {
501       addr_area = ADDR_AREA_SMALL;
502     }
503   else
504     {
505       warning (OPT_Wattributes, "invalid argument of %qs attribute",
506                IDENTIFIER_POINTER (name));
507       *no_add_attrs = true;
508     }
509
510   switch (TREE_CODE (decl))
511     {
512     case VAR_DECL:
513       if ((DECL_CONTEXT (decl) && TREE_CODE (DECL_CONTEXT (decl))
514            == FUNCTION_DECL)
515           && !TREE_STATIC (decl))
516         {
517           error ("%Jan address area attribute cannot be specified for "
518                  "local variables", decl);
519           *no_add_attrs = true;
520         }
521       area = ia64_get_addr_area (decl);
522       if (area != ADDR_AREA_NORMAL && addr_area != area)
523         {
524           error ("address area of %q+D conflicts with previous "
525                  "declaration", decl);
526           *no_add_attrs = true;
527         }
528       break;
529
530     case FUNCTION_DECL:
531       error ("%Jaddress area attribute cannot be specified for functions",
532              decl);
533       *no_add_attrs = true;
534       break;
535
536     default:
537       warning (OPT_Wattributes, "%qs attribute ignored",
538                IDENTIFIER_POINTER (name));
539       *no_add_attrs = true;
540       break;
541     }
542
543   return NULL_TREE;
544 }
545
546 static void
547 ia64_encode_addr_area (tree decl, rtx symbol)
548 {
549   int flags;
550
551   flags = SYMBOL_REF_FLAGS (symbol);
552   switch (ia64_get_addr_area (decl))
553     {
554     case ADDR_AREA_NORMAL: break;
555     case ADDR_AREA_SMALL: flags |= SYMBOL_FLAG_SMALL_ADDR; break;
556     default: gcc_unreachable ();
557     }
558   SYMBOL_REF_FLAGS (symbol) = flags;
559 }
560
561 static void
562 ia64_encode_section_info (tree decl, rtx rtl, int first)
563 {
564   default_encode_section_info (decl, rtl, first);
565
566   /* Careful not to prod global register variables.  */
567   if (TREE_CODE (decl) == VAR_DECL
568       && GET_CODE (DECL_RTL (decl)) == MEM
569       && GET_CODE (XEXP (DECL_RTL (decl), 0)) == SYMBOL_REF
570       && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
571     ia64_encode_addr_area (decl, XEXP (rtl, 0));
572 }
573 \f
574 /* Implement CONST_OK_FOR_LETTER_P.  */
575
576 bool
577 ia64_const_ok_for_letter_p (HOST_WIDE_INT value, char c)
578 {
579   switch (c)
580     {
581     case 'I':
582       return CONST_OK_FOR_I (value);
583     case 'J':
584       return CONST_OK_FOR_J (value);
585     case 'K':
586       return CONST_OK_FOR_K (value);
587     case 'L':
588       return CONST_OK_FOR_L (value);
589     case 'M':
590       return CONST_OK_FOR_M (value);
591     case 'N':
592       return CONST_OK_FOR_N (value);
593     case 'O':
594       return CONST_OK_FOR_O (value);
595     case 'P':
596       return CONST_OK_FOR_P (value);
597     default:
598       return false;
599     }
600 }
601
602 /* Implement CONST_DOUBLE_OK_FOR_LETTER_P.  */
603
604 bool
605 ia64_const_double_ok_for_letter_p (rtx value, char c)
606 {
607   switch (c)
608     {
609     case 'G':
610       return CONST_DOUBLE_OK_FOR_G (value);
611     default:
612       return false;
613     }
614 }
615
616 /* Implement EXTRA_CONSTRAINT.  */
617
618 bool
619 ia64_extra_constraint (rtx value, char c)
620 {
621   switch (c)
622     {
623     case 'Q':
624       /* Non-volatile memory for FP_REG loads/stores.  */
625       return memory_operand(value, VOIDmode) && !MEM_VOLATILE_P (value);
626
627     case 'R':
628       /* 1..4 for shladd arguments.  */
629       return (GET_CODE (value) == CONST_INT
630               && INTVAL (value) >= 1 && INTVAL (value) <= 4);
631
632     case 'S':
633       /* Non-post-inc memory for asms and other unsavory creatures.  */
634       return (GET_CODE (value) == MEM
635               && GET_RTX_CLASS (GET_CODE (XEXP (value, 0))) != RTX_AUTOINC
636               && (reload_in_progress || memory_operand (value, VOIDmode)));
637
638     case 'T':
639       /* Symbol ref to small-address-area.  */
640       return small_addr_symbolic_operand (value, VOIDmode);
641
642     case 'U':
643       /* Vector zero.  */
644       return value == CONST0_RTX (GET_MODE (value));
645
646     case 'W':
647       /* An integer vector, such that conversion to an integer yields a
648          value appropriate for an integer 'J' constraint.  */
649       if (GET_CODE (value) == CONST_VECTOR
650           && GET_MODE_CLASS (GET_MODE (value)) == MODE_VECTOR_INT)
651         {
652           value = simplify_subreg (DImode, value, GET_MODE (value), 0);
653           return ia64_const_ok_for_letter_p (INTVAL (value), 'J');
654         }
655       return false;
656
657     case 'Y':
658       /* A V2SF vector containing elements that satisfy 'G'.  */
659       return
660         (GET_CODE (value) == CONST_VECTOR
661          && GET_MODE (value) == V2SFmode
662          && ia64_const_double_ok_for_letter_p (XVECEXP (value, 0, 0), 'G')
663          && ia64_const_double_ok_for_letter_p (XVECEXP (value, 0, 1), 'G'));
664
665     default:
666       return false;
667     }
668 }
669 \f
670 /* Return 1 if the operands of a move are ok.  */
671
672 int
673 ia64_move_ok (rtx dst, rtx src)
674 {
675   /* If we're under init_recog_no_volatile, we'll not be able to use
676      memory_operand.  So check the code directly and don't worry about
677      the validity of the underlying address, which should have been
678      checked elsewhere anyway.  */
679   if (GET_CODE (dst) != MEM)
680     return 1;
681   if (GET_CODE (src) == MEM)
682     return 0;
683   if (register_operand (src, VOIDmode))
684     return 1;
685
686   /* Otherwise, this must be a constant, and that either 0 or 0.0 or 1.0.  */
687   if (INTEGRAL_MODE_P (GET_MODE (dst)))
688     return src == const0_rtx;
689   else
690     return GET_CODE (src) == CONST_DOUBLE && CONST_DOUBLE_OK_FOR_G (src);
691 }
692
693 int
694 addp4_optimize_ok (rtx op1, rtx op2)
695 {
696   return (basereg_operand (op1, GET_MODE(op1)) !=
697           basereg_operand (op2, GET_MODE(op2)));
698 }
699
700 /* Check if OP is a mask suitable for use with SHIFT in a dep.z instruction.
701    Return the length of the field, or <= 0 on failure.  */
702
703 int
704 ia64_depz_field_mask (rtx rop, rtx rshift)
705 {
706   unsigned HOST_WIDE_INT op = INTVAL (rop);
707   unsigned HOST_WIDE_INT shift = INTVAL (rshift);
708
709   /* Get rid of the zero bits we're shifting in.  */
710   op >>= shift;
711
712   /* We must now have a solid block of 1's at bit 0.  */
713   return exact_log2 (op + 1);
714 }
715
716 /* Return the TLS model to use for ADDR.  */
717
718 static enum tls_model
719 tls_symbolic_operand_type (rtx addr)
720 {
721   enum tls_model tls_kind = 0;
722
723   if (GET_CODE (addr) == CONST)
724     {
725       if (GET_CODE (XEXP (addr, 0)) == PLUS
726           && GET_CODE (XEXP (XEXP (addr, 0), 0)) == SYMBOL_REF)
727         tls_kind = SYMBOL_REF_TLS_MODEL (XEXP (XEXP (addr, 0), 0));
728     }
729   else if (GET_CODE (addr) == SYMBOL_REF)
730     tls_kind = SYMBOL_REF_TLS_MODEL (addr);
731
732   return tls_kind;
733 }
734
735 /* Return true if X is a constant that is valid for some immediate
736    field in an instruction.  */
737
738 bool
739 ia64_legitimate_constant_p (rtx x)
740 {
741   switch (GET_CODE (x))
742     {
743     case CONST_INT:
744     case LABEL_REF:
745       return true;
746
747     case CONST_DOUBLE:
748       if (GET_MODE (x) == VOIDmode)
749         return true;
750       return CONST_DOUBLE_OK_FOR_G (x);
751
752     case CONST:
753     case SYMBOL_REF:
754       return tls_symbolic_operand_type (x) == 0;
755
756     case CONST_VECTOR:
757       {
758         enum machine_mode mode = GET_MODE (x);
759
760         if (mode == V2SFmode)
761           return ia64_extra_constraint (x, 'Y');
762
763         return (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
764                 && GET_MODE_SIZE (mode) <= 8);
765       }
766
767     default:
768       return false;
769     }
770 }
771
772 /* Don't allow TLS addresses to get spilled to memory.  */
773
774 static bool
775 ia64_cannot_force_const_mem (rtx x)
776 {
777   return tls_symbolic_operand_type (x) != 0;
778 }
779
780 /* Expand a symbolic constant load.  */
781
782 bool
783 ia64_expand_load_address (rtx dest, rtx src)
784 {
785   gcc_assert (GET_CODE (dest) == REG);
786
787   /* ILP32 mode still loads 64-bits of data from the GOT.  This avoids
788      having to pointer-extend the value afterward.  Other forms of address
789      computation below are also more natural to compute as 64-bit quantities.
790      If we've been given an SImode destination register, change it.  */
791   if (GET_MODE (dest) != Pmode)
792     dest = gen_rtx_REG_offset (dest, Pmode, REGNO (dest), 0);
793
794   if (TARGET_NO_PIC)
795     return false;
796   if (small_addr_symbolic_operand (src, VOIDmode))
797     return false;
798
799   if (TARGET_AUTO_PIC)
800     emit_insn (gen_load_gprel64 (dest, src));
801   else if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (src))
802     emit_insn (gen_load_fptr (dest, src));
803   else if (sdata_symbolic_operand (src, VOIDmode))
804     emit_insn (gen_load_gprel (dest, src));
805   else
806     {
807       HOST_WIDE_INT addend = 0;
808       rtx tmp;
809
810       /* We did split constant offsets in ia64_expand_move, and we did try
811          to keep them split in move_operand, but we also allowed reload to
812          rematerialize arbitrary constants rather than spill the value to
813          the stack and reload it.  So we have to be prepared here to split
814          them apart again.  */
815       if (GET_CODE (src) == CONST)
816         {
817           HOST_WIDE_INT hi, lo;
818
819           hi = INTVAL (XEXP (XEXP (src, 0), 1));
820           lo = ((hi & 0x3fff) ^ 0x2000) - 0x2000;
821           hi = hi - lo;
822
823           if (lo != 0)
824             {
825               addend = lo;
826               src = plus_constant (XEXP (XEXP (src, 0), 0), hi);
827             }
828         }
829
830       tmp = gen_rtx_HIGH (Pmode, src);
831       tmp = gen_rtx_PLUS (Pmode, tmp, pic_offset_table_rtx);
832       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
833
834       tmp = gen_rtx_LO_SUM (Pmode, dest, src);
835       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
836
837       if (addend)
838         {
839           tmp = gen_rtx_PLUS (Pmode, dest, GEN_INT (addend));
840           emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
841         }
842     }
843
844   return true;
845 }
846
847 static GTY(()) rtx gen_tls_tga;
848 static rtx
849 gen_tls_get_addr (void)
850 {
851   if (!gen_tls_tga)
852     gen_tls_tga = init_one_libfunc ("__tls_get_addr");
853   return gen_tls_tga;
854 }
855
856 static GTY(()) rtx thread_pointer_rtx;
857 static rtx
858 gen_thread_pointer (void)
859 {
860   if (!thread_pointer_rtx)
861     thread_pointer_rtx = gen_rtx_REG (Pmode, 13);
862   return thread_pointer_rtx;
863 }
864
865 static rtx
866 ia64_expand_tls_address (enum tls_model tls_kind, rtx op0, rtx op1,
867                          HOST_WIDE_INT addend)
868 {
869   rtx tga_op1, tga_op2, tga_ret, tga_eqv, tmp, insns;
870   rtx orig_op0 = op0, orig_op1 = op1;
871   HOST_WIDE_INT addend_lo, addend_hi;
872
873   addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
874   addend_hi = addend - addend_lo;
875
876   switch (tls_kind)
877     {
878     case TLS_MODEL_GLOBAL_DYNAMIC:
879       start_sequence ();
880
881       tga_op1 = gen_reg_rtx (Pmode);
882       emit_insn (gen_load_dtpmod (tga_op1, op1));
883
884       tga_op2 = gen_reg_rtx (Pmode);
885       emit_insn (gen_load_dtprel (tga_op2, op1));
886
887       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
888                                          LCT_CONST, Pmode, 2, tga_op1,
889                                          Pmode, tga_op2, Pmode);
890
891       insns = get_insns ();
892       end_sequence ();
893
894       if (GET_MODE (op0) != Pmode)
895         op0 = tga_ret;
896       emit_libcall_block (insns, op0, tga_ret, op1);
897       break;
898
899     case TLS_MODEL_LOCAL_DYNAMIC:
900       /* ??? This isn't the completely proper way to do local-dynamic
901          If the call to __tls_get_addr is used only by a single symbol,
902          then we should (somehow) move the dtprel to the second arg
903          to avoid the extra add.  */
904       start_sequence ();
905
906       tga_op1 = gen_reg_rtx (Pmode);
907       emit_insn (gen_load_dtpmod (tga_op1, op1));
908
909       tga_op2 = const0_rtx;
910
911       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
912                                          LCT_CONST, Pmode, 2, tga_op1,
913                                          Pmode, tga_op2, Pmode);
914
915       insns = get_insns ();
916       end_sequence ();
917
918       tga_eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
919                                 UNSPEC_LD_BASE);
920       tmp = gen_reg_rtx (Pmode);
921       emit_libcall_block (insns, tmp, tga_ret, tga_eqv);
922
923       if (!register_operand (op0, Pmode))
924         op0 = gen_reg_rtx (Pmode);
925       if (TARGET_TLS64)
926         {
927           emit_insn (gen_load_dtprel (op0, op1));
928           emit_insn (gen_adddi3 (op0, tmp, op0));
929         }
930       else
931         emit_insn (gen_add_dtprel (op0, op1, tmp));
932       break;
933
934     case TLS_MODEL_INITIAL_EXEC:
935       op1 = plus_constant (op1, addend_hi);
936       addend = addend_lo;
937
938       tmp = gen_reg_rtx (Pmode);
939       emit_insn (gen_load_tprel (tmp, op1));
940
941       if (!register_operand (op0, Pmode))
942         op0 = gen_reg_rtx (Pmode);
943       emit_insn (gen_adddi3 (op0, tmp, gen_thread_pointer ()));
944       break;
945
946     case TLS_MODEL_LOCAL_EXEC:
947       if (!register_operand (op0, Pmode))
948         op0 = gen_reg_rtx (Pmode);
949
950       op1 = orig_op1;
951       addend = 0;
952       if (TARGET_TLS64)
953         {
954           emit_insn (gen_load_tprel (op0, op1));
955           emit_insn (gen_adddi3 (op0, op0, gen_thread_pointer ()));
956         }
957       else
958         emit_insn (gen_add_tprel (op0, op1, gen_thread_pointer ()));
959       break;
960
961     default:
962       gcc_unreachable ();
963     }
964
965   if (addend)
966     op0 = expand_simple_binop (Pmode, PLUS, op0, GEN_INT (addend),
967                                orig_op0, 1, OPTAB_DIRECT);
968   if (orig_op0 == op0)
969     return NULL_RTX;
970   if (GET_MODE (orig_op0) == Pmode)
971     return op0;
972   return gen_lowpart (GET_MODE (orig_op0), op0);
973 }
974
975 rtx
976 ia64_expand_move (rtx op0, rtx op1)
977 {
978   enum machine_mode mode = GET_MODE (op0);
979
980   if (!reload_in_progress && !reload_completed && !ia64_move_ok (op0, op1))
981     op1 = force_reg (mode, op1);
982
983   if ((mode == Pmode || mode == ptr_mode) && symbolic_operand (op1, VOIDmode))
984     {
985       HOST_WIDE_INT addend = 0;
986       enum tls_model tls_kind;
987       rtx sym = op1;
988
989       if (GET_CODE (op1) == CONST
990           && GET_CODE (XEXP (op1, 0)) == PLUS
991           && GET_CODE (XEXP (XEXP (op1, 0), 1)) == CONST_INT)
992         {
993           addend = INTVAL (XEXP (XEXP (op1, 0), 1));
994           sym = XEXP (XEXP (op1, 0), 0);
995         }
996
997       tls_kind = tls_symbolic_operand_type (sym);
998       if (tls_kind)
999         return ia64_expand_tls_address (tls_kind, op0, sym, addend);
1000
1001       if (any_offset_symbol_operand (sym, mode))
1002         addend = 0;
1003       else if (aligned_offset_symbol_operand (sym, mode))
1004         {
1005           HOST_WIDE_INT addend_lo, addend_hi;
1006               
1007           addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
1008           addend_hi = addend - addend_lo;
1009
1010           if (addend_lo != 0)
1011             {
1012               op1 = plus_constant (sym, addend_hi);
1013               addend = addend_lo;
1014             }
1015           else
1016             addend = 0;
1017         }
1018       else
1019         op1 = sym;
1020
1021       if (reload_completed)
1022         {
1023           /* We really should have taken care of this offset earlier.  */
1024           gcc_assert (addend == 0);
1025           if (ia64_expand_load_address (op0, op1))
1026             return NULL_RTX;
1027         }
1028
1029       if (addend)
1030         {
1031           rtx subtarget = no_new_pseudos ? op0 : gen_reg_rtx (mode);
1032
1033           emit_insn (gen_rtx_SET (VOIDmode, subtarget, op1));
1034
1035           op1 = expand_simple_binop (mode, PLUS, subtarget,
1036                                      GEN_INT (addend), op0, 1, OPTAB_DIRECT);
1037           if (op0 == op1)
1038             return NULL_RTX;
1039         }
1040     }
1041
1042   return op1;
1043 }
1044
1045 /* Split a move from OP1 to OP0 conditional on COND.  */
1046
1047 void
1048 ia64_emit_cond_move (rtx op0, rtx op1, rtx cond)
1049 {
1050   rtx insn, first = get_last_insn ();
1051
1052   emit_move_insn (op0, op1);
1053
1054   for (insn = get_last_insn (); insn != first; insn = PREV_INSN (insn))
1055     if (INSN_P (insn))
1056       PATTERN (insn) = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond),
1057                                           PATTERN (insn));
1058 }
1059
1060 /* Split a post-reload TImode or TFmode reference into two DImode
1061    components.  This is made extra difficult by the fact that we do
1062    not get any scratch registers to work with, because reload cannot
1063    be prevented from giving us a scratch that overlaps the register
1064    pair involved.  So instead, when addressing memory, we tweak the
1065    pointer register up and back down with POST_INCs.  Or up and not
1066    back down when we can get away with it.
1067
1068    REVERSED is true when the loads must be done in reversed order
1069    (high word first) for correctness.  DEAD is true when the pointer
1070    dies with the second insn we generate and therefore the second
1071    address must not carry a postmodify.
1072
1073    May return an insn which is to be emitted after the moves.  */
1074
1075 static rtx
1076 ia64_split_tmode (rtx out[2], rtx in, bool reversed, bool dead)
1077 {
1078   rtx fixup = 0;
1079
1080   switch (GET_CODE (in))
1081     {
1082     case REG:
1083       out[reversed] = gen_rtx_REG (DImode, REGNO (in));
1084       out[!reversed] = gen_rtx_REG (DImode, REGNO (in) + 1);
1085       break;
1086
1087     case CONST_INT:
1088     case CONST_DOUBLE:
1089       /* Cannot occur reversed.  */
1090       gcc_assert (!reversed);
1091       
1092       if (GET_MODE (in) != TFmode)
1093         split_double (in, &out[0], &out[1]);
1094       else
1095         /* split_double does not understand how to split a TFmode
1096            quantity into a pair of DImode constants.  */
1097         {
1098           REAL_VALUE_TYPE r;
1099           unsigned HOST_WIDE_INT p[2];
1100           long l[4];  /* TFmode is 128 bits */
1101
1102           REAL_VALUE_FROM_CONST_DOUBLE (r, in);
1103           real_to_target (l, &r, TFmode);
1104
1105           if (FLOAT_WORDS_BIG_ENDIAN)
1106             {
1107               p[0] = (((unsigned HOST_WIDE_INT) l[0]) << 32) + l[1];
1108               p[1] = (((unsigned HOST_WIDE_INT) l[2]) << 32) + l[3];
1109             }
1110           else
1111             {
1112               p[0] = (((unsigned HOST_WIDE_INT) l[3]) << 32) + l[2];
1113               p[1] = (((unsigned HOST_WIDE_INT) l[1]) << 32) + l[0];
1114             }
1115           out[0] = GEN_INT (p[0]);
1116           out[1] = GEN_INT (p[1]);
1117         }
1118       break;
1119
1120     case MEM:
1121       {
1122         rtx base = XEXP (in, 0);
1123         rtx offset;
1124
1125         switch (GET_CODE (base))
1126           {
1127           case REG:
1128             if (!reversed)
1129               {
1130                 out[0] = adjust_automodify_address
1131                   (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1132                 out[1] = adjust_automodify_address
1133                   (in, DImode, dead ? 0 : gen_rtx_POST_DEC (Pmode, base), 8);
1134               }
1135             else
1136               {
1137                 /* Reversal requires a pre-increment, which can only
1138                    be done as a separate insn.  */
1139                 emit_insn (gen_adddi3 (base, base, GEN_INT (8)));
1140                 out[0] = adjust_automodify_address
1141                   (in, DImode, gen_rtx_POST_DEC (Pmode, base), 8);
1142                 out[1] = adjust_address (in, DImode, 0);
1143               }
1144             break;
1145
1146           case POST_INC:
1147             gcc_assert (!reversed && !dead);
1148             
1149             /* Just do the increment in two steps.  */
1150             out[0] = adjust_automodify_address (in, DImode, 0, 0);
1151             out[1] = adjust_automodify_address (in, DImode, 0, 8);
1152             break;
1153
1154           case POST_DEC:
1155             gcc_assert (!reversed && !dead);
1156             
1157             /* Add 8, subtract 24.  */
1158             base = XEXP (base, 0);
1159             out[0] = adjust_automodify_address
1160               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1161             out[1] = adjust_automodify_address
1162               (in, DImode,
1163                gen_rtx_POST_MODIFY (Pmode, base, plus_constant (base, -24)),
1164                8);
1165             break;
1166
1167           case POST_MODIFY:
1168             gcc_assert (!reversed && !dead);
1169
1170             /* Extract and adjust the modification.  This case is
1171                trickier than the others, because we might have an
1172                index register, or we might have a combined offset that
1173                doesn't fit a signed 9-bit displacement field.  We can
1174                assume the incoming expression is already legitimate.  */
1175             offset = XEXP (base, 1);
1176             base = XEXP (base, 0);
1177
1178             out[0] = adjust_automodify_address
1179               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1180
1181             if (GET_CODE (XEXP (offset, 1)) == REG)
1182               {
1183                 /* Can't adjust the postmodify to match.  Emit the
1184                    original, then a separate addition insn.  */
1185                 out[1] = adjust_automodify_address (in, DImode, 0, 8);
1186                 fixup = gen_adddi3 (base, base, GEN_INT (-8));
1187               }
1188             else
1189               {
1190                 gcc_assert (GET_CODE (XEXP (offset, 1)) == CONST_INT);
1191                 if (INTVAL (XEXP (offset, 1)) < -256 + 8)
1192                   {
1193                     /* Again the postmodify cannot be made to match,
1194                        but in this case it's more efficient to get rid
1195                        of the postmodify entirely and fix up with an
1196                        add insn.  */
1197                     out[1] = adjust_automodify_address (in, DImode, base, 8);
1198                     fixup = gen_adddi3
1199                       (base, base, GEN_INT (INTVAL (XEXP (offset, 1)) - 8));
1200                   }
1201                 else
1202                   {
1203                     /* Combined offset still fits in the displacement field.
1204                        (We cannot overflow it at the high end.)  */
1205                     out[1] = adjust_automodify_address
1206                       (in, DImode, gen_rtx_POST_MODIFY
1207                        (Pmode, base, gen_rtx_PLUS
1208                         (Pmode, base,
1209                          GEN_INT (INTVAL (XEXP (offset, 1)) - 8))),
1210                        8);
1211                   }
1212               }
1213             break;
1214
1215           default:
1216             gcc_unreachable ();
1217           }
1218         break;
1219       }
1220
1221     default:
1222       gcc_unreachable ();
1223     }
1224
1225   return fixup;
1226 }
1227
1228 /* Split a TImode or TFmode move instruction after reload.
1229    This is used by *movtf_internal and *movti_internal.  */
1230 void
1231 ia64_split_tmode_move (rtx operands[])
1232 {
1233   rtx in[2], out[2], insn;
1234   rtx fixup[2];
1235   bool dead = false;
1236   bool reversed = false;
1237
1238   /* It is possible for reload to decide to overwrite a pointer with
1239      the value it points to.  In that case we have to do the loads in
1240      the appropriate order so that the pointer is not destroyed too
1241      early.  Also we must not generate a postmodify for that second
1242      load, or rws_access_regno will die.  */
1243   if (GET_CODE (operands[1]) == MEM
1244       && reg_overlap_mentioned_p (operands[0], operands[1]))
1245     {
1246       rtx base = XEXP (operands[1], 0);
1247       while (GET_CODE (base) != REG)
1248         base = XEXP (base, 0);
1249
1250       if (REGNO (base) == REGNO (operands[0]))
1251         reversed = true;
1252       dead = true;
1253     }
1254   /* Another reason to do the moves in reversed order is if the first
1255      element of the target register pair is also the second element of
1256      the source register pair.  */
1257   if (GET_CODE (operands[0]) == REG && GET_CODE (operands[1]) == REG
1258       && REGNO (operands[0]) == REGNO (operands[1]) + 1)
1259     reversed = true;
1260
1261   fixup[0] = ia64_split_tmode (in, operands[1], reversed, dead);
1262   fixup[1] = ia64_split_tmode (out, operands[0], reversed, dead);
1263
1264 #define MAYBE_ADD_REG_INC_NOTE(INSN, EXP)                               \
1265   if (GET_CODE (EXP) == MEM                                             \
1266       && (GET_CODE (XEXP (EXP, 0)) == POST_MODIFY                       \
1267           || GET_CODE (XEXP (EXP, 0)) == POST_INC                       \
1268           || GET_CODE (XEXP (EXP, 0)) == POST_DEC))                     \
1269     REG_NOTES (INSN) = gen_rtx_EXPR_LIST (REG_INC,                      \
1270                                           XEXP (XEXP (EXP, 0), 0),      \
1271                                           REG_NOTES (INSN))
1272
1273   insn = emit_insn (gen_rtx_SET (VOIDmode, out[0], in[0]));
1274   MAYBE_ADD_REG_INC_NOTE (insn, in[0]);
1275   MAYBE_ADD_REG_INC_NOTE (insn, out[0]);
1276
1277   insn = emit_insn (gen_rtx_SET (VOIDmode, out[1], in[1]));
1278   MAYBE_ADD_REG_INC_NOTE (insn, in[1]);
1279   MAYBE_ADD_REG_INC_NOTE (insn, out[1]);
1280
1281   if (fixup[0])
1282     emit_insn (fixup[0]);
1283   if (fixup[1])
1284     emit_insn (fixup[1]);
1285
1286 #undef MAYBE_ADD_REG_INC_NOTE
1287 }
1288
1289 /* ??? Fixing GR->FR XFmode moves during reload is hard.  You need to go
1290    through memory plus an extra GR scratch register.  Except that you can
1291    either get the first from SECONDARY_MEMORY_NEEDED or the second from
1292    SECONDARY_RELOAD_CLASS, but not both.
1293
1294    We got into problems in the first place by allowing a construct like
1295    (subreg:XF (reg:TI)), which we got from a union containing a long double.
1296    This solution attempts to prevent this situation from occurring.  When
1297    we see something like the above, we spill the inner register to memory.  */
1298
1299 static rtx
1300 spill_xfmode_rfmode_operand (rtx in, int force, enum machine_mode mode)
1301 {
1302   if (GET_CODE (in) == SUBREG
1303       && GET_MODE (SUBREG_REG (in)) == TImode
1304       && GET_CODE (SUBREG_REG (in)) == REG)
1305     {
1306       rtx memt = assign_stack_temp (TImode, 16, 0);
1307       emit_move_insn (memt, SUBREG_REG (in));
1308       return adjust_address (memt, mode, 0);
1309     }
1310   else if (force && GET_CODE (in) == REG)
1311     {
1312       rtx memx = assign_stack_temp (mode, 16, 0);
1313       emit_move_insn (memx, in);
1314       return memx;
1315     }
1316   else
1317     return in;
1318 }
1319
1320 /* Expand the movxf or movrf pattern (MODE says which) with the given
1321    OPERANDS, returning true if the pattern should then invoke
1322    DONE.  */
1323
1324 bool
1325 ia64_expand_movxf_movrf (enum machine_mode mode, rtx operands[])
1326 {
1327   rtx op0 = operands[0];
1328
1329   if (GET_CODE (op0) == SUBREG)
1330     op0 = SUBREG_REG (op0);
1331
1332   /* We must support XFmode loads into general registers for stdarg/vararg,
1333      unprototyped calls, and a rare case where a long double is passed as
1334      an argument after a float HFA fills the FP registers.  We split them into
1335      DImode loads for convenience.  We also need to support XFmode stores
1336      for the last case.  This case does not happen for stdarg/vararg routines,
1337      because we do a block store to memory of unnamed arguments.  */
1338
1339   if (GET_CODE (op0) == REG && GR_REGNO_P (REGNO (op0)))
1340     {
1341       rtx out[2];
1342
1343       /* We're hoping to transform everything that deals with XFmode
1344          quantities and GR registers early in the compiler.  */
1345       gcc_assert (!no_new_pseudos);
1346
1347       /* Struct to register can just use TImode instead.  */
1348       if ((GET_CODE (operands[1]) == SUBREG
1349            && GET_MODE (SUBREG_REG (operands[1])) == TImode)
1350           || (GET_CODE (operands[1]) == REG
1351               && GR_REGNO_P (REGNO (operands[1]))))
1352         {
1353           rtx op1 = operands[1];
1354
1355           if (GET_CODE (op1) == SUBREG)
1356             op1 = SUBREG_REG (op1);
1357           else
1358             op1 = gen_rtx_REG (TImode, REGNO (op1));
1359
1360           emit_move_insn (gen_rtx_REG (TImode, REGNO (op0)), op1);
1361           return true;
1362         }
1363
1364       if (GET_CODE (operands[1]) == CONST_DOUBLE)
1365         {
1366           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0)),
1367                           operand_subword (operands[1], 0, 0, mode));
1368           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0) + 1),
1369                           operand_subword (operands[1], 1, 0, mode));
1370           return true;
1371         }
1372
1373       /* If the quantity is in a register not known to be GR, spill it.  */
1374       if (register_operand (operands[1], mode))
1375         operands[1] = spill_xfmode_rfmode_operand (operands[1], 1, mode);
1376
1377       gcc_assert (GET_CODE (operands[1]) == MEM);
1378
1379       out[WORDS_BIG_ENDIAN] = gen_rtx_REG (DImode, REGNO (op0));
1380       out[!WORDS_BIG_ENDIAN] = gen_rtx_REG (DImode, REGNO (op0) + 1);
1381
1382       emit_move_insn (out[0], adjust_address (operands[1], DImode, 0));
1383       emit_move_insn (out[1], adjust_address (operands[1], DImode, 8));
1384       return true;
1385     }
1386
1387   if (GET_CODE (operands[1]) == REG && GR_REGNO_P (REGNO (operands[1])))
1388     {
1389       /* We're hoping to transform everything that deals with XFmode
1390          quantities and GR registers early in the compiler.  */
1391       gcc_assert (!no_new_pseudos);
1392
1393       /* Op0 can't be a GR_REG here, as that case is handled above.
1394          If op0 is a register, then we spill op1, so that we now have a
1395          MEM operand.  This requires creating an XFmode subreg of a TImode reg
1396          to force the spill.  */
1397       if (register_operand (operands[0], mode))
1398         {
1399           rtx op1 = gen_rtx_REG (TImode, REGNO (operands[1]));
1400           op1 = gen_rtx_SUBREG (mode, op1, 0);
1401           operands[1] = spill_xfmode_rfmode_operand (op1, 0, mode);
1402         }
1403
1404       else
1405         {
1406           rtx in[2];
1407
1408           gcc_assert (GET_CODE (operands[0]) == MEM);
1409           in[WORDS_BIG_ENDIAN] = gen_rtx_REG (DImode, REGNO (operands[1]));
1410           in[!WORDS_BIG_ENDIAN] = gen_rtx_REG (DImode, REGNO (operands[1]) + 1);
1411
1412           emit_move_insn (adjust_address (operands[0], DImode, 0), in[0]);
1413           emit_move_insn (adjust_address (operands[0], DImode, 8), in[1]);
1414           return true;
1415         }
1416     }
1417
1418   if (!reload_in_progress && !reload_completed)
1419     {
1420       operands[1] = spill_xfmode_rfmode_operand (operands[1], 0, mode);
1421
1422       if (GET_MODE (op0) == TImode && GET_CODE (op0) == REG)
1423         {
1424           rtx memt, memx, in = operands[1];
1425           if (CONSTANT_P (in))
1426             in = validize_mem (force_const_mem (mode, in));
1427           if (GET_CODE (in) == MEM)
1428             memt = adjust_address (in, TImode, 0);
1429           else
1430             {
1431               memt = assign_stack_temp (TImode, 16, 0);
1432               memx = adjust_address (memt, mode, 0);
1433               emit_move_insn (memx, in);
1434             }
1435           emit_move_insn (op0, memt);
1436           return true;
1437         }
1438
1439       if (!ia64_move_ok (operands[0], operands[1]))
1440         operands[1] = force_reg (mode, operands[1]);
1441     }
1442
1443   return false;
1444 }
1445
1446 /* Emit comparison instruction if necessary, returning the expression
1447    that holds the compare result in the proper mode.  */
1448
1449 static GTY(()) rtx cmptf_libfunc;
1450
1451 rtx
1452 ia64_expand_compare (enum rtx_code code, enum machine_mode mode)
1453 {
1454   rtx op0 = ia64_compare_op0, op1 = ia64_compare_op1;
1455   rtx cmp;
1456
1457   /* If we have a BImode input, then we already have a compare result, and
1458      do not need to emit another comparison.  */
1459   if (GET_MODE (op0) == BImode)
1460     {
1461       gcc_assert ((code == NE || code == EQ) && op1 == const0_rtx);
1462       cmp = op0;
1463     }
1464   /* HPUX TFmode compare requires a library call to _U_Qfcmp, which takes a
1465      magic number as its third argument, that indicates what to do.
1466      The return value is an integer to be compared against zero.  */
1467   else if (GET_MODE (op0) == TFmode)
1468     {
1469       enum qfcmp_magic {
1470         QCMP_INV = 1,   /* Raise FP_INVALID on SNaN as a side effect.  */
1471         QCMP_UNORD = 2,
1472         QCMP_EQ = 4,
1473         QCMP_LT = 8,
1474         QCMP_GT = 16
1475       } magic;
1476       enum rtx_code ncode;
1477       rtx ret, insns;
1478       
1479       gcc_assert (cmptf_libfunc && GET_MODE (op1) == TFmode);
1480       switch (code)
1481         {
1482           /* 1 = equal, 0 = not equal.  Equality operators do
1483              not raise FP_INVALID when given an SNaN operand.  */
1484         case EQ:        magic = QCMP_EQ;                  ncode = NE; break;
1485         case NE:        magic = QCMP_EQ;                  ncode = EQ; break;
1486           /* isunordered() from C99.  */
1487         case UNORDERED: magic = QCMP_UNORD;               ncode = NE; break;
1488         case ORDERED:   magic = QCMP_UNORD;               ncode = EQ; break;
1489           /* Relational operators raise FP_INVALID when given
1490              an SNaN operand.  */
1491         case LT:        magic = QCMP_LT        |QCMP_INV; ncode = NE; break;
1492         case LE:        magic = QCMP_LT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1493         case GT:        magic = QCMP_GT        |QCMP_INV; ncode = NE; break;
1494         case GE:        magic = QCMP_GT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1495           /* FUTURE: Implement UNEQ, UNLT, UNLE, UNGT, UNGE, LTGT.
1496              Expanders for buneq etc. weuld have to be added to ia64.md
1497              for this to be useful.  */
1498         default: gcc_unreachable ();
1499         }
1500
1501       start_sequence ();
1502
1503       ret = emit_library_call_value (cmptf_libfunc, 0, LCT_CONST, DImode, 3,
1504                                      op0, TFmode, op1, TFmode,
1505                                      GEN_INT (magic), DImode);
1506       cmp = gen_reg_rtx (BImode);
1507       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1508                               gen_rtx_fmt_ee (ncode, BImode,
1509                                               ret, const0_rtx)));
1510
1511       insns = get_insns ();
1512       end_sequence ();
1513
1514       emit_libcall_block (insns, cmp, cmp,
1515                           gen_rtx_fmt_ee (code, BImode, op0, op1));
1516       code = NE;
1517     }
1518   else
1519     {
1520       cmp = gen_reg_rtx (BImode);
1521       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1522                               gen_rtx_fmt_ee (code, BImode, op0, op1)));
1523       code = NE;
1524     }
1525
1526   return gen_rtx_fmt_ee (code, mode, cmp, const0_rtx);
1527 }
1528
1529 /* Generate an integral vector comparison.  Return true if the condition has
1530    been reversed, and so the sense of the comparison should be inverted.  */
1531
1532 static bool
1533 ia64_expand_vecint_compare (enum rtx_code code, enum machine_mode mode,
1534                             rtx dest, rtx op0, rtx op1)
1535 {
1536   bool negate = false;
1537   rtx x;
1538
1539   /* Canonicalize the comparison to EQ, GT, GTU.  */
1540   switch (code)
1541     {
1542     case EQ:
1543     case GT:
1544     case GTU:
1545       break;
1546
1547     case NE:
1548     case LE:
1549     case LEU:
1550       code = reverse_condition (code);
1551       negate = true;
1552       break;
1553
1554     case GE:
1555     case GEU:
1556       code = reverse_condition (code);
1557       negate = true;
1558       /* FALLTHRU */
1559
1560     case LT:
1561     case LTU:
1562       code = swap_condition (code);
1563       x = op0, op0 = op1, op1 = x;
1564       break;
1565
1566     default:
1567       gcc_unreachable ();
1568     }
1569
1570   /* Unsigned parallel compare is not supported by the hardware.  Play some
1571      tricks to turn this into a signed comparison against 0.  */
1572   if (code == GTU)
1573     {
1574       switch (mode)
1575         {
1576         case V2SImode:
1577           {
1578             rtx t1, t2, mask;
1579
1580             /* Perform a parallel modulo subtraction.  */
1581             t1 = gen_reg_rtx (V2SImode);
1582             emit_insn (gen_subv2si3 (t1, op0, op1));
1583
1584             /* Extract the original sign bit of op0.  */
1585             mask = GEN_INT (-0x80000000);
1586             mask = gen_rtx_CONST_VECTOR (V2SImode, gen_rtvec (2, mask, mask));
1587             mask = force_reg (V2SImode, mask);
1588             t2 = gen_reg_rtx (V2SImode);
1589             emit_insn (gen_andv2si3 (t2, op0, mask));
1590
1591             /* XOR it back into the result of the subtraction.  This results
1592                in the sign bit set iff we saw unsigned underflow.  */
1593             x = gen_reg_rtx (V2SImode);
1594             emit_insn (gen_xorv2si3 (x, t1, t2));
1595
1596             code = GT;
1597             op0 = x;
1598             op1 = CONST0_RTX (mode);
1599           }
1600           break;
1601
1602         case V8QImode:
1603         case V4HImode:
1604           /* Perform a parallel unsigned saturating subtraction.  */
1605           x = gen_reg_rtx (mode);
1606           emit_insn (gen_rtx_SET (VOIDmode, x,
1607                                   gen_rtx_US_MINUS (mode, op0, op1)));
1608
1609           code = EQ;
1610           op0 = x;
1611           op1 = CONST0_RTX (mode);
1612           negate = !negate;
1613           break;
1614
1615         default:
1616           gcc_unreachable ();
1617         }
1618     }
1619
1620   x = gen_rtx_fmt_ee (code, mode, op0, op1);
1621   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
1622
1623   return negate;
1624 }
1625
1626 /* Emit an integral vector conditional move.  */
1627
1628 void
1629 ia64_expand_vecint_cmov (rtx operands[])
1630 {
1631   enum machine_mode mode = GET_MODE (operands[0]);
1632   enum rtx_code code = GET_CODE (operands[3]);
1633   bool negate;
1634   rtx cmp, x, ot, of;
1635
1636   cmp = gen_reg_rtx (mode);
1637   negate = ia64_expand_vecint_compare (code, mode, cmp,
1638                                        operands[4], operands[5]);
1639
1640   ot = operands[1+negate];
1641   of = operands[2-negate];
1642
1643   if (ot == CONST0_RTX (mode))
1644     {
1645       if (of == CONST0_RTX (mode))
1646         {
1647           emit_move_insn (operands[0], ot);
1648           return;
1649         }
1650
1651       x = gen_rtx_NOT (mode, cmp);
1652       x = gen_rtx_AND (mode, x, of);
1653       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1654     }
1655   else if (of == CONST0_RTX (mode))
1656     {
1657       x = gen_rtx_AND (mode, cmp, ot);
1658       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1659     }
1660   else
1661     {
1662       rtx t, f;
1663
1664       t = gen_reg_rtx (mode);
1665       x = gen_rtx_AND (mode, cmp, operands[1+negate]);
1666       emit_insn (gen_rtx_SET (VOIDmode, t, x));
1667
1668       f = gen_reg_rtx (mode);
1669       x = gen_rtx_NOT (mode, cmp);
1670       x = gen_rtx_AND (mode, x, operands[2-negate]);
1671       emit_insn (gen_rtx_SET (VOIDmode, f, x));
1672
1673       x = gen_rtx_IOR (mode, t, f);
1674       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1675     }
1676 }
1677
1678 /* Emit an integral vector min or max operation.  Return true if all done.  */
1679
1680 bool
1681 ia64_expand_vecint_minmax (enum rtx_code code, enum machine_mode mode,
1682                            rtx operands[])
1683 {
1684   rtx xops[6];
1685
1686   /* These four combinations are supported directly.  */
1687   if (mode == V8QImode && (code == UMIN || code == UMAX))
1688     return false;
1689   if (mode == V4HImode && (code == SMIN || code == SMAX))
1690     return false;
1691
1692   /* This combination can be implemented with only saturating subtraction.  */
1693   if (mode == V4HImode && code == UMAX)
1694     {
1695       rtx x, tmp = gen_reg_rtx (mode);
1696
1697       x = gen_rtx_US_MINUS (mode, operands[1], operands[2]);
1698       emit_insn (gen_rtx_SET (VOIDmode, tmp, x));
1699
1700       emit_insn (gen_addv4hi3 (operands[0], tmp, operands[2]));
1701       return true;
1702     }
1703
1704   /* Everything else implemented via vector comparisons.  */
1705   xops[0] = operands[0];
1706   xops[4] = xops[1] = operands[1];
1707   xops[5] = xops[2] = operands[2];
1708
1709   switch (code)
1710     {
1711     case UMIN:
1712       code = LTU;
1713       break;
1714     case UMAX:
1715       code = GTU;
1716       break;
1717     case SMIN:
1718       code = LT;
1719       break;
1720     case SMAX:
1721       code = GT;
1722       break;
1723     default:
1724       gcc_unreachable ();
1725     }
1726   xops[3] = gen_rtx_fmt_ee (code, VOIDmode, operands[1], operands[2]);
1727
1728   ia64_expand_vecint_cmov (xops);
1729   return true;
1730 }
1731
1732 /* Emit the appropriate sequence for a call.  */
1733
1734 void
1735 ia64_expand_call (rtx retval, rtx addr, rtx nextarg ATTRIBUTE_UNUSED,
1736                   int sibcall_p)
1737 {
1738   rtx insn, b0;
1739
1740   addr = XEXP (addr, 0);
1741   addr = convert_memory_address (DImode, addr);
1742   b0 = gen_rtx_REG (DImode, R_BR (0));
1743
1744   /* ??? Should do this for functions known to bind local too.  */
1745   if (TARGET_NO_PIC || TARGET_AUTO_PIC)
1746     {
1747       if (sibcall_p)
1748         insn = gen_sibcall_nogp (addr);
1749       else if (! retval)
1750         insn = gen_call_nogp (addr, b0);
1751       else
1752         insn = gen_call_value_nogp (retval, addr, b0);
1753       insn = emit_call_insn (insn);
1754     }
1755   else
1756     {
1757       if (sibcall_p)
1758         insn = gen_sibcall_gp (addr);
1759       else if (! retval)
1760         insn = gen_call_gp (addr, b0);
1761       else
1762         insn = gen_call_value_gp (retval, addr, b0);
1763       insn = emit_call_insn (insn);
1764
1765       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
1766     }
1767
1768   if (sibcall_p)
1769     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), b0);
1770 }
1771
1772 void
1773 ia64_reload_gp (void)
1774 {
1775   rtx tmp;
1776
1777   if (current_frame_info.reg_save_gp)
1778     tmp = gen_rtx_REG (DImode, current_frame_info.reg_save_gp);
1779   else
1780     {
1781       HOST_WIDE_INT offset;
1782
1783       offset = (current_frame_info.spill_cfa_off
1784                 + current_frame_info.spill_size);
1785       if (frame_pointer_needed)
1786         {
1787           tmp = hard_frame_pointer_rtx;
1788           offset = -offset;
1789         }
1790       else
1791         {
1792           tmp = stack_pointer_rtx;
1793           offset = current_frame_info.total_size - offset;
1794         }
1795
1796       if (CONST_OK_FOR_I (offset))
1797         emit_insn (gen_adddi3 (pic_offset_table_rtx,
1798                                tmp, GEN_INT (offset)));
1799       else
1800         {
1801           emit_move_insn (pic_offset_table_rtx, GEN_INT (offset));
1802           emit_insn (gen_adddi3 (pic_offset_table_rtx,
1803                                  pic_offset_table_rtx, tmp));
1804         }
1805
1806       tmp = gen_rtx_MEM (DImode, pic_offset_table_rtx);
1807     }
1808
1809   emit_move_insn (pic_offset_table_rtx, tmp);
1810 }
1811
1812 void
1813 ia64_split_call (rtx retval, rtx addr, rtx retaddr, rtx scratch_r,
1814                  rtx scratch_b, int noreturn_p, int sibcall_p)
1815 {
1816   rtx insn;
1817   bool is_desc = false;
1818
1819   /* If we find we're calling through a register, then we're actually
1820      calling through a descriptor, so load up the values.  */
1821   if (REG_P (addr) && GR_REGNO_P (REGNO (addr)))
1822     {
1823       rtx tmp;
1824       bool addr_dead_p;
1825
1826       /* ??? We are currently constrained to *not* use peep2, because
1827          we can legitimately change the global lifetime of the GP
1828          (in the form of killing where previously live).  This is
1829          because a call through a descriptor doesn't use the previous
1830          value of the GP, while a direct call does, and we do not
1831          commit to either form until the split here.
1832
1833          That said, this means that we lack precise life info for
1834          whether ADDR is dead after this call.  This is not terribly
1835          important, since we can fix things up essentially for free
1836          with the POST_DEC below, but it's nice to not use it when we
1837          can immediately tell it's not necessary.  */
1838       addr_dead_p = ((noreturn_p || sibcall_p
1839                       || TEST_HARD_REG_BIT (regs_invalidated_by_call,
1840                                             REGNO (addr)))
1841                      && !FUNCTION_ARG_REGNO_P (REGNO (addr)));
1842
1843       /* Load the code address into scratch_b.  */
1844       tmp = gen_rtx_POST_INC (Pmode, addr);
1845       tmp = gen_rtx_MEM (Pmode, tmp);
1846       emit_move_insn (scratch_r, tmp);
1847       emit_move_insn (scratch_b, scratch_r);
1848
1849       /* Load the GP address.  If ADDR is not dead here, then we must
1850          revert the change made above via the POST_INCREMENT.  */
1851       if (!addr_dead_p)
1852         tmp = gen_rtx_POST_DEC (Pmode, addr);
1853       else
1854         tmp = addr;
1855       tmp = gen_rtx_MEM (Pmode, tmp);
1856       emit_move_insn (pic_offset_table_rtx, tmp);
1857
1858       is_desc = true;
1859       addr = scratch_b;
1860     }
1861
1862   if (sibcall_p)
1863     insn = gen_sibcall_nogp (addr);
1864   else if (retval)
1865     insn = gen_call_value_nogp (retval, addr, retaddr);
1866   else
1867     insn = gen_call_nogp (addr, retaddr);
1868   emit_call_insn (insn);
1869
1870   if ((!TARGET_CONST_GP || is_desc) && !noreturn_p && !sibcall_p)
1871     ia64_reload_gp ();
1872 }
1873
1874 /* Expand an atomic operation.  We want to perform MEM <CODE>= VAL atomically.
1875
1876    This differs from the generic code in that we know about the zero-extending
1877    properties of cmpxchg, and the zero-extending requirements of ar.ccv.  We
1878    also know that ld.acq+cmpxchg.rel equals a full barrier.
1879
1880    The loop we want to generate looks like
1881
1882         cmp_reg = mem;
1883       label:
1884         old_reg = cmp_reg;
1885         new_reg = cmp_reg op val;
1886         cmp_reg = compare-and-swap(mem, old_reg, new_reg)
1887         if (cmp_reg != old_reg)
1888           goto label;
1889
1890    Note that we only do the plain load from memory once.  Subsequent
1891    iterations use the value loaded by the compare-and-swap pattern.  */
1892
1893 void
1894 ia64_expand_atomic_op (enum rtx_code code, rtx mem, rtx val,
1895                        rtx old_dst, rtx new_dst)
1896 {
1897   enum machine_mode mode = GET_MODE (mem);
1898   rtx old_reg, new_reg, cmp_reg, ar_ccv, label;
1899   enum insn_code icode;
1900
1901   /* Special case for using fetchadd.  */
1902   if ((mode == SImode || mode == DImode) && fetchadd_operand (val, mode))
1903     {
1904       if (!old_dst)
1905         old_dst = gen_reg_rtx (mode);
1906
1907       emit_insn (gen_memory_barrier ());
1908
1909       if (mode == SImode)
1910         icode = CODE_FOR_fetchadd_acq_si;
1911       else
1912         icode = CODE_FOR_fetchadd_acq_di;
1913       emit_insn (GEN_FCN (icode) (old_dst, mem, val));
1914
1915       if (new_dst)
1916         {
1917           new_reg = expand_simple_binop (mode, PLUS, old_dst, val, new_dst,
1918                                          true, OPTAB_WIDEN);
1919           if (new_reg != new_dst)
1920             emit_move_insn (new_dst, new_reg);
1921         }
1922       return;
1923     }
1924
1925   /* Because of the volatile mem read, we get an ld.acq, which is the
1926      front half of the full barrier.  The end half is the cmpxchg.rel.  */
1927   gcc_assert (MEM_VOLATILE_P (mem));
1928
1929   old_reg = gen_reg_rtx (DImode);
1930   cmp_reg = gen_reg_rtx (DImode);
1931   label = gen_label_rtx ();
1932
1933   if (mode != DImode)
1934     {
1935       val = simplify_gen_subreg (DImode, val, mode, 0);
1936       emit_insn (gen_extend_insn (cmp_reg, mem, DImode, mode, 1));
1937     }
1938   else
1939     emit_move_insn (cmp_reg, mem);
1940
1941   emit_label (label);
1942
1943   ar_ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
1944   emit_move_insn (old_reg, cmp_reg);
1945   emit_move_insn (ar_ccv, cmp_reg);
1946
1947   if (old_dst)
1948     emit_move_insn (old_dst, gen_lowpart (mode, cmp_reg));
1949
1950   new_reg = cmp_reg;
1951   if (code == NOT)
1952     {
1953       new_reg = expand_simple_unop (DImode, NOT, new_reg, NULL_RTX, true);
1954       code = AND;
1955     }
1956   new_reg = expand_simple_binop (DImode, code, new_reg, val, NULL_RTX,
1957                                  true, OPTAB_DIRECT);
1958
1959   if (mode != DImode)
1960     new_reg = gen_lowpart (mode, new_reg);
1961   if (new_dst)
1962     emit_move_insn (new_dst, new_reg);
1963
1964   switch (mode)
1965     {
1966     case QImode:  icode = CODE_FOR_cmpxchg_rel_qi;  break;
1967     case HImode:  icode = CODE_FOR_cmpxchg_rel_hi;  break;
1968     case SImode:  icode = CODE_FOR_cmpxchg_rel_si;  break;
1969     case DImode:  icode = CODE_FOR_cmpxchg_rel_di;  break;
1970     default:
1971       gcc_unreachable ();
1972     }
1973
1974   emit_insn (GEN_FCN (icode) (cmp_reg, mem, ar_ccv, new_reg));
1975
1976   emit_cmp_and_jump_insns (cmp_reg, old_reg, EQ, NULL, DImode, true, label);
1977 }
1978 \f
1979 /* Begin the assembly file.  */
1980
1981 static void
1982 ia64_file_start (void)
1983 {
1984   /* Variable tracking should be run after all optimizations which change order
1985      of insns.  It also needs a valid CFG.  This can't be done in
1986      ia64_override_options, because flag_var_tracking is finalized after
1987      that.  */
1988   ia64_flag_var_tracking = flag_var_tracking;
1989   flag_var_tracking = 0;
1990
1991   default_file_start ();
1992   emit_safe_across_calls ();
1993 }
1994
1995 void
1996 emit_safe_across_calls (void)
1997 {
1998   unsigned int rs, re;
1999   int out_state;
2000
2001   rs = 1;
2002   out_state = 0;
2003   while (1)
2004     {
2005       while (rs < 64 && call_used_regs[PR_REG (rs)])
2006         rs++;
2007       if (rs >= 64)
2008         break;
2009       for (re = rs + 1; re < 64 && ! call_used_regs[PR_REG (re)]; re++)
2010         continue;
2011       if (out_state == 0)
2012         {
2013           fputs ("\t.pred.safe_across_calls ", asm_out_file);
2014           out_state = 1;
2015         }
2016       else
2017         fputc (',', asm_out_file);
2018       if (re == rs + 1)
2019         fprintf (asm_out_file, "p%u", rs);
2020       else
2021         fprintf (asm_out_file, "p%u-p%u", rs, re - 1);
2022       rs = re + 1;
2023     }
2024   if (out_state)
2025     fputc ('\n', asm_out_file);
2026 }
2027
2028 /* Helper function for ia64_compute_frame_size: find an appropriate general
2029    register to spill some special register to.  SPECIAL_SPILL_MASK contains
2030    bits in GR0 to GR31 that have already been allocated by this routine.
2031    TRY_LOCALS is true if we should attempt to locate a local regnum.  */
2032
2033 static int
2034 find_gr_spill (int try_locals)
2035 {
2036   int regno;
2037
2038   /* If this is a leaf function, first try an otherwise unused
2039      call-clobbered register.  */
2040   if (current_function_is_leaf)
2041     {
2042       for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2043         if (! regs_ever_live[regno]
2044             && call_used_regs[regno]
2045             && ! fixed_regs[regno]
2046             && ! global_regs[regno]
2047             && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
2048           {
2049             current_frame_info.gr_used_mask |= 1 << regno;
2050             return regno;
2051           }
2052     }
2053
2054   if (try_locals)
2055     {
2056       regno = current_frame_info.n_local_regs;
2057       /* If there is a frame pointer, then we can't use loc79, because
2058          that is HARD_FRAME_POINTER_REGNUM.  In particular, see the
2059          reg_name switching code in ia64_expand_prologue.  */
2060       if (regno < (80 - frame_pointer_needed))
2061         {
2062           current_frame_info.n_local_regs = regno + 1;
2063           return LOC_REG (0) + regno;
2064         }
2065     }
2066
2067   /* Failed to find a general register to spill to.  Must use stack.  */
2068   return 0;
2069 }
2070
2071 /* In order to make for nice schedules, we try to allocate every temporary
2072    to a different register.  We must of course stay away from call-saved,
2073    fixed, and global registers.  We must also stay away from registers
2074    allocated in current_frame_info.gr_used_mask, since those include regs
2075    used all through the prologue.
2076
2077    Any register allocated here must be used immediately.  The idea is to
2078    aid scheduling, not to solve data flow problems.  */
2079
2080 static int last_scratch_gr_reg;
2081
2082 static int
2083 next_scratch_gr_reg (void)
2084 {
2085   int i, regno;
2086
2087   for (i = 0; i < 32; ++i)
2088     {
2089       regno = (last_scratch_gr_reg + i + 1) & 31;
2090       if (call_used_regs[regno]
2091           && ! fixed_regs[regno]
2092           && ! global_regs[regno]
2093           && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
2094         {
2095           last_scratch_gr_reg = regno;
2096           return regno;
2097         }
2098     }
2099
2100   /* There must be _something_ available.  */
2101   gcc_unreachable ();
2102 }
2103
2104 /* Helper function for ia64_compute_frame_size, called through
2105    diddle_return_value.  Mark REG in current_frame_info.gr_used_mask.  */
2106
2107 static void
2108 mark_reg_gr_used_mask (rtx reg, void *data ATTRIBUTE_UNUSED)
2109 {
2110   unsigned int regno = REGNO (reg);
2111   if (regno < 32)
2112     {
2113       unsigned int i, n = hard_regno_nregs[regno][GET_MODE (reg)];
2114       for (i = 0; i < n; ++i)
2115         current_frame_info.gr_used_mask |= 1 << (regno + i);
2116     }
2117 }
2118
2119 /* Returns the number of bytes offset between the frame pointer and the stack
2120    pointer for the current function.  SIZE is the number of bytes of space
2121    needed for local variables.  */
2122
2123 static void
2124 ia64_compute_frame_size (HOST_WIDE_INT size)
2125 {
2126   HOST_WIDE_INT total_size;
2127   HOST_WIDE_INT spill_size = 0;
2128   HOST_WIDE_INT extra_spill_size = 0;
2129   HOST_WIDE_INT pretend_args_size;
2130   HARD_REG_SET mask;
2131   int n_spilled = 0;
2132   int spilled_gr_p = 0;
2133   int spilled_fr_p = 0;
2134   unsigned int regno;
2135   int i;
2136
2137   if (current_frame_info.initialized)
2138     return;
2139
2140   memset (&current_frame_info, 0, sizeof current_frame_info);
2141   CLEAR_HARD_REG_SET (mask);
2142
2143   /* Don't allocate scratches to the return register.  */
2144   diddle_return_value (mark_reg_gr_used_mask, NULL);
2145
2146   /* Don't allocate scratches to the EH scratch registers.  */
2147   if (cfun->machine->ia64_eh_epilogue_sp)
2148     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_sp, NULL);
2149   if (cfun->machine->ia64_eh_epilogue_bsp)
2150     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_bsp, NULL);
2151
2152   /* Find the size of the register stack frame.  We have only 80 local
2153      registers, because we reserve 8 for the inputs and 8 for the
2154      outputs.  */
2155
2156   /* Skip HARD_FRAME_POINTER_REGNUM (loc79) when frame_pointer_needed,
2157      since we'll be adjusting that down later.  */
2158   regno = LOC_REG (78) + ! frame_pointer_needed;
2159   for (; regno >= LOC_REG (0); regno--)
2160     if (regs_ever_live[regno])
2161       break;
2162   current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2163
2164   /* For functions marked with the syscall_linkage attribute, we must mark
2165      all eight input registers as in use, so that locals aren't visible to
2166      the caller.  */
2167
2168   if (cfun->machine->n_varargs > 0
2169       || lookup_attribute ("syscall_linkage",
2170                            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
2171     current_frame_info.n_input_regs = 8;
2172   else
2173     {
2174       for (regno = IN_REG (7); regno >= IN_REG (0); regno--)
2175         if (regs_ever_live[regno])
2176           break;
2177       current_frame_info.n_input_regs = regno - IN_REG (0) + 1;
2178     }
2179
2180   for (regno = OUT_REG (7); regno >= OUT_REG (0); regno--)
2181     if (regs_ever_live[regno])
2182       break;
2183   i = regno - OUT_REG (0) + 1;
2184
2185 #ifndef PROFILE_HOOK
2186   /* When -p profiling, we need one output register for the mcount argument.
2187      Likewise for -a profiling for the bb_init_func argument.  For -ax
2188      profiling, we need two output registers for the two bb_init_trace_func
2189      arguments.  */
2190   if (current_function_profile)
2191     i = MAX (i, 1);
2192 #endif
2193   current_frame_info.n_output_regs = i;
2194
2195   /* ??? No rotating register support yet.  */
2196   current_frame_info.n_rotate_regs = 0;
2197
2198   /* Discover which registers need spilling, and how much room that
2199      will take.  Begin with floating point and general registers,
2200      which will always wind up on the stack.  */
2201
2202   for (regno = FR_REG (2); regno <= FR_REG (127); regno++)
2203     if (regs_ever_live[regno] && ! call_used_regs[regno])
2204       {
2205         SET_HARD_REG_BIT (mask, regno);
2206         spill_size += 16;
2207         n_spilled += 1;
2208         spilled_fr_p = 1;
2209       }
2210
2211   for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2212     if (regs_ever_live[regno] && ! call_used_regs[regno])
2213       {
2214         SET_HARD_REG_BIT (mask, regno);
2215         spill_size += 8;
2216         n_spilled += 1;
2217         spilled_gr_p = 1;
2218       }
2219
2220   for (regno = BR_REG (1); regno <= BR_REG (7); regno++)
2221     if (regs_ever_live[regno] && ! call_used_regs[regno])
2222       {
2223         SET_HARD_REG_BIT (mask, regno);
2224         spill_size += 8;
2225         n_spilled += 1;
2226       }
2227
2228   /* Now come all special registers that might get saved in other
2229      general registers.  */
2230
2231   if (frame_pointer_needed)
2232     {
2233       current_frame_info.reg_fp = find_gr_spill (1);
2234       /* If we did not get a register, then we take LOC79.  This is guaranteed
2235          to be free, even if regs_ever_live is already set, because this is
2236          HARD_FRAME_POINTER_REGNUM.  This requires incrementing n_local_regs,
2237          as we don't count loc79 above.  */
2238       if (current_frame_info.reg_fp == 0)
2239         {
2240           current_frame_info.reg_fp = LOC_REG (79);
2241           current_frame_info.n_local_regs++;
2242         }
2243     }
2244
2245   if (! current_function_is_leaf)
2246     {
2247       /* Emit a save of BR0 if we call other functions.  Do this even
2248          if this function doesn't return, as EH depends on this to be
2249          able to unwind the stack.  */
2250       SET_HARD_REG_BIT (mask, BR_REG (0));
2251
2252       current_frame_info.reg_save_b0 = find_gr_spill (1);
2253       if (current_frame_info.reg_save_b0 == 0)
2254         {
2255           spill_size += 8;
2256           n_spilled += 1;
2257         }
2258
2259       /* Similarly for ar.pfs.  */
2260       SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2261       current_frame_info.reg_save_ar_pfs = find_gr_spill (1);
2262       if (current_frame_info.reg_save_ar_pfs == 0)
2263         {
2264           extra_spill_size += 8;
2265           n_spilled += 1;
2266         }
2267
2268       /* Similarly for gp.  Note that if we're calling setjmp, the stacked
2269          registers are clobbered, so we fall back to the stack.  */
2270       current_frame_info.reg_save_gp
2271         = (current_function_calls_setjmp ? 0 : find_gr_spill (1));
2272       if (current_frame_info.reg_save_gp == 0)
2273         {
2274           SET_HARD_REG_BIT (mask, GR_REG (1));
2275           spill_size += 8;
2276           n_spilled += 1;
2277         }
2278     }
2279   else
2280     {
2281       if (regs_ever_live[BR_REG (0)] && ! call_used_regs[BR_REG (0)])
2282         {
2283           SET_HARD_REG_BIT (mask, BR_REG (0));
2284           spill_size += 8;
2285           n_spilled += 1;
2286         }
2287
2288       if (regs_ever_live[AR_PFS_REGNUM])
2289         {
2290           SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2291           current_frame_info.reg_save_ar_pfs = find_gr_spill (1);
2292           if (current_frame_info.reg_save_ar_pfs == 0)
2293             {
2294               extra_spill_size += 8;
2295               n_spilled += 1;
2296             }
2297         }
2298     }
2299
2300   /* Unwind descriptor hackery: things are most efficient if we allocate
2301      consecutive GR save registers for RP, PFS, FP in that order. However,
2302      it is absolutely critical that FP get the only hard register that's
2303      guaranteed to be free, so we allocated it first.  If all three did
2304      happen to be allocated hard regs, and are consecutive, rearrange them
2305      into the preferred order now.  */
2306   if (current_frame_info.reg_fp != 0
2307       && current_frame_info.reg_save_b0 == current_frame_info.reg_fp + 1
2308       && current_frame_info.reg_save_ar_pfs == current_frame_info.reg_fp + 2)
2309     {
2310       current_frame_info.reg_save_b0 = current_frame_info.reg_fp;
2311       current_frame_info.reg_save_ar_pfs = current_frame_info.reg_fp + 1;
2312       current_frame_info.reg_fp = current_frame_info.reg_fp + 2;
2313     }
2314
2315   /* See if we need to store the predicate register block.  */
2316   for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2317     if (regs_ever_live[regno] && ! call_used_regs[regno])
2318       break;
2319   if (regno <= PR_REG (63))
2320     {
2321       SET_HARD_REG_BIT (mask, PR_REG (0));
2322       current_frame_info.reg_save_pr = find_gr_spill (1);
2323       if (current_frame_info.reg_save_pr == 0)
2324         {
2325           extra_spill_size += 8;
2326           n_spilled += 1;
2327         }
2328
2329       /* ??? Mark them all as used so that register renaming and such
2330          are free to use them.  */
2331       for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2332         regs_ever_live[regno] = 1;
2333     }
2334
2335   /* If we're forced to use st8.spill, we're forced to save and restore
2336      ar.unat as well.  The check for existing liveness allows inline asm
2337      to touch ar.unat.  */
2338   if (spilled_gr_p || cfun->machine->n_varargs
2339       || regs_ever_live[AR_UNAT_REGNUM])
2340     {
2341       regs_ever_live[AR_UNAT_REGNUM] = 1;
2342       SET_HARD_REG_BIT (mask, AR_UNAT_REGNUM);
2343       current_frame_info.reg_save_ar_unat = find_gr_spill (spill_size == 0);
2344       if (current_frame_info.reg_save_ar_unat == 0)
2345         {
2346           extra_spill_size += 8;
2347           n_spilled += 1;
2348         }
2349     }
2350
2351   if (regs_ever_live[AR_LC_REGNUM])
2352     {
2353       SET_HARD_REG_BIT (mask, AR_LC_REGNUM);
2354       current_frame_info.reg_save_ar_lc = find_gr_spill (spill_size == 0);
2355       if (current_frame_info.reg_save_ar_lc == 0)
2356         {
2357           extra_spill_size += 8;
2358           n_spilled += 1;
2359         }
2360     }
2361
2362   /* If we have an odd number of words of pretend arguments written to
2363      the stack, then the FR save area will be unaligned.  We round the
2364      size of this area up to keep things 16 byte aligned.  */
2365   if (spilled_fr_p)
2366     pretend_args_size = IA64_STACK_ALIGN (current_function_pretend_args_size);
2367   else
2368     pretend_args_size = current_function_pretend_args_size;
2369
2370   total_size = (spill_size + extra_spill_size + size + pretend_args_size
2371                 + current_function_outgoing_args_size);
2372   total_size = IA64_STACK_ALIGN (total_size);
2373
2374   /* We always use the 16-byte scratch area provided by the caller, but
2375      if we are a leaf function, there's no one to which we need to provide
2376      a scratch area.  */
2377   if (current_function_is_leaf)
2378     total_size = MAX (0, total_size - 16);
2379
2380   current_frame_info.total_size = total_size;
2381   current_frame_info.spill_cfa_off = pretend_args_size - 16;
2382   current_frame_info.spill_size = spill_size;
2383   current_frame_info.extra_spill_size = extra_spill_size;
2384   COPY_HARD_REG_SET (current_frame_info.mask, mask);
2385   current_frame_info.n_spilled = n_spilled;
2386   current_frame_info.initialized = reload_completed;
2387 }
2388
2389 /* Compute the initial difference between the specified pair of registers.  */
2390
2391 HOST_WIDE_INT
2392 ia64_initial_elimination_offset (int from, int to)
2393 {
2394   HOST_WIDE_INT offset;
2395
2396   ia64_compute_frame_size (get_frame_size ());
2397   switch (from)
2398     {
2399     case FRAME_POINTER_REGNUM:
2400       switch (to)
2401         {
2402         case HARD_FRAME_POINTER_REGNUM:
2403           if (current_function_is_leaf)
2404             offset = -current_frame_info.total_size;
2405           else
2406             offset = -(current_frame_info.total_size
2407                        - current_function_outgoing_args_size - 16);
2408           break;
2409
2410         case STACK_POINTER_REGNUM:
2411           if (current_function_is_leaf)
2412             offset = 0;
2413           else
2414             offset = 16 + current_function_outgoing_args_size;
2415           break;
2416
2417         default:
2418           gcc_unreachable ();
2419         }
2420       break;
2421
2422     case ARG_POINTER_REGNUM:
2423       /* Arguments start above the 16 byte save area, unless stdarg
2424          in which case we store through the 16 byte save area.  */
2425       switch (to)
2426         {
2427         case HARD_FRAME_POINTER_REGNUM:
2428           offset = 16 - current_function_pretend_args_size;
2429           break;
2430
2431         case STACK_POINTER_REGNUM:
2432           offset = (current_frame_info.total_size
2433                     + 16 - current_function_pretend_args_size);
2434           break;
2435
2436         default:
2437           gcc_unreachable ();
2438         }
2439       break;
2440
2441     default:
2442       gcc_unreachable ();
2443     }
2444
2445   return offset;
2446 }
2447
2448 /* If there are more than a trivial number of register spills, we use
2449    two interleaved iterators so that we can get two memory references
2450    per insn group.
2451
2452    In order to simplify things in the prologue and epilogue expanders,
2453    we use helper functions to fix up the memory references after the
2454    fact with the appropriate offsets to a POST_MODIFY memory mode.
2455    The following data structure tracks the state of the two iterators
2456    while insns are being emitted.  */
2457
2458 struct spill_fill_data
2459 {
2460   rtx init_after;               /* point at which to emit initializations */
2461   rtx init_reg[2];              /* initial base register */
2462   rtx iter_reg[2];              /* the iterator registers */
2463   rtx *prev_addr[2];            /* address of last memory use */
2464   rtx prev_insn[2];             /* the insn corresponding to prev_addr */
2465   HOST_WIDE_INT prev_off[2];    /* last offset */
2466   int n_iter;                   /* number of iterators in use */
2467   int next_iter;                /* next iterator to use */
2468   unsigned int save_gr_used_mask;
2469 };
2470
2471 static struct spill_fill_data spill_fill_data;
2472
2473 static void
2474 setup_spill_pointers (int n_spills, rtx init_reg, HOST_WIDE_INT cfa_off)
2475 {
2476   int i;
2477
2478   spill_fill_data.init_after = get_last_insn ();
2479   spill_fill_data.init_reg[0] = init_reg;
2480   spill_fill_data.init_reg[1] = init_reg;
2481   spill_fill_data.prev_addr[0] = NULL;
2482   spill_fill_data.prev_addr[1] = NULL;
2483   spill_fill_data.prev_insn[0] = NULL;
2484   spill_fill_data.prev_insn[1] = NULL;
2485   spill_fill_data.prev_off[0] = cfa_off;
2486   spill_fill_data.prev_off[1] = cfa_off;
2487   spill_fill_data.next_iter = 0;
2488   spill_fill_data.save_gr_used_mask = current_frame_info.gr_used_mask;
2489
2490   spill_fill_data.n_iter = 1 + (n_spills > 2);
2491   for (i = 0; i < spill_fill_data.n_iter; ++i)
2492     {
2493       int regno = next_scratch_gr_reg ();
2494       spill_fill_data.iter_reg[i] = gen_rtx_REG (DImode, regno);
2495       current_frame_info.gr_used_mask |= 1 << regno;
2496     }
2497 }
2498
2499 static void
2500 finish_spill_pointers (void)
2501 {
2502   current_frame_info.gr_used_mask = spill_fill_data.save_gr_used_mask;
2503 }
2504
2505 static rtx
2506 spill_restore_mem (rtx reg, HOST_WIDE_INT cfa_off)
2507 {
2508   int iter = spill_fill_data.next_iter;
2509   HOST_WIDE_INT disp = spill_fill_data.prev_off[iter] - cfa_off;
2510   rtx disp_rtx = GEN_INT (disp);
2511   rtx mem;
2512
2513   if (spill_fill_data.prev_addr[iter])
2514     {
2515       if (CONST_OK_FOR_N (disp))
2516         {
2517           *spill_fill_data.prev_addr[iter]
2518             = gen_rtx_POST_MODIFY (DImode, spill_fill_data.iter_reg[iter],
2519                                    gen_rtx_PLUS (DImode,
2520                                                  spill_fill_data.iter_reg[iter],
2521                                                  disp_rtx));
2522           REG_NOTES (spill_fill_data.prev_insn[iter])
2523             = gen_rtx_EXPR_LIST (REG_INC, spill_fill_data.iter_reg[iter],
2524                                  REG_NOTES (spill_fill_data.prev_insn[iter]));
2525         }
2526       else
2527         {
2528           /* ??? Could use register post_modify for loads.  */
2529           if (! CONST_OK_FOR_I (disp))
2530             {
2531               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2532               emit_move_insn (tmp, disp_rtx);
2533               disp_rtx = tmp;
2534             }
2535           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2536                                  spill_fill_data.iter_reg[iter], disp_rtx));
2537         }
2538     }
2539   /* Micro-optimization: if we've created a frame pointer, it's at
2540      CFA 0, which may allow the real iterator to be initialized lower,
2541      slightly increasing parallelism.  Also, if there are few saves
2542      it may eliminate the iterator entirely.  */
2543   else if (disp == 0
2544            && spill_fill_data.init_reg[iter] == stack_pointer_rtx
2545            && frame_pointer_needed)
2546     {
2547       mem = gen_rtx_MEM (GET_MODE (reg), hard_frame_pointer_rtx);
2548       set_mem_alias_set (mem, get_varargs_alias_set ());
2549       return mem;
2550     }
2551   else
2552     {
2553       rtx seq, insn;
2554
2555       if (disp == 0)
2556         seq = gen_movdi (spill_fill_data.iter_reg[iter],
2557                          spill_fill_data.init_reg[iter]);
2558       else
2559         {
2560           start_sequence ();
2561
2562           if (! CONST_OK_FOR_I (disp))
2563             {
2564               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2565               emit_move_insn (tmp, disp_rtx);
2566               disp_rtx = tmp;
2567             }
2568
2569           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2570                                  spill_fill_data.init_reg[iter],
2571                                  disp_rtx));
2572
2573           seq = get_insns ();
2574           end_sequence ();
2575         }
2576
2577       /* Careful for being the first insn in a sequence.  */
2578       if (spill_fill_data.init_after)
2579         insn = emit_insn_after (seq, spill_fill_data.init_after);
2580       else
2581         {
2582           rtx first = get_insns ();
2583           if (first)
2584             insn = emit_insn_before (seq, first);
2585           else
2586             insn = emit_insn (seq);
2587         }
2588       spill_fill_data.init_after = insn;
2589
2590       /* If DISP is 0, we may or may not have a further adjustment
2591          afterward.  If we do, then the load/store insn may be modified
2592          to be a post-modify.  If we don't, then this copy may be
2593          eliminated by copyprop_hardreg_forward, which makes this
2594          insn garbage, which runs afoul of the sanity check in
2595          propagate_one_insn.  So mark this insn as legal to delete.  */
2596       if (disp == 0)
2597         REG_NOTES(insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx,
2598                                              REG_NOTES (insn));
2599     }
2600
2601   mem = gen_rtx_MEM (GET_MODE (reg), spill_fill_data.iter_reg[iter]);
2602
2603   /* ??? Not all of the spills are for varargs, but some of them are.
2604      The rest of the spills belong in an alias set of their own.  But
2605      it doesn't actually hurt to include them here.  */
2606   set_mem_alias_set (mem, get_varargs_alias_set ());
2607
2608   spill_fill_data.prev_addr[iter] = &XEXP (mem, 0);
2609   spill_fill_data.prev_off[iter] = cfa_off;
2610
2611   if (++iter >= spill_fill_data.n_iter)
2612     iter = 0;
2613   spill_fill_data.next_iter = iter;
2614
2615   return mem;
2616 }
2617
2618 static void
2619 do_spill (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off,
2620           rtx frame_reg)
2621 {
2622   int iter = spill_fill_data.next_iter;
2623   rtx mem, insn;
2624
2625   mem = spill_restore_mem (reg, cfa_off);
2626   insn = emit_insn ((*move_fn) (mem, reg, GEN_INT (cfa_off)));
2627   spill_fill_data.prev_insn[iter] = insn;
2628
2629   if (frame_reg)
2630     {
2631       rtx base;
2632       HOST_WIDE_INT off;
2633
2634       RTX_FRAME_RELATED_P (insn) = 1;
2635
2636       /* Don't even pretend that the unwind code can intuit its way
2637          through a pair of interleaved post_modify iterators.  Just
2638          provide the correct answer.  */
2639
2640       if (frame_pointer_needed)
2641         {
2642           base = hard_frame_pointer_rtx;
2643           off = - cfa_off;
2644         }
2645       else
2646         {
2647           base = stack_pointer_rtx;
2648           off = current_frame_info.total_size - cfa_off;
2649         }
2650
2651       REG_NOTES (insn)
2652         = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2653                 gen_rtx_SET (VOIDmode,
2654                              gen_rtx_MEM (GET_MODE (reg),
2655                                           plus_constant (base, off)),
2656                              frame_reg),
2657                 REG_NOTES (insn));
2658     }
2659 }
2660
2661 static void
2662 do_restore (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off)
2663 {
2664   int iter = spill_fill_data.next_iter;
2665   rtx insn;
2666
2667   insn = emit_insn ((*move_fn) (reg, spill_restore_mem (reg, cfa_off),
2668                                 GEN_INT (cfa_off)));
2669   spill_fill_data.prev_insn[iter] = insn;
2670 }
2671
2672 /* Wrapper functions that discards the CONST_INT spill offset.  These
2673    exist so that we can give gr_spill/gr_fill the offset they need and
2674    use a consistent function interface.  */
2675
2676 static rtx
2677 gen_movdi_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2678 {
2679   return gen_movdi (dest, src);
2680 }
2681
2682 static rtx
2683 gen_fr_spill_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2684 {
2685   return gen_fr_spill (dest, src);
2686 }
2687
2688 static rtx
2689 gen_fr_restore_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2690 {
2691   return gen_fr_restore (dest, src);
2692 }
2693
2694 /* Called after register allocation to add any instructions needed for the
2695    prologue.  Using a prologue insn is favored compared to putting all of the
2696    instructions in output_function_prologue(), since it allows the scheduler
2697    to intermix instructions with the saves of the caller saved registers.  In
2698    some cases, it might be necessary to emit a barrier instruction as the last
2699    insn to prevent such scheduling.
2700
2701    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
2702    so that the debug info generation code can handle them properly.
2703
2704    The register save area is layed out like so:
2705    cfa+16
2706         [ varargs spill area ]
2707         [ fr register spill area ]
2708         [ br register spill area ]
2709         [ ar register spill area ]
2710         [ pr register spill area ]
2711         [ gr register spill area ] */
2712
2713 /* ??? Get inefficient code when the frame size is larger than can fit in an
2714    adds instruction.  */
2715
2716 void
2717 ia64_expand_prologue (void)
2718 {
2719   rtx insn, ar_pfs_save_reg, ar_unat_save_reg;
2720   int i, epilogue_p, regno, alt_regno, cfa_off, n_varargs;
2721   rtx reg, alt_reg;
2722
2723   ia64_compute_frame_size (get_frame_size ());
2724   last_scratch_gr_reg = 15;
2725
2726   /* If there is no epilogue, then we don't need some prologue insns.
2727      We need to avoid emitting the dead prologue insns, because flow
2728      will complain about them.  */
2729   if (optimize)
2730     {
2731       edge e;
2732       edge_iterator ei;
2733
2734       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
2735         if ((e->flags & EDGE_FAKE) == 0
2736             && (e->flags & EDGE_FALLTHRU) != 0)
2737           break;
2738       epilogue_p = (e != NULL);
2739     }
2740   else
2741     epilogue_p = 1;
2742
2743   /* Set the local, input, and output register names.  We need to do this
2744      for GNU libc, which creates crti.S/crtn.S by splitting initfini.c in
2745      half.  If we use in/loc/out register names, then we get assembler errors
2746      in crtn.S because there is no alloc insn or regstk directive in there.  */
2747   if (! TARGET_REG_NAMES)
2748     {
2749       int inputs = current_frame_info.n_input_regs;
2750       int locals = current_frame_info.n_local_regs;
2751       int outputs = current_frame_info.n_output_regs;
2752
2753       for (i = 0; i < inputs; i++)
2754         reg_names[IN_REG (i)] = ia64_reg_numbers[i];
2755       for (i = 0; i < locals; i++)
2756         reg_names[LOC_REG (i)] = ia64_reg_numbers[inputs + i];
2757       for (i = 0; i < outputs; i++)
2758         reg_names[OUT_REG (i)] = ia64_reg_numbers[inputs + locals + i];
2759     }
2760
2761   /* Set the frame pointer register name.  The regnum is logically loc79,
2762      but of course we'll not have allocated that many locals.  Rather than
2763      worrying about renumbering the existing rtxs, we adjust the name.  */
2764   /* ??? This code means that we can never use one local register when
2765      there is a frame pointer.  loc79 gets wasted in this case, as it is
2766      renamed to a register that will never be used.  See also the try_locals
2767      code in find_gr_spill.  */
2768   if (current_frame_info.reg_fp)
2769     {
2770       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
2771       reg_names[HARD_FRAME_POINTER_REGNUM]
2772         = reg_names[current_frame_info.reg_fp];
2773       reg_names[current_frame_info.reg_fp] = tmp;
2774     }
2775
2776   /* We don't need an alloc instruction if we've used no outputs or locals.  */
2777   if (current_frame_info.n_local_regs == 0
2778       && current_frame_info.n_output_regs == 0
2779       && current_frame_info.n_input_regs <= current_function_args_info.int_regs
2780       && !TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
2781     {
2782       /* If there is no alloc, but there are input registers used, then we
2783          need a .regstk directive.  */
2784       current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
2785       ar_pfs_save_reg = NULL_RTX;
2786     }
2787   else
2788     {
2789       current_frame_info.need_regstk = 0;
2790
2791       if (current_frame_info.reg_save_ar_pfs)
2792         regno = current_frame_info.reg_save_ar_pfs;
2793       else
2794         regno = next_scratch_gr_reg ();
2795       ar_pfs_save_reg = gen_rtx_REG (DImode, regno);
2796
2797       insn = emit_insn (gen_alloc (ar_pfs_save_reg,
2798                                    GEN_INT (current_frame_info.n_input_regs),
2799                                    GEN_INT (current_frame_info.n_local_regs),
2800                                    GEN_INT (current_frame_info.n_output_regs),
2801                                    GEN_INT (current_frame_info.n_rotate_regs)));
2802       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_pfs != 0);
2803     }
2804
2805   /* Set up frame pointer, stack pointer, and spill iterators.  */
2806
2807   n_varargs = cfun->machine->n_varargs;
2808   setup_spill_pointers (current_frame_info.n_spilled + n_varargs,
2809                         stack_pointer_rtx, 0);
2810
2811   if (frame_pointer_needed)
2812     {
2813       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
2814       RTX_FRAME_RELATED_P (insn) = 1;
2815     }
2816
2817   if (current_frame_info.total_size != 0)
2818     {
2819       rtx frame_size_rtx = GEN_INT (- current_frame_info.total_size);
2820       rtx offset;
2821
2822       if (CONST_OK_FOR_I (- current_frame_info.total_size))
2823         offset = frame_size_rtx;
2824       else
2825         {
2826           regno = next_scratch_gr_reg ();
2827           offset = gen_rtx_REG (DImode, regno);
2828           emit_move_insn (offset, frame_size_rtx);
2829         }
2830
2831       insn = emit_insn (gen_adddi3 (stack_pointer_rtx,
2832                                     stack_pointer_rtx, offset));
2833
2834       if (! frame_pointer_needed)
2835         {
2836           RTX_FRAME_RELATED_P (insn) = 1;
2837           if (GET_CODE (offset) != CONST_INT)
2838             {
2839               REG_NOTES (insn)
2840                 = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2841                         gen_rtx_SET (VOIDmode,
2842                                      stack_pointer_rtx,
2843                                      gen_rtx_PLUS (DImode,
2844                                                    stack_pointer_rtx,
2845                                                    frame_size_rtx)),
2846                         REG_NOTES (insn));
2847             }
2848         }
2849
2850       /* ??? At this point we must generate a magic insn that appears to
2851          modify the stack pointer, the frame pointer, and all spill
2852          iterators.  This would allow the most scheduling freedom.  For
2853          now, just hard stop.  */
2854       emit_insn (gen_blockage ());
2855     }
2856
2857   /* Must copy out ar.unat before doing any integer spills.  */
2858   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
2859     {
2860       if (current_frame_info.reg_save_ar_unat)
2861         ar_unat_save_reg
2862           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
2863       else
2864         {
2865           alt_regno = next_scratch_gr_reg ();
2866           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
2867           current_frame_info.gr_used_mask |= 1 << alt_regno;
2868         }
2869
2870       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2871       insn = emit_move_insn (ar_unat_save_reg, reg);
2872       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_unat != 0);
2873
2874       /* Even if we're not going to generate an epilogue, we still
2875          need to save the register so that EH works.  */
2876       if (! epilogue_p && current_frame_info.reg_save_ar_unat)
2877         emit_insn (gen_prologue_use (ar_unat_save_reg));
2878     }
2879   else
2880     ar_unat_save_reg = NULL_RTX;
2881
2882   /* Spill all varargs registers.  Do this before spilling any GR registers,
2883      since we want the UNAT bits for the GR registers to override the UNAT
2884      bits from varargs, which we don't care about.  */
2885
2886   cfa_off = -16;
2887   for (regno = GR_ARG_FIRST + 7; n_varargs > 0; --n_varargs, --regno)
2888     {
2889       reg = gen_rtx_REG (DImode, regno);
2890       do_spill (gen_gr_spill, reg, cfa_off += 8, NULL_RTX);
2891     }
2892
2893   /* Locate the bottom of the register save area.  */
2894   cfa_off = (current_frame_info.spill_cfa_off
2895              + current_frame_info.spill_size
2896              + current_frame_info.extra_spill_size);
2897
2898   /* Save the predicate register block either in a register or in memory.  */
2899   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
2900     {
2901       reg = gen_rtx_REG (DImode, PR_REG (0));
2902       if (current_frame_info.reg_save_pr != 0)
2903         {
2904           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
2905           insn = emit_move_insn (alt_reg, reg);
2906
2907           /* ??? Denote pr spill/fill by a DImode move that modifies all
2908              64 hard registers.  */
2909           RTX_FRAME_RELATED_P (insn) = 1;
2910           REG_NOTES (insn)
2911             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2912                         gen_rtx_SET (VOIDmode, alt_reg, reg),
2913                         REG_NOTES (insn));
2914
2915           /* Even if we're not going to generate an epilogue, we still
2916              need to save the register so that EH works.  */
2917           if (! epilogue_p)
2918             emit_insn (gen_prologue_use (alt_reg));
2919         }
2920       else
2921         {
2922           alt_regno = next_scratch_gr_reg ();
2923           alt_reg = gen_rtx_REG (DImode, alt_regno);
2924           insn = emit_move_insn (alt_reg, reg);
2925           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2926           cfa_off -= 8;
2927         }
2928     }
2929
2930   /* Handle AR regs in numerical order.  All of them get special handling.  */
2931   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM)
2932       && current_frame_info.reg_save_ar_unat == 0)
2933     {
2934       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2935       do_spill (gen_movdi_x, ar_unat_save_reg, cfa_off, reg);
2936       cfa_off -= 8;
2937     }
2938
2939   /* The alloc insn already copied ar.pfs into a general register.  The
2940      only thing we have to do now is copy that register to a stack slot
2941      if we'd not allocated a local register for the job.  */
2942   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM)
2943       && current_frame_info.reg_save_ar_pfs == 0)
2944     {
2945       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
2946       do_spill (gen_movdi_x, ar_pfs_save_reg, cfa_off, reg);
2947       cfa_off -= 8;
2948     }
2949
2950   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
2951     {
2952       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
2953       if (current_frame_info.reg_save_ar_lc != 0)
2954         {
2955           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
2956           insn = emit_move_insn (alt_reg, reg);
2957           RTX_FRAME_RELATED_P (insn) = 1;
2958
2959           /* Even if we're not going to generate an epilogue, we still
2960              need to save the register so that EH works.  */
2961           if (! epilogue_p)
2962             emit_insn (gen_prologue_use (alt_reg));
2963         }
2964       else
2965         {
2966           alt_regno = next_scratch_gr_reg ();
2967           alt_reg = gen_rtx_REG (DImode, alt_regno);
2968           emit_move_insn (alt_reg, reg);
2969           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2970           cfa_off -= 8;
2971         }
2972     }
2973
2974   if (current_frame_info.reg_save_gp)
2975     {
2976       insn = emit_move_insn (gen_rtx_REG (DImode,
2977                                           current_frame_info.reg_save_gp),
2978                              pic_offset_table_rtx);
2979       /* We don't know for sure yet if this is actually needed, since
2980          we've not split the PIC call patterns.  If all of the calls
2981          are indirect, and not followed by any uses of the gp, then
2982          this save is dead.  Allow it to go away.  */
2983       REG_NOTES (insn)
2984         = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx, REG_NOTES (insn));
2985     }
2986
2987   /* We should now be at the base of the gr/br/fr spill area.  */
2988   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
2989                           + current_frame_info.spill_size));
2990
2991   /* Spill all general registers.  */
2992   for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
2993     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2994       {
2995         reg = gen_rtx_REG (DImode, regno);
2996         do_spill (gen_gr_spill, reg, cfa_off, reg);
2997         cfa_off -= 8;
2998       }
2999
3000   /* Handle BR0 specially -- it may be getting stored permanently in
3001      some GR register.  */
3002   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3003     {
3004       reg = gen_rtx_REG (DImode, BR_REG (0));
3005       if (current_frame_info.reg_save_b0 != 0)
3006         {
3007           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
3008           insn = emit_move_insn (alt_reg, reg);
3009           RTX_FRAME_RELATED_P (insn) = 1;
3010
3011           /* Even if we're not going to generate an epilogue, we still
3012              need to save the register so that EH works.  */
3013           if (! epilogue_p)
3014             emit_insn (gen_prologue_use (alt_reg));
3015         }
3016       else
3017         {
3018           alt_regno = next_scratch_gr_reg ();
3019           alt_reg = gen_rtx_REG (DImode, alt_regno);
3020           emit_move_insn (alt_reg, reg);
3021           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3022           cfa_off -= 8;
3023         }
3024     }
3025
3026   /* Spill the rest of the BR registers.  */
3027   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3028     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3029       {
3030         alt_regno = next_scratch_gr_reg ();
3031         alt_reg = gen_rtx_REG (DImode, alt_regno);
3032         reg = gen_rtx_REG (DImode, regno);
3033         emit_move_insn (alt_reg, reg);
3034         do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3035         cfa_off -= 8;
3036       }
3037
3038   /* Align the frame and spill all FR registers.  */
3039   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3040     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3041       {
3042         gcc_assert (!(cfa_off & 15));
3043         reg = gen_rtx_REG (XFmode, regno);
3044         do_spill (gen_fr_spill_x, reg, cfa_off, reg);
3045         cfa_off -= 16;
3046       }
3047
3048   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3049
3050   finish_spill_pointers ();
3051 }
3052
3053 /* Called after register allocation to add any instructions needed for the
3054    epilogue.  Using an epilogue insn is favored compared to putting all of the
3055    instructions in output_function_prologue(), since it allows the scheduler
3056    to intermix instructions with the saves of the caller saved registers.  In
3057    some cases, it might be necessary to emit a barrier instruction as the last
3058    insn to prevent such scheduling.  */
3059
3060 void
3061 ia64_expand_epilogue (int sibcall_p)
3062 {
3063   rtx insn, reg, alt_reg, ar_unat_save_reg;
3064   int regno, alt_regno, cfa_off;
3065
3066   ia64_compute_frame_size (get_frame_size ());
3067
3068   /* If there is a frame pointer, then we use it instead of the stack
3069      pointer, so that the stack pointer does not need to be valid when
3070      the epilogue starts.  See EXIT_IGNORE_STACK.  */
3071   if (frame_pointer_needed)
3072     setup_spill_pointers (current_frame_info.n_spilled,
3073                           hard_frame_pointer_rtx, 0);
3074   else
3075     setup_spill_pointers (current_frame_info.n_spilled, stack_pointer_rtx,
3076                           current_frame_info.total_size);
3077
3078   if (current_frame_info.total_size != 0)
3079     {
3080       /* ??? At this point we must generate a magic insn that appears to
3081          modify the spill iterators and the frame pointer.  This would
3082          allow the most scheduling freedom.  For now, just hard stop.  */
3083       emit_insn (gen_blockage ());
3084     }
3085
3086   /* Locate the bottom of the register save area.  */
3087   cfa_off = (current_frame_info.spill_cfa_off
3088              + current_frame_info.spill_size
3089              + current_frame_info.extra_spill_size);
3090
3091   /* Restore the predicate registers.  */
3092   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
3093     {
3094       if (current_frame_info.reg_save_pr != 0)
3095         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
3096       else
3097         {
3098           alt_regno = next_scratch_gr_reg ();
3099           alt_reg = gen_rtx_REG (DImode, alt_regno);
3100           do_restore (gen_movdi_x, alt_reg, cfa_off);
3101           cfa_off -= 8;
3102         }
3103       reg = gen_rtx_REG (DImode, PR_REG (0));
3104       emit_move_insn (reg, alt_reg);
3105     }
3106
3107   /* Restore the application registers.  */
3108
3109   /* Load the saved unat from the stack, but do not restore it until
3110      after the GRs have been restored.  */
3111   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3112     {
3113       if (current_frame_info.reg_save_ar_unat != 0)
3114         ar_unat_save_reg
3115           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
3116       else
3117         {
3118           alt_regno = next_scratch_gr_reg ();
3119           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3120           current_frame_info.gr_used_mask |= 1 << alt_regno;
3121           do_restore (gen_movdi_x, ar_unat_save_reg, cfa_off);
3122           cfa_off -= 8;
3123         }
3124     }
3125   else
3126     ar_unat_save_reg = NULL_RTX;
3127
3128   if (current_frame_info.reg_save_ar_pfs != 0)
3129     {
3130       alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_pfs);
3131       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3132       emit_move_insn (reg, alt_reg);
3133     }
3134   else if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3135     {
3136       alt_regno = next_scratch_gr_reg ();
3137       alt_reg = gen_rtx_REG (DImode, alt_regno);
3138       do_restore (gen_movdi_x, alt_reg, cfa_off);
3139       cfa_off -= 8;
3140       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3141       emit_move_insn (reg, alt_reg);
3142     }
3143
3144   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3145     {
3146       if (current_frame_info.reg_save_ar_lc != 0)
3147         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
3148       else
3149         {
3150           alt_regno = next_scratch_gr_reg ();
3151           alt_reg = gen_rtx_REG (DImode, alt_regno);
3152           do_restore (gen_movdi_x, alt_reg, cfa_off);
3153           cfa_off -= 8;
3154         }
3155       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3156       emit_move_insn (reg, alt_reg);
3157     }
3158
3159   /* We should now be at the base of the gr/br/fr spill area.  */
3160   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
3161                           + current_frame_info.spill_size));
3162
3163   /* The GP may be stored on the stack in the prologue, but it's
3164      never restored in the epilogue.  Skip the stack slot.  */
3165   if (TEST_HARD_REG_BIT (current_frame_info.mask, GR_REG (1)))
3166     cfa_off -= 8;
3167
3168   /* Restore all general registers.  */
3169   for (regno = GR_REG (2); regno <= GR_REG (31); ++regno)
3170     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3171       {
3172         reg = gen_rtx_REG (DImode, regno);
3173         do_restore (gen_gr_restore, reg, cfa_off);
3174         cfa_off -= 8;
3175       }
3176
3177   /* Restore the branch registers.  Handle B0 specially, as it may
3178      have gotten stored in some GR register.  */
3179   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3180     {
3181       if (current_frame_info.reg_save_b0 != 0)
3182         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
3183       else
3184         {
3185           alt_regno = next_scratch_gr_reg ();
3186           alt_reg = gen_rtx_REG (DImode, alt_regno);
3187           do_restore (gen_movdi_x, alt_reg, cfa_off);
3188           cfa_off -= 8;
3189         }
3190       reg = gen_rtx_REG (DImode, BR_REG (0));
3191       emit_move_insn (reg, alt_reg);
3192     }
3193
3194   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3195     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3196       {
3197         alt_regno = next_scratch_gr_reg ();
3198         alt_reg = gen_rtx_REG (DImode, alt_regno);
3199         do_restore (gen_movdi_x, alt_reg, cfa_off);
3200         cfa_off -= 8;
3201         reg = gen_rtx_REG (DImode, regno);
3202         emit_move_insn (reg, alt_reg);
3203       }
3204
3205   /* Restore floating point registers.  */
3206   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3207     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3208       {
3209         gcc_assert (!(cfa_off & 15));
3210         reg = gen_rtx_REG (XFmode, regno);
3211         do_restore (gen_fr_restore_x, reg, cfa_off);
3212         cfa_off -= 16;
3213       }
3214
3215   /* Restore ar.unat for real.  */
3216   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3217     {
3218       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3219       emit_move_insn (reg, ar_unat_save_reg);
3220     }
3221
3222   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3223
3224   finish_spill_pointers ();
3225
3226   if (current_frame_info.total_size || cfun->machine->ia64_eh_epilogue_sp)
3227     {
3228       /* ??? At this point we must generate a magic insn that appears to
3229          modify the spill iterators, the stack pointer, and the frame
3230          pointer.  This would allow the most scheduling freedom.  For now,
3231          just hard stop.  */
3232       emit_insn (gen_blockage ());
3233     }
3234
3235   if (cfun->machine->ia64_eh_epilogue_sp)
3236     emit_move_insn (stack_pointer_rtx, cfun->machine->ia64_eh_epilogue_sp);
3237   else if (frame_pointer_needed)
3238     {
3239       insn = emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
3240       RTX_FRAME_RELATED_P (insn) = 1;
3241     }
3242   else if (current_frame_info.total_size)
3243     {
3244       rtx offset, frame_size_rtx;
3245
3246       frame_size_rtx = GEN_INT (current_frame_info.total_size);
3247       if (CONST_OK_FOR_I (current_frame_info.total_size))
3248         offset = frame_size_rtx;
3249       else
3250         {
3251           regno = next_scratch_gr_reg ();
3252           offset = gen_rtx_REG (DImode, regno);
3253           emit_move_insn (offset, frame_size_rtx);
3254         }
3255
3256       insn = emit_insn (gen_adddi3 (stack_pointer_rtx, stack_pointer_rtx,
3257                                     offset));
3258
3259       RTX_FRAME_RELATED_P (insn) = 1;
3260       if (GET_CODE (offset) != CONST_INT)
3261         {
3262           REG_NOTES (insn)
3263             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
3264                         gen_rtx_SET (VOIDmode,
3265                                      stack_pointer_rtx,
3266                                      gen_rtx_PLUS (DImode,
3267                                                    stack_pointer_rtx,
3268                                                    frame_size_rtx)),
3269                         REG_NOTES (insn));
3270         }
3271     }
3272
3273   if (cfun->machine->ia64_eh_epilogue_bsp)
3274     emit_insn (gen_set_bsp (cfun->machine->ia64_eh_epilogue_bsp));
3275
3276   if (! sibcall_p)
3277     emit_jump_insn (gen_return_internal (gen_rtx_REG (DImode, BR_REG (0))));
3278   else
3279     {
3280       int fp = GR_REG (2);
3281       /* We need a throw away register here, r0 and r1 are reserved, so r2 is the
3282          first available call clobbered register.  If there was a frame_pointer
3283          register, we may have swapped the names of r2 and HARD_FRAME_POINTER_REGNUM,
3284          so we have to make sure we're using the string "r2" when emitting
3285          the register name for the assembler.  */
3286       if (current_frame_info.reg_fp && current_frame_info.reg_fp == GR_REG (2))
3287         fp = HARD_FRAME_POINTER_REGNUM;
3288
3289       /* We must emit an alloc to force the input registers to become output
3290          registers.  Otherwise, if the callee tries to pass its parameters
3291          through to another call without an intervening alloc, then these
3292          values get lost.  */
3293       /* ??? We don't need to preserve all input registers.  We only need to
3294          preserve those input registers used as arguments to the sibling call.
3295          It is unclear how to compute that number here.  */
3296       if (current_frame_info.n_input_regs != 0)
3297         {
3298           rtx n_inputs = GEN_INT (current_frame_info.n_input_regs);
3299           insn = emit_insn (gen_alloc (gen_rtx_REG (DImode, fp),
3300                                 const0_rtx, const0_rtx,
3301                                 n_inputs, const0_rtx));
3302           RTX_FRAME_RELATED_P (insn) = 1;
3303         }
3304     }
3305 }
3306
3307 /* Return 1 if br.ret can do all the work required to return from a
3308    function.  */
3309
3310 int
3311 ia64_direct_return (void)
3312 {
3313   if (reload_completed && ! frame_pointer_needed)
3314     {
3315       ia64_compute_frame_size (get_frame_size ());
3316
3317       return (current_frame_info.total_size == 0
3318               && current_frame_info.n_spilled == 0
3319               && current_frame_info.reg_save_b0 == 0
3320               && current_frame_info.reg_save_pr == 0
3321               && current_frame_info.reg_save_ar_pfs == 0
3322               && current_frame_info.reg_save_ar_unat == 0
3323               && current_frame_info.reg_save_ar_lc == 0);
3324     }
3325   return 0;
3326 }
3327
3328 /* Return the magic cookie that we use to hold the return address
3329    during early compilation.  */
3330
3331 rtx
3332 ia64_return_addr_rtx (HOST_WIDE_INT count, rtx frame ATTRIBUTE_UNUSED)
3333 {
3334   if (count != 0)
3335     return NULL;
3336   return gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_RET_ADDR);
3337 }
3338
3339 /* Split this value after reload, now that we know where the return
3340    address is saved.  */
3341
3342 void
3343 ia64_split_return_addr_rtx (rtx dest)
3344 {
3345   rtx src;
3346
3347   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3348     {
3349       if (current_frame_info.reg_save_b0 != 0)
3350         src = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
3351       else
3352         {
3353           HOST_WIDE_INT off;
3354           unsigned int regno;
3355
3356           /* Compute offset from CFA for BR0.  */
3357           /* ??? Must be kept in sync with ia64_expand_prologue.  */
3358           off = (current_frame_info.spill_cfa_off
3359                  + current_frame_info.spill_size);
3360           for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3361             if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3362               off -= 8;
3363
3364           /* Convert CFA offset to a register based offset.  */
3365           if (frame_pointer_needed)
3366             src = hard_frame_pointer_rtx;
3367           else
3368             {
3369               src = stack_pointer_rtx;
3370               off += current_frame_info.total_size;
3371             }
3372
3373           /* Load address into scratch register.  */
3374           if (CONST_OK_FOR_I (off))
3375             emit_insn (gen_adddi3 (dest, src, GEN_INT (off)));
3376           else
3377             {
3378               emit_move_insn (dest, GEN_INT (off));
3379               emit_insn (gen_adddi3 (dest, src, dest));
3380             }
3381
3382           src = gen_rtx_MEM (Pmode, dest);
3383         }
3384     }
3385   else
3386     src = gen_rtx_REG (DImode, BR_REG (0));
3387
3388   emit_move_insn (dest, src);
3389 }
3390
3391 int
3392 ia64_hard_regno_rename_ok (int from, int to)
3393 {
3394   /* Don't clobber any of the registers we reserved for the prologue.  */
3395   if (to == current_frame_info.reg_fp
3396       || to == current_frame_info.reg_save_b0
3397       || to == current_frame_info.reg_save_pr
3398       || to == current_frame_info.reg_save_ar_pfs
3399       || to == current_frame_info.reg_save_ar_unat
3400       || to == current_frame_info.reg_save_ar_lc)
3401     return 0;
3402
3403   if (from == current_frame_info.reg_fp
3404       || from == current_frame_info.reg_save_b0
3405       || from == current_frame_info.reg_save_pr
3406       || from == current_frame_info.reg_save_ar_pfs
3407       || from == current_frame_info.reg_save_ar_unat
3408       || from == current_frame_info.reg_save_ar_lc)
3409     return 0;
3410
3411   /* Don't use output registers outside the register frame.  */
3412   if (OUT_REGNO_P (to) && to >= OUT_REG (current_frame_info.n_output_regs))
3413     return 0;
3414
3415   /* Retain even/oddness on predicate register pairs.  */
3416   if (PR_REGNO_P (from) && PR_REGNO_P (to))
3417     return (from & 1) == (to & 1);
3418
3419   return 1;
3420 }
3421
3422 /* Target hook for assembling integer objects.  Handle word-sized
3423    aligned objects and detect the cases when @fptr is needed.  */
3424
3425 static bool
3426 ia64_assemble_integer (rtx x, unsigned int size, int aligned_p)
3427 {
3428   if (size == POINTER_SIZE / BITS_PER_UNIT
3429       && !(TARGET_NO_PIC || TARGET_AUTO_PIC)
3430       && GET_CODE (x) == SYMBOL_REF
3431       && SYMBOL_REF_FUNCTION_P (x))
3432     {
3433       static const char * const directive[2][2] = {
3434           /* 64-bit pointer */  /* 32-bit pointer */
3435         { "\tdata8.ua\t@fptr(", "\tdata4.ua\t@fptr("},  /* unaligned */
3436         { "\tdata8\t@fptr(",    "\tdata4\t@fptr("}      /* aligned */
3437       };
3438       fputs (directive[(aligned_p != 0)][POINTER_SIZE == 32], asm_out_file);
3439       output_addr_const (asm_out_file, x);
3440       fputs (")\n", asm_out_file);
3441       return true;
3442     }
3443   return default_assemble_integer (x, size, aligned_p);
3444 }
3445
3446 /* Emit the function prologue.  */
3447
3448 static void
3449 ia64_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3450 {
3451   int mask, grsave, grsave_prev;
3452
3453   if (current_frame_info.need_regstk)
3454     fprintf (file, "\t.regstk %d, %d, %d, %d\n",
3455              current_frame_info.n_input_regs,
3456              current_frame_info.n_local_regs,
3457              current_frame_info.n_output_regs,
3458              current_frame_info.n_rotate_regs);
3459
3460   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3461     return;
3462
3463   /* Emit the .prologue directive.  */
3464
3465   mask = 0;
3466   grsave = grsave_prev = 0;
3467   if (current_frame_info.reg_save_b0 != 0)
3468     {
3469       mask |= 8;
3470       grsave = grsave_prev = current_frame_info.reg_save_b0;
3471     }
3472   if (current_frame_info.reg_save_ar_pfs != 0
3473       && (grsave_prev == 0
3474           || current_frame_info.reg_save_ar_pfs == grsave_prev + 1))
3475     {
3476       mask |= 4;
3477       if (grsave_prev == 0)
3478         grsave = current_frame_info.reg_save_ar_pfs;
3479       grsave_prev = current_frame_info.reg_save_ar_pfs;
3480     }
3481   if (current_frame_info.reg_fp != 0
3482       && (grsave_prev == 0
3483           || current_frame_info.reg_fp == grsave_prev + 1))
3484     {
3485       mask |= 2;
3486       if (grsave_prev == 0)
3487         grsave = HARD_FRAME_POINTER_REGNUM;
3488       grsave_prev = current_frame_info.reg_fp;
3489     }
3490   if (current_frame_info.reg_save_pr != 0
3491       && (grsave_prev == 0
3492           || current_frame_info.reg_save_pr == grsave_prev + 1))
3493     {
3494       mask |= 1;
3495       if (grsave_prev == 0)
3496         grsave = current_frame_info.reg_save_pr;
3497     }
3498
3499   if (mask && TARGET_GNU_AS)
3500     fprintf (file, "\t.prologue %d, %d\n", mask,
3501              ia64_dbx_register_number (grsave));
3502   else
3503     fputs ("\t.prologue\n", file);
3504
3505   /* Emit a .spill directive, if necessary, to relocate the base of
3506      the register spill area.  */
3507   if (current_frame_info.spill_cfa_off != -16)
3508     fprintf (file, "\t.spill %ld\n",
3509              (long) (current_frame_info.spill_cfa_off
3510                      + current_frame_info.spill_size));
3511 }
3512
3513 /* Emit the .body directive at the scheduled end of the prologue.  */
3514
3515 static void
3516 ia64_output_function_end_prologue (FILE *file)
3517 {
3518   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3519     return;
3520
3521   fputs ("\t.body\n", file);
3522 }
3523
3524 /* Emit the function epilogue.  */
3525
3526 static void
3527 ia64_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
3528                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3529 {
3530   int i;
3531
3532   if (current_frame_info.reg_fp)
3533     {
3534       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
3535       reg_names[HARD_FRAME_POINTER_REGNUM]
3536         = reg_names[current_frame_info.reg_fp];
3537       reg_names[current_frame_info.reg_fp] = tmp;
3538     }
3539   if (! TARGET_REG_NAMES)
3540     {
3541       for (i = 0; i < current_frame_info.n_input_regs; i++)
3542         reg_names[IN_REG (i)] = ia64_input_reg_names[i];
3543       for (i = 0; i < current_frame_info.n_local_regs; i++)
3544         reg_names[LOC_REG (i)] = ia64_local_reg_names[i];
3545       for (i = 0; i < current_frame_info.n_output_regs; i++)
3546         reg_names[OUT_REG (i)] = ia64_output_reg_names[i];
3547     }
3548
3549   current_frame_info.initialized = 0;
3550 }
3551
3552 int
3553 ia64_dbx_register_number (int regno)
3554 {
3555   /* In ia64_expand_prologue we quite literally renamed the frame pointer
3556      from its home at loc79 to something inside the register frame.  We
3557      must perform the same renumbering here for the debug info.  */
3558   if (current_frame_info.reg_fp)
3559     {
3560       if (regno == HARD_FRAME_POINTER_REGNUM)
3561         regno = current_frame_info.reg_fp;
3562       else if (regno == current_frame_info.reg_fp)
3563         regno = HARD_FRAME_POINTER_REGNUM;
3564     }
3565
3566   if (IN_REGNO_P (regno))
3567     return 32 + regno - IN_REG (0);
3568   else if (LOC_REGNO_P (regno))
3569     return 32 + current_frame_info.n_input_regs + regno - LOC_REG (0);
3570   else if (OUT_REGNO_P (regno))
3571     return (32 + current_frame_info.n_input_regs
3572             + current_frame_info.n_local_regs + regno - OUT_REG (0));
3573   else
3574     return regno;
3575 }
3576
3577 void
3578 ia64_initialize_trampoline (rtx addr, rtx fnaddr, rtx static_chain)
3579 {
3580   rtx addr_reg, eight = GEN_INT (8);
3581
3582   /* The Intel assembler requires that the global __ia64_trampoline symbol
3583      be declared explicitly */
3584   if (!TARGET_GNU_AS)
3585     {
3586       static bool declared_ia64_trampoline = false;
3587
3588       if (!declared_ia64_trampoline)
3589         {
3590           declared_ia64_trampoline = true;
3591           (*targetm.asm_out.globalize_label) (asm_out_file,
3592                                               "__ia64_trampoline");
3593         }
3594     }
3595
3596   /* Make sure addresses are Pmode even if we are in ILP32 mode. */
3597   addr = convert_memory_address (Pmode, addr);
3598   fnaddr = convert_memory_address (Pmode, fnaddr);
3599   static_chain = convert_memory_address (Pmode, static_chain);
3600
3601   /* Load up our iterator.  */
3602   addr_reg = gen_reg_rtx (Pmode);
3603   emit_move_insn (addr_reg, addr);
3604
3605   /* The first two words are the fake descriptor:
3606      __ia64_trampoline, ADDR+16.  */
3607   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3608                   gen_rtx_SYMBOL_REF (Pmode, "__ia64_trampoline"));
3609   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3610
3611   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3612                   copy_to_reg (plus_constant (addr, 16)));
3613   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3614
3615   /* The third word is the target descriptor.  */
3616   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), fnaddr);
3617   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3618
3619   /* The fourth word is the static chain.  */
3620   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), static_chain);
3621 }
3622 \f
3623 /* Do any needed setup for a variadic function.  CUM has not been updated
3624    for the last named argument which has type TYPE and mode MODE.
3625
3626    We generate the actual spill instructions during prologue generation.  */
3627
3628 static void
3629 ia64_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3630                              tree type, int * pretend_size,
3631                              int second_time ATTRIBUTE_UNUSED)
3632 {
3633   CUMULATIVE_ARGS next_cum = *cum;
3634
3635   /* Skip the current argument.  */
3636   ia64_function_arg_advance (&next_cum, mode, type, 1);
3637
3638   if (next_cum.words < MAX_ARGUMENT_SLOTS)
3639     {
3640       int n = MAX_ARGUMENT_SLOTS - next_cum.words;
3641       *pretend_size = n * UNITS_PER_WORD;
3642       cfun->machine->n_varargs = n;
3643     }
3644 }
3645
3646 /* Check whether TYPE is a homogeneous floating point aggregate.  If
3647    it is, return the mode of the floating point type that appears
3648    in all leafs.  If it is not, return VOIDmode.
3649
3650    An aggregate is a homogeneous floating point aggregate is if all
3651    fields/elements in it have the same floating point type (e.g,
3652    SFmode).  128-bit quad-precision floats are excluded.
3653
3654    Variable sized aggregates should never arrive here, since we should
3655    have already decided to pass them by reference.  Top-level zero-sized
3656    aggregates are excluded because our parallels crash the middle-end.  */
3657
3658 static enum machine_mode
3659 hfa_element_mode (tree type, bool nested)
3660 {
3661   enum machine_mode element_mode = VOIDmode;
3662   enum machine_mode mode;
3663   enum tree_code code = TREE_CODE (type);
3664   int know_element_mode = 0;
3665   tree t;
3666
3667   if (!nested && (!TYPE_SIZE (type) || integer_zerop (TYPE_SIZE (type))))
3668     return VOIDmode;
3669
3670   switch (code)
3671     {
3672     case VOID_TYPE:     case INTEGER_TYPE:      case ENUMERAL_TYPE:
3673     case BOOLEAN_TYPE:  case CHAR_TYPE:         case POINTER_TYPE:
3674     case OFFSET_TYPE:   case REFERENCE_TYPE:    case METHOD_TYPE:
3675     case LANG_TYPE:             case FUNCTION_TYPE:
3676       return VOIDmode;
3677
3678       /* Fortran complex types are supposed to be HFAs, so we need to handle
3679          gcc's COMPLEX_TYPEs as HFAs.  We need to exclude the integral complex
3680          types though.  */
3681     case COMPLEX_TYPE:
3682       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_COMPLEX_FLOAT
3683           && TYPE_MODE (type) != TCmode)
3684         return GET_MODE_INNER (TYPE_MODE (type));
3685       else
3686         return VOIDmode;
3687
3688     case REAL_TYPE:
3689       /* We want to return VOIDmode for raw REAL_TYPEs, but the actual
3690          mode if this is contained within an aggregate.  */
3691       if (nested && TYPE_MODE (type) != TFmode)
3692         return TYPE_MODE (type);
3693       else
3694         return VOIDmode;
3695
3696     case ARRAY_TYPE:
3697       return hfa_element_mode (TREE_TYPE (type), 1);
3698
3699     case RECORD_TYPE:
3700     case UNION_TYPE:
3701     case QUAL_UNION_TYPE:
3702       for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
3703         {
3704           if (TREE_CODE (t) != FIELD_DECL)
3705             continue;
3706
3707           mode = hfa_element_mode (TREE_TYPE (t), 1);
3708           if (know_element_mode)
3709             {
3710               if (mode != element_mode)
3711                 return VOIDmode;
3712             }
3713           else if (GET_MODE_CLASS (mode) != MODE_FLOAT)
3714             return VOIDmode;
3715           else
3716             {
3717               know_element_mode = 1;
3718               element_mode = mode;
3719             }
3720         }
3721       return element_mode;
3722
3723     default:
3724       /* If we reach here, we probably have some front-end specific type
3725          that the backend doesn't know about.  This can happen via the
3726          aggregate_value_p call in init_function_start.  All we can do is
3727          ignore unknown tree types.  */
3728       return VOIDmode;
3729     }
3730
3731   return VOIDmode;
3732 }
3733
3734 /* Return the number of words required to hold a quantity of TYPE and MODE
3735    when passed as an argument.  */
3736 static int
3737 ia64_function_arg_words (tree type, enum machine_mode mode)
3738 {
3739   int words;
3740
3741   if (mode == BLKmode)
3742     words = int_size_in_bytes (type);
3743   else
3744     words = GET_MODE_SIZE (mode);
3745
3746   return (words + UNITS_PER_WORD - 1) / UNITS_PER_WORD;  /* round up */
3747 }
3748
3749 /* Return the number of registers that should be skipped so the current
3750    argument (described by TYPE and WORDS) will be properly aligned.
3751
3752    Integer and float arguments larger than 8 bytes start at the next
3753    even boundary.  Aggregates larger than 8 bytes start at the next
3754    even boundary if the aggregate has 16 byte alignment.  Note that
3755    in the 32-bit ABI, TImode and TFmode have only 8-byte alignment
3756    but are still to be aligned in registers.
3757
3758    ??? The ABI does not specify how to handle aggregates with
3759    alignment from 9 to 15 bytes, or greater than 16.  We handle them
3760    all as if they had 16 byte alignment.  Such aggregates can occur
3761    only if gcc extensions are used.  */
3762 static int
3763 ia64_function_arg_offset (CUMULATIVE_ARGS *cum, tree type, int words)
3764 {
3765   if ((cum->words & 1) == 0)
3766     return 0;
3767
3768   if (type
3769       && TREE_CODE (type) != INTEGER_TYPE
3770       && TREE_CODE (type) != REAL_TYPE)
3771     return TYPE_ALIGN (type) > 8 * BITS_PER_UNIT;
3772   else
3773     return words > 1;
3774 }
3775
3776 /* Return rtx for register where argument is passed, or zero if it is passed
3777    on the stack.  */
3778 /* ??? 128-bit quad-precision floats are always passed in general
3779    registers.  */
3780
3781 rtx
3782 ia64_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode, tree type,
3783                    int named, int incoming)
3784 {
3785   int basereg = (incoming ? GR_ARG_FIRST : AR_ARG_FIRST);
3786   int words = ia64_function_arg_words (type, mode);
3787   int offset = ia64_function_arg_offset (cum, type, words);
3788   enum machine_mode hfa_mode = VOIDmode;
3789
3790   /* If all argument slots are used, then it must go on the stack.  */
3791   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3792     return 0;
3793
3794   /* Check for and handle homogeneous FP aggregates.  */
3795   if (type)
3796     hfa_mode = hfa_element_mode (type, 0);
3797
3798   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
3799      and unprototyped hfas are passed specially.  */
3800   if (hfa_mode != VOIDmode && (! cum->prototype || named))
3801     {
3802       rtx loc[16];
3803       int i = 0;
3804       int fp_regs = cum->fp_regs;
3805       int int_regs = cum->words + offset;
3806       int hfa_size = GET_MODE_SIZE (hfa_mode);
3807       int byte_size;
3808       int args_byte_size;
3809
3810       /* If prototyped, pass it in FR regs then GR regs.
3811          If not prototyped, pass it in both FR and GR regs.
3812
3813          If this is an SFmode aggregate, then it is possible to run out of
3814          FR regs while GR regs are still left.  In that case, we pass the
3815          remaining part in the GR regs.  */
3816
3817       /* Fill the FP regs.  We do this always.  We stop if we reach the end
3818          of the argument, the last FP register, or the last argument slot.  */
3819
3820       byte_size = ((mode == BLKmode)
3821                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3822       args_byte_size = int_regs * UNITS_PER_WORD;
3823       offset = 0;
3824       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
3825               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD)); i++)
3826         {
3827           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3828                                       gen_rtx_REG (hfa_mode, (FR_ARG_FIRST
3829                                                               + fp_regs)),
3830                                       GEN_INT (offset));
3831           offset += hfa_size;
3832           args_byte_size += hfa_size;
3833           fp_regs++;
3834         }
3835
3836       /* If no prototype, then the whole thing must go in GR regs.  */
3837       if (! cum->prototype)
3838         offset = 0;
3839       /* If this is an SFmode aggregate, then we might have some left over
3840          that needs to go in GR regs.  */
3841       else if (byte_size != offset)
3842         int_regs += offset / UNITS_PER_WORD;
3843
3844       /* Fill in the GR regs.  We must use DImode here, not the hfa mode.  */
3845
3846       for (; offset < byte_size && int_regs < MAX_ARGUMENT_SLOTS; i++)
3847         {
3848           enum machine_mode gr_mode = DImode;
3849           unsigned int gr_size;
3850
3851           /* If we have an odd 4 byte hunk because we ran out of FR regs,
3852              then this goes in a GR reg left adjusted/little endian, right
3853              adjusted/big endian.  */
3854           /* ??? Currently this is handled wrong, because 4-byte hunks are
3855              always right adjusted/little endian.  */
3856           if (offset & 0x4)
3857             gr_mode = SImode;
3858           /* If we have an even 4 byte hunk because the aggregate is a
3859              multiple of 4 bytes in size, then this goes in a GR reg right
3860              adjusted/little endian.  */
3861           else if (byte_size - offset == 4)
3862             gr_mode = SImode;
3863
3864           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3865                                       gen_rtx_REG (gr_mode, (basereg
3866                                                              + int_regs)),
3867                                       GEN_INT (offset));
3868
3869           gr_size = GET_MODE_SIZE (gr_mode);
3870           offset += gr_size;
3871           if (gr_size == UNITS_PER_WORD
3872               || (gr_size < UNITS_PER_WORD && offset % UNITS_PER_WORD == 0))
3873             int_regs++;
3874           else if (gr_size > UNITS_PER_WORD)
3875             int_regs += gr_size / UNITS_PER_WORD;
3876         }
3877       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
3878     }
3879
3880   /* Integral and aggregates go in general registers.  If we have run out of
3881      FR registers, then FP values must also go in general registers.  This can
3882      happen when we have a SFmode HFA.  */
3883   else if (mode == TFmode || mode == TCmode
3884            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
3885     {
3886       int byte_size = ((mode == BLKmode)
3887                        ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3888       if (BYTES_BIG_ENDIAN
3889         && (mode == BLKmode || (type && AGGREGATE_TYPE_P (type)))
3890         && byte_size < UNITS_PER_WORD
3891         && byte_size > 0)
3892         {
3893           rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3894                                           gen_rtx_REG (DImode,
3895                                                        (basereg + cum->words
3896                                                         + offset)),
3897                                           const0_rtx);
3898           return gen_rtx_PARALLEL (mode, gen_rtvec (1, gr_reg));
3899         }
3900       else
3901         return gen_rtx_REG (mode, basereg + cum->words + offset);
3902
3903     }
3904
3905   /* If there is a prototype, then FP values go in a FR register when
3906      named, and in a GR register when unnamed.  */
3907   else if (cum->prototype)
3908     {
3909       if (named)
3910         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->fp_regs);
3911       /* In big-endian mode, an anonymous SFmode value must be represented
3912          as (parallel:SF [(expr_list (reg:DI n) (const_int 0))]) to force
3913          the value into the high half of the general register.  */
3914       else if (BYTES_BIG_ENDIAN && mode == SFmode)
3915         return gen_rtx_PARALLEL (mode,
3916                  gen_rtvec (1,
3917                    gen_rtx_EXPR_LIST (VOIDmode,
3918                      gen_rtx_REG (DImode, basereg + cum->words + offset),
3919                                       const0_rtx)));
3920       /* Similarly, an anonymous XFmode or RFmode value must be split
3921          into two registers and padded appropriately.  */
3922       else if (BYTES_BIG_ENDIAN && (mode == XFmode || mode == RFmode))
3923         {
3924           rtx loc[2];
3925           loc[0] = gen_rtx_EXPR_LIST (VOIDmode,
3926                      gen_rtx_REG (DImode, basereg + cum->words + offset),
3927                                       const0_rtx);
3928           loc[1] = gen_rtx_EXPR_LIST (VOIDmode,
3929                      gen_rtx_REG (DImode, basereg + cum->words + offset + 1),
3930                                       GEN_INT (UNITS_PER_WORD));
3931           return gen_rtx_PARALLEL (mode, gen_rtvec_v (2, loc));
3932         }
3933       else
3934         return gen_rtx_REG (mode, basereg + cum->words + offset);
3935     }
3936   /* If there is no prototype, then FP values go in both FR and GR
3937      registers.  */
3938   else
3939     {
3940       /* See comment above.  */
3941       enum machine_mode inner_mode =
3942         (BYTES_BIG_ENDIAN && mode == SFmode) ? DImode : mode;
3943
3944       rtx fp_reg = gen_rtx_EXPR_LIST (VOIDmode,
3945                                       gen_rtx_REG (mode, (FR_ARG_FIRST
3946                                                           + cum->fp_regs)),
3947                                       const0_rtx);
3948       rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3949                                       gen_rtx_REG (inner_mode,
3950                                                    (basereg + cum->words
3951                                                     + offset)),
3952                                       const0_rtx);
3953
3954       return gen_rtx_PARALLEL (mode, gen_rtvec (2, fp_reg, gr_reg));
3955     }
3956 }
3957
3958 /* Return number of bytes, at the beginning of the argument, that must be
3959    put in registers.  0 is the argument is entirely in registers or entirely
3960    in memory.  */
3961
3962 static int
3963 ia64_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3964                         tree type, bool named ATTRIBUTE_UNUSED)
3965 {
3966   int words = ia64_function_arg_words (type, mode);
3967   int offset = ia64_function_arg_offset (cum, type, words);
3968
3969   /* If all argument slots are used, then it must go on the stack.  */
3970   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3971     return 0;
3972
3973   /* It doesn't matter whether the argument goes in FR or GR regs.  If
3974      it fits within the 8 argument slots, then it goes entirely in
3975      registers.  If it extends past the last argument slot, then the rest
3976      goes on the stack.  */
3977
3978   if (words + cum->words + offset <= MAX_ARGUMENT_SLOTS)
3979     return 0;
3980
3981   return (MAX_ARGUMENT_SLOTS - cum->words - offset) * UNITS_PER_WORD;
3982 }
3983
3984 /* Update CUM to point after this argument.  This is patterned after
3985    ia64_function_arg.  */
3986
3987 void
3988 ia64_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3989                            tree type, int named)
3990 {
3991   int words = ia64_function_arg_words (type, mode);
3992   int offset = ia64_function_arg_offset (cum, type, words);
3993   enum machine_mode hfa_mode = VOIDmode;
3994
3995   /* If all arg slots are already full, then there is nothing to do.  */
3996   if (cum->words >= MAX_ARGUMENT_SLOTS)
3997     return;
3998
3999   cum->words += words + offset;
4000
4001   /* Check for and handle homogeneous FP aggregates.  */
4002   if (type)
4003     hfa_mode = hfa_element_mode (type, 0);
4004
4005   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
4006      and unprototyped hfas are passed specially.  */
4007   if (hfa_mode != VOIDmode && (! cum->prototype || named))
4008     {
4009       int fp_regs = cum->fp_regs;
4010       /* This is the original value of cum->words + offset.  */
4011       int int_regs = cum->words - words;
4012       int hfa_size = GET_MODE_SIZE (hfa_mode);
4013       int byte_size;
4014       int args_byte_size;
4015
4016       /* If prototyped, pass it in FR regs then GR regs.
4017          If not prototyped, pass it in both FR and GR regs.
4018
4019          If this is an SFmode aggregate, then it is possible to run out of
4020          FR regs while GR regs are still left.  In that case, we pass the
4021          remaining part in the GR regs.  */
4022
4023       /* Fill the FP regs.  We do this always.  We stop if we reach the end
4024          of the argument, the last FP register, or the last argument slot.  */
4025
4026       byte_size = ((mode == BLKmode)
4027                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4028       args_byte_size = int_regs * UNITS_PER_WORD;
4029       offset = 0;
4030       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
4031               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD));)
4032         {
4033           offset += hfa_size;
4034           args_byte_size += hfa_size;
4035           fp_regs++;
4036         }
4037
4038       cum->fp_regs = fp_regs;
4039     }
4040
4041   /* Integral and aggregates go in general registers.  So do TFmode FP values.
4042      If we have run out of FR registers, then other FP values must also go in
4043      general registers.  This can happen when we have a SFmode HFA.  */
4044   else if (mode == TFmode || mode == TCmode
4045            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
4046     cum->int_regs = cum->words;
4047
4048   /* If there is a prototype, then FP values go in a FR register when
4049      named, and in a GR register when unnamed.  */
4050   else if (cum->prototype)
4051     {
4052       if (! named)
4053         cum->int_regs = cum->words;
4054       else
4055         /* ??? Complex types should not reach here.  */
4056         cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4057     }
4058   /* If there is no prototype, then FP values go in both FR and GR
4059      registers.  */
4060   else
4061     {
4062       /* ??? Complex types should not reach here.  */
4063       cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4064       cum->int_regs = cum->words;
4065     }
4066 }
4067
4068 /* Arguments with alignment larger than 8 bytes start at the next even
4069    boundary.  On ILP32 HPUX, TFmode arguments start on next even boundary
4070    even though their normal alignment is 8 bytes.  See ia64_function_arg.  */
4071
4072 int
4073 ia64_function_arg_boundary (enum machine_mode mode, tree type)
4074 {
4075
4076   if (mode == TFmode && TARGET_HPUX && TARGET_ILP32)
4077     return PARM_BOUNDARY * 2;
4078
4079   if (type)
4080     {
4081       if (TYPE_ALIGN (type) > PARM_BOUNDARY)
4082         return PARM_BOUNDARY * 2;
4083       else
4084         return PARM_BOUNDARY;
4085     }
4086
4087   if (GET_MODE_BITSIZE (mode) > PARM_BOUNDARY)
4088     return PARM_BOUNDARY * 2;
4089   else
4090     return PARM_BOUNDARY;
4091 }
4092
4093 /* Variable sized types are passed by reference.  */
4094 /* ??? At present this is a GCC extension to the IA-64 ABI.  */
4095
4096 static bool
4097 ia64_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
4098                         enum machine_mode mode ATTRIBUTE_UNUSED,
4099                         tree type, bool named ATTRIBUTE_UNUSED)
4100 {
4101   return type && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST;
4102 }
4103
4104 /* True if it is OK to do sibling call optimization for the specified
4105    call expression EXP.  DECL will be the called function, or NULL if
4106    this is an indirect call.  */
4107 static bool
4108 ia64_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
4109 {
4110   /* We can't perform a sibcall if the current function has the syscall_linkage
4111      attribute.  */
4112   if (lookup_attribute ("syscall_linkage",
4113                         TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
4114     return false;
4115
4116   /* We must always return with our current GP.  This means we can
4117      only sibcall to functions defined in the current module.  */
4118   return decl && (*targetm.binds_local_p) (decl);
4119 }
4120 \f
4121
4122 /* Implement va_arg.  */
4123
4124 static tree
4125 ia64_gimplify_va_arg (tree valist, tree type, tree *pre_p, tree *post_p)
4126 {
4127   /* Variable sized types are passed by reference.  */
4128   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
4129     {
4130       tree ptrtype = build_pointer_type (type);
4131       tree addr = std_gimplify_va_arg_expr (valist, ptrtype, pre_p, post_p);
4132       return build_va_arg_indirect_ref (addr);
4133     }
4134
4135   /* Aggregate arguments with alignment larger than 8 bytes start at
4136      the next even boundary.  Integer and floating point arguments
4137      do so if they are larger than 8 bytes, whether or not they are
4138      also aligned larger than 8 bytes.  */
4139   if ((TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == INTEGER_TYPE)
4140       ? int_size_in_bytes (type) > 8 : TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
4141     {
4142       tree t = build (PLUS_EXPR, TREE_TYPE (valist), valist,
4143                       build_int_cst (NULL_TREE, 2 * UNITS_PER_WORD - 1));
4144       t = build (BIT_AND_EXPR, TREE_TYPE (t), t,
4145                  build_int_cst (NULL_TREE, -2 * UNITS_PER_WORD));
4146       t = build (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
4147       gimplify_and_add (t, pre_p);
4148     }
4149
4150   return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
4151 }
4152 \f
4153 /* Return 1 if function return value returned in memory.  Return 0 if it is
4154    in a register.  */
4155
4156 static bool
4157 ia64_return_in_memory (tree valtype, tree fntype ATTRIBUTE_UNUSED)
4158 {
4159   enum machine_mode mode;
4160   enum machine_mode hfa_mode;
4161   HOST_WIDE_INT byte_size;
4162
4163   mode = TYPE_MODE (valtype);
4164   byte_size = GET_MODE_SIZE (mode);
4165   if (mode == BLKmode)
4166     {
4167       byte_size = int_size_in_bytes (valtype);
4168       if (byte_size < 0)
4169         return true;
4170     }
4171
4172   /* Hfa's with up to 8 elements are returned in the FP argument registers.  */
4173
4174   hfa_mode = hfa_element_mode (valtype, 0);
4175   if (hfa_mode != VOIDmode)
4176     {
4177       int hfa_size = GET_MODE_SIZE (hfa_mode);
4178
4179       if (byte_size / hfa_size > MAX_ARGUMENT_SLOTS)
4180         return true;
4181       else
4182         return false;
4183     }
4184   else if (byte_size > UNITS_PER_WORD * MAX_INT_RETURN_SLOTS)
4185     return true;
4186   else
4187     return false;
4188 }
4189
4190 /* Return rtx for register that holds the function return value.  */
4191
4192 rtx
4193 ia64_function_value (tree valtype, tree func ATTRIBUTE_UNUSED)
4194 {
4195   enum machine_mode mode;
4196   enum machine_mode hfa_mode;
4197
4198   mode = TYPE_MODE (valtype);
4199   hfa_mode = hfa_element_mode (valtype, 0);
4200
4201   if (hfa_mode != VOIDmode)
4202     {
4203       rtx loc[8];
4204       int i;
4205       int hfa_size;
4206       int byte_size;
4207       int offset;
4208
4209       hfa_size = GET_MODE_SIZE (hfa_mode);
4210       byte_size = ((mode == BLKmode)
4211                    ? int_size_in_bytes (valtype) : GET_MODE_SIZE (mode));
4212       offset = 0;
4213       for (i = 0; offset < byte_size; i++)
4214         {
4215           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4216                                       gen_rtx_REG (hfa_mode, FR_ARG_FIRST + i),
4217                                       GEN_INT (offset));
4218           offset += hfa_size;
4219         }
4220       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4221     }
4222   else if (FLOAT_TYPE_P (valtype) && mode != TFmode && mode != TCmode)
4223     return gen_rtx_REG (mode, FR_ARG_FIRST);
4224   else
4225     {
4226       bool need_parallel = false;
4227
4228       /* In big-endian mode, we need to manage the layout of aggregates
4229          in the registers so that we get the bits properly aligned in
4230          the highpart of the registers.  */
4231       if (BYTES_BIG_ENDIAN
4232           && (mode == BLKmode || (valtype && AGGREGATE_TYPE_P (valtype))))
4233         need_parallel = true;
4234
4235       /* Something like struct S { long double x; char a[0] } is not an
4236          HFA structure, and therefore doesn't go in fp registers.  But
4237          the middle-end will give it XFmode anyway, and XFmode values
4238          don't normally fit in integer registers.  So we need to smuggle
4239          the value inside a parallel.  */
4240       else if (mode == XFmode || mode == XCmode || mode == RFmode)
4241         need_parallel = true;
4242
4243       if (need_parallel)
4244         {
4245           rtx loc[8];
4246           int offset;
4247           int bytesize;
4248           int i;
4249
4250           offset = 0;
4251           bytesize = int_size_in_bytes (valtype);
4252           /* An empty PARALLEL is invalid here, but the return value
4253              doesn't matter for empty structs.  */
4254           if (bytesize == 0)
4255             return gen_rtx_REG (mode, GR_RET_FIRST);
4256           for (i = 0; offset < bytesize; i++)
4257             {
4258               loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4259                                           gen_rtx_REG (DImode,
4260                                                        GR_RET_FIRST + i),
4261                                           GEN_INT (offset));
4262               offset += UNITS_PER_WORD;
4263             }
4264           return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4265         }
4266
4267       return gen_rtx_REG (mode, GR_RET_FIRST);
4268     }
4269 }
4270
4271 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
4272    We need to emit DTP-relative relocations.  */
4273
4274 static void
4275 ia64_output_dwarf_dtprel (FILE *file, int size, rtx x)
4276 {
4277   gcc_assert (size == 8);
4278   fputs ("\tdata8.ua\t@dtprel(", file);
4279   output_addr_const (file, x);
4280   fputs (")", file);
4281 }
4282
4283 /* Print a memory address as an operand to reference that memory location.  */
4284
4285 /* ??? Do we need this?  It gets used only for 'a' operands.  We could perhaps
4286    also call this from ia64_print_operand for memory addresses.  */
4287
4288 void
4289 ia64_print_operand_address (FILE * stream ATTRIBUTE_UNUSED,
4290                             rtx address ATTRIBUTE_UNUSED)
4291 {
4292 }
4293
4294 /* Print an operand to an assembler instruction.
4295    C    Swap and print a comparison operator.
4296    D    Print an FP comparison operator.
4297    E    Print 32 - constant, for SImode shifts as extract.
4298    e    Print 64 - constant, for DImode rotates.
4299    F    A floating point constant 0.0 emitted as f0, or 1.0 emitted as f1, or
4300         a floating point register emitted normally.
4301    I    Invert a predicate register by adding 1.
4302    J    Select the proper predicate register for a condition.
4303    j    Select the inverse predicate register for a condition.
4304    O    Append .acq for volatile load.
4305    P    Postincrement of a MEM.
4306    Q    Append .rel for volatile store.
4307    S    Shift amount for shladd instruction.
4308    T    Print an 8-bit sign extended number (K) as a 32-bit unsigned number
4309         for Intel assembler.
4310    U    Print an 8-bit sign extended number (K) as a 64-bit unsigned number
4311         for Intel assembler.
4312    r    Print register name, or constant 0 as r0.  HP compatibility for
4313         Linux kernel.
4314    v    Print vector constant value as an 8-byte integer value.  */
4315
4316 void
4317 ia64_print_operand (FILE * file, rtx x, int code)
4318 {
4319   const char *str;
4320
4321   switch (code)
4322     {
4323     case 0:
4324       /* Handled below.  */
4325       break;
4326
4327     case 'C':
4328       {
4329         enum rtx_code c = swap_condition (GET_CODE (x));
4330         fputs (GET_RTX_NAME (c), file);
4331         return;
4332       }
4333
4334     case 'D':
4335       switch (GET_CODE (x))
4336         {
4337         case NE:
4338           str = "neq";
4339           break;
4340         case UNORDERED:
4341           str = "unord";
4342           break;
4343         case ORDERED:
4344           str = "ord";
4345           break;
4346         default:
4347           str = GET_RTX_NAME (GET_CODE (x));
4348           break;
4349         }
4350       fputs (str, file);
4351       return;
4352
4353     case 'E':
4354       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 32 - INTVAL (x));
4355       return;
4356
4357     case 'e':
4358       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 64 - INTVAL (x));
4359       return;
4360
4361     case 'F':
4362       if (x == CONST0_RTX (GET_MODE (x)))
4363         str = reg_names [FR_REG (0)];
4364       else if (x == CONST1_RTX (GET_MODE (x)))
4365         str = reg_names [FR_REG (1)];
4366       else
4367         {
4368           gcc_assert (GET_CODE (x) == REG);
4369           str = reg_names [REGNO (x)];
4370         }
4371       fputs (str, file);
4372       return;
4373
4374     case 'I':
4375       fputs (reg_names [REGNO (x) + 1], file);
4376       return;
4377
4378     case 'J':
4379     case 'j':
4380       {
4381         unsigned int regno = REGNO (XEXP (x, 0));
4382         if (GET_CODE (x) == EQ)
4383           regno += 1;
4384         if (code == 'j')
4385           regno ^= 1;
4386         fputs (reg_names [regno], file);
4387       }
4388       return;
4389
4390     case 'O':
4391       if (MEM_VOLATILE_P (x))
4392         fputs(".acq", file);
4393       return;
4394
4395     case 'P':
4396       {
4397         HOST_WIDE_INT value;
4398
4399         switch (GET_CODE (XEXP (x, 0)))
4400           {
4401           default:
4402             return;
4403
4404           case POST_MODIFY:
4405             x = XEXP (XEXP (XEXP (x, 0), 1), 1);
4406             if (GET_CODE (x) == CONST_INT)
4407               value = INTVAL (x);
4408             else
4409               {
4410                 gcc_assert (GET_CODE (x) == REG);
4411                 fprintf (file, ", %s", reg_names[REGNO (x)]);
4412                 return;
4413               }
4414             break;
4415
4416           case POST_INC:
4417             value = GET_MODE_SIZE (GET_MODE (x));
4418             break;
4419
4420           case POST_DEC:
4421             value = - (HOST_WIDE_INT) GET_MODE_SIZE (GET_MODE (x));
4422             break;
4423           }
4424
4425         fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC, value);
4426         return;
4427       }
4428
4429     case 'Q':
4430       if (MEM_VOLATILE_P (x))
4431         fputs(".rel", file);
4432       return;
4433
4434     case 'S':
4435       fprintf (file, "%d", exact_log2 (INTVAL (x)));
4436       return;
4437
4438     case 'T':
4439       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
4440         {
4441           fprintf (file, "0x%x", (int) INTVAL (x) & 0xffffffff);
4442           return;
4443         }
4444       break;
4445
4446     case 'U':
4447       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
4448         {
4449           const char *prefix = "0x";
4450           if (INTVAL (x) & 0x80000000)
4451             {
4452               fprintf (file, "0xffffffff");
4453               prefix = "";
4454             }
4455           fprintf (file, "%s%x", prefix, (int) INTVAL (x) & 0xffffffff);
4456           return;
4457         }
4458       break;
4459
4460     case 'r':
4461       /* If this operand is the constant zero, write it as register zero.
4462          Any register, zero, or CONST_INT value is OK here.  */
4463       if (GET_CODE (x) == REG)
4464         fputs (reg_names[REGNO (x)], file);
4465       else if (x == CONST0_RTX (GET_MODE (x)))
4466         fputs ("r0", file);
4467       else if (GET_CODE (x) == CONST_INT)
4468         output_addr_const (file, x);
4469       else
4470         output_operand_lossage ("invalid %%r value");
4471       return;
4472
4473     case 'v':
4474       gcc_assert (GET_CODE (x) == CONST_VECTOR);
4475       x = simplify_subreg (DImode, x, GET_MODE (x), 0);
4476       break;
4477
4478     case '+':
4479       {
4480         const char *which;
4481
4482         /* For conditional branches, returns or calls, substitute
4483            sptk, dptk, dpnt, or spnt for %s.  */
4484         x = find_reg_note (current_output_insn, REG_BR_PROB, 0);
4485         if (x)
4486           {
4487             int pred_val = INTVAL (XEXP (x, 0));
4488
4489             /* Guess top and bottom 10% statically predicted.  */
4490             if (pred_val < REG_BR_PROB_BASE / 50)
4491               which = ".spnt";
4492             else if (pred_val < REG_BR_PROB_BASE / 2)
4493               which = ".dpnt";
4494             else if (pred_val < REG_BR_PROB_BASE / 100 * 98)
4495               which = ".dptk";
4496             else
4497               which = ".sptk";
4498           }
4499         else if (GET_CODE (current_output_insn) == CALL_INSN)
4500           which = ".sptk";
4501         else
4502           which = ".dptk";
4503
4504         fputs (which, file);
4505         return;
4506       }
4507
4508     case ',':
4509       x = current_insn_predicate;
4510       if (x)
4511         {
4512           unsigned int regno = REGNO (XEXP (x, 0));
4513           if (GET_CODE (x) == EQ)
4514             regno += 1;
4515           fprintf (file, "(%s) ", reg_names [regno]);
4516         }
4517       return;
4518
4519     default:
4520       output_operand_lossage ("ia64_print_operand: unknown code");
4521       return;
4522     }
4523
4524   switch (GET_CODE (x))
4525     {
4526       /* This happens for the spill/restore instructions.  */
4527     case POST_INC:
4528     case POST_DEC:
4529     case POST_MODIFY:
4530       x = XEXP (x, 0);
4531       /* ... fall through ...  */
4532
4533     case REG:
4534       fputs (reg_names [REGNO (x)], file);
4535       break;
4536
4537     case MEM:
4538       {
4539         rtx addr = XEXP (x, 0);
4540         if (GET_RTX_CLASS (GET_CODE (addr)) == RTX_AUTOINC)
4541           addr = XEXP (addr, 0);
4542         fprintf (file, "[%s]", reg_names [REGNO (addr)]);
4543         break;
4544       }
4545
4546     default:
4547       output_addr_const (file, x);
4548       break;
4549     }
4550
4551   return;
4552 }
4553 \f
4554 /* Compute a (partial) cost for rtx X.  Return true if the complete
4555    cost has been computed, and false if subexpressions should be
4556    scanned.  In either case, *TOTAL contains the cost result.  */
4557 /* ??? This is incomplete.  */
4558
4559 static bool
4560 ia64_rtx_costs (rtx x, int code, int outer_code, int *total)
4561 {
4562   switch (code)
4563     {
4564     case CONST_INT:
4565       switch (outer_code)
4566         {
4567         case SET:
4568           *total = CONST_OK_FOR_J (INTVAL (x)) ? 0 : COSTS_N_INSNS (1);
4569           return true;
4570         case PLUS:
4571           if (CONST_OK_FOR_I (INTVAL (x)))
4572             *total = 0;
4573           else if (CONST_OK_FOR_J (INTVAL (x)))
4574             *total = 1;
4575           else
4576             *total = COSTS_N_INSNS (1);
4577           return true;
4578         default:
4579           if (CONST_OK_FOR_K (INTVAL (x)) || CONST_OK_FOR_L (INTVAL (x)))
4580             *total = 0;
4581           else
4582             *total = COSTS_N_INSNS (1);
4583           return true;
4584         }
4585
4586     case CONST_DOUBLE:
4587       *total = COSTS_N_INSNS (1);
4588       return true;
4589
4590     case CONST:
4591     case SYMBOL_REF:
4592     case LABEL_REF:
4593       *total = COSTS_N_INSNS (3);
4594       return true;
4595
4596     case MULT:
4597       /* For multiplies wider than HImode, we have to go to the FPU,
4598          which normally involves copies.  Plus there's the latency
4599          of the multiply itself, and the latency of the instructions to
4600          transfer integer regs to FP regs.  */
4601       /* ??? Check for FP mode.  */
4602       if (GET_MODE_SIZE (GET_MODE (x)) > 2)
4603         *total = COSTS_N_INSNS (10);
4604       else
4605         *total = COSTS_N_INSNS (2);
4606       return true;
4607
4608     case PLUS:
4609     case MINUS:
4610     case ASHIFT:
4611     case ASHIFTRT:
4612     case LSHIFTRT:
4613       *total = COSTS_N_INSNS (1);
4614       return true;
4615
4616     case DIV:
4617     case UDIV:
4618     case MOD:
4619     case UMOD:
4620       /* We make divide expensive, so that divide-by-constant will be
4621          optimized to a multiply.  */
4622       *total = COSTS_N_INSNS (60);
4623       return true;
4624
4625     default:
4626       return false;
4627     }
4628 }
4629
4630 /* Calculate the cost of moving data from a register in class FROM to
4631    one in class TO, using MODE.  */
4632
4633 int
4634 ia64_register_move_cost (enum machine_mode mode, enum reg_class from,
4635                          enum reg_class to)
4636 {
4637   /* ADDL_REGS is the same as GR_REGS for movement purposes.  */
4638   if (to == ADDL_REGS)
4639     to = GR_REGS;
4640   if (from == ADDL_REGS)
4641     from = GR_REGS;
4642
4643   /* All costs are symmetric, so reduce cases by putting the
4644      lower number class as the destination.  */
4645   if (from < to)
4646     {
4647       enum reg_class tmp = to;
4648       to = from, from = tmp;
4649     }
4650
4651   /* Moving from FR<->GR in XFmode must be more expensive than 2,
4652      so that we get secondary memory reloads.  Between FR_REGS,
4653      we have to make this at least as expensive as MEMORY_MOVE_COST
4654      to avoid spectacularly poor register class preferencing.  */
4655   if (mode == XFmode || mode == RFmode)
4656     {
4657       if (to != GR_REGS || from != GR_REGS)
4658         return MEMORY_MOVE_COST (mode, to, 0);
4659       else
4660         return 3;
4661     }
4662
4663   switch (to)
4664     {
4665     case PR_REGS:
4666       /* Moving between PR registers takes two insns.  */
4667       if (from == PR_REGS)
4668         return 3;
4669       /* Moving between PR and anything but GR is impossible.  */
4670       if (from != GR_REGS)
4671         return MEMORY_MOVE_COST (mode, to, 0);
4672       break;
4673
4674     case BR_REGS:
4675       /* Moving between BR and anything but GR is impossible.  */
4676       if (from != GR_REGS && from != GR_AND_BR_REGS)
4677         return MEMORY_MOVE_COST (mode, to, 0);
4678       break;
4679
4680     case AR_I_REGS:
4681     case AR_M_REGS:
4682       /* Moving between AR and anything but GR is impossible.  */
4683       if (from != GR_REGS)
4684         return MEMORY_MOVE_COST (mode, to, 0);
4685       break;
4686
4687     case GR_REGS:
4688     case FR_REGS:
4689     case GR_AND_FR_REGS:
4690     case GR_AND_BR_REGS:
4691     case ALL_REGS:
4692       break;
4693
4694     default:
4695       gcc_unreachable ();
4696     }
4697
4698   return 2;
4699 }
4700
4701 /* Implement PREFERRED_RELOAD_CLASS.  Place additional restrictions on CLASS
4702    to use when copying X into that class.  */
4703
4704 enum reg_class
4705 ia64_preferred_reload_class (rtx x, enum reg_class class)
4706 {
4707   switch (class)
4708     {
4709     case FR_REGS:
4710       /* Don't allow volatile mem reloads into floating point registers.
4711          This is defined to force reload to choose the r/m case instead
4712          of the f/f case when reloading (set (reg fX) (mem/v)).  */
4713       if (MEM_P (x) && MEM_VOLATILE_P (x))
4714         return NO_REGS;
4715       
4716       /* Force all unrecognized constants into the constant pool.  */
4717       if (CONSTANT_P (x))
4718         return NO_REGS;
4719       break;
4720
4721     case AR_M_REGS:
4722     case AR_I_REGS:
4723       if (!OBJECT_P (x))
4724         return NO_REGS;
4725       break;
4726
4727     default:
4728       break;
4729     }
4730
4731   return class;
4732 }
4733
4734 /* This function returns the register class required for a secondary
4735    register when copying between one of the registers in CLASS, and X,
4736    using MODE.  A return value of NO_REGS means that no secondary register
4737    is required.  */
4738
4739 enum reg_class
4740 ia64_secondary_reload_class (enum reg_class class,
4741                              enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
4742 {
4743   int regno = -1;
4744
4745   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
4746     regno = true_regnum (x);
4747
4748   switch (class)
4749     {
4750     case BR_REGS:
4751     case AR_M_REGS:
4752     case AR_I_REGS:
4753       /* ??? BR<->BR register copies can happen due to a bad gcse/cse/global
4754          interaction.  We end up with two pseudos with overlapping lifetimes
4755          both of which are equiv to the same constant, and both which need
4756          to be in BR_REGS.  This seems to be a cse bug.  cse_basic_block_end
4757          changes depending on the path length, which means the qty_first_reg
4758          check in make_regs_eqv can give different answers at different times.
4759          At some point I'll probably need a reload_indi pattern to handle
4760          this.
4761
4762          We can also get GR_AND_FR_REGS to BR_REGS/AR_REGS copies, where we
4763          wound up with a FP register from GR_AND_FR_REGS.  Extend that to all
4764          non-general registers for good measure.  */
4765       if (regno >= 0 && ! GENERAL_REGNO_P (regno))
4766         return GR_REGS;
4767
4768       /* This is needed if a pseudo used as a call_operand gets spilled to a
4769          stack slot.  */
4770       if (GET_CODE (x) == MEM)
4771         return GR_REGS;
4772       break;
4773
4774     case FR_REGS:
4775       /* Need to go through general registers to get to other class regs.  */
4776       if (regno >= 0 && ! (FR_REGNO_P (regno) || GENERAL_REGNO_P (regno)))
4777         return GR_REGS;
4778
4779       /* This can happen when a paradoxical subreg is an operand to the
4780          muldi3 pattern.  */
4781       /* ??? This shouldn't be necessary after instruction scheduling is
4782          enabled, because paradoxical subregs are not accepted by
4783          register_operand when INSN_SCHEDULING is defined.  Or alternatively,
4784          stop the paradoxical subreg stupidity in the *_operand functions
4785          in recog.c.  */
4786       if (GET_CODE (x) == MEM
4787           && (GET_MODE (x) == SImode || GET_MODE (x) == HImode
4788               || GET_MODE (x) == QImode))
4789         return GR_REGS;
4790
4791       /* This can happen because of the ior/and/etc patterns that accept FP
4792          registers as operands.  If the third operand is a constant, then it
4793          needs to be reloaded into a FP register.  */
4794       if (GET_CODE (x) == CONST_INT)
4795         return GR_REGS;
4796
4797       /* This can happen because of register elimination in a muldi3 insn.
4798          E.g. `26107 * (unsigned long)&u'.  */
4799       if (GET_CODE (x) == PLUS)
4800         return GR_REGS;
4801       break;
4802
4803     case PR_REGS:
4804       /* ??? This happens if we cse/gcse a BImode value across a call,
4805          and the function has a nonlocal goto.  This is because global
4806          does not allocate call crossing pseudos to hard registers when
4807          current_function_has_nonlocal_goto is true.  This is relatively
4808          common for C++ programs that use exceptions.  To reproduce,
4809          return NO_REGS and compile libstdc++.  */
4810       if (GET_CODE (x) == MEM)
4811         return GR_REGS;
4812
4813       /* This can happen when we take a BImode subreg of a DImode value,
4814          and that DImode value winds up in some non-GR register.  */
4815       if (regno >= 0 && ! GENERAL_REGNO_P (regno) && ! PR_REGNO_P (regno))
4816         return GR_REGS;
4817       break;
4818
4819     default:
4820       break;
4821     }
4822
4823   return NO_REGS;
4824 }
4825
4826 \f
4827 /* Emit text to declare externally defined variables and functions, because
4828    the Intel assembler does not support undefined externals.  */
4829
4830 void
4831 ia64_asm_output_external (FILE *file, tree decl, const char *name)
4832 {
4833   int save_referenced;
4834
4835   /* GNU as does not need anything here, but the HP linker does need
4836      something for external functions.  */
4837
4838   if (TARGET_GNU_AS
4839       && (!TARGET_HPUX_LD
4840           || TREE_CODE (decl) != FUNCTION_DECL
4841           || strstr (name, "__builtin_") == name))
4842     return;
4843
4844   /* ??? The Intel assembler creates a reference that needs to be satisfied by
4845      the linker when we do this, so we need to be careful not to do this for
4846      builtin functions which have no library equivalent.  Unfortunately, we
4847      can't tell here whether or not a function will actually be called by
4848      expand_expr, so we pull in library functions even if we may not need
4849      them later.  */
4850   if (! strcmp (name, "__builtin_next_arg")
4851       || ! strcmp (name, "alloca")
4852       || ! strcmp (name, "__builtin_constant_p")
4853       || ! strcmp (name, "__builtin_args_info"))
4854     return;
4855
4856   if (TARGET_HPUX_LD)
4857     ia64_hpux_add_extern_decl (decl);
4858   else
4859     {
4860       /* assemble_name will set TREE_SYMBOL_REFERENCED, so we must save and
4861          restore it.  */
4862       save_referenced = TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl));
4863       if (TREE_CODE (decl) == FUNCTION_DECL)
4864         ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
4865       (*targetm.asm_out.globalize_label) (file, name);
4866       TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = save_referenced;
4867     }
4868 }
4869 \f
4870 /* Parse the -mfixed-range= option string.  */
4871
4872 static void
4873 fix_range (const char *const_str)
4874 {
4875   int i, first, last;
4876   char *str, *dash, *comma;
4877
4878   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
4879      REG2 are either register names or register numbers.  The effect
4880      of this option is to mark the registers in the range from REG1 to
4881      REG2 as ``fixed'' so they won't be used by the compiler.  This is
4882      used, e.g., to ensure that kernel mode code doesn't use f32-f127.  */
4883
4884   i = strlen (const_str);
4885   str = (char *) alloca (i + 1);
4886   memcpy (str, const_str, i + 1);
4887
4888   while (1)
4889     {
4890       dash = strchr (str, '-');
4891       if (!dash)
4892         {
4893           warning (0, "value of -mfixed-range must have form REG1-REG2");
4894           return;
4895         }
4896       *dash = '\0';
4897
4898       comma = strchr (dash + 1, ',');
4899       if (comma)
4900         *comma = '\0';
4901
4902       first = decode_reg_name (str);
4903       if (first < 0)
4904         {
4905           warning (0, "unknown register name: %s", str);
4906           return;
4907         }
4908
4909       last = decode_reg_name (dash + 1);
4910       if (last < 0)
4911         {
4912           warning (0, "unknown register name: %s", dash + 1);
4913           return;
4914         }
4915
4916       *dash = '-';
4917
4918       if (first > last)
4919         {
4920           warning (0, "%s-%s is an empty range", str, dash + 1);
4921           return;
4922         }
4923
4924       for (i = first; i <= last; ++i)
4925         fixed_regs[i] = call_used_regs[i] = 1;
4926
4927       if (!comma)
4928         break;
4929
4930       *comma = ',';
4931       str = comma + 1;
4932     }
4933 }
4934
4935 /* Implement TARGET_HANDLE_OPTION.  */
4936
4937 static bool
4938 ia64_handle_option (size_t code, const char *arg, int value)
4939 {
4940   switch (code)
4941     {
4942     case OPT_mfixed_range_:
4943       fix_range (arg);
4944       return true;
4945
4946     case OPT_mtls_size_:
4947       if (value != 14 && value != 22 && value != 64)
4948         error ("bad value %<%s%> for -mtls-size= switch", arg);
4949       return true;
4950
4951     case OPT_mtune_:
4952       {
4953         static struct pta
4954           {
4955             const char *name;           /* processor name or nickname.  */
4956             enum processor_type processor;
4957           }
4958         const processor_alias_table[] =
4959           {
4960             {"itanium", PROCESSOR_ITANIUM},
4961             {"itanium1", PROCESSOR_ITANIUM},
4962             {"merced", PROCESSOR_ITANIUM},
4963             {"itanium2", PROCESSOR_ITANIUM2},
4964             {"mckinley", PROCESSOR_ITANIUM2},
4965           };
4966         int const pta_size = ARRAY_SIZE (processor_alias_table);
4967         int i;
4968
4969         for (i = 0; i < pta_size; i++)
4970           if (!strcmp (arg, processor_alias_table[i].name))
4971             {
4972               ia64_tune = processor_alias_table[i].processor;
4973               break;
4974             }
4975         if (i == pta_size)
4976           error ("bad value %<%s%> for -mtune= switch", arg);
4977         return true;
4978       }
4979
4980     default:
4981       return true;
4982     }
4983 }
4984
4985 /* Implement OVERRIDE_OPTIONS.  */
4986
4987 void
4988 ia64_override_options (void)
4989 {
4990   if (TARGET_AUTO_PIC)
4991     target_flags |= MASK_CONST_GP;
4992
4993   if (TARGET_INLINE_SQRT == INL_MIN_LAT)
4994     {
4995       warning (0, "not yet implemented: latency-optimized inline square root");
4996       TARGET_INLINE_SQRT = INL_MAX_THR;
4997     }
4998
4999   ia64_flag_schedule_insns2 = flag_schedule_insns_after_reload;
5000   flag_schedule_insns_after_reload = 0;
5001
5002   ia64_section_threshold = g_switch_set ? g_switch_value : IA64_DEFAULT_GVALUE;
5003
5004   init_machine_status = ia64_init_machine_status;
5005 }
5006
5007 static struct machine_function *
5008 ia64_init_machine_status (void)
5009 {
5010   return ggc_alloc_cleared (sizeof (struct machine_function));
5011 }
5012 \f
5013 static enum attr_itanium_class ia64_safe_itanium_class (rtx);
5014 static enum attr_type ia64_safe_type (rtx);
5015
5016 static enum attr_itanium_class
5017 ia64_safe_itanium_class (rtx insn)
5018 {
5019   if (recog_memoized (insn) >= 0)
5020     return get_attr_itanium_class (insn);
5021   else
5022     return ITANIUM_CLASS_UNKNOWN;
5023 }
5024
5025 static enum attr_type
5026 ia64_safe_type (rtx insn)
5027 {
5028   if (recog_memoized (insn) >= 0)
5029     return get_attr_type (insn);
5030   else
5031     return TYPE_UNKNOWN;
5032 }
5033 \f
5034 /* The following collection of routines emit instruction group stop bits as
5035    necessary to avoid dependencies.  */
5036
5037 /* Need to track some additional registers as far as serialization is
5038    concerned so we can properly handle br.call and br.ret.  We could
5039    make these registers visible to gcc, but since these registers are
5040    never explicitly used in gcc generated code, it seems wasteful to
5041    do so (plus it would make the call and return patterns needlessly
5042    complex).  */
5043 #define REG_RP          (BR_REG (0))
5044 #define REG_AR_CFM      (FIRST_PSEUDO_REGISTER + 1)
5045 /* This is used for volatile asms which may require a stop bit immediately
5046    before and after them.  */
5047 #define REG_VOLATILE    (FIRST_PSEUDO_REGISTER + 2)
5048 #define AR_UNAT_BIT_0   (FIRST_PSEUDO_REGISTER + 3)
5049 #define NUM_REGS        (AR_UNAT_BIT_0 + 64)
5050
5051 /* For each register, we keep track of how it has been written in the
5052    current instruction group.
5053
5054    If a register is written unconditionally (no qualifying predicate),
5055    WRITE_COUNT is set to 2 and FIRST_PRED is ignored.
5056
5057    If a register is written if its qualifying predicate P is true, we
5058    set WRITE_COUNT to 1 and FIRST_PRED to P.  Later on, the same register
5059    may be written again by the complement of P (P^1) and when this happens,
5060    WRITE_COUNT gets set to 2.
5061
5062    The result of this is that whenever an insn attempts to write a register
5063    whose WRITE_COUNT is two, we need to issue an insn group barrier first.
5064
5065    If a predicate register is written by a floating-point insn, we set
5066    WRITTEN_BY_FP to true.
5067
5068    If a predicate register is written by an AND.ORCM we set WRITTEN_BY_AND
5069    to true; if it was written by an OR.ANDCM we set WRITTEN_BY_OR to true.  */
5070
5071 struct reg_write_state
5072 {
5073   unsigned int write_count : 2;
5074   unsigned int first_pred : 16;
5075   unsigned int written_by_fp : 1;
5076   unsigned int written_by_and : 1;
5077   unsigned int written_by_or : 1;
5078 };
5079
5080 /* Cumulative info for the current instruction group.  */
5081 struct reg_write_state rws_sum[NUM_REGS];
5082 /* Info for the current instruction.  This gets copied to rws_sum after a
5083    stop bit is emitted.  */
5084 struct reg_write_state rws_insn[NUM_REGS];
5085
5086 /* Indicates whether this is the first instruction after a stop bit,
5087    in which case we don't need another stop bit.  Without this,
5088    ia64_variable_issue will die when scheduling an alloc.  */
5089 static int first_instruction;
5090
5091 /* Misc flags needed to compute RAW/WAW dependencies while we are traversing
5092    RTL for one instruction.  */
5093 struct reg_flags
5094 {
5095   unsigned int is_write : 1;    /* Is register being written?  */
5096   unsigned int is_fp : 1;       /* Is register used as part of an fp op?  */
5097   unsigned int is_branch : 1;   /* Is register used as part of a branch?  */
5098   unsigned int is_and : 1;      /* Is register used as part of and.orcm?  */
5099   unsigned int is_or : 1;       /* Is register used as part of or.andcm?  */
5100   unsigned int is_sibcall : 1;  /* Is this a sibling or normal call?  */
5101 };
5102
5103 static void rws_update (struct reg_write_state *, int, struct reg_flags, int);
5104 static int rws_access_regno (int, struct reg_flags, int);
5105 static int rws_access_reg (rtx, struct reg_flags, int);
5106 static void update_set_flags (rtx, struct reg_flags *);
5107 static int set_src_needs_barrier (rtx, struct reg_flags, int);
5108 static int rtx_needs_barrier (rtx, struct reg_flags, int);
5109 static void init_insn_group_barriers (void);
5110 static int group_barrier_needed (rtx);
5111 static int safe_group_barrier_needed (rtx);
5112
5113 /* Update *RWS for REGNO, which is being written by the current instruction,
5114    with predicate PRED, and associated register flags in FLAGS.  */
5115
5116 static void
5117 rws_update (struct reg_write_state *rws, int regno, struct reg_flags flags, int pred)
5118 {
5119   if (pred)
5120     rws[regno].write_count++;
5121   else
5122     rws[regno].write_count = 2;
5123   rws[regno].written_by_fp |= flags.is_fp;
5124   /* ??? Not tracking and/or across differing predicates.  */
5125   rws[regno].written_by_and = flags.is_and;
5126   rws[regno].written_by_or = flags.is_or;
5127   rws[regno].first_pred = pred;
5128 }
5129
5130 /* Handle an access to register REGNO of type FLAGS using predicate register
5131    PRED.  Update rws_insn and rws_sum arrays.  Return 1 if this access creates
5132    a dependency with an earlier instruction in the same group.  */
5133
5134 static int
5135 rws_access_regno (int regno, struct reg_flags flags, int pred)
5136 {
5137   int need_barrier = 0;
5138
5139   gcc_assert (regno < NUM_REGS);
5140
5141   if (! PR_REGNO_P (regno))
5142     flags.is_and = flags.is_or = 0;
5143
5144   if (flags.is_write)
5145     {
5146       int write_count;
5147
5148       /* One insn writes same reg multiple times?  */
5149       gcc_assert (!rws_insn[regno].write_count);
5150
5151       /* Update info for current instruction.  */
5152       rws_update (rws_insn, regno, flags, pred);
5153       write_count = rws_sum[regno].write_count;
5154
5155       switch (write_count)
5156         {
5157         case 0:
5158           /* The register has not been written yet.  */
5159           rws_update (rws_sum, regno, flags, pred);
5160           break;
5161
5162         case 1:
5163           /* The register has been written via a predicate.  If this is
5164              not a complementary predicate, then we need a barrier.  */
5165           /* ??? This assumes that P and P+1 are always complementary
5166              predicates for P even.  */
5167           if (flags.is_and && rws_sum[regno].written_by_and)
5168             ;
5169           else if (flags.is_or && rws_sum[regno].written_by_or)
5170             ;
5171           else if ((rws_sum[regno].first_pred ^ 1) != pred)
5172             need_barrier = 1;
5173           rws_update (rws_sum, regno, flags, pred);
5174           break;
5175
5176         case 2:
5177           /* The register has been unconditionally written already.  We
5178              need a barrier.  */
5179           if (flags.is_and && rws_sum[regno].written_by_and)
5180             ;
5181           else if (flags.is_or && rws_sum[regno].written_by_or)
5182             ;
5183           else
5184             need_barrier = 1;
5185           rws_sum[regno].written_by_and = flags.is_and;
5186           rws_sum[regno].written_by_or = flags.is_or;
5187           break;
5188
5189         default:
5190           gcc_unreachable ();
5191         }
5192     }
5193   else
5194     {
5195       if (flags.is_branch)
5196         {
5197           /* Branches have several RAW exceptions that allow to avoid
5198              barriers.  */
5199
5200           if (REGNO_REG_CLASS (regno) == BR_REGS || regno == AR_PFS_REGNUM)
5201             /* RAW dependencies on branch regs are permissible as long
5202                as the writer is a non-branch instruction.  Since we
5203                never generate code that uses a branch register written
5204                by a branch instruction, handling this case is
5205                easy.  */
5206             return 0;
5207
5208           if (REGNO_REG_CLASS (regno) == PR_REGS
5209               && ! rws_sum[regno].written_by_fp)
5210             /* The predicates of a branch are available within the
5211                same insn group as long as the predicate was written by
5212                something other than a floating-point instruction.  */
5213             return 0;
5214         }
5215
5216       if (flags.is_and && rws_sum[regno].written_by_and)
5217         return 0;
5218       if (flags.is_or && rws_sum[regno].written_by_or)
5219         return 0;
5220
5221       switch (rws_sum[regno].write_count)
5222         {
5223         case 0:
5224           /* The register has not been written yet.  */
5225           break;
5226
5227         case 1:
5228           /* The register has been written via a predicate.  If this is
5229              not a complementary predicate, then we need a barrier.  */
5230           /* ??? This assumes that P and P+1 are always complementary
5231              predicates for P even.  */
5232           if ((rws_sum[regno].first_pred ^ 1) != pred)
5233             need_barrier = 1;
5234           break;
5235
5236         case 2:
5237           /* The register has been unconditionally written already.  We
5238              need a barrier.  */
5239           need_barrier = 1;
5240           break;
5241
5242         default:
5243           gcc_unreachable ();
5244         }
5245     }
5246
5247   return need_barrier;
5248 }
5249
5250 static int
5251 rws_access_reg (rtx reg, struct reg_flags flags, int pred)
5252 {
5253   int regno = REGNO (reg);
5254   int n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
5255
5256   if (n == 1)
5257     return rws_access_regno (regno, flags, pred);
5258   else
5259     {
5260       int need_barrier = 0;
5261       while (--n >= 0)
5262         need_barrier |= rws_access_regno (regno + n, flags, pred);
5263       return need_barrier;
5264     }
5265 }
5266
5267 /* Examine X, which is a SET rtx, and update the flags, the predicate, and
5268    the condition, stored in *PFLAGS, *PPRED and *PCOND.  */
5269
5270 static void
5271 update_set_flags (rtx x, struct reg_flags *pflags)
5272 {
5273   rtx src = SET_SRC (x);
5274
5275   switch (GET_CODE (src))
5276     {
5277     case CALL:
5278       return;
5279
5280     case IF_THEN_ELSE:
5281       /* There are three cases here:
5282          (1) The destination is (pc), in which case this is a branch,
5283          nothing here applies.
5284          (2) The destination is ar.lc, in which case this is a
5285          doloop_end_internal,
5286          (3) The destination is an fp register, in which case this is
5287          an fselect instruction.
5288          In all cases, nothing we do in this function applies.  */
5289       return;
5290
5291     default:
5292       if (COMPARISON_P (src)
5293           && SCALAR_FLOAT_MODE_P (GET_MODE (XEXP (src, 0))))
5294         /* Set pflags->is_fp to 1 so that we know we're dealing
5295            with a floating point comparison when processing the
5296            destination of the SET.  */
5297         pflags->is_fp = 1;
5298
5299       /* Discover if this is a parallel comparison.  We only handle
5300          and.orcm and or.andcm at present, since we must retain a
5301          strict inverse on the predicate pair.  */
5302       else if (GET_CODE (src) == AND)
5303         pflags->is_and = 1;
5304       else if (GET_CODE (src) == IOR)
5305         pflags->is_or = 1;
5306
5307       break;
5308     }
5309 }
5310
5311 /* Subroutine of rtx_needs_barrier; this function determines whether the
5312    source of a given SET rtx found in X needs a barrier.  FLAGS and PRED
5313    are as in rtx_needs_barrier.  COND is an rtx that holds the condition
5314    for this insn.  */
5315
5316 static int
5317 set_src_needs_barrier (rtx x, struct reg_flags flags, int pred)
5318 {
5319   int need_barrier = 0;
5320   rtx dst;
5321   rtx src = SET_SRC (x);
5322
5323   if (GET_CODE (src) == CALL)
5324     /* We don't need to worry about the result registers that
5325        get written by subroutine call.  */
5326     return rtx_needs_barrier (src, flags, pred);
5327   else if (SET_DEST (x) == pc_rtx)
5328     {
5329       /* X is a conditional branch.  */
5330       /* ??? This seems redundant, as the caller sets this bit for
5331          all JUMP_INSNs.  */
5332       flags.is_branch = 1;
5333       return rtx_needs_barrier (src, flags, pred);
5334     }
5335
5336   need_barrier = rtx_needs_barrier (src, flags, pred);
5337
5338   dst = SET_DEST (x);
5339   if (GET_CODE (dst) == ZERO_EXTRACT)
5340     {
5341       need_barrier |= rtx_needs_barrier (XEXP (dst, 1), flags, pred);
5342       need_barrier |= rtx_needs_barrier (XEXP (dst, 2), flags, pred);
5343       dst = XEXP (dst, 0);
5344     }
5345   return need_barrier;
5346 }
5347
5348 /* Handle an access to rtx X of type FLAGS using predicate register
5349    PRED.  Return 1 if this access creates a dependency with an earlier
5350    instruction in the same group.  */
5351
5352 static int
5353 rtx_needs_barrier (rtx x, struct reg_flags flags, int pred)
5354 {
5355   int i, j;
5356   int is_complemented = 0;
5357   int need_barrier = 0;
5358   const char *format_ptr;
5359   struct reg_flags new_flags;
5360   rtx cond;
5361
5362   if (! x)
5363     return 0;
5364
5365   new_flags = flags;
5366
5367   switch (GET_CODE (x))
5368     {
5369     case SET:
5370       update_set_flags (x, &new_flags);
5371       need_barrier = set_src_needs_barrier (x, new_flags, pred);
5372       if (GET_CODE (SET_SRC (x)) != CALL)
5373         {
5374           new_flags.is_write = 1;
5375           need_barrier |= rtx_needs_barrier (SET_DEST (x), new_flags, pred);
5376         }
5377       break;
5378
5379     case CALL:
5380       new_flags.is_write = 0;
5381       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
5382
5383       /* Avoid multiple register writes, in case this is a pattern with
5384          multiple CALL rtx.  This avoids a failure in rws_access_reg.  */
5385       if (! flags.is_sibcall && ! rws_insn[REG_AR_CFM].write_count)
5386         {
5387           new_flags.is_write = 1;
5388           need_barrier |= rws_access_regno (REG_RP, new_flags, pred);
5389           need_barrier |= rws_access_regno (AR_PFS_REGNUM, new_flags, pred);
5390           need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
5391         }
5392       break;
5393
5394     case COND_EXEC:
5395       /* X is a predicated instruction.  */
5396
5397       cond = COND_EXEC_TEST (x);
5398       gcc_assert (!pred);
5399       need_barrier = rtx_needs_barrier (cond, flags, 0);
5400
5401       if (GET_CODE (cond) == EQ)
5402         is_complemented = 1;
5403       cond = XEXP (cond, 0);
5404       gcc_assert (GET_CODE (cond) == REG
5405                   && REGNO_REG_CLASS (REGNO (cond)) == PR_REGS);
5406       pred = REGNO (cond);
5407       if (is_complemented)
5408         ++pred;
5409
5410       need_barrier |= rtx_needs_barrier (COND_EXEC_CODE (x), flags, pred);
5411       return need_barrier;
5412
5413     case CLOBBER:
5414     case USE:
5415       /* Clobber & use are for earlier compiler-phases only.  */
5416       break;
5417
5418     case ASM_OPERANDS:
5419     case ASM_INPUT:
5420       /* We always emit stop bits for traditional asms.  We emit stop bits
5421          for volatile extended asms if TARGET_VOL_ASM_STOP is true.  */
5422       if (GET_CODE (x) != ASM_OPERANDS
5423           || (MEM_VOLATILE_P (x) && TARGET_VOL_ASM_STOP))
5424         {
5425           /* Avoid writing the register multiple times if we have multiple
5426              asm outputs.  This avoids a failure in rws_access_reg.  */
5427           if (! rws_insn[REG_VOLATILE].write_count)
5428             {
5429               new_flags.is_write = 1;
5430               rws_access_regno (REG_VOLATILE, new_flags, pred);
5431             }
5432           return 1;
5433         }
5434
5435       /* For all ASM_OPERANDS, we must traverse the vector of input operands.
5436          We cannot just fall through here since then we would be confused
5437          by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
5438          traditional asms unlike their normal usage.  */
5439
5440       for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; --i)
5441         if (rtx_needs_barrier (ASM_OPERANDS_INPUT (x, i), flags, pred))
5442           need_barrier = 1;
5443       break;
5444
5445     case PARALLEL:
5446       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
5447         {
5448           rtx pat = XVECEXP (x, 0, i);
5449           switch (GET_CODE (pat))
5450             {
5451             case SET:
5452               update_set_flags (pat, &new_flags);
5453               need_barrier |= set_src_needs_barrier (pat, new_flags, pred);
5454               break;
5455
5456             case USE:
5457             case CALL:
5458             case ASM_OPERANDS:
5459               need_barrier |= rtx_needs_barrier (pat, flags, pred);
5460               break;
5461
5462             case CLOBBER:
5463             case RETURN:
5464               break;
5465
5466             default:
5467               gcc_unreachable ();
5468             }
5469         }
5470       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
5471         {
5472           rtx pat = XVECEXP (x, 0, i);
5473           if (GET_CODE (pat) == SET)
5474             {
5475               if (GET_CODE (SET_SRC (pat)) != CALL)
5476                 {
5477                   new_flags.is_write = 1;
5478                   need_barrier |= rtx_needs_barrier (SET_DEST (pat), new_flags,
5479                                                      pred);
5480                 }
5481             }
5482           else if (GET_CODE (pat) == CLOBBER || GET_CODE (pat) == RETURN)
5483             need_barrier |= rtx_needs_barrier (pat, flags, pred);
5484         }
5485       break;
5486
5487     case SUBREG:
5488       need_barrier |= rtx_needs_barrier (SUBREG_REG (x), flags, pred);
5489       break;
5490     case REG:
5491       if (REGNO (x) == AR_UNAT_REGNUM)
5492         {
5493           for (i = 0; i < 64; ++i)
5494             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + i, flags, pred);
5495         }
5496       else
5497         need_barrier = rws_access_reg (x, flags, pred);
5498       break;
5499
5500     case MEM:
5501       /* Find the regs used in memory address computation.  */
5502       new_flags.is_write = 0;
5503       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5504       break;
5505
5506     case CONST_INT:   case CONST_DOUBLE:  case CONST_VECTOR:
5507     case SYMBOL_REF:  case LABEL_REF:     case CONST:
5508       break;
5509
5510       /* Operators with side-effects.  */
5511     case POST_INC:    case POST_DEC:
5512       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
5513
5514       new_flags.is_write = 0;
5515       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5516       new_flags.is_write = 1;
5517       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5518       break;
5519
5520     case POST_MODIFY:
5521       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
5522
5523       new_flags.is_write = 0;
5524       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5525       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5526       new_flags.is_write = 1;
5527       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5528       break;
5529
5530       /* Handle common unary and binary ops for efficiency.  */
5531     case COMPARE:  case PLUS:    case MINUS:   case MULT:      case DIV:
5532     case MOD:      case UDIV:    case UMOD:    case AND:       case IOR:
5533     case XOR:      case ASHIFT:  case ROTATE:  case ASHIFTRT:  case LSHIFTRT:
5534     case ROTATERT: case SMIN:    case SMAX:    case UMIN:      case UMAX:
5535     case NE:       case EQ:      case GE:      case GT:        case LE:
5536     case LT:       case GEU:     case GTU:     case LEU:       case LTU:
5537       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5538       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5539       break;
5540
5541     case NEG:      case NOT:            case SIGN_EXTEND:     case ZERO_EXTEND:
5542     case TRUNCATE: case FLOAT_EXTEND:   case FLOAT_TRUNCATE:  case FLOAT:
5543     case FIX:      case UNSIGNED_FLOAT: case UNSIGNED_FIX:    case ABS:
5544     case SQRT:     case FFS:            case POPCOUNT:
5545       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
5546       break;
5547
5548     case VEC_SELECT:
5549       /* VEC_SELECT's second argument is a PARALLEL with integers that
5550          describe the elements selected.  On ia64, those integers are
5551          always constants.  Avoid walking the PARALLEL so that we don't
5552          get confused with "normal" parallels and then die.  */
5553       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
5554       break;
5555
5556     case UNSPEC:
5557       switch (XINT (x, 1))
5558         {
5559         case UNSPEC_LTOFF_DTPMOD:
5560         case UNSPEC_LTOFF_DTPREL:
5561         case UNSPEC_DTPREL:
5562         case UNSPEC_LTOFF_TPREL:
5563         case UNSPEC_TPREL:
5564         case UNSPEC_PRED_REL_MUTEX:
5565         case UNSPEC_PIC_CALL:
5566         case UNSPEC_MF:
5567         case UNSPEC_FETCHADD_ACQ:
5568         case UNSPEC_BSP_VALUE:
5569         case UNSPEC_FLUSHRS:
5570         case UNSPEC_BUNDLE_SELECTOR:
5571           break;
5572
5573         case UNSPEC_GR_SPILL:
5574         case UNSPEC_GR_RESTORE:
5575           {
5576             HOST_WIDE_INT offset = INTVAL (XVECEXP (x, 0, 1));
5577             HOST_WIDE_INT bit = (offset >> 3) & 63;
5578
5579             need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5580             new_flags.is_write = (XINT (x, 1) == UNSPEC_GR_SPILL);
5581             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + bit,
5582                                               new_flags, pred);
5583             break;
5584           }
5585
5586         case UNSPEC_FR_SPILL:
5587         case UNSPEC_FR_RESTORE:
5588         case UNSPEC_GETF_EXP:
5589         case UNSPEC_SETF_EXP:
5590         case UNSPEC_ADDP4:
5591         case UNSPEC_FR_SQRT_RECIP_APPROX:
5592           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5593           break;
5594
5595         case UNSPEC_FR_RECIP_APPROX:
5596         case UNSPEC_SHRP:
5597         case UNSPEC_COPYSIGN:
5598           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5599           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5600           break;
5601
5602         case UNSPEC_CMPXCHG_ACQ:
5603           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5604           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 2), flags, pred);
5605           break;
5606
5607         default:
5608           gcc_unreachable ();
5609         }
5610       break;
5611
5612     case UNSPEC_VOLATILE:
5613       switch (XINT (x, 1))
5614         {
5615         case UNSPECV_ALLOC:
5616           /* Alloc must always be the first instruction of a group.
5617              We force this by always returning true.  */
5618           /* ??? We might get better scheduling if we explicitly check for
5619              input/local/output register dependencies, and modify the
5620              scheduler so that alloc is always reordered to the start of
5621              the current group.  We could then eliminate all of the
5622              first_instruction code.  */
5623           rws_access_regno (AR_PFS_REGNUM, flags, pred);
5624
5625           new_flags.is_write = 1;
5626           rws_access_regno (REG_AR_CFM, new_flags, pred);
5627           return 1;
5628
5629         case UNSPECV_SET_BSP:
5630           need_barrier = 1;
5631           break;
5632
5633         case UNSPECV_BLOCKAGE:
5634         case UNSPECV_INSN_GROUP_BARRIER:
5635         case UNSPECV_BREAK:
5636         case UNSPECV_PSAC_ALL:
5637         case UNSPECV_PSAC_NORMAL:
5638           return 0;
5639
5640         default:
5641           gcc_unreachable ();
5642         }
5643       break;
5644
5645     case RETURN:
5646       new_flags.is_write = 0;
5647       need_barrier  = rws_access_regno (REG_RP, flags, pred);
5648       need_barrier |= rws_access_regno (AR_PFS_REGNUM, flags, pred);
5649
5650       new_flags.is_write = 1;
5651       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
5652       need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
5653       break;
5654
5655     default:
5656       format_ptr = GET_RTX_FORMAT (GET_CODE (x));
5657       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
5658         switch (format_ptr[i])
5659           {
5660           case '0':     /* unused field */
5661           case 'i':     /* integer */
5662           case 'n':     /* note */
5663           case 'w':     /* wide integer */
5664           case 's':     /* pointer to string */
5665           case 'S':     /* optional pointer to string */
5666             break;
5667
5668           case 'e':
5669             if (rtx_needs_barrier (XEXP (x, i), flags, pred))
5670               need_barrier = 1;
5671             break;
5672
5673           case 'E':
5674             for (j = XVECLEN (x, i) - 1; j >= 0; --j)
5675               if (rtx_needs_barrier (XVECEXP (x, i, j), flags, pred))
5676                 need_barrier = 1;
5677             break;
5678
5679           default:
5680             gcc_unreachable ();
5681           }
5682       break;
5683     }
5684   return need_barrier;
5685 }
5686
5687 /* Clear out the state for group_barrier_needed at the start of a
5688    sequence of insns.  */
5689
5690 static void
5691 init_insn_group_barriers (void)
5692 {
5693   memset (rws_sum, 0, sizeof (rws_sum));
5694   first_instruction = 1;
5695 }
5696
5697 /* Given the current state, determine whether a group barrier (a stop bit) is
5698    necessary before INSN.  Return nonzero if so.  This modifies the state to
5699    include the effects of INSN as a side-effect.  */
5700
5701 static int
5702 group_barrier_needed (rtx insn)
5703 {
5704   rtx pat;
5705   int need_barrier = 0;
5706   struct reg_flags flags;
5707
5708   memset (&flags, 0, sizeof (flags));
5709   switch (GET_CODE (insn))
5710     {
5711     case NOTE:
5712       break;
5713
5714     case BARRIER:
5715       /* A barrier doesn't imply an instruction group boundary.  */
5716       break;
5717
5718     case CODE_LABEL:
5719       memset (rws_insn, 0, sizeof (rws_insn));
5720       return 1;
5721
5722     case CALL_INSN:
5723       flags.is_branch = 1;
5724       flags.is_sibcall = SIBLING_CALL_P (insn);
5725       memset (rws_insn, 0, sizeof (rws_insn));
5726
5727       /* Don't bundle a call following another call.  */
5728       if ((pat = prev_active_insn (insn))
5729           && GET_CODE (pat) == CALL_INSN)
5730         {
5731           need_barrier = 1;
5732           break;
5733         }
5734
5735       need_barrier = rtx_needs_barrier (PATTERN (insn), flags, 0);
5736       break;
5737
5738     case JUMP_INSN:
5739       flags.is_branch = 1;
5740
5741       /* Don't bundle a jump following a call.  */
5742       if ((pat = prev_active_insn (insn))
5743           && GET_CODE (pat) == CALL_INSN)
5744         {
5745           need_barrier = 1;
5746           break;
5747         }
5748       /* FALLTHRU */
5749
5750     case INSN:
5751       if (GET_CODE (PATTERN (insn)) == USE
5752           || GET_CODE (PATTERN (insn)) == CLOBBER)
5753         /* Don't care about USE and CLOBBER "insns"---those are used to
5754            indicate to the optimizer that it shouldn't get rid of
5755            certain operations.  */
5756         break;
5757
5758       pat = PATTERN (insn);
5759
5760       /* Ug.  Hack hacks hacked elsewhere.  */
5761       switch (recog_memoized (insn))
5762         {
5763           /* We play dependency tricks with the epilogue in order
5764              to get proper schedules.  Undo this for dv analysis.  */
5765         case CODE_FOR_epilogue_deallocate_stack:
5766         case CODE_FOR_prologue_allocate_stack:
5767           pat = XVECEXP (pat, 0, 0);
5768           break;
5769
5770           /* The pattern we use for br.cloop confuses the code above.
5771              The second element of the vector is representative.  */
5772         case CODE_FOR_doloop_end_internal:
5773           pat = XVECEXP (pat, 0, 1);
5774           break;
5775
5776           /* Doesn't generate code.  */
5777         case CODE_FOR_pred_rel_mutex:
5778         case CODE_FOR_prologue_use:
5779           return 0;
5780
5781         default:
5782           break;
5783         }
5784
5785       memset (rws_insn, 0, sizeof (rws_insn));
5786       need_barrier = rtx_needs_barrier (pat, flags, 0);
5787
5788       /* Check to see if the previous instruction was a volatile
5789          asm.  */
5790       if (! need_barrier)
5791         need_barrier = rws_access_regno (REG_VOLATILE, flags, 0);
5792       break;
5793
5794     default:
5795       gcc_unreachable ();
5796     }
5797
5798   if (first_instruction && INSN_P (insn)
5799       && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
5800       && GET_CODE (PATTERN (insn)) != USE
5801       && GET_CODE (PATTERN (insn)) != CLOBBER)
5802     {
5803       need_barrier = 0;
5804       first_instruction = 0;
5805     }
5806
5807   return need_barrier;
5808 }
5809
5810 /* Like group_barrier_needed, but do not clobber the current state.  */
5811
5812 static int
5813 safe_group_barrier_needed (rtx insn)
5814 {
5815   struct reg_write_state rws_saved[NUM_REGS];
5816   int saved_first_instruction;
5817   int t;
5818
5819   memcpy (rws_saved, rws_sum, NUM_REGS * sizeof *rws_saved);
5820   saved_first_instruction = first_instruction;
5821
5822   t = group_barrier_needed (insn);
5823
5824   memcpy (rws_sum, rws_saved, NUM_REGS * sizeof *rws_saved);
5825   first_instruction = saved_first_instruction;
5826
5827   return t;
5828 }
5829
5830 /* Scan the current function and insert stop bits as necessary to
5831    eliminate dependencies.  This function assumes that a final
5832    instruction scheduling pass has been run which has already
5833    inserted most of the necessary stop bits.  This function only
5834    inserts new ones at basic block boundaries, since these are
5835    invisible to the scheduler.  */
5836
5837 static void
5838 emit_insn_group_barriers (FILE *dump)
5839 {
5840   rtx insn;
5841   rtx last_label = 0;
5842   int insns_since_last_label = 0;
5843
5844   init_insn_group_barriers ();
5845
5846   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5847     {
5848       if (GET_CODE (insn) == CODE_LABEL)
5849         {
5850           if (insns_since_last_label)
5851             last_label = insn;
5852           insns_since_last_label = 0;
5853         }
5854       else if (GET_CODE (insn) == NOTE
5855                && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
5856         {
5857           if (insns_since_last_label)
5858             last_label = insn;
5859           insns_since_last_label = 0;
5860         }
5861       else if (GET_CODE (insn) == INSN
5862                && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
5863                && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
5864         {
5865           init_insn_group_barriers ();
5866           last_label = 0;
5867         }
5868       else if (INSN_P (insn))
5869         {
5870           insns_since_last_label = 1;
5871
5872           if (group_barrier_needed (insn))
5873             {
5874               if (last_label)
5875                 {
5876                   if (dump)
5877                     fprintf (dump, "Emitting stop before label %d\n",
5878                              INSN_UID (last_label));
5879                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), last_label);
5880                   insn = last_label;
5881
5882                   init_insn_group_barriers ();
5883                   last_label = 0;
5884                 }
5885             }
5886         }
5887     }
5888 }
5889
5890 /* Like emit_insn_group_barriers, but run if no final scheduling pass was run.
5891    This function has to emit all necessary group barriers.  */
5892
5893 static void
5894 emit_all_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
5895 {
5896   rtx insn;
5897
5898   init_insn_group_barriers ();
5899
5900   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5901     {
5902       if (GET_CODE (insn) == BARRIER)
5903         {
5904           rtx last = prev_active_insn (insn);
5905
5906           if (! last)
5907             continue;
5908           if (GET_CODE (last) == JUMP_INSN
5909               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
5910             last = prev_active_insn (last);
5911           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
5912             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
5913
5914           init_insn_group_barriers ();
5915         }
5916       else if (INSN_P (insn))
5917         {
5918           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
5919             init_insn_group_barriers ();
5920           else if (group_barrier_needed (insn))
5921             {
5922               emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5923               init_insn_group_barriers ();
5924               group_barrier_needed (insn);
5925             }
5926         }
5927     }
5928 }
5929
5930 \f
5931
5932 /* Instruction scheduling support.  */
5933
5934 #define NR_BUNDLES 10
5935
5936 /* A list of names of all available bundles.  */
5937
5938 static const char *bundle_name [NR_BUNDLES] =
5939 {
5940   ".mii",
5941   ".mmi",
5942   ".mfi",
5943   ".mmf",
5944 #if NR_BUNDLES == 10
5945   ".bbb",
5946   ".mbb",
5947 #endif
5948   ".mib",
5949   ".mmb",
5950   ".mfb",
5951   ".mlx"
5952 };
5953
5954 /* Nonzero if we should insert stop bits into the schedule.  */
5955
5956 int ia64_final_schedule = 0;
5957
5958 /* Codes of the corresponding queried units: */
5959
5960 static int _0mii_, _0mmi_, _0mfi_, _0mmf_;
5961 static int _0bbb_, _0mbb_, _0mib_, _0mmb_, _0mfb_, _0mlx_;
5962
5963 static int _1mii_, _1mmi_, _1mfi_, _1mmf_;
5964 static int _1bbb_, _1mbb_, _1mib_, _1mmb_, _1mfb_, _1mlx_;
5965
5966 static int pos_1, pos_2, pos_3, pos_4, pos_5, pos_6;
5967
5968 /* The following variable value is an insn group barrier.  */
5969
5970 static rtx dfa_stop_insn;
5971
5972 /* The following variable value is the last issued insn.  */
5973
5974 static rtx last_scheduled_insn;
5975
5976 /* The following variable value is size of the DFA state.  */
5977
5978 static size_t dfa_state_size;
5979
5980 /* The following variable value is pointer to a DFA state used as
5981    temporary variable.  */
5982
5983 static state_t temp_dfa_state = NULL;
5984
5985 /* The following variable value is DFA state after issuing the last
5986    insn.  */
5987
5988 static state_t prev_cycle_state = NULL;
5989
5990 /* The following array element values are TRUE if the corresponding
5991    insn requires to add stop bits before it.  */
5992
5993 static char *stops_p;
5994
5995 /* The following variable is used to set up the mentioned above array.  */
5996
5997 static int stop_before_p = 0;
5998
5999 /* The following variable value is length of the arrays `clocks' and
6000    `add_cycles'. */
6001
6002 static int clocks_length;
6003
6004 /* The following array element values are cycles on which the
6005    corresponding insn will be issued.  The array is used only for
6006    Itanium1.  */
6007
6008 static int *clocks;
6009
6010 /* The following array element values are numbers of cycles should be
6011    added to improve insn scheduling for MM_insns for Itanium1.  */
6012
6013 static int *add_cycles;
6014
6015 static rtx ia64_single_set (rtx);
6016 static void ia64_emit_insn_before (rtx, rtx);
6017
6018 /* Map a bundle number to its pseudo-op.  */
6019
6020 const char *
6021 get_bundle_name (int b)
6022 {
6023   return bundle_name[b];
6024 }
6025
6026
6027 /* Return the maximum number of instructions a cpu can issue.  */
6028
6029 static int
6030 ia64_issue_rate (void)
6031 {
6032   return 6;
6033 }
6034
6035 /* Helper function - like single_set, but look inside COND_EXEC.  */
6036
6037 static rtx
6038 ia64_single_set (rtx insn)
6039 {
6040   rtx x = PATTERN (insn), ret;
6041   if (GET_CODE (x) == COND_EXEC)
6042     x = COND_EXEC_CODE (x);
6043   if (GET_CODE (x) == SET)
6044     return x;
6045
6046   /* Special case here prologue_allocate_stack and epilogue_deallocate_stack.
6047      Although they are not classical single set, the second set is there just
6048      to protect it from moving past FP-relative stack accesses.  */
6049   switch (recog_memoized (insn))
6050     {
6051     case CODE_FOR_prologue_allocate_stack:
6052     case CODE_FOR_epilogue_deallocate_stack:
6053       ret = XVECEXP (x, 0, 0);
6054       break;
6055
6056     default:
6057       ret = single_set_2 (insn, x);
6058       break;
6059     }
6060
6061   return ret;
6062 }
6063
6064 /* Adjust the cost of a scheduling dependency.  Return the new cost of
6065    a dependency LINK or INSN on DEP_INSN.  COST is the current cost.  */
6066
6067 static int
6068 ia64_adjust_cost (rtx insn, rtx link, rtx dep_insn, int cost)
6069 {
6070   enum attr_itanium_class dep_class;
6071   enum attr_itanium_class insn_class;
6072
6073   if (REG_NOTE_KIND (link) != REG_DEP_OUTPUT)
6074     return cost;
6075
6076   insn_class = ia64_safe_itanium_class (insn);
6077   dep_class = ia64_safe_itanium_class (dep_insn);
6078   if (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF
6079       || insn_class == ITANIUM_CLASS_ST || insn_class == ITANIUM_CLASS_STF)
6080     return 0;
6081
6082   return cost;
6083 }
6084
6085 /* Like emit_insn_before, but skip cycle_display notes.
6086    ??? When cycle display notes are implemented, update this.  */
6087
6088 static void
6089 ia64_emit_insn_before (rtx insn, rtx before)
6090 {
6091   emit_insn_before (insn, before);
6092 }
6093
6094 /* The following function marks insns who produce addresses for load
6095    and store insns.  Such insns will be placed into M slots because it
6096    decrease latency time for Itanium1 (see function
6097    `ia64_produce_address_p' and the DFA descriptions).  */
6098
6099 static void
6100 ia64_dependencies_evaluation_hook (rtx head, rtx tail)
6101 {
6102   rtx insn, link, next, next_tail;
6103
6104   /* Before reload, which_alternative is not set, which means that
6105      ia64_safe_itanium_class will produce wrong results for (at least)
6106      move instructions.  */
6107   if (!reload_completed)
6108     return;
6109
6110   next_tail = NEXT_INSN (tail);
6111   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6112     if (INSN_P (insn))
6113       insn->call = 0;
6114   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6115     if (INSN_P (insn)
6116         && ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IALU)
6117       {
6118         for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
6119           {
6120             if (REG_NOTE_KIND (link) != REG_DEP_TRUE)
6121               continue;
6122             next = XEXP (link, 0);
6123             if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_ST
6124                  || ia64_safe_itanium_class (next) == ITANIUM_CLASS_STF)
6125                 && ia64_st_address_bypass_p (insn, next))
6126               break;
6127             else if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_LD
6128                       || ia64_safe_itanium_class (next)
6129                       == ITANIUM_CLASS_FLD)
6130                      && ia64_ld_address_bypass_p (insn, next))
6131               break;
6132           }
6133         insn->call = link != 0;
6134       }
6135 }
6136
6137 /* We're beginning a new block.  Initialize data structures as necessary.  */
6138
6139 static void
6140 ia64_sched_init (FILE *dump ATTRIBUTE_UNUSED,
6141                  int sched_verbose ATTRIBUTE_UNUSED,
6142                  int max_ready ATTRIBUTE_UNUSED)
6143 {
6144 #ifdef ENABLE_CHECKING
6145   rtx insn;
6146
6147   if (reload_completed)
6148     for (insn = NEXT_INSN (current_sched_info->prev_head);
6149          insn != current_sched_info->next_tail;
6150          insn = NEXT_INSN (insn))
6151       gcc_assert (!SCHED_GROUP_P (insn));
6152 #endif
6153   last_scheduled_insn = NULL_RTX;
6154   init_insn_group_barriers ();
6155 }
6156
6157 /* We are about to being issuing insns for this clock cycle.
6158    Override the default sort algorithm to better slot instructions.  */
6159
6160 static int
6161 ia64_dfa_sched_reorder (FILE *dump, int sched_verbose, rtx *ready,
6162                         int *pn_ready, int clock_var ATTRIBUTE_UNUSED,
6163                         int reorder_type)
6164 {
6165   int n_asms;
6166   int n_ready = *pn_ready;
6167   rtx *e_ready = ready + n_ready;
6168   rtx *insnp;
6169
6170   if (sched_verbose)
6171     fprintf (dump, "// ia64_dfa_sched_reorder (type %d):\n", reorder_type);
6172
6173   if (reorder_type == 0)
6174     {
6175       /* First, move all USEs, CLOBBERs and other crud out of the way.  */
6176       n_asms = 0;
6177       for (insnp = ready; insnp < e_ready; insnp++)
6178         if (insnp < e_ready)
6179           {
6180             rtx insn = *insnp;
6181             enum attr_type t = ia64_safe_type (insn);
6182             if (t == TYPE_UNKNOWN)
6183               {
6184                 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6185                     || asm_noperands (PATTERN (insn)) >= 0)
6186                   {
6187                     rtx lowest = ready[n_asms];
6188                     ready[n_asms] = insn;
6189                     *insnp = lowest;
6190                     n_asms++;
6191                   }
6192                 else
6193                   {
6194                     rtx highest = ready[n_ready - 1];
6195                     ready[n_ready - 1] = insn;
6196                     *insnp = highest;
6197                     return 1;
6198                   }
6199               }
6200           }
6201
6202       if (n_asms < n_ready)
6203         {
6204           /* Some normal insns to process.  Skip the asms.  */
6205           ready += n_asms;
6206           n_ready -= n_asms;
6207         }
6208       else if (n_ready > 0)
6209         return 1;
6210     }
6211
6212   if (ia64_final_schedule)
6213     {
6214       int deleted = 0;
6215       int nr_need_stop = 0;
6216
6217       for (insnp = ready; insnp < e_ready; insnp++)
6218         if (safe_group_barrier_needed (*insnp))
6219           nr_need_stop++;
6220
6221       if (reorder_type == 1 && n_ready == nr_need_stop)
6222         return 0;
6223       if (reorder_type == 0)
6224         return 1;
6225       insnp = e_ready;
6226       /* Move down everything that needs a stop bit, preserving
6227          relative order.  */
6228       while (insnp-- > ready + deleted)
6229         while (insnp >= ready + deleted)
6230           {
6231             rtx insn = *insnp;
6232             if (! safe_group_barrier_needed (insn))
6233               break;
6234             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
6235             *ready = insn;
6236             deleted++;
6237           }
6238       n_ready -= deleted;
6239       ready += deleted;
6240     }
6241
6242   return 1;
6243 }
6244
6245 /* We are about to being issuing insns for this clock cycle.  Override
6246    the default sort algorithm to better slot instructions.  */
6247
6248 static int
6249 ia64_sched_reorder (FILE *dump, int sched_verbose, rtx *ready, int *pn_ready,
6250                     int clock_var)
6251 {
6252   return ia64_dfa_sched_reorder (dump, sched_verbose, ready,
6253                                  pn_ready, clock_var, 0);
6254 }
6255
6256 /* Like ia64_sched_reorder, but called after issuing each insn.
6257    Override the default sort algorithm to better slot instructions.  */
6258
6259 static int
6260 ia64_sched_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
6261                      int sched_verbose ATTRIBUTE_UNUSED, rtx *ready,
6262                      int *pn_ready, int clock_var)
6263 {
6264   if (ia64_tune == PROCESSOR_ITANIUM && reload_completed && last_scheduled_insn)
6265     clocks [INSN_UID (last_scheduled_insn)] = clock_var;
6266   return ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
6267                                  clock_var, 1);
6268 }
6269
6270 /* We are about to issue INSN.  Return the number of insns left on the
6271    ready queue that can be issued this cycle.  */
6272
6273 static int
6274 ia64_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
6275                      int sched_verbose ATTRIBUTE_UNUSED,
6276                      rtx insn ATTRIBUTE_UNUSED,
6277                      int can_issue_more ATTRIBUTE_UNUSED)
6278 {
6279   last_scheduled_insn = insn;
6280   memcpy (prev_cycle_state, curr_state, dfa_state_size);
6281   if (reload_completed)
6282     {
6283       int needed = group_barrier_needed (insn);
6284       
6285       gcc_assert (!needed);
6286       if (GET_CODE (insn) == CALL_INSN)
6287         init_insn_group_barriers ();
6288       stops_p [INSN_UID (insn)] = stop_before_p;
6289       stop_before_p = 0;
6290     }
6291   return 1;
6292 }
6293
6294 /* We are choosing insn from the ready queue.  Return nonzero if INSN
6295    can be chosen.  */
6296
6297 static int
6298 ia64_first_cycle_multipass_dfa_lookahead_guard (rtx insn)
6299 {
6300   gcc_assert (insn  && INSN_P (insn));
6301   return (!reload_completed
6302           || !safe_group_barrier_needed (insn));
6303 }
6304
6305 /* The following variable value is pseudo-insn used by the DFA insn
6306    scheduler to change the DFA state when the simulated clock is
6307    increased.  */
6308
6309 static rtx dfa_pre_cycle_insn;
6310
6311 /* We are about to being issuing INSN.  Return nonzero if we cannot
6312    issue it on given cycle CLOCK and return zero if we should not sort
6313    the ready queue on the next clock start.  */
6314
6315 static int
6316 ia64_dfa_new_cycle (FILE *dump, int verbose, rtx insn, int last_clock,
6317                     int clock, int *sort_p)
6318 {
6319   int setup_clocks_p = FALSE;
6320
6321   gcc_assert (insn && INSN_P (insn));
6322   if ((reload_completed && safe_group_barrier_needed (insn))
6323       || (last_scheduled_insn
6324           && (GET_CODE (last_scheduled_insn) == CALL_INSN
6325               || GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
6326               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)))
6327     {
6328       init_insn_group_barriers ();
6329       if (verbose && dump)
6330         fprintf (dump, "//    Stop should be before %d%s\n", INSN_UID (insn),
6331                  last_clock == clock ? " + cycle advance" : "");
6332       stop_before_p = 1;
6333       if (last_clock == clock)
6334         {
6335           state_transition (curr_state, dfa_stop_insn);
6336           if (TARGET_EARLY_STOP_BITS)
6337             *sort_p = (last_scheduled_insn == NULL_RTX
6338                        || GET_CODE (last_scheduled_insn) != CALL_INSN);
6339           else
6340             *sort_p = 0;
6341           return 1;
6342         }
6343       else if (reload_completed)
6344         setup_clocks_p = TRUE;
6345       if (GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
6346           || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)
6347         state_reset (curr_state);
6348       else
6349         {
6350           memcpy (curr_state, prev_cycle_state, dfa_state_size);
6351           state_transition (curr_state, dfa_stop_insn);
6352           state_transition (curr_state, dfa_pre_cycle_insn);
6353           state_transition (curr_state, NULL);
6354         }
6355     }
6356   else if (reload_completed)
6357     setup_clocks_p = TRUE;
6358   if (setup_clocks_p && ia64_tune == PROCESSOR_ITANIUM
6359       && GET_CODE (PATTERN (insn)) != ASM_INPUT
6360       && asm_noperands (PATTERN (insn)) < 0)
6361     {
6362       enum attr_itanium_class c = ia64_safe_itanium_class (insn);
6363
6364       if (c != ITANIUM_CLASS_MMMUL && c != ITANIUM_CLASS_MMSHF)
6365         {
6366           rtx link;
6367           int d = -1;
6368
6369           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
6370             if (REG_NOTE_KIND (link) == 0)
6371               {
6372                 enum attr_itanium_class dep_class;
6373                 rtx dep_insn = XEXP (link, 0);
6374
6375                 dep_class = ia64_safe_itanium_class (dep_insn);
6376                 if ((dep_class == ITANIUM_CLASS_MMMUL
6377                      || dep_class == ITANIUM_CLASS_MMSHF)
6378                     && last_clock - clocks [INSN_UID (dep_insn)] < 4
6379                     && (d < 0
6380                         || last_clock - clocks [INSN_UID (dep_insn)] < d))
6381                   d = last_clock - clocks [INSN_UID (dep_insn)];
6382               }
6383           if (d >= 0)
6384             add_cycles [INSN_UID (insn)] = 3 - d;
6385         }
6386     }
6387   return 0;
6388 }
6389
6390 \f
6391
6392 /* The following page contains abstract data `bundle states' which are
6393    used for bundling insns (inserting nops and template generation).  */
6394
6395 /* The following describes state of insn bundling.  */
6396
6397 struct bundle_state
6398 {
6399   /* Unique bundle state number to identify them in the debugging
6400      output  */
6401   int unique_num;
6402   rtx insn;     /* corresponding insn, NULL for the 1st and the last state  */
6403   /* number nops before and after the insn  */
6404   short before_nops_num, after_nops_num;
6405   int insn_num; /* insn number (0 - for initial state, 1 - for the 1st
6406                    insn */
6407   int cost;     /* cost of the state in cycles */
6408   int accumulated_insns_num; /* number of all previous insns including
6409                                 nops.  L is considered as 2 insns */
6410   int branch_deviation; /* deviation of previous branches from 3rd slots  */
6411   struct bundle_state *next;  /* next state with the same insn_num  */
6412   struct bundle_state *originator; /* originator (previous insn state)  */
6413   /* All bundle states are in the following chain.  */
6414   struct bundle_state *allocated_states_chain;
6415   /* The DFA State after issuing the insn and the nops.  */
6416   state_t dfa_state;
6417 };
6418
6419 /* The following is map insn number to the corresponding bundle state.  */
6420
6421 static struct bundle_state **index_to_bundle_states;
6422
6423 /* The unique number of next bundle state.  */
6424
6425 static int bundle_states_num;
6426
6427 /* All allocated bundle states are in the following chain.  */
6428
6429 static struct bundle_state *allocated_bundle_states_chain;
6430
6431 /* All allocated but not used bundle states are in the following
6432    chain.  */
6433
6434 static struct bundle_state *free_bundle_state_chain;
6435
6436
6437 /* The following function returns a free bundle state.  */
6438
6439 static struct bundle_state *
6440 get_free_bundle_state (void)
6441 {
6442   struct bundle_state *result;
6443
6444   if (free_bundle_state_chain != NULL)
6445     {
6446       result = free_bundle_state_chain;
6447       free_bundle_state_chain = result->next;
6448     }
6449   else
6450     {
6451       result = xmalloc (sizeof (struct bundle_state));
6452       result->dfa_state = xmalloc (dfa_state_size);
6453       result->allocated_states_chain = allocated_bundle_states_chain;
6454       allocated_bundle_states_chain = result;
6455     }
6456   result->unique_num = bundle_states_num++;
6457   return result;
6458
6459 }
6460
6461 /* The following function frees given bundle state.  */
6462
6463 static void
6464 free_bundle_state (struct bundle_state *state)
6465 {
6466   state->next = free_bundle_state_chain;
6467   free_bundle_state_chain = state;
6468 }
6469
6470 /* Start work with abstract data `bundle states'.  */
6471
6472 static void
6473 initiate_bundle_states (void)
6474 {
6475   bundle_states_num = 0;
6476   free_bundle_state_chain = NULL;
6477   allocated_bundle_states_chain = NULL;
6478 }
6479
6480 /* Finish work with abstract data `bundle states'.  */
6481
6482 static void
6483 finish_bundle_states (void)
6484 {
6485   struct bundle_state *curr_state, *next_state;
6486
6487   for (curr_state = allocated_bundle_states_chain;
6488        curr_state != NULL;
6489        curr_state = next_state)
6490     {
6491       next_state = curr_state->allocated_states_chain;
6492       free (curr_state->dfa_state);
6493       free (curr_state);
6494     }
6495 }
6496
6497 /* Hash table of the bundle states.  The key is dfa_state and insn_num
6498    of the bundle states.  */
6499
6500 static htab_t bundle_state_table;
6501
6502 /* The function returns hash of BUNDLE_STATE.  */
6503
6504 static unsigned
6505 bundle_state_hash (const void *bundle_state)
6506 {
6507   const struct bundle_state *state = (struct bundle_state *) bundle_state;
6508   unsigned result, i;
6509
6510   for (result = i = 0; i < dfa_state_size; i++)
6511     result += (((unsigned char *) state->dfa_state) [i]
6512                << ((i % CHAR_BIT) * 3 + CHAR_BIT));
6513   return result + state->insn_num;
6514 }
6515
6516 /* The function returns nonzero if the bundle state keys are equal.  */
6517
6518 static int
6519 bundle_state_eq_p (const void *bundle_state_1, const void *bundle_state_2)
6520 {
6521   const struct bundle_state * state1 = (struct bundle_state *) bundle_state_1;
6522   const struct bundle_state * state2 = (struct bundle_state *) bundle_state_2;
6523
6524   return (state1->insn_num == state2->insn_num
6525           && memcmp (state1->dfa_state, state2->dfa_state,
6526                      dfa_state_size) == 0);
6527 }
6528
6529 /* The function inserts the BUNDLE_STATE into the hash table.  The
6530    function returns nonzero if the bundle has been inserted into the
6531    table.  The table contains the best bundle state with given key.  */
6532
6533 static int
6534 insert_bundle_state (struct bundle_state *bundle_state)
6535 {
6536   void **entry_ptr;
6537
6538   entry_ptr = htab_find_slot (bundle_state_table, bundle_state, 1);
6539   if (*entry_ptr == NULL)
6540     {
6541       bundle_state->next = index_to_bundle_states [bundle_state->insn_num];
6542       index_to_bundle_states [bundle_state->insn_num] = bundle_state;
6543       *entry_ptr = (void *) bundle_state;
6544       return TRUE;
6545     }
6546   else if (bundle_state->cost < ((struct bundle_state *) *entry_ptr)->cost
6547            || (bundle_state->cost == ((struct bundle_state *) *entry_ptr)->cost
6548                && (((struct bundle_state *)*entry_ptr)->accumulated_insns_num
6549                    > bundle_state->accumulated_insns_num
6550                    || (((struct bundle_state *)
6551                         *entry_ptr)->accumulated_insns_num
6552                        == bundle_state->accumulated_insns_num
6553                        && ((struct bundle_state *)
6554                            *entry_ptr)->branch_deviation
6555                        > bundle_state->branch_deviation))))
6556
6557     {
6558       struct bundle_state temp;
6559
6560       temp = *(struct bundle_state *) *entry_ptr;
6561       *(struct bundle_state *) *entry_ptr = *bundle_state;
6562       ((struct bundle_state *) *entry_ptr)->next = temp.next;
6563       *bundle_state = temp;
6564     }
6565   return FALSE;
6566 }
6567
6568 /* Start work with the hash table.  */
6569
6570 static void
6571 initiate_bundle_state_table (void)
6572 {
6573   bundle_state_table = htab_create (50, bundle_state_hash, bundle_state_eq_p,
6574                                     (htab_del) 0);
6575 }
6576
6577 /* Finish work with the hash table.  */
6578
6579 static void
6580 finish_bundle_state_table (void)
6581 {
6582   htab_delete (bundle_state_table);
6583 }
6584
6585 \f
6586
6587 /* The following variable is a insn `nop' used to check bundle states
6588    with different number of inserted nops.  */
6589
6590 static rtx ia64_nop;
6591
6592 /* The following function tries to issue NOPS_NUM nops for the current
6593    state without advancing processor cycle.  If it failed, the
6594    function returns FALSE and frees the current state.  */
6595
6596 static int
6597 try_issue_nops (struct bundle_state *curr_state, int nops_num)
6598 {
6599   int i;
6600
6601   for (i = 0; i < nops_num; i++)
6602     if (state_transition (curr_state->dfa_state, ia64_nop) >= 0)
6603       {
6604         free_bundle_state (curr_state);
6605         return FALSE;
6606       }
6607   return TRUE;
6608 }
6609
6610 /* The following function tries to issue INSN for the current
6611    state without advancing processor cycle.  If it failed, the
6612    function returns FALSE and frees the current state.  */
6613
6614 static int
6615 try_issue_insn (struct bundle_state *curr_state, rtx insn)
6616 {
6617   if (insn && state_transition (curr_state->dfa_state, insn) >= 0)
6618     {
6619       free_bundle_state (curr_state);
6620       return FALSE;
6621     }
6622   return TRUE;
6623 }
6624
6625 /* The following function tries to issue BEFORE_NOPS_NUM nops and INSN
6626    starting with ORIGINATOR without advancing processor cycle.  If
6627    TRY_BUNDLE_END_P is TRUE, the function also/only (if
6628    ONLY_BUNDLE_END_P is TRUE) tries to issue nops to fill all bundle.
6629    If it was successful, the function creates new bundle state and
6630    insert into the hash table and into `index_to_bundle_states'.  */
6631
6632 static void
6633 issue_nops_and_insn (struct bundle_state *originator, int before_nops_num,
6634                      rtx insn, int try_bundle_end_p, int only_bundle_end_p)
6635 {
6636   struct bundle_state *curr_state;
6637
6638   curr_state = get_free_bundle_state ();
6639   memcpy (curr_state->dfa_state, originator->dfa_state, dfa_state_size);
6640   curr_state->insn = insn;
6641   curr_state->insn_num = originator->insn_num + 1;
6642   curr_state->cost = originator->cost;
6643   curr_state->originator = originator;
6644   curr_state->before_nops_num = before_nops_num;
6645   curr_state->after_nops_num = 0;
6646   curr_state->accumulated_insns_num
6647     = originator->accumulated_insns_num + before_nops_num;
6648   curr_state->branch_deviation = originator->branch_deviation;
6649   gcc_assert (insn);
6650   if (INSN_CODE (insn) == CODE_FOR_insn_group_barrier)
6651     {
6652       gcc_assert (GET_MODE (insn) != TImode);
6653       if (!try_issue_nops (curr_state, before_nops_num))
6654         return;
6655       if (!try_issue_insn (curr_state, insn))
6656         return;
6657       memcpy (temp_dfa_state, curr_state->dfa_state, dfa_state_size);
6658       if (state_transition (temp_dfa_state, dfa_pre_cycle_insn) >= 0
6659           && curr_state->accumulated_insns_num % 3 != 0)
6660         {
6661           free_bundle_state (curr_state);
6662           return;
6663         }
6664     }
6665   else if (GET_MODE (insn) != TImode)
6666     {
6667       if (!try_issue_nops (curr_state, before_nops_num))
6668         return;
6669       if (!try_issue_insn (curr_state, insn))
6670         return;
6671       curr_state->accumulated_insns_num++;
6672       gcc_assert (GET_CODE (PATTERN (insn)) != ASM_INPUT
6673                   && asm_noperands (PATTERN (insn)) < 0);
6674
6675       if (ia64_safe_type (insn) == TYPE_L)
6676         curr_state->accumulated_insns_num++;
6677     }
6678   else
6679     {
6680       /* If this is an insn that must be first in a group, then don't allow
6681          nops to be emitted before it.  Currently, alloc is the only such
6682          supported instruction.  */
6683       /* ??? The bundling automatons should handle this for us, but they do
6684          not yet have support for the first_insn attribute.  */
6685       if (before_nops_num > 0 && get_attr_first_insn (insn) == FIRST_INSN_YES)
6686         {
6687           free_bundle_state (curr_state);
6688           return;
6689         }
6690
6691       state_transition (curr_state->dfa_state, dfa_pre_cycle_insn);
6692       state_transition (curr_state->dfa_state, NULL);
6693       curr_state->cost++;
6694       if (!try_issue_nops (curr_state, before_nops_num))
6695         return;
6696       if (!try_issue_insn (curr_state, insn))
6697         return;
6698       curr_state->accumulated_insns_num++;
6699       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6700           || asm_noperands (PATTERN (insn)) >= 0)
6701         {
6702           /* Finish bundle containing asm insn.  */
6703           curr_state->after_nops_num
6704             = 3 - curr_state->accumulated_insns_num % 3;
6705           curr_state->accumulated_insns_num
6706             += 3 - curr_state->accumulated_insns_num % 3;
6707         }
6708       else if (ia64_safe_type (insn) == TYPE_L)
6709         curr_state->accumulated_insns_num++;
6710     }
6711   if (ia64_safe_type (insn) == TYPE_B)
6712     curr_state->branch_deviation
6713       += 2 - (curr_state->accumulated_insns_num - 1) % 3;
6714   if (try_bundle_end_p && curr_state->accumulated_insns_num % 3 != 0)
6715     {
6716       if (!only_bundle_end_p && insert_bundle_state (curr_state))
6717         {
6718           state_t dfa_state;
6719           struct bundle_state *curr_state1;
6720           struct bundle_state *allocated_states_chain;
6721
6722           curr_state1 = get_free_bundle_state ();
6723           dfa_state = curr_state1->dfa_state;
6724           allocated_states_chain = curr_state1->allocated_states_chain;
6725           *curr_state1 = *curr_state;
6726           curr_state1->dfa_state = dfa_state;
6727           curr_state1->allocated_states_chain = allocated_states_chain;
6728           memcpy (curr_state1->dfa_state, curr_state->dfa_state,
6729                   dfa_state_size);
6730           curr_state = curr_state1;
6731         }
6732       if (!try_issue_nops (curr_state,
6733                            3 - curr_state->accumulated_insns_num % 3))
6734         return;
6735       curr_state->after_nops_num
6736         = 3 - curr_state->accumulated_insns_num % 3;
6737       curr_state->accumulated_insns_num
6738         += 3 - curr_state->accumulated_insns_num % 3;
6739     }
6740   if (!insert_bundle_state (curr_state))
6741     free_bundle_state (curr_state);
6742   return;
6743 }
6744
6745 /* The following function returns position in the two window bundle
6746    for given STATE.  */
6747
6748 static int
6749 get_max_pos (state_t state)
6750 {
6751   if (cpu_unit_reservation_p (state, pos_6))
6752     return 6;
6753   else if (cpu_unit_reservation_p (state, pos_5))
6754     return 5;
6755   else if (cpu_unit_reservation_p (state, pos_4))
6756     return 4;
6757   else if (cpu_unit_reservation_p (state, pos_3))
6758     return 3;
6759   else if (cpu_unit_reservation_p (state, pos_2))
6760     return 2;
6761   else if (cpu_unit_reservation_p (state, pos_1))
6762     return 1;
6763   else
6764     return 0;
6765 }
6766
6767 /* The function returns code of a possible template for given position
6768    and state.  The function should be called only with 2 values of
6769    position equal to 3 or 6.  We avoid generating F NOPs by putting
6770    templates containing F insns at the end of the template search
6771    because undocumented anomaly in McKinley derived cores which can
6772    cause stalls if an F-unit insn (including a NOP) is issued within a
6773    six-cycle window after reading certain application registers (such
6774    as ar.bsp).  Furthermore, power-considerations also argue against
6775    the use of F-unit instructions unless they're really needed.  */
6776
6777 static int
6778 get_template (state_t state, int pos)
6779 {
6780   switch (pos)
6781     {
6782     case 3:
6783       if (cpu_unit_reservation_p (state, _0mmi_))
6784         return 1;
6785       else if (cpu_unit_reservation_p (state, _0mii_))
6786         return 0;
6787       else if (cpu_unit_reservation_p (state, _0mmb_))
6788         return 7;
6789       else if (cpu_unit_reservation_p (state, _0mib_))
6790         return 6;
6791       else if (cpu_unit_reservation_p (state, _0mbb_))
6792         return 5;
6793       else if (cpu_unit_reservation_p (state, _0bbb_))
6794         return 4;
6795       else if (cpu_unit_reservation_p (state, _0mmf_))
6796         return 3;
6797       else if (cpu_unit_reservation_p (state, _0mfi_))
6798         return 2;
6799       else if (cpu_unit_reservation_p (state, _0mfb_))
6800         return 8;
6801       else if (cpu_unit_reservation_p (state, _0mlx_))
6802         return 9;
6803       else
6804         gcc_unreachable ();
6805     case 6:
6806       if (cpu_unit_reservation_p (state, _1mmi_))
6807         return 1;
6808       else if (cpu_unit_reservation_p (state, _1mii_))
6809         return 0;
6810       else if (cpu_unit_reservation_p (state, _1mmb_))
6811         return 7;
6812       else if (cpu_unit_reservation_p (state, _1mib_))
6813         return 6;
6814       else if (cpu_unit_reservation_p (state, _1mbb_))
6815         return 5;
6816       else if (cpu_unit_reservation_p (state, _1bbb_))
6817         return 4;
6818       else if (_1mmf_ >= 0 && cpu_unit_reservation_p (state, _1mmf_))
6819         return 3;
6820       else if (cpu_unit_reservation_p (state, _1mfi_))
6821         return 2;
6822       else if (cpu_unit_reservation_p (state, _1mfb_))
6823         return 8;
6824       else if (cpu_unit_reservation_p (state, _1mlx_))
6825         return 9;
6826       else
6827         gcc_unreachable ();
6828     default:
6829       gcc_unreachable ();
6830     }
6831 }
6832
6833 /* The following function returns an insn important for insn bundling
6834    followed by INSN and before TAIL.  */
6835
6836 static rtx
6837 get_next_important_insn (rtx insn, rtx tail)
6838 {
6839   for (; insn && insn != tail; insn = NEXT_INSN (insn))
6840     if (INSN_P (insn)
6841         && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6842         && GET_CODE (PATTERN (insn)) != USE
6843         && GET_CODE (PATTERN (insn)) != CLOBBER)
6844       return insn;
6845   return NULL_RTX;
6846 }
6847
6848 /* The following function does insn bundling.  Bundling means
6849    inserting templates and nop insns to fit insn groups into permitted
6850    templates.  Instruction scheduling uses NDFA (non-deterministic
6851    finite automata) encoding informations about the templates and the
6852    inserted nops.  Nondeterminism of the automata permits follows
6853    all possible insn sequences very fast.
6854
6855    Unfortunately it is not possible to get information about inserting
6856    nop insns and used templates from the automata states.  The
6857    automata only says that we can issue an insn possibly inserting
6858    some nops before it and using some template.  Therefore insn
6859    bundling in this function is implemented by using DFA
6860    (deterministic finite automata).  We follows all possible insn
6861    sequences by inserting 0-2 nops (that is what the NDFA describe for
6862    insn scheduling) before/after each insn being bundled.  We know the
6863    start of simulated processor cycle from insn scheduling (insn
6864    starting a new cycle has TImode).
6865
6866    Simple implementation of insn bundling would create enormous
6867    number of possible insn sequences satisfying information about new
6868    cycle ticks taken from the insn scheduling.  To make the algorithm
6869    practical we use dynamic programming.  Each decision (about
6870    inserting nops and implicitly about previous decisions) is described
6871    by structure bundle_state (see above).  If we generate the same
6872    bundle state (key is automaton state after issuing the insns and
6873    nops for it), we reuse already generated one.  As consequence we
6874    reject some decisions which cannot improve the solution and
6875    reduce memory for the algorithm.
6876
6877    When we reach the end of EBB (extended basic block), we choose the
6878    best sequence and then, moving back in EBB, insert templates for
6879    the best alternative.  The templates are taken from querying
6880    automaton state for each insn in chosen bundle states.
6881
6882    So the algorithm makes two (forward and backward) passes through
6883    EBB.  There is an additional forward pass through EBB for Itanium1
6884    processor.  This pass inserts more nops to make dependency between
6885    a producer insn and MMMUL/MMSHF at least 4 cycles long.  */
6886
6887 static void
6888 bundling (FILE *dump, int verbose, rtx prev_head_insn, rtx tail)
6889 {
6890   struct bundle_state *curr_state, *next_state, *best_state;
6891   rtx insn, next_insn;
6892   int insn_num;
6893   int i, bundle_end_p, only_bundle_end_p, asm_p;
6894   int pos = 0, max_pos, template0, template1;
6895   rtx b;
6896   rtx nop;
6897   enum attr_type type;
6898
6899   insn_num = 0;
6900   /* Count insns in the EBB.  */
6901   for (insn = NEXT_INSN (prev_head_insn);
6902        insn && insn != tail;
6903        insn = NEXT_INSN (insn))
6904     if (INSN_P (insn))
6905       insn_num++;
6906   if (insn_num == 0)
6907     return;
6908   bundling_p = 1;
6909   dfa_clean_insn_cache ();
6910   initiate_bundle_state_table ();
6911   index_to_bundle_states = xmalloc ((insn_num + 2)
6912                                     * sizeof (struct bundle_state *));
6913   /* First (forward) pass -- generation of bundle states.  */
6914   curr_state = get_free_bundle_state ();
6915   curr_state->insn = NULL;
6916   curr_state->before_nops_num = 0;
6917   curr_state->after_nops_num = 0;
6918   curr_state->insn_num = 0;
6919   curr_state->cost = 0;
6920   curr_state->accumulated_insns_num = 0;
6921   curr_state->branch_deviation = 0;
6922   curr_state->next = NULL;
6923   curr_state->originator = NULL;
6924   state_reset (curr_state->dfa_state);
6925   index_to_bundle_states [0] = curr_state;
6926   insn_num = 0;
6927   /* Shift cycle mark if it is put on insn which could be ignored.  */
6928   for (insn = NEXT_INSN (prev_head_insn);
6929        insn != tail;
6930        insn = NEXT_INSN (insn))
6931     if (INSN_P (insn)
6932         && (ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6933             || GET_CODE (PATTERN (insn)) == USE
6934             || GET_CODE (PATTERN (insn)) == CLOBBER)
6935         && GET_MODE (insn) == TImode)
6936       {
6937         PUT_MODE (insn, VOIDmode);
6938         for (next_insn = NEXT_INSN (insn);
6939              next_insn != tail;
6940              next_insn = NEXT_INSN (next_insn))
6941           if (INSN_P (next_insn)
6942               && ia64_safe_itanium_class (next_insn) != ITANIUM_CLASS_IGNORE
6943               && GET_CODE (PATTERN (next_insn)) != USE
6944               && GET_CODE (PATTERN (next_insn)) != CLOBBER)
6945             {
6946               PUT_MODE (next_insn, TImode);
6947               break;
6948             }
6949       }
6950   /* Froward pass: generation of bundle states.  */
6951   for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
6952        insn != NULL_RTX;
6953        insn = next_insn)
6954     {
6955       gcc_assert (INSN_P (insn)
6956                   && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6957                   && GET_CODE (PATTERN (insn)) != USE
6958                   && GET_CODE (PATTERN (insn)) != CLOBBER);
6959       type = ia64_safe_type (insn);
6960       next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
6961       insn_num++;
6962       index_to_bundle_states [insn_num] = NULL;
6963       for (curr_state = index_to_bundle_states [insn_num - 1];
6964            curr_state != NULL;
6965            curr_state = next_state)
6966         {
6967           pos = curr_state->accumulated_insns_num % 3;
6968           next_state = curr_state->next;
6969           /* We must fill up the current bundle in order to start a
6970              subsequent asm insn in a new bundle.  Asm insn is always
6971              placed in a separate bundle.  */
6972           only_bundle_end_p
6973             = (next_insn != NULL_RTX
6974                && INSN_CODE (insn) == CODE_FOR_insn_group_barrier
6975                && ia64_safe_type (next_insn) == TYPE_UNKNOWN);
6976           /* We may fill up the current bundle if it is the cycle end
6977              without a group barrier.  */
6978           bundle_end_p
6979             = (only_bundle_end_p || next_insn == NULL_RTX
6980                || (GET_MODE (next_insn) == TImode
6981                    && INSN_CODE (insn) != CODE_FOR_insn_group_barrier));
6982           if (type == TYPE_F || type == TYPE_B || type == TYPE_L
6983               || type == TYPE_S
6984               /* We need to insert 2 nops for cases like M_MII.  To
6985                  guarantee issuing all insns on the same cycle for
6986                  Itanium 1, we need to issue 2 nops after the first M
6987                  insn (MnnMII where n is a nop insn).  */
6988               || ((type == TYPE_M || type == TYPE_A)
6989                   && ia64_tune == PROCESSOR_ITANIUM
6990                   && !bundle_end_p && pos == 1))
6991             issue_nops_and_insn (curr_state, 2, insn, bundle_end_p,
6992                                  only_bundle_end_p);
6993           issue_nops_and_insn (curr_state, 1, insn, bundle_end_p,
6994                                only_bundle_end_p);
6995           issue_nops_and_insn (curr_state, 0, insn, bundle_end_p,
6996                                only_bundle_end_p);
6997         }
6998       gcc_assert (index_to_bundle_states [insn_num]);
6999       for (curr_state = index_to_bundle_states [insn_num];
7000            curr_state != NULL;
7001            curr_state = curr_state->next)
7002         if (verbose >= 2 && dump)
7003           {
7004             /* This structure is taken from generated code of the
7005                pipeline hazard recognizer (see file insn-attrtab.c).
7006                Please don't forget to change the structure if a new
7007                automaton is added to .md file.  */
7008             struct DFA_chip
7009             {
7010               unsigned short one_automaton_state;
7011               unsigned short oneb_automaton_state;
7012               unsigned short two_automaton_state;
7013               unsigned short twob_automaton_state;
7014             };
7015
7016             fprintf
7017               (dump,
7018                "//    Bundle state %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
7019                curr_state->unique_num,
7020                (curr_state->originator == NULL
7021                 ? -1 : curr_state->originator->unique_num),
7022                curr_state->cost,
7023                curr_state->before_nops_num, curr_state->after_nops_num,
7024                curr_state->accumulated_insns_num, curr_state->branch_deviation,
7025                (ia64_tune == PROCESSOR_ITANIUM
7026                 ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
7027                 : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
7028                INSN_UID (insn));
7029           }
7030     }
7031   
7032   /* We should find a solution because the 2nd insn scheduling has
7033      found one.  */
7034   gcc_assert (index_to_bundle_states [insn_num]);
7035   /* Find a state corresponding to the best insn sequence.  */
7036   best_state = NULL;
7037   for (curr_state = index_to_bundle_states [insn_num];
7038        curr_state != NULL;
7039        curr_state = curr_state->next)
7040     /* We are just looking at the states with fully filled up last
7041        bundle.  The first we prefer insn sequences with minimal cost
7042        then with minimal inserted nops and finally with branch insns
7043        placed in the 3rd slots.  */
7044     if (curr_state->accumulated_insns_num % 3 == 0
7045         && (best_state == NULL || best_state->cost > curr_state->cost
7046             || (best_state->cost == curr_state->cost
7047                 && (curr_state->accumulated_insns_num
7048                     < best_state->accumulated_insns_num
7049                     || (curr_state->accumulated_insns_num
7050                         == best_state->accumulated_insns_num
7051                         && curr_state->branch_deviation
7052                         < best_state->branch_deviation)))))
7053       best_state = curr_state;
7054   /* Second (backward) pass: adding nops and templates.  */
7055   insn_num = best_state->before_nops_num;
7056   template0 = template1 = -1;
7057   for (curr_state = best_state;
7058        curr_state->originator != NULL;
7059        curr_state = curr_state->originator)
7060     {
7061       insn = curr_state->insn;
7062       asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
7063                || asm_noperands (PATTERN (insn)) >= 0);
7064       insn_num++;
7065       if (verbose >= 2 && dump)
7066         {
7067           struct DFA_chip
7068           {
7069             unsigned short one_automaton_state;
7070             unsigned short oneb_automaton_state;
7071             unsigned short two_automaton_state;
7072             unsigned short twob_automaton_state;
7073           };
7074
7075           fprintf
7076             (dump,
7077              "//    Best %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
7078              curr_state->unique_num,
7079              (curr_state->originator == NULL
7080               ? -1 : curr_state->originator->unique_num),
7081              curr_state->cost,
7082              curr_state->before_nops_num, curr_state->after_nops_num,
7083              curr_state->accumulated_insns_num, curr_state->branch_deviation,
7084              (ia64_tune == PROCESSOR_ITANIUM
7085               ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
7086               : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
7087              INSN_UID (insn));
7088         }
7089       /* Find the position in the current bundle window.  The window can
7090          contain at most two bundles.  Two bundle window means that
7091          the processor will make two bundle rotation.  */
7092       max_pos = get_max_pos (curr_state->dfa_state);
7093       if (max_pos == 6
7094           /* The following (negative template number) means that the
7095              processor did one bundle rotation.  */
7096           || (max_pos == 3 && template0 < 0))
7097         {
7098           /* We are at the end of the window -- find template(s) for
7099              its bundle(s).  */
7100           pos = max_pos;
7101           if (max_pos == 3)
7102             template0 = get_template (curr_state->dfa_state, 3);
7103           else
7104             {
7105               template1 = get_template (curr_state->dfa_state, 3);
7106               template0 = get_template (curr_state->dfa_state, 6);
7107             }
7108         }
7109       if (max_pos > 3 && template1 < 0)
7110         /* It may happen when we have the stop inside a bundle.  */
7111         {
7112           gcc_assert (pos <= 3);
7113           template1 = get_template (curr_state->dfa_state, 3);
7114           pos += 3;
7115         }
7116       if (!asm_p)
7117         /* Emit nops after the current insn.  */
7118         for (i = 0; i < curr_state->after_nops_num; i++)
7119           {
7120             nop = gen_nop ();
7121             emit_insn_after (nop, insn);
7122             pos--;
7123             gcc_assert (pos >= 0);
7124             if (pos % 3 == 0)
7125               {
7126                 /* We are at the start of a bundle: emit the template
7127                    (it should be defined).  */
7128                 gcc_assert (template0 >= 0);
7129                 b = gen_bundle_selector (GEN_INT (template0));
7130                 ia64_emit_insn_before (b, nop);
7131                 /* If we have two bundle window, we make one bundle
7132                    rotation.  Otherwise template0 will be undefined
7133                    (negative value).  */
7134                 template0 = template1;
7135                 template1 = -1;
7136               }
7137           }
7138       /* Move the position backward in the window.  Group barrier has
7139          no slot.  Asm insn takes all bundle.  */
7140       if (INSN_CODE (insn) != CODE_FOR_insn_group_barrier
7141           && GET_CODE (PATTERN (insn)) != ASM_INPUT
7142           && asm_noperands (PATTERN (insn)) < 0)
7143         pos--;
7144       /* Long insn takes 2 slots.  */
7145       if (ia64_safe_type (insn) == TYPE_L)
7146         pos--;
7147       gcc_assert (pos >= 0);
7148       if (pos % 3 == 0
7149           && INSN_CODE (insn) != CODE_FOR_insn_group_barrier
7150           && GET_CODE (PATTERN (insn)) != ASM_INPUT
7151           && asm_noperands (PATTERN (insn)) < 0)
7152         {
7153           /* The current insn is at the bundle start: emit the
7154              template.  */
7155           gcc_assert (template0 >= 0);
7156           b = gen_bundle_selector (GEN_INT (template0));
7157           ia64_emit_insn_before (b, insn);
7158           b = PREV_INSN (insn);
7159           insn = b;
7160           /* See comment above in analogous place for emitting nops
7161              after the insn.  */
7162           template0 = template1;
7163           template1 = -1;
7164         }
7165       /* Emit nops after the current insn.  */
7166       for (i = 0; i < curr_state->before_nops_num; i++)
7167         {
7168           nop = gen_nop ();
7169           ia64_emit_insn_before (nop, insn);
7170           nop = PREV_INSN (insn);
7171           insn = nop;
7172           pos--;
7173           gcc_assert (pos >= 0);
7174           if (pos % 3 == 0)
7175             {
7176               /* See comment above in analogous place for emitting nops
7177                  after the insn.  */
7178               gcc_assert (template0 >= 0);
7179               b = gen_bundle_selector (GEN_INT (template0));
7180               ia64_emit_insn_before (b, insn);
7181               b = PREV_INSN (insn);
7182               insn = b;
7183               template0 = template1;
7184               template1 = -1;
7185             }
7186         }
7187     }
7188   if (ia64_tune == PROCESSOR_ITANIUM)
7189     /* Insert additional cycles for MM-insns (MMMUL and MMSHF).
7190        Itanium1 has a strange design, if the distance between an insn
7191        and dependent MM-insn is less 4 then we have a 6 additional
7192        cycles stall.  So we make the distance equal to 4 cycles if it
7193        is less.  */
7194     for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
7195          insn != NULL_RTX;
7196          insn = next_insn)
7197       {
7198         gcc_assert (INSN_P (insn)
7199                     && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
7200                     && GET_CODE (PATTERN (insn)) != USE
7201                     && GET_CODE (PATTERN (insn)) != CLOBBER);
7202         next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
7203         if (INSN_UID (insn) < clocks_length && add_cycles [INSN_UID (insn)])
7204           /* We found a MM-insn which needs additional cycles.  */
7205           {
7206             rtx last;
7207             int i, j, n;
7208             int pred_stop_p;
7209
7210             /* Now we are searching for a template of the bundle in
7211                which the MM-insn is placed and the position of the
7212                insn in the bundle (0, 1, 2).  Also we are searching
7213                for that there is a stop before the insn.  */
7214             last = prev_active_insn (insn);
7215             pred_stop_p = recog_memoized (last) == CODE_FOR_insn_group_barrier;
7216             if (pred_stop_p)
7217               last = prev_active_insn (last);
7218             n = 0;
7219             for (;; last = prev_active_insn (last))
7220               if (recog_memoized (last) == CODE_FOR_bundle_selector)
7221                 {
7222                   template0 = XINT (XVECEXP (PATTERN (last), 0, 0), 0);
7223                   if (template0 == 9)
7224                     /* The insn is in MLX bundle.  Change the template
7225                        onto MFI because we will add nops before the
7226                        insn.  It simplifies subsequent code a lot.  */
7227                     PATTERN (last)
7228                       = gen_bundle_selector (const2_rtx); /* -> MFI */
7229                   break;
7230                 }
7231               else if (recog_memoized (last) != CODE_FOR_insn_group_barrier
7232                        && (ia64_safe_itanium_class (last)
7233                            != ITANIUM_CLASS_IGNORE))
7234                 n++;
7235             /* Some check of correctness: the stop is not at the
7236                bundle start, there are no more 3 insns in the bundle,
7237                and the MM-insn is not at the start of bundle with
7238                template MLX.  */
7239             gcc_assert ((!pred_stop_p || n)
7240                         && n <= 2
7241                         && (template0 != 9 || !n));
7242             /* Put nops after the insn in the bundle.  */
7243             for (j = 3 - n; j > 0; j --)
7244               ia64_emit_insn_before (gen_nop (), insn);
7245             /* It takes into account that we will add more N nops
7246                before the insn lately -- please see code below.  */
7247             add_cycles [INSN_UID (insn)]--;
7248             if (!pred_stop_p || add_cycles [INSN_UID (insn)])
7249               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7250                                      insn);
7251             if (pred_stop_p)
7252               add_cycles [INSN_UID (insn)]--;
7253             for (i = add_cycles [INSN_UID (insn)]; i > 0; i--)
7254               {
7255                 /* Insert "MII;" template.  */
7256                 ia64_emit_insn_before (gen_bundle_selector (const0_rtx),
7257                                        insn);
7258                 ia64_emit_insn_before (gen_nop (), insn);
7259                 ia64_emit_insn_before (gen_nop (), insn);
7260                 if (i > 1)
7261                   {
7262                     /* To decrease code size, we use "MI;I;"
7263                        template.  */
7264                     ia64_emit_insn_before
7265                       (gen_insn_group_barrier (GEN_INT (3)), insn);
7266                     i--;
7267                   }
7268                 ia64_emit_insn_before (gen_nop (), insn);
7269                 ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7270                                        insn);
7271               }
7272             /* Put the MM-insn in the same slot of a bundle with the
7273                same template as the original one.  */
7274             ia64_emit_insn_before (gen_bundle_selector (GEN_INT (template0)),
7275                                    insn);
7276             /* To put the insn in the same slot, add necessary number
7277                of nops.  */
7278             for (j = n; j > 0; j --)
7279               ia64_emit_insn_before (gen_nop (), insn);
7280             /* Put the stop if the original bundle had it.  */
7281             if (pred_stop_p)
7282               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7283                                      insn);
7284           }
7285       }
7286   free (index_to_bundle_states);
7287   finish_bundle_state_table ();
7288   bundling_p = 0;
7289   dfa_clean_insn_cache ();
7290 }
7291
7292 /* The following function is called at the end of scheduling BB or
7293    EBB.  After reload, it inserts stop bits and does insn bundling.  */
7294
7295 static void
7296 ia64_sched_finish (FILE *dump, int sched_verbose)
7297 {
7298   if (sched_verbose)
7299     fprintf (dump, "// Finishing schedule.\n");
7300   if (!reload_completed)
7301     return;
7302   if (reload_completed)
7303     {
7304       final_emit_insn_group_barriers (dump);
7305       bundling (dump, sched_verbose, current_sched_info->prev_head,
7306                 current_sched_info->next_tail);
7307       if (sched_verbose && dump)
7308         fprintf (dump, "//    finishing %d-%d\n",
7309                  INSN_UID (NEXT_INSN (current_sched_info->prev_head)),
7310                  INSN_UID (PREV_INSN (current_sched_info->next_tail)));
7311
7312       return;
7313     }
7314 }
7315
7316 /* The following function inserts stop bits in scheduled BB or EBB.  */
7317
7318 static void
7319 final_emit_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
7320 {
7321   rtx insn;
7322   int need_barrier_p = 0;
7323   rtx prev_insn = NULL_RTX;
7324
7325   init_insn_group_barriers ();
7326
7327   for (insn = NEXT_INSN (current_sched_info->prev_head);
7328        insn != current_sched_info->next_tail;
7329        insn = NEXT_INSN (insn))
7330     {
7331       if (GET_CODE (insn) == BARRIER)
7332         {
7333           rtx last = prev_active_insn (insn);
7334
7335           if (! last)
7336             continue;
7337           if (GET_CODE (last) == JUMP_INSN
7338               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
7339             last = prev_active_insn (last);
7340           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
7341             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
7342
7343           init_insn_group_barriers ();
7344           need_barrier_p = 0;
7345           prev_insn = NULL_RTX;
7346         }
7347       else if (INSN_P (insn))
7348         {
7349           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
7350             {
7351               init_insn_group_barriers ();
7352               need_barrier_p = 0;
7353               prev_insn = NULL_RTX;
7354             }
7355           else if (need_barrier_p || group_barrier_needed (insn))
7356             {
7357               if (TARGET_EARLY_STOP_BITS)
7358                 {
7359                   rtx last;
7360
7361                   for (last = insn;
7362                        last != current_sched_info->prev_head;
7363                        last = PREV_INSN (last))
7364                     if (INSN_P (last) && GET_MODE (last) == TImode
7365                         && stops_p [INSN_UID (last)])
7366                       break;
7367                   if (last == current_sched_info->prev_head)
7368                     last = insn;
7369                   last = prev_active_insn (last);
7370                   if (last
7371                       && recog_memoized (last) != CODE_FOR_insn_group_barrier)
7372                     emit_insn_after (gen_insn_group_barrier (GEN_INT (3)),
7373                                      last);
7374                   init_insn_group_barriers ();
7375                   for (last = NEXT_INSN (last);
7376                        last != insn;
7377                        last = NEXT_INSN (last))
7378                     if (INSN_P (last))
7379                       group_barrier_needed (last);
7380                 }
7381               else
7382                 {
7383                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7384                                     insn);
7385                   init_insn_group_barriers ();
7386                 }
7387               group_barrier_needed (insn);
7388               prev_insn = NULL_RTX;
7389             }
7390           else if (recog_memoized (insn) >= 0)
7391             prev_insn = insn;
7392           need_barrier_p = (GET_CODE (insn) == CALL_INSN
7393                             || GET_CODE (PATTERN (insn)) == ASM_INPUT
7394                             || asm_noperands (PATTERN (insn)) >= 0);
7395         }
7396     }
7397 }
7398
7399 \f
7400
7401 /* If the following function returns TRUE, we will use the the DFA
7402    insn scheduler.  */
7403
7404 static int
7405 ia64_first_cycle_multipass_dfa_lookahead (void)
7406 {
7407   return (reload_completed ? 6 : 4);
7408 }
7409
7410 /* The following function initiates variable `dfa_pre_cycle_insn'.  */
7411
7412 static void
7413 ia64_init_dfa_pre_cycle_insn (void)
7414 {
7415   if (temp_dfa_state == NULL)
7416     {
7417       dfa_state_size = state_size ();
7418       temp_dfa_state = xmalloc (dfa_state_size);
7419       prev_cycle_state = xmalloc (dfa_state_size);
7420     }
7421   dfa_pre_cycle_insn = make_insn_raw (gen_pre_cycle ());
7422   PREV_INSN (dfa_pre_cycle_insn) = NEXT_INSN (dfa_pre_cycle_insn) = NULL_RTX;
7423   recog_memoized (dfa_pre_cycle_insn);
7424   dfa_stop_insn = make_insn_raw (gen_insn_group_barrier (GEN_INT (3)));
7425   PREV_INSN (dfa_stop_insn) = NEXT_INSN (dfa_stop_insn) = NULL_RTX;
7426   recog_memoized (dfa_stop_insn);
7427 }
7428
7429 /* The following function returns the pseudo insn DFA_PRE_CYCLE_INSN
7430    used by the DFA insn scheduler.  */
7431
7432 static rtx
7433 ia64_dfa_pre_cycle_insn (void)
7434 {
7435   return dfa_pre_cycle_insn;
7436 }
7437
7438 /* The following function returns TRUE if PRODUCER (of type ilog or
7439    ld) produces address for CONSUMER (of type st or stf). */
7440
7441 int
7442 ia64_st_address_bypass_p (rtx producer, rtx consumer)
7443 {
7444   rtx dest, reg, mem;
7445
7446   gcc_assert (producer && consumer);
7447   dest = ia64_single_set (producer);
7448   gcc_assert (dest);
7449   reg = SET_DEST (dest);
7450   gcc_assert (reg);
7451   if (GET_CODE (reg) == SUBREG)
7452     reg = SUBREG_REG (reg);
7453   gcc_assert (GET_CODE (reg) == REG);
7454   
7455   dest = ia64_single_set (consumer);
7456   gcc_assert (dest);
7457   mem = SET_DEST (dest);
7458   gcc_assert (mem && GET_CODE (mem) == MEM);
7459   return reg_mentioned_p (reg, mem);
7460 }
7461
7462 /* The following function returns TRUE if PRODUCER (of type ilog or
7463    ld) produces address for CONSUMER (of type ld or fld). */
7464
7465 int
7466 ia64_ld_address_bypass_p (rtx producer, rtx consumer)
7467 {
7468   rtx dest, src, reg, mem;
7469
7470   gcc_assert (producer && consumer);
7471   dest = ia64_single_set (producer);
7472   gcc_assert (dest);
7473   reg = SET_DEST (dest);
7474   gcc_assert (reg);
7475   if (GET_CODE (reg) == SUBREG)
7476     reg = SUBREG_REG (reg);
7477   gcc_assert (GET_CODE (reg) == REG);
7478   
7479   src = ia64_single_set (consumer);
7480   gcc_assert (src);
7481   mem = SET_SRC (src);
7482   gcc_assert (mem);
7483   if (GET_CODE (mem) == UNSPEC && XVECLEN (mem, 0) > 0)
7484     mem = XVECEXP (mem, 0, 0);
7485   while (GET_CODE (mem) == SUBREG || GET_CODE (mem) == ZERO_EXTEND)
7486     mem = XEXP (mem, 0);
7487
7488   /* Note that LO_SUM is used for GOT loads.  */
7489   gcc_assert (GET_CODE (mem) == LO_SUM || GET_CODE (mem) == MEM);
7490
7491   return reg_mentioned_p (reg, mem);
7492 }
7493
7494 /* The following function returns TRUE if INSN produces address for a
7495    load/store insn.  We will place such insns into M slot because it
7496    decreases its latency time.  */
7497
7498 int
7499 ia64_produce_address_p (rtx insn)
7500 {
7501   return insn->call;
7502 }
7503
7504 \f
7505 /* Emit pseudo-ops for the assembler to describe predicate relations.
7506    At present this assumes that we only consider predicate pairs to
7507    be mutex, and that the assembler can deduce proper values from
7508    straight-line code.  */
7509
7510 static void
7511 emit_predicate_relation_info (void)
7512 {
7513   basic_block bb;
7514
7515   FOR_EACH_BB_REVERSE (bb)
7516     {
7517       int r;
7518       rtx head = BB_HEAD (bb);
7519
7520       /* We only need such notes at code labels.  */
7521       if (GET_CODE (head) != CODE_LABEL)
7522         continue;
7523       if (GET_CODE (NEXT_INSN (head)) == NOTE
7524           && NOTE_LINE_NUMBER (NEXT_INSN (head)) == NOTE_INSN_BASIC_BLOCK)
7525         head = NEXT_INSN (head);
7526
7527       /* Skip p0, which may be thought to be live due to (reg:DI p0)
7528          grabbing the entire block of predicate registers.  */
7529       for (r = PR_REG (2); r < PR_REG (64); r += 2)
7530         if (REGNO_REG_SET_P (bb->il.rtl->global_live_at_start, r))
7531           {
7532             rtx p = gen_rtx_REG (BImode, r);
7533             rtx n = emit_insn_after (gen_pred_rel_mutex (p), head);
7534             if (head == BB_END (bb))
7535               BB_END (bb) = n;
7536             head = n;
7537           }
7538     }
7539
7540   /* Look for conditional calls that do not return, and protect predicate
7541      relations around them.  Otherwise the assembler will assume the call
7542      returns, and complain about uses of call-clobbered predicates after
7543      the call.  */
7544   FOR_EACH_BB_REVERSE (bb)
7545     {
7546       rtx insn = BB_HEAD (bb);
7547
7548       while (1)
7549         {
7550           if (GET_CODE (insn) == CALL_INSN
7551               && GET_CODE (PATTERN (insn)) == COND_EXEC
7552               && find_reg_note (insn, REG_NORETURN, NULL_RTX))
7553             {
7554               rtx b = emit_insn_before (gen_safe_across_calls_all (), insn);
7555               rtx a = emit_insn_after (gen_safe_across_calls_normal (), insn);
7556               if (BB_HEAD (bb) == insn)
7557                 BB_HEAD (bb) = b;
7558               if (BB_END (bb) == insn)
7559                 BB_END (bb) = a;
7560             }
7561
7562           if (insn == BB_END (bb))
7563             break;
7564           insn = NEXT_INSN (insn);
7565         }
7566     }
7567 }
7568
7569 /* Perform machine dependent operations on the rtl chain INSNS.  */
7570
7571 static void
7572 ia64_reorg (void)
7573 {
7574   /* We are freeing block_for_insn in the toplev to keep compatibility
7575      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
7576   compute_bb_for_insn ();
7577
7578   /* If optimizing, we'll have split before scheduling.  */
7579   if (optimize == 0)
7580     split_all_insns (0);
7581
7582   /* ??? update_life_info_in_dirty_blocks fails to terminate during
7583      non-optimizing bootstrap.  */
7584   update_life_info (NULL, UPDATE_LIFE_GLOBAL_RM_NOTES, PROP_DEATH_NOTES);
7585
7586   if (optimize && ia64_flag_schedule_insns2)
7587     {
7588       timevar_push (TV_SCHED2);
7589       ia64_final_schedule = 1;
7590
7591       initiate_bundle_states ();
7592       ia64_nop = make_insn_raw (gen_nop ());
7593       PREV_INSN (ia64_nop) = NEXT_INSN (ia64_nop) = NULL_RTX;
7594       recog_memoized (ia64_nop);
7595       clocks_length = get_max_uid () + 1;
7596       stops_p = xcalloc (1, clocks_length);
7597       if (ia64_tune == PROCESSOR_ITANIUM)
7598         {
7599           clocks = xcalloc (clocks_length, sizeof (int));
7600           add_cycles = xcalloc (clocks_length, sizeof (int));
7601         }
7602       if (ia64_tune == PROCESSOR_ITANIUM2)
7603         {
7604           pos_1 = get_cpu_unit_code ("2_1");
7605           pos_2 = get_cpu_unit_code ("2_2");
7606           pos_3 = get_cpu_unit_code ("2_3");
7607           pos_4 = get_cpu_unit_code ("2_4");
7608           pos_5 = get_cpu_unit_code ("2_5");
7609           pos_6 = get_cpu_unit_code ("2_6");
7610           _0mii_ = get_cpu_unit_code ("2b_0mii.");
7611           _0mmi_ = get_cpu_unit_code ("2b_0mmi.");
7612           _0mfi_ = get_cpu_unit_code ("2b_0mfi.");
7613           _0mmf_ = get_cpu_unit_code ("2b_0mmf.");
7614           _0bbb_ = get_cpu_unit_code ("2b_0bbb.");
7615           _0mbb_ = get_cpu_unit_code ("2b_0mbb.");
7616           _0mib_ = get_cpu_unit_code ("2b_0mib.");
7617           _0mmb_ = get_cpu_unit_code ("2b_0mmb.");
7618           _0mfb_ = get_cpu_unit_code ("2b_0mfb.");
7619           _0mlx_ = get_cpu_unit_code ("2b_0mlx.");
7620           _1mii_ = get_cpu_unit_code ("2b_1mii.");
7621           _1mmi_ = get_cpu_unit_code ("2b_1mmi.");
7622           _1mfi_ = get_cpu_unit_code ("2b_1mfi.");
7623           _1mmf_ = get_cpu_unit_code ("2b_1mmf.");
7624           _1bbb_ = get_cpu_unit_code ("2b_1bbb.");
7625           _1mbb_ = get_cpu_unit_code ("2b_1mbb.");
7626           _1mib_ = get_cpu_unit_code ("2b_1mib.");
7627           _1mmb_ = get_cpu_unit_code ("2b_1mmb.");
7628           _1mfb_ = get_cpu_unit_code ("2b_1mfb.");
7629           _1mlx_ = get_cpu_unit_code ("2b_1mlx.");
7630         }
7631       else
7632         {
7633           pos_1 = get_cpu_unit_code ("1_1");
7634           pos_2 = get_cpu_unit_code ("1_2");
7635           pos_3 = get_cpu_unit_code ("1_3");
7636           pos_4 = get_cpu_unit_code ("1_4");
7637           pos_5 = get_cpu_unit_code ("1_5");
7638           pos_6 = get_cpu_unit_code ("1_6");
7639           _0mii_ = get_cpu_unit_code ("1b_0mii.");
7640           _0mmi_ = get_cpu_unit_code ("1b_0mmi.");
7641           _0mfi_ = get_cpu_unit_code ("1b_0mfi.");
7642           _0mmf_ = get_cpu_unit_code ("1b_0mmf.");
7643           _0bbb_ = get_cpu_unit_code ("1b_0bbb.");
7644           _0mbb_ = get_cpu_unit_code ("1b_0mbb.");
7645           _0mib_ = get_cpu_unit_code ("1b_0mib.");
7646           _0mmb_ = get_cpu_unit_code ("1b_0mmb.");
7647           _0mfb_ = get_cpu_unit_code ("1b_0mfb.");
7648           _0mlx_ = get_cpu_unit_code ("1b_0mlx.");
7649           _1mii_ = get_cpu_unit_code ("1b_1mii.");
7650           _1mmi_ = get_cpu_unit_code ("1b_1mmi.");
7651           _1mfi_ = get_cpu_unit_code ("1b_1mfi.");
7652           _1mmf_ = get_cpu_unit_code ("1b_1mmf.");
7653           _1bbb_ = get_cpu_unit_code ("1b_1bbb.");
7654           _1mbb_ = get_cpu_unit_code ("1b_1mbb.");
7655           _1mib_ = get_cpu_unit_code ("1b_1mib.");
7656           _1mmb_ = get_cpu_unit_code ("1b_1mmb.");
7657           _1mfb_ = get_cpu_unit_code ("1b_1mfb.");
7658           _1mlx_ = get_cpu_unit_code ("1b_1mlx.");
7659         }
7660       schedule_ebbs (dump_file);
7661       finish_bundle_states ();
7662       if (ia64_tune == PROCESSOR_ITANIUM)
7663         {
7664           free (add_cycles);
7665           free (clocks);
7666         }
7667       free (stops_p);
7668       emit_insn_group_barriers (dump_file);
7669
7670       ia64_final_schedule = 0;
7671       timevar_pop (TV_SCHED2);
7672     }
7673   else
7674     emit_all_insn_group_barriers (dump_file);
7675
7676   /* A call must not be the last instruction in a function, so that the
7677      return address is still within the function, so that unwinding works
7678      properly.  Note that IA-64 differs from dwarf2 on this point.  */
7679   if (flag_unwind_tables || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
7680     {
7681       rtx insn;
7682       int saw_stop = 0;
7683
7684       insn = get_last_insn ();
7685       if (! INSN_P (insn))
7686         insn = prev_active_insn (insn);
7687       /* Skip over insns that expand to nothing.  */
7688       while (GET_CODE (insn) == INSN && get_attr_empty (insn) == EMPTY_YES)
7689         {
7690           if (GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
7691               && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
7692             saw_stop = 1;
7693           insn = prev_active_insn (insn);
7694         }
7695       if (GET_CODE (insn) == CALL_INSN)
7696         {
7697           if (! saw_stop)
7698             emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7699           emit_insn (gen_break_f ());
7700           emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7701         }
7702     }
7703
7704   emit_predicate_relation_info ();
7705
7706   if (ia64_flag_var_tracking)
7707     {
7708       timevar_push (TV_VAR_TRACKING);
7709       variable_tracking_main ();
7710       timevar_pop (TV_VAR_TRACKING);
7711     }
7712 }
7713 \f
7714 /* Return true if REGNO is used by the epilogue.  */
7715
7716 int
7717 ia64_epilogue_uses (int regno)
7718 {
7719   switch (regno)
7720     {
7721     case R_GR (1):
7722       /* With a call to a function in another module, we will write a new
7723          value to "gp".  After returning from such a call, we need to make
7724          sure the function restores the original gp-value, even if the
7725          function itself does not use the gp anymore.  */
7726       return !(TARGET_AUTO_PIC || TARGET_NO_PIC);
7727
7728     case IN_REG (0): case IN_REG (1): case IN_REG (2): case IN_REG (3):
7729     case IN_REG (4): case IN_REG (5): case IN_REG (6): case IN_REG (7):
7730       /* For functions defined with the syscall_linkage attribute, all
7731          input registers are marked as live at all function exits.  This
7732          prevents the register allocator from using the input registers,
7733          which in turn makes it possible to restart a system call after
7734          an interrupt without having to save/restore the input registers.
7735          This also prevents kernel data from leaking to application code.  */
7736       return lookup_attribute ("syscall_linkage",
7737            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))) != NULL;
7738
7739     case R_BR (0):
7740       /* Conditional return patterns can't represent the use of `b0' as
7741          the return address, so we force the value live this way.  */
7742       return 1;
7743
7744     case AR_PFS_REGNUM:
7745       /* Likewise for ar.pfs, which is used by br.ret.  */
7746       return 1;
7747
7748     default:
7749       return 0;
7750     }
7751 }
7752
7753 /* Return true if REGNO is used by the frame unwinder.  */
7754
7755 int
7756 ia64_eh_uses (int regno)
7757 {
7758   if (! reload_completed)
7759     return 0;
7760
7761   if (current_frame_info.reg_save_b0
7762       && regno == current_frame_info.reg_save_b0)
7763     return 1;
7764   if (current_frame_info.reg_save_pr
7765       && regno == current_frame_info.reg_save_pr)
7766     return 1;
7767   if (current_frame_info.reg_save_ar_pfs
7768       && regno == current_frame_info.reg_save_ar_pfs)
7769     return 1;
7770   if (current_frame_info.reg_save_ar_unat
7771       && regno == current_frame_info.reg_save_ar_unat)
7772     return 1;
7773   if (current_frame_info.reg_save_ar_lc
7774       && regno == current_frame_info.reg_save_ar_lc)
7775     return 1;
7776
7777   return 0;
7778 }
7779 \f
7780 /* Return true if this goes in small data/bss.  */
7781
7782 /* ??? We could also support own long data here.  Generating movl/add/ld8
7783    instead of addl,ld8/ld8.  This makes the code bigger, but should make the
7784    code faster because there is one less load.  This also includes incomplete
7785    types which can't go in sdata/sbss.  */
7786
7787 static bool
7788 ia64_in_small_data_p (tree exp)
7789 {
7790   if (TARGET_NO_SDATA)
7791     return false;
7792
7793   /* We want to merge strings, so we never consider them small data.  */
7794   if (TREE_CODE (exp) == STRING_CST)
7795     return false;
7796
7797   /* Functions are never small data.  */
7798   if (TREE_CODE (exp) == FUNCTION_DECL)
7799     return false;
7800
7801   if (TREE_CODE (exp) == VAR_DECL && DECL_SECTION_NAME (exp))
7802     {
7803       const char *section = TREE_STRING_POINTER (DECL_SECTION_NAME (exp));
7804
7805       if (strcmp (section, ".sdata") == 0
7806           || strncmp (section, ".sdata.", 7) == 0
7807           || strncmp (section, ".gnu.linkonce.s.", 16) == 0
7808           || strcmp (section, ".sbss") == 0
7809           || strncmp (section, ".sbss.", 6) == 0
7810           || strncmp (section, ".gnu.linkonce.sb.", 17) == 0)
7811         return true;
7812     }
7813   else
7814     {
7815       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (exp));
7816
7817       /* If this is an incomplete type with size 0, then we can't put it
7818          in sdata because it might be too big when completed.  */
7819       if (size > 0 && size <= ia64_section_threshold)
7820         return true;
7821     }
7822
7823   return false;
7824 }
7825 \f
7826 /* Output assembly directives for prologue regions.  */
7827
7828 /* The current basic block number.  */
7829
7830 static bool last_block;
7831
7832 /* True if we need a copy_state command at the start of the next block.  */
7833
7834 static bool need_copy_state;
7835
7836 /* The function emits unwind directives for the start of an epilogue.  */
7837
7838 static void
7839 process_epilogue (void)
7840 {
7841   /* If this isn't the last block of the function, then we need to label the
7842      current state, and copy it back in at the start of the next block.  */
7843
7844   if (!last_block)
7845     {
7846       fprintf (asm_out_file, "\t.label_state %d\n",
7847                ++cfun->machine->state_num);
7848       need_copy_state = true;
7849     }
7850
7851   fprintf (asm_out_file, "\t.restore sp\n");
7852 }
7853
7854 /* This function processes a SET pattern looking for specific patterns
7855    which result in emitting an assembly directive required for unwinding.  */
7856
7857 static int
7858 process_set (FILE *asm_out_file, rtx pat)
7859 {
7860   rtx src = SET_SRC (pat);
7861   rtx dest = SET_DEST (pat);
7862   int src_regno, dest_regno;
7863
7864   /* Look for the ALLOC insn.  */
7865   if (GET_CODE (src) == UNSPEC_VOLATILE
7866       && XINT (src, 1) == UNSPECV_ALLOC
7867       && GET_CODE (dest) == REG)
7868     {
7869       dest_regno = REGNO (dest);
7870
7871       /* If this is the final destination for ar.pfs, then this must
7872          be the alloc in the prologue.  */
7873       if (dest_regno == current_frame_info.reg_save_ar_pfs)
7874         fprintf (asm_out_file, "\t.save ar.pfs, r%d\n",
7875                  ia64_dbx_register_number (dest_regno));
7876       else
7877         {
7878           /* This must be an alloc before a sibcall.  We must drop the
7879              old frame info.  The easiest way to drop the old frame
7880              info is to ensure we had a ".restore sp" directive
7881              followed by a new prologue.  If the procedure doesn't
7882              have a memory-stack frame, we'll issue a dummy ".restore
7883              sp" now.  */
7884           if (current_frame_info.total_size == 0 && !frame_pointer_needed)
7885             /* if haven't done process_epilogue() yet, do it now */
7886             process_epilogue ();
7887           fprintf (asm_out_file, "\t.prologue\n");
7888         }
7889       return 1;
7890     }
7891
7892   /* Look for SP = ....  */
7893   if (GET_CODE (dest) == REG && REGNO (dest) == STACK_POINTER_REGNUM)
7894     {
7895       if (GET_CODE (src) == PLUS)
7896         {
7897           rtx op0 = XEXP (src, 0);
7898           rtx op1 = XEXP (src, 1);
7899           
7900           gcc_assert (op0 == dest && GET_CODE (op1) == CONST_INT);
7901           
7902           if (INTVAL (op1) < 0)
7903             fprintf (asm_out_file, "\t.fframe "HOST_WIDE_INT_PRINT_DEC"\n",
7904                      -INTVAL (op1));
7905           else
7906             process_epilogue ();
7907         }
7908       else
7909         {
7910           gcc_assert (GET_CODE (src) == REG
7911                       && REGNO (src) == HARD_FRAME_POINTER_REGNUM);
7912           process_epilogue ();
7913         }
7914
7915       return 1;
7916     }
7917
7918   /* Register move we need to look at.  */
7919   if (GET_CODE (dest) == REG && GET_CODE (src) == REG)
7920     {
7921       src_regno = REGNO (src);
7922       dest_regno = REGNO (dest);
7923
7924       switch (src_regno)
7925         {
7926         case BR_REG (0):
7927           /* Saving return address pointer.  */
7928           gcc_assert (dest_regno == current_frame_info.reg_save_b0);
7929           fprintf (asm_out_file, "\t.save rp, r%d\n",
7930                    ia64_dbx_register_number (dest_regno));
7931           return 1;
7932
7933         case PR_REG (0):
7934           gcc_assert (dest_regno == current_frame_info.reg_save_pr);
7935           fprintf (asm_out_file, "\t.save pr, r%d\n",
7936                    ia64_dbx_register_number (dest_regno));
7937           return 1;
7938
7939         case AR_UNAT_REGNUM:
7940           gcc_assert (dest_regno == current_frame_info.reg_save_ar_unat);
7941           fprintf (asm_out_file, "\t.save ar.unat, r%d\n",
7942                    ia64_dbx_register_number (dest_regno));
7943           return 1;
7944
7945         case AR_LC_REGNUM:
7946           gcc_assert (dest_regno == current_frame_info.reg_save_ar_lc);
7947           fprintf (asm_out_file, "\t.save ar.lc, r%d\n",
7948                    ia64_dbx_register_number (dest_regno));
7949           return 1;
7950
7951         case STACK_POINTER_REGNUM:
7952           gcc_assert (dest_regno == HARD_FRAME_POINTER_REGNUM
7953                       && frame_pointer_needed);
7954           fprintf (asm_out_file, "\t.vframe r%d\n",
7955                    ia64_dbx_register_number (dest_regno));
7956           return 1;
7957
7958         default:
7959           /* Everything else should indicate being stored to memory.  */
7960           gcc_unreachable ();
7961         }
7962     }
7963
7964   /* Memory store we need to look at.  */
7965   if (GET_CODE (dest) == MEM && GET_CODE (src) == REG)
7966     {
7967       long off;
7968       rtx base;
7969       const char *saveop;
7970
7971       if (GET_CODE (XEXP (dest, 0)) == REG)
7972         {
7973           base = XEXP (dest, 0);
7974           off = 0;
7975         }
7976       else
7977         {
7978           gcc_assert (GET_CODE (XEXP (dest, 0)) == PLUS
7979                       && GET_CODE (XEXP (XEXP (dest, 0), 1)) == CONST_INT);
7980           base = XEXP (XEXP (dest, 0), 0);
7981           off = INTVAL (XEXP (XEXP (dest, 0), 1));
7982         }
7983
7984       if (base == hard_frame_pointer_rtx)
7985         {
7986           saveop = ".savepsp";
7987           off = - off;
7988         }
7989       else
7990         {
7991           gcc_assert (base == stack_pointer_rtx);
7992           saveop = ".savesp";
7993         }
7994
7995       src_regno = REGNO (src);
7996       switch (src_regno)
7997         {
7998         case BR_REG (0):
7999           gcc_assert (!current_frame_info.reg_save_b0);
8000           fprintf (asm_out_file, "\t%s rp, %ld\n", saveop, off);
8001           return 1;
8002
8003         case PR_REG (0):
8004           gcc_assert (!current_frame_info.reg_save_pr);
8005           fprintf (asm_out_file, "\t%s pr, %ld\n", saveop, off);
8006           return 1;
8007
8008         case AR_LC_REGNUM:
8009           gcc_assert (!current_frame_info.reg_save_ar_lc);
8010           fprintf (asm_out_file, "\t%s ar.lc, %ld\n", saveop, off);
8011           return 1;
8012
8013         case AR_PFS_REGNUM:
8014           gcc_assert (!current_frame_info.reg_save_ar_pfs);
8015           fprintf (asm_out_file, "\t%s ar.pfs, %ld\n", saveop, off);
8016           return 1;
8017
8018         case AR_UNAT_REGNUM:
8019           gcc_assert (!current_frame_info.reg_save_ar_unat);
8020           fprintf (asm_out_file, "\t%s ar.unat, %ld\n", saveop, off);
8021           return 1;
8022
8023         case GR_REG (4):
8024         case GR_REG (5):
8025         case GR_REG (6):
8026         case GR_REG (7):
8027           fprintf (asm_out_file, "\t.save.g 0x%x\n",
8028                    1 << (src_regno - GR_REG (4)));
8029           return 1;
8030
8031         case BR_REG (1):
8032         case BR_REG (2):
8033         case BR_REG (3):
8034         case BR_REG (4):
8035         case BR_REG (5):
8036           fprintf (asm_out_file, "\t.save.b 0x%x\n",
8037                    1 << (src_regno - BR_REG (1)));
8038           return 1;
8039
8040         case FR_REG (2):
8041         case FR_REG (3):
8042         case FR_REG (4):
8043         case FR_REG (5):
8044           fprintf (asm_out_file, "\t.save.f 0x%x\n",
8045                    1 << (src_regno - FR_REG (2)));
8046           return 1;
8047
8048         case FR_REG (16): case FR_REG (17): case FR_REG (18): case FR_REG (19):
8049         case FR_REG (20): case FR_REG (21): case FR_REG (22): case FR_REG (23):
8050         case FR_REG (24): case FR_REG (25): case FR_REG (26): case FR_REG (27):
8051         case FR_REG (28): case FR_REG (29): case FR_REG (30): case FR_REG (31):
8052           fprintf (asm_out_file, "\t.save.gf 0x0, 0x%x\n",
8053                    1 << (src_regno - FR_REG (12)));
8054           return 1;
8055
8056         default:
8057           return 0;
8058         }
8059     }
8060
8061   return 0;
8062 }
8063
8064
8065 /* This function looks at a single insn and emits any directives
8066    required to unwind this insn.  */
8067 void
8068 process_for_unwind_directive (FILE *asm_out_file, rtx insn)
8069 {
8070   if (flag_unwind_tables
8071       || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
8072     {
8073       rtx pat;
8074
8075       if (GET_CODE (insn) == NOTE
8076           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
8077         {
8078           last_block = NOTE_BASIC_BLOCK (insn)->next_bb == EXIT_BLOCK_PTR;
8079
8080           /* Restore unwind state from immediately before the epilogue.  */
8081           if (need_copy_state)
8082             {
8083               fprintf (asm_out_file, "\t.body\n");
8084               fprintf (asm_out_file, "\t.copy_state %d\n",
8085                        cfun->machine->state_num);
8086               need_copy_state = false;
8087             }
8088         }
8089
8090       if (GET_CODE (insn) == NOTE || ! RTX_FRAME_RELATED_P (insn))
8091         return;
8092
8093       pat = find_reg_note (insn, REG_FRAME_RELATED_EXPR, NULL_RTX);
8094       if (pat)
8095         pat = XEXP (pat, 0);
8096       else
8097         pat = PATTERN (insn);
8098
8099       switch (GET_CODE (pat))
8100         {
8101         case SET:
8102           process_set (asm_out_file, pat);
8103           break;
8104
8105         case PARALLEL:
8106           {
8107             int par_index;
8108             int limit = XVECLEN (pat, 0);
8109             for (par_index = 0; par_index < limit; par_index++)
8110               {
8111                 rtx x = XVECEXP (pat, 0, par_index);
8112                 if (GET_CODE (x) == SET)
8113                   process_set (asm_out_file, x);
8114               }
8115             break;
8116           }
8117
8118         default:
8119           gcc_unreachable ();
8120         }
8121     }
8122 }
8123
8124 \f
8125 enum ia64_builtins
8126 {
8127   IA64_BUILTIN_BSP,
8128   IA64_BUILTIN_FLUSHRS
8129 };
8130
8131 void
8132 ia64_init_builtins (void)
8133 {
8134   tree fpreg_type;
8135   tree float80_type;
8136
8137   /* The __fpreg type.  */
8138   fpreg_type = make_node (REAL_TYPE);
8139   TYPE_PRECISION (fpreg_type) = 82;
8140   layout_type (fpreg_type);
8141   (*lang_hooks.types.register_builtin_type) (fpreg_type, "__fpreg");
8142
8143   /* The __float80 type.  */
8144   float80_type = make_node (REAL_TYPE);
8145   TYPE_PRECISION (float80_type) = 80;
8146   layout_type (float80_type);
8147   (*lang_hooks.types.register_builtin_type) (float80_type, "__float80");
8148
8149   /* The __float128 type.  */
8150   if (!TARGET_HPUX)
8151     {
8152       tree float128_type = make_node (REAL_TYPE);
8153       TYPE_PRECISION (float128_type) = 128;
8154       layout_type (float128_type);
8155       (*lang_hooks.types.register_builtin_type) (float128_type, "__float128");
8156     }
8157   else
8158     /* Under HPUX, this is a synonym for "long double".  */
8159     (*lang_hooks.types.register_builtin_type) (long_double_type_node,
8160                                                "__float128");
8161
8162 #define def_builtin(name, type, code)                                   \
8163   lang_hooks.builtin_function ((name), (type), (code), BUILT_IN_MD,     \
8164                                NULL, NULL_TREE)
8165
8166   def_builtin ("__builtin_ia64_bsp",
8167                build_function_type (ptr_type_node, void_list_node),
8168                IA64_BUILTIN_BSP);
8169
8170   def_builtin ("__builtin_ia64_flushrs",
8171                build_function_type (void_type_node, void_list_node),
8172                IA64_BUILTIN_FLUSHRS);
8173
8174 #undef def_builtin
8175 }
8176
8177 rtx
8178 ia64_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
8179                      enum machine_mode mode ATTRIBUTE_UNUSED,
8180                      int ignore ATTRIBUTE_UNUSED)
8181 {
8182   tree fndecl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
8183   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
8184
8185   switch (fcode)
8186     {
8187     case IA64_BUILTIN_BSP:
8188       if (! target || ! register_operand (target, DImode))
8189         target = gen_reg_rtx (DImode);
8190       emit_insn (gen_bsp_value (target));
8191 #ifdef POINTERS_EXTEND_UNSIGNED
8192       target = convert_memory_address (ptr_mode, target);
8193 #endif
8194       return target;
8195
8196     case IA64_BUILTIN_FLUSHRS:
8197       emit_insn (gen_flushrs ());
8198       return const0_rtx;
8199
8200     default:
8201       break;
8202     }
8203
8204   return NULL_RTX;
8205 }
8206
8207 /* For the HP-UX IA64 aggregate parameters are passed stored in the
8208    most significant bits of the stack slot.  */
8209
8210 enum direction
8211 ia64_hpux_function_arg_padding (enum machine_mode mode, tree type)
8212 {
8213    /* Exception to normal case for structures/unions/etc.  */
8214
8215    if (type && AGGREGATE_TYPE_P (type)
8216        && int_size_in_bytes (type) < UNITS_PER_WORD)
8217      return upward;
8218
8219    /* Fall back to the default.  */
8220    return DEFAULT_FUNCTION_ARG_PADDING (mode, type);
8221 }
8222
8223 /* Linked list of all external functions that are to be emitted by GCC.
8224    We output the name if and only if TREE_SYMBOL_REFERENCED is set in
8225    order to avoid putting out names that are never really used.  */
8226
8227 struct extern_func_list GTY(())
8228 {
8229   struct extern_func_list *next;
8230   tree decl;
8231 };
8232
8233 static GTY(()) struct extern_func_list *extern_func_head;
8234
8235 static void
8236 ia64_hpux_add_extern_decl (tree decl)
8237 {
8238   struct extern_func_list *p = ggc_alloc (sizeof (struct extern_func_list));
8239
8240   p->decl = decl;
8241   p->next = extern_func_head;
8242   extern_func_head = p;
8243 }
8244
8245 /* Print out the list of used global functions.  */
8246
8247 static void
8248 ia64_hpux_file_end (void)
8249 {
8250   struct extern_func_list *p;
8251
8252   for (p = extern_func_head; p; p = p->next)
8253     {
8254       tree decl = p->decl;
8255       tree id = DECL_ASSEMBLER_NAME (decl);
8256
8257       gcc_assert (id);
8258
8259       if (!TREE_ASM_WRITTEN (decl) && TREE_SYMBOL_REFERENCED (id))
8260         {
8261           const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
8262
8263           TREE_ASM_WRITTEN (decl) = 1;
8264           (*targetm.asm_out.globalize_label) (asm_out_file, name);
8265           fputs (TYPE_ASM_OP, asm_out_file);
8266           assemble_name (asm_out_file, name);
8267           fprintf (asm_out_file, "," TYPE_OPERAND_FMT "\n", "function");
8268         }
8269     }
8270
8271   extern_func_head = 0;
8272 }
8273
8274 /* Set SImode div/mod functions, init_integral_libfuncs only initializes
8275    modes of word_mode and larger.  Rename the TFmode libfuncs using the
8276    HPUX conventions. __divtf3 is used for XFmode. We need to keep it for
8277    backward compatibility. */
8278
8279 static void
8280 ia64_init_libfuncs (void)
8281 {
8282   set_optab_libfunc (sdiv_optab, SImode, "__divsi3");
8283   set_optab_libfunc (udiv_optab, SImode, "__udivsi3");
8284   set_optab_libfunc (smod_optab, SImode, "__modsi3");
8285   set_optab_libfunc (umod_optab, SImode, "__umodsi3");
8286
8287   set_optab_libfunc (add_optab, TFmode, "_U_Qfadd");
8288   set_optab_libfunc (sub_optab, TFmode, "_U_Qfsub");
8289   set_optab_libfunc (smul_optab, TFmode, "_U_Qfmpy");
8290   set_optab_libfunc (sdiv_optab, TFmode, "_U_Qfdiv");
8291   set_optab_libfunc (neg_optab, TFmode, "_U_Qfneg");
8292
8293   set_conv_libfunc (sext_optab, TFmode, SFmode, "_U_Qfcnvff_sgl_to_quad");
8294   set_conv_libfunc (sext_optab, TFmode, DFmode, "_U_Qfcnvff_dbl_to_quad");
8295   set_conv_libfunc (sext_optab, TFmode, XFmode, "_U_Qfcnvff_f80_to_quad");
8296   set_conv_libfunc (trunc_optab, SFmode, TFmode, "_U_Qfcnvff_quad_to_sgl");
8297   set_conv_libfunc (trunc_optab, DFmode, TFmode, "_U_Qfcnvff_quad_to_dbl");
8298   set_conv_libfunc (trunc_optab, XFmode, TFmode, "_U_Qfcnvff_quad_to_f80");
8299
8300   set_conv_libfunc (sfix_optab, SImode, TFmode, "_U_Qfcnvfxt_quad_to_sgl");
8301   set_conv_libfunc (sfix_optab, DImode, TFmode, "_U_Qfcnvfxt_quad_to_dbl");
8302   set_conv_libfunc (ufix_optab, SImode, TFmode, "_U_Qfcnvfxut_quad_to_sgl");
8303   set_conv_libfunc (ufix_optab, DImode, TFmode, "_U_Qfcnvfxut_quad_to_dbl");
8304
8305   set_conv_libfunc (sfloat_optab, TFmode, SImode, "_U_Qfcnvxf_sgl_to_quad");
8306   set_conv_libfunc (sfloat_optab, TFmode, DImode, "_U_Qfcnvxf_dbl_to_quad");
8307 }
8308
8309 /* Rename all the TFmode libfuncs using the HPUX conventions.  */
8310
8311 static void
8312 ia64_hpux_init_libfuncs (void)
8313 {
8314   ia64_init_libfuncs ();
8315
8316   set_optab_libfunc (smin_optab, TFmode, "_U_Qfmin");
8317   set_optab_libfunc (smax_optab, TFmode, "_U_Qfmax");
8318   set_optab_libfunc (abs_optab, TFmode, "_U_Qfabs");
8319
8320   /* ia64_expand_compare uses this.  */
8321   cmptf_libfunc = init_one_libfunc ("_U_Qfcmp");
8322
8323   /* These should never be used.  */
8324   set_optab_libfunc (eq_optab, TFmode, 0);
8325   set_optab_libfunc (ne_optab, TFmode, 0);
8326   set_optab_libfunc (gt_optab, TFmode, 0);
8327   set_optab_libfunc (ge_optab, TFmode, 0);
8328   set_optab_libfunc (lt_optab, TFmode, 0);
8329   set_optab_libfunc (le_optab, TFmode, 0);
8330 }
8331
8332 /* Rename the division and modulus functions in VMS.  */
8333
8334 static void
8335 ia64_vms_init_libfuncs (void)
8336 {
8337   set_optab_libfunc (sdiv_optab, SImode, "OTS$DIV_I");
8338   set_optab_libfunc (sdiv_optab, DImode, "OTS$DIV_L");
8339   set_optab_libfunc (udiv_optab, SImode, "OTS$DIV_UI");
8340   set_optab_libfunc (udiv_optab, DImode, "OTS$DIV_UL");
8341   set_optab_libfunc (smod_optab, SImode, "OTS$REM_I");
8342   set_optab_libfunc (smod_optab, DImode, "OTS$REM_L");
8343   set_optab_libfunc (umod_optab, SImode, "OTS$REM_UI");
8344   set_optab_libfunc (umod_optab, DImode, "OTS$REM_UL");
8345 }
8346
8347 /* Rename the TFmode libfuncs available from soft-fp in glibc using
8348    the HPUX conventions.  */
8349
8350 static void
8351 ia64_sysv4_init_libfuncs (void)
8352 {
8353   ia64_init_libfuncs ();
8354
8355   /* These functions are not part of the HPUX TFmode interface.  We
8356      use them instead of _U_Qfcmp, which doesn't work the way we
8357      expect.  */
8358   set_optab_libfunc (eq_optab, TFmode, "_U_Qfeq");
8359   set_optab_libfunc (ne_optab, TFmode, "_U_Qfne");
8360   set_optab_libfunc (gt_optab, TFmode, "_U_Qfgt");
8361   set_optab_libfunc (ge_optab, TFmode, "_U_Qfge");
8362   set_optab_libfunc (lt_optab, TFmode, "_U_Qflt");
8363   set_optab_libfunc (le_optab, TFmode, "_U_Qfle");
8364
8365   /* We leave out _U_Qfmin, _U_Qfmax and _U_Qfabs since soft-fp in
8366      glibc doesn't have them.  */
8367 }
8368 \f
8369 /* Switch to the section to which we should output X.  The only thing
8370    special we do here is to honor small data.  */
8371
8372 static void
8373 ia64_select_rtx_section (enum machine_mode mode, rtx x,
8374                          unsigned HOST_WIDE_INT align)
8375 {
8376   if (GET_MODE_SIZE (mode) > 0
8377       && GET_MODE_SIZE (mode) <= ia64_section_threshold)
8378     sdata_section ();
8379   else
8380     default_elf_select_rtx_section (mode, x, align);
8381 }
8382
8383 /* It is illegal to have relocations in shared segments on AIX and HPUX.
8384    Pretend flag_pic is always set.  */
8385
8386 static void
8387 ia64_rwreloc_select_section (tree exp, int reloc, unsigned HOST_WIDE_INT align)
8388 {
8389   default_elf_select_section_1 (exp, reloc, align, true);
8390 }
8391
8392 static void
8393 ia64_rwreloc_unique_section (tree decl, int reloc)
8394 {
8395   default_unique_section_1 (decl, reloc, true);
8396 }
8397
8398 static void
8399 ia64_rwreloc_select_rtx_section (enum machine_mode mode, rtx x,
8400                                  unsigned HOST_WIDE_INT align)
8401 {
8402   int save_pic = flag_pic;
8403   flag_pic = 1;
8404   ia64_select_rtx_section (mode, x, align);
8405   flag_pic = save_pic;
8406 }
8407
8408 #ifndef TARGET_RWRELOC
8409 #define TARGET_RWRELOC flag_pic
8410 #endif
8411
8412 static unsigned int
8413 ia64_section_type_flags (tree decl, const char *name, int reloc)
8414 {
8415   unsigned int flags = 0;
8416
8417   if (strcmp (name, ".sdata") == 0
8418       || strncmp (name, ".sdata.", 7) == 0
8419       || strncmp (name, ".gnu.linkonce.s.", 16) == 0
8420       || strncmp (name, ".sdata2.", 8) == 0
8421       || strncmp (name, ".gnu.linkonce.s2.", 17) == 0
8422       || strcmp (name, ".sbss") == 0
8423       || strncmp (name, ".sbss.", 6) == 0
8424       || strncmp (name, ".gnu.linkonce.sb.", 17) == 0)
8425     flags = SECTION_SMALL;
8426
8427   flags |= default_section_type_flags_1 (decl, name, reloc, TARGET_RWRELOC);
8428   return flags;
8429 }
8430
8431 /* Returns true if FNTYPE (a FUNCTION_TYPE or a METHOD_TYPE) returns a
8432    structure type and that the address of that type should be passed
8433    in out0, rather than in r8.  */
8434
8435 static bool
8436 ia64_struct_retval_addr_is_first_parm_p (tree fntype)
8437 {
8438   tree ret_type = TREE_TYPE (fntype);
8439
8440   /* The Itanium C++ ABI requires that out0, rather than r8, be used
8441      as the structure return address parameter, if the return value
8442      type has a non-trivial copy constructor or destructor.  It is not
8443      clear if this same convention should be used for other
8444      programming languages.  Until G++ 3.4, we incorrectly used r8 for
8445      these return values.  */
8446   return (abi_version_at_least (2)
8447           && ret_type
8448           && TYPE_MODE (ret_type) == BLKmode 
8449           && TREE_ADDRESSABLE (ret_type)
8450           && strcmp (lang_hooks.name, "GNU C++") == 0);
8451 }
8452
8453 /* Output the assembler code for a thunk function.  THUNK_DECL is the
8454    declaration for the thunk function itself, FUNCTION is the decl for
8455    the target function.  DELTA is an immediate constant offset to be
8456    added to THIS.  If VCALL_OFFSET is nonzero, the word at
8457    *(*this + vcall_offset) should be added to THIS.  */
8458
8459 static void
8460 ia64_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
8461                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
8462                       tree function)
8463 {
8464   rtx this, insn, funexp;
8465   unsigned int this_parmno;
8466   unsigned int this_regno;
8467
8468   reload_completed = 1;
8469   epilogue_completed = 1;
8470   no_new_pseudos = 1;
8471   reset_block_changes ();
8472
8473   /* Set things up as ia64_expand_prologue might.  */
8474   last_scratch_gr_reg = 15;
8475
8476   memset (&current_frame_info, 0, sizeof (current_frame_info));
8477   current_frame_info.spill_cfa_off = -16;
8478   current_frame_info.n_input_regs = 1;
8479   current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
8480
8481   /* Mark the end of the (empty) prologue.  */
8482   emit_note (NOTE_INSN_PROLOGUE_END);
8483
8484   /* Figure out whether "this" will be the first parameter (the
8485      typical case) or the second parameter (as happens when the
8486      virtual function returns certain class objects).  */
8487   this_parmno
8488     = (ia64_struct_retval_addr_is_first_parm_p (TREE_TYPE (thunk))
8489        ? 1 : 0);
8490   this_regno = IN_REG (this_parmno);
8491   if (!TARGET_REG_NAMES)
8492     reg_names[this_regno] = ia64_reg_numbers[this_parmno];
8493
8494   this = gen_rtx_REG (Pmode, this_regno);
8495   if (TARGET_ILP32)
8496     {
8497       rtx tmp = gen_rtx_REG (ptr_mode, this_regno);
8498       REG_POINTER (tmp) = 1;
8499       if (delta && CONST_OK_FOR_I (delta))
8500         {
8501           emit_insn (gen_ptr_extend_plus_imm (this, tmp, GEN_INT (delta)));
8502           delta = 0;
8503         }
8504       else
8505         emit_insn (gen_ptr_extend (this, tmp));
8506     }
8507
8508   /* Apply the constant offset, if required.  */
8509   if (delta)
8510     {
8511       rtx delta_rtx = GEN_INT (delta);
8512
8513       if (!CONST_OK_FOR_I (delta))
8514         {
8515           rtx tmp = gen_rtx_REG (Pmode, 2);
8516           emit_move_insn (tmp, delta_rtx);
8517           delta_rtx = tmp;
8518         }
8519       emit_insn (gen_adddi3 (this, this, delta_rtx));
8520     }
8521
8522   /* Apply the offset from the vtable, if required.  */
8523   if (vcall_offset)
8524     {
8525       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
8526       rtx tmp = gen_rtx_REG (Pmode, 2);
8527
8528       if (TARGET_ILP32)
8529         {
8530           rtx t = gen_rtx_REG (ptr_mode, 2);
8531           REG_POINTER (t) = 1;
8532           emit_move_insn (t, gen_rtx_MEM (ptr_mode, this));
8533           if (CONST_OK_FOR_I (vcall_offset))
8534             {
8535               emit_insn (gen_ptr_extend_plus_imm (tmp, t, 
8536                                                   vcall_offset_rtx));
8537               vcall_offset = 0;
8538             }
8539           else
8540             emit_insn (gen_ptr_extend (tmp, t));
8541         }
8542       else
8543         emit_move_insn (tmp, gen_rtx_MEM (Pmode, this));
8544
8545       if (vcall_offset)
8546         {
8547           if (!CONST_OK_FOR_J (vcall_offset))
8548             {
8549               rtx tmp2 = gen_rtx_REG (Pmode, next_scratch_gr_reg ());
8550               emit_move_insn (tmp2, vcall_offset_rtx);
8551               vcall_offset_rtx = tmp2;
8552             }
8553           emit_insn (gen_adddi3 (tmp, tmp, vcall_offset_rtx));
8554         }
8555
8556       if (TARGET_ILP32)
8557         emit_move_insn (gen_rtx_REG (ptr_mode, 2), 
8558                         gen_rtx_MEM (ptr_mode, tmp));
8559       else
8560         emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
8561
8562       emit_insn (gen_adddi3 (this, this, tmp));
8563     }
8564
8565   /* Generate a tail call to the target function.  */
8566   if (! TREE_USED (function))
8567     {
8568       assemble_external (function);
8569       TREE_USED (function) = 1;
8570     }
8571   funexp = XEXP (DECL_RTL (function), 0);
8572   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
8573   ia64_expand_call (NULL_RTX, funexp, NULL_RTX, 1);
8574   insn = get_last_insn ();
8575   SIBLING_CALL_P (insn) = 1;
8576
8577   /* Code generation for calls relies on splitting.  */
8578   reload_completed = 1;
8579   epilogue_completed = 1;
8580   try_split (PATTERN (insn), insn, 0);
8581
8582   emit_barrier ();
8583
8584   /* Run just enough of rest_of_compilation to get the insns emitted.
8585      There's not really enough bulk here to make other passes such as
8586      instruction scheduling worth while.  Note that use_thunk calls
8587      assemble_start_function and assemble_end_function.  */
8588
8589   insn_locators_initialize ();
8590   emit_all_insn_group_barriers (NULL);
8591   insn = get_insns ();
8592   shorten_branches (insn);
8593   final_start_function (insn, file, 1);
8594   final (insn, file, 1);
8595   final_end_function ();
8596
8597   reload_completed = 0;
8598   epilogue_completed = 0;
8599   no_new_pseudos = 0;
8600 }
8601
8602 /* Worker function for TARGET_STRUCT_VALUE_RTX.  */
8603
8604 static rtx
8605 ia64_struct_value_rtx (tree fntype,
8606                        int incoming ATTRIBUTE_UNUSED)
8607 {
8608   if (fntype && ia64_struct_retval_addr_is_first_parm_p (fntype))
8609     return NULL_RTX;
8610   return gen_rtx_REG (Pmode, GR_REG (8));
8611 }
8612
8613 static bool
8614 ia64_scalar_mode_supported_p (enum machine_mode mode)
8615 {
8616   switch (mode)
8617     {
8618     case QImode:
8619     case HImode:
8620     case SImode:
8621     case DImode:
8622     case TImode:
8623       return true;
8624
8625     case SFmode:
8626     case DFmode:
8627     case XFmode:
8628     case RFmode:
8629       return true;
8630
8631     case TFmode:
8632       return TARGET_HPUX;
8633
8634     default:
8635       return false;
8636     }
8637 }
8638
8639 static bool
8640 ia64_vector_mode_supported_p (enum machine_mode mode)
8641 {
8642   switch (mode)
8643     {
8644     case V8QImode:
8645     case V4HImode:
8646     case V2SImode:
8647       return true;
8648
8649     case V2SFmode:
8650       return true;
8651
8652     default:
8653       return false;
8654     }
8655 }
8656
8657 void
8658 ia64_output_function_profiler (FILE *file, int labelno)
8659 {
8660   if (TARGET_GNU_AS)
8661     fputs ("\t.prologue 4, r40\n", file);
8662   else
8663     fputs ("\t.prologue\n\t.save ar.pfs, r40\n", file);
8664   fputs ("\talloc out0 = ar.pfs, 8, 0, 4, 0\n", file);
8665
8666   if (NO_PROFILE_COUNTERS)
8667     fputs ("\tmov out3 = r0\n\t;;\n", file);
8668   else
8669     {
8670       char buf[20];
8671       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
8672
8673       if (TARGET_AUTO_PIC)
8674         fputs ("\tmovl out3 = @gprel(", file);
8675       else
8676         fputs ("\taddl out3 = @ltoff(", file);
8677       assemble_name (file, buf);
8678       if (TARGET_AUTO_PIC)
8679         fputs (")\n\t;;\n", file);
8680       else
8681         fputs ("), r1\n\t;;\n", file);
8682     }
8683
8684   fputs ("\t.save rp, r42\n", file);
8685   fputs ("\tmov out2 = b0\n", file);
8686   fputs ("\t.body\n", file);
8687   fputs ("\tmov out1 = r1\n", file);
8688   fputs ("\tbr.call.sptk.many b0 = _mcount\n\t;;\n", file);
8689 }
8690
8691 static GTY(()) rtx mcount_func_rtx;
8692 static rtx
8693 gen_mcount_func_rtx (void)
8694 {
8695   if (!mcount_func_rtx)
8696     mcount_func_rtx = init_one_libfunc ("_mcount");
8697   return mcount_func_rtx;
8698 }
8699
8700 void
8701 ia64_profile_hook (int labelno)
8702 {
8703   rtx label, ip;
8704
8705   if (NO_PROFILE_COUNTERS)
8706     label = const0_rtx;
8707   else
8708     {
8709       char buf[30];
8710       const char *label_name;
8711       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
8712       label_name = (*targetm.strip_name_encoding) (ggc_strdup (buf));
8713       label = gen_rtx_SYMBOL_REF (Pmode, label_name);
8714       SYMBOL_REF_FLAGS (label) = SYMBOL_FLAG_LOCAL;
8715     }
8716   ip = gen_reg_rtx (Pmode);
8717   emit_insn (gen_ip_value (ip));
8718   emit_library_call (gen_mcount_func_rtx (), LCT_NORMAL,
8719                      VOIDmode, 3,
8720                      gen_rtx_REG (Pmode, BR_REG (0)), Pmode,
8721                      ip, Pmode,
8722                      label, Pmode);
8723 }
8724
8725 /* Return the mangling of TYPE if it is an extended fundamental type.  */
8726
8727 static const char *
8728 ia64_mangle_fundamental_type (tree type)
8729 {
8730   /* On HP-UX, "long double" is mangled as "e" so __float128 is
8731      mangled as "e".  */
8732   if (!TARGET_HPUX && TYPE_MODE (type) == TFmode)
8733     return "g";
8734   /* On HP-UX, "e" is not available as a mangling of __float80 so use
8735      an extended mangling.  Elsewhere, "e" is available since long
8736      double is 80 bits.  */
8737   if (TYPE_MODE (type) == XFmode)
8738     return TARGET_HPUX ? "u9__float80" : "e";
8739   if (TYPE_MODE (type) == RFmode)
8740     return "u7__fpreg";
8741   return NULL;
8742 }
8743
8744 /* Return the diagnostic message string if conversion from FROMTYPE to
8745    TOTYPE is not allowed, NULL otherwise.  */
8746 static const char *
8747 ia64_invalid_conversion (tree fromtype, tree totype)
8748 {
8749   /* Reject nontrivial conversion to or from __fpreg.  */
8750   if (TYPE_MODE (fromtype) == RFmode
8751       && TYPE_MODE (totype) != RFmode
8752       && TYPE_MODE (totype) != VOIDmode)
8753     return N_("invalid conversion from %<__fpreg%>");
8754   if (TYPE_MODE (totype) == RFmode
8755       && TYPE_MODE (fromtype) != RFmode)
8756     return N_("invalid conversion to %<__fpreg%>");
8757   return NULL;
8758 }
8759
8760 /* Return the diagnostic message string if the unary operation OP is
8761    not permitted on TYPE, NULL otherwise.  */
8762 static const char *
8763 ia64_invalid_unary_op (int op, tree type)
8764 {
8765   /* Reject operations on __fpreg other than unary + or &.  */
8766   if (TYPE_MODE (type) == RFmode
8767       && op != CONVERT_EXPR
8768       && op != ADDR_EXPR)
8769     return N_("invalid operation on %<__fpreg%>");
8770   return NULL;
8771 }
8772
8773 /* Return the diagnostic message string if the binary operation OP is
8774    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
8775 static const char *
8776 ia64_invalid_binary_op (int op ATTRIBUTE_UNUSED, tree type1, tree type2)
8777 {
8778   /* Reject operations on __fpreg.  */
8779   if (TYPE_MODE (type1) == RFmode || TYPE_MODE (type2) == RFmode)
8780     return N_("invalid operation on %<__fpreg%>");
8781   return NULL;
8782 }
8783
8784 #include "gt-ia64.h"