OSDN Git Service

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