OSDN Git Service

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