129b916715e1fdc4bcc85996d590bbed6b1754a9
[platform/upstream/gcc.git] / gcc / config / msp430 / msp430.c
1 /* Subroutines used for code generation on TI MSP430 processors.
2    Copyright (C) 2012-2020 Free Software Foundation, Inc.
3    Contributed by Red Hat.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    GCC is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public 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 #define IN_TARGET_CODE 1
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "backend.h"
27 #include "target.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "stringpool.h"
31 #include "attribs.h"
32 #include "gimple-expr.h"
33 #include "df.h"
34 #include "memmodel.h"
35 #include "tm_p.h"
36 #include "regs.h"
37 #include "emit-rtl.h"
38 #include "varasm.h"
39 #include "diagnostic-core.h"
40 #include "fold-const.h"
41 #include "stor-layout.h"
42 #include "calls.h"
43 #include "output.h"
44 #include "explow.h"
45 #include "expr.h"
46 #include "langhooks.h"
47 #include "builtins.h"
48 #include "intl.h"
49 #include "msp430-devices.h"
50 #include "incpath.h"
51 #include "prefix.h"
52
53 /* This file should be included last.  */
54 #include "target-def.h"
55 \f
56
57 static void msp430_compute_frame_info (void);
58 static bool use_32bit_hwmult (void);
59
60 \f
61
62 /* Run-time Target Specification.  */
63
64 bool msp430x = true;
65
66 struct GTY(()) machine_function
67 {
68   /* If set, the rest of the fields have been computed.  */
69   int computed;
70   /* Which registers need to be saved in the pro/epilogue.  */
71   int need_to_save[FIRST_PSEUDO_REGISTER];
72
73   /* These fields describe the frame layout...  */
74   /* arg pointer */
75   /* 2/4 bytes for saved PC */
76   int framesize_regs;
77   /* frame pointer */
78   int framesize_locals;
79   int framesize_outgoing;
80   /* stack pointer */
81   int framesize;
82
83   /* How much we adjust the stack when returning from an exception
84      handler.  */
85   rtx eh_stack_adjust;
86 };
87
88 /* This is our init_machine_status, as set in
89    msp430_option_override.  */
90 static struct machine_function *
91 msp430_init_machine_status (void)
92 {
93   struct machine_function *m;
94
95   m = ggc_cleared_alloc<machine_function> ();
96
97   return m;
98 }
99
100 #undef  TARGET_OPTION_OVERRIDE
101 #define TARGET_OPTION_OVERRIDE          msp430_option_override
102
103 /* Generate a C preprocessor symbol based upon the MCU selected by the user.
104    If a specific MCU has not been selected then return a generic symbol
105    instead.  */
106
107 const char *
108 msp430_mcu_name (void)
109 {
110   if (target_mcu)
111     {
112       msp430_extract_mcu_data (target_mcu);
113       unsigned int i;
114       unsigned int start_upper;
115       unsigned int end_upper;
116       static char mcu_name[64];
117
118       /* The 'i' in the device name symbol for msp430i* devices must be lower
119          case, to match the expected symbol in msp430.h.  */
120       if (strncmp (target_mcu, "msp430i", 7) == 0)
121         {
122           snprintf (mcu_name, sizeof (mcu_name) - 1, "__MSP430i%s__",
123                     target_mcu + 7);
124           start_upper = 9;
125         }
126       else
127         {
128           snprintf (mcu_name, sizeof (mcu_name) - 1, "__%s__", target_mcu);
129           start_upper = 2;
130         }
131       end_upper = strlen (mcu_name) - 2;
132       for (i = start_upper; i < end_upper; i++)
133         mcu_name[i] = TOUPPER (mcu_name[i]);
134       return mcu_name;
135     }
136
137   return msp430x ? "__MSP430XGENERIC__" : "__MSP430GENERIC__";
138 }
139
140 static const char *
141 hwmult_name (unsigned int val)
142 {
143   switch (val)
144     {
145     case 0: return "none";
146     case 1: return "16-bit";
147     case 2: return "16-bit";
148     case 4: return "32-bit";
149     case 8: return "32-bit (5xx)";
150     default: gcc_unreachable ();
151     }
152 }
153
154 static void
155 msp430_option_override (void)
156 {
157   /* The MSP430 architecture can safely dereference a NULL pointer.  In fact,
158      there are memory mapped registers there.  */
159   flag_delete_null_pointer_checks = 0;
160
161   init_machine_status = msp430_init_machine_status;
162
163   if (target_cpu)
164     {
165       /* gcc/common/config/msp430-common.c will have
166          already canonicalised the string in target_cpu.  */
167       if (strcasecmp (target_cpu, "msp430x") == 0)
168         msp430x = true;
169       else /* target_cpu == "msp430" - already handled by the front end.  */
170         msp430x = false;
171     }
172
173   if (target_mcu)
174     {
175       msp430_extract_mcu_data (target_mcu);
176
177       if (extracted_mcu_data.name != NULL)
178         {
179           bool xisa = extracted_mcu_data.revision >= 1;
180
181           if (msp430_warn_mcu)
182             {
183               if (target_cpu && msp430x != xisa)
184                 warning (0, "MCU %qs supports %s ISA but %<-mcpu%> option "
185                          "is set to %s",
186                          target_mcu, xisa ? "430X" : "430",
187                          msp430x ? "430X" : "430");
188
189               if (extracted_mcu_data.hwmpy == 0
190                   && msp430_hwmult_type != MSP430_HWMULT_AUTO
191                   && msp430_hwmult_type != MSP430_HWMULT_NONE)
192                 warning (0, "MCU %qs does not have hardware multiply "
193                          "support, but %<-mhwmult%> is set to %s",
194                          target_mcu,
195                          msp430_hwmult_type == MSP430_HWMULT_SMALL ? "16-bit"
196                          : msp430_hwmult_type == MSP430_HWMULT_LARGE
197                          ? "32-bit" : "f5series");
198               else if (msp430_hwmult_type == MSP430_HWMULT_SMALL
199                        && extracted_mcu_data.hwmpy != 1
200                        && extracted_mcu_data.hwmpy != 2)
201                 warning (0, "MCU %qs supports %s hardware multiply, "
202                          "but %<-mhwmult%> is set to 16-bit",
203                          target_mcu, hwmult_name (extracted_mcu_data.hwmpy));
204               else if (msp430_hwmult_type == MSP430_HWMULT_LARGE
205                        && extracted_mcu_data.hwmpy != 4)
206                 warning (0, "MCU %qs supports %s hardware multiply, "
207                          "but %<-mhwmult%> is set to 32-bit",
208                          target_mcu, hwmult_name (extracted_mcu_data.hwmpy));
209               else if (msp430_hwmult_type == MSP430_HWMULT_F5SERIES
210                        && extracted_mcu_data.hwmpy != 8)
211                 warning (0, "MCU %qs supports %s hardware multiply, "
212                          "but %<-mhwmult%> is set to f5series",
213                          target_mcu, hwmult_name (extracted_mcu_data.hwmpy));
214             }
215           msp430x = xisa;
216         }
217       else
218         {
219           if (msp430_hwmult_type == MSP430_HWMULT_AUTO)
220             {
221               if (msp430_warn_mcu)
222                 {
223                   if (target_cpu == NULL)
224                     warning (0,
225                              "Unrecognized MCU name %qs, assuming that it is "
226                              "just a MSP430X with no hardware multiply.\n"
227                              "Use the %<-mcpu%> and %<-mhwmult%> options to "
228                              "set these explicitly.",
229                              target_mcu);
230                   else
231                     warning (0,
232                              "Unrecognized MCU name %qs, assuming that it "
233                              "has no hardware multiply.\nUse the %<-mhwmult%> "
234                              "option to set this explicitly.",
235                              target_mcu);
236                 }
237
238               msp430_hwmult_type = MSP430_HWMULT_NONE;
239             }
240           else if (target_cpu == NULL)
241             {
242               if (msp430_warn_mcu)
243                 warning (0,
244                          "Unrecognized MCU name %qs, assuming that it just "
245                          "supports the MSP430X ISA.\nUse the %<-mcpu%> option "
246                          "to set the ISA explicitly.",
247                          target_mcu);
248             }
249           else if (msp430_warn_mcu)
250             warning (0, "Unrecognized MCU name %qs.", target_mcu);
251         }
252     }
253
254   if (TARGET_LARGE && !msp430x)
255     error ("%<-mlarge%> requires a 430X-compatible %<-mmcu=%>");
256
257   if (!TARGET_LARGE && msp430_code_region == MSP430_REGION_EITHER)
258     error ("%<-mcode-region=either%> requires the large memory model "
259            "(%<-mlarge%>)");
260   else if (!TARGET_LARGE && msp430_code_region == MSP430_REGION_UPPER)
261     error ("%<-mcode-region=upper%> requires the large memory model "
262            "(%<-mlarge%>)");
263
264   if (!TARGET_LARGE && msp430_data_region == MSP430_REGION_EITHER)
265     error ("%<-mdata-region=either%> requires the large memory model "
266            "(%<-mlarge%>)");
267   else if (!TARGET_LARGE && msp430_data_region == MSP430_REGION_UPPER)
268     error ("%<-mdata-region=upper%> requires the large memory model "
269            "(%<-mlarge%>)");
270
271   if (flag_exceptions || flag_non_call_exceptions
272       || flag_unwind_tables || flag_asynchronous_unwind_tables)
273     flag_omit_frame_pointer = false;
274   else
275     flag_omit_frame_pointer = true;
276
277   /* This is a hack to work around a problem with the newlib build
278      mechanism.  Newlib always appends CFLAGS to the end of the GCC
279      command line and always sets -O2 in CFLAGS.  Thus it is not
280      possible to build newlib with -Os enabled.  Until now...  */
281   if (TARGET_OPT_SPACE && optimize < 3)
282     optimize_size = 1;
283
284 #if !DEFAULT_USE_CXA_ATEXIT
285   /* For some configurations, we use atexit () instead of __cxa_atexit () by
286      default to save on code size and remove the declaration of __dso_handle
287      from the CRT library.
288      Configuring GCC with --enable-__cxa-atexit re-enables it by defining
289      DEFAULT_USE_CXA_ATEXIT to 1.  */
290   if (flag_use_cxa_atexit)
291     error ("%<-fuse-cxa-atexit%> is not supported for msp430-elf");
292 #endif
293
294 #ifndef HAVE_NEWLIB_NANO_FORMATTED_IO
295   if (TARGET_TINY_PRINTF)
296     error ("GCC must be configured with %<--enable-newlib-nano-formatted-io%> "
297            "to use %<-mtiny-printf%>");
298 #endif
299 }
300
301 #undef  TARGET_SCALAR_MODE_SUPPORTED_P
302 #define TARGET_SCALAR_MODE_SUPPORTED_P msp430_scalar_mode_supported_p
303
304 static bool
305 msp430_scalar_mode_supported_p (scalar_mode m)
306 {
307   if (m == PSImode && msp430x)
308     return true;
309 #if 0
310   if (m == TImode)
311     return true;
312 #endif
313   return default_scalar_mode_supported_p (m);
314 }
315
316 \f
317
318 /* Storage Layout */
319
320 #undef  TARGET_MS_BITFIELD_LAYOUT_P
321 #define TARGET_MS_BITFIELD_LAYOUT_P msp430_ms_bitfield_layout_p
322
323 bool
324 msp430_ms_bitfield_layout_p (const_tree record_type ATTRIBUTE_UNUSED)
325 {
326   return false;
327 }
328
329 \f
330
331 /* Register Usage */
332
333 #undef TARGET_HARD_REGNO_NREGS
334 #define TARGET_HARD_REGNO_NREGS msp430_hard_regno_nregs
335
336 static unsigned int
337 msp430_hard_regno_nregs (unsigned int, machine_mode mode)
338 {
339   if (mode == PSImode && msp430x)
340     return 1;
341   if (mode == CPSImode && msp430x)
342     return 2;
343   return ((GET_MODE_SIZE (mode) + UNITS_PER_WORD - 1)
344           / UNITS_PER_WORD);
345 }
346
347 /* subreg_get_info correctly handles PSImode registers, so defining
348    HARD_REGNO_NREGS_HAS_PADDING and HARD_REGNO_NREGS_WITH_PADDING
349    has no effect.  */
350
351 #undef TARGET_HARD_REGNO_MODE_OK
352 #define TARGET_HARD_REGNO_MODE_OK msp430_hard_regno_mode_ok
353
354 static bool
355 msp430_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
356 {
357   return regno <= (ARG_POINTER_REGNUM
358                    - (unsigned int) msp430_hard_regno_nregs (regno, mode));
359 }
360
361 #undef TARGET_MODES_TIEABLE_P
362 #define TARGET_MODES_TIEABLE_P msp430_modes_tieable_p
363
364 static bool
365 msp430_modes_tieable_p (machine_mode mode1, machine_mode mode2)
366 {
367   if ((mode1 == PSImode || mode2 == SImode)
368       || (mode1 == SImode || mode2 == PSImode))
369     return false;
370
371   return ((GET_MODE_CLASS (mode1) == MODE_FLOAT
372            || GET_MODE_CLASS (mode1) == MODE_COMPLEX_FLOAT)
373           == (GET_MODE_CLASS (mode2) == MODE_FLOAT
374               || GET_MODE_CLASS (mode2) == MODE_COMPLEX_FLOAT));
375 }
376
377 #undef  TARGET_FRAME_POINTER_REQUIRED
378 #define TARGET_FRAME_POINTER_REQUIRED msp430_frame_pointer_required
379
380 static bool
381 msp430_frame_pointer_required (void)
382 {
383   return false;
384 }
385
386 #undef  TARGET_CAN_ELIMINATE
387 #define TARGET_CAN_ELIMINATE            msp430_can_eliminate
388
389 static bool
390 msp430_can_eliminate (const int from_reg ATTRIBUTE_UNUSED,
391                       const int to_reg ATTRIBUTE_UNUSED)
392 {
393   return true;
394 }
395
396 /* Implements INITIAL_ELIMINATION_OFFSET.  */
397 int
398 msp430_initial_elimination_offset (int from, int to)
399 {
400   int rv = 0; /* As if arg to arg.  */
401
402   msp430_compute_frame_info ();
403
404   switch (to)
405     {
406     case STACK_POINTER_REGNUM:
407       rv += cfun->machine->framesize_outgoing;
408       rv += cfun->machine->framesize_locals;
409       /* Fall through.  */
410     case FRAME_POINTER_REGNUM:
411       rv += cfun->machine->framesize_regs;
412       /* Allow for the saved return address.  */
413       rv += (TARGET_LARGE ? 4 : 2);
414       /* NB/ No need to allow for crtl->args.pretend_args_size.
415          GCC does that for us.  */
416       break;
417     default:
418       gcc_unreachable ();
419     }
420
421   switch (from)
422     {
423     case FRAME_POINTER_REGNUM:
424       /* Allow for the fall through above.  */
425       rv -= (TARGET_LARGE ? 4 : 2);
426       rv -= cfun->machine->framesize_regs;
427     case ARG_POINTER_REGNUM:
428       break;
429     default:
430       gcc_unreachable ();
431     }
432
433   return rv;
434 }
435 \f
436 /* Named Address Space support */
437
438
439 /* Return the appropriate mode for a named address pointer.  */
440 #undef  TARGET_ADDR_SPACE_POINTER_MODE
441 #define TARGET_ADDR_SPACE_POINTER_MODE msp430_addr_space_pointer_mode
442 #undef  TARGET_ADDR_SPACE_ADDRESS_MODE
443 #define TARGET_ADDR_SPACE_ADDRESS_MODE msp430_addr_space_pointer_mode
444
445 static scalar_int_mode
446 msp430_addr_space_pointer_mode (addr_space_t addrspace)
447 {
448   switch (addrspace)
449     {
450     default:
451     case ADDR_SPACE_GENERIC:
452       return Pmode;
453     case ADDR_SPACE_NEAR:
454       return HImode;
455     case ADDR_SPACE_FAR:
456       return PSImode;
457     }
458 }
459
460 /* Function pointers are stored in unwind_word sized
461    variables, so make sure that unwind_word is big enough.  */
462 #undef  TARGET_UNWIND_WORD_MODE
463 #define TARGET_UNWIND_WORD_MODE msp430_unwind_word_mode
464
465 static scalar_int_mode
466 msp430_unwind_word_mode (void)
467 {
468   /* This needs to match msp430_init_dwarf_reg_sizes_extra (below).  */
469   return msp430x ? PSImode : HImode;
470 }
471
472 /* Determine if one named address space is a subset of another.  */
473 #undef  TARGET_ADDR_SPACE_SUBSET_P
474 #define TARGET_ADDR_SPACE_SUBSET_P msp430_addr_space_subset_p
475 static bool
476 msp430_addr_space_subset_p (addr_space_t subset, addr_space_t superset)
477 {
478   if (subset == superset)
479     return true;
480   else
481     return (subset != ADDR_SPACE_FAR && superset == ADDR_SPACE_FAR);
482 }
483
484 #undef  TARGET_ADDR_SPACE_CONVERT
485 #define TARGET_ADDR_SPACE_CONVERT msp430_addr_space_convert
486 /* Convert from one address space to another.  */
487 static rtx
488 msp430_addr_space_convert (rtx op, tree from_type, tree to_type)
489 {
490   addr_space_t from_as = TYPE_ADDR_SPACE (TREE_TYPE (from_type));
491   addr_space_t to_as = TYPE_ADDR_SPACE (TREE_TYPE (to_type));
492   rtx result;
493
494   if (to_as != ADDR_SPACE_FAR && from_as == ADDR_SPACE_FAR)
495     {
496       /* This is unpredictable, as we're truncating off usable address
497          bits.  */
498
499       if (CONSTANT_P (op))
500         return gen_rtx_CONST (HImode, op);
501
502       result = gen_reg_rtx (HImode);
503       emit_insn (gen_truncpsihi2 (result, op));
504       return result;
505     }
506   else if (to_as == ADDR_SPACE_FAR && from_as != ADDR_SPACE_FAR)
507     {
508       /* This always works.  */
509
510       if (CONSTANT_P (op))
511         return gen_rtx_CONST (PSImode, op);
512
513       result = gen_reg_rtx (PSImode);
514       emit_insn (gen_zero_extendhipsi2 (result, op));
515       return result;
516     }
517   else
518     gcc_unreachable ();
519 }
520 \f
521 /* Stack Layout and Calling Conventions.  */
522
523 /* For each function, we list the gcc version and the TI version on
524    each line, where we're converting the function names.  */
525 static char const * const special_convention_function_names[] =
526 {
527   "__muldi3", "__mspabi_mpyll",
528   "__udivdi3", "__mspabi_divull",
529   "__umoddi3", "__mspabi_remull",
530   "__divdi3", "__mspabi_divlli",
531   "__moddi3", "__mspabi_remlli",
532   "__mspabi_srall",
533   "__mspabi_srlll",
534   "__mspabi_sllll",
535   "__adddf3", "__mspabi_addd",
536   "__subdf3", "__mspabi_subd",
537   "__muldf3", "__mspabi_mpyd",
538   "__divdf3", "__mspabi_divd",
539   "__mspabi_cmpd",
540   NULL
541 };
542
543 /* TRUE if the function passed is a "speical" function.  Special
544    functions pass two DImode parameters in registers.  */
545 static bool
546 msp430_special_register_convention_p (const char *name)
547 {
548   int i;
549
550   for (i = 0; special_convention_function_names[i]; i++)
551     if (!strcmp (name, special_convention_function_names[i]))
552       return true;
553
554   return false;
555 }
556
557 #undef  TARGET_FUNCTION_VALUE_REGNO_P
558 #define TARGET_FUNCTION_VALUE_REGNO_P msp430_function_value_regno_p
559
560 bool
561 msp430_function_value_regno_p (unsigned int regno)
562 {
563   return regno == 12;
564 }
565
566
567 #undef  TARGET_FUNCTION_VALUE
568 #define TARGET_FUNCTION_VALUE msp430_function_value
569
570 rtx
571 msp430_function_value (const_tree ret_type,
572                        const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
573                        bool outgoing ATTRIBUTE_UNUSED)
574 {
575   return gen_rtx_REG (TYPE_MODE (ret_type), 12);
576 }
577
578 #undef  TARGET_LIBCALL_VALUE
579 #define TARGET_LIBCALL_VALUE msp430_libcall_value
580
581 rtx
582 msp430_libcall_value (machine_mode mode, const_rtx fun ATTRIBUTE_UNUSED)
583 {
584   return gen_rtx_REG (mode, 12);
585 }
586
587 /* Implements INIT_CUMULATIVE_ARGS.  */
588 void
589 msp430_init_cumulative_args (CUMULATIVE_ARGS *ca,
590                              tree fntype ATTRIBUTE_UNUSED,
591                              rtx libname ATTRIBUTE_UNUSED,
592                              tree fndecl ATTRIBUTE_UNUSED,
593                              int n_named_args ATTRIBUTE_UNUSED)
594 {
595   const char *fname;
596   memset (ca, 0, sizeof(*ca));
597
598   ca->can_split = 1;
599
600   if (fndecl)
601     fname = IDENTIFIER_POINTER (DECL_NAME (fndecl));
602   else if (libname)
603     fname = XSTR (libname, 0);
604   else
605     fname = NULL;
606
607   if (fname && msp430_special_register_convention_p (fname))
608     ca->special_p = 1;
609 }
610
611 /* Helper function for argument passing; this function is the common
612    code that determines where an argument will be passed.  */
613 static void
614 msp430_evaluate_arg (cumulative_args_t cap,
615                      machine_mode mode,
616                      const_tree type ATTRIBUTE_UNUSED,
617                      bool named)
618 {
619   CUMULATIVE_ARGS *ca = get_cumulative_args (cap);
620   int nregs = GET_MODE_SIZE (mode);
621   int i;
622
623   ca->reg_count = 0;
624   ca->mem_count = 0;
625
626   if (!named)
627     return;
628
629   if (mode == PSImode)
630     nregs = 1;
631   else
632     nregs = (nregs + 1) / 2;
633
634   if (ca->special_p)
635     {
636       /* Function is passed two DImode operands, in R8:R11 and
637          R12:15.  */
638       ca->start_reg = 8;
639       ca->reg_count = 4;
640       return;
641     }
642
643   switch (nregs)
644     {
645     case 1:
646       for (i = 0; i < 4; i++)
647         if (!ca->reg_used[i])
648           {
649             ca->reg_count = 1;
650             ca->start_reg = CA_FIRST_REG + i;
651             return;
652           }
653       break;
654     case 2:
655       for (i = 0; i < 3; i++)
656         if (!ca->reg_used[i] && !ca->reg_used[i + 1])
657           {
658             ca->reg_count = 2;
659             ca->start_reg = CA_FIRST_REG + i;
660             return;
661           }
662       if (!ca->reg_used[3] && ca->can_split)
663         {
664           ca->reg_count = 1;
665           ca->mem_count = 2;
666           ca->start_reg = CA_FIRST_REG + 3;
667           return;
668         }
669       break;
670     case 3:
671     case 4:
672       ca->can_split = 0;
673       if (!ca->reg_used[0]
674           && !ca->reg_used[1]
675           && !ca->reg_used[2]
676           && !ca->reg_used[3])
677         {
678           ca->reg_count = 4;
679           ca->start_reg = CA_FIRST_REG;
680           return;
681         }
682       break;
683     }
684 }
685
686 #undef  TARGET_PROMOTE_PROTOTYPES
687 #define TARGET_PROMOTE_PROTOTYPES msp430_promote_prototypes
688
689 bool
690 msp430_promote_prototypes (const_tree fntype ATTRIBUTE_UNUSED)
691 {
692   return false;
693 }
694
695 #undef  TARGET_FUNCTION_ARG
696 #define TARGET_FUNCTION_ARG msp430_function_arg
697
698 rtx
699 msp430_function_arg (cumulative_args_t cap,
700                      const function_arg_info &arg)
701 {
702   CUMULATIVE_ARGS *ca = get_cumulative_args (cap);
703
704   msp430_evaluate_arg (cap, arg.mode, arg.type, arg.named);
705
706   if (ca->reg_count)
707     return gen_rtx_REG (arg.mode, ca->start_reg);
708
709   return 0;
710 }
711
712 #undef  TARGET_ARG_PARTIAL_BYTES
713 #define TARGET_ARG_PARTIAL_BYTES msp430_arg_partial_bytes
714
715 int
716 msp430_arg_partial_bytes (cumulative_args_t cap, const function_arg_info &arg)
717 {
718   CUMULATIVE_ARGS *ca = get_cumulative_args (cap);
719
720   msp430_evaluate_arg (cap, arg.mode, arg.type, arg.named);
721
722   if (ca->reg_count && ca->mem_count)
723     return ca->reg_count * UNITS_PER_WORD;
724
725   return 0;
726 }
727
728 #undef  TARGET_PASS_BY_REFERENCE
729 #define TARGET_PASS_BY_REFERENCE msp430_pass_by_reference
730
731 static bool
732 msp430_pass_by_reference (cumulative_args_t, const function_arg_info &arg)
733 {
734   return (arg.mode == BLKmode
735           || (arg.type && TREE_CODE (arg.type) == RECORD_TYPE)
736           || (arg.type && TREE_CODE (arg.type) == UNION_TYPE));
737 }
738
739 #undef  TARGET_CALLEE_COPIES
740 #define TARGET_CALLEE_COPIES hook_bool_CUMULATIVE_ARGS_arg_info_true
741
742 #undef  TARGET_FUNCTION_ARG_ADVANCE
743 #define TARGET_FUNCTION_ARG_ADVANCE msp430_function_arg_advance
744
745 void
746 msp430_function_arg_advance (cumulative_args_t cap,
747                              const function_arg_info &arg)
748 {
749   CUMULATIVE_ARGS *ca = get_cumulative_args (cap);
750   int i;
751
752   msp430_evaluate_arg (cap, arg.mode, arg.type, arg.named);
753
754   if (ca->start_reg >= CA_FIRST_REG)
755     for (i = 0; i < ca->reg_count; i ++)
756       ca->reg_used[i + ca->start_reg - CA_FIRST_REG] = 1;
757
758   ca->special_p = 0;
759 }
760
761 #undef  TARGET_FUNCTION_ARG_BOUNDARY
762 #define TARGET_FUNCTION_ARG_BOUNDARY msp430_function_arg_boundary
763
764 static unsigned int
765 msp430_function_arg_boundary (machine_mode mode, const_tree type)
766 {
767   if (mode == BLKmode
768       && int_size_in_bytes (type) > 1)
769     return 16;
770   if (GET_MODE_BITSIZE (mode) > 8)
771     return 16;
772   return 8;
773 }
774
775 #undef  TARGET_RETURN_IN_MEMORY
776 #define TARGET_RETURN_IN_MEMORY msp430_return_in_memory
777
778 static bool
779 msp430_return_in_memory (const_tree ret_type,
780                          const_tree fntype ATTRIBUTE_UNUSED)
781 {
782   machine_mode mode = TYPE_MODE (ret_type);
783
784   if (mode == BLKmode
785       || (fntype && TREE_CODE (TREE_TYPE (fntype)) == RECORD_TYPE)
786       || (fntype && TREE_CODE (TREE_TYPE (fntype)) == UNION_TYPE))
787     return true;
788
789   if (GET_MODE_SIZE (mode) > 8)
790     return true;
791
792   return false;
793 }
794
795 #undef  TARGET_GET_RAW_ARG_MODE
796 #define TARGET_GET_RAW_ARG_MODE msp430_get_raw_arg_mode
797
798 static fixed_size_mode
799 msp430_get_raw_arg_mode (int regno)
800 {
801   return as_a <fixed_size_mode> (regno == ARG_POINTER_REGNUM
802                                  ? VOIDmode : Pmode);
803 }
804
805 #undef  TARGET_GET_RAW_RESULT_MODE
806 #define TARGET_GET_RAW_RESULT_MODE msp430_get_raw_result_mode
807
808 static fixed_size_mode
809 msp430_get_raw_result_mode (int regno ATTRIBUTE_UNUSED)
810 {
811   return Pmode;
812 }
813
814 #undef  TARGET_GIMPLIFY_VA_ARG_EXPR
815 #define TARGET_GIMPLIFY_VA_ARG_EXPR msp430_gimplify_va_arg_expr
816
817 #include "gimplify.h"
818
819 static tree
820 msp430_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
821                              gimple_seq *post_p)
822 {
823   tree addr, t, type_size, rounded_size, valist_tmp;
824   unsigned HOST_WIDE_INT align, boundary;
825   bool indirect;
826
827   indirect = pass_va_arg_by_reference (type);
828   if (indirect)
829     type = build_pointer_type (type);
830
831   align = PARM_BOUNDARY / BITS_PER_UNIT;
832   boundary = targetm.calls.function_arg_boundary (TYPE_MODE (type), type);
833
834   /* When we align parameter on stack for caller, if the parameter
835      alignment is beyond MAX_SUPPORTED_STACK_ALIGNMENT, it will be
836      aligned at MAX_SUPPORTED_STACK_ALIGNMENT.  We will match callee
837      here with caller.  */
838   if (boundary > MAX_SUPPORTED_STACK_ALIGNMENT)
839     boundary = MAX_SUPPORTED_STACK_ALIGNMENT;
840
841   boundary /= BITS_PER_UNIT;
842
843   /* Hoist the valist value into a temporary for the moment.  */
844   valist_tmp = get_initialized_tmp_var (valist, pre_p, NULL);
845
846   /* va_list pointer is aligned to PARM_BOUNDARY.  If argument actually
847      requires greater alignment, we must perform dynamic alignment.  */
848   if (boundary > align
849       && !integer_zerop (TYPE_SIZE (type)))
850     {
851       /* FIXME: This is where this function diverts from targhooks.c:
852          std_gimplify_va_arg_expr().  It works, but I do not know why...  */
853       if (! POINTER_TYPE_P (type))
854         {
855           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
856                       fold_build_pointer_plus_hwi (valist_tmp, boundary - 1));
857           gimplify_and_add (t, pre_p);
858
859           t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist_tmp,
860                       fold_build2 (BIT_AND_EXPR, TREE_TYPE (valist),
861                                    valist_tmp,
862                                    build_int_cst (TREE_TYPE (valist),
863                                                   -boundary)));
864           gimplify_and_add (t, pre_p);
865         }
866     }
867   else
868     boundary = align;
869
870   /* If the actual alignment is less than the alignment of the type,
871      adjust the type accordingly so that we don't assume strict alignment
872      when dereferencing the pointer.  */
873   boundary *= BITS_PER_UNIT;
874   if (boundary < TYPE_ALIGN (type))
875     {
876       type = build_variant_type_copy (type);
877       SET_TYPE_ALIGN (type, boundary);
878     }
879
880   /* Compute the rounded size of the type.  */
881   type_size = size_in_bytes (type);
882   rounded_size = round_up (type_size, align);
883
884   /* Reduce rounded_size so it's sharable with the postqueue.  */
885   gimplify_expr (&rounded_size, pre_p, post_p, is_gimple_val, fb_rvalue);
886
887   /* Get AP.  */
888   addr = valist_tmp;
889
890   /* Compute new value for AP.  */
891   t = fold_build_pointer_plus (valist_tmp, rounded_size);
892   t = build2 (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
893   gimplify_and_add (t, pre_p);
894
895   addr = fold_convert (build_pointer_type (type), addr);
896
897   if (indirect)
898     addr = build_va_arg_indirect_ref (addr);
899
900   addr = build_va_arg_indirect_ref (addr);
901
902   return addr;
903 }
904 \f
905 #undef TARGET_LRA_P
906 #define TARGET_LRA_P hook_bool_void_false
907
908 /* Addressing Modes */
909
910 #undef  TARGET_LEGITIMATE_ADDRESS_P
911 #define TARGET_LEGITIMATE_ADDRESS_P msp430_legitimate_address_p
912
913 static bool
914 reg_ok_for_addr (rtx r, bool strict)
915 {
916   int rn = REGNO (r);
917
918   if (strict && rn >= FIRST_PSEUDO_REGISTER)
919     rn = reg_renumber[rn];
920   if (strict && 0 <= rn && rn < FIRST_PSEUDO_REGISTER)
921     return true;
922   if (!strict)
923     return true;
924   return false;
925 }
926
927 bool
928 msp430_legitimate_address_p (machine_mode mode ATTRIBUTE_UNUSED,
929                              rtx x ATTRIBUTE_UNUSED,
930                              bool strict ATTRIBUTE_UNUSED)
931 {
932   switch (GET_CODE (x))
933     {
934     case MEM:
935       return false;
936
937     case PLUS:
938     case POST_INC:
939       if (REG_P (XEXP (x, 0)))
940         {
941           if (GET_MODE (x) != GET_MODE (XEXP (x, 0)))
942             return false;
943           if (!reg_ok_for_addr (XEXP (x, 0), strict))
944             return false;
945           if (GET_CODE (x) == POST_INC)
946             /* At this point, if the original rtx was a post_inc, we don't have
947                anything further to check.  */
948             return true;
949           switch (GET_CODE (XEXP (x, 1)))
950             {
951             case CONST:
952             case SYMBOL_REF:
953             case CONST_INT:
954               return true;
955             default:
956               return false;
957             }
958         }
959       return false;
960
961     case REG:
962       if (!reg_ok_for_addr (x, strict))
963         return false;
964       /* FALLTHRU */
965     case CONST:
966     case SYMBOL_REF:
967     case CONST_INT:
968       return true;
969
970     default:
971       return false;
972     }
973 }
974
975 #undef  TARGET_ADDR_SPACE_LEGITIMATE_ADDRESS_P
976 #define TARGET_ADDR_SPACE_LEGITIMATE_ADDRESS_P \
977   msp430_addr_space_legitimate_address_p
978
979 bool
980 msp430_addr_space_legitimate_address_p (machine_mode mode,
981                                         rtx x,
982                                         bool strict,
983                                         addr_space_t as ATTRIBUTE_UNUSED)
984 {
985   return msp430_legitimate_address_p (mode, x, strict);
986 }
987
988 #undef  TARGET_ASM_INTEGER
989 #define TARGET_ASM_INTEGER msp430_asm_integer
990 static bool
991 msp430_asm_integer (rtx x, unsigned int size, int aligned_p)
992 {
993   int c = GET_CODE (x);
994
995   if (size == 3 && GET_MODE (x) == PSImode)
996     size = 4;
997
998   switch (size)
999     {
1000     case 4:
1001       if (c == SYMBOL_REF || c == CONST || c == LABEL_REF || c == CONST_INT
1002           || c == PLUS || c == MINUS)
1003         {
1004           fprintf (asm_out_file, "\t.long\t");
1005           output_addr_const (asm_out_file, x);
1006           fputc ('\n', asm_out_file);
1007           return true;
1008         }
1009       break;
1010     }
1011   return default_assemble_integer (x, size, aligned_p);
1012 }
1013
1014 #undef  TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
1015 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA msp430_asm_output_addr_const_extra
1016 static bool
1017 msp430_asm_output_addr_const_extra (FILE *file ATTRIBUTE_UNUSED, rtx x)
1018 {
1019   debug_rtx (x);
1020   return false;
1021 }
1022
1023 #undef  TARGET_LEGITIMATE_CONSTANT_P
1024 #define TARGET_LEGITIMATE_CONSTANT_P msp430_legitimate_constant
1025
1026 static bool
1027 msp430_legitimate_constant (machine_mode mode, rtx x)
1028 {
1029   return ! CONST_INT_P (x)
1030     || mode != PSImode
1031     /* GCC does not know the width of the PSImode, so make
1032        sure that it does not try to use a constant value that
1033        is out of range.  */
1034     || (INTVAL (x) < (1 << 20)
1035         && INTVAL (x) >= (HOST_WIDE_INT)(HOST_WIDE_INT_M1U << 20));
1036 }
1037
1038 \f
1039 #undef  TARGET_RTX_COSTS
1040 #define TARGET_RTX_COSTS msp430_rtx_costs
1041
1042 static bool msp430_rtx_costs (rtx          x ATTRIBUTE_UNUSED,
1043                               machine_mode mode,
1044                               int          outer_code ATTRIBUTE_UNUSED,
1045                               int          opno ATTRIBUTE_UNUSED,
1046                               int *        total,
1047                               bool         speed ATTRIBUTE_UNUSED)
1048 {
1049   int code = GET_CODE (x);
1050
1051   switch (code)
1052     {
1053     case SIGN_EXTEND:
1054       if (mode == SImode && outer_code == SET)
1055         {
1056           *total = COSTS_N_INSNS (4);
1057           return true;
1058         }
1059       break;
1060     }
1061   return false;
1062 }
1063 \f
1064 /* Function Entry and Exit */
1065
1066 /* The MSP430 call frame looks like this:
1067
1068    <higher addresses>
1069    +--------------------+
1070    |                    |
1071    | Stack Arguments    |
1072    |                    |
1073    +--------------------+ <-- "arg pointer"
1074    |                    |
1075    | PC from call       |  (2 bytes for 430, 4 for TARGET_LARGE)
1076    |                    |
1077    +--------------------+
1078    | SR if this func has|
1079    | been called via an |
1080    | interrupt.         |
1081    +--------------------+  <-- SP before prologue, also AP
1082    |                    |
1083    | Saved Regs         |  (2 bytes per reg for 430, 4 per for TARGET_LARGE)
1084    |                    |
1085    +--------------------+  <-- "frame pointer"
1086    |                    |
1087    | Locals             |
1088    |                    |
1089    +--------------------+
1090    |                    |
1091    | Outgoing Args      |
1092    |                    |
1093    +--------------------+  <-- SP during function
1094    <lower addresses>
1095
1096 */
1097
1098 /* We use this to wrap all emitted insns in the prologue, so they get
1099    the "frame-related" (/f) flag set.  */
1100 static rtx
1101 F (rtx x)
1102 {
1103   RTX_FRAME_RELATED_P (x) = 1;
1104   return x;
1105 }
1106
1107 /* This is the one spot that decides if a register is to be saved and
1108    restored in the prologue/epilogue.  */
1109 static bool
1110 msp430_preserve_reg_p (int regno)
1111 {
1112   /* PC, SP, SR, and the constant generator.  */
1113   if (regno <= 3)
1114     return false;
1115
1116   /* FIXME: add interrupt, EH, etc.  */
1117   if (crtl->calls_eh_return)
1118     return true;
1119
1120   /* Shouldn't be more than the above, but just in case...  */
1121   if (fixed_regs[regno])
1122     return false;
1123
1124   /* For interrupt functions we must save and restore the used regs that
1125      would normally be caller-saved (R11->R15).  */
1126   if (msp430_is_interrupt_func () && regno >= 11 && regno <= 15)
1127     {
1128       if (crtl->is_leaf && df_regs_ever_live_p (regno))
1129         /* If the interrupt func is a leaf then we only need to restore the
1130            caller-saved regs that are used.  */
1131         return true;
1132       else if (!crtl->is_leaf)
1133         /* If the interrupt function is not a leaf we must save all
1134            caller-saved regs in case the callee modifies them.  */
1135         return true;
1136     }
1137
1138   if (!call_used_or_fixed_reg_p (regno)
1139       && df_regs_ever_live_p (regno))
1140     return true;
1141
1142   return false;
1143 }
1144
1145 /* Compute all the frame-related fields in our machine_function
1146    structure.  */
1147 static void
1148 msp430_compute_frame_info (void)
1149 {
1150   int i;
1151
1152   cfun->machine->computed = 1;
1153   cfun->machine->framesize_regs = 0;
1154   cfun->machine->framesize_locals = get_frame_size ();
1155   cfun->machine->framesize_outgoing = crtl->outgoing_args_size;
1156
1157   for (i = 0; i < ARG_POINTER_REGNUM; i ++)
1158     if (msp430_preserve_reg_p (i))
1159       {
1160         cfun->machine->need_to_save[i] = 1;
1161         cfun->machine->framesize_regs += (TARGET_LARGE ? 4 : 2);
1162       }
1163     else
1164       cfun->machine->need_to_save[i] = 0;
1165
1166   if ((cfun->machine->framesize_locals + cfun->machine->framesize_outgoing) & 1)
1167     cfun->machine->framesize_locals ++;
1168
1169   cfun->machine->framesize = (cfun->machine->framesize_regs
1170                               + cfun->machine->framesize_locals
1171                               + cfun->machine->framesize_outgoing);
1172 }
1173
1174 /* Attribute Handling.  */
1175
1176 const char * const  ATTR_INTR   = "interrupt";
1177 const char * const  ATTR_WAKEUP = "wakeup";
1178 const char * const  ATTR_NAKED  = "naked";
1179 const char * const  ATTR_REENT  = "reentrant";
1180 const char * const  ATTR_CRIT   = "critical";
1181 const char * const  ATTR_LOWER  = "lower";
1182 const char * const  ATTR_UPPER  = "upper";
1183 const char * const  ATTR_EITHER = "either";
1184 const char * const  ATTR_NOINIT = "noinit";
1185 const char * const  ATTR_PERSIST = "persistent";
1186
1187 static inline bool
1188 has_attr (const char * attr, tree decl)
1189 {
1190   if (decl == NULL_TREE)
1191     return false;
1192   return lookup_attribute (attr, DECL_ATTRIBUTES (decl)) != NULL_TREE;
1193 }
1194
1195 static bool
1196 is_interrupt_func (tree decl = current_function_decl)
1197 {
1198   return has_attr (ATTR_INTR, decl);
1199 }
1200
1201 /* Returns true if the current function has the "interrupt" attribute.  */
1202
1203 bool
1204 msp430_is_interrupt_func (void)
1205 {
1206   return is_interrupt_func (current_function_decl);
1207 }
1208
1209 static bool
1210 is_wakeup_func (tree decl = current_function_decl)
1211 {
1212   return is_interrupt_func (decl) && has_attr (ATTR_WAKEUP, decl);
1213 }
1214
1215 static inline bool
1216 is_naked_func (tree decl = current_function_decl)
1217 {
1218   return has_attr (ATTR_NAKED, decl);
1219 }
1220
1221 static inline bool
1222 is_reentrant_func (tree decl = current_function_decl)
1223 {
1224   return has_attr (ATTR_REENT, decl);
1225 }
1226
1227 static inline bool
1228 is_critical_func (tree decl = current_function_decl)
1229 {
1230   return has_attr (ATTR_CRIT, decl);
1231 }
1232
1233 static bool
1234 has_section_name (const char * name, tree decl = current_function_decl)
1235 {
1236   if (decl == NULL_TREE)
1237     return false;
1238   return (DECL_SECTION_NAME (decl)
1239           && (strcmp (name, DECL_SECTION_NAME (decl)) == 0));
1240 }
1241
1242 #undef  TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
1243 #define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS \
1244   msp430_allocate_stack_slots_for_args
1245
1246 static bool
1247 msp430_allocate_stack_slots_for_args (void)
1248 {
1249   /* Naked functions should not allocate stack slots for arguments.  */
1250   return ! is_naked_func ();
1251 }
1252
1253 #undef TARGET_WARN_FUNC_RETURN
1254 #define TARGET_WARN_FUNC_RETURN msp430_warn_func_return
1255
1256 static bool
1257 msp430_warn_func_return (tree decl)
1258 {
1259   /* Naked functions are implemented entirely in assembly, including the
1260      return sequence, so suppress warnings about this.  */
1261   return !is_naked_func (decl);
1262 }
1263
1264 /* Verify MSP430 specific attributes.  */
1265 #define TREE_NAME_EQ(NAME, STR) (strcmp (IDENTIFIER_POINTER (NAME), (STR)) == 0)
1266
1267 static tree
1268 msp430_attr (tree * node,
1269              tree   name,
1270              tree   args,
1271              int    flags ATTRIBUTE_UNUSED,
1272              bool * no_add_attrs)
1273 {
1274   gcc_assert (DECL_P (* node));
1275
1276   /* Only the interrupt attribute takes an argument.  */
1277   if (args != NULL)
1278     {
1279       tree value = TREE_VALUE (args);
1280
1281       switch (TREE_CODE (value))
1282         {
1283         case STRING_CST:
1284           if (   strcmp (TREE_STRING_POINTER (value), "reset")
1285               && strcmp (TREE_STRING_POINTER (value), "nmi")
1286               && strcmp (TREE_STRING_POINTER (value), "watchdog"))
1287             /* Allow the attribute to be added - the linker script
1288                being used may still recognise this name.  */
1289             warning (OPT_Wattributes,
1290                      "unrecognized interrupt vector argument of %qE attribute",
1291                      name);
1292           break;
1293
1294         case INTEGER_CST:
1295           if (wi::gtu_p (wi::to_wide (value), 63))
1296             /* Allow the attribute to be added - the linker script
1297                being used may still recognise this value.  */
1298             warning (OPT_Wattributes,
1299                      "numeric argument of %qE attribute must be in range 0..63",
1300                      name);
1301           break;
1302
1303         default:
1304           warning (OPT_Wattributes,
1305                    "argument of %qE attribute is not a string constant "
1306                    "or number", name);
1307           *no_add_attrs = true;
1308           break;
1309         }
1310     }
1311
1312   const char * message = NULL;
1313
1314   if (TREE_CODE (* node) != FUNCTION_DECL)
1315     {
1316       message = "%qE attribute only applies to functions";
1317     }
1318   else if (TREE_NAME_EQ (name, ATTR_INTR))
1319     {
1320       if (TREE_CODE (TREE_TYPE (* node)) == FUNCTION_TYPE
1321           && ! VOID_TYPE_P (TREE_TYPE (TREE_TYPE (* node))))
1322         message = "interrupt handlers must be void";
1323       else
1324         {
1325           /* Ensure interrupt handlers never get optimised out.  */
1326           TREE_USED (* node) = 1;
1327           DECL_PRESERVE_P (* node) = 1;
1328         }
1329       if (is_critical_func (* node))
1330         {
1331           /* We always ignore the critical attribute when interrupt and
1332              critical are used together.  */
1333           warning (OPT_Wattributes,
1334                    "critical attribute has no effect on interrupt functions");
1335           DECL_ATTRIBUTES (*node) = remove_attribute (ATTR_CRIT,
1336                                                       DECL_ATTRIBUTES (* node));
1337         }
1338     }
1339   else if (TREE_NAME_EQ (name, ATTR_CRIT))
1340     {
1341       if (is_interrupt_func ( *node))
1342         message = "critical attribute has no effect on interrupt functions";
1343     }
1344
1345   if (message)
1346     {
1347       warning (OPT_Wattributes, message, name);
1348       * no_add_attrs = true;
1349     }
1350
1351   return NULL_TREE;
1352 }
1353
1354 static tree
1355 msp430_section_attr (tree * node,
1356                      tree   name,
1357                      tree   args,
1358                      int    flags ATTRIBUTE_UNUSED,
1359                      bool * no_add_attrs ATTRIBUTE_UNUSED)
1360 {
1361   gcc_assert (DECL_P (* node));
1362   gcc_assert (args == NULL);
1363
1364   const char * message = NULL;
1365
1366   /* The "noinit" and "section" attributes are handled generically, so we
1367      cannot set up additional target-specific attribute exclusions using the
1368      existing mechanism.  */
1369   if (has_attr (ATTR_NOINIT, *node))
1370     message = G_("ignoring attribute %qE because it conflicts with "
1371                  "attribute %<noinit%>");
1372   else if (has_attr ("section", *node) && !TREE_NAME_EQ (name, "lower"))
1373     message = G_("ignoring attribute %qE because it conflicts with "
1374                  "attribute %<section%>");
1375   /* It does not make sense to use upper/lower/either attributes without
1376      -mlarge.
1377      Without -mlarge, "lower" is the default and only region, so is redundant.
1378      Without -mlarge, "upper" will (and "either" might) place code/data in the
1379      upper region, which for data could result in relocation overflows, and for
1380      code could result in stack mismanagement and incorrect call/return
1381      instructions.  */
1382   else if (!TARGET_LARGE)
1383     message = G_("%qE attribute ignored.  Large memory model (%<-mlarge%>) "
1384                  "is required.");
1385
1386   if (message)
1387     {
1388       warning (OPT_Wattributes, message, name);
1389       * no_add_attrs = true;
1390     }
1391
1392   return NULL_TREE;
1393 }
1394
1395 static tree
1396 msp430_persist_attr (tree *node,
1397                   tree   name,
1398                   tree   args,
1399                   int    flags ATTRIBUTE_UNUSED,
1400                   bool * no_add_attrs ATTRIBUTE_UNUSED)
1401 {
1402   const char * message = NULL;
1403
1404   gcc_assert (DECL_P (* node));
1405   gcc_assert (args == NULL);
1406   gcc_assert (TREE_NAME_EQ (name, ATTR_PERSIST));
1407
1408   /* Check for the section attribute separately from DECL_SECTION_NAME so
1409      we can provide a clearer warning.  */
1410   if (has_attr ("section", *node))
1411     message = G_("ignoring attribute %qE because it conflicts with "
1412                  "attribute %<section%>");
1413   /* Check that it's possible for the variable to have a section.  */
1414   else if ((TREE_STATIC (*node) || DECL_EXTERNAL (*node) || in_lto_p)
1415            && (DECL_SECTION_NAME (*node)))
1416     message = G_("%qE attribute cannot be applied to variables with specific "
1417                  "sections");
1418   else if (has_attr (ATTR_NOINIT, *node))
1419     message = G_("ignoring attribute %qE because it conflicts with "
1420                  "attribute %<noinit%>");
1421   else if (TREE_CODE (*node) != VAR_DECL)
1422     message = G_("%qE attribute only applies to variables");
1423   else if (!TREE_STATIC (*node) && !TREE_PUBLIC (*node)
1424            && !DECL_EXTERNAL (*node))
1425     message = G_("%qE attribute has no effect on automatic variables");
1426   else if (DECL_COMMON (*node) || DECL_INITIAL (*node) == NULL)
1427     message = G_("variables marked with %qE attribute must be initialized");
1428   else
1429     /* It's not clear if there is anything that can be set here to prevent the
1430        front end placing the variable before the back end can handle it, in a
1431        similar way to how DECL_COMMON is cleared for .noinit variables in
1432        handle_noinit_attribute (gcc/c-family/c-attribs.c).
1433        So just place the variable in the .persistent section now.  */
1434     set_decl_section_name (* node, ".persistent");
1435
1436   if (message)
1437     {
1438       warning (OPT_Wattributes, message, name);
1439       * no_add_attrs = true;
1440     }
1441
1442   return NULL_TREE;
1443 }
1444
1445 /* Helper to define attribute exclusions.  */
1446 #define ATTR_EXCL(name, function, type, variable)       \
1447   { name, function, type, variable }
1448
1449 /* "reentrant", "critical" and "naked" functions must conflict because
1450    they all modify the prologue or epilogue of functions in mutually exclusive
1451    ways.  */
1452 static const struct attribute_spec::exclusions attr_reent_exclusions[] =
1453 {
1454   ATTR_EXCL (ATTR_NAKED, true, true, true),
1455   ATTR_EXCL (ATTR_CRIT, true, true, true),
1456   ATTR_EXCL (NULL, false, false, false)
1457 };
1458
1459 static const struct attribute_spec::exclusions attr_naked_exclusions[] =
1460 {
1461   ATTR_EXCL (ATTR_REENT, true, true, true),
1462   ATTR_EXCL (ATTR_CRIT, true, true, true),
1463   ATTR_EXCL (NULL, false, false, false)
1464 };
1465
1466 static const struct attribute_spec::exclusions attr_crit_exclusions[] =
1467 {
1468   ATTR_EXCL (ATTR_REENT, true, true, true),
1469   ATTR_EXCL (ATTR_NAKED, true, true, true),
1470   ATTR_EXCL (NULL, false, false, false)
1471 };
1472
1473 /* Attributes which put the given object in a specific section must conflict
1474    with one another.  */
1475 static const struct attribute_spec::exclusions attr_lower_exclusions[] =
1476 {
1477   ATTR_EXCL (ATTR_UPPER, true, true, true),
1478   ATTR_EXCL (ATTR_EITHER, true, true, true),
1479   ATTR_EXCL (ATTR_PERSIST, true, true, true),
1480   ATTR_EXCL (NULL, false, false, false)
1481 };
1482
1483 static const struct attribute_spec::exclusions attr_upper_exclusions[] =
1484 {
1485   ATTR_EXCL (ATTR_LOWER, true, true, true),
1486   ATTR_EXCL (ATTR_EITHER, true, true, true),
1487   ATTR_EXCL (ATTR_PERSIST, true, true, true),
1488   ATTR_EXCL (NULL, false, false, false)
1489 };
1490
1491 static const struct attribute_spec::exclusions attr_either_exclusions[] =
1492 {
1493   ATTR_EXCL (ATTR_LOWER, true, true, true),
1494   ATTR_EXCL (ATTR_UPPER, true, true, true),
1495   ATTR_EXCL (ATTR_PERSIST, true, true, true),
1496   ATTR_EXCL (NULL, false, false, false)
1497 };
1498
1499 static const struct attribute_spec::exclusions attr_persist_exclusions[] =
1500 {
1501   ATTR_EXCL (ATTR_LOWER, true, true, true),
1502   ATTR_EXCL (ATTR_UPPER, true, true, true),
1503   ATTR_EXCL (ATTR_EITHER, true, true, true),
1504   ATTR_EXCL (NULL, false, false, false)
1505 };
1506
1507 #undef  TARGET_ATTRIBUTE_TABLE
1508 #define TARGET_ATTRIBUTE_TABLE          msp430_attribute_table
1509
1510 /* Table of MSP430-specific attributes.  */
1511 const struct attribute_spec msp430_attribute_table[] =
1512   {
1513     /* { name, min_num_args, max_num_args, decl_req, type_req, fn_type_req,
1514          affects_type_identity, handler, exclude } */
1515     { ATTR_INTR,        0, 1, true,  false, false, false, msp430_attr, NULL },
1516     { ATTR_NAKED,       0, 0, true,  false, false, false, msp430_attr,
1517       attr_naked_exclusions },
1518     { ATTR_REENT,       0, 0, true,  false, false, false, msp430_attr,
1519       attr_reent_exclusions },
1520     { ATTR_CRIT,        0, 0, true,  false, false, false, msp430_attr,
1521       attr_crit_exclusions },
1522     { ATTR_WAKEUP,      0, 0, true,  false, false, false, msp430_attr, NULL },
1523
1524     { ATTR_LOWER,       0, 0, true,  false, false, false, msp430_section_attr,
1525       attr_lower_exclusions },
1526     { ATTR_UPPER,       0, 0, true,  false, false, false, msp430_section_attr,
1527       attr_upper_exclusions },
1528     { ATTR_EITHER,      0, 0, true,  false, false, false, msp430_section_attr,
1529       attr_either_exclusions },
1530
1531     { ATTR_PERSIST,     0, 0, true,  false, false, false, msp430_persist_attr,
1532       attr_persist_exclusions },
1533
1534     { NULL,             0, 0, false, false, false, false, NULL,  NULL }
1535   };
1536
1537 #undef TARGET_HANDLE_GENERIC_ATTRIBUTE
1538 #define TARGET_HANDLE_GENERIC_ATTRIBUTE msp430_handle_generic_attribute
1539
1540 tree
1541 msp430_handle_generic_attribute (tree *node,
1542                                  tree   name,
1543                                  tree   args ATTRIBUTE_UNUSED,
1544                                  int    flags ATTRIBUTE_UNUSED,
1545                                  bool *no_add_attrs)
1546
1547 {
1548   const char *message = NULL;
1549
1550   /* The front end has set up an exclusion between the "noinit" and "section"
1551      attributes.  */
1552   if (!(TREE_NAME_EQ (name, ATTR_NOINIT) || TREE_NAME_EQ (name, "section")))
1553     return NULL_TREE;
1554
1555   /* We allow the "lower" attribute to be used on variables with the "section"
1556      attribute.  */
1557   if (has_attr (ATTR_LOWER, *node) && !TREE_NAME_EQ (name, "section"))
1558     message = G_("ignoring attribute %qE because it conflicts with "
1559                  "attribute %<lower%>");
1560   else if (has_attr (ATTR_UPPER, *node))
1561     message = G_("ignoring attribute %qE because it conflicts with "
1562                  "attribute %<upper%>");
1563   else if (has_attr (ATTR_EITHER, *node))
1564     message = G_("ignoring attribute %qE because it conflicts with "
1565                  "attribute %<either%>");
1566   else if (has_attr (ATTR_PERSIST, *node))
1567     message = G_("ignoring attribute %qE because it conflicts with "
1568                  "attribute %<persistent%>");
1569
1570   if (message)
1571     {
1572       warning (OPT_Wattributes, message, name);
1573       *no_add_attrs = true;
1574     }
1575
1576   return NULL_TREE;
1577 }
1578
1579 /* Given a non-automatic VAR_DECL which can possibly have a section, return
1580    true if the variable will definitely be placed in the lower memory
1581    region (below address 0x10000).  */
1582 static bool
1583 msp430_var_in_low_mem (tree decl)
1584 {
1585   gcc_assert (VAR_P (decl));
1586
1587   /* "noinit" variables are always placed in the lower memory region.  */
1588   if (has_attr (ATTR_UPPER, decl)
1589       || has_attr (ATTR_EITHER, decl)
1590       || has_attr (ATTR_PERSIST, decl)
1591       /* Unless the variable is marked with the lower or noinit attribute, we
1592          cannot assume that it is in the lower region if it is marked with the
1593          section attribute or -mdata-region={upper,either,none} have been
1594          passed.
1595          The noinit and section attributes conflict.  */
1596       || (!has_attr (ATTR_LOWER, decl) && !has_attr (ATTR_NOINIT, decl)
1597           && (has_attr ("section", decl)
1598               || msp430_data_region == MSP430_REGION_UPPER
1599               || msp430_data_region == MSP430_REGION_EITHER
1600               || msp430_data_region == MSP430_REGION_ANY)))
1601     return false;
1602   return true;
1603 }
1604
1605 #undef TARGET_ENCODE_SECTION_INFO
1606 #define TARGET_ENCODE_SECTION_INFO msp430_encode_section_info
1607
1608 /* Encode whether a SYMBOL_REF is definitely in the lower memory region.  */
1609 static void
1610 msp430_encode_section_info (tree decl, rtx rtl, int first)
1611 {
1612   rtx symbol;
1613   default_encode_section_info (decl, rtl, first);
1614
1615   /* Careful not to prod global register variables.  */
1616   if (!MEM_P (rtl))
1617     return;
1618   symbol = XEXP (rtl, 0);
1619   if (GET_CODE (symbol) != SYMBOL_REF)
1620     return;
1621
1622   if (VAR_P (decl)
1623       && (TREE_STATIC (decl) || DECL_EXTERNAL (decl))
1624       && msp430_var_in_low_mem (decl))
1625     SYMBOL_REF_FLAGS (symbol) = SYMBOL_FLAG_LOW_MEM;
1626 }
1627
1628 #undef  TARGET_ASM_FUNCTION_PROLOGUE
1629 #define TARGET_ASM_FUNCTION_PROLOGUE    msp430_start_function
1630
1631 static void
1632 msp430_start_function (FILE *outfile)
1633 {
1634   int r, n;
1635
1636   fprintf (outfile, "; start of function\n");
1637
1638   if (DECL_ATTRIBUTES (current_function_decl) != NULL_TREE)
1639     {
1640       fprintf (outfile, "; attributes: ");
1641       if (is_naked_func ())
1642         fprintf (outfile, "naked ");
1643       if (msp430_is_interrupt_func ())
1644         fprintf (outfile, "interrupt ");
1645       if (is_reentrant_func ())
1646         fprintf (outfile, "reentrant ");
1647       if (is_critical_func ())
1648         fprintf (outfile, "critical ");
1649       if (is_wakeup_func ())
1650         fprintf (outfile, "wakeup ");
1651       fprintf (outfile, "\n");
1652     }
1653
1654   fprintf (outfile, "; framesize_regs:     %d\n",
1655            cfun->machine->framesize_regs);
1656   fprintf (outfile, "; framesize_locals:   %d\n",
1657            cfun->machine->framesize_locals);
1658   fprintf (outfile, "; framesize_outgoing: %d\n",
1659            cfun->machine->framesize_outgoing);
1660   fprintf (outfile, "; framesize:          %d\n", cfun->machine->framesize);
1661   fprintf (outfile, "; elim ap -> fp       %d\n",
1662            msp430_initial_elimination_offset (ARG_POINTER_REGNUM,
1663                                               FRAME_POINTER_REGNUM));
1664   fprintf (outfile, "; elim fp -> sp       %d\n",
1665            msp430_initial_elimination_offset (FRAME_POINTER_REGNUM,
1666                                               STACK_POINTER_REGNUM));
1667
1668   n = 0;
1669   fprintf (outfile, "; saved regs:");
1670   for (r = 0; r < ARG_POINTER_REGNUM; r++)
1671     if (cfun->machine->need_to_save[r])
1672       {
1673         fprintf (outfile, " %s", reg_names[r]);
1674         n = 1;
1675       }
1676   if (n == 0)
1677     fprintf (outfile, "(none)");
1678   fprintf (outfile, "\n");
1679 }
1680
1681 /* Common code to change the stack pointer.  */
1682 static void
1683 increment_stack (HOST_WIDE_INT amount)
1684 {
1685   rtx inc;
1686   rtx sp =  stack_pointer_rtx;
1687
1688   if (amount == 0)
1689     return;
1690
1691   if (amount < 0)
1692     {
1693       inc = GEN_INT (- amount);
1694       if (TARGET_LARGE)
1695         F (emit_insn (gen_subpsi3 (sp, sp, inc)));
1696       else
1697         F (emit_insn (gen_subhi3 (sp, sp, inc)));
1698     }
1699   else
1700     {
1701       inc = GEN_INT (amount);
1702       if (TARGET_LARGE)
1703         emit_insn (gen_addpsi3 (sp, sp, inc));
1704       else
1705         emit_insn (gen_addhi3 (sp, sp, inc));
1706     }
1707 }
1708
1709 void
1710 msp430_start_function (FILE *file, const char *name, tree decl)
1711 {
1712   tree int_attr;
1713
1714   int_attr = lookup_attribute ("interrupt", DECL_ATTRIBUTES (decl));
1715   if (int_attr != NULL_TREE)
1716     {
1717       tree intr_vector = TREE_VALUE (int_attr);
1718
1719       if (intr_vector != NULL_TREE)
1720         {
1721           char buf[101];
1722
1723           /* Interrupt vector sections should be unique, but use of weak
1724              functions implies multiple definitions.  */
1725           if (DECL_WEAK (decl))
1726             {
1727               error ("argument to interrupt attribute is unsupported for weak "
1728                      "functions");
1729             }
1730
1731           intr_vector = TREE_VALUE (intr_vector);
1732
1733           /* The interrupt attribute has a vector value.  Turn this into a
1734              section name, switch to that section and put the address of
1735              the current function into that vector slot.  Note msp430_attr()
1736              has already verified the vector name for us.  */
1737           if (TREE_CODE (intr_vector) == STRING_CST)
1738             sprintf (buf, "__interrupt_vector_%.80s",
1739                      TREE_STRING_POINTER (intr_vector));
1740           else /* TREE_CODE (intr_vector) == INTEGER_CST */
1741             sprintf (buf, "__interrupt_vector_%u",
1742                      (unsigned int) TREE_INT_CST_LOW (intr_vector));
1743
1744           switch_to_section (get_section (buf, SECTION_CODE, decl));
1745           fputs ("\t.word\t", file);
1746           assemble_name (file, name);
1747           fputc ('\n', file);
1748           fputc ('\t', file);
1749         }
1750     }
1751
1752   switch_to_section (function_section (decl));
1753   ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
1754   ASM_OUTPUT_FUNCTION_LABEL (file, name, decl);
1755 }
1756
1757 static const char * const lower_prefix = ".lower";
1758 static const char * const upper_prefix = ".upper";
1759 static const char * const either_prefix = ".either";
1760
1761 /* Generate a prefix for a section name, based upon
1762    the region into which the object should be placed.  */
1763
1764 static const char *
1765 gen_prefix (tree decl)
1766 {
1767   if (DECL_ONE_ONLY (decl))
1768     return NULL;
1769
1770   /* If the user has specified a particular section then do not use any
1771      prefix.  */
1772   if (has_attr ("section", decl))
1773     return NULL;
1774
1775   /* If the function has been put in the .lowtext section (because it is an
1776      interrupt handler, and the large memory model is used), then do not add
1777      any prefixes.  */
1778   if (has_section_name (".lowtext", decl))
1779     return NULL;
1780
1781   /* Memory regions require the large memory model.  */
1782   if (!TARGET_LARGE)
1783     return NULL;
1784
1785   /* Note that we always apply the lower prefix when the attribute has been
1786      used.  But we only apply the lower prefix when the lower region has been
1787      specified by a command line option if -muse-lower-region-prefix has also
1788      been passed.  */
1789   if (has_attr (ATTR_LOWER, decl))
1790     return lower_prefix;
1791
1792   if (has_attr (ATTR_UPPER, decl))
1793     return upper_prefix;
1794
1795   if (has_attr (ATTR_EITHER, decl))
1796     return either_prefix;
1797
1798   if (TREE_CODE (decl) == FUNCTION_DECL)
1799     {
1800       if ((msp430_code_region == MSP430_REGION_LOWER)
1801           && TARGET_USE_LOWER_REGION_PREFIX)
1802         return lower_prefix;
1803
1804       if (msp430_code_region == MSP430_REGION_UPPER)
1805         return upper_prefix;
1806
1807       if (msp430_code_region == MSP430_REGION_EITHER)
1808         return either_prefix;
1809     }
1810   else
1811     {
1812       if ((msp430_data_region == MSP430_REGION_LOWER)
1813           && TARGET_USE_LOWER_REGION_PREFIX)
1814         return lower_prefix;
1815
1816       if (msp430_data_region == MSP430_REGION_UPPER)
1817         return upper_prefix;
1818
1819       if (msp430_data_region == MSP430_REGION_EITHER)
1820         return either_prefix;
1821     }
1822
1823   return NULL;
1824 }
1825
1826 static section * persist_section;
1827
1828 #undef  TARGET_ASM_INIT_SECTIONS
1829 #define TARGET_ASM_INIT_SECTIONS msp430_init_sections
1830
1831 static void
1832 msp430_init_sections (void)
1833 {
1834   persist_section = get_unnamed_section (0, output_section_asm_op,
1835                                          ".section .persistent,\"aw\"");
1836 }
1837
1838 #undef  TARGET_ASM_SELECT_SECTION
1839 #define TARGET_ASM_SELECT_SECTION msp430_select_section
1840
1841 static section *
1842 msp430_select_section (tree decl, int reloc, unsigned HOST_WIDE_INT align)
1843 {
1844   const char *prefix;
1845   const char *sec_name;
1846   const char *base_sec_name;
1847
1848   gcc_assert (decl != NULL_TREE);
1849
1850   if (TREE_CODE (decl) == STRING_CST
1851       || TREE_CODE (decl) == CONSTRUCTOR
1852       || TREE_CODE (decl) == INTEGER_CST
1853       || TREE_CODE (decl) == VECTOR_CST
1854       || TREE_CODE (decl) == COMPLEX_CST)
1855     return default_select_section (decl, reloc, align);
1856
1857   /* In large mode we must make sure that interrupt handlers are put into
1858      low memory as the vector table only accepts 16-bit addresses.  */
1859   if (TARGET_LARGE && TREE_CODE (decl) == FUNCTION_DECL
1860       && is_interrupt_func (decl))
1861     return get_section (".lowtext", SECTION_CODE | SECTION_WRITE , decl);
1862
1863   if (has_attr (ATTR_PERSIST, decl))
1864     return persist_section;
1865
1866   /* ATTR_NOINIT is handled generically.  */
1867   if (has_attr (ATTR_NOINIT, decl))
1868     return default_elf_select_section (decl, reloc, align);
1869
1870   prefix = gen_prefix (decl);
1871
1872   switch (categorize_decl_for_section (decl, reloc))
1873     {
1874     case SECCAT_TEXT:
1875       if (!prefix)
1876         return text_section;
1877       base_sec_name = ".text";
1878       break;
1879     case SECCAT_DATA:
1880       if (!prefix)
1881         return data_section;
1882       base_sec_name = ".data";
1883       break;
1884     case SECCAT_BSS:
1885       if (!prefix)
1886         return bss_section;
1887       base_sec_name = ".bss";
1888       break;
1889     case SECCAT_RODATA:
1890       if (!prefix)
1891         return readonly_data_section;
1892       base_sec_name = ".rodata";
1893       break;
1894
1895     /* Enable merging of constant data by the GNU linker using
1896        default_elf_select_section and therefore enabling creation of
1897        sections with the SHF_MERGE flag.  */
1898     case SECCAT_RODATA_MERGE_STR:
1899     case SECCAT_RODATA_MERGE_STR_INIT:
1900     case SECCAT_RODATA_MERGE_CONST:
1901       return default_elf_select_section (decl, reloc, align);
1902
1903     /* The sections listed below are not supported for MSP430.
1904        They should not be generated, but in case they are, we use
1905        default_select_section so they get placed in sections
1906        the msp430 assembler and linker understand.  */
1907     /* "small data" sections are not supported.  */
1908     case SECCAT_SRODATA:
1909     case SECCAT_SDATA:
1910     case SECCAT_SBSS:
1911     /* Thread-local storage (TLS) is not supported.  */
1912     case SECCAT_TDATA:
1913     case SECCAT_TBSS:
1914     /* Sections used by a dynamic linker are not supported.  */
1915     case SECCAT_DATA_REL:
1916     case SECCAT_DATA_REL_LOCAL:
1917     case SECCAT_DATA_REL_RO:
1918     case SECCAT_DATA_REL_RO_LOCAL:
1919       return default_select_section (decl, reloc, align);
1920
1921     default:
1922       gcc_unreachable ();
1923     }
1924
1925   sec_name = ACONCAT ((prefix, base_sec_name, DECL_SECTION_NAME (decl), NULL));
1926
1927   return get_named_section (decl, sec_name, 0);
1928 }
1929
1930 #undef  TARGET_ASM_FUNCTION_SECTION
1931 #define TARGET_ASM_FUNCTION_SECTION msp430_function_section
1932
1933 static section *
1934 msp430_function_section (tree decl, enum node_frequency freq, bool startup,
1935                          bool exit)
1936 {
1937   const char * name;
1938
1939   gcc_assert (DECL_SECTION_NAME (decl) != NULL);
1940   name = DECL_SECTION_NAME (decl);
1941
1942   const char * prefix = gen_prefix (decl);
1943   if (prefix == NULL
1944       || strncmp (name, prefix, strlen (prefix)) == 0)
1945     return default_function_section (decl, freq, startup, exit);
1946
1947   name = ACONCAT ((prefix, name, NULL));
1948   return get_named_section (decl, name, 0);
1949 }
1950
1951 #undef  TARGET_SECTION_TYPE_FLAGS
1952 #define TARGET_SECTION_TYPE_FLAGS msp430_section_type_flags
1953
1954 unsigned int
1955 msp430_section_type_flags (tree decl, const char * name, int reloc)
1956 {
1957   if (strncmp (name, lower_prefix, strlen (lower_prefix)) == 0)
1958     name += strlen (lower_prefix);
1959   else if (strncmp (name, upper_prefix, strlen (upper_prefix)) == 0)
1960     name += strlen (upper_prefix);
1961   else if (strncmp (name, either_prefix, strlen (either_prefix)) == 0)
1962     name += strlen (either_prefix);
1963   else if (strcmp (name, ".persistent") == 0)
1964     return SECTION_WRITE | SECTION_NOTYPE;
1965
1966   return default_section_type_flags (decl, name, reloc);
1967 }
1968
1969 #undef  TARGET_ASM_UNIQUE_SECTION
1970 #define TARGET_ASM_UNIQUE_SECTION msp430_unique_section
1971
1972 static void
1973 msp430_unique_section (tree decl, int reloc)
1974 {
1975   gcc_assert (decl != NULL_TREE);
1976
1977   /* In large mode we must make sure that interrupt handlers are put into
1978      low memory as the vector table only accepts 16-bit addresses.  */
1979   if (TARGET_LARGE && TREE_CODE (decl) == FUNCTION_DECL
1980       && is_interrupt_func (decl))
1981     {
1982       set_decl_section_name (decl, ".lowtext");
1983       return;
1984     }
1985
1986   default_unique_section (decl, reloc);
1987
1988   const char * prefix;
1989
1990   if (   TREE_CODE (decl) == STRING_CST
1991       || TREE_CODE (decl) == CONSTRUCTOR
1992       || TREE_CODE (decl) == INTEGER_CST
1993       || TREE_CODE (decl) == VECTOR_CST
1994       || TREE_CODE (decl) == COMPLEX_CST
1995       || (prefix = gen_prefix (decl)) == NULL)
1996     return;
1997
1998   const char * dec_name = DECL_SECTION_NAME (decl);
1999   char * name = ACONCAT ((prefix, dec_name, NULL));
2000
2001   set_decl_section_name (decl, name);
2002 }
2003
2004 /* Emit a declaration of a common symbol.
2005    If a data region is in use then put the symbol into the
2006    equivalent .bss section instead.
2007    If LOCAL is 1, then DECL is for a local common variable.  */
2008 void
2009 msp430_output_aligned_decl_common (FILE *                 stream,
2010                                    const tree             decl,
2011                                    const char *           name,
2012                                    unsigned HOST_WIDE_INT size,
2013                                    unsigned int           align,
2014                                    int local)
2015 {
2016   /* Only emit a common symbol if the variable does not have a specific section
2017      assigned.  */
2018   if ((msp430_data_region == MSP430_REGION_ANY
2019        || ((msp430_data_region == MSP430_REGION_LOWER)
2020            && !TARGET_USE_LOWER_REGION_PREFIX))
2021       && !(decl != NULL_TREE && DECL_SECTION_NAME (decl))
2022       && !has_attr (ATTR_EITHER, decl)
2023       && !has_attr (ATTR_LOWER, decl)
2024       && !has_attr (ATTR_UPPER, decl)
2025       && !has_attr (ATTR_PERSIST, decl)
2026       && !has_attr (ATTR_NOINIT, decl))
2027     {
2028       if (local)
2029         {
2030           fprintf (stream, LOCAL_ASM_OP);
2031           assemble_name (stream, name);
2032           fprintf (stream, "\n");
2033         }
2034       fprintf (stream, COMMON_ASM_OP);
2035       assemble_name (stream, name);
2036       fprintf (stream, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
2037                size, align / BITS_PER_UNIT);
2038     }
2039   else
2040     {
2041       section * sec;
2042
2043       if (decl)
2044         sec = msp430_select_section (decl, 0, align);
2045       else
2046         switch (msp430_data_region)
2047           {
2048           case MSP430_REGION_UPPER:
2049             sec = get_named_section (NULL, ".upper.bss", 0);
2050             break;
2051           case MSP430_REGION_LOWER:
2052             sec = get_named_section (NULL, ".lower.bss", 0);
2053             break;
2054           case MSP430_REGION_EITHER:
2055             sec = get_named_section (NULL, ".either.bss", 0);
2056             break;
2057           default:
2058             gcc_unreachable ();
2059           }
2060       gcc_assert (sec != NULL);
2061
2062       switch_to_section (sec);
2063       ASM_OUTPUT_ALIGN (stream, floor_log2 (align / BITS_PER_UNIT));
2064       if (!local)
2065         {
2066           targetm.asm_out.globalize_label (stream, name);
2067           ASM_WEAKEN_LABEL (stream, name);
2068         }
2069       ASM_OUTPUT_LABEL (stream, name);
2070       ASM_OUTPUT_SKIP (stream, size ? size : 1);
2071     }
2072 }
2073
2074 #undef TARGET_ASM_FILE_END
2075 #define TARGET_ASM_FILE_END msp430_file_end
2076
2077 /* Emit MSPABI and GNU object attributes.
2078    Tags and values for MSPABI attributes are:
2079    OFBA_MSPABI_Tag_ISA          4
2080      MSP430     1
2081      MSP430X    2
2082    OFBA_MSPABI_Tag_Code_Model   6
2083      Small      1
2084      Large      2
2085    OFBA_MSPABI_Tag_Data_Model   8
2086      Small      1
2087      Large      2
2088      Restricted 3 (Unused by GNU)
2089    OFBA_MSPABI_Tag_enum_size    10 (Unused by GNU)
2090    Note that Code_Model and Data_Model are always equal for GNU.
2091    We define a new .gnu_attribute to keep track of the data region used.
2092    Tag_GNU_MSP430_Data_Region   4
2093      LOWER      1
2094      ANY        2
2095    See binutils-gdb/include/elf/msp430.h for the full details.  */
2096 static void
2097 msp430_file_end (void)
2098 {
2099 #ifdef HAVE_AS_GNU_ATTRIBUTE
2100   /* Enum for tag names.  */
2101   enum
2102     {
2103       OFBA_MSPABI_Tag_ISA = 4,
2104       OFBA_MSPABI_Tag_Code_Model = 6,
2105       OFBA_MSPABI_Tag_Data_Model = 8,
2106       Tag_GNU_MSP430_Data_Region = 4
2107     };
2108   /* Enum for tag values.  */
2109   enum
2110     {
2111       OFBA_MSPABI_Val_ISA_MSP430 = 1,
2112       OFBA_MSPABI_Val_ISA_MSP430X = 2,
2113       OFBA_MSPABI_Val_Model_Small = 1,
2114       OFBA_MSPABI_Val_Model_Large = 2,
2115       Tag_GNU_MSP430_Data_Region_Lower = 1,
2116       Tag_GNU_MSP430_Data_Region_Any = 2
2117     };
2118   /* .mspabi_attribute is a GNU assembler directive only.  The assembler will
2119      construct a .MSP430.attributes section based on the options it is invoked
2120      with.  The values it reads from these directives are used for validating
2121      those options.  */
2122   const char *msp430_attr = ".mspabi_attribute";
2123   const char *gnu_attr = ".gnu_attribute";
2124
2125   /* Emit .mspabi_attribute directive for OFBA_MSPABI_Tag_ISA.  */
2126   fprintf (asm_out_file, "\t%s %d, %d\n", msp430_attr, OFBA_MSPABI_Tag_ISA,
2127            msp430x ? OFBA_MSPABI_Val_ISA_MSP430X : OFBA_MSPABI_Val_ISA_MSP430);
2128   /* Emit .mspabi_attribute directive for OFBA_MSPABI_Tag_Code_Model.  */
2129   fprintf (asm_out_file, "\t%s %d, %d\n", msp430_attr,
2130            OFBA_MSPABI_Tag_Code_Model,
2131            TARGET_LARGE ? OFBA_MSPABI_Val_Model_Large
2132            : OFBA_MSPABI_Val_Model_Small);
2133   /* Emit .mspabi_attribute directive for OFBA_MSPABI_Tag_Data_Model.  */
2134   fprintf (asm_out_file, "\t%s %d, %d\n", msp430_attr,
2135            OFBA_MSPABI_Tag_Data_Model,
2136            TARGET_LARGE ? OFBA_MSPABI_Val_Model_Large
2137            : OFBA_MSPABI_Val_Model_Small);
2138 #ifdef HAVE_AS_MSPABI_ATTRIBUTE
2139   /* Emit .gnu_attribute directive for Tag_GNU_MSP430_Data_Region.  */
2140   fprintf (asm_out_file, "\t%s %d, %d\n", gnu_attr, Tag_GNU_MSP430_Data_Region,
2141            msp430_data_region == MSP430_REGION_LOWER
2142            ? Tag_GNU_MSP430_Data_Region_Lower
2143            : Tag_GNU_MSP430_Data_Region_Any);
2144 #endif
2145 #endif
2146 }
2147
2148 enum msp430_builtin
2149 {
2150   MSP430_BUILTIN_BIC_SR,
2151   MSP430_BUILTIN_BIS_SR,
2152   MSP430_BUILTIN_DELAY_CYCLES,
2153   MSP430_BUILTIN_max
2154 };
2155
2156 static GTY(()) tree msp430_builtins[(int) MSP430_BUILTIN_max];
2157
2158 static void
2159 msp430_init_builtins (void)
2160 {
2161   tree void_ftype_int = build_function_type_list (void_type_node,
2162                                                   integer_type_node, NULL);
2163   tree void_ftype_longlong
2164     = build_function_type_list (void_type_node, long_long_integer_type_node,
2165                                 NULL);
2166
2167   msp430_builtins[MSP430_BUILTIN_BIC_SR] =
2168     add_builtin_function ( "__bic_SR_register_on_exit", void_ftype_int,
2169                           MSP430_BUILTIN_BIC_SR, BUILT_IN_MD, NULL, NULL_TREE);
2170
2171   msp430_builtins[MSP430_BUILTIN_BIS_SR] =
2172     add_builtin_function ( "__bis_SR_register_on_exit", void_ftype_int,
2173                           MSP430_BUILTIN_BIS_SR, BUILT_IN_MD, NULL, NULL_TREE);
2174
2175   msp430_builtins[MSP430_BUILTIN_DELAY_CYCLES] =
2176     add_builtin_function ( "__delay_cycles", void_ftype_longlong,
2177                           MSP430_BUILTIN_DELAY_CYCLES, BUILT_IN_MD, NULL,
2178                           NULL_TREE);
2179 }
2180
2181 static tree
2182 msp430_builtin_decl (unsigned code, bool initialize ATTRIBUTE_UNUSED)
2183 {
2184   switch (code)
2185     {
2186     case MSP430_BUILTIN_BIC_SR:
2187     case MSP430_BUILTIN_BIS_SR:
2188     case MSP430_BUILTIN_DELAY_CYCLES:
2189       return msp430_builtins[code];
2190     default:
2191       return error_mark_node;
2192     }
2193 }
2194
2195 /* These constants are really register reads, which are faster than
2196    regular constants.  */
2197 static int
2198 cg_magic_constant (HOST_WIDE_INT c)
2199 {
2200   switch (c)
2201     {
2202     case 0xffff:
2203     case -1:
2204     case 0:
2205     case 1:
2206     case 2:
2207     case 4:
2208     case 8:
2209       return 1;
2210     default:
2211       return 0;
2212     }
2213 }
2214
2215 static rtx
2216 msp430_expand_delay_cycles (rtx arg)
2217 {
2218   HOST_WIDE_INT i, c, n;
2219   /* extra cycles for MSP430X instructions */
2220 #define CYCX(M,X) (msp430x ? (X) : (M))
2221
2222   if (GET_CODE (arg) != CONST_INT)
2223     {
2224       error ("__delay_cycles() only takes constant arguments");
2225       return NULL_RTX;
2226     }
2227
2228   c = INTVAL (arg);
2229
2230   if (HOST_BITS_PER_WIDE_INT > 32)
2231     {
2232       if (c < 0)
2233         {
2234           error ("__delay_cycles only takes non-negative cycle counts");
2235           return NULL_RTX;
2236         }
2237     }
2238
2239   emit_insn (gen_delay_cycles_start (arg));
2240
2241   /* For 32-bit loops, there's 13(16) + 5(min(x,0x10000) + 6x cycles.  */
2242   if (c > 3 * 0xffff + CYCX (7, 10))
2243     {
2244       n = c;
2245       /* There's 4 cycles in the short (i>0xffff) loop and 7 in the long
2246          (x<=0xffff) loop.  */
2247       if (c >= 0x10000 * 7 + CYCX (14, 16))
2248         {
2249           i = 0x10000;
2250           c -= CYCX (14, 16) + 7 * 0x10000;
2251           i += c / 4;
2252           c %= 4;
2253           if ((unsigned long long) i > 0xffffffffULL)
2254             {
2255               error ("__delay_cycles is limited to 32-bit loop counts");
2256               return NULL_RTX;
2257             }
2258         }
2259       else
2260         {
2261           i = (c - CYCX (14, 16)) / 7;
2262           c -= CYCX (14, 16) + i * 7;
2263         }
2264
2265       if (cg_magic_constant (i & 0xffff))
2266         c ++;
2267       if (cg_magic_constant ((i >> 16) & 0xffff))
2268         c ++;
2269
2270       if (msp430x)
2271         emit_insn (gen_delay_cycles_32x (GEN_INT (i), GEN_INT (n - c)));
2272       else
2273         emit_insn (gen_delay_cycles_32 (GEN_INT (i), GEN_INT (n - c)));
2274     }
2275
2276   /* For 16-bit loops, there's 7(10) + 3x cycles - so the max cycles is
2277      0x30004(7).  */
2278   if (c > 12)
2279     {
2280       n = c;
2281       i = (c - CYCX (7, 10)) / 3;
2282       c -= CYCX (7, 10) + i * 3;
2283
2284       if (cg_magic_constant (i))
2285         c ++;
2286
2287       if (msp430x)
2288         emit_insn (gen_delay_cycles_16x (GEN_INT (i), GEN_INT (n - c)));
2289       else
2290         emit_insn (gen_delay_cycles_16 (GEN_INT (i), GEN_INT (n - c)));
2291     }
2292
2293   while (c > 1)
2294     {
2295       emit_insn (gen_delay_cycles_2 ());
2296       c -= 2;
2297     }
2298
2299   if (c)
2300     {
2301       emit_insn (gen_delay_cycles_1 ());
2302       c -= 1;
2303     }
2304
2305   emit_insn (gen_delay_cycles_end (arg));
2306
2307   return NULL_RTX;
2308 }
2309
2310 static rtx
2311 msp430_expand_builtin (tree exp,
2312                        rtx target ATTRIBUTE_UNUSED,
2313                        rtx subtarget ATTRIBUTE_UNUSED,
2314                        machine_mode mode ATTRIBUTE_UNUSED,
2315                        int ignore ATTRIBUTE_UNUSED)
2316 {
2317   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
2318   unsigned int fcode = DECL_MD_FUNCTION_CODE (fndecl);
2319   rtx arg1 = expand_normal (CALL_EXPR_ARG (exp, 0));
2320
2321   if (fcode == MSP430_BUILTIN_DELAY_CYCLES)
2322     return msp430_expand_delay_cycles (arg1);
2323
2324   if (! msp430_is_interrupt_func ())
2325     {
2326       error ("MSP430 builtin functions only work inside interrupt handlers");
2327       return NULL_RTX;
2328     }
2329
2330   if (! REG_P (arg1) && ! CONSTANT_P (arg1))
2331     arg1 = force_reg (mode, arg1);
2332
2333   switch (fcode)
2334     {
2335     case MSP430_BUILTIN_BIC_SR:  emit_insn (gen_bic_SR (arg1)); break;
2336     case MSP430_BUILTIN_BIS_SR:  emit_insn (gen_bis_SR (arg1)); break;
2337     default:
2338       internal_error ("bad builtin code");
2339       break;
2340     }
2341   return NULL_RTX;
2342 }
2343
2344 #undef  TARGET_INIT_BUILTINS
2345 #define TARGET_INIT_BUILTINS  msp430_init_builtins
2346
2347 #undef  TARGET_EXPAND_BUILTIN
2348 #define TARGET_EXPAND_BUILTIN msp430_expand_builtin
2349
2350 #undef  TARGET_BUILTIN_DECL
2351 #define TARGET_BUILTIN_DECL   msp430_builtin_decl
2352
2353 void
2354 msp430_expand_prologue (void)
2355 {
2356   int i, j;
2357   int fs;
2358   /* Always use stack_pointer_rtx instead of calling
2359      rtx_gen_REG ourselves.  Code elsewhere in GCC assumes
2360      that there is a single rtx representing the stack pointer,
2361      namely stack_pointer_rtx, and uses == to recognize it.  */
2362   rtx sp = stack_pointer_rtx;
2363   rtx p;
2364
2365   if (is_naked_func ())
2366     {
2367       /* We must generate some RTX as thread_prologue_and_epilogue_insns()
2368          examines the output of the gen_prologue() function.  */
2369       emit_insn (gen_rtx_CLOBBER (VOIDmode, GEN_INT (0)));
2370       return;
2371     }
2372
2373   emit_insn (gen_prologue_start_marker ());
2374
2375   if (is_critical_func ())
2376     {
2377       emit_insn (gen_push_intr_state ());
2378       emit_insn (gen_disable_interrupts ());
2379     }
2380   else if (is_reentrant_func ())
2381     emit_insn (gen_disable_interrupts ());
2382
2383   if (!cfun->machine->computed)
2384     msp430_compute_frame_info ();
2385
2386   if (flag_stack_usage_info)
2387     current_function_static_stack_size = cfun->machine->framesize;
2388
2389   if (crtl->args.pretend_args_size)
2390     {
2391       rtx note;
2392
2393       gcc_assert (crtl->args.pretend_args_size == 2);
2394
2395       p = emit_insn (gen_grow_and_swap ());
2396
2397       /* Document the stack decrement...  */
2398       note = F (gen_rtx_SET (stack_pointer_rtx,
2399                              gen_rtx_MINUS (Pmode,
2400                                             stack_pointer_rtx, GEN_INT (2))));
2401       add_reg_note (p, REG_FRAME_RELATED_EXPR, note);
2402
2403       /* ...and the establishment of a new location for the return address.  */
2404       note = F (gen_rtx_SET (gen_rtx_MEM (Pmode,
2405                                           gen_rtx_PLUS (Pmode,
2406                                                         stack_pointer_rtx,
2407                                                         GEN_INT (-2))),
2408                              pc_rtx));
2409       add_reg_note (p, REG_CFA_OFFSET, note);
2410       F (p);
2411     }
2412
2413   for (i = 15; i >= 4; i--)
2414     if (cfun->machine->need_to_save[i])
2415       {
2416         int seq, count;
2417         rtx note;
2418
2419         for (seq = i - 1; seq >= 4 && cfun->machine->need_to_save[seq]; seq --)
2420           ;
2421         count = i - seq;
2422
2423         if (msp430x)
2424           {
2425             /* Note: with TARGET_LARGE we still use PUSHM as PUSHX.A is two
2426                bytes bigger.  */
2427             p = F (emit_insn (gen_pushm (gen_rtx_REG (Pmode, i),
2428                                          GEN_INT (count))));
2429
2430             note = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (count + 1));
2431
2432             XVECEXP (note, 0, 0)
2433               = F (gen_rtx_SET (stack_pointer_rtx,
2434                                 gen_rtx_PLUS (Pmode,
2435                                               stack_pointer_rtx,
2436                                               GEN_INT (count * (TARGET_LARGE
2437                                                                 ? -4 : -2)))));
2438
2439             /* *sp-- = R[i-j] */
2440             /* sp+N     R10
2441                ...
2442                sp       R4  */
2443             for (j = 0; j < count; j ++)
2444               {
2445                 rtx addr;
2446                 int ofs = (count - j - 1) * (TARGET_LARGE ? 4 : 2);
2447
2448                 if (ofs)
2449                   addr = gen_rtx_PLUS (Pmode, sp, GEN_INT (ofs));
2450                 else
2451                   addr = stack_pointer_rtx;
2452
2453                 XVECEXP (note, 0, j + 1) =
2454                   F (gen_rtx_SET (gen_rtx_MEM (Pmode, addr),
2455                                   gen_rtx_REG (Pmode, i - j)));
2456               }
2457
2458             add_reg_note (p, REG_FRAME_RELATED_EXPR, note);
2459             i -= count - 1;
2460           }
2461         else
2462           F (emit_insn (gen_push (gen_rtx_REG (Pmode, i))));
2463       }
2464
2465   if (frame_pointer_needed)
2466     F (emit_move_insn (gen_rtx_REG (Pmode, FRAME_POINTER_REGNUM), sp));
2467
2468   fs = cfun->machine->framesize_locals + cfun->machine->framesize_outgoing;
2469
2470   increment_stack (- fs);
2471
2472   emit_insn (gen_prologue_end_marker ());
2473 }
2474
2475 void
2476 msp430_expand_epilogue (int is_eh)
2477 {
2478   int i;
2479   int fs;
2480   int helper_n = 0;
2481
2482   if (is_naked_func ())
2483     {
2484       /* We must generate some RTX as thread_prologue_and_epilogue_insns()
2485          examines the output of the gen_epilogue() function.  */
2486       emit_insn (gen_rtx_CLOBBER (VOIDmode, GEN_INT (0)));
2487       return;
2488     }
2489
2490   if (cfun->machine->need_to_save[10])
2491     {
2492       /* Check for a helper function.  */
2493       helper_n = 7; /* For when the loop below never sees a match.  */
2494       for (i = 9; i >= 4; i--)
2495         if (!cfun->machine->need_to_save[i])
2496           {
2497             helper_n = 10 - i;
2498             for (; i >= 4; i--)
2499               if (cfun->machine->need_to_save[i])
2500                 {
2501                   helper_n = 0;
2502                   break;
2503                 }
2504             break;
2505           }
2506     }
2507
2508   emit_insn (gen_epilogue_start_marker ());
2509
2510   if (cfun->decl && strcmp (IDENTIFIER_POINTER (DECL_NAME (cfun->decl)),
2511                             "main") == 0)
2512     emit_insn (gen_msp430_refsym_need_exit ());
2513
2514   if (is_wakeup_func ())
2515     /* Clear the SCG1, SCG0, OSCOFF and CPUOFF bits in the saved copy of the
2516        status register current residing on the stack.  When this function
2517        executes its RETI instruction the SR will be updated with this saved
2518        value, thus ensuring that the processor is woken up from any low power
2519        state in which it may be residing.  */
2520     emit_insn (gen_bic_SR (GEN_INT (0xf0)));
2521
2522   fs = cfun->machine->framesize_locals + cfun->machine->framesize_outgoing;
2523
2524   increment_stack (fs);
2525
2526   if (is_eh)
2527     {
2528       /* We need to add the right "SP" register save just after the
2529          regular ones, so that when we pop it off we're in the EH
2530          return frame, not this one.  This overwrites our own return
2531          address, but we're not going to be returning anyway.  */
2532       rtx r12 = gen_rtx_REG (Pmode, 12);
2533       rtx (*addPmode)(rtx, rtx, rtx) = TARGET_LARGE ? gen_addpsi3 : gen_addhi3;
2534
2535       /* R12 will hold the new SP.  */
2536       i = cfun->machine->framesize_regs;
2537       emit_move_insn (r12, stack_pointer_rtx);
2538       emit_insn (addPmode (r12, r12, EH_RETURN_STACKADJ_RTX));
2539       emit_insn (addPmode (r12, r12, GEN_INT (i)));
2540       emit_move_insn (gen_rtx_MEM (Pmode, plus_constant (Pmode,
2541                                                          stack_pointer_rtx,
2542                                                          i)), r12);
2543     }
2544
2545   for (i = 4; i <= 15; i++)
2546     if (cfun->machine->need_to_save[i])
2547       {
2548         int seq, count;
2549
2550         for (seq = i + 1; seq <= 15 && cfun->machine->need_to_save[seq]; seq ++)
2551           ;
2552         count = seq - i;
2553
2554         if (msp430x)
2555           {
2556             /* Note: With TARGET_LARGE we still use
2557                POPM as POPX.A is two bytes bigger.  */
2558             emit_insn (gen_popm (stack_pointer_rtx, GEN_INT (seq - 1),
2559                                  GEN_INT (count)));
2560             i += count - 1;
2561           }
2562         else if (i == 11 - helper_n
2563                  && ! msp430_is_interrupt_func ()
2564                  && ! is_reentrant_func ()
2565                  && ! is_critical_func ()
2566                  && crtl->args.pretend_args_size == 0
2567                  /* Calling the helper takes as many bytes as the POP;RET
2568                     sequence.  */
2569                  && helper_n > 1
2570                  && !is_eh)
2571           {
2572             emit_jump_insn (gen_epilogue_helper (GEN_INT (helper_n)));
2573             return;
2574           }
2575         else
2576           emit_insn (gen_pop (gen_rtx_REG (Pmode, i)));
2577       }
2578
2579   if (is_eh)
2580     {
2581       /* Also pop SP, which puts us into the EH return frame.  Except
2582          that you can't "pop" sp, you have to just load it off the
2583          stack.  */
2584       emit_move_insn (stack_pointer_rtx, gen_rtx_MEM (Pmode,
2585                                                       stack_pointer_rtx));
2586     }
2587
2588   if (crtl->args.pretend_args_size)
2589     emit_insn (gen_swap_and_shrink ());
2590
2591   if (is_critical_func ())
2592     emit_insn (gen_pop_intr_state ());
2593   else if (is_reentrant_func ())
2594     emit_insn (gen_enable_interrupts ());
2595
2596   emit_jump_insn (gen_msp430_return ());
2597 }
2598
2599 /* Implements EH_RETURN_STACKADJ_RTX.  Saved and used later in
2600    m32c_emit_eh_epilogue.  */
2601 rtx
2602 msp430_eh_return_stackadj_rtx (void)
2603 {
2604   if (!cfun->machine->eh_stack_adjust)
2605     {
2606       rtx sa;
2607
2608       sa = gen_rtx_REG (Pmode, 15);
2609       cfun->machine->eh_stack_adjust = sa;
2610     }
2611   return cfun->machine->eh_stack_adjust;
2612 }
2613
2614 /* This function is called before reload, to "fix" the stack in
2615    preparation for an EH return.  */
2616 void
2617 msp430_expand_eh_return (rtx eh_handler)
2618 {
2619   /* These are all Pmode */
2620   rtx ap, sa, ra, tmp;
2621
2622   ap = arg_pointer_rtx;
2623   sa = msp430_eh_return_stackadj_rtx ();
2624   ra = eh_handler;
2625
2626   tmp = ap;
2627   tmp = gen_rtx_PLUS (Pmode, ap, sa);
2628   tmp = plus_constant (Pmode, tmp, TARGET_LARGE ? -4 : -2);
2629   tmp = gen_rtx_MEM (Pmode, tmp);
2630   emit_move_insn (tmp, ra);
2631 }
2632
2633 #undef  TARGET_INIT_DWARF_REG_SIZES_EXTRA
2634 #define TARGET_INIT_DWARF_REG_SIZES_EXTRA msp430_init_dwarf_reg_sizes_extra
2635 void
2636 msp430_init_dwarf_reg_sizes_extra (tree address)
2637 {
2638   int i;
2639   rtx addr = expand_normal (address);
2640   rtx mem = gen_rtx_MEM (BLKmode, addr);
2641
2642   /* This needs to match msp430_unwind_word_mode (above).  */
2643   if (!msp430x)
2644     return;
2645
2646   for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
2647     {
2648       unsigned int dnum = DWARF_FRAME_REGNUM (i);
2649       unsigned int rnum = DWARF2_FRAME_REG_OUT (dnum, 1);
2650
2651       if (rnum < DWARF_FRAME_REGISTERS)
2652         {
2653           HOST_WIDE_INT offset = rnum * GET_MODE_SIZE (QImode);
2654
2655           emit_move_insn (adjust_address (mem, QImode, offset),
2656                           gen_int_mode (4, QImode));
2657         }
2658     }
2659 }
2660
2661 /* The MSP430 ABI defines a number of helper functions that should be
2662    used for, for example, 32-bit shifts.  This function is called to
2663    emit such a function, using the table above to optimize some
2664    cases.  */
2665 void
2666 msp430_expand_helper (rtx *operands, const char *helper_name,
2667                       bool const_variants)
2668 {
2669   rtx c, fusage, fsym;
2670   char *helper_const = NULL;
2671   int arg1 = 12;
2672   int arg2 = 13;
2673   int arg1sz = 1;
2674   machine_mode arg0mode = GET_MODE (operands[0]);
2675   machine_mode arg1mode = GET_MODE (operands[1]);
2676   machine_mode arg2mode = GET_MODE (operands[2]);
2677   int expand_mpy = strncmp (helper_name, "__mspabi_mpy",
2678                             sizeof ("__mspabi_mpy") - 1) == 0;
2679   /* This function has been used incorrectly if CONST_VARIANTS is TRUE for a
2680      hwmpy function.  */
2681   gcc_assert (!(expand_mpy && const_variants));
2682
2683   if (arg1mode != VOIDmode && arg2mode != VOIDmode)
2684     /* Modes of arguments must be equal if not constants.  */
2685     gcc_assert (arg1mode == arg2mode);
2686
2687   if (arg1mode == VOIDmode)
2688     arg1mode = arg0mode;
2689   if (arg2mode == VOIDmode)
2690     arg2mode = arg0mode;
2691
2692   if (arg1mode == SImode)
2693     {
2694       arg2 = 14;
2695       arg1sz = 2;
2696     }
2697   else if (arg1mode == DImode)
2698     {
2699       arg1 = 8;
2700       arg1sz = 4;
2701       arg2 = 12;
2702     }
2703
2704   /* Use the "const_variant" of a shift library function if requested.
2705      These are faster, but have larger code size.  */
2706   if (const_variants
2707       && CONST_INT_P (operands[2])
2708       && INTVAL (operands[2]) >= 1
2709       && INTVAL (operands[2]) <= 15)
2710     {
2711       /* Note that the INTVAL is limited in value and length by the conditional
2712          above.  */
2713       int len = strlen (helper_name) + 4;
2714       helper_const = (char *) xmalloc (len);
2715       snprintf (helper_const, len, "%s_%d", helper_name,
2716                 (int) INTVAL (operands[2]));
2717     }
2718
2719   /* Setup the arguments to the helper function.  */
2720   emit_move_insn (gen_rtx_REG (arg1mode, arg1),
2721                   operands[1]);
2722   if (!helper_const)
2723     emit_move_insn (gen_rtx_REG (arg2mode, arg2),
2724                     operands[2]);
2725
2726   if (expand_mpy)
2727     {
2728       if (msp430_use_f5_series_hwmult ())
2729         fsym = gen_rtx_SYMBOL_REF (VOIDmode, concat (helper_name,
2730                                                      "_f5hw", NULL));
2731       else if (use_32bit_hwmult ())
2732         {
2733           /* When the arguments are 16-bits, the 16-bit hardware multiplier is
2734              used.  */
2735           if (arg1mode == HImode)
2736             fsym = gen_rtx_SYMBOL_REF (VOIDmode, concat (helper_name,
2737                                                          "_hw", NULL));
2738           else
2739             fsym = gen_rtx_SYMBOL_REF (VOIDmode, concat (helper_name,
2740                                                          "_hw32", NULL));
2741         }
2742       /* 16-bit hardware multiply.  */
2743       else if (msp430_has_hwmult ())
2744         fsym = gen_rtx_SYMBOL_REF (VOIDmode, concat (helper_name,
2745                                                      "_hw", NULL));
2746       else
2747         fsym = gen_rtx_SYMBOL_REF (VOIDmode, helper_name);
2748     }
2749   else
2750     fsym = gen_rtx_SYMBOL_REF (VOIDmode,
2751                                helper_const ? helper_const : helper_name);
2752
2753   c = gen_call_value_internal (gen_rtx_REG (arg0mode, 12), fsym, GEN_INT (0));
2754
2755   c = emit_call_insn (c);
2756   RTL_CONST_CALL_P (c) = 1;
2757
2758   /* Add register usage information for the arguments to the call.  */
2759   fusage = NULL;
2760   use_regs (&fusage, arg1, arg1sz);
2761   if (!helper_const)
2762     {
2763       /* If we are expanding a shift, we only need to use the low register
2764          for the shift amount.  */
2765       if (!expand_mpy)
2766         use_regs (&fusage, arg2, 1);
2767       else
2768         use_regs (&fusage, arg2, arg1sz);
2769     }
2770   add_function_usage_to (c, fusage);
2771
2772   emit_move_insn (operands[0],
2773                   /* Return value will always start in R12.  */
2774                   gen_rtx_REG (arg0mode, 12));
2775 }
2776
2777 /* Return TRUE if the helper function should be used and FALSE if the shifts
2778    insns should be emitted inline.  */
2779 static bool
2780 use_helper_for_const_shift (enum rtx_code code, machine_mode mode,
2781                             HOST_WIDE_INT amt)
2782 {
2783   const int default_inline_shift = 4;
2784   /* We initialize the option to 65 so we know if the user set it or not.  */
2785   int user_set_max_inline = (msp430_max_inline_shift == 65 ? 0 : 1);
2786   int max_inline = (user_set_max_inline ? msp430_max_inline_shift
2787                     : default_inline_shift);
2788   /* 32-bit shifts are roughly twice as costly as 16-bit shifts so we adjust
2789      the heuristic accordingly.  */
2790   int max_inline_32 = max_inline / 2;
2791
2792   /* Don't use helpers for these modes on 430X, when optimizing for speed, or
2793      when emitting a small number of insns.  */
2794   if ((mode == E_QImode || mode == E_HImode || mode == E_PSImode)
2795       && (msp430x
2796           /* If the user set max_inline then we always obey that number.
2797              Otherwise we always emit the shifts inline at -O2 and above.  */
2798           || amt <= max_inline
2799           || (!user_set_max_inline
2800               && (optimize >= 2 && !optimize_size))))
2801     return false;
2802
2803   /* 430 and 430X codegen for SImode shifts is the same.
2804      Set a hard limit of 15 for the number of shifts that will be emitted
2805      inline by default, even at -O2 and above, to prevent code size
2806      explosion.  */
2807   if (mode == E_SImode
2808       && (amt <= max_inline_32
2809           || (!user_set_max_inline
2810               && (optimize >= 2 && !optimize_size)
2811               && amt <= 15)))
2812     return false;
2813
2814   return true;
2815 }
2816
2817 /* For shift operations which will use an mspabi helper function, setup the
2818    call to msp430_expand helper.  Return 1 to indicate we have finished with
2819    this insn and invoke "DONE".
2820    Otherwise return 0 to indicate the insn should fallthrough.
2821    Never FAIL.  */
2822 int
2823 msp430_expand_shift (enum rtx_code code, machine_mode mode, rtx *operands)
2824 {
2825   /* Always use the helper function when the shift amount is not a
2826      constant.  */
2827   if (!CONST_INT_P (operands[2])
2828       || mode == E_DImode
2829       || use_helper_for_const_shift (code, mode, INTVAL (operands[2])))
2830     {
2831       const char *helper_name = NULL;
2832       /* The const variants of mspabi shifts have significantly larger code
2833          size than the generic version, so use the generic version if
2834          optimizing for size.  */
2835       bool const_variant = !optimize_size;
2836       switch (mode)
2837         {
2838         case E_HImode:
2839           helper_name = (code == ASHIFT ? "__mspabi_slli" :
2840                          (code == ASHIFTRT ? "__mspabi_srai" :
2841                           (code == LSHIFTRT ? "__mspabi_srli" :
2842                            NULL)));
2843           break;
2844         case E_PSImode:
2845           helper_name = (code == ASHIFT ? "__gnu_mspabi_sllp" :
2846                          (code == ASHIFTRT ? "__gnu_mspabi_srap" :
2847                           (code == LSHIFTRT ? "__gnu_mspabi_srlp" :
2848                            NULL)));
2849           /* No const variant for PSImode shifts FIXME.  */
2850           const_variant = false;
2851           break;
2852         case E_SImode:
2853           helper_name = (code == ASHIFT ? "__mspabi_slll" :
2854                          (code == ASHIFTRT ? "__mspabi_sral" :
2855                           (code == LSHIFTRT ? "__mspabi_srll" :
2856                            NULL)));
2857           break;
2858         case E_DImode:
2859           helper_name = (code == ASHIFT ? "__mspabi_sllll" :
2860                          (code == ASHIFTRT ? "__mspabi_srall" :
2861                           (code == LSHIFTRT ? "__mspabi_srlll" :
2862                            NULL)));
2863           /* No const variant for DImode shifts.  */
2864           const_variant = false;
2865           break;
2866         default:
2867           gcc_unreachable ();
2868           break;
2869         }
2870       gcc_assert (helper_name);
2871       msp430_expand_helper (operands, helper_name, const_variant);
2872       return 1;
2873     }
2874   /* When returning 0, there must be an insn to match the RTL pattern
2875      otherwise there will be an unrecognizeable insn.  */
2876   return 0;
2877 }
2878
2879 /* Helper function to emit a sequence of shift instructions.  The amount of
2880    shift instructions to emit is in OPERANDS[2].
2881    For 430 we output copies of identical inline shifts for all modes.
2882    For 430X it is inneficient to do so for any modes except SI and DI, since we
2883    can make use of R*M insns or RPT with 430X insns, so this function is only
2884    used for SImode in that case.  */
2885 const char *
2886 msp430_output_asm_shift_insns (enum rtx_code code, machine_mode mode,
2887                                rtx *operands)
2888 {
2889   int i;
2890   int amt;
2891   int max_shift = GET_MODE_BITSIZE (mode) - 1;
2892   gcc_assert (CONST_INT_P (operands[2]));
2893   amt = INTVAL (operands[2]);
2894
2895   if (amt == 0 || amt > max_shift)
2896     {
2897       switch (code)
2898         {
2899         case ASHIFT:
2900           output_asm_insn ("# ignored undefined behaviour left shift "
2901                            "of %1 by %2", operands);
2902           break;
2903         case ASHIFTRT:
2904           output_asm_insn ("# ignored undefined behaviour arithmetic right "
2905                            "shift of %1 by %2", operands);
2906           break;
2907         case LSHIFTRT:
2908           output_asm_insn ("# ignored undefined behaviour logical right shift "
2909                            "of %1 by %2", operands);
2910           break;
2911         default:
2912           gcc_unreachable ();
2913         }
2914       return "";
2915     }
2916
2917   if (code == ASHIFT)
2918     {
2919       if (!msp430x && mode == HImode)
2920         for (i = 0; i < amt; i++)
2921           output_asm_insn ("RLA.W\t%0", operands);
2922       else if (mode == SImode)
2923         for (i = 0; i < amt; i++)
2924           output_asm_insn ("RLA%X0.W\t%L0 { RLC%X0.W\t%H0", operands);
2925       else
2926         /* Catch unhandled cases.  */
2927         gcc_unreachable ();
2928     }
2929   else if (code == ASHIFTRT)
2930     {
2931       if (!msp430x && mode == HImode)
2932         for (i = 0; i < amt; i++)
2933           output_asm_insn ("RRA.W\t%0", operands);
2934       else if (mode == SImode)
2935         for (i = 0; i < amt; i++)
2936           output_asm_insn ("RRA%X0.W\t%H0 { RRC%X0.W\t%L0", operands);
2937       else
2938         gcc_unreachable ();
2939     }
2940   else if (code == LSHIFTRT)
2941     {
2942       if (!msp430x && mode == HImode)
2943         for (i = 0; i < amt; i++)
2944           output_asm_insn ("CLRC { RRC.W\t%0", operands);
2945       else if (mode == SImode)
2946         for (i = 0; i < amt; i++)
2947           output_asm_insn ("CLRC { RRC%X0.W\t%H0 { RRC%X0.W\t%L0", operands);
2948       /* FIXME: Why doesn't "RRUX.W\t%H0 { RRC%X0.W\t%L0" work for msp430x?
2949          It causes execution timeouts e.g. pr41963.c.  */
2950 #if 0
2951       else if (msp430x && mode == SImode)
2952         for (i = 0; i < amt; i++)
2953           output_asm_insn ("RRUX.W\t%H0 { RRC%X0.W\t%L0", operands);
2954 #endif
2955       else
2956         gcc_unreachable ();
2957     }
2958   return "";
2959 }
2960
2961 /* Called by cbranch<mode>4 to coerce operands into usable forms.  */
2962 void
2963 msp430_fixup_compare_operands (machine_mode my_mode, rtx * operands)
2964 {
2965   /* constants we're looking for, not constants which are allowed.  */
2966   int const_op_idx = 1;
2967
2968   if (msp430_reversible_cmp_operator (operands[0], VOIDmode))
2969     const_op_idx = 2;
2970
2971   if (GET_CODE (operands[const_op_idx]) != REG
2972       && GET_CODE (operands[const_op_idx]) != MEM)
2973     operands[const_op_idx] = copy_to_mode_reg (my_mode, operands[const_op_idx]);
2974 }
2975
2976 /* Simplify_gen_subreg() doesn't handle memory references the way we
2977    need it to below, so we use this function for when we must get a
2978    valid subreg in a "natural" state.  */
2979 rtx
2980 msp430_subreg (machine_mode mode, rtx r, machine_mode omode, int byte)
2981 {
2982   rtx rv;
2983   gcc_assert (mode == HImode);
2984
2985   if (GET_CODE (r) == SUBREG
2986       && SUBREG_BYTE (r) == 0)
2987     {
2988       rtx ireg = SUBREG_REG (r);
2989       machine_mode imode = GET_MODE (ireg);
2990
2991       /* special case for (HI (SI (PSI ...), 0)) */
2992       if (imode == PSImode
2993           && mode == HImode
2994           && byte == 0)
2995         rv = gen_rtx_SUBREG (mode, ireg, byte);
2996       else
2997         rv = simplify_gen_subreg (mode, ireg, imode, byte);
2998     }
2999   else if (GET_CODE (r) == MEM)
3000     {
3001       /* When byte == 2, we can be certain that we were already called with an
3002          identical rtx with byte == 0.  So we don't need to do anything to
3003          get a 2 byte offset of a (mem (post_inc)) rtx, since the address has
3004          already been offset by the post_inc itself.  */
3005       if (GET_CODE (XEXP (r, 0)) == POST_INC && byte == 2)
3006         byte = 0;
3007       rv = adjust_address (r, mode, byte);
3008     }
3009   else if (GET_CODE (r) == SYMBOL_REF
3010            && (byte == 0 || byte == 2)
3011            && mode == HImode)
3012     {
3013       rv = gen_rtx_ZERO_EXTRACT (HImode, r, GEN_INT (16), GEN_INT (8*byte));
3014       rv = gen_rtx_CONST (HImode, r);
3015     }
3016   else
3017     rv = simplify_gen_subreg (mode, r, omode, byte);
3018
3019   if (!rv)
3020     gcc_unreachable ();
3021
3022   return rv;
3023 }
3024
3025 int
3026 msp430_split_addsi (rtx *operands)
3027 {
3028   operands[3] = msp430_subreg (HImode, operands[0], SImode, 0);
3029   operands[4] = msp430_subreg (HImode, operands[1], SImode, 0);
3030   operands[5] = msp430_subreg (HImode, operands[2], SImode, 0);
3031   operands[6] = msp430_subreg (HImode, operands[0], SImode, 2);
3032   operands[7] = msp430_subreg (HImode, operands[1], SImode, 2);
3033   operands[8] = msp430_subreg (HImode, operands[2], SImode, 2);
3034
3035   /* BZ 64160: Do not use this splitter when the dest partially overlaps the
3036      source.  */
3037   if (reg_overlap_mentioned_p (operands[3], operands[7])
3038       || reg_overlap_mentioned_p (operands[3], operands[8]))
3039     return 1;
3040
3041   if (GET_CODE (operands[5]) == CONST_INT)
3042     operands[9] = GEN_INT (INTVAL (operands[5]) & 0xffff);
3043   /* Handle post_inc, for example:
3044      (set (reg:SI)
3045           (plus:SI (reg:SI)
3046                    (mem:SI (post_inc:PSI (reg:PSI))))).  */
3047   else if (MEM_P (operands[5]) && GET_CODE (XEXP (operands[5], 0)) == POST_INC)
3048     {
3049       /* Strip out the post_inc from (mem (post_inc (reg))).  */
3050       operands[9] = XEXP (XEXP (operands[5], 0), 0);
3051       operands[9] = gen_rtx_MEM (HImode, operands[9]);
3052       /* Then zero extend as normal.  */
3053       operands[9] = gen_rtx_ZERO_EXTEND (SImode, operands[9]);
3054     }
3055   else
3056     operands[9] = gen_rtx_ZERO_EXTEND (SImode, operands[5]);
3057   return 0;
3058 }
3059
3060 /* Called by movsi_x to generate the HImode operands.  */
3061 void
3062 msp430_split_movsi (rtx *operands)
3063 {
3064   rtx op00, op02, op10, op12;
3065
3066   op00 = msp430_subreg (HImode, operands[0], SImode, 0);
3067   op02 = msp430_subreg (HImode, operands[0], SImode, 2);
3068
3069   if (GET_CODE (operands[1]) == CONST
3070       || GET_CODE (operands[1]) == SYMBOL_REF)
3071     {
3072       op10 = gen_rtx_ZERO_EXTRACT (HImode, operands[1], GEN_INT (16),
3073                                    GEN_INT (0));
3074       op10 = gen_rtx_CONST (HImode, op10);
3075       op12 = gen_rtx_ZERO_EXTRACT (HImode, operands[1], GEN_INT (16),
3076                                    GEN_INT (16));
3077       op12 = gen_rtx_CONST (HImode, op12);
3078     }
3079   else
3080     {
3081       op10 = msp430_subreg (HImode, operands[1], SImode, 0);
3082       op12 = msp430_subreg (HImode, operands[1], SImode, 2);
3083     }
3084
3085   if (rtx_equal_p (operands[0], operands[1]))
3086     {
3087       operands[2] = op02;
3088       operands[4] = op12;
3089       operands[3] = op00;
3090       operands[5] = op10;
3091     }
3092   else if (rtx_equal_p (op00, op12)
3093            /* Catch the case where we are loading (rN, rN+1) from mem (rN).  */
3094            || (REG_P (op00) && reg_mentioned_p (op00, op10))
3095            /* Or storing (rN) into mem (rN).  */
3096            || (REG_P (op10) && reg_mentioned_p (op10, op00)))
3097     {
3098       operands[2] = op02;
3099       operands[4] = op12;
3100       operands[3] = op00;
3101       operands[5] = op10;
3102     }
3103   else
3104     {
3105       operands[2] = op00;
3106       operands[4] = op10;
3107       operands[3] = op02;
3108       operands[5] = op12;
3109     }
3110 }
3111
3112 \f
3113 /* The MSPABI specifies the names of various helper functions, many of
3114    which are compatible with GCC's helpers.  This table maps the GCC
3115    name to the MSPABI name.  */
3116 static const struct
3117 {
3118   char const * const gcc_name;
3119   char const * const ti_name;
3120 }
3121 helper_function_name_mappings[] =
3122   {
3123     /* Floating point to/from integer conversions.  */
3124     { "__truncdfsf2", "__mspabi_cvtdf" },
3125     { "__extendsfdf2", "__mspabi_cvtfd" },
3126     { "__fixdfhi", "__mspabi_fixdi" },
3127     { "__fixdfsi", "__mspabi_fixdli" },
3128     { "__fixdfdi", "__mspabi_fixdlli" },
3129     { "__fixunsdfhi", "__mspabi_fixdu" },
3130     { "__fixunsdfsi", "__mspabi_fixdul" },
3131     { "__fixunsdfdi", "__mspabi_fixdull" },
3132     { "__fixsfhi", "__mspabi_fixfi" },
3133     { "__fixsfsi", "__mspabi_fixfli" },
3134     { "__fixsfdi", "__mspabi_fixflli" },
3135     { "__fixunsfhi", "__mspabi_fixfu" },
3136     { "__fixunsfsi", "__mspabi_fixful" },
3137     { "__fixunsfdi", "__mspabi_fixfull" },
3138     { "__floathisf", "__mspabi_fltif" },
3139     { "__floatsisf", "__mspabi_fltlif" },
3140     { "__floatdisf", "__mspabi_fltllif" },
3141     { "__floathidf", "__mspabi_fltid" },
3142     { "__floatsidf", "__mspabi_fltlid" },
3143     { "__floatdidf", "__mspabi_fltllid" },
3144     { "__floatunhisf", "__mspabi_fltuf" },
3145     { "__floatunsisf", "__mspabi_fltulf" },
3146     { "__floatundisf", "__mspabi_fltullf" },
3147     { "__floatunhidf", "__mspabi_fltud" },
3148     { "__floatunsidf", "__mspabi_fltuld" },
3149     { "__floatundidf", "__mspabi_fltulld" },
3150
3151     /* Floating point comparisons.  */
3152     /* GCC uses individual functions for each comparison, TI uses one
3153        compare <=> function.  */
3154
3155     /* Floating point arithmetic.  */
3156     { "__adddf3", "__mspabi_addd" },
3157     { "__addsf3", "__mspabi_addf" },
3158     { "__divdf3", "__mspabi_divd" },
3159     { "__divsf3", "__mspabi_divf" },
3160     { "__muldf3", "__mspabi_mpyd" },
3161     { "__mulsf3", "__mspabi_mpyf" },
3162     { "__subdf3", "__mspabi_subd" },
3163     { "__subsf3", "__mspabi_subf" },
3164     /* GCC does not use helper functions for negation.  */
3165
3166     /* Integer multiply, divide, remainder.  */
3167     { "__mulhi3", "__mspabi_mpyi" },
3168     { "__mulsi3", "__mspabi_mpyl" },
3169     { "__muldi3", "__mspabi_mpyll" },
3170 #if 0
3171     /* Clarify signed vs unsigned first.  */
3172     { "__mulhisi3", "__mspabi_mpysl" }, /* gcc doesn't use widening multiply
3173                                            (yet?) */
3174     { "__mulsidi3", "__mspabi_mpysll" }, /* gcc doesn't use widening multiply
3175                                             (yet?) */
3176 #endif
3177
3178     { "__divhi3", "__mspabi_divi" },
3179     { "__divsi3", "__mspabi_divli" },
3180     { "__divdi3", "__mspabi_divlli" },
3181     { "__udivhi3", "__mspabi_divu" },
3182     { "__udivsi3", "__mspabi_divul" },
3183     { "__udivdi3", "__mspabi_divull" },
3184     { "__modhi3", "__mspabi_remi" },
3185     { "__modsi3", "__mspabi_remli" },
3186     { "__moddi3", "__mspabi_remlli" },
3187     { "__umodhi3", "__mspabi_remu" },
3188     { "__umodsi3", "__mspabi_remul" },
3189     { "__umoddi3", "__mspabi_remull" },
3190
3191     /* Bitwise operations.  */
3192     /* Rotation - no rotation support yet.  */
3193     /* Logical left shift - gcc already does these itself.  */
3194     /* Arithmetic left shift - gcc already does these itself.  */
3195     /* Arithmetic right shift - gcc already does these itself.  */
3196
3197     { NULL, NULL }
3198   };
3199
3200 /* Returns true if the current MCU supports an F5xxx series
3201    hardware multiper.  */
3202
3203 bool
3204 msp430_use_f5_series_hwmult (void)
3205 {
3206   static const char * cached_match = NULL;
3207   static bool cached_result;
3208
3209   if (msp430_hwmult_type == MSP430_HWMULT_F5SERIES)
3210     return true;
3211
3212   if (target_mcu == NULL || msp430_hwmult_type != MSP430_HWMULT_AUTO)
3213     return false;
3214
3215   if (target_mcu == cached_match)
3216     return cached_result;
3217
3218   cached_match = target_mcu;
3219
3220   if (strncasecmp (target_mcu, "msp430f5", 8) == 0)
3221     return cached_result = true;
3222   if (strncasecmp (target_mcu, "msp430fr5", 9) == 0)
3223     return cached_result = true;
3224   if (strncasecmp (target_mcu, "msp430f6", 8) == 0)
3225     return cached_result = true;
3226
3227   msp430_extract_mcu_data (target_mcu);
3228
3229   if (extracted_mcu_data.name != NULL)
3230     return cached_result = extracted_mcu_data.hwmpy == 8;
3231
3232   return cached_result = false;
3233 }
3234
3235 /* Returns true if the current MCU has a second generation
3236    32-bit hardware multiplier.  */
3237
3238 static bool
3239 use_32bit_hwmult (void)
3240 {
3241   static const char * cached_match = NULL;
3242   static bool cached_result;
3243
3244   if (msp430_hwmult_type == MSP430_HWMULT_LARGE)
3245     return true;
3246
3247   if (target_mcu == NULL || msp430_hwmult_type != MSP430_HWMULT_AUTO)
3248     return false;
3249
3250   if (target_mcu == cached_match)
3251     return cached_result;
3252
3253   cached_match = target_mcu;
3254
3255   msp430_extract_mcu_data (target_mcu);
3256   if (extracted_mcu_data.name != NULL)
3257     return cached_result = extracted_mcu_data.hwmpy == 4;
3258
3259   return cached_result = false;
3260 }
3261
3262 /* Returns true if the current MCU does not have a
3263    hardware multiplier of any kind.  */
3264
3265 bool
3266 msp430_has_hwmult (void)
3267 {
3268   static const char * cached_match = NULL;
3269   static bool cached_result;
3270
3271   if (msp430_hwmult_type == MSP430_HWMULT_NONE)
3272     return false;
3273
3274   /* TRUE for any other explicit hwmult specified.  */
3275   if (msp430_hwmult_type != MSP430_HWMULT_AUTO)
3276     return true;
3277
3278   /* Now handle -mhwmult=auto.  */
3279   if (target_mcu == NULL)
3280     return false;
3281
3282   if (target_mcu == cached_match)
3283     return cached_result;
3284
3285   cached_match = target_mcu;
3286
3287   msp430_extract_mcu_data (target_mcu);
3288   if (extracted_mcu_data.name != NULL)
3289     return cached_result = extracted_mcu_data.hwmpy != 0;
3290
3291   /* If we do not recognise the MCU name, we assume that it does not support
3292      any kind of hardware multiply - this is the safest assumption to make.  */
3293   return cached_result = false;
3294 }
3295
3296 /* This function does the same as the default, but it will replace GCC
3297    function names with the MSPABI-specified ones.  */
3298
3299 void
3300 msp430_output_labelref (FILE *file, const char *name)
3301 {
3302   int i;
3303
3304   for (i = 0; helper_function_name_mappings[i].gcc_name; i++)
3305     if (strcmp (helper_function_name_mappings[i].gcc_name, name) == 0)
3306       {
3307         name = helper_function_name_mappings[i].ti_name;
3308         break;
3309       }
3310
3311   /* If we have been given a specific MCU name then we may be
3312      able to make use of its hardware multiply capabilities.  */
3313   if (msp430_has_hwmult ())
3314     {
3315       if (strcmp ("__mspabi_mpyi", name) == 0)
3316         {
3317           if (msp430_use_f5_series_hwmult ())
3318             name = "__mulhi2_f5";
3319           else
3320             name = "__mulhi2";
3321         }
3322       else if (strcmp ("__mspabi_mpyl", name) == 0)
3323         {
3324           if (msp430_use_f5_series_hwmult ())
3325             name = "__mulsi2_f5";
3326           else if (use_32bit_hwmult ())
3327             name = "__mulsi2_hw32";
3328           else
3329             name = "__mulsi2";
3330         }
3331     }
3332
3333   if (user_label_prefix[0] != 0)
3334     fputs (user_label_prefix, file);
3335
3336   fputs (name, file);
3337 }
3338
3339 /* Common code for msp430_print_operand...  */
3340
3341 static void
3342 msp430_print_operand_raw (FILE * file, rtx op)
3343 {
3344   HOST_WIDE_INT i;
3345
3346   switch (GET_CODE (op))
3347     {
3348     case REG:
3349       fprintf (file, "%s", reg_names[REGNO (op)]);
3350       break;
3351
3352     case CONST_INT:
3353       i = INTVAL (op);
3354       if (TARGET_ASM_HEX)
3355         fprintf (file, "%#" HOST_WIDE_INT_PRINT "x", i);
3356       else
3357         fprintf (file, "%" HOST_WIDE_INT_PRINT "d", i);
3358       break;
3359
3360     case CONST:
3361     case PLUS:
3362     case MINUS:
3363     case SYMBOL_REF:
3364     case LABEL_REF:
3365       output_addr_const (file, op);
3366       break;
3367
3368     default:
3369       print_rtl (file, op);
3370       break;
3371     }
3372 }
3373
3374 #undef  TARGET_ASM_ALIGNED_PSI_OP
3375 #define TARGET_ASM_ALIGNED_PSI_OP "\t.long\t"
3376 #undef  TARGET_ASM_UNALIGNED_PSI_OP
3377 #define TARGET_ASM_UNALIGNED_PSI_OP TARGET_ASM_ALIGNED_PSI_OP
3378
3379 #undef  TARGET_PRINT_OPERAND_ADDRESS
3380 #define TARGET_PRINT_OPERAND_ADDRESS    msp430_print_operand_addr
3381
3382 /* Output to stdio stream FILE the assembler syntax for an
3383    instruction operand that is a memory reference whose address
3384    is ADDR.  */
3385
3386 static void
3387 msp430_print_operand_addr (FILE * file, machine_mode /*mode*/, rtx addr)
3388 {
3389   switch (GET_CODE (addr))
3390     {
3391     case PLUS:
3392       msp430_print_operand_raw (file, XEXP (addr, 1));
3393       gcc_assert (REG_P (XEXP (addr, 0)));
3394       fprintf (file, "(%s)", reg_names[REGNO (XEXP (addr, 0))]);
3395       return;
3396
3397     case REG:
3398       fprintf (file, "@");
3399       break;
3400
3401     case POST_INC:
3402       fprintf (file, "@%s+", reg_names[REGNO (XEXP (addr, 0))]);
3403       return;
3404
3405     case CONST:
3406     case CONST_INT:
3407     case SYMBOL_REF:
3408     case LABEL_REF:
3409       fprintf (file, "&");
3410       break;
3411
3412     default:
3413       break;
3414     }
3415
3416   msp430_print_operand_raw (file, addr);
3417 }
3418
3419 /* We can only allow signed 15-bit indexes i.e. +/-32K.  */
3420 static bool
3421 msp430_check_index_not_high_mem (rtx op)
3422 {
3423   if (CONST_INT_P (op)
3424       && IN_RANGE (INTVAL (op), HOST_WIDE_INT_M1U << 15, (1 << 15) - 1))
3425     return true;
3426   return false;
3427 }
3428
3429 /* If this returns true, we don't need a 430X insn.  */
3430 static bool
3431 msp430_check_plus_not_high_mem (rtx op)
3432 {
3433   if (GET_CODE (op) != PLUS)
3434     return false;
3435   rtx op0 = XEXP (op, 0);
3436   rtx op1 = XEXP (op, 1);
3437   if (SYMBOL_REF_P (op0)
3438       && (SYMBOL_REF_FLAGS (op0) & SYMBOL_FLAG_LOW_MEM)
3439       && msp430_check_index_not_high_mem (op1))
3440     return true;
3441   return false;
3442 }
3443
3444 /* Determine whether an RTX is definitely not a MEM referencing an address in
3445    the upper memory region.  Returns true if we've decided the address will be
3446    in the lower memory region, or the RTX is not a MEM.  Returns false
3447    otherwise.
3448    The Ys constraint will catch (mem (plus (const/reg)) but we catch cases
3449    involving a symbol_ref here.  */
3450 bool
3451 msp430_op_not_in_high_mem (rtx op)
3452 {
3453   rtx op0;
3454
3455   if (!TARGET_LARGE || !MEM_P (op))
3456     return true;
3457
3458   op0 = XEXP (op, 0);
3459
3460   if (SYMBOL_REF_P (op0) && (SYMBOL_REF_FLAGS (op0) & SYMBOL_FLAG_LOW_MEM))
3461     /* msp430_encode_section_info decided this mem will be in lower
3462        memory.  */
3463     return true;
3464
3465   /* Check possibilites for (mem (plus)).
3466      e.g. (mem (const (plus ((symbol_ref) (const_int))))) : &addr+2.  */
3467   if (msp430_check_plus_not_high_mem (op0)
3468       || ((GET_CODE (op0) == CONST)
3469           && msp430_check_plus_not_high_mem (XEXP (op0, 0))))
3470     return true;
3471
3472   /* An absolute 16-bit address is allowed.  */
3473   if ((CONST_INT_P (op0) && (IN_RANGE (INTVAL (op0), 0, (1 << 16) - 1))))
3474     return true;
3475
3476   /* Return false when undecided.  */
3477   return false;
3478 }
3479
3480 #undef  TARGET_PRINT_OPERAND
3481 #define TARGET_PRINT_OPERAND            msp430_print_operand
3482
3483 /* A   low 16-bits of int/lower of register pair
3484    B   high 16-bits of int/higher of register pair
3485    C   bits 32-47 of a 64-bit value/reg 3 of a DImode value
3486    D   bits 48-63 of a 64-bit value/reg 4 of a DImode value
3487    H   like %B (for backwards compatibility)
3488    I   inverse of value
3489    J   an integer without a # prefix
3490    L   like %A (for backwards compatibility)
3491    O   offset of the top of the stack
3492    Q   like X but generates an A postfix
3493    R   inverse of condition code, unsigned.
3494    W   value - 16
3495    X   X instruction postfix in large mode
3496    Y   value - 4
3497    Z   value - 1
3498    b   .B or .W or .A, depending upon the mode
3499    p   bit position
3500    r   inverse of condition code
3501    x   like X but only for pointers.  */
3502
3503 static void
3504 msp430_print_operand (FILE * file, rtx op, int letter)
3505 {
3506   rtx addr;
3507
3508   /* We can't use c, n, a, or l.  */
3509   switch (letter)
3510     {
3511     case 'Z':
3512       gcc_assert (CONST_INT_P (op));
3513       /* Print the constant value, less one.  */
3514       fprintf (file, "#%ld", INTVAL (op) - 1);
3515       return;
3516     case 'Y':
3517       gcc_assert (CONST_INT_P (op));
3518       /* Print the constant value, less four.  */
3519       fprintf (file, "#%ld", INTVAL (op) - 4);
3520       return;
3521     case 'W':
3522       gcc_assert (CONST_INT_P (op));
3523       /* Print the constant value, less 16.  */
3524       fprintf (file, "#%ld", INTVAL (op) - 16);
3525       return;
3526     case 'I':
3527       if (GET_CODE (op) == CONST_INT)
3528         {
3529           /* Inverse of constants */
3530           int i = INTVAL (op);
3531           fprintf (file, "%d", ~i);
3532           return;
3533         }
3534       op = XEXP (op, 0);
3535       break;
3536     case 'r': /* Conditional jump where the condition is reversed.  */
3537       switch (GET_CODE (op))
3538         {
3539         case EQ: fprintf (file, "NE"); break;
3540         case NE: fprintf (file, "EQ"); break;
3541         case GEU: fprintf (file, "LO"); break;
3542         case LTU: fprintf (file, "HS"); break;
3543         case GE: fprintf (file, "L"); break;
3544         case LT: fprintf (file, "GE"); break;
3545           /* Assume these have reversed operands.  */
3546         case GTU: fprintf (file, "HS"); break;
3547         case LEU: fprintf (file, "LO"); break;
3548         case GT: fprintf (file, "GE"); break;
3549         case LE: fprintf (file, "L"); break;
3550         default:
3551           msp430_print_operand_raw (file, op);
3552           break;
3553         }
3554       return;
3555     case 'R': /* Conditional jump where the operands are reversed.  */
3556       switch (GET_CODE (op))
3557         {
3558         case GTU: fprintf (file, "LO"); break;
3559         case LEU: fprintf (file, "HS"); break;
3560         case GT: fprintf (file, "L"); break;
3561         case LE: fprintf (file, "GE"); break;
3562         default:
3563           msp430_print_operand_raw (file, op);
3564           break;
3565         }
3566       return;
3567     case 'p': /* Bit position.  0 == 0x01, 3 = 0x08 etc.  */
3568       gcc_assert (CONST_INT_P (op));
3569       fprintf (file, "#%d", 1 << INTVAL (op));
3570       return;
3571     case 'b':
3572       switch (GET_MODE (op))
3573         {
3574         case E_QImode: fprintf (file, ".B"); return;
3575         case E_HImode: fprintf (file, ".W"); return;
3576         case E_PSImode: fprintf (file, ".A"); return;
3577         case E_SImode: fprintf (file, ".A"); return;
3578         default:
3579           return;
3580         }
3581     case 'A':
3582     case 'L': /* Low half.  */
3583       switch (GET_CODE (op))
3584         {
3585         case MEM:
3586           op = adjust_address (op, Pmode, 0);
3587           break;
3588         case REG:
3589           break;
3590         case CONST_INT:
3591           op = GEN_INT (INTVAL (op) & 0xffff);
3592           letter = 0;
3593           break;
3594         default:
3595           /* If you get here, figure out a test case :-) */
3596           gcc_unreachable ();
3597         }
3598       break;
3599     case 'B':
3600     case 'H': /* high half */
3601       switch (GET_CODE (op))
3602         {
3603         case MEM:
3604           /* We don't need to adjust the address for post_inc.  */
3605           op = adjust_address (op, Pmode,
3606                                (GET_CODE (XEXP (op, 0)) == POST_INC) ? 0 : 2);
3607           break;
3608         case REG:
3609           op = gen_rtx_REG (Pmode, REGNO (op) + 1);
3610           break;
3611         case CONST_INT:
3612           op = GEN_INT (INTVAL (op) >> 16);
3613           letter = 0;
3614           break;
3615         default:
3616           /* If you get here, figure out a test case :-) */
3617           gcc_unreachable ();
3618         }
3619       break;
3620     case 'C':
3621       switch (GET_CODE (op))
3622         {
3623         case MEM:
3624           op = adjust_address (op, Pmode,
3625                                (GET_CODE (XEXP (op, 0)) == POST_INC) ? 0 : 4);
3626           break;
3627         case REG:
3628           op = gen_rtx_REG (Pmode, REGNO (op) + 2);
3629           break;
3630         case CONST_INT:
3631           op = GEN_INT ((long long) INTVAL (op) >> 32);
3632           letter = 0;
3633           break;
3634         default:
3635           /* If you get here, figure out a test case :-) */
3636           gcc_unreachable ();
3637         }
3638       break;
3639     case 'D':
3640       switch (GET_CODE (op))
3641         {
3642         case MEM:
3643           op = adjust_address (op, Pmode,
3644                                (GET_CODE (XEXP (op, 0)) == POST_INC) ? 0 : 6);
3645           break;
3646         case REG:
3647           op = gen_rtx_REG (Pmode, REGNO (op) + 3);
3648           break;
3649         case CONST_INT:
3650           op = GEN_INT ((long long) INTVAL (op) >> 48);
3651           letter = 0;
3652           break;
3653         default:
3654           /* If you get here, figure out a test case :-) */
3655           gcc_unreachable ();
3656         }
3657       break;
3658
3659     case 'X':
3660       /* This is used to turn, for example, an ADD opcode into an ADDX
3661          opcode when we're using 20-bit addresses.
3662          This can be used for insns which have only one operand which might be
3663          a mem.
3664          If an insn has two different operands which could be memory operands,
3665          then the "Yx" constraint must be used to determine if the X suffix is
3666          required by checking both operands.  */
3667       if (GET_MODE (op) == PSImode
3668           || !msp430_op_not_in_high_mem (op))
3669         fprintf (file, "X");
3670       return;
3671
3672     case 'x':
3673       /* Similarly, but only for PSImodes.  BIC, and other insn patterns using
3674          the QHI mode iterator (which includes, QI, HI, and PSImode) use
3675          this.  */
3676       if (GET_MODE (op) == PSImode)
3677         fprintf (file, "X");
3678       return;
3679
3680     case 'Q':
3681       /* Likewise, for BR -> BRA.  */
3682       if (TARGET_LARGE)
3683         fprintf (file, "A");
3684       return;
3685
3686     case 'O':
3687       /* Computes the offset to the top of the stack for the current frame.
3688          This has to be done here rather than in, say, msp430_expand_builtin()
3689          because builtins are expanded before the frame layout is
3690          determined.  */
3691       fprintf (file, "%d",
3692                msp430_initial_elimination_offset (ARG_POINTER_REGNUM,
3693                                                   STACK_POINTER_REGNUM)
3694                - (TARGET_LARGE ? 4 : 2));
3695       return;
3696
3697     case 'J':
3698       gcc_assert (GET_CODE (op) == CONST_INT);
3699     case 0:
3700       break;
3701     default:
3702       output_operand_lossage ("invalid operand prefix");
3703       return;
3704     }
3705
3706   switch (GET_CODE (op))
3707     {
3708     case REG:
3709       msp430_print_operand_raw (file, op);
3710       break;
3711
3712     case MEM:
3713       addr = XEXP (op, 0);
3714       msp430_print_operand_addr (file, GET_MODE (op), addr);
3715       break;
3716
3717     case CONST:
3718       if (GET_CODE (XEXP (op, 0)) == ZERO_EXTRACT)
3719         {
3720           op = XEXP (op, 0);
3721           switch (INTVAL (XEXP (op, 2)))
3722             {
3723             case 0:
3724               fprintf (file, "#lo (");
3725               msp430_print_operand_raw (file, XEXP (op, 0));
3726               fprintf (file, ")");
3727               break;
3728
3729             case 16:
3730               fprintf (file, "#hi (");
3731               msp430_print_operand_raw (file, XEXP (op, 0));
3732               fprintf (file, ")");
3733               break;
3734
3735             default:
3736               output_operand_lossage ("invalid zero extract");
3737               break;
3738             }
3739           break;
3740         }
3741       /* Fall through.  */
3742     case CONST_INT:
3743     case SYMBOL_REF:
3744     case LABEL_REF:
3745       if (letter == 0)
3746         fprintf (file, "#");
3747       msp430_print_operand_raw (file, op);
3748       break;
3749
3750     case EQ: fprintf (file, "EQ"); break;
3751     case NE: fprintf (file, "NE"); break;
3752     case GEU: fprintf (file, "HS"); break;
3753     case LTU: fprintf (file, "LO"); break;
3754     case GE: fprintf (file, "GE"); break;
3755     case LT: fprintf (file, "L"); break;
3756
3757     default:
3758       print_rtl (file, op);
3759       break;
3760     }
3761 }
3762
3763 \f
3764 /* Frame stuff.  */
3765
3766 rtx
3767 msp430_return_addr_rtx (int count)
3768 {
3769   int ra_size;
3770   if (count)
3771     return NULL_RTX;
3772
3773   ra_size = TARGET_LARGE ? 4 : 2;
3774   if (crtl->args.pretend_args_size)
3775     ra_size += 2;
3776
3777   return gen_rtx_MEM (Pmode, gen_rtx_PLUS (Pmode, arg_pointer_rtx,
3778                                            GEN_INT (- ra_size)));
3779 }
3780
3781 rtx
3782 msp430_incoming_return_addr_rtx (void)
3783 {
3784   return gen_rtx_MEM (Pmode, stack_pointer_rtx);
3785 }
3786
3787 /* If the path to the MSP430-GCC support files has been found by examining
3788    an environment variable (see msp430_check_env_var_for_devices in
3789    msp430-devices.c), or -mdevices-csv-loc=, register this path as an include
3790    directory so the user can #include msp430.h without needing to specify the
3791    path to the support files with -I.  */
3792 void
3793 msp430_register_pre_includes (const char *sysroot ATTRIBUTE_UNUSED,
3794                               const char *iprefix ATTRIBUTE_UNUSED,
3795                               int stdinc ATTRIBUTE_UNUSED)
3796 {
3797   char *include_dir;
3798   if (msp430_devices_csv_loc)
3799     include_dir = xstrdup (msp430_devices_csv_loc);
3800   else if (msp430_check_env_var_for_devices (&include_dir))
3801     return;
3802   include_dir = msp430_dirname (include_dir);
3803
3804   include_dir = update_path (include_dir, "");
3805   add_path (include_dir, INC_SYSTEM, false, false);
3806 }
3807 \f
3808 /* Instruction generation stuff.  */
3809
3810 /* Generate a sequence of instructions to sign-extend an HI
3811    value into an SI value.  Handles the tricky case where
3812    we are overwriting the destination.  */
3813
3814 const char *
3815 msp430x_extendhisi (rtx * operands)
3816 {
3817   if (REGNO (operands[0]) == REGNO (operands[1]))
3818     /* Low word of dest == source word.  8-byte sequence.  */
3819     return "BIT.W\t#0x8000, %L0 { SUBC.W\t%H0, %H0 { INV.W\t%H0, %H0";
3820
3821   if (! msp430x)
3822     /* Note: This sequence is approximately the same length as invoking a helper
3823        function to perform the sign-extension, as in:
3824
3825        MOV.W  %1, %L0
3826        MOV.W  %1, r12
3827        CALL   __mspabi_srai_15
3828        MOV.W  r12, %H0
3829
3830        but this version does not involve any function calls or using argument
3831        registers, so it reduces register pressure.  10-byte sequence.  */
3832     return "MOV.W\t%1, %L0 { BIT.W\t#0x8000, %L0 { SUBC.W\t%H0, %H0 "
3833       "{ INV.W\t%H0, %H0";
3834
3835   if (REGNO (operands[0]) + 1 == REGNO (operands[1]))
3836     /* High word of dest == source word.  6-byte sequence.  */
3837     return "MOV.W\t%1, %L0 { RPT\t#15 { RRAX.W\t%H0";
3838
3839   /* No overlap between dest and source.  8-byte sequence.  */
3840   return "MOV.W\t%1, %L0 { MOV.W\t%1, %H0 { RPT\t#15 { RRAX.W\t%H0";
3841 }
3842
3843 /* Stop GCC from thinking that it can eliminate (SUBREG:PSI (SI)).  */
3844
3845 #undef TARGET_CAN_CHANGE_MODE_CLASS
3846 #define TARGET_CAN_CHANGE_MODE_CLASS msp430_can_change_mode_class
3847
3848 static bool
3849 msp430_can_change_mode_class (machine_mode from, machine_mode to, reg_class_t)
3850 {
3851   if ((to == PSImode && from == SImode)
3852       || (to == SImode && from == PSImode)
3853       || (to == DImode && from == PSImode)
3854       || (to == PSImode && from == DImode))
3855     return false;
3856   return true;
3857 }
3858 \f
3859 #undef  TARGET_HAVE_SPECULATION_SAFE_VALUE
3860 #define TARGET_HAVE_SPECULATION_SAFE_VALUE speculation_safe_value_not_needed
3861
3862 struct gcc_target targetm = TARGET_INITIALIZER;
3863
3864 #include "gt-msp430.h"