OSDN Git Service

PR target/38842
[pf3gnuchains/gcc-fork.git] / gcc / config / mcore / mcore.c
1 /* Output routines for Motorola MCore processor
2    Copyright (C) 1993, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007
3    Free Software Foundation, Inc.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it
8    under the terms of the GNU General Public License as published
9    by the Free Software Foundation; either version 3, or (at your
10    option) any later version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT
13    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
15    License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING3.  If not see
19    <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "tm_p.h"
28 #include "assert.h"
29 #include "mcore.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 "obstack.h"
39 #include "expr.h"
40 #include "reload.h"
41 #include "recog.h"
42 #include "function.h"
43 #include "ggc.h"
44 #include "toplev.h"
45 #include "target.h"
46 #include "target-def.h"
47 #include "df.h"
48
49 /* Maximum size we are allowed to grow the stack in a single operation.
50    If we want more, we must do it in increments of at most this size.
51    If this value is 0, we don't check at all.  */
52 int mcore_stack_increment = STACK_UNITS_MAXSTEP;
53
54 /* For dumping information about frame sizes.  */
55 char * mcore_current_function_name = 0;
56 long   mcore_current_compilation_timestamp = 0;
57
58 /* Global variables for machine-dependent things.  */
59
60 /* Saved operands from the last compare to use when we generate an scc
61   or bcc insn.  */
62 rtx arch_compare_op0;
63 rtx arch_compare_op1;
64
65 /* Provides the class number of the smallest class containing
66    reg number.  */
67 const int regno_reg_class[FIRST_PSEUDO_REGISTER] =
68 {
69   GENERAL_REGS, ONLYR1_REGS,  LRW_REGS,     LRW_REGS,
70   LRW_REGS,     LRW_REGS,     LRW_REGS,     LRW_REGS,
71   LRW_REGS,     LRW_REGS,     LRW_REGS,     LRW_REGS,
72   LRW_REGS,     LRW_REGS,     LRW_REGS,     GENERAL_REGS,
73   GENERAL_REGS, C_REGS,       NO_REGS,      NO_REGS,
74 };
75
76 /* Provide reg_class from a letter such as appears in the machine
77    description.  */
78 const enum reg_class reg_class_from_letter[] =
79 {
80   /* a */ LRW_REGS, /* b */ ONLYR1_REGS, /* c */ C_REGS,  /* d */ NO_REGS,
81   /* e */ NO_REGS, /* f */ NO_REGS, /* g */ NO_REGS, /* h */ NO_REGS,
82   /* i */ NO_REGS, /* j */ NO_REGS, /* k */ NO_REGS, /* l */ NO_REGS,
83   /* m */ NO_REGS, /* n */ NO_REGS, /* o */ NO_REGS, /* p */ NO_REGS,
84   /* q */ NO_REGS, /* r */ GENERAL_REGS, /* s */ NO_REGS, /* t */ NO_REGS,
85   /* u */ NO_REGS, /* v */ NO_REGS, /* w */ NO_REGS, /* x */ ALL_REGS,
86   /* y */ NO_REGS, /* z */ NO_REGS
87 };
88
89 struct mcore_frame
90 {
91   int arg_size;                 /* Stdarg spills (bytes).  */
92   int reg_size;                 /* Non-volatile reg saves (bytes).  */
93   int reg_mask;                 /* Non-volatile reg saves.  */
94   int local_size;               /* Locals.  */
95   int outbound_size;            /* Arg overflow on calls out.  */
96   int pad_outbound;
97   int pad_local;
98   int pad_reg;
99   /* Describe the steps we'll use to grow it.  */
100 #define MAX_STACK_GROWS 4       /* Gives us some spare space.  */
101   int growth[MAX_STACK_GROWS];
102   int arg_offset;
103   int reg_offset;
104   int reg_growth;
105   int local_growth;
106 };
107
108 typedef enum
109 {
110   COND_NO,
111   COND_MOV_INSN,
112   COND_CLR_INSN,
113   COND_INC_INSN,
114   COND_DEC_INSN,
115   COND_BRANCH_INSN
116 }
117 cond_type;
118
119 static void       output_stack_adjust           (int, int);
120 static int        calc_live_regs                (int *);
121 static int        try_constant_tricks           (long, HOST_WIDE_INT *, HOST_WIDE_INT *);
122 static const char *     output_inline_const     (enum machine_mode, rtx *);
123 static void       layout_mcore_frame            (struct mcore_frame *);
124 static void       mcore_setup_incoming_varargs  (CUMULATIVE_ARGS *, enum machine_mode, tree, int *, int);
125 static cond_type  is_cond_candidate             (rtx);
126 static rtx        emit_new_cond_insn            (rtx, int);
127 static rtx        conditionalize_block          (rtx);
128 static void       conditionalize_optimization   (void);
129 static void       mcore_reorg                   (void);
130 static rtx        handle_structs_in_regs        (enum machine_mode, const_tree, int);
131 static void       mcore_mark_dllexport          (tree);
132 static void       mcore_mark_dllimport          (tree);
133 static int        mcore_dllexport_p             (tree);
134 static int        mcore_dllimport_p             (tree);
135 const struct attribute_spec mcore_attribute_table[];
136 static tree       mcore_handle_naked_attribute  (tree *, tree, tree, int, bool *);
137 #ifdef OBJECT_FORMAT_ELF
138 static void       mcore_asm_named_section       (const char *,
139                                                  unsigned int, tree);
140 #endif
141 static void       mcore_unique_section          (tree, int);
142 static void mcore_encode_section_info           (tree, rtx, int);
143 static const char *mcore_strip_name_encoding    (const char *);
144 static int        mcore_const_costs             (rtx, RTX_CODE);
145 static int        mcore_and_cost                (rtx);
146 static int        mcore_ior_cost                (rtx);
147 static bool       mcore_rtx_costs               (rtx, int, int, int *, bool);
148 static void       mcore_external_libcall        (rtx);
149 static bool       mcore_return_in_memory        (const_tree, const_tree);
150 static int        mcore_arg_partial_bytes       (CUMULATIVE_ARGS *,
151                                                  enum machine_mode,
152                                                  tree, bool);
153
154 \f
155 /* Initialize the GCC target structure.  */
156 #undef  TARGET_ASM_EXTERNAL_LIBCALL
157 #define TARGET_ASM_EXTERNAL_LIBCALL     mcore_external_libcall
158
159 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
160 #undef  TARGET_MERGE_DECL_ATTRIBUTES
161 #define TARGET_MERGE_DECL_ATTRIBUTES    merge_dllimport_decl_attributes
162 #endif
163
164 #ifdef OBJECT_FORMAT_ELF
165 #undef  TARGET_ASM_UNALIGNED_HI_OP
166 #define TARGET_ASM_UNALIGNED_HI_OP "\t.short\t"
167 #undef  TARGET_ASM_UNALIGNED_SI_OP
168 #define TARGET_ASM_UNALIGNED_SI_OP "\t.long\t"
169 #endif
170
171 #undef  TARGET_ATTRIBUTE_TABLE
172 #define TARGET_ATTRIBUTE_TABLE          mcore_attribute_table
173 #undef  TARGET_ASM_UNIQUE_SECTION
174 #define TARGET_ASM_UNIQUE_SECTION       mcore_unique_section
175 #undef  TARGET_ASM_FUNCTION_RODATA_SECTION
176 #define TARGET_ASM_FUNCTION_RODATA_SECTION default_no_function_rodata_section
177 #undef  TARGET_DEFAULT_TARGET_FLAGS
178 #define TARGET_DEFAULT_TARGET_FLAGS     TARGET_DEFAULT
179 #undef  TARGET_ENCODE_SECTION_INFO
180 #define TARGET_ENCODE_SECTION_INFO      mcore_encode_section_info
181 #undef  TARGET_STRIP_NAME_ENCODING
182 #define TARGET_STRIP_NAME_ENCODING      mcore_strip_name_encoding
183 #undef  TARGET_RTX_COSTS
184 #define TARGET_RTX_COSTS                mcore_rtx_costs
185 #undef  TARGET_ADDRESS_COST
186 #define TARGET_ADDRESS_COST             hook_int_rtx_bool_0
187 #undef  TARGET_MACHINE_DEPENDENT_REORG
188 #define TARGET_MACHINE_DEPENDENT_REORG  mcore_reorg
189
190 #undef  TARGET_PROMOTE_FUNCTION_ARGS
191 #define TARGET_PROMOTE_FUNCTION_ARGS    hook_bool_const_tree_true
192 #undef  TARGET_PROMOTE_FUNCTION_RETURN
193 #define TARGET_PROMOTE_FUNCTION_RETURN  hook_bool_const_tree_true
194 #undef  TARGET_PROMOTE_PROTOTYPES
195 #define TARGET_PROMOTE_PROTOTYPES       hook_bool_const_tree_true
196
197 #undef  TARGET_RETURN_IN_MEMORY
198 #define TARGET_RETURN_IN_MEMORY         mcore_return_in_memory
199 #undef  TARGET_MUST_PASS_IN_STACK
200 #define TARGET_MUST_PASS_IN_STACK       must_pass_in_stack_var_size
201 #undef  TARGET_PASS_BY_REFERENCE
202 #define TARGET_PASS_BY_REFERENCE  hook_pass_by_reference_must_pass_in_stack
203 #undef  TARGET_ARG_PARTIAL_BYTES
204 #define TARGET_ARG_PARTIAL_BYTES        mcore_arg_partial_bytes
205
206 #undef  TARGET_SETUP_INCOMING_VARARGS
207 #define TARGET_SETUP_INCOMING_VARARGS   mcore_setup_incoming_varargs
208
209 struct gcc_target targetm = TARGET_INITIALIZER;
210 \f
211 /* Adjust the stack and return the number of bytes taken to do it.  */
212 static void
213 output_stack_adjust (int direction, int size)
214 {
215   /* If extending stack a lot, we do it incrementally.  */
216   if (direction < 0 && size > mcore_stack_increment && mcore_stack_increment > 0)
217     {
218       rtx tmp = gen_rtx_REG (SImode, 1);
219       rtx memref;
220
221       emit_insn (gen_movsi (tmp, GEN_INT (mcore_stack_increment)));
222       do
223         {
224           emit_insn (gen_subsi3 (stack_pointer_rtx, stack_pointer_rtx, tmp));
225           memref = gen_rtx_MEM (SImode, stack_pointer_rtx);
226           MEM_VOLATILE_P (memref) = 1;
227           emit_insn (gen_movsi (memref, stack_pointer_rtx));
228           size -= mcore_stack_increment;
229         }
230       while (size > mcore_stack_increment);
231
232       /* SIZE is now the residual for the last adjustment,
233          which doesn't require a probe.  */
234     }
235
236   if (size)
237     {
238       rtx insn;
239       rtx val = GEN_INT (size);
240
241       if (size > 32)
242         {
243           rtx nval = gen_rtx_REG (SImode, 1);
244           emit_insn (gen_movsi (nval, val));
245           val = nval;
246         }
247       
248       if (direction > 0)
249         insn = gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx, val);
250       else
251         insn = gen_subsi3 (stack_pointer_rtx, stack_pointer_rtx, val);
252       
253       emit_insn (insn);
254     }
255 }
256
257 /* Work out the registers which need to be saved,
258    both as a mask and a count.  */
259
260 static int
261 calc_live_regs (int * count)
262 {
263   int reg;
264   int live_regs_mask = 0;
265   
266   * count = 0;
267
268   for (reg = 0; reg < FIRST_PSEUDO_REGISTER; reg++)
269     {
270       if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
271         {
272           (*count)++;
273           live_regs_mask |= (1 << reg);
274         }
275     }
276
277   return live_regs_mask;
278 }
279
280 /* Print the operand address in x to the stream.  */
281
282 void
283 mcore_print_operand_address (FILE * stream, rtx x)
284 {
285   switch (GET_CODE (x))
286     {
287     case REG:
288       fprintf (stream, "(%s)", reg_names[REGNO (x)]);
289       break;
290       
291     case PLUS:
292       {
293         rtx base = XEXP (x, 0);
294         rtx index = XEXP (x, 1);
295
296         if (GET_CODE (base) != REG)
297           {
298             /* Ensure that BASE is a register (one of them must be).  */
299             rtx temp = base;
300             base = index;
301             index = temp;
302           }
303
304         switch (GET_CODE (index))
305           {
306           case CONST_INT:
307             fprintf (stream, "(%s," HOST_WIDE_INT_PRINT_DEC ")",
308                      reg_names[REGNO(base)], INTVAL (index));
309             break;
310
311           default:
312             gcc_unreachable ();
313           }
314       }
315
316       break;
317
318     default:
319       output_addr_const (stream, x);
320       break;
321     }
322 }
323
324 /* Print operand x (an rtx) in assembler syntax to file stream
325    according to modifier code.
326
327    'R'  print the next register or memory location along, i.e. the lsw in
328         a double word value
329    'O'  print a constant without the #
330    'M'  print a constant as its negative
331    'P'  print log2 of a power of two
332    'Q'  print log2 of an inverse of a power of two
333    'U'  print register for ldm/stm instruction
334    'X'  print byte number for xtrbN instruction.  */
335
336 void
337 mcore_print_operand (FILE * stream, rtx x, int code)
338 {
339   switch (code)
340     {
341     case 'N':
342       if (INTVAL(x) == -1)
343         fprintf (asm_out_file, "32");
344       else
345         fprintf (asm_out_file, "%d", exact_log2 (INTVAL (x) + 1));
346       break;
347     case 'P':
348       fprintf (asm_out_file, "%d", exact_log2 (INTVAL (x) & 0xffffffff));
349       break;
350     case 'Q':
351       fprintf (asm_out_file, "%d", exact_log2 (~INTVAL (x)));
352       break;
353     case 'O':
354       fprintf (asm_out_file, HOST_WIDE_INT_PRINT_DEC, INTVAL (x));
355       break;
356     case 'M':
357       fprintf (asm_out_file, HOST_WIDE_INT_PRINT_DEC, - INTVAL (x));
358       break;
359     case 'R':
360       /* Next location along in memory or register.  */
361       switch (GET_CODE (x))
362         {
363         case REG:
364           fputs (reg_names[REGNO (x) + 1], (stream));
365           break;
366         case MEM:
367           mcore_print_operand_address
368             (stream, XEXP (adjust_address (x, SImode, 4), 0));
369           break;
370         default:
371           gcc_unreachable ();
372         }
373       break;
374     case 'U':
375       fprintf (asm_out_file, "%s-%s", reg_names[REGNO (x)],
376                reg_names[REGNO (x) + 3]);
377       break;
378     case 'x':
379       fprintf (asm_out_file, HOST_WIDE_INT_PRINT_HEX, INTVAL (x));
380       break;
381     case 'X':
382       fprintf (asm_out_file, HOST_WIDE_INT_PRINT_DEC, 3 - INTVAL (x) / 8);
383       break;
384
385     default:
386       switch (GET_CODE (x))
387         {
388         case REG:
389           fputs (reg_names[REGNO (x)], (stream));
390           break;
391         case MEM:
392           output_address (XEXP (x, 0));
393           break;
394         default:
395           output_addr_const (stream, x);
396           break;
397         }
398       break;
399     }
400 }
401
402 /* What does a constant cost ?  */
403
404 static int
405 mcore_const_costs (rtx exp, enum rtx_code code)
406 {
407   HOST_WIDE_INT val = INTVAL (exp);
408
409   /* Easy constants.  */
410   if (   CONST_OK_FOR_I (val)   
411       || CONST_OK_FOR_M (val)   
412       || CONST_OK_FOR_N (val)   
413       || (code == PLUS && CONST_OK_FOR_L (val)))
414     return 1;                                   
415   else if (code == AND
416            && (   CONST_OK_FOR_M (~val)
417                || CONST_OK_FOR_N (~val)))
418     return 2;
419   else if (code == PLUS                 
420            && (   CONST_OK_FOR_I (-val) 
421                || CONST_OK_FOR_M (-val) 
422                || CONST_OK_FOR_N (-val)))       
423     return 2;                                           
424
425   return 5;                                     
426 }
427
428 /* What does an and instruction cost - we do this b/c immediates may 
429    have been relaxed.   We want to ensure that cse will cse relaxed immeds
430    out.  Otherwise we'll get bad code (multiple reloads of the same const).  */
431
432 static int
433 mcore_and_cost (rtx x)
434 {
435   HOST_WIDE_INT val;
436
437   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
438     return 2;
439
440   val = INTVAL (XEXP (x, 1));
441    
442   /* Do it directly.  */
443   if (CONST_OK_FOR_K (val) || CONST_OK_FOR_M (~val))
444     return 2;
445   /* Takes one instruction to load.  */
446   else if (const_ok_for_mcore (val))
447     return 3;
448   /* Takes two instructions to load.  */
449   else if (TARGET_HARDLIT && mcore_const_ok_for_inline (val))
450     return 4;
451
452   /* Takes a lrw to load.  */
453   return 5;
454 }
455
456 /* What does an or cost - see and_cost().  */
457
458 static int
459 mcore_ior_cost (rtx x)
460 {
461   HOST_WIDE_INT val;
462
463   if (GET_CODE (XEXP (x, 1)) != CONST_INT)
464     return 2;
465
466   val = INTVAL (XEXP (x, 1));
467
468   /* Do it directly with bclri.  */
469   if (CONST_OK_FOR_M (val))
470     return 2;
471   /* Takes one instruction to load.  */
472   else if (const_ok_for_mcore (val))
473     return 3;
474   /* Takes two instructions to load.  */
475   else if (TARGET_HARDLIT && mcore_const_ok_for_inline (val))
476     return 4;
477   
478   /* Takes a lrw to load.  */
479   return 5;
480 }
481
482 static bool
483 mcore_rtx_costs (rtx x, int code, int outer_code, int * total,
484                  bool speed ATTRIBUTE_UNUSED)
485 {
486   switch (code)
487     {
488     case CONST_INT:
489       *total = mcore_const_costs (x, outer_code);
490       return true;
491     case CONST:
492     case LABEL_REF:
493     case SYMBOL_REF:
494       *total = 5;
495       return true;
496     case CONST_DOUBLE:
497       *total = 10;
498       return true;
499
500     case AND:
501       *total = COSTS_N_INSNS (mcore_and_cost (x));
502       return true;
503
504     case IOR:
505       *total = COSTS_N_INSNS (mcore_ior_cost (x));
506       return true;
507
508     case DIV:
509     case UDIV:
510     case MOD:
511     case UMOD:
512     case FLOAT:
513     case FIX:
514       *total = COSTS_N_INSNS (100);
515       return true;
516   
517     default:
518       return false;
519     }
520 }
521
522 /* Check to see if a comparison against a constant can be made more efficient
523    by incrementing/decrementing the constant to get one that is more efficient
524    to load.  */
525
526 int
527 mcore_modify_comparison (enum rtx_code code)
528 {
529   rtx op1 = arch_compare_op1;
530   
531   if (GET_CODE (op1) == CONST_INT)
532     {
533       HOST_WIDE_INT val = INTVAL (op1);
534       
535       switch (code)
536         {
537         case LE:
538           if (CONST_OK_FOR_J (val + 1))
539             {
540               arch_compare_op1 = GEN_INT (val + 1);
541               return 1;
542             }
543           break;
544           
545         default:
546           break;
547         }
548     }
549   
550   return 0;
551 }
552
553 /* Prepare the operands for a comparison.  */
554
555 rtx
556 mcore_gen_compare_reg (enum rtx_code code)
557 {
558   rtx op0 = arch_compare_op0;
559   rtx op1 = arch_compare_op1;
560   rtx cc_reg = gen_rtx_REG (CCmode, CC_REG);
561
562   if (CONSTANT_P (op1) && GET_CODE (op1) != CONST_INT)
563     op1 = force_reg (SImode, op1);
564
565   /* cmpnei: 0-31 (K immediate)
566      cmplti: 1-32 (J immediate, 0 using btsti x,31).  */
567   switch (code)
568     {
569     case EQ:    /* Use inverted condition, cmpne.  */
570       code = NE;
571       /* Drop through.  */
572       
573     case NE:    /* Use normal condition, cmpne.  */
574       if (GET_CODE (op1) == CONST_INT && ! CONST_OK_FOR_K (INTVAL (op1)))
575         op1 = force_reg (SImode, op1);
576       break;
577
578     case LE:    /* Use inverted condition, reversed cmplt.  */
579       code = GT;
580       /* Drop through.  */
581       
582     case GT:    /* Use normal condition, reversed cmplt.  */
583       if (GET_CODE (op1) == CONST_INT)
584         op1 = force_reg (SImode, op1);
585       break;
586
587     case GE:    /* Use inverted condition, cmplt.  */
588       code = LT;
589       /* Drop through.  */
590       
591     case LT:    /* Use normal condition, cmplt.  */
592       if (GET_CODE (op1) == CONST_INT && 
593           /* covered by btsti x,31.  */
594           INTVAL (op1) != 0 &&
595           ! CONST_OK_FOR_J (INTVAL (op1)))
596         op1 = force_reg (SImode, op1);
597       break;
598
599     case GTU:   /* Use inverted condition, cmple.  */
600       /* Unsigned > 0 is the same as != 0, but we need to invert the
601          condition, so we want to set code = EQ.  This cannot be done
602          however, as the mcore does not support such a test.  Instead
603          we cope with this case in the "bgtu" pattern itself so we
604          should never reach this point.  */
605       gcc_assert (GET_CODE (op1) != CONST_INT || INTVAL (op1) != 0);
606       code = LEU;
607       /* Drop through.  */
608       
609     case LEU:   /* Use normal condition, reversed cmphs.  */
610       if (GET_CODE (op1) == CONST_INT && INTVAL (op1) != 0)
611         op1 = force_reg (SImode, op1);
612       break;
613
614     case LTU:   /* Use inverted condition, cmphs.  */
615       code = GEU;
616       /* Drop through.  */
617       
618     case GEU:   /* Use normal condition, cmphs.  */
619       if (GET_CODE (op1) == CONST_INT && INTVAL (op1) != 0)
620         op1 = force_reg (SImode, op1);
621       break;
622
623     default:
624       break;
625     }
626
627   emit_insn (gen_rtx_SET (VOIDmode, cc_reg, gen_rtx_fmt_ee (code, CCmode, op0, op1)));
628   
629   return cc_reg;
630 }
631
632 int
633 mcore_symbolic_address_p (rtx x)
634 {
635   switch (GET_CODE (x))
636     {
637     case SYMBOL_REF:
638     case LABEL_REF:
639       return 1;
640     case CONST:
641       x = XEXP (x, 0);
642       return (   (GET_CODE (XEXP (x, 0)) == SYMBOL_REF
643                || GET_CODE (XEXP (x, 0)) == LABEL_REF)
644               && GET_CODE (XEXP (x, 1)) == CONST_INT);
645     default:
646       return 0;
647     }
648 }
649
650 /* Functions to output assembly code for a function call.  */
651
652 char *
653 mcore_output_call (rtx operands[], int index)
654 {
655   static char buffer[20];
656   rtx addr = operands [index];
657   
658   if (REG_P (addr))
659     {
660       if (TARGET_CG_DATA)
661         {
662           gcc_assert (mcore_current_function_name);
663           
664           ASM_OUTPUT_CG_EDGE (asm_out_file, mcore_current_function_name,
665                               "unknown", 1);
666         }
667
668       sprintf (buffer, "jsr\t%%%d", index);
669     }
670   else
671     {
672       if (TARGET_CG_DATA)
673         {
674           gcc_assert (mcore_current_function_name);
675           gcc_assert (GET_CODE (addr) == SYMBOL_REF);
676           
677           ASM_OUTPUT_CG_EDGE (asm_out_file, mcore_current_function_name,
678                               XSTR (addr, 0), 0);
679         }
680       
681       sprintf (buffer, "jbsr\t%%%d", index);
682     }
683
684   return buffer;
685 }
686
687 /* Can we load a constant with a single instruction ?  */
688
689 int
690 const_ok_for_mcore (HOST_WIDE_INT value)
691 {
692   if (value >= 0 && value <= 127)
693     return 1;
694   
695   /* Try exact power of two.  */
696   if (CONST_OK_FOR_M (value))
697     return 1;
698   
699   /* Try exact power of two - 1.  */
700   if (CONST_OK_FOR_N (value) && value != -1)
701     return 1;
702   
703   return 0;
704 }
705
706 /* Can we load a constant inline with up to 2 instructions ?  */
707
708 int
709 mcore_const_ok_for_inline (HOST_WIDE_INT value)
710 {
711   HOST_WIDE_INT x, y;
712    
713   return try_constant_tricks (value, & x, & y) > 0;
714 }
715
716 /* Are we loading the constant using a not ?  */
717
718 int
719 mcore_const_trick_uses_not (HOST_WIDE_INT value)
720 {
721   HOST_WIDE_INT x, y;
722
723   return try_constant_tricks (value, & x, & y) == 2; 
724 }       
725
726 /* Try tricks to load a constant inline and return the trick number if
727    success (0 is non-inlinable).
728   
729    0: not inlinable
730    1: single instruction (do the usual thing)
731    2: single insn followed by a 'not'
732    3: single insn followed by a subi
733    4: single insn followed by an addi
734    5: single insn followed by rsubi
735    6: single insn followed by bseti
736    7: single insn followed by bclri
737    8: single insn followed by rotli
738    9: single insn followed by lsli
739    10: single insn followed by ixh
740    11: single insn followed by ixw.  */
741
742 static int
743 try_constant_tricks (HOST_WIDE_INT value, HOST_WIDE_INT * x, HOST_WIDE_INT * y)
744 {
745   HOST_WIDE_INT i;
746   unsigned HOST_WIDE_INT bit, shf, rot;
747
748   if (const_ok_for_mcore (value))
749     return 1;   /* Do the usual thing.  */
750   
751   if (! TARGET_HARDLIT) 
752     return 0;
753
754   if (const_ok_for_mcore (~value))
755     {
756       *x = ~value;
757       return 2;
758     }
759
760   for (i = 1; i <= 32; i++)
761     {
762       if (const_ok_for_mcore (value - i))
763         {
764           *x = value - i;
765           *y = i;
766
767           return 3;
768         }
769
770       if (const_ok_for_mcore (value + i))
771         {
772           *x = value + i;
773           *y = i;
774
775           return 4;
776         }
777     }
778
779   bit = 0x80000000ULL;
780
781   for (i = 0; i <= 31; i++)
782     {
783       if (const_ok_for_mcore (i - value))
784         {
785           *x = i - value;
786           *y = i;
787
788           return 5;
789         }
790
791       if (const_ok_for_mcore (value & ~bit))
792         {
793           *y = bit;
794           *x = value & ~bit;
795           return 6;
796         }
797
798       if (const_ok_for_mcore (value | bit))
799         {
800           *y = ~bit;
801           *x = value | bit;
802
803           return 7;
804         }
805
806       bit >>= 1;
807     }
808
809   shf = value;
810   rot = value;
811
812   for (i = 1; i < 31; i++)
813     {
814       int c;
815
816       /* MCore has rotate left.  */
817       c = rot << 31;
818       rot >>= 1;
819       rot &= 0x7FFFFFFF;
820       rot |= c;   /* Simulate rotate.  */
821
822       if (const_ok_for_mcore (rot))
823         {
824           *y = i;
825           *x = rot;
826
827           return 8;
828         }
829
830       if (shf & 1)
831         shf = 0;        /* Can't use logical shift, low order bit is one.  */
832
833       shf >>= 1;
834
835       if (shf != 0 && const_ok_for_mcore (shf))
836         {
837           *y = i;
838           *x = shf;
839
840           return 9;
841         }
842     }
843
844   if ((value % 3) == 0 && const_ok_for_mcore (value / 3))
845     {
846       *x = value / 3;
847
848       return 10;
849     }
850
851   if ((value % 5) == 0 && const_ok_for_mcore (value / 5))
852     {
853       *x = value / 5;
854
855       return 11;
856     }
857   
858   return 0;
859 }
860
861 /* Check whether reg is dead at first.  This is done by searching ahead
862    for either the next use (i.e., reg is live), a death note, or a set of
863    reg.  Don't just use dead_or_set_p() since reload does not always mark 
864    deaths (especially if PRESERVE_DEATH_NOTES_REGNO_P is not defined). We
865    can ignore subregs by extracting the actual register.  BRC  */
866
867 int
868 mcore_is_dead (rtx first, rtx reg)
869 {
870   rtx insn;
871
872   /* For mcore, subregs can't live independently of their parent regs.  */
873   if (GET_CODE (reg) == SUBREG)
874     reg = SUBREG_REG (reg);
875
876   /* Dies immediately.  */
877   if (dead_or_set_p (first, reg))
878     return 1;
879
880   /* Look for conclusive evidence of live/death, otherwise we have
881      to assume that it is live.  */
882   for (insn = NEXT_INSN (first); insn; insn = NEXT_INSN (insn))
883     {
884       if (GET_CODE (insn) == JUMP_INSN)
885         return 0;       /* We lose track, assume it is alive.  */
886
887       else if (GET_CODE(insn) == CALL_INSN)
888         {
889           /* Call's might use it for target or register parms.  */
890           if (reg_referenced_p (reg, PATTERN (insn))
891               || find_reg_fusage (insn, USE, reg))
892             return 0;
893           else if (dead_or_set_p (insn, reg))
894             return 1;
895         }
896       else if (GET_CODE (insn) == INSN)
897         {
898           if (reg_referenced_p (reg, PATTERN (insn)))
899             return 0;
900           else if (dead_or_set_p (insn, reg))
901             return 1;
902         }
903     }
904
905   /* No conclusive evidence either way, we cannot take the chance
906      that control flow hid the use from us -- "I'm not dead yet".  */
907   return 0;
908 }
909
910 /* Count the number of ones in mask.  */
911
912 int
913 mcore_num_ones (HOST_WIDE_INT mask)
914 {
915   /* A trick to count set bits recently posted on comp.compilers.  */
916   mask =  (mask >> 1  & 0x55555555) + (mask & 0x55555555);
917   mask = ((mask >> 2) & 0x33333333) + (mask & 0x33333333);
918   mask = ((mask >> 4) + mask) & 0x0f0f0f0f;
919   mask = ((mask >> 8) + mask);
920
921   return (mask + (mask >> 16)) & 0xff;
922 }
923
924 /* Count the number of zeros in mask.  */
925
926 int
927 mcore_num_zeros (HOST_WIDE_INT mask)
928 {
929   return 32 - mcore_num_ones (mask);
930 }
931
932 /* Determine byte being masked.  */
933
934 int
935 mcore_byte_offset (unsigned int mask)
936 {
937   if (mask == 0x00ffffffL)
938     return 0;
939   else if (mask == 0xff00ffffL)
940     return 1;
941   else if (mask == 0xffff00ffL)
942     return 2;
943   else if (mask == 0xffffff00L)
944     return 3;
945
946   return -1;
947 }
948
949 /* Determine halfword being masked.  */
950
951 int
952 mcore_halfword_offset (unsigned int mask)
953 {
954   if (mask == 0x0000ffffL)
955     return 0;
956   else if (mask == 0xffff0000L)
957     return 1;
958
959   return -1;
960 }
961
962 /* Output a series of bseti's corresponding to mask.  */
963
964 const char *
965 mcore_output_bseti (rtx dst, int mask)
966 {
967   rtx out_operands[2];
968   int bit;
969
970   out_operands[0] = dst;
971
972   for (bit = 0; bit < 32; bit++)
973     {
974       if ((mask & 0x1) == 0x1)
975         {
976           out_operands[1] = GEN_INT (bit);
977           
978           output_asm_insn ("bseti\t%0,%1", out_operands);
979         }
980       mask >>= 1;
981     }  
982
983   return "";
984 }
985
986 /* Output a series of bclri's corresponding to mask.  */
987
988 const char *
989 mcore_output_bclri (rtx dst, int mask)
990 {
991   rtx out_operands[2];
992   int bit;
993
994   out_operands[0] = dst;
995
996   for (bit = 0; bit < 32; bit++)
997     {
998       if ((mask & 0x1) == 0x0)
999         {
1000           out_operands[1] = GEN_INT (bit);
1001           
1002           output_asm_insn ("bclri\t%0,%1", out_operands);
1003         }
1004       
1005       mask >>= 1;
1006     }  
1007
1008   return "";
1009 }
1010
1011 /* Output a conditional move of two constants that are +/- 1 within each
1012    other.  See the "movtK" patterns in mcore.md.   I'm not sure this is
1013    really worth the effort.  */
1014
1015 const char *
1016 mcore_output_cmov (rtx operands[], int cmp_t, const char * test)
1017 {
1018   HOST_WIDE_INT load_value;
1019   HOST_WIDE_INT adjust_value;
1020   rtx out_operands[4];
1021
1022   out_operands[0] = operands[0];
1023
1024   /* Check to see which constant is loadable.  */
1025   if (const_ok_for_mcore (INTVAL (operands[1])))
1026     {
1027       out_operands[1] = operands[1];
1028       out_operands[2] = operands[2];
1029     }
1030   else if (const_ok_for_mcore (INTVAL (operands[2])))
1031     {
1032       out_operands[1] = operands[2];
1033       out_operands[2] = operands[1];
1034
1035       /* Complement test since constants are swapped.  */
1036       cmp_t = (cmp_t == 0);
1037     }
1038   load_value   = INTVAL (out_operands[1]);
1039   adjust_value = INTVAL (out_operands[2]);
1040
1041   /* First output the test if folded into the pattern.  */
1042
1043   if (test) 
1044     output_asm_insn (test, operands);
1045
1046   /* Load the constant - for now, only support constants that can be
1047      generated with a single instruction.  maybe add general inlinable
1048      constants later (this will increase the # of patterns since the
1049      instruction sequence has a different length attribute).  */
1050   if (load_value >= 0 && load_value <= 127)
1051     output_asm_insn ("movi\t%0,%1", out_operands);
1052   else if (CONST_OK_FOR_M (load_value))
1053     output_asm_insn ("bgeni\t%0,%P1", out_operands);
1054   else if (CONST_OK_FOR_N (load_value))
1055     output_asm_insn ("bmaski\t%0,%N1", out_operands);
1056    
1057   /* Output the constant adjustment.  */
1058   if (load_value > adjust_value)
1059     {
1060       if (cmp_t)
1061         output_asm_insn ("decf\t%0", out_operands);
1062       else
1063         output_asm_insn ("dect\t%0", out_operands);
1064     }
1065   else
1066     {
1067       if (cmp_t)
1068         output_asm_insn ("incf\t%0", out_operands);
1069       else
1070         output_asm_insn ("inct\t%0", out_operands);
1071     }
1072
1073   return "";
1074 }
1075
1076 /* Outputs the peephole for moving a constant that gets not'ed followed 
1077    by an and (i.e. combine the not and the and into andn). BRC  */
1078
1079 const char *
1080 mcore_output_andn (rtx insn ATTRIBUTE_UNUSED, rtx operands[])
1081 {
1082   HOST_WIDE_INT x, y;
1083   rtx out_operands[3];
1084   const char * load_op;
1085   char buf[256];
1086   int trick_no;
1087
1088   trick_no = try_constant_tricks (INTVAL (operands[1]), &x, &y);
1089   gcc_assert (trick_no == 2);
1090
1091   out_operands[0] = operands[0];
1092   out_operands[1] = GEN_INT (x);
1093   out_operands[2] = operands[2];
1094
1095   if (x >= 0 && x <= 127)
1096     load_op = "movi\t%0,%1";
1097   
1098   /* Try exact power of two.  */
1099   else if (CONST_OK_FOR_M (x))
1100     load_op = "bgeni\t%0,%P1";
1101   
1102   /* Try exact power of two - 1.  */
1103   else if (CONST_OK_FOR_N (x))
1104     load_op = "bmaski\t%0,%N1";
1105   
1106   else
1107     {
1108       load_op = "BADMOVI-andn\t%0, %1";
1109       gcc_unreachable ();
1110     }
1111
1112   sprintf (buf, "%s\n\tandn\t%%2,%%0", load_op);
1113   output_asm_insn (buf, out_operands);
1114
1115   return "";
1116 }
1117
1118 /* Output an inline constant.  */
1119
1120 static const char *
1121 output_inline_const (enum machine_mode mode, rtx operands[])
1122 {
1123   HOST_WIDE_INT x = 0, y = 0;
1124   int trick_no;
1125   rtx out_operands[3];
1126   char buf[256];
1127   char load_op[256];
1128   const char *dst_fmt;
1129   HOST_WIDE_INT value;
1130
1131   value = INTVAL (operands[1]);
1132
1133   trick_no = try_constant_tricks (value, &x, &y);
1134   /* lrw's are handled separately: Large inlinable constants never get
1135      turned into lrw's.  Our caller uses try_constant_tricks to back
1136      off to an lrw rather than calling this routine.  */
1137   gcc_assert (trick_no != 0);
1138   
1139   if (trick_no == 1)
1140     x = value;
1141
1142   /* operands: 0 = dst, 1 = load immed., 2 = immed. adjustment.  */
1143   out_operands[0] = operands[0];
1144   out_operands[1] = GEN_INT (x);
1145   
1146   if (trick_no > 2)
1147     out_operands[2] = GEN_INT (y);
1148
1149   /* Select dst format based on mode.  */
1150   if (mode == DImode && (! TARGET_LITTLE_END))
1151     dst_fmt = "%R0";
1152   else
1153     dst_fmt = "%0";
1154
1155   if (x >= 0 && x <= 127)
1156     sprintf (load_op, "movi\t%s,%%1", dst_fmt);
1157   
1158   /* Try exact power of two.  */
1159   else if (CONST_OK_FOR_M (x))
1160     sprintf (load_op, "bgeni\t%s,%%P1", dst_fmt);
1161   
1162   /* Try exact power of two - 1.  */
1163   else if (CONST_OK_FOR_N (x))
1164     sprintf (load_op, "bmaski\t%s,%%N1", dst_fmt);
1165   
1166   else
1167     {
1168       sprintf (load_op, "BADMOVI-inline_const %s, %%1", dst_fmt);
1169       gcc_unreachable ();
1170     }      
1171
1172   switch (trick_no)
1173     {
1174     case 1:
1175       strcpy (buf, load_op);
1176       break;
1177     case 2:   /* not */
1178       sprintf (buf, "%s\n\tnot\t%s\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1179       break;
1180     case 3:   /* add */
1181       sprintf (buf, "%s\n\taddi\t%s,%%2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1182       break;
1183     case 4:   /* sub */
1184       sprintf (buf, "%s\n\tsubi\t%s,%%2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1185       break;
1186     case 5:   /* rsub */
1187       /* Never happens unless -mrsubi, see try_constant_tricks().  */
1188       sprintf (buf, "%s\n\trsubi\t%s,%%2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1189       break;
1190     case 6:   /* bseti */
1191       sprintf (buf, "%s\n\tbseti\t%s,%%P2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1192       break;
1193     case 7:   /* bclr */
1194       sprintf (buf, "%s\n\tbclri\t%s,%%Q2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1195       break;
1196     case 8:   /* rotl */
1197       sprintf (buf, "%s\n\trotli\t%s,%%2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1198       break;
1199     case 9:   /* lsl */
1200       sprintf (buf, "%s\n\tlsli\t%s,%%2\t// %ld 0x%lx", load_op, dst_fmt, value, value);
1201       break;
1202     case 10:  /* ixh */
1203       sprintf (buf, "%s\n\tixh\t%s,%s\t// %ld 0x%lx", load_op, dst_fmt, dst_fmt, value, value);
1204       break;
1205     case 11:  /* ixw */
1206       sprintf (buf, "%s\n\tixw\t%s,%s\t// %ld 0x%lx", load_op, dst_fmt, dst_fmt, value, value);
1207       break;
1208     default:
1209       return "";
1210     }
1211   
1212   output_asm_insn (buf, out_operands);
1213
1214   return "";
1215 }
1216
1217 /* Output a move of a word or less value.  */
1218
1219 const char *
1220 mcore_output_move (rtx insn ATTRIBUTE_UNUSED, rtx operands[],
1221                    enum machine_mode mode ATTRIBUTE_UNUSED)
1222 {
1223   rtx dst = operands[0];
1224   rtx src = operands[1];
1225
1226   if (GET_CODE (dst) == REG)
1227     {
1228       if (GET_CODE (src) == REG)
1229         {               
1230           if (REGNO (src) == CC_REG)            /* r-c */
1231             return "mvc\t%0"; 
1232           else 
1233             return "mov\t%0,%1";                /* r-r*/
1234         }
1235       else if (GET_CODE (src) == MEM)
1236         {
1237           if (GET_CODE (XEXP (src, 0)) == LABEL_REF) 
1238             return "lrw\t%0,[%1]";              /* a-R */
1239           else
1240             switch (GET_MODE (src))             /* r-m */
1241               {
1242               case SImode:
1243                 return "ldw\t%0,%1";
1244               case HImode:
1245                 return "ld.h\t%0,%1";
1246               case QImode:
1247                 return "ld.b\t%0,%1";
1248               default:
1249                 gcc_unreachable ();
1250               }
1251         }
1252       else if (GET_CODE (src) == CONST_INT)
1253         {
1254           HOST_WIDE_INT x, y;
1255           
1256           if (CONST_OK_FOR_I (INTVAL (src)))       /* r-I */
1257             return "movi\t%0,%1";
1258           else if (CONST_OK_FOR_M (INTVAL (src)))  /* r-M */
1259             return "bgeni\t%0,%P1\t// %1 %x1";
1260           else if (CONST_OK_FOR_N (INTVAL (src)))  /* r-N */
1261             return "bmaski\t%0,%N1\t// %1 %x1";
1262           else if (try_constant_tricks (INTVAL (src), &x, &y))     /* R-P */
1263             return output_inline_const (SImode, operands);  /* 1-2 insns */
1264           else 
1265             return "lrw\t%0,%x1\t// %1";        /* Get it from literal pool.  */
1266         }
1267       else
1268         return "lrw\t%0, %1";                /* Into the literal pool.  */
1269     }
1270   else if (GET_CODE (dst) == MEM)               /* m-r */
1271     switch (GET_MODE (dst))
1272       {
1273       case SImode:
1274         return "stw\t%1,%0";
1275       case HImode:
1276         return "st.h\t%1,%0";
1277       case QImode:
1278         return "st.b\t%1,%0";
1279       default:
1280         gcc_unreachable ();
1281       }
1282
1283   gcc_unreachable ();
1284 }
1285
1286 /* Return a sequence of instructions to perform DI or DF move.
1287    Since the MCORE cannot move a DI or DF in one instruction, we have
1288    to take care when we see overlapping source and dest registers.  */
1289
1290 const char *
1291 mcore_output_movedouble (rtx operands[], enum machine_mode mode ATTRIBUTE_UNUSED)
1292 {
1293   rtx dst = operands[0];
1294   rtx src = operands[1];
1295
1296   if (GET_CODE (dst) == REG)
1297     {
1298       if (GET_CODE (src) == REG)
1299         {
1300           int dstreg = REGNO (dst);
1301           int srcreg = REGNO (src);
1302           
1303           /* Ensure the second source not overwritten.  */
1304           if (srcreg + 1 == dstreg)
1305             return "mov %R0,%R1\n\tmov  %0,%1";
1306           else
1307             return "mov %0,%1\n\tmov    %R0,%R1";
1308         }
1309       else if (GET_CODE (src) == MEM)
1310         {
1311           rtx memexp = memexp = XEXP (src, 0);
1312           int dstreg = REGNO (dst);
1313           int basereg = -1;
1314           
1315           if (GET_CODE (memexp) == LABEL_REF)
1316             return "lrw\t%0,[%1]\n\tlrw\t%R0,[%R1]";
1317           else if (GET_CODE (memexp) == REG) 
1318             basereg = REGNO (memexp);
1319           else if (GET_CODE (memexp) == PLUS)
1320             {
1321               if (GET_CODE (XEXP (memexp, 0)) == REG)
1322                 basereg = REGNO (XEXP (memexp, 0));
1323               else if (GET_CODE (XEXP (memexp, 1)) == REG)
1324                 basereg = REGNO (XEXP (memexp, 1));
1325               else
1326                 gcc_unreachable ();
1327             }
1328           else
1329             gcc_unreachable ();
1330
1331           /* ??? length attribute is wrong here.  */
1332           if (dstreg == basereg)
1333             {
1334               /* Just load them in reverse order.  */
1335               return "ldw\t%R0,%R1\n\tldw\t%0,%1";
1336               
1337               /* XXX: alternative: move basereg to basereg+1
1338                  and then fall through.  */
1339             }
1340           else
1341             return "ldw\t%0,%1\n\tldw\t%R0,%R1";
1342         }
1343       else if (GET_CODE (src) == CONST_INT)
1344         {
1345           if (TARGET_LITTLE_END)
1346             {
1347               if (CONST_OK_FOR_I (INTVAL (src)))
1348                 output_asm_insn ("movi  %0,%1", operands);
1349               else if (CONST_OK_FOR_M (INTVAL (src)))
1350                 output_asm_insn ("bgeni %0,%P1", operands);
1351               else if (CONST_OK_FOR_N (INTVAL (src)))
1352                 output_asm_insn ("bmaski        %0,%N1", operands);
1353               else
1354                 gcc_unreachable ();
1355
1356               if (INTVAL (src) < 0)
1357                 return "bmaski  %R0,32";
1358               else
1359                 return "movi    %R0,0";
1360             }
1361           else
1362             {
1363               if (CONST_OK_FOR_I (INTVAL (src)))
1364                 output_asm_insn ("movi  %R0,%1", operands);
1365               else if (CONST_OK_FOR_M (INTVAL (src)))
1366                 output_asm_insn ("bgeni %R0,%P1", operands);
1367               else if (CONST_OK_FOR_N (INTVAL (src)))
1368                 output_asm_insn ("bmaski        %R0,%N1", operands);
1369               else
1370                 gcc_unreachable ();
1371
1372               if (INTVAL (src) < 0)
1373                 return "bmaski  %0,32";
1374               else
1375                 return "movi    %0,0";
1376             }
1377         }
1378       else
1379         gcc_unreachable ();
1380     }
1381   else if (GET_CODE (dst) == MEM && GET_CODE (src) == REG)
1382     return "stw\t%1,%0\n\tstw\t%R1,%R0";
1383   else
1384     gcc_unreachable ();
1385 }
1386
1387 /* Predicates used by the templates.  */
1388
1389 int
1390 mcore_arith_S_operand (rtx op)
1391 {
1392   if (GET_CODE (op) == CONST_INT && CONST_OK_FOR_M (~INTVAL (op)))
1393     return 1;
1394   
1395   return 0;
1396 }
1397
1398 /* Expand insert bit field.  BRC  */
1399
1400 int
1401 mcore_expand_insv (rtx operands[])
1402 {
1403   int width = INTVAL (operands[1]);
1404   int posn = INTVAL (operands[2]);
1405   int mask;
1406   rtx mreg, sreg, ereg;
1407
1408   /* To get width 1 insv, the test in store_bit_field() (expmed.c, line 191)
1409      for width==1 must be removed.  Look around line 368.  This is something
1410      we really want the md part to do.  */
1411   if (width == 1 && GET_CODE (operands[3]) == CONST_INT)
1412     {
1413       /* Do directly with bseti or bclri.  */
1414       /* RBE: 2/97 consider only low bit of constant.  */
1415       if ((INTVAL (operands[3]) & 1) == 0)
1416         {
1417           mask = ~(1 << posn);
1418           emit_insn (gen_rtx_SET (SImode, operands[0],
1419                               gen_rtx_AND (SImode, operands[0], GEN_INT (mask))));
1420         }
1421       else
1422         {
1423           mask = 1 << posn;
1424           emit_insn (gen_rtx_SET (SImode, operands[0],
1425                             gen_rtx_IOR (SImode, operands[0], GEN_INT (mask))));
1426         }
1427       
1428       return 1;
1429     }
1430
1431   /* Look at some bit-field placements that we aren't interested
1432      in handling ourselves, unless specifically directed to do so.  */
1433   if (! TARGET_W_FIELD)
1434     return 0;           /* Generally, give up about now.  */
1435
1436   if (width == 8 && posn % 8 == 0)
1437     /* Byte sized and aligned; let caller break it up.  */
1438     return 0;
1439   
1440   if (width == 16 && posn % 16 == 0)
1441     /* Short sized and aligned; let caller break it up.  */
1442     return 0;
1443
1444   /* The general case - we can do this a little bit better than what the
1445      machine independent part tries.  This will get rid of all the subregs
1446      that mess up constant folding in combine when working with relaxed
1447      immediates.  */
1448
1449   /* If setting the entire field, do it directly.  */
1450   if (GET_CODE (operands[3]) == CONST_INT
1451       && INTVAL (operands[3]) == ((1 << width) - 1))
1452     {
1453       mreg = force_reg (SImode, GEN_INT (INTVAL (operands[3]) << posn));
1454       emit_insn (gen_rtx_SET (SImode, operands[0],
1455                          gen_rtx_IOR (SImode, operands[0], mreg)));
1456       return 1;
1457     }
1458
1459   /* Generate the clear mask.  */
1460   mreg = force_reg (SImode, GEN_INT (~(((1 << width) - 1) << posn)));
1461
1462   /* Clear the field, to overlay it later with the source.  */
1463   emit_insn (gen_rtx_SET (SImode, operands[0], 
1464                       gen_rtx_AND (SImode, operands[0], mreg)));
1465
1466   /* If the source is constant 0, we've nothing to add back.  */
1467   if (GET_CODE (operands[3]) == CONST_INT && INTVAL (operands[3]) == 0)
1468     return 1;
1469
1470   /* XXX: Should we worry about more games with constant values?
1471      We've covered the high profile: set/clear single-bit and many-bit
1472      fields. How often do we see "arbitrary bit pattern" constants?  */
1473   sreg = copy_to_mode_reg (SImode, operands[3]);
1474
1475   /* Extract src as same width as dst (needed for signed values).  We
1476      always have to do this since we widen everything to SImode.
1477      We don't have to mask if we're shifting this up against the
1478      MSB of the register (e.g., the shift will push out any hi-order
1479      bits.  */
1480   if (width + posn != (int) GET_MODE_SIZE (SImode))
1481     {
1482       ereg = force_reg (SImode, GEN_INT ((1 << width) - 1));      
1483       emit_insn (gen_rtx_SET (SImode, sreg,
1484                           gen_rtx_AND (SImode, sreg, ereg)));
1485     }
1486
1487   /* Insert source value in dest.  */
1488   if (posn != 0)
1489     emit_insn (gen_rtx_SET (SImode, sreg,
1490                         gen_rtx_ASHIFT (SImode, sreg, GEN_INT (posn))));
1491   
1492   emit_insn (gen_rtx_SET (SImode, operands[0],
1493                       gen_rtx_IOR (SImode, operands[0], sreg)));
1494
1495   return 1;
1496 }
1497 \f
1498 /* ??? Block move stuff stolen from m88k.  This code has not been
1499    verified for correctness.  */
1500
1501 /* Emit code to perform a block move.  Choose the best method.
1502
1503    OPERANDS[0] is the destination.
1504    OPERANDS[1] is the source.
1505    OPERANDS[2] is the size.
1506    OPERANDS[3] is the alignment safe to use.  */
1507
1508 /* Emit code to perform a block move with an offset sequence of ldw/st
1509    instructions (..., ldw 0, stw 1, ldw 1, stw 0, ...).  SIZE and ALIGN are
1510    known constants.  DEST and SRC are registers.  OFFSET is the known
1511    starting point for the output pattern.  */
1512
1513 static const enum machine_mode mode_from_align[] =
1514 {
1515   VOIDmode, QImode, HImode, VOIDmode, SImode,
1516 };
1517
1518 static void
1519 block_move_sequence (rtx dst_mem, rtx src_mem, int size, int align)
1520 {
1521   rtx temp[2];
1522   enum machine_mode mode[2];
1523   int amount[2];
1524   bool active[2];
1525   int phase = 0;
1526   int next;
1527   int offset_ld = 0;
1528   int offset_st = 0;
1529   rtx x;
1530
1531   x = XEXP (dst_mem, 0);
1532   if (!REG_P (x))
1533     {
1534       x = force_reg (Pmode, x);
1535       dst_mem = replace_equiv_address (dst_mem, x);
1536     }
1537
1538   x = XEXP (src_mem, 0);
1539   if (!REG_P (x))
1540     {
1541       x = force_reg (Pmode, x);
1542       src_mem = replace_equiv_address (src_mem, x);
1543     }
1544
1545   active[0] = active[1] = false;
1546
1547   do
1548     {
1549       next = phase;
1550       phase ^= 1;
1551
1552       if (size > 0)
1553         {
1554           int next_amount;
1555
1556           next_amount = (size >= 4 ? 4 : (size >= 2 ? 2 : 1));
1557           next_amount = MIN (next_amount, align);
1558
1559           amount[next] = next_amount;
1560           mode[next] = mode_from_align[next_amount];
1561           temp[next] = gen_reg_rtx (mode[next]);
1562
1563           x = adjust_address (src_mem, mode[next], offset_ld);
1564           emit_insn (gen_rtx_SET (VOIDmode, temp[next], x));
1565
1566           offset_ld += next_amount;
1567           size -= next_amount;
1568           active[next] = true;
1569         }
1570
1571       if (active[phase])
1572         {
1573           active[phase] = false;
1574           
1575           x = adjust_address (dst_mem, mode[phase], offset_st);
1576           emit_insn (gen_rtx_SET (VOIDmode, x, temp[phase]));
1577
1578           offset_st += amount[phase];
1579         }
1580     }
1581   while (active[next]);
1582 }
1583
1584 bool
1585 mcore_expand_block_move (rtx *operands)
1586 {
1587   HOST_WIDE_INT align, bytes, max;
1588
1589   if (GET_CODE (operands[2]) != CONST_INT)
1590     return false;
1591
1592   bytes = INTVAL (operands[2]);
1593   align = INTVAL (operands[3]);
1594
1595   if (bytes <= 0)
1596     return false;
1597   if (align > 4)
1598     align = 4;
1599
1600   switch (align)
1601     {
1602     case 4:
1603       if (bytes & 1)
1604         max = 4*4;
1605       else if (bytes & 3)
1606         max = 8*4;
1607       else
1608         max = 16*4;
1609       break;
1610     case 2:
1611       max = 4*2;
1612       break;
1613     case 1:
1614       max = 4*1;
1615       break;
1616     default:
1617       gcc_unreachable ();
1618     }
1619
1620   if (bytes <= max)
1621     {
1622       block_move_sequence (operands[0], operands[1], bytes, align);
1623       return true;
1624     }
1625
1626   return false;
1627 }
1628 \f
1629
1630 /* Code to generate prologue and epilogue sequences.  */
1631 static int number_of_regs_before_varargs;
1632
1633 /* Set by TARGET_SETUP_INCOMING_VARARGS to indicate to prolog that this is
1634    for a varargs function.  */
1635 static int current_function_anonymous_args;
1636
1637 #define STACK_BYTES (STACK_BOUNDARY/BITS_PER_UNIT)
1638 #define STORE_REACH (64)        /* Maximum displace of word store + 4.  */
1639 #define ADDI_REACH (32)         /* Maximum addi operand.  */
1640
1641 static void
1642 layout_mcore_frame (struct mcore_frame * infp)
1643 {
1644   int n;
1645   unsigned int i;
1646   int nbytes;
1647   int regarg;
1648   int localregarg;
1649   int localreg;
1650   int outbounds;
1651   unsigned int growths;
1652   int step;
1653
1654   /* Might have to spill bytes to re-assemble a big argument that
1655      was passed partially in registers and partially on the stack.  */
1656   nbytes = crtl->args.pretend_args_size;
1657   
1658   /* Determine how much space for spilled anonymous args (e.g., stdarg).  */
1659   if (current_function_anonymous_args)
1660     nbytes += (NPARM_REGS - number_of_regs_before_varargs) * UNITS_PER_WORD;
1661   
1662   infp->arg_size = nbytes;
1663
1664   /* How much space to save non-volatile registers we stomp.  */
1665   infp->reg_mask = calc_live_regs (& n);
1666   infp->reg_size = n * 4;
1667
1668   /* And the rest of it... locals and space for overflowed outbounds.  */
1669   infp->local_size = get_frame_size ();
1670   infp->outbound_size = crtl->outgoing_args_size;
1671
1672   /* Make sure we have a whole number of words for the locals.  */
1673   if (infp->local_size % STACK_BYTES)
1674     infp->local_size = (infp->local_size + STACK_BYTES - 1) & ~ (STACK_BYTES -1);
1675   
1676   /* Only thing we know we have to pad is the outbound space, since
1677      we've aligned our locals assuming that base of locals is aligned.  */
1678   infp->pad_local = 0;
1679   infp->pad_reg = 0;
1680   infp->pad_outbound = 0;
1681   if (infp->outbound_size % STACK_BYTES)
1682     infp->pad_outbound = STACK_BYTES - (infp->outbound_size % STACK_BYTES);
1683
1684   /* Now we see how we want to stage the prologue so that it does
1685      the most appropriate stack growth and register saves to either:
1686      (1) run fast,
1687      (2) reduce instruction space, or
1688      (3) reduce stack space.  */
1689   for (i = 0; i < ARRAY_SIZE (infp->growth); i++)
1690     infp->growth[i] = 0;
1691
1692   regarg      = infp->reg_size + infp->arg_size;
1693   localregarg = infp->local_size + regarg;
1694   localreg    = infp->local_size + infp->reg_size;
1695   outbounds   = infp->outbound_size + infp->pad_outbound;
1696   growths     = 0;
1697
1698   /* XXX: Consider one where we consider localregarg + outbound too! */
1699
1700   /* Frame of <= 32 bytes and using stm would get <= 2 registers.
1701      use stw's with offsets and buy the frame in one shot.  */
1702   if (localregarg <= ADDI_REACH
1703       && (infp->reg_size <= 8 || (infp->reg_mask & 0xc000) != 0xc000))
1704     {
1705       /* Make sure we'll be aligned.  */
1706       if (localregarg % STACK_BYTES)
1707         infp->pad_reg = STACK_BYTES - (localregarg % STACK_BYTES);
1708
1709       step = localregarg + infp->pad_reg;
1710       infp->reg_offset = infp->local_size;
1711       
1712       if (outbounds + step <= ADDI_REACH && !frame_pointer_needed)
1713         {
1714           step += outbounds;
1715           infp->reg_offset += outbounds;
1716           outbounds = 0;
1717         }
1718       
1719       infp->arg_offset = step - 4;
1720       infp->growth[growths++] = step;
1721       infp->reg_growth = growths;
1722       infp->local_growth = growths;
1723       
1724       /* If we haven't already folded it in.  */
1725       if (outbounds)
1726         infp->growth[growths++] = outbounds;
1727       
1728       goto finish;
1729     }
1730
1731   /* Frame can't be done with a single subi, but can be done with 2
1732      insns.  If the 'stm' is getting <= 2 registers, we use stw's and
1733      shift some of the stack purchase into the first subi, so both are
1734      single instructions.  */
1735   if (localregarg <= STORE_REACH
1736       && (infp->local_size > ADDI_REACH)
1737       && (infp->reg_size <= 8 || (infp->reg_mask & 0xc000) != 0xc000))
1738     {
1739       int all;
1740
1741       /* Make sure we'll be aligned; use either pad_reg or pad_local.  */
1742       if (localregarg % STACK_BYTES)
1743         infp->pad_reg = STACK_BYTES - (localregarg % STACK_BYTES);
1744
1745       all = localregarg + infp->pad_reg + infp->pad_local;
1746       step = ADDI_REACH;        /* As much up front as we can.  */
1747       if (step > all)
1748         step = all;
1749       
1750       /* XXX: Consider whether step will still be aligned; we believe so.  */
1751       infp->arg_offset = step - 4;
1752       infp->growth[growths++] = step;
1753       infp->reg_growth = growths;
1754       infp->reg_offset = step - infp->pad_reg - infp->reg_size;
1755       all -= step;
1756
1757       /* Can we fold in any space required for outbounds?  */
1758       if (outbounds + all <= ADDI_REACH && !frame_pointer_needed)
1759         {
1760           all += outbounds;
1761           outbounds = 0;
1762         }
1763
1764       /* Get the rest of the locals in place.  */
1765       step = all;
1766       infp->growth[growths++] = step;
1767       infp->local_growth = growths;
1768       all -= step;
1769
1770       assert (all == 0);
1771
1772       /* Finish off if we need to do so.  */
1773       if (outbounds)
1774         infp->growth[growths++] = outbounds;
1775       
1776       goto finish;
1777     }
1778
1779   /* Registers + args is nicely aligned, so we'll buy that in one shot.
1780      Then we buy the rest of the frame in 1 or 2 steps depending on
1781      whether we need a frame pointer.  */
1782   if ((regarg % STACK_BYTES) == 0)
1783     {
1784       infp->growth[growths++] = regarg;
1785       infp->reg_growth = growths;
1786       infp->arg_offset = regarg - 4;
1787       infp->reg_offset = 0;
1788
1789       if (infp->local_size % STACK_BYTES)
1790         infp->pad_local = STACK_BYTES - (infp->local_size % STACK_BYTES);
1791       
1792       step = infp->local_size + infp->pad_local;
1793       
1794       if (!frame_pointer_needed)
1795         {
1796           step += outbounds;
1797           outbounds = 0;
1798         }
1799       
1800       infp->growth[growths++] = step;
1801       infp->local_growth = growths;
1802
1803       /* If there's any left to be done.  */
1804       if (outbounds)
1805         infp->growth[growths++] = outbounds;
1806       
1807       goto finish;
1808     }
1809
1810   /* XXX: optimizations that we'll want to play with....
1811      -- regarg is not aligned, but it's a small number of registers;
1812         use some of localsize so that regarg is aligned and then 
1813         save the registers.  */
1814
1815   /* Simple encoding; plods down the stack buying the pieces as it goes.
1816      -- does not optimize space consumption.
1817      -- does not attempt to optimize instruction counts.
1818      -- but it is safe for all alignments.  */
1819   if (regarg % STACK_BYTES != 0)
1820     infp->pad_reg = STACK_BYTES - (regarg % STACK_BYTES);
1821   
1822   infp->growth[growths++] = infp->arg_size + infp->reg_size + infp->pad_reg;
1823   infp->reg_growth = growths;
1824   infp->arg_offset = infp->growth[0] - 4;
1825   infp->reg_offset = 0;
1826   
1827   if (frame_pointer_needed)
1828     {
1829       if (infp->local_size % STACK_BYTES != 0)
1830         infp->pad_local = STACK_BYTES - (infp->local_size % STACK_BYTES);
1831       
1832       infp->growth[growths++] = infp->local_size + infp->pad_local;
1833       infp->local_growth = growths;
1834       
1835       infp->growth[growths++] = outbounds;
1836     }
1837   else
1838     {
1839       if ((infp->local_size + outbounds) % STACK_BYTES != 0)
1840         infp->pad_local = STACK_BYTES - ((infp->local_size + outbounds) % STACK_BYTES);
1841       
1842       infp->growth[growths++] = infp->local_size + infp->pad_local + outbounds;
1843       infp->local_growth = growths;
1844     }
1845
1846   /* Anything else that we've forgotten?, plus a few consistency checks.  */
1847  finish:
1848   assert (infp->reg_offset >= 0);
1849   assert (growths <= MAX_STACK_GROWS);
1850   
1851   for (i = 0; i < growths; i++)
1852     gcc_assert (!(infp->growth[i] % STACK_BYTES));
1853 }
1854
1855 /* Define the offset between two registers, one to be eliminated, and
1856    the other its replacement, at the start of a routine.  */
1857
1858 int
1859 mcore_initial_elimination_offset (int from, int to)
1860 {
1861   int above_frame;
1862   int below_frame;
1863   struct mcore_frame fi;
1864
1865   layout_mcore_frame (& fi);
1866
1867   /* fp to ap */
1868   above_frame = fi.local_size + fi.pad_local + fi.reg_size + fi.pad_reg;
1869   /* sp to fp */
1870   below_frame = fi.outbound_size + fi.pad_outbound;
1871
1872   if (from == ARG_POINTER_REGNUM && to == FRAME_POINTER_REGNUM)
1873     return above_frame;
1874
1875   if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
1876     return above_frame + below_frame;
1877
1878   if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
1879     return below_frame;
1880
1881   gcc_unreachable ();
1882 }
1883
1884 /* Keep track of some information about varargs for the prolog.  */
1885
1886 static void
1887 mcore_setup_incoming_varargs (CUMULATIVE_ARGS *args_so_far,
1888                               enum machine_mode mode, tree type,
1889                               int * ptr_pretend_size ATTRIBUTE_UNUSED,
1890                               int second_time ATTRIBUTE_UNUSED)
1891 {
1892   current_function_anonymous_args = 1;
1893
1894   /* We need to know how many argument registers are used before
1895      the varargs start, so that we can push the remaining argument
1896      registers during the prologue.  */
1897   number_of_regs_before_varargs = *args_so_far + mcore_num_arg_regs (mode, type);
1898   
1899   /* There is a bug somewhere in the arg handling code.
1900      Until I can find it this workaround always pushes the
1901      last named argument onto the stack.  */
1902   number_of_regs_before_varargs = *args_so_far;
1903   
1904   /* The last named argument may be split between argument registers
1905      and the stack.  Allow for this here.  */
1906   if (number_of_regs_before_varargs > NPARM_REGS)
1907     number_of_regs_before_varargs = NPARM_REGS;
1908 }
1909
1910 void
1911 mcore_expand_prolog (void)
1912 {
1913   struct mcore_frame fi;
1914   int space_allocated = 0;
1915   int growth = 0;
1916
1917   /* Find out what we're doing.  */
1918   layout_mcore_frame (&fi);
1919   
1920   space_allocated = fi.arg_size + fi.reg_size + fi.local_size +
1921     fi.outbound_size + fi.pad_outbound + fi.pad_local + fi.pad_reg;
1922
1923   if (TARGET_CG_DATA)
1924     {
1925       /* Emit a symbol for this routine's frame size.  */
1926       rtx x;
1927
1928       x = DECL_RTL (current_function_decl);
1929       
1930       gcc_assert (GET_CODE (x) == MEM);
1931       
1932       x = XEXP (x, 0);
1933       
1934       gcc_assert (GET_CODE (x) == SYMBOL_REF);
1935       
1936       if (mcore_current_function_name)
1937         free (mcore_current_function_name);
1938       
1939       mcore_current_function_name = xstrdup (XSTR (x, 0));
1940       
1941       ASM_OUTPUT_CG_NODE (asm_out_file, mcore_current_function_name, space_allocated);
1942
1943       if (cfun->calls_alloca)
1944         ASM_OUTPUT_CG_EDGE (asm_out_file, mcore_current_function_name, "alloca", 1);
1945
1946       /* 970425: RBE:
1947          We're looking at how the 8byte alignment affects stack layout
1948          and where we had to pad things. This emits information we can
1949          extract which tells us about frame sizes and the like.  */
1950       fprintf (asm_out_file,
1951                "\t.equ\t__$frame$info$_%s_$_%d_%d_x%x_%d_%d_%d,0\n",
1952                mcore_current_function_name,
1953                fi.arg_size, fi.reg_size, fi.reg_mask,
1954                fi.local_size, fi.outbound_size,
1955                frame_pointer_needed);
1956     }
1957
1958   if (mcore_naked_function_p ())
1959     return;
1960   
1961   /* Handle stdarg+regsaves in one shot: can't be more than 64 bytes.  */
1962   output_stack_adjust (-1, fi.growth[growth++]);        /* Grows it.  */
1963
1964   /* If we have a parameter passed partially in regs and partially in memory,
1965      the registers will have been stored to memory already in function.c.  So
1966      we only need to do something here for varargs functions.  */
1967   if (fi.arg_size != 0 && crtl->args.pretend_args_size == 0)
1968     {
1969       int offset;
1970       int rn = FIRST_PARM_REG + NPARM_REGS - 1;
1971       int remaining = fi.arg_size;
1972
1973       for (offset = fi.arg_offset; remaining >= 4; offset -= 4, rn--, remaining -= 4)
1974         {
1975           emit_insn (gen_movsi
1976                      (gen_rtx_MEM (SImode,
1977                                plus_constant (stack_pointer_rtx, offset)),
1978                       gen_rtx_REG (SImode, rn)));
1979         }
1980     }
1981
1982   /* Do we need another stack adjustment before we do the register saves?  */
1983   if (growth < fi.reg_growth)
1984     output_stack_adjust (-1, fi.growth[growth++]);              /* Grows it.  */
1985
1986   if (fi.reg_size != 0)
1987     {
1988       int i;
1989       int offs = fi.reg_offset;
1990       
1991       for (i = 15; i >= 0; i--)
1992         {
1993           if (offs == 0 && i == 15 && ((fi.reg_mask & 0xc000) == 0xc000))
1994             {
1995               int first_reg = 15;
1996
1997               while (fi.reg_mask & (1 << first_reg))
1998                 first_reg--;
1999               first_reg++;
2000
2001               emit_insn (gen_store_multiple (gen_rtx_MEM (SImode, stack_pointer_rtx),
2002                                              gen_rtx_REG (SImode, first_reg),
2003                                              GEN_INT (16 - first_reg)));
2004
2005               i -= (15 - first_reg);
2006               offs += (16 - first_reg) * 4;
2007             }
2008           else if (fi.reg_mask & (1 << i))
2009             {
2010               emit_insn (gen_movsi
2011                          (gen_rtx_MEM (SImode,
2012                                    plus_constant (stack_pointer_rtx, offs)),
2013                           gen_rtx_REG (SImode, i)));
2014               offs += 4;
2015             }
2016         }
2017     }
2018
2019   /* Figure the locals + outbounds.  */
2020   if (frame_pointer_needed)
2021     {
2022       /* If we haven't already purchased to 'fp'.  */
2023       if (growth < fi.local_growth)
2024         output_stack_adjust (-1, fi.growth[growth++]);          /* Grows it.  */
2025       
2026       emit_insn (gen_movsi (frame_pointer_rtx, stack_pointer_rtx));
2027
2028       /* ... and then go any remaining distance for outbounds, etc.  */
2029       if (fi.growth[growth])
2030         output_stack_adjust (-1, fi.growth[growth++]);
2031     }
2032   else
2033     {
2034       if (growth < fi.local_growth)
2035         output_stack_adjust (-1, fi.growth[growth++]);          /* Grows it.  */
2036       if (fi.growth[growth])
2037         output_stack_adjust (-1, fi.growth[growth++]);
2038     }
2039 }
2040
2041 void
2042 mcore_expand_epilog (void)
2043 {
2044   struct mcore_frame fi;
2045   int i;
2046   int offs;
2047   int growth = MAX_STACK_GROWS - 1 ;
2048
2049     
2050   /* Find out what we're doing.  */
2051   layout_mcore_frame(&fi);
2052
2053   if (mcore_naked_function_p ())
2054     return;
2055
2056   /* If we had a frame pointer, restore the sp from that.  */
2057   if (frame_pointer_needed)
2058     {
2059       emit_insn (gen_movsi (stack_pointer_rtx, frame_pointer_rtx));
2060       growth = fi.local_growth - 1;
2061     }
2062   else
2063     {
2064       /* XXX: while loop should accumulate and do a single sell.  */
2065       while (growth >= fi.local_growth)
2066         {
2067           if (fi.growth[growth] != 0)
2068             output_stack_adjust (1, fi.growth[growth]);
2069           growth--;
2070         }
2071     }
2072
2073   /* Make sure we've shrunk stack back to the point where the registers
2074      were laid down. This is typically 0/1 iterations.  Then pull the
2075      register save information back off the stack.  */
2076   while (growth >= fi.reg_growth)
2077     output_stack_adjust ( 1, fi.growth[growth--]);
2078   
2079   offs = fi.reg_offset;
2080   
2081   for (i = 15; i >= 0; i--)
2082     {
2083       if (offs == 0 && i == 15 && ((fi.reg_mask & 0xc000) == 0xc000))
2084         {
2085           int first_reg;
2086
2087           /* Find the starting register.  */
2088           first_reg = 15;
2089           
2090           while (fi.reg_mask & (1 << first_reg))
2091             first_reg--;
2092           
2093           first_reg++;
2094
2095           emit_insn (gen_load_multiple (gen_rtx_REG (SImode, first_reg),
2096                                         gen_rtx_MEM (SImode, stack_pointer_rtx),
2097                                         GEN_INT (16 - first_reg)));
2098
2099           i -= (15 - first_reg);
2100           offs += (16 - first_reg) * 4;
2101         }
2102       else if (fi.reg_mask & (1 << i))
2103         {
2104           emit_insn (gen_movsi
2105                      (gen_rtx_REG (SImode, i),
2106                       gen_rtx_MEM (SImode,
2107                                plus_constant (stack_pointer_rtx, offs))));
2108           offs += 4;
2109         }
2110     }
2111
2112   /* Give back anything else.  */
2113   /* XXX: Should accumulate total and then give it back.  */
2114   while (growth >= 0)
2115     output_stack_adjust ( 1, fi.growth[growth--]);
2116 }
2117 \f
2118 /* This code is borrowed from the SH port.  */
2119
2120 /* The MCORE cannot load a large constant into a register, constants have to
2121    come from a pc relative load.  The reference of a pc relative load
2122    instruction must be less than 1k in front of the instruction.  This
2123    means that we often have to dump a constant inside a function, and
2124    generate code to branch around it.
2125
2126    It is important to minimize this, since the branches will slow things
2127    down and make things bigger.
2128
2129    Worst case code looks like:
2130
2131    lrw   L1,r0
2132    br    L2
2133    align
2134    L1:   .long value
2135    L2:
2136    ..
2137
2138    lrw   L3,r0
2139    br    L4
2140    align
2141    L3:   .long value
2142    L4:
2143    ..
2144
2145    We fix this by performing a scan before scheduling, which notices which
2146    instructions need to have their operands fetched from the constant table
2147    and builds the table.
2148
2149    The algorithm is:
2150
2151    scan, find an instruction which needs a pcrel move.  Look forward, find the
2152    last barrier which is within MAX_COUNT bytes of the requirement.
2153    If there isn't one, make one.  Process all the instructions between
2154    the find and the barrier.
2155
2156    In the above example, we can tell that L3 is within 1k of L1, so
2157    the first move can be shrunk from the 2 insn+constant sequence into
2158    just 1 insn, and the constant moved to L3 to make:
2159
2160    lrw          L1,r0
2161    ..
2162    lrw          L3,r0
2163    bra          L4
2164    align
2165    L3:.long value
2166    L4:.long value
2167
2168    Then the second move becomes the target for the shortening process.  */
2169
2170 typedef struct
2171 {
2172   rtx value;                    /* Value in table.  */
2173   rtx label;                    /* Label of value.  */
2174 } pool_node;
2175
2176 /* The maximum number of constants that can fit into one pool, since
2177    the pc relative range is 0...1020 bytes and constants are at least 4
2178    bytes long.  We subtract 4 from the range to allow for the case where
2179    we need to add a branch/align before the constant pool.  */
2180
2181 #define MAX_COUNT 1016
2182 #define MAX_POOL_SIZE (MAX_COUNT/4)
2183 static pool_node pool_vector[MAX_POOL_SIZE];
2184 static int pool_size;
2185
2186 /* Dump out any constants accumulated in the final pass.  These
2187    will only be labels.  */
2188
2189 const char *
2190 mcore_output_jump_label_table (void)
2191 {
2192   int i;
2193
2194   if (pool_size)
2195     {
2196       fprintf (asm_out_file, "\t.align 2\n");
2197       
2198       for (i = 0; i < pool_size; i++)
2199         {
2200           pool_node * p = pool_vector + i;
2201
2202           (*targetm.asm_out.internal_label) (asm_out_file, "L", CODE_LABEL_NUMBER (p->label));
2203           
2204           output_asm_insn (".long       %0", &p->value);
2205         }
2206       
2207       pool_size = 0;
2208     }
2209
2210   return "";
2211 }
2212
2213 /* Check whether insn is a candidate for a conditional.  */
2214
2215 static cond_type
2216 is_cond_candidate (rtx insn)
2217 {
2218   /* The only things we conditionalize are those that can be directly
2219      changed into a conditional.  Only bother with SImode items.  If 
2220      we wanted to be a little more aggressive, we could also do other
2221      modes such as DImode with reg-reg move or load 0.  */
2222   if (GET_CODE (insn) == INSN)
2223     {
2224       rtx pat = PATTERN (insn);
2225       rtx src, dst;
2226
2227       if (GET_CODE (pat) != SET)
2228         return COND_NO;
2229
2230       dst = XEXP (pat, 0);
2231
2232       if ((GET_CODE (dst) != REG &&
2233            GET_CODE (dst) != SUBREG) ||
2234           GET_MODE (dst) != SImode)
2235         return COND_NO;
2236   
2237       src = XEXP (pat, 1);
2238
2239       if ((GET_CODE (src) == REG ||
2240            (GET_CODE (src) == SUBREG &&
2241             GET_CODE (SUBREG_REG (src)) == REG)) &&
2242           GET_MODE (src) == SImode)
2243         return COND_MOV_INSN;
2244       else if (GET_CODE (src) == CONST_INT && 
2245                INTVAL (src) == 0)
2246         return COND_CLR_INSN;
2247       else if (GET_CODE (src) == PLUS &&
2248                (GET_CODE (XEXP (src, 0)) == REG ||
2249                 (GET_CODE (XEXP (src, 0)) == SUBREG &&
2250                  GET_CODE (SUBREG_REG (XEXP (src, 0))) == REG)) &&
2251                GET_MODE (XEXP (src, 0)) == SImode &&
2252                GET_CODE (XEXP (src, 1)) == CONST_INT &&
2253                INTVAL (XEXP (src, 1)) == 1)
2254         return COND_INC_INSN;
2255       else if (((GET_CODE (src) == MINUS &&
2256                  GET_CODE (XEXP (src, 1)) == CONST_INT &&
2257                  INTVAL( XEXP (src, 1)) == 1) ||
2258                 (GET_CODE (src) == PLUS &&
2259                  GET_CODE (XEXP (src, 1)) == CONST_INT &&
2260                  INTVAL (XEXP (src, 1)) == -1)) &&
2261                (GET_CODE (XEXP (src, 0)) == REG ||
2262                 (GET_CODE (XEXP (src, 0)) == SUBREG &&
2263                  GET_CODE (SUBREG_REG (XEXP (src, 0))) == REG)) &&
2264                GET_MODE (XEXP (src, 0)) == SImode)
2265         return COND_DEC_INSN;
2266
2267       /* Some insns that we don't bother with:
2268          (set (rx:DI) (ry:DI))
2269          (set (rx:DI) (const_int 0))
2270       */            
2271
2272     }
2273   else if (GET_CODE (insn) == JUMP_INSN &&
2274            GET_CODE (PATTERN (insn)) == SET &&
2275            GET_CODE (XEXP (PATTERN (insn), 1)) == LABEL_REF)
2276     return COND_BRANCH_INSN;
2277
2278   return COND_NO;
2279 }
2280
2281 /* Emit a conditional version of insn and replace the old insn with the
2282    new one.  Return the new insn if emitted.  */
2283
2284 static rtx
2285 emit_new_cond_insn (rtx insn, int cond)
2286 {
2287   rtx c_insn = 0;
2288   rtx pat, dst, src;
2289   cond_type num;
2290
2291   if ((num = is_cond_candidate (insn)) == COND_NO)
2292     return NULL;
2293
2294   pat = PATTERN (insn);
2295
2296   if (GET_CODE (insn) == INSN)
2297     {
2298       dst = SET_DEST (pat);
2299       src = SET_SRC (pat);
2300     }
2301   else
2302     {
2303       dst = JUMP_LABEL (insn);
2304       src = NULL_RTX;
2305     }
2306
2307   switch (num)
2308     {
2309     case COND_MOV_INSN: 
2310     case COND_CLR_INSN:
2311       if (cond)
2312         c_insn = gen_movt0 (dst, src, dst);
2313       else
2314         c_insn = gen_movt0 (dst, dst, src);
2315       break;
2316
2317     case COND_INC_INSN:
2318       if (cond)
2319         c_insn = gen_incscc (dst, dst);
2320       else
2321         c_insn = gen_incscc_false (dst, dst);
2322       break;
2323   
2324     case COND_DEC_INSN:
2325       if (cond)
2326         c_insn = gen_decscc (dst, dst);
2327       else
2328         c_insn = gen_decscc_false (dst, dst);
2329       break;
2330
2331     case COND_BRANCH_INSN:
2332       if (cond)
2333         c_insn = gen_branch_true (dst);
2334       else
2335         c_insn = gen_branch_false (dst);
2336       break;
2337
2338     default:
2339       return NULL;
2340     }
2341
2342   /* Only copy the notes if they exist.  */
2343   if (rtx_length [GET_CODE (c_insn)] >= 7 && rtx_length [GET_CODE (insn)] >= 7)
2344     {
2345       /* We really don't need to bother with the notes and links at this
2346          point, but go ahead and save the notes.  This will help is_dead()
2347          when applying peepholes (links don't matter since they are not
2348          used any more beyond this point for the mcore).  */
2349       REG_NOTES (c_insn) = REG_NOTES (insn);
2350     }
2351   
2352   if (num == COND_BRANCH_INSN)
2353     {
2354       /* For jumps, we need to be a little bit careful and emit the new jump
2355          before the old one and to update the use count for the target label.
2356          This way, the barrier following the old (uncond) jump will get
2357          deleted, but the label won't.  */
2358       c_insn = emit_jump_insn_before (c_insn, insn);
2359       
2360       ++ LABEL_NUSES (dst);
2361       
2362       JUMP_LABEL (c_insn) = dst;
2363     }
2364   else
2365     c_insn = emit_insn_after (c_insn, insn);
2366
2367   delete_insn (insn);
2368   
2369   return c_insn;
2370 }
2371
2372 /* Attempt to change a basic block into a series of conditional insns.  This
2373    works by taking the branch at the end of the 1st block and scanning for the 
2374    end of the 2nd block.  If all instructions in the 2nd block have cond.
2375    versions and the label at the start of block 3 is the same as the target
2376    from the branch at block 1, then conditionalize all insn in block 2 using
2377    the inverse condition of the branch at block 1.  (Note I'm bending the
2378    definition of basic block here.)
2379
2380    e.g., change:   
2381
2382                 bt      L2             <-- end of block 1 (delete)
2383                 mov     r7,r8          
2384                 addu    r7,1           
2385                 br      L3             <-- end of block 2
2386
2387         L2:     ...                    <-- start of block 3 (NUSES==1)
2388         L3:     ...
2389
2390    to:
2391
2392                 movf    r7,r8
2393                 incf    r7
2394                 bf      L3
2395
2396         L3:     ...
2397
2398    we can delete the L2 label if NUSES==1 and re-apply the optimization
2399    starting at the last instruction of block 2.  This may allow an entire
2400    if-then-else statement to be conditionalized.  BRC  */
2401 static rtx
2402 conditionalize_block (rtx first)
2403 {
2404   rtx insn;
2405   rtx br_pat;
2406   rtx end_blk_1_br = 0;
2407   rtx end_blk_2_insn = 0;
2408   rtx start_blk_3_lab = 0;
2409   int cond;
2410   int br_lab_num;
2411   int blk_size = 0;
2412
2413     
2414   /* Check that the first insn is a candidate conditional jump.  This is
2415      the one that we'll eliminate.  If not, advance to the next insn to
2416      try.  */
2417   if (GET_CODE (first) != JUMP_INSN ||
2418       GET_CODE (PATTERN (first)) != SET ||
2419       GET_CODE (XEXP (PATTERN (first), 1)) != IF_THEN_ELSE)
2420     return NEXT_INSN (first);
2421
2422   /* Extract some information we need.  */
2423   end_blk_1_br = first;
2424   br_pat = PATTERN (end_blk_1_br);
2425
2426   /* Complement the condition since we use the reverse cond. for the insns.  */
2427   cond = (GET_CODE (XEXP (XEXP (br_pat, 1), 0)) == EQ);
2428
2429   /* Determine what kind of branch we have.  */
2430   if (GET_CODE (XEXP (XEXP (br_pat, 1), 1)) == LABEL_REF)
2431     {
2432       /* A normal branch, so extract label out of first arm.  */
2433       br_lab_num = CODE_LABEL_NUMBER (XEXP (XEXP (XEXP (br_pat, 1), 1), 0));
2434     }
2435   else
2436     {
2437       /* An inverse branch, so extract the label out of the 2nd arm
2438          and complement the condition.  */
2439       cond = (cond == 0);
2440       br_lab_num = CODE_LABEL_NUMBER (XEXP (XEXP (XEXP (br_pat, 1), 2), 0));
2441     }
2442
2443   /* Scan forward for the start of block 2: it must start with a
2444      label and that label must be the same as the branch target
2445      label from block 1.  We don't care about whether block 2 actually
2446      ends with a branch or a label (an uncond. branch is 
2447      conditionalizable).  */
2448   for (insn = NEXT_INSN (first); insn; insn = NEXT_INSN (insn))
2449     {
2450       enum rtx_code code;
2451       
2452       code = GET_CODE (insn);
2453
2454       /* Look for the label at the start of block 3.  */
2455       if (code == CODE_LABEL && CODE_LABEL_NUMBER (insn) == br_lab_num)
2456         break;
2457
2458       /* Skip barriers, notes, and conditionalizable insns.  If the
2459          insn is not conditionalizable or makes this optimization fail,
2460          just return the next insn so we can start over from that point.  */
2461       if (code != BARRIER && code != NOTE && !is_cond_candidate (insn))
2462         return NEXT_INSN (insn);
2463      
2464       /* Remember the last real insn before the label (i.e. end of block 2).  */
2465       if (code == JUMP_INSN || code == INSN)
2466         {
2467           blk_size ++;
2468           end_blk_2_insn = insn;
2469         }
2470     }
2471
2472   if (!insn)
2473     return insn;
2474  
2475   /* It is possible for this optimization to slow performance if the blocks 
2476      are long.  This really depends upon whether the branch is likely taken 
2477      or not.  If the branch is taken, we slow performance in many cases.  But,
2478      if the branch is not taken, we always help performance (for a single 
2479      block, but for a double block (i.e. when the optimization is re-applied) 
2480      this is not true since the 'right thing' depends on the overall length of
2481      the collapsed block).  As a compromise, don't apply this optimization on 
2482      blocks larger than size 2 (unlikely for the mcore) when speed is important.
2483      the best threshold depends on the latencies of the instructions (i.e., 
2484      the branch penalty).  */
2485   if (optimize > 1 && blk_size > 2)
2486     return insn;
2487
2488   /* At this point, we've found the start of block 3 and we know that
2489      it is the destination of the branch from block 1.   Also, all
2490      instructions in the block 2 are conditionalizable.  So, apply the
2491      conditionalization and delete the branch.  */
2492   start_blk_3_lab = insn;   
2493    
2494   for (insn = NEXT_INSN (end_blk_1_br); insn != start_blk_3_lab; 
2495        insn = NEXT_INSN (insn))
2496     {
2497       rtx newinsn;
2498
2499       if (INSN_DELETED_P (insn))
2500         continue;
2501       
2502       /* Try to form a conditional variant of the instruction and emit it.  */
2503       if ((newinsn = emit_new_cond_insn (insn, cond)))
2504         {
2505           if (end_blk_2_insn == insn)
2506             end_blk_2_insn = newinsn;
2507
2508           insn = newinsn;
2509         }
2510     }
2511
2512   /* Note whether we will delete the label starting blk 3 when the jump
2513      gets deleted.  If so, we want to re-apply this optimization at the 
2514      last real instruction right before the label.  */
2515   if (LABEL_NUSES (start_blk_3_lab) == 1)
2516     {
2517       start_blk_3_lab = 0;
2518     }
2519
2520   /* ??? we probably should redistribute the death notes for this insn, esp.
2521      the death of cc, but it doesn't really matter this late in the game.
2522      The peepholes all use is_dead() which will find the correct death
2523      regardless of whether there is a note.  */
2524   delete_insn (end_blk_1_br);
2525
2526   if (! start_blk_3_lab)
2527     return end_blk_2_insn;
2528   
2529   /* Return the insn right after the label at the start of block 3.  */
2530   return NEXT_INSN (start_blk_3_lab);
2531 }
2532
2533 /* Apply the conditionalization of blocks optimization.  This is the
2534    outer loop that traverses through the insns scanning for a branch
2535    that signifies an opportunity to apply the optimization.  Note that
2536    this optimization is applied late.  If we could apply it earlier,
2537    say before cse 2, it may expose more optimization opportunities.  
2538    but, the pay back probably isn't really worth the effort (we'd have 
2539    to update all reg/flow/notes/links/etc to make it work - and stick it
2540    in before cse 2).  */
2541
2542 static void
2543 conditionalize_optimization (void)
2544 {
2545   rtx insn;
2546
2547   for (insn = get_insns (); insn; insn = conditionalize_block (insn))
2548     continue;
2549 }
2550
2551 static int saved_warn_return_type = -1;
2552 static int saved_warn_return_type_count = 0;
2553
2554 /* This is to handle loads from the constant pool.  */
2555
2556 static void
2557 mcore_reorg (void)
2558 {
2559   /* Reset this variable.  */
2560   current_function_anonymous_args = 0;
2561   
2562   /* Restore the warn_return_type if it has been altered.  */
2563   if (saved_warn_return_type != -1)
2564     {
2565       /* Only restore the value if we have reached another function.
2566          The test of warn_return_type occurs in final_function () in
2567          c-decl.c a long time after the code for the function is generated,
2568          so we need a counter to tell us when we have finished parsing that
2569          function and can restore the flag.  */
2570       if (--saved_warn_return_type_count == 0)
2571         {
2572           warn_return_type = saved_warn_return_type;
2573           saved_warn_return_type = -1;
2574         }
2575     }
2576   
2577   if (optimize == 0)
2578     return;
2579   
2580   /* Conditionalize blocks where we can.  */
2581   conditionalize_optimization ();
2582
2583   /* Literal pool generation is now pushed off until the assembler.  */
2584 }
2585
2586 \f
2587 /* Return true if X is something that can be moved directly into r15.  */
2588
2589 bool
2590 mcore_r15_operand_p (rtx x)
2591 {
2592   switch (GET_CODE (x))
2593     {
2594     case CONST_INT:
2595       return mcore_const_ok_for_inline (INTVAL (x));
2596
2597     case REG:
2598     case SUBREG:
2599     case MEM:
2600       return 1;
2601
2602     default:
2603       return 0;
2604     }
2605 }
2606
2607 /* Implement SECONDARY_RELOAD_CLASS.  If RCLASS contains r15, and we can't
2608    directly move X into it, use r1-r14 as a temporary.  */
2609
2610 enum reg_class
2611 mcore_secondary_reload_class (enum reg_class rclass,
2612                               enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
2613 {
2614   if (TEST_HARD_REG_BIT (reg_class_contents[rclass], 15)
2615       && !mcore_r15_operand_p (x))
2616     return LRW_REGS;
2617   return NO_REGS;
2618 }
2619
2620 /* Return the reg_class to use when reloading the rtx X into the class
2621    RCLASS.  If X is too complex to move directly into r15, prefer to
2622    use LRW_REGS instead.  */
2623
2624 enum reg_class
2625 mcore_reload_class (rtx x, enum reg_class rclass)
2626 {
2627   if (reg_class_subset_p (LRW_REGS, rclass) && !mcore_r15_operand_p (x))
2628     return LRW_REGS;
2629
2630   return rclass;
2631 }
2632
2633 /* Tell me if a pair of reg/subreg rtx's actually refer to the same
2634    register.  Note that the current version doesn't worry about whether
2635    they are the same mode or note (e.g., a QImode in r2 matches an HImode
2636    in r2 matches an SImode in r2. Might think in the future about whether
2637    we want to be able to say something about modes.  */
2638
2639 int
2640 mcore_is_same_reg (rtx x, rtx y)
2641 {
2642   /* Strip any and all of the subreg wrappers.  */
2643   while (GET_CODE (x) == SUBREG)
2644     x = SUBREG_REG (x);
2645   
2646   while (GET_CODE (y) == SUBREG)
2647     y = SUBREG_REG (y);
2648
2649   if (GET_CODE(x) == REG && GET_CODE(y) == REG && REGNO(x) == REGNO(y))
2650     return 1;
2651
2652   return 0;
2653 }
2654
2655 void
2656 mcore_override_options (void)
2657 {
2658   /* Only the m340 supports little endian code.  */
2659   if (TARGET_LITTLE_END && ! TARGET_M340)
2660     target_flags |= MASK_M340;
2661 }
2662 \f
2663 /* Compute the number of word sized registers needed to 
2664    hold a function argument of mode MODE and type TYPE.  */
2665
2666 int
2667 mcore_num_arg_regs (enum machine_mode mode, const_tree type)
2668 {
2669   int size;
2670
2671   if (targetm.calls.must_pass_in_stack (mode, type))
2672     return 0;
2673
2674   if (type && mode == BLKmode)
2675     size = int_size_in_bytes (type);
2676   else
2677     size = GET_MODE_SIZE (mode);
2678
2679   return ROUND_ADVANCE (size);
2680 }
2681
2682 static rtx
2683 handle_structs_in_regs (enum machine_mode mode, const_tree type, int reg)
2684 {
2685   int size;
2686
2687   /* The MCore ABI defines that a structure whose size is not a whole multiple
2688      of bytes is passed packed into registers (or spilled onto the stack if
2689      not enough registers are available) with the last few bytes of the
2690      structure being packed, left-justified, into the last register/stack slot.
2691      GCC handles this correctly if the last word is in a stack slot, but we
2692      have to generate a special, PARALLEL RTX if the last word is in an
2693      argument register.  */
2694   if (type
2695       && TYPE_MODE (type) == BLKmode
2696       && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
2697       && (size = int_size_in_bytes (type)) > UNITS_PER_WORD
2698       && (size % UNITS_PER_WORD != 0)
2699       && (reg + mcore_num_arg_regs (mode, type) <= (FIRST_PARM_REG + NPARM_REGS)))
2700     {
2701       rtx    arg_regs [NPARM_REGS]; 
2702       int    nregs;
2703       rtx    result;
2704       rtvec  rtvec;
2705                      
2706       for (nregs = 0; size > 0; size -= UNITS_PER_WORD)
2707         {
2708           arg_regs [nregs] =
2709             gen_rtx_EXPR_LIST (SImode, gen_rtx_REG (SImode, reg ++),
2710                                GEN_INT (nregs * UNITS_PER_WORD));
2711           nregs ++;
2712         }
2713
2714       /* We assume here that NPARM_REGS == 6.  The assert checks this.  */
2715       assert (ARRAY_SIZE (arg_regs) == 6);
2716       rtvec = gen_rtvec (nregs, arg_regs[0], arg_regs[1], arg_regs[2],
2717                           arg_regs[3], arg_regs[4], arg_regs[5]);
2718       
2719       result = gen_rtx_PARALLEL (mode, rtvec);
2720       return result;
2721     }
2722   
2723   return gen_rtx_REG (mode, reg);
2724 }
2725
2726 rtx
2727 mcore_function_value (const_tree valtype, const_tree func ATTRIBUTE_UNUSED)
2728 {
2729   enum machine_mode mode;
2730   int unsigned_p;
2731   
2732   mode = TYPE_MODE (valtype);
2733
2734   mode = promote_mode (valtype, mode, &unsigned_p, 1);
2735   
2736   return handle_structs_in_regs (mode, valtype, FIRST_RET_REG);
2737 }
2738
2739 /* Define where to put the arguments to a function.
2740    Value is zero to push the argument on the stack,
2741    or a hard register in which to store the argument.
2742
2743    MODE is the argument's machine mode.
2744    TYPE is the data type of the argument (as a tree).
2745     This is null for libcalls where that information may
2746     not be available.
2747    CUM is a variable of type CUMULATIVE_ARGS which gives info about
2748     the preceding args and about the function being called.
2749    NAMED is nonzero if this argument is a named parameter
2750     (otherwise it is an extra parameter matching an ellipsis).
2751
2752    On MCore the first args are normally in registers
2753    and the rest are pushed.  Any arg that starts within the first
2754    NPARM_REGS words is at least partially passed in a register unless
2755    its data type forbids.  */
2756
2757 rtx
2758 mcore_function_arg (CUMULATIVE_ARGS cum, enum machine_mode mode,
2759                     tree type, int named)
2760 {
2761   int arg_reg;
2762   
2763   if (! named || mode == VOIDmode)
2764     return 0;
2765
2766   if (targetm.calls.must_pass_in_stack (mode, type))
2767     return 0;
2768
2769   arg_reg = ROUND_REG (cum, mode);
2770   
2771   if (arg_reg < NPARM_REGS)
2772     return handle_structs_in_regs (mode, type, FIRST_PARM_REG + arg_reg);
2773
2774   return 0;
2775 }
2776
2777 /* Returns the number of bytes of argument registers required to hold *part*
2778    of a parameter of machine mode MODE and type TYPE (which may be NULL if
2779    the type is not known).  If the argument fits entirely in the argument
2780    registers, or entirely on the stack, then 0 is returned.  CUM is the
2781    number of argument registers already used by earlier parameters to
2782    the function.  */
2783
2784 static int
2785 mcore_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
2786                          tree type, bool named)
2787 {
2788   int reg = ROUND_REG (*cum, mode);
2789
2790   if (named == 0)
2791     return 0;
2792
2793   if (targetm.calls.must_pass_in_stack (mode, type))
2794     return 0;
2795       
2796   /* REG is not the *hardware* register number of the register that holds
2797      the argument, it is the *argument* register number.  So for example,
2798      the first argument to a function goes in argument register 0, which
2799      translates (for the MCore) into hardware register 2.  The second
2800      argument goes into argument register 1, which translates into hardware
2801      register 3, and so on.  NPARM_REGS is the number of argument registers
2802      supported by the target, not the maximum hardware register number of
2803      the target.  */
2804   if (reg >= NPARM_REGS)
2805     return 0;
2806
2807   /* If the argument fits entirely in registers, return 0.  */
2808   if (reg + mcore_num_arg_regs (mode, type) <= NPARM_REGS)
2809     return 0;
2810
2811   /* The argument overflows the number of available argument registers.
2812      Compute how many argument registers have not yet been assigned to
2813      hold an argument.  */
2814   reg = NPARM_REGS - reg;
2815
2816   /* Return partially in registers and partially on the stack.  */
2817   return reg * UNITS_PER_WORD;
2818 }
2819 \f
2820 /* Return nonzero if SYMBOL is marked as being dllexport'd.  */
2821
2822 int
2823 mcore_dllexport_name_p (const char * symbol)
2824 {
2825   return symbol[0] == '@' && symbol[1] == 'e' && symbol[2] == '.';
2826 }
2827
2828 /* Return nonzero if SYMBOL is marked as being dllimport'd.  */
2829
2830 int
2831 mcore_dllimport_name_p (const char * symbol)
2832 {
2833   return symbol[0] == '@' && symbol[1] == 'i' && symbol[2] == '.';
2834 }
2835
2836 /* Mark a DECL as being dllexport'd.  */
2837
2838 static void
2839 mcore_mark_dllexport (tree decl)
2840 {
2841   const char * oldname;
2842   char * newname;
2843   rtx    rtlname;
2844   tree   idp;
2845
2846   rtlname = XEXP (DECL_RTL (decl), 0);
2847   
2848   if (GET_CODE (rtlname) == MEM)
2849     rtlname = XEXP (rtlname, 0);
2850   gcc_assert (GET_CODE (rtlname) == SYMBOL_REF);
2851   oldname = XSTR (rtlname, 0);
2852   
2853   if (mcore_dllexport_name_p (oldname))
2854     return;  /* Already done.  */
2855
2856   newname = XALLOCAVEC (char, strlen (oldname) + 4);
2857   sprintf (newname, "@e.%s", oldname);
2858
2859   /* We pass newname through get_identifier to ensure it has a unique
2860      address.  RTL processing can sometimes peek inside the symbol ref
2861      and compare the string's addresses to see if two symbols are
2862      identical.  */
2863   /* ??? At least I think that's why we do this.  */
2864   idp = get_identifier (newname);
2865
2866   XEXP (DECL_RTL (decl), 0) =
2867     gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (idp));
2868 }
2869
2870 /* Mark a DECL as being dllimport'd.  */
2871
2872 static void
2873 mcore_mark_dllimport (tree decl)
2874 {
2875   const char * oldname;
2876   char * newname;
2877   tree   idp;
2878   rtx    rtlname;
2879   rtx    newrtl;
2880
2881   rtlname = XEXP (DECL_RTL (decl), 0);
2882   
2883   if (GET_CODE (rtlname) == MEM)
2884     rtlname = XEXP (rtlname, 0);
2885   gcc_assert (GET_CODE (rtlname) == SYMBOL_REF);
2886   oldname = XSTR (rtlname, 0);
2887   
2888   gcc_assert (!mcore_dllexport_name_p (oldname));
2889   if (mcore_dllimport_name_p (oldname))
2890     return; /* Already done.  */
2891
2892   /* ??? One can well ask why we're making these checks here,
2893      and that would be a good question.  */
2894
2895   /* Imported variables can't be initialized.  */
2896   if (TREE_CODE (decl) == VAR_DECL
2897       && !DECL_VIRTUAL_P (decl)
2898       && DECL_INITIAL (decl))
2899     {
2900       error ("initialized variable %q+D is marked dllimport", decl);
2901       return;
2902     }
2903   
2904   /* `extern' needn't be specified with dllimport.
2905      Specify `extern' now and hope for the best.  Sigh.  */
2906   if (TREE_CODE (decl) == VAR_DECL
2907       /* ??? Is this test for vtables needed?  */
2908       && !DECL_VIRTUAL_P (decl))
2909     {
2910       DECL_EXTERNAL (decl) = 1;
2911       TREE_PUBLIC (decl) = 1;
2912     }
2913
2914   newname = XALLOCAVEC (char, strlen (oldname) + 11);
2915   sprintf (newname, "@i.__imp_%s", oldname);
2916
2917   /* We pass newname through get_identifier to ensure it has a unique
2918      address.  RTL processing can sometimes peek inside the symbol ref
2919      and compare the string's addresses to see if two symbols are
2920      identical.  */
2921   /* ??? At least I think that's why we do this.  */
2922   idp = get_identifier (newname);
2923
2924   newrtl = gen_rtx_MEM (Pmode,
2925                     gen_rtx_SYMBOL_REF (Pmode,
2926                              IDENTIFIER_POINTER (idp)));
2927   XEXP (DECL_RTL (decl), 0) = newrtl;
2928 }
2929
2930 static int
2931 mcore_dllexport_p (tree decl)
2932 {
2933   if (   TREE_CODE (decl) != VAR_DECL
2934       && TREE_CODE (decl) != FUNCTION_DECL)
2935     return 0;
2936
2937   return lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)) != 0;
2938 }
2939
2940 static int
2941 mcore_dllimport_p (tree decl)
2942 {
2943   if (   TREE_CODE (decl) != VAR_DECL
2944       && TREE_CODE (decl) != FUNCTION_DECL)
2945     return 0;
2946
2947   return lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl)) != 0;
2948 }
2949
2950 /* We must mark dll symbols specially.  Definitions of dllexport'd objects
2951    install some info in the .drective (PE) or .exports (ELF) sections.  */
2952
2953 static void
2954 mcore_encode_section_info (tree decl, rtx rtl ATTRIBUTE_UNUSED, int first ATTRIBUTE_UNUSED)
2955 {
2956   /* Mark the decl so we can tell from the rtl whether the object is
2957      dllexport'd or dllimport'd.  */
2958   if (mcore_dllexport_p (decl))
2959     mcore_mark_dllexport (decl);
2960   else if (mcore_dllimport_p (decl))
2961     mcore_mark_dllimport (decl);
2962   
2963   /* It might be that DECL has already been marked as dllimport, but
2964      a subsequent definition nullified that.  The attribute is gone
2965      but DECL_RTL still has @i.__imp_foo.  We need to remove that.  */
2966   else if ((TREE_CODE (decl) == FUNCTION_DECL
2967             || TREE_CODE (decl) == VAR_DECL)
2968            && DECL_RTL (decl) != NULL_RTX
2969            && GET_CODE (DECL_RTL (decl)) == MEM
2970            && GET_CODE (XEXP (DECL_RTL (decl), 0)) == MEM
2971            && GET_CODE (XEXP (XEXP (DECL_RTL (decl), 0), 0)) == SYMBOL_REF
2972            && mcore_dllimport_name_p (XSTR (XEXP (XEXP (DECL_RTL (decl), 0), 0), 0)))
2973     {
2974       const char * oldname = XSTR (XEXP (XEXP (DECL_RTL (decl), 0), 0), 0);
2975       tree idp = get_identifier (oldname + 9);
2976       rtx newrtl = gen_rtx_SYMBOL_REF (Pmode, IDENTIFIER_POINTER (idp));
2977
2978       XEXP (DECL_RTL (decl), 0) = newrtl;
2979
2980       /* We previously set TREE_PUBLIC and DECL_EXTERNAL.
2981          ??? We leave these alone for now.  */
2982     }
2983 }
2984
2985 /* Undo the effects of the above.  */
2986
2987 static const char *
2988 mcore_strip_name_encoding (const char * str)
2989 {
2990   return str + (str[0] == '@' ? 3 : 0);
2991 }
2992
2993 /* MCore specific attribute support.
2994    dllexport - for exporting a function/variable that will live in a dll
2995    dllimport - for importing a function/variable from a dll
2996    naked     - do not create a function prologue/epilogue.  */
2997
2998 const struct attribute_spec mcore_attribute_table[] =
2999 {
3000   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
3001   { "dllexport", 0, 0, true,  false, false, NULL },
3002   { "dllimport", 0, 0, true,  false, false, NULL },
3003   { "naked",     0, 0, true,  false, false, mcore_handle_naked_attribute },
3004   { NULL,        0, 0, false, false, false, NULL }
3005 };
3006
3007 /* Handle a "naked" attribute; arguments as in
3008    struct attribute_spec.handler.  */
3009
3010 static tree
3011 mcore_handle_naked_attribute (tree * node, tree name, tree args ATTRIBUTE_UNUSED,
3012                               int flags ATTRIBUTE_UNUSED, bool * no_add_attrs)
3013 {
3014   if (TREE_CODE (*node) == FUNCTION_DECL)
3015     {
3016       /* PR14310 - don't complain about lack of return statement
3017          in naked functions.  The solution here is a gross hack
3018          but this is the only way to solve the problem without
3019          adding a new feature to GCC.  I did try submitting a patch
3020          that would add such a new feature, but it was (rightfully)
3021          rejected on the grounds that it was creeping featurism,
3022          so hence this code.  */
3023       if (warn_return_type)
3024         {
3025           saved_warn_return_type = warn_return_type;
3026           warn_return_type = 0;
3027           saved_warn_return_type_count = 2;
3028         }
3029       else if (saved_warn_return_type_count)
3030         saved_warn_return_type_count = 2;
3031     }
3032   else
3033     {
3034       warning (OPT_Wattributes, "%qs attribute only applies to functions",
3035                IDENTIFIER_POINTER (name));
3036       *no_add_attrs = true;
3037     }
3038
3039   return NULL_TREE;
3040 }
3041
3042 /* ??? It looks like this is PE specific?  Oh well, this is what the
3043    old code did as well.  */
3044
3045 static void
3046 mcore_unique_section (tree decl, int reloc ATTRIBUTE_UNUSED)
3047 {
3048   int len;
3049   const char * name;
3050   char * string;
3051   const char * prefix;
3052
3053   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
3054   
3055   /* Strip off any encoding in name.  */
3056   name = (* targetm.strip_name_encoding) (name);
3057
3058   /* The object is put in, for example, section .text$foo.
3059      The linker will then ultimately place them in .text
3060      (everything from the $ on is stripped).  */
3061   if (TREE_CODE (decl) == FUNCTION_DECL)
3062     prefix = ".text$";
3063   /* For compatibility with EPOC, we ignore the fact that the
3064      section might have relocs against it.  */
3065   else if (decl_readonly_section (decl, 0))
3066     prefix = ".rdata$";
3067   else
3068     prefix = ".data$";
3069   
3070   len = strlen (name) + strlen (prefix);
3071   string = XALLOCAVEC (char, len + 1);
3072   
3073   sprintf (string, "%s%s", prefix, name);
3074
3075   DECL_SECTION_NAME (decl) = build_string (len, string);
3076 }
3077
3078 int
3079 mcore_naked_function_p (void)
3080 {
3081   return lookup_attribute ("naked", DECL_ATTRIBUTES (current_function_decl)) != NULL_TREE;
3082 }
3083
3084 #ifdef OBJECT_FORMAT_ELF
3085 static void
3086 mcore_asm_named_section (const char *name, 
3087                          unsigned int flags ATTRIBUTE_UNUSED,
3088                          tree decl ATTRIBUTE_UNUSED)
3089 {
3090   fprintf (asm_out_file, "\t.section %s\n", name);
3091 }
3092 #endif /* OBJECT_FORMAT_ELF */
3093
3094 /* Worker function for TARGET_ASM_EXTERNAL_LIBCALL.  */
3095
3096 static void
3097 mcore_external_libcall (rtx fun)
3098 {
3099   fprintf (asm_out_file, "\t.import\t");
3100   assemble_name (asm_out_file, XSTR (fun, 0));
3101   fprintf (asm_out_file, "\n");
3102 }
3103
3104 /* Worker function for TARGET_RETURN_IN_MEMORY.  */
3105
3106 static bool
3107 mcore_return_in_memory (const_tree type, const_tree fntype ATTRIBUTE_UNUSED)
3108 {
3109   const HOST_WIDE_INT size = int_size_in_bytes (type);
3110   return (size == -1 || size > 2 * UNITS_PER_WORD);
3111 }