OSDN Git Service

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