OSDN Git Service

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