19990502 sourceware import
[external/binutils.git] / gas / config / tc-m32r.c
1 /* tc-m32r.c -- Assembler for the Mitsubishi M32R.
2    Copyright (C) 1996, 1997, 1998, 1999 Free Software Foundation.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to
18    the Free Software Foundation, 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <stdio.h>
22 #include <ctype.h>
23 #include "as.h"
24 #include "subsegs.h"     
25 #include "symcat.h"
26 #include "opcodes/m32r-desc.h"
27 #include "opcodes/m32r-opc.h"
28 #include "cgen.h"
29
30 /* Linked list of symbols that are debugging symbols to be defined as the
31    beginning of the current instruction.  */
32 typedef struct sym_link
33 {
34   struct sym_link *next;
35   symbolS         *symbol;
36 } sym_linkS;
37
38 static sym_linkS *debug_sym_link = (sym_linkS *)0;
39   
40 /* Structure to hold all of the different components describing
41    an individual instruction.  */
42 typedef struct
43 {
44   const CGEN_INSN *     insn;
45   const CGEN_INSN *     orig_insn;
46   CGEN_FIELDS           fields;
47 #if CGEN_INT_INSN_P
48   CGEN_INSN_INT         buffer [1];
49 #define INSN_VALUE(buf) (*(buf))
50 #else
51   unsigned char         buffer [CGEN_MAX_INSN_SIZE];
52 #define INSN_VALUE(buf) (buf)
53 #endif
54   char *                addr;
55   fragS *               frag;
56   int                   num_fixups;
57   fixS *                fixups [GAS_CGEN_MAX_FIXUPS];
58   int                   indices [MAX_OPERAND_INSTANCES];
59   sym_linkS             *debug_sym_link;
60 }
61 m32r_insn;
62
63 /* prev_insn.insn is non-null if last insn was a 16 bit insn on a 32 bit
64    boundary (i.e. was the first of two 16 bit insns).  */
65 static m32r_insn        prev_insn;
66
67 /* Non-zero if we've seen a relaxable insn since the last 32 bit
68    alignment request.  */
69 static int seen_relaxable_p = 0;
70
71 /* Non-zero if -relax specified, in which case sufficient relocs are output
72    for the linker to do relaxing.
73    We do simple forms of relaxing internally, but they are always done.
74    This flag does not apply to them.  */
75 static int m32r_relax;
76
77 #if 0 /* not supported yet */
78 /* If non-NULL, pointer to cpu description file to read.
79    This allows runtime additions to the assembler.  */
80 static const char * m32r_cpu_desc;
81 #endif
82
83 /* Non-zero if warn when a high/shigh reloc has no matching low reloc.
84    Each high/shigh reloc must be paired with it's low cousin in order to
85    properly calculate the addend in a relocatable link (since there is a
86    potential carry from the low to the high/shigh).
87    This option is off by default though for user-written assembler code it
88    might make sense to make the default be on (i.e. have gcc pass a flag
89    to turn it off).  This warning must not be on for GCC created code as
90    optimization may delete the low but not the high/shigh (at least we
91    shouldn't assume or require it to).  */
92 static int warn_unmatched_high = 0;
93
94
95 /* stuff for .scomm symbols.  */
96 static segT     sbss_section;
97 static asection scom_section;
98 static asymbol  scom_symbol;
99
100 const char comment_chars[]        = ";";
101 const char line_comment_chars[]   = "#";
102 const char line_separator_chars[] = "";
103 const char EXP_CHARS[]            = "eE";
104 const char FLT_CHARS[]            = "dD";
105
106 /* Relocations against symbols are done in two
107    parts, with a HI relocation and a LO relocation.  Each relocation
108    has only 16 bits of space to store an addend.  This means that in
109    order for the linker to handle carries correctly, it must be able
110    to locate both the HI and the LO relocation.  This means that the
111    relocations must appear in order in the relocation table.
112
113    In order to implement this, we keep track of each unmatched HI
114    relocation.  We then sort them so that they immediately precede the
115    corresponding LO relocation. */
116
117 struct m32r_hi_fixup
118 {
119   struct m32r_hi_fixup * next;  /* Next HI fixup.  */
120   fixS *                 fixp;  /* This fixup.  */
121   segT                   seg;   /* The section this fixup is in.  */
122
123 };
124
125 /* The list of unmatched HI relocs.  */
126
127 static struct m32r_hi_fixup * m32r_hi_fixup_list;
128
129 \f
130 \f
131 #define M32R_SHORTOPTS ""
132 const char * md_shortopts = M32R_SHORTOPTS;
133
134 struct option md_longopts[] =
135 {
136
137   /* Sigh.  I guess all warnings must now have both variants.  */
138 #define OPTION_WARN_UNMATCHED (OPTION_MD_BASE + 4)
139   {"warn-unmatched-high", OPTION_WARN_UNMATCHED},
140   {"Wuh", OPTION_WARN_UNMATCHED},
141 #define OPTION_NO_WARN_UNMATCHED (OPTION_MD_BASE + 5)
142   {"no-warn-unmatched-high", OPTION_WARN_UNMATCHED},
143   {"Wnuh", OPTION_WARN_UNMATCHED},
144
145 #if 0 /* not supported yet */
146 #define OPTION_RELAX  (OPTION_MD_BASE + 6)
147   {"relax", no_argument, NULL, OPTION_RELAX},
148 #define OPTION_CPU_DESC (OPTION_MD_BASE + 7)
149   {"cpu-desc", required_argument, NULL, OPTION_CPU_DESC},
150 #endif
151
152   {NULL, no_argument, NULL, 0}
153 };
154 size_t md_longopts_size = sizeof (md_longopts);
155
156 int
157 md_parse_option (c, arg)
158      int    c;
159      char * arg;
160 {
161   switch (c)
162     {
163
164     case OPTION_WARN_UNMATCHED:
165       warn_unmatched_high = 1;
166       break;
167
168     case OPTION_NO_WARN_UNMATCHED:
169       warn_unmatched_high = 0;
170       break;
171       
172 #if 0 /* not supported yet */
173     case OPTION_RELAX:
174       m32r_relax = 1;
175       break;
176     case OPTION_CPU_DESC:
177       m32r_cpu_desc = arg;
178       break;
179 #endif
180
181     default:
182       return 0;
183     }
184   return 1;
185 }
186
187 void
188 md_show_usage (stream)
189   FILE * stream;
190 {
191   fprintf (stream, _(" M32R specific command line options:\n"));
192
193
194   fprintf (stream, _("\
195   -warn-unmatched-high    warn when an (s)high reloc has no matching low reloc\n"));
196   fprintf (stream, _("\
197   -no-warn-unmatched-high do not warn about missing low relocs\n"));
198   fprintf (stream, _("\
199   -Wuh                    synonym for -warn-unmatched-high\n"));
200   fprintf (stream, _("\
201   -Wnuh                   synonym for -no-warn-unmatched-high\n"));
202
203 #if 0
204   fprintf (stream, _("\
205   -relax                 create linker relaxable code\n"));
206   fprintf (stream, _("\
207   -cpu-desc              provide runtime cpu description file\n"));
208 #endif
209
210
211 static void fill_insn PARAMS ((int));
212 static void m32r_scomm PARAMS ((int));
213 static void debug_sym PARAMS ((int));
214 static void expand_debug_syms PARAMS ((sym_linkS *, int));
215
216 /* Set by md_assemble for use by m32r_fill_insn.  */
217 static subsegT prev_subseg;
218 static segT prev_seg;
219
220 /* The target specific pseudo-ops which we support.  */
221 const pseudo_typeS md_pseudo_table[] =
222 {
223   { "word",     cons,           4 },
224   { "fillinsn", fill_insn,      0 },
225   { "scomm",    m32r_scomm,     0 },
226   { "debugsym", debug_sym,      0 },
227   { NULL, NULL, 0 }
228 };
229
230 /* FIXME: Should be machine generated.  */
231 #define NOP_INSN 0x7000
232 #define PAR_NOP_INSN 0xf000 /* can only be used in 2nd slot */
233
234 /* When we align the .text section, insert the correct NOP pattern.
235    N is the power of 2 alignment.  LEN is the length of pattern FILL.
236    MAX is the maximum number of characters to skip when doing the alignment,
237    or 0 if there is no maximum.  */
238
239 int
240 m32r_do_align (n, fill, len, max)
241      int          n;
242      const char * fill;
243      int          len;
244      int          max;
245 {
246   /* Only do this if the fill pattern wasn't specified.  */
247   if (fill == NULL
248       && (now_seg->flags & SEC_CODE) != 0
249       /* Only do this special handling if aligning to at least a
250          4 byte boundary.  */
251       && n > 1
252      /* Only do this special handling if we're allowed to emit at
253          least two bytes.  */
254       && (max == 0 || max > 1))
255     {
256       static const unsigned char nop_pattern[] = { 0xf0, 0x00 };
257
258 #if 0
259       /* First align to a 2 byte boundary, in case there is an odd .byte.  */
260       /* FIXME: How much memory will cause gas to use when assembling a big
261          program?  Perhaps we can avoid the frag_align call?  */
262       frag_align (1, 0, 0);
263 #endif
264       /* Next align to a 4 byte boundary (we know n >= 2) using a parallel
265          nop.  */
266       frag_align_pattern (2, nop_pattern, sizeof nop_pattern, 0);
267       /* If doing larger alignments use a repeating sequence of appropriate
268          nops.  */
269       if (n > 2)
270         {
271           static const unsigned char multi_nop_pattern[] =
272           { 0x70, 0x00, 0xf0, 0x00 };
273           frag_align_pattern (n, multi_nop_pattern, sizeof multi_nop_pattern,
274                               max ? max - 2 : 0);
275         }
276       
277       prev_insn.insn = NULL;
278       return 1;
279     }
280
281   return 0;
282 }
283
284 /* If the last instruction was the first of 2 16 bit insns,
285    output a nop to move the PC to a 32 bit boundary.
286
287    This is done via an alignment specification since branch relaxing
288    may make it unnecessary.
289
290    Internally, we need to output one of these each time a 32 bit insn is
291    seen after an insn that is relaxable.  */
292
293 static void
294 fill_insn (ignore)
295      int ignore;
296 {
297   (void) m32r_do_align (2, NULL, 0, 0);
298   prev_insn.insn = NULL;
299   seen_relaxable_p = 0;
300 }
301
302 /* Record the symbol so that when we output the insn, we can create
303    a symbol that is at the start of the instruction.  This is used
304    to emit the label for the start of a breakpoint without causing
305    the assembler to emit a NOP if the previous instruction was a
306    16 bit instruction.  */
307
308 static void
309 debug_sym (ignore)
310      int ignore;
311 {
312   register char *name;
313   register char delim;
314   register char *end_name;
315   register symbolS *symbolP;
316   register sym_linkS *link;
317
318   name = input_line_pointer;
319   delim = get_symbol_end ();
320   end_name = input_line_pointer;
321  
322   if ((symbolP = symbol_find (name)) == NULL
323       && (symbolP = md_undefined_symbol (name)) == NULL)
324     {
325       symbolP = symbol_new (name, undefined_section, 0, &zero_address_frag);
326     }
327
328   symbol_table_insert (symbolP);
329   if (S_IS_DEFINED (symbolP) && S_GET_SEGMENT (symbolP) != reg_section)
330     /* xgettext:c-format */
331     as_bad (_("symbol `%s' already defined"), S_GET_NAME (symbolP));
332
333   else
334     {
335       link = (sym_linkS *) xmalloc (sizeof (sym_linkS));
336       link->symbol = symbolP;
337       link->next = debug_sym_link;
338       debug_sym_link = link;
339       symbolP->local = 1;
340     }
341
342   *end_name = delim;
343   demand_empty_rest_of_line ();
344 }
345
346 /* Second pass to expanding the debug symbols, go through linked
347    list of symbols and reassign the address.  */
348
349 static void
350 expand_debug_syms (syms, align)
351      sym_linkS *syms;
352      int align;
353 {
354   char *save_input_line = input_line_pointer;
355   sym_linkS *next_syms;
356
357   if (!syms)
358     return;
359
360   (void) m32r_do_align (align, NULL, 0, 0);
361   for (; syms != (sym_linkS *)0; syms = next_syms)
362     {
363       symbolS *symbolP = syms->symbol;
364       next_syms = syms->next;
365       input_line_pointer = ".\n";
366       pseudo_set (symbolP);
367       free ((char *)syms);
368     }
369
370   input_line_pointer = save_input_line;
371 }
372
373 /* Cover function to fill_insn called after a label and at end of assembly.
374    The result is always 1: we're called in a conditional to see if the
375    current line is a label.  */
376
377 int
378 m32r_fill_insn (done)
379      int done;
380 {
381   if (prev_seg != NULL)
382     {
383       segT    seg    = now_seg;
384       subsegT subseg = now_subseg;
385
386       subseg_set (prev_seg, prev_subseg);
387       
388       fill_insn (0);
389
390       subseg_set (seg, subseg);
391     }
392
393   if (done && debug_sym_link)
394     {
395       expand_debug_syms (debug_sym_link, 1);
396       debug_sym_link = (sym_linkS *)0;
397     }
398
399   return 1;
400 }
401 \f
402 void
403 md_begin ()
404 {
405   flagword applicable;
406   segT     seg;
407   subsegT  subseg;
408
409   /* Initialize the `cgen' interface.  */
410   
411   /* Set the machine number and endian.  */
412   gas_cgen_cpu_desc = m32r_cgen_cpu_open (CGEN_CPU_OPEN_MACHS, 0,
413                                           CGEN_CPU_OPEN_ENDIAN,
414                                           CGEN_ENDIAN_BIG,
415                                           CGEN_CPU_OPEN_END);
416   m32r_cgen_init_asm (gas_cgen_cpu_desc);
417
418   /* The operand instance table is used during optimization to determine
419      which insns can be executed in parallel.  It is also used to give
420      warnings regarding operand interference in parallel insns.  */
421   m32r_cgen_init_opinst_table (gas_cgen_cpu_desc);
422
423   /* This is a callback from cgen to gas to parse operands.  */
424   cgen_set_parse_operand_fn (gas_cgen_cpu_desc, gas_cgen_parse_operand);
425
426 #if 0 /* not supported yet */
427   /* If a runtime cpu description file was provided, parse it.  */
428   if (m32r_cpu_desc != NULL)
429     {
430       const char * errmsg;
431
432       errmsg = cgen_read_cpu_file (gas_cgen_cpu_desc, m32r_cpu_desc);
433       if (errmsg != NULL)
434         as_bad ("%s: %s", m32r_cpu_desc, errmsg);
435     }
436 #endif
437
438   /* Save the current subseg so we can restore it [it's the default one and
439      we don't want the initial section to be .sbss].  */
440   seg    = now_seg;
441   subseg = now_subseg;
442
443   /* The sbss section is for local .scomm symbols.  */
444   sbss_section = subseg_new (".sbss", 0);
445   
446   /* This is copied from perform_an_assembly_pass.  */
447   applicable = bfd_applicable_section_flags (stdoutput);
448   bfd_set_section_flags (stdoutput, sbss_section, applicable & SEC_ALLOC);
449   
450 #if 0 /* What does this do? [see perform_an_assembly_pass]  */
451   seg_info (bss_section)->bss = 1;
452 #endif
453
454   subseg_set (seg, subseg);
455
456   /* We must construct a fake section similar to bfd_com_section
457      but with the name .scommon.  */
458   scom_section                = bfd_com_section;
459   scom_section.name           = ".scommon";
460   scom_section.output_section = & scom_section;
461   scom_section.symbol         = & scom_symbol;
462   scom_section.symbol_ptr_ptr = & scom_section.symbol;
463   scom_symbol                 = * bfd_com_section.symbol;
464   scom_symbol.name            = ".scommon";
465   scom_symbol.section         = & scom_section;
466
467 }
468
469
470
471 void
472 md_assemble (str)
473      char * str;
474 {
475   m32r_insn insn;
476   char *    errmsg;
477   char *    str2 = NULL;
478
479   /* Initialize GAS's cgen interface for a new instruction.  */
480   gas_cgen_init_parse ();
481
482   
483   insn.debug_sym_link = debug_sym_link;
484   debug_sym_link = (sym_linkS *)0;
485
486   insn.insn = m32r_cgen_assemble_insn
487     (gas_cgen_cpu_desc, str, & insn.fields, insn.buffer, & errmsg);
488   
489   if (!insn.insn)
490     {
491       as_bad (errmsg);
492       return;
493     }
494
495   
496   if (CGEN_INSN_BITSIZE (insn.insn) == 32)
497     {
498       /* 32 bit insns must live on 32 bit boundaries.  */
499       if (prev_insn.insn || seen_relaxable_p)
500         {
501           /* ??? If calling fill_insn too many times turns us into a memory
502              pig, can we call a fn to assemble a nop instead of
503              !seen_relaxable_p?  */
504           fill_insn (0);
505         }
506
507       expand_debug_syms (insn.debug_sym_link, 2);
508
509       /* Doesn't really matter what we pass for RELAX_P here.  */
510       gas_cgen_finish_insn (insn.insn, insn.buffer,
511                             CGEN_FIELDS_BITSIZE (& insn.fields), 1, NULL);
512     }
513   else
514     {
515       int on_32bit_boundary_p;
516
517       if (CGEN_INSN_BITSIZE (insn.insn) != 16)
518         abort();
519
520       insn.orig_insn = insn.insn;
521
522       /* Compute whether we're on a 32 bit boundary or not.
523          prev_insn.insn is NULL when we're on a 32 bit boundary.  */
524       on_32bit_boundary_p = prev_insn.insn == NULL;
525
526
527       expand_debug_syms (insn.debug_sym_link, 1);
528
529       {
530         int i;
531         finished_insnS fi;
532
533         /* Ensure each pair of 16 bit insns is in the same frag.  */
534         frag_grow (4);
535
536         gas_cgen_finish_insn (insn.orig_insn, insn.buffer,
537                               CGEN_FIELDS_BITSIZE (& insn.fields),
538                               1 /*relax_p*/, &fi);
539         insn.addr = fi.addr;
540         insn.frag = fi.frag;
541         insn.num_fixups = fi.num_fixups;
542         for (i = 0; i < fi.num_fixups; ++i)
543           insn.fixups[i] = fi.fixups[i];
544       }
545
546
547       /* Keep track of whether we've seen a pair of 16 bit insns.
548          prev_insn.insn is NULL when we're on a 32 bit boundary.  */
549       if (on_32bit_boundary_p)
550         prev_insn = insn;
551       else
552         prev_insn.insn = NULL;
553       
554       /* If the insn needs the following one to be on a 32 bit boundary
555          (e.g. subroutine calls), fill this insn's slot.  */
556       if (on_32bit_boundary_p
557           && CGEN_INSN_ATTR_VALUE (insn.orig_insn, CGEN_INSN_FILL_SLOT) != 0)
558         fill_insn (0);
559
560       /* If this is a relaxable insn (can be replaced with a larger version)
561          mark the fact so that we can emit an alignment directive for a
562          following 32 bit insn if we see one.   */
563       if (CGEN_INSN_ATTR_VALUE (insn.orig_insn, CGEN_INSN_RELAXABLE) != 0)
564         seen_relaxable_p = 1;
565     }
566
567   /* Set these so m32r_fill_insn can use them.  */
568   prev_seg    = now_seg;
569   prev_subseg = now_subseg;
570 }
571
572 /* The syntax in the manual says constants begin with '#'.
573    We just ignore it.  */
574
575 void 
576 md_operand (expressionP)
577      expressionS * expressionP;
578 {
579   if (* input_line_pointer == '#')
580     {
581       input_line_pointer ++;
582       expression (expressionP);
583     }
584 }
585
586 valueT
587 md_section_align (segment, size)
588      segT   segment;
589      valueT size;
590 {
591   int align = bfd_get_section_alignment (stdoutput, segment);
592   return ((size + (1 << align) - 1) & (-1 << align));
593 }
594
595 symbolS *
596 md_undefined_symbol (name)
597   char * name;
598 {
599   return 0;
600 }
601 \f
602 /* .scomm pseudo-op handler.
603
604    This is a new pseudo-op to handle putting objects in .scommon.
605    By doing this the linker won't need to do any work and more importantly
606    it removes the implicit -G arg necessary to correctly link the object file.
607 */
608
609 static void
610 m32r_scomm (ignore)
611      int ignore;
612 {
613   register char *    name;
614   register char      c;
615   register char *    p;
616   offsetT            size;
617   register symbolS * symbolP;
618   offsetT            align;
619   int                align2;
620
621   name = input_line_pointer;
622   c = get_symbol_end ();
623
624   /* just after name is now '\0' */
625   p = input_line_pointer;
626   * p = c;
627   SKIP_WHITESPACE ();
628   if (* input_line_pointer != ',')
629     {
630       as_bad (_("Expected comma after symbol-name: rest of line ignored."));
631       ignore_rest_of_line ();
632       return;
633     }
634
635   input_line_pointer ++;                /* skip ',' */
636   if ((size = get_absolute_expression ()) < 0)
637     {
638       /* xgettext:c-format */
639       as_warn (_(".SCOMMon length (%ld.) <0! Ignored."), (long) size);
640       ignore_rest_of_line ();
641       return;
642     }
643
644   /* The third argument to .scomm is the alignment.  */
645   if (* input_line_pointer != ',')
646     align = 8;
647   else
648     {
649       ++ input_line_pointer;
650       align = get_absolute_expression ();
651       if (align <= 0)
652         {
653           as_warn (_("ignoring bad alignment"));
654           align = 8;
655         }
656     }
657   /* Convert to a power of 2 alignment.  */
658   if (align)
659     {
660       for (align2 = 0; (align & 1) == 0; align >>= 1, ++ align2)
661         continue;
662       if (align != 1)
663         {
664           as_bad (_("Common alignment not a power of 2"));
665           ignore_rest_of_line ();
666           return;
667         }
668     }
669   else
670     align2 = 0;
671
672   * p = 0;
673   symbolP = symbol_find_or_make (name);
674   * p = c;
675
676   if (S_IS_DEFINED (symbolP))
677     {
678       /* xgettext:c-format */
679       as_bad (_("Ignoring attempt to re-define symbol `%s'."),
680               S_GET_NAME (symbolP));
681       ignore_rest_of_line ();
682       return;
683     }
684
685   if (S_GET_VALUE (symbolP) && S_GET_VALUE (symbolP) != (valueT) size)
686     {
687       /* xgettext:c-format */
688       as_bad (_("Length of .scomm \"%s\" is already %ld. Not changed to %ld."),
689               S_GET_NAME (symbolP),
690               (long) S_GET_VALUE (symbolP),
691               (long) size);
692
693       ignore_rest_of_line ();
694       return;
695     }
696
697   if (symbolP->local)
698     {
699       segT   old_sec    = now_seg;
700       int    old_subsec = now_subseg;
701       char * pfrag;
702
703       record_alignment (sbss_section, align2);
704       subseg_set (sbss_section, 0);
705       
706       if (align2)
707         frag_align (align2, 0, 0);
708       
709       if (S_GET_SEGMENT (symbolP) == sbss_section)
710         symbolP->sy_frag->fr_symbol = 0;
711       
712       symbolP->sy_frag = frag_now;
713       
714       pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP, size,
715                         (char *) 0);
716       * pfrag = 0;
717       S_SET_SIZE (symbolP, size);
718       S_SET_SEGMENT (symbolP, sbss_section);
719       S_CLEAR_EXTERNAL (symbolP);
720       subseg_set (old_sec, old_subsec);
721     }
722   else
723     {
724       S_SET_VALUE (symbolP, (valueT) size);
725       S_SET_ALIGN (symbolP, align2);
726       S_SET_EXTERNAL (symbolP);
727       S_SET_SEGMENT (symbolP, & scom_section);
728     }
729
730   demand_empty_rest_of_line ();
731 }
732 \f
733 /* Interface to relax_segment.  */
734
735 /* FIXME: Build table by hand, get it working, then machine generate.  */
736
737 const relax_typeS md_relax_table[] =
738 {
739 /* The fields are:
740    1) most positive reach of this state,
741    2) most negative reach of this state,
742    3) how many bytes this mode will add to the size of the current frag
743    4) which index into the table to try if we can't fit into this one.  */
744
745   /* The first entry must be unused because an `rlx_more' value of zero ends
746      each list.  */
747   {1, 1, 0, 0},
748
749   /* The displacement used by GAS is from the end of the 2 byte insn,
750      so we subtract 2 from the following.  */
751   /* 16 bit insn, 8 bit disp -> 10 bit range.
752      This doesn't handle a branch in the right slot at the border:
753      the "& -4" isn't taken into account.  It's not important enough to
754      complicate things over it, so we subtract an extra 2 (or + 2 in -ve
755      case).  */
756   {511 - 2 - 2, -512 - 2 + 2, 0, 2 },
757   /* 32 bit insn, 24 bit disp -> 26 bit range.  */
758   {0x2000000 - 1 - 2, -0x2000000 - 2, 2, 0 },
759   /* Same thing, but with leading nop for alignment.  */
760   {0x2000000 - 1 - 2, -0x2000000 - 2, 4, 0 }
761 };
762
763 long
764 m32r_relax_frag (fragP, stretch)
765      fragS * fragP;
766      long    stretch;
767 {
768   /* Address of branch insn.  */
769   long address = fragP->fr_address + fragP->fr_fix - 2;
770   long growth = 0;
771
772   /* Keep 32 bit insns aligned on 32 bit boundaries.  */
773   if (fragP->fr_subtype == 2)
774     {
775       if ((address & 3) != 0)
776         {
777           fragP->fr_subtype = 3;
778           growth = 2;
779         }
780     }
781   else if (fragP->fr_subtype == 3)
782     {
783       if ((address & 3) == 0)
784         {
785           fragP->fr_subtype = 2;
786           growth = -2;
787         }
788     }
789   else
790     {
791       growth = relax_frag (fragP, stretch);
792
793       /* Long jump on odd halfword boundary?  */
794       if (fragP->fr_subtype == 2 && (address & 3) != 0)
795         {
796           fragP->fr_subtype = 3;
797           growth += 2;
798         }
799     }
800
801   return growth;
802 }
803
804 /* Return an initial guess of the length by which a fragment must grow to
805    hold a branch to reach its destination.
806    Also updates fr_type/fr_subtype as necessary.
807
808    Called just before doing relaxation.
809    Any symbol that is now undefined will not become defined.
810    The guess for fr_var is ACTUALLY the growth beyond fr_fix.
811    Whatever we do to grow fr_fix or fr_var contributes to our returned value.
812    Although it may not be explicit in the frag, pretend fr_var starts with a
813    0 value.  */
814
815 int
816 md_estimate_size_before_relax (fragP, segment)
817      fragS * fragP;
818      segT    segment;
819 {
820   int    old_fr_fix = fragP->fr_fix;
821
822   /* The only thing we have to handle here are symbols outside of the
823      current segment.  They may be undefined or in a different segment in
824      which case linker scripts may place them anywhere.
825      However, we can't finish the fragment here and emit the reloc as insn
826      alignment requirements may move the insn about.  */
827
828   if (S_GET_SEGMENT (fragP->fr_symbol) != segment)
829     {
830       /* The symbol is undefined in this segment.
831          Change the relaxation subtype to the max allowable and leave
832          all further handling to md_convert_frag.  */
833       fragP->fr_subtype = 2;
834
835 #if 0 /* Can't use this, but leave in for illustration.  */     
836       /* Change 16 bit insn to 32 bit insn.  */
837       fragP->fr_opcode[0] |= 0x80;
838
839       /* Increase known (fixed) size of fragment.  */
840       fragP->fr_fix += 2;
841
842       /* Create a relocation for it.  */
843       fix_new (fragP, old_fr_fix, 4,
844                fragP->fr_symbol,
845                fragP->fr_offset, 1 /* pcrel */,
846                /* FIXME: Can't use a real BFD reloc here.
847                   gas_cgen_md_apply_fix3 can't handle it.  */
848                BFD_RELOC_M32R_26_PCREL);
849
850       /* Mark this fragment as finished.  */
851       frag_wane (fragP);
852 #else
853       {
854         const CGEN_INSN * insn;
855         int               i;
856
857         /* Update the recorded insn.
858            Fortunately we don't have to look very far.
859            FIXME: Change this to record in the instruction the next higher
860            relaxable insn to use.  */
861         for (i = 0, insn = fragP->fr_cgen.insn; i < 4; i++, insn++)
862           {
863             if ((strcmp (CGEN_INSN_MNEMONIC (insn),
864                          CGEN_INSN_MNEMONIC (fragP->fr_cgen.insn))
865                  == 0)
866                 && CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAX))
867               break;
868           }
869         if (i == 4)
870           abort ();
871
872         fragP->fr_cgen.insn = insn;
873         return 2;
874       }
875 #endif
876     }
877
878   return (fragP->fr_var + fragP->fr_fix - old_fr_fix);
879
880
881 /* *fragP has been relaxed to its final size, and now needs to have
882    the bytes inside it modified to conform to the new size.
883
884    Called after relaxation is finished.
885    fragP->fr_type == rs_machine_dependent.
886    fragP->fr_subtype is the subtype of what the address relaxed to.  */
887
888 void
889 md_convert_frag (abfd, sec, fragP)
890   bfd *   abfd;
891   segT    sec;
892   fragS * fragP;
893 {
894   char * opcode;
895   char * displacement;
896   int    target_address;
897   int    opcode_address;
898   int    extension;
899   int    addend;
900
901   opcode = fragP->fr_opcode;
902
903   /* Address opcode resides at in file space.  */
904   opcode_address = fragP->fr_address + fragP->fr_fix - 2;
905
906   switch (fragP->fr_subtype)
907     {
908     case 1 :
909       extension = 0;
910       displacement = & opcode[1];
911       break;
912     case 2 :
913       opcode[0] |= 0x80;
914       extension = 2;
915       displacement = & opcode[1];
916       break;
917     case 3 :
918       opcode[2] = opcode[0] | 0x80;
919       md_number_to_chars (opcode, PAR_NOP_INSN, 2);
920       opcode_address += 2;
921       extension = 4;
922       displacement = & opcode[3];
923       break;
924     default :
925       abort ();
926     }
927
928   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
929     {
930       /* symbol must be resolved by linker */
931       if (fragP->fr_offset & 3)
932         as_warn (_("Addend to unresolved symbol not on word boundary."));
933       addend = fragP->fr_offset >> 2;
934     }
935   else
936     {
937       /* Address we want to reach in file space.  */
938       target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
939       target_address += fragP->fr_symbol->sy_frag->fr_address;
940       addend = (target_address - (opcode_address & -4)) >> 2;
941     }
942
943   /* Create a relocation for symbols that must be resolved by the linker.
944      Otherwise output the completed insn.  */
945
946   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
947     {
948       assert (fragP->fr_subtype != 1);
949       assert (fragP->fr_cgen.insn != 0);
950       gas_cgen_record_fixup (fragP,
951                              /* Offset of branch insn in frag.  */
952                              fragP->fr_fix + extension - 4,
953                              fragP->fr_cgen.insn,
954                              4 /*length*/,
955                              /* FIXME: quick hack */
956 #if 0
957                              cgen_operand_lookup_by_num (gas_cgen_cpu_desc,
958                                                          fragP->fr_cgen.opindex),
959 #else
960                              cgen_operand_lookup_by_num (gas_cgen_cpu_desc,
961                                                          M32R_OPERAND_DISP24),
962 #endif
963                              fragP->fr_cgen.opinfo,
964                              fragP->fr_symbol, fragP->fr_offset);
965     }
966
967 #define SIZE_FROM_RELAX_STATE(n) ((n) == 1 ? 1 : 3)
968
969   md_number_to_chars (displacement, (valueT) addend,
970                       SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
971
972   fragP->fr_fix += extension;
973 }
974 \f
975 /* Functions concerning relocs.  */
976
977 /* The location from which a PC relative jump should be calculated,
978    given a PC relative reloc.  */
979
980 long
981 md_pcrel_from_section (fixP, sec)
982      fixS * fixP;
983      segT   sec;
984 {
985   if (fixP->fx_addsy != (symbolS *) NULL
986       && (! S_IS_DEFINED (fixP->fx_addsy)
987           || S_GET_SEGMENT (fixP->fx_addsy) != sec))
988     {
989       /* The symbol is undefined (or is defined but not in this section).
990          Let the linker figure it out.  */
991       return 0;
992     }
993
994   return (fixP->fx_frag->fr_address + fixP->fx_where) & -4L;
995 }
996
997 /* Return the bfd reloc type for OPERAND of INSN at fixup FIXP.
998    Returns BFD_RELOC_NONE if no reloc type can be found.
999    *FIXP may be modified if desired.  */
1000
1001 bfd_reloc_code_real_type
1002 md_cgen_lookup_reloc (insn, operand, fixP)
1003      const CGEN_INSN *    insn;
1004      const CGEN_OPERAND * operand;
1005      fixS *               fixP;
1006 {
1007   switch (operand->type)
1008     {
1009     case M32R_OPERAND_DISP8 : return  BFD_RELOC_M32R_10_PCREL;
1010     case M32R_OPERAND_DISP16 : return BFD_RELOC_M32R_18_PCREL;
1011     case M32R_OPERAND_DISP24 : return BFD_RELOC_M32R_26_PCREL;
1012     case M32R_OPERAND_UIMM24 : return BFD_RELOC_M32R_24;
1013     case M32R_OPERAND_HI16 :
1014     case M32R_OPERAND_SLO16 :
1015     case M32R_OPERAND_ULO16 :
1016       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1017       if (fixP->fx_cgen.opinfo != 0)
1018         return fixP->fx_cgen.opinfo;
1019       break;
1020     default : /* avoid -Wall warning */
1021       break;
1022     }
1023   return BFD_RELOC_NONE;
1024 }
1025
1026 /* Record a HI16 reloc for later matching with its LO16 cousin.  */
1027
1028 static void
1029 m32r_record_hi16 (reloc_type, fixP, seg)
1030      int    reloc_type;
1031      fixS * fixP;
1032      segT   seg;
1033 {
1034   struct m32r_hi_fixup * hi_fixup;
1035
1036   assert (reloc_type == BFD_RELOC_M32R_HI16_SLO
1037           || reloc_type == BFD_RELOC_M32R_HI16_ULO);
1038
1039   hi_fixup = ((struct m32r_hi_fixup *)
1040               xmalloc (sizeof (struct m32r_hi_fixup)));
1041   hi_fixup->fixp = fixP;
1042   hi_fixup->seg  = now_seg;
1043   hi_fixup->next = m32r_hi_fixup_list;
1044   
1045   m32r_hi_fixup_list = hi_fixup;
1046 }
1047
1048 /* Called while parsing an instruction to create a fixup.
1049    We need to check for HI16 relocs and queue them up for later sorting.  */
1050
1051 fixS *
1052 m32r_cgen_record_fixup_exp (frag, where, insn, length, operand, opinfo, exp)
1053      fragS *              frag;
1054      int                  where;
1055      const CGEN_INSN *    insn;
1056      int                  length;
1057      const CGEN_OPERAND * operand;
1058      int                  opinfo;
1059      expressionS *        exp;
1060 {
1061   fixS * fixP = gas_cgen_record_fixup_exp (frag, where, insn, length,
1062                                            operand, opinfo, exp);
1063
1064   switch (operand->type)
1065     {
1066     case M32R_OPERAND_HI16 :
1067       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1068       if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_SLO
1069           || fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_ULO)
1070         m32r_record_hi16 (fixP->fx_cgen.opinfo, fixP, now_seg);
1071       break;
1072     default : /* avoid -Wall warning */
1073       break;
1074     }
1075
1076   return fixP;
1077 }
1078
1079 /* Return BFD reloc type from opinfo field in a fixS.
1080    It's tricky using fx_r_type in m32r_frob_file because the values
1081    are BFD_RELOC_UNUSED + operand number.  */
1082 #define FX_OPINFO_R_TYPE(f) ((f)->fx_cgen.opinfo)
1083
1084 /* Sort any unmatched HI16 relocs so that they immediately precede
1085    the corresponding LO16 reloc.  This is called before md_apply_fix and
1086    tc_gen_reloc.  */
1087
1088 void
1089 m32r_frob_file ()
1090 {
1091   struct m32r_hi_fixup * l;
1092
1093   for (l = m32r_hi_fixup_list; l != NULL; l = l->next)
1094     {
1095       segment_info_type * seginfo;
1096       int                 pass;
1097
1098       assert (FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_SLO
1099               || FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_ULO);
1100
1101       /* Check quickly whether the next fixup happens to be a matching low.  */
1102       if (l->fixp->fx_next != NULL
1103           && FX_OPINFO_R_TYPE (l->fixp->fx_next) == BFD_RELOC_M32R_LO16
1104           && l->fixp->fx_addsy == l->fixp->fx_next->fx_addsy
1105           && l->fixp->fx_offset == l->fixp->fx_next->fx_offset)
1106         continue;
1107
1108       /* Look through the fixups for this segment for a matching `low'.
1109          When we find one, move the high/shigh just in front of it.  We do
1110          this in two passes.  In the first pass, we try to find a
1111          unique `low'.  In the second pass, we permit multiple high's
1112          relocs for a single `low'.  */
1113       seginfo = seg_info (l->seg);
1114       for (pass = 0; pass < 2; pass++)
1115         {
1116           fixS * f;
1117           fixS * prev;
1118
1119           prev = NULL;
1120           for (f = seginfo->fix_root; f != NULL; f = f->fx_next)
1121             {
1122               /* Check whether this is a `low' fixup which matches l->fixp.  */
1123               if (FX_OPINFO_R_TYPE (f) == BFD_RELOC_M32R_LO16
1124                   && f->fx_addsy == l->fixp->fx_addsy
1125                   && f->fx_offset == l->fixp->fx_offset
1126                   && (pass == 1
1127                       || prev == NULL
1128                       || (FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_SLO
1129                           && FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_ULO)
1130                       || prev->fx_addsy != f->fx_addsy
1131                       || prev->fx_offset !=  f->fx_offset))
1132                 {
1133                   fixS ** pf;
1134
1135                   /* Move l->fixp before f.  */
1136                   for (pf = &seginfo->fix_root;
1137                        * pf != l->fixp;
1138                        pf = & (* pf)->fx_next)
1139                     assert (* pf != NULL);
1140
1141                   * pf = l->fixp->fx_next;
1142
1143                   l->fixp->fx_next = f;
1144                   if (prev == NULL)
1145                     seginfo->fix_root = l->fixp;
1146                   else
1147                     prev->fx_next = l->fixp;
1148
1149                   break;
1150                 }
1151
1152               prev = f;
1153             }
1154
1155           if (f != NULL)
1156             break;
1157
1158           if (pass == 1
1159               && warn_unmatched_high)
1160             as_warn_where (l->fixp->fx_file, l->fixp->fx_line,
1161                            _("Unmatched high/shigh reloc"));
1162         }
1163     }
1164 }
1165
1166 /* See whether we need to force a relocation into the output file.
1167    This is used to force out switch and PC relative relocations when
1168    relaxing.  */
1169
1170 int
1171 m32r_force_relocation (fix)
1172      fixS * fix;
1173 {
1174   if (fix->fx_r_type == BFD_RELOC_VTABLE_INHERIT
1175       || fix->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
1176     return 1;
1177
1178   if (! m32r_relax)
1179     return 0;
1180
1181   return (fix->fx_pcrel
1182           || 0 /* ??? */);
1183 }
1184 \f
1185 /* Write a value out to the object file, using the appropriate endianness.  */
1186
1187 void
1188 md_number_to_chars (buf, val, n)
1189      char * buf;
1190      valueT val;
1191      int    n;
1192 {
1193   if (target_big_endian)
1194     number_to_chars_bigendian (buf, val, n);
1195   else
1196     number_to_chars_littleendian (buf, val, n);
1197 }
1198
1199 /* Turn a string in input_line_pointer into a floating point constant of type
1200    type, and store the appropriate bytes in *litP.  The number of LITTLENUMS
1201    emitted is stored in *sizeP .  An error message is returned, or NULL on OK.
1202 */
1203
1204 /* Equal to MAX_PRECISION in atof-ieee.c */
1205 #define MAX_LITTLENUMS 6
1206
1207 char *
1208 md_atof (type, litP, sizeP)
1209      char type;
1210      char *litP;
1211      int *sizeP;
1212 {
1213   int              i;
1214   int              prec;
1215   LITTLENUM_TYPE   words [MAX_LITTLENUMS];
1216   char *           t;
1217   char *           atof_ieee ();
1218
1219   switch (type)
1220     {
1221     case 'f':
1222     case 'F':
1223     case 's':
1224     case 'S':
1225       prec = 2;
1226       break;
1227
1228     case 'd':
1229     case 'D':
1230     case 'r':
1231     case 'R':
1232       prec = 4;
1233       break;
1234
1235    /* FIXME: Some targets allow other format chars for bigger sizes here.  */
1236
1237     default:
1238       * sizeP = 0;
1239       return _("Bad call to md_atof()");
1240     }
1241
1242   t = atof_ieee (input_line_pointer, type, words);
1243   if (t)
1244     input_line_pointer = t;
1245   * sizeP = prec * sizeof (LITTLENUM_TYPE);
1246
1247   if (target_big_endian)
1248     {
1249       for (i = 0; i < prec; i++)
1250         {
1251           md_number_to_chars (litP, (valueT) words[i],
1252                               sizeof (LITTLENUM_TYPE));
1253           litP += sizeof (LITTLENUM_TYPE);
1254         }
1255     }
1256   else
1257     {
1258       for (i = prec - 1; i >= 0; i--)
1259         {
1260           md_number_to_chars (litP, (valueT) words[i],
1261                               sizeof (LITTLENUM_TYPE));
1262           litP += sizeof (LITTLENUM_TYPE);
1263         }
1264     }
1265      
1266   return 0;
1267 }
1268
1269 void
1270 m32r_elf_section_change_hook ()
1271 {
1272   /* If we have reached the end of a section and we have just emitted a
1273      16 bit insn, then emit a nop to make sure that the section ends on
1274      a 32 bit boundary.  */
1275   
1276   if (prev_insn.insn || seen_relaxable_p)
1277     (void) m32r_fill_insn (0);
1278 }
1279
1280 boolean
1281 m32r_fix_adjustable (fixP)
1282    fixS *fixP;
1283 {
1284
1285   if (fixP->fx_addsy == NULL)
1286     return 1;
1287   
1288   /* Prevent all adjustments to global symbols. */
1289   if (S_IS_EXTERN (fixP->fx_addsy))
1290     return 0;
1291   if (S_IS_WEAK (fixP->fx_addsy))
1292     return 0;
1293   
1294   /* We need the symbol name for the VTABLE entries */
1295   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
1296       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
1297     return 0;
1298
1299   return 1;
1300 }