OSDN Git Service

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