1 /* tc-m32r.c -- Assembler for the Renesas M32R.
2    Copyright (C) 1996-2021 Free Software Foundation, Inc.
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 3, 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, 51 Franklin Street - Fifth Floor,
19    Boston, MA 02110-1301, USA.  */
20 
21 #include "as.h"
22 #include "safe-ctype.h"
23 #include "subsegs.h"
24 #include "symcat.h"
25 #include "opcodes/m32r-desc.h"
26 #include "opcodes/m32r-opc.h"
27 #include "cgen.h"
28 #include "elf/m32r.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 we are generating PIC code.  */
72 int pic_code;
73 
74 /* Non-zero if -relax specified, in which case sufficient relocs are output
75    for the linker to do relaxing.
76    We do simple forms of relaxing internally, but they are always done.
77    This flag does not apply to them.  */
78 static int m32r_relax;
79 
80 /* Non-zero if warn when a high/shigh reloc has no matching low reloc.
81    Each high/shigh reloc must be paired with it's low cousin in order to
82    properly calculate the addend in a relocatable link (since there is a
83    potential carry from the low to the high/shigh).
84    This option is off by default though for user-written assembler code it
85    might make sense to make the default be on (i.e. have gcc pass a flag
86    to turn it off).  This warning must not be on for GCC created code as
87    optimization may delete the low but not the high/shigh (at least we
88    shouldn't assume or require it to).  */
89 static int warn_unmatched_high = 0;
90 
91 /* 1 if -m32rx has been specified, in which case support for
92      the extended M32RX instruction set should be enabled.
93    2 if -m32r2 has been specified, in which case support for
94      the extended M32R2 instruction set should be enabled.  */
95 static int enable_m32rx = 0; /* Default to M32R.  */
96 
97 /* Non-zero if -m32rx -hidden has been specified, in which case support for
98    the special M32RX instruction set should be enabled.  */
99 static int enable_special = 0;
100 
101 /* Non-zero if -bitinst has been specified, in which case support
102    for extended M32R bit-field instruction set should be enabled.  */
103 static int enable_special_m32r = 1;
104 
105 /* Non-zero if -float has been specified, in which case support for
106    extended M32R floating point instruction set should be enabled.  */
107 static int enable_special_float = 0;
108 
109 /* Non-zero if the programmer should be warned when an explicit parallel
110    instruction might have constraint violations.  */
111 static int warn_explicit_parallel_conflicts = 1;
112 
113 /* Non-zero if the programmer should not receive any messages about
114    parallel instruction with potential or real constraint violations.
115    The ability to suppress these messages is intended only for hardware
116    vendors testing the chip.  It supersedes
117    warn_explicit_parallel_conflicts.  */
118 static int ignore_parallel_conflicts = 0;
119 
120 /* Non-zero if insns can be made parallel.  */
121 static int use_parallel = 0;
122 
123 /* Non-zero if optimizations should be performed.  */
124 static int optimize;
125 
126 /* m32r er_flags.  */
127 static int m32r_flags = 0;
128 
129 /* Stuff for .scomm symbols.  */
130 static segT     sbss_section;
131 static asection scom_section;
132 static asymbol  scom_symbol;
133 
134 const char comment_chars[]        = ";";
135 const char line_comment_chars[]   = "#";
136 const char line_separator_chars[] = "!";
137 const char EXP_CHARS[]            = "eE";
138 const char FLT_CHARS[]            = "dD";
139 
140 /* Relocations against symbols are done in two
141    parts, with a HI relocation and a LO relocation.  Each relocation
142    has only 16 bits of space to store an addend.  This means that in
143    order for the linker to handle carries correctly, it must be able
144    to locate both the HI and the LO relocation.  This means that the
145    relocations must appear in order in the relocation table.
146 
147    In order to implement this, we keep track of each unmatched HI
148    relocation.  We then sort them so that they immediately precede the
149    corresponding LO relocation.  */
150 
151 struct m32r_hi_fixup
152 {
153   /* Next HI fixup.  */
154   struct m32r_hi_fixup *next;
155 
156   /* This fixup.  */
157   fixS *fixp;
158 
159   /* The section this fixup is in.  */
160   segT seg;
161 };
162 
163 /* The list of unmatched HI relocs.  */
164 
165 static struct m32r_hi_fixup *m32r_hi_fixup_list;
166 
167 static const struct
168 {
169   enum bfd_architecture bfd_mach;
170   int mach_flags;
171 } mach_table[] =
172 {
173   { bfd_mach_m32r,  (1<<MACH_M32R) },
174   { bfd_mach_m32rx, (1<<MACH_M32RX) },
175   { bfd_mach_m32r2, (1<<MACH_M32R2) }
176 };
177 
178 static void
allow_m32rx(int on)179 allow_m32rx (int on)
180 {
181   enable_m32rx = on;
182 
183   if (stdoutput != NULL)
184     bfd_set_arch_mach (stdoutput, TARGET_ARCH, mach_table[on].bfd_mach);
185 
186   if (gas_cgen_cpu_desc != NULL)
187     gas_cgen_cpu_desc->machs = mach_table[on].mach_flags;
188 }
189 
190 #define M32R_SHORTOPTS "O::K:"
191 
192 const char *md_shortopts = M32R_SHORTOPTS;
193 
194 enum md_option_enums
195 {
196   OPTION_M32R = OPTION_MD_BASE,
197   OPTION_M32RX,
198   OPTION_M32R2,
199   OPTION_BIG,
200   OPTION_LITTLE,
201   OPTION_PARALLEL,
202   OPTION_NO_PARALLEL,
203   OPTION_WARN_PARALLEL,
204   OPTION_NO_WARN_PARALLEL,
205   OPTION_IGNORE_PARALLEL,
206   OPTION_NO_IGNORE_PARALLEL,
207   OPTION_SPECIAL,
208   OPTION_SPECIAL_M32R,
209   OPTION_NO_SPECIAL_M32R,
210   OPTION_SPECIAL_FLOAT,
211   OPTION_WARN_UNMATCHED,
212   OPTION_NO_WARN_UNMATCHED
213 };
214 
215 struct option md_longopts[] =
216 {
217   {"m32r",  no_argument, NULL, OPTION_M32R},
218   {"m32rx", no_argument, NULL, OPTION_M32RX},
219   {"m32r2", no_argument, NULL, OPTION_M32R2},
220   {"big", no_argument, NULL, OPTION_BIG},
221   {"little", no_argument, NULL, OPTION_LITTLE},
222   {"EB", no_argument, NULL, OPTION_BIG},
223   {"EL", no_argument, NULL, OPTION_LITTLE},
224   {"parallel", no_argument, NULL, OPTION_PARALLEL},
225   {"no-parallel", no_argument, NULL, OPTION_NO_PARALLEL},
226   {"warn-explicit-parallel-conflicts", no_argument, NULL, OPTION_WARN_PARALLEL},
227   {"Wp", no_argument, NULL, OPTION_WARN_PARALLEL},
228   {"no-warn-explicit-parallel-conflicts", no_argument, NULL, OPTION_NO_WARN_PARALLEL},
229   {"Wnp", no_argument, NULL, OPTION_NO_WARN_PARALLEL},
230   {"ignore-parallel-conflicts", no_argument, NULL, OPTION_IGNORE_PARALLEL},
231   {"Ip", no_argument, NULL, OPTION_IGNORE_PARALLEL},
232   {"no-ignore-parallel-conflicts", no_argument, NULL, OPTION_NO_IGNORE_PARALLEL},
233   {"nIp", no_argument, NULL, OPTION_NO_IGNORE_PARALLEL},
234   {"hidden", no_argument, NULL, OPTION_SPECIAL},
235   {"bitinst", no_argument, NULL, OPTION_SPECIAL_M32R},
236   {"no-bitinst", no_argument, NULL, OPTION_NO_SPECIAL_M32R},
237   {"float", no_argument, NULL, OPTION_SPECIAL_FLOAT},
238   /* Sigh.  I guess all warnings must now have both variants.  */
239   {"warn-unmatched-high", no_argument, NULL, OPTION_WARN_UNMATCHED},
240   {"Wuh", no_argument, NULL, OPTION_WARN_UNMATCHED},
241   {"no-warn-unmatched-high", no_argument, NULL, OPTION_NO_WARN_UNMATCHED},
242   {"Wnuh", no_argument, NULL, OPTION_NO_WARN_UNMATCHED},
243   {NULL, no_argument, NULL, 0}
244 };
245 
246 size_t md_longopts_size = sizeof (md_longopts);
247 
248 static void
little(int on)249 little (int on)
250 {
251   target_big_endian = ! on;
252 }
253 
254 /* Use parallel execution.  */
255 
256 static int
parallel(void)257 parallel (void)
258 {
259   if (! enable_m32rx)
260     return 0;
261 
262   if (use_parallel == 1)
263     return 1;
264 
265   return 0;
266 }
267 
268 int
md_parse_option(int c,const char * arg ATTRIBUTE_UNUSED)269 md_parse_option (int c, const char *arg ATTRIBUTE_UNUSED)
270 {
271   switch (c)
272     {
273     case 'O':
274       optimize = 1;
275       use_parallel = 1;
276       break;
277 
278     case OPTION_M32R:
279       allow_m32rx (0);
280       break;
281 
282     case OPTION_M32RX:
283       allow_m32rx (1);
284       break;
285 
286     case OPTION_M32R2:
287       allow_m32rx (2);
288       enable_special = 1;
289       enable_special_m32r = 1;
290       break;
291 
292     case OPTION_BIG:
293       target_big_endian = 1;
294       break;
295 
296     case OPTION_LITTLE:
297       target_big_endian = 0;
298       break;
299 
300     case OPTION_PARALLEL:
301       use_parallel = 1;
302       break;
303 
304     case OPTION_NO_PARALLEL:
305       use_parallel = 0;
306       break;
307 
308     case OPTION_WARN_PARALLEL:
309       warn_explicit_parallel_conflicts = 1;
310       break;
311 
312     case OPTION_NO_WARN_PARALLEL:
313       warn_explicit_parallel_conflicts = 0;
314       break;
315 
316     case OPTION_IGNORE_PARALLEL:
317       ignore_parallel_conflicts = 1;
318       break;
319 
320     case OPTION_NO_IGNORE_PARALLEL:
321       ignore_parallel_conflicts = 0;
322       break;
323 
324     case OPTION_SPECIAL:
325       if (enable_m32rx)
326 	enable_special = 1;
327       else
328 	{
329 	  /* Pretend that we do not recognise this option.  */
330 	  as_bad (_("Unrecognised option: -hidden"));
331 	  return 0;
332 	}
333       break;
334 
335     case OPTION_SPECIAL_M32R:
336       enable_special_m32r = 1;
337       break;
338 
339     case OPTION_NO_SPECIAL_M32R:
340       enable_special_m32r = 0;
341       break;
342 
343     case OPTION_SPECIAL_FLOAT:
344       enable_special_float = 1;
345       break;
346 
347     case OPTION_WARN_UNMATCHED:
348       warn_unmatched_high = 1;
349       break;
350 
351     case OPTION_NO_WARN_UNMATCHED:
352       warn_unmatched_high = 0;
353       break;
354 
355     case 'K':
356       if (strcmp (arg, "PIC") != 0)
357         as_warn (_("Unrecognized option following -K"));
358       else
359         pic_code = 1;
360       break;
361 
362     default:
363       return 0;
364     }
365 
366   return 1;
367 }
368 
369 void
md_show_usage(FILE * stream)370 md_show_usage (FILE *stream)
371 {
372   fprintf (stream, _(" M32R specific command line options:\n"));
373 
374   fprintf (stream, _("\
375   -m32r                   disable support for the m32rx instruction set\n"));
376   fprintf (stream, _("\
377   -m32rx                  support the extended m32rx instruction set\n"));
378   fprintf (stream, _("\
379   -m32r2                  support the extended m32r2 instruction set\n"));
380   fprintf (stream, _("\
381   -EL,-little             produce little endian code and data\n"));
382   fprintf (stream, _("\
383   -EB,-big                produce big endian code and data\n"));
384   fprintf (stream, _("\
385   -parallel               try to combine instructions in parallel\n"));
386   fprintf (stream, _("\
387   -no-parallel            disable -parallel\n"));
388   fprintf (stream, _("\
389   -no-bitinst             disallow the M32R2's extended bit-field instructions\n"));
390   fprintf (stream, _("\
391   -O                      try to optimize code.  Implies -parallel\n"));
392 
393   fprintf (stream, _("\
394   -warn-explicit-parallel-conflicts     warn when parallel instructions\n"));
395   fprintf (stream, _("\
396                                          might violate constraints\n"));
397   fprintf (stream, _("\
398   -no-warn-explicit-parallel-conflicts  do not warn when parallel\n"));
399   fprintf (stream, _("\
400                                          instructions might violate constraints\n"));
401   fprintf (stream, _("\
402   -Wp                     synonym for -warn-explicit-parallel-conflicts\n"));
403   fprintf (stream, _("\
404   -Wnp                    synonym for -no-warn-explicit-parallel-conflicts\n"));
405   fprintf (stream, _("\
406   -ignore-parallel-conflicts            do not check parallel instructions\n"));
407   fprintf (stream, _("\
408                                          for constraint violations\n"));
409   fprintf (stream, _("\
410   -no-ignore-parallel-conflicts         check parallel instructions for\n"));
411   fprintf (stream, _("\
412                                          constraint violations\n"));
413   fprintf (stream, _("\
414   -Ip                     synonym for -ignore-parallel-conflicts\n"));
415   fprintf (stream, _("\
416   -nIp                    synonym for -no-ignore-parallel-conflicts\n"));
417 
418   fprintf (stream, _("\
419   -warn-unmatched-high    warn when an (s)high reloc has no matching low reloc\n"));
420   fprintf (stream, _("\
421   -no-warn-unmatched-high do not warn about missing low relocs\n"));
422   fprintf (stream, _("\
423   -Wuh                    synonym for -warn-unmatched-high\n"));
424   fprintf (stream, _("\
425   -Wnuh                   synonym for -no-warn-unmatched-high\n"));
426 
427   fprintf (stream, _("\
428   -KPIC                   generate PIC\n"));
429 }
430 
431 /* Set by md_assemble for use by m32r_fill_insn.  */
432 static subsegT prev_subseg;
433 static segT prev_seg;
434 
435 #define GOT_NAME "_GLOBAL_OFFSET_TABLE_"
436 symbolS * GOT_symbol;
437 
438 static inline int
m32r_PIC_related_p(symbolS * sym)439 m32r_PIC_related_p (symbolS *sym)
440 {
441   expressionS *exp;
442 
443   if (! sym)
444     return 0;
445 
446   if (sym == GOT_symbol)
447     return 1;
448 
449   exp = symbol_get_value_expression (sym);
450 
451   return (exp->X_op == O_PIC_reloc
452           || exp->X_md == BFD_RELOC_M32R_26_PLTREL
453           || m32r_PIC_related_p (exp->X_add_symbol)
454           || m32r_PIC_related_p (exp->X_op_symbol));
455 }
456 
457 static inline int
m32r_check_fixup(expressionS * main_exp,bfd_reloc_code_real_type * r_type_p)458 m32r_check_fixup (expressionS *main_exp, bfd_reloc_code_real_type *r_type_p)
459 {
460   expressionS *exp = main_exp;
461 
462   if (exp->X_op == O_add && m32r_PIC_related_p (exp->X_op_symbol))
463     return 1;
464 
465   if (exp->X_op == O_symbol && exp->X_add_symbol)
466     {
467       if (exp->X_add_symbol == GOT_symbol)
468         {
469           *r_type_p = BFD_RELOC_M32R_GOTPC24;
470           return 0;
471         }
472     }
473   else if (exp->X_op == O_add)
474     {
475       exp = symbol_get_value_expression (exp->X_add_symbol);
476       if (! exp)
477         return 0;
478     }
479 
480   if (exp->X_op == O_PIC_reloc)
481     {
482       *r_type_p = exp->X_md;
483       if (exp == main_exp)
484         exp->X_op = O_symbol;
485       else
486        {
487           main_exp->X_add_symbol = exp->X_add_symbol;
488           main_exp->X_add_number += exp->X_add_number;
489        }
490     }
491   else
492     return (m32r_PIC_related_p (exp->X_add_symbol)
493             || m32r_PIC_related_p (exp->X_op_symbol));
494 
495   return 0;
496 }
497 
498 /* FIXME: Should be machine generated.  */
499 #define NOP_INSN     0x7000
500 #define PAR_NOP_INSN 0xf000 /* Can only be used in 2nd slot.  */
501 
502 /* This is called from HANDLE_ALIGN in write.c.  Fill in the contents
503    of an rs_align_code fragment.  */
504 
505 void
m32r_handle_align(fragS * fragp)506 m32r_handle_align (fragS *fragp)
507 {
508   static const unsigned char nop_pattern[] = { 0xf0, 0x00 };
509   static const unsigned char multi_nop_pattern[] = { 0x70, 0x00, 0xf0, 0x00 };
510 
511   int bytes, fix;
512   char *p;
513 
514   if (fragp->fr_type != rs_align_code)
515     return;
516 
517   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
518   p = fragp->fr_literal + fragp->fr_fix;
519   fix = 0;
520 
521   if (bytes & 1)
522     {
523       fix = 1;
524       *p++ = 0;
525       bytes--;
526     }
527 
528   if (bytes & 2)
529     {
530       memcpy (p, nop_pattern, 2);
531       p += 2;
532       bytes -= 2;
533       fix += 2;
534     }
535 
536   memcpy (p, multi_nop_pattern, 4);
537 
538   fragp->fr_fix += fix;
539   fragp->fr_var = 4;
540 }
541 
542 /* If the last instruction was the first of 2 16 bit insns,
543    output a nop to move the PC to a 32 bit boundary.
544 
545    This is done via an alignment specification since branch relaxing
546    may make it unnecessary.
547 
548    Internally, we need to output one of these each time a 32 bit insn is
549    seen after an insn that is relaxable.  */
550 
551 static void
fill_insn(int ignore ATTRIBUTE_UNUSED)552 fill_insn (int ignore ATTRIBUTE_UNUSED)
553 {
554   frag_align_code (2, 0);
555   prev_insn.insn = NULL;
556   seen_relaxable_p = 0;
557 }
558 
559 /* Record the symbol so that when we output the insn, we can create
560    a symbol that is at the start of the instruction.  This is used
561    to emit the label for the start of a breakpoint without causing
562    the assembler to emit a NOP if the previous instruction was a
563    16 bit instruction.  */
564 
565 static void
debug_sym(int ignore ATTRIBUTE_UNUSED)566 debug_sym (int ignore ATTRIBUTE_UNUSED)
567 {
568   char *name;
569   char delim;
570   symbolS *symbolP;
571   sym_linkS *lnk;
572 
573   delim = get_symbol_name (&name);
574 
575   if ((symbolP = symbol_find (name)) == NULL
576       && (symbolP = md_undefined_symbol (name)) == NULL)
577     symbolP = symbol_new (name, undefined_section, &zero_address_frag, 0);
578 
579   symbol_table_insert (symbolP);
580   if (S_IS_DEFINED (symbolP) && (S_GET_SEGMENT (symbolP) != reg_section
581                                  || S_IS_EXTERNAL (symbolP)
582                                  || S_IS_WEAK (symbolP)))
583     /* xgettext:c-format */
584     as_bad (_("symbol `%s' already defined"), S_GET_NAME (symbolP));
585 
586   else
587     {
588       lnk = XNEW (sym_linkS);
589       lnk->symbol = symbolP;
590       lnk->next = debug_sym_link;
591       debug_sym_link = lnk;
592       symbol_get_obj (symbolP)->local = 1;
593     }
594 
595   (void) restore_line_pointer (delim);
596   demand_empty_rest_of_line ();
597 }
598 
599 /* Second pass to expanding the debug symbols, go through linked
600    list of symbols and reassign the address.  */
601 
602 static void
expand_debug_syms(sym_linkS * syms,int align)603 expand_debug_syms (sym_linkS *syms, int align)
604 {
605   char *save_input_line = input_line_pointer;
606   sym_linkS *next_syms;
607 
608   if (!syms)
609     return;
610 
611   (void) frag_align_code (align, 0);
612   for (; syms != (sym_linkS *) 0; syms = next_syms)
613     {
614       symbolS *symbolP = syms->symbol;
615       next_syms = syms->next;
616       input_line_pointer = (char *) ".\n";
617       pseudo_set (symbolP);
618       free ((char *) syms);
619     }
620 
621   input_line_pointer = save_input_line;
622 }
623 
624 void
m32r_flush_pending_output(void)625 m32r_flush_pending_output (void)
626 {
627   if (debug_sym_link)
628     {
629       expand_debug_syms (debug_sym_link, 1);
630       debug_sym_link = (sym_linkS *) 0;
631     }
632 }
633 
634 /* Cover function to fill_insn called after a label and at end of assembly.
635    The result is always 1: we're called in a conditional to see if the
636    current line is a label.  */
637 
638 int
m32r_fill_insn(int done)639 m32r_fill_insn (int done)
640 {
641   if (prev_seg != NULL)
642     {
643       segT seg = now_seg;
644       subsegT subseg = now_subseg;
645 
646       subseg_set (prev_seg, prev_subseg);
647 
648       fill_insn (0);
649 
650       subseg_set (seg, subseg);
651     }
652 
653   if (done && debug_sym_link)
654     {
655       expand_debug_syms (debug_sym_link, 1);
656       debug_sym_link = (sym_linkS *) 0;
657     }
658 
659   return 1;
660 }
661 
662 /* The default target format to use.  */
663 
664 const char *
m32r_target_format(void)665 m32r_target_format (void)
666 {
667 #ifdef TE_LINUX
668   if (target_big_endian)
669     return "elf32-m32r-linux";
670   else
671     return "elf32-m32rle-linux";
672 #else
673   if (target_big_endian)
674     return "elf32-m32r";
675   else
676     return "elf32-m32rle";
677 #endif
678 }
679 
680 void
md_begin(void)681 md_begin (void)
682 {
683   flagword applicable;
684   segT seg;
685   subsegT subseg;
686 
687   /* Initialize the `cgen' interface.  */
688 
689   /* Set the machine number and endian.  */
690   gas_cgen_cpu_desc = m32r_cgen_cpu_open (CGEN_CPU_OPEN_MACHS, 0,
691 					  CGEN_CPU_OPEN_ENDIAN,
692 					  (target_big_endian ?
693 					   CGEN_ENDIAN_BIG : CGEN_ENDIAN_LITTLE),
694 					  CGEN_CPU_OPEN_END);
695   m32r_cgen_init_asm (gas_cgen_cpu_desc);
696 
697   /* The operand instance table is used during optimization to determine
698      which insns can be executed in parallel.  It is also used to give
699      warnings regarding operand interference in parallel insns.  */
700   m32r_cgen_init_opinst_table (gas_cgen_cpu_desc);
701 
702   /* This is a callback from cgen to gas to parse operands.  */
703   cgen_set_parse_operand_fn (gas_cgen_cpu_desc, gas_cgen_parse_operand);
704 
705   /* Save the current subseg so we can restore it [it's the default one and
706      we don't want the initial section to be .sbss].  */
707   seg    = now_seg;
708   subseg = now_subseg;
709 
710   /* The sbss section is for local .scomm symbols.  */
711   sbss_section = subseg_new (".sbss", 0);
712   seg_info (sbss_section)->bss = 1;
713 
714   /* This is copied from perform_an_assembly_pass.  */
715   applicable = bfd_applicable_section_flags (stdoutput);
716   bfd_set_section_flags (sbss_section,
717 			 applicable & (SEC_ALLOC | SEC_SMALL_DATA));
718 
719   subseg_set (seg, subseg);
720 
721   /* We must construct a fake section similar to bfd_com_section
722      but with the name .scommon.  */
723   scom_section                = *bfd_com_section_ptr;
724   scom_section.name           = ".scommon";
725   scom_section.flags          = SEC_IS_COMMON | SEC_SMALL_DATA;
726   scom_section.output_section = & scom_section;
727   scom_section.symbol         = & scom_symbol;
728   scom_section.symbol_ptr_ptr = & scom_section.symbol;
729   scom_symbol                 = * bfd_com_section_ptr->symbol;
730   scom_symbol.name            = ".scommon";
731   scom_symbol.section         = & scom_section;
732 
733   allow_m32rx (enable_m32rx);
734 
735   gas_cgen_initialize_saved_fixups_array ();
736 }
737 
738 #define OPERAND_IS_COND_BIT(operand, indices, index) \
739   ((operand)->hw_type == HW_H_COND			\
740    || ((operand)->hw_type == HW_H_PSW)			\
741    || ((operand)->hw_type == HW_H_CR			\
742        && (indices [index] == 0 || indices [index] == 1)))
743 
744 /* Returns true if an output of instruction 'a' is referenced by an operand
745    of instruction 'b'.  If 'check_outputs' is true then b's outputs are
746    checked, otherwise its inputs are examined.  */
747 
748 static int
first_writes_to_seconds_operands(m32r_insn * a,m32r_insn * b,const int check_outputs)749 first_writes_to_seconds_operands (m32r_insn *a,
750 				  m32r_insn *b,
751 				  const int check_outputs)
752 {
753   const CGEN_OPINST *a_operands = CGEN_INSN_OPERANDS (a->insn);
754   const CGEN_OPINST *b_ops = CGEN_INSN_OPERANDS (b->insn);
755   int a_index;
756 
757   if (ignore_parallel_conflicts)
758     return 0;
759 
760   /* If at least one of the instructions takes no operands, then there is
761      nothing to check.  There really are instructions without operands,
762      eg 'nop'.  */
763   if (a_operands == NULL || b_ops == NULL)
764     return 0;
765 
766   /* Scan the operand list of 'a' looking for an output operand.  */
767   for (a_index = 0;
768        a_operands->type != CGEN_OPINST_END;
769        a_index ++, a_operands ++)
770     {
771       if (a_operands->type == CGEN_OPINST_OUTPUT)
772 	{
773 	  int b_index;
774 	  const CGEN_OPINST *b_operands = b_ops;
775 
776 	  /* Special Case:
777 	     The Condition bit 'C' is a shadow of the CBR register (control
778 	     register 1) and also a shadow of bit 31 of the program status
779 	     word (control register 0).  For now this is handled here, rather
780 	     than by cgen....  */
781 
782 	  if (OPERAND_IS_COND_BIT (a_operands, a->indices, a_index))
783 	    {
784 	      /* Scan operand list of 'b' looking for another reference to the
785 		 condition bit, which goes in the right direction.  */
786 	      for (b_index = 0;
787 		   b_operands->type != CGEN_OPINST_END;
788 		   b_index++, b_operands++)
789 		{
790 		  if ((b_operands->type
791 		       == (check_outputs
792 			   ? CGEN_OPINST_OUTPUT
793 			   : CGEN_OPINST_INPUT))
794 		      && OPERAND_IS_COND_BIT (b_operands, b->indices, b_index))
795 		    return 1;
796 		}
797 	    }
798 	  else
799 	    {
800 	      /* Scan operand list of 'b' looking for an operand that
801 		 references the same hardware element, and which goes in the
802 		 right direction.  */
803 	      for (b_index = 0;
804 		   b_operands->type != CGEN_OPINST_END;
805 		   b_index++, b_operands++)
806 		{
807 		  if ((b_operands->type
808 		       == (check_outputs
809 			   ? CGEN_OPINST_OUTPUT
810 			   : CGEN_OPINST_INPUT))
811 		      && (b_operands->hw_type == a_operands->hw_type)
812 		      && (a->indices[a_index] == b->indices[b_index]))
813 		    return 1;
814 		}
815 	    }
816 	}
817     }
818 
819   return 0;
820 }
821 
822 /* Returns true if the insn can (potentially) alter the program counter.  */
823 
824 static int
writes_to_pc(m32r_insn * a)825 writes_to_pc (m32r_insn *a)
826 {
827   if (CGEN_INSN_ATTR_VALUE (a->insn, CGEN_INSN_UNCOND_CTI)
828       || CGEN_INSN_ATTR_VALUE (a->insn, CGEN_INSN_COND_CTI))
829     return 1;
830   return 0;
831 }
832 
833 /* Return NULL if the two 16 bit insns can be executed in parallel.
834    Otherwise return a pointer to an error message explaining why not.  */
835 
836 static const char *
can_make_parallel(m32r_insn * a,m32r_insn * b)837 can_make_parallel (m32r_insn *a, m32r_insn *b)
838 {
839   PIPE_ATTR a_pipe;
840   PIPE_ATTR b_pipe;
841 
842   /* Make sure the instructions are the right length.  */
843   if (CGEN_FIELDS_BITSIZE (&a->fields) != 16
844       || CGEN_FIELDS_BITSIZE (&b->fields) != 16)
845     abort ();
846 
847   if (first_writes_to_seconds_operands (a, b, true))
848     return _("instructions write to the same destination register.");
849 
850   a_pipe = CGEN_INSN_ATTR_VALUE (a->insn, CGEN_INSN_PIPE);
851   b_pipe = CGEN_INSN_ATTR_VALUE (b->insn, CGEN_INSN_PIPE);
852 
853   /* Make sure that the instructions use the correct execution pipelines.  */
854   if (a_pipe == PIPE_NONE
855       || b_pipe == PIPE_NONE)
856     return _("Instructions do not use parallel execution pipelines.");
857 
858   /* Leave this test for last, since it is the only test that can
859      go away if the instructions are swapped, and we want to make
860      sure that any other errors are detected before this happens.  */
861   if (a_pipe == PIPE_S
862       || b_pipe == PIPE_O
863       || (b_pipe == PIPE_O_OS && (enable_m32rx != 2)))
864     return _("Instructions share the same execution pipeline");
865 
866   return NULL;
867 }
868 
869 /* Force the top bit of the second 16-bit insn to be set.  */
870 
871 static void
make_parallel(CGEN_INSN_BYTES_PTR buffer)872 make_parallel (CGEN_INSN_BYTES_PTR buffer)
873 {
874 #if CGEN_INT_INSN_P
875   *buffer |= 0x8000;
876 #else
877   buffer[CGEN_CPU_ENDIAN (gas_cgen_cpu_desc) == CGEN_ENDIAN_BIG ? 0 : 1]
878     |= 0x80;
879 #endif
880 }
881 
882 /* Same as make_parallel except buffer contains the bytes in target order.  */
883 
884 static void
target_make_parallel(char * buffer)885 target_make_parallel (char *buffer)
886 {
887   buffer[CGEN_CPU_ENDIAN (gas_cgen_cpu_desc) == CGEN_ENDIAN_BIG ? 0 : 1]
888     |= 0x80;
889 }
890 
891 /* Assemble two instructions with an explicit parallel operation (||) or
892    sequential operation (->).  */
893 
894 static void
assemble_two_insns(char * str1,char * str2,int parallel_p)895 assemble_two_insns (char *str1, char *str2, int parallel_p)
896 {
897   char *str3;
898   m32r_insn first;
899   m32r_insn second;
900   char *errmsg;
901   char save_str2 = *str2;
902 
903   /* Separate the two instructions.  */
904   *str2 = 0;
905 
906   /* Make sure the two insns begin on a 32 bit boundary.
907      This is also done for the serial case (foo -> bar), relaxing doesn't
908      affect insns written like this.
909      Note that we must always do this as we can't assume anything about
910      whether we're currently on a 32 bit boundary or not.  Relaxing may
911      change this.  */
912   fill_insn (0);
913 
914   first.debug_sym_link = debug_sym_link;
915   debug_sym_link = (sym_linkS *) 0;
916 
917   /* Parse the first instruction.  */
918   if (! (first.insn = m32r_cgen_assemble_insn
919 	 (gas_cgen_cpu_desc, str1, & first.fields, first.buffer, & errmsg)))
920     {
921       as_bad ("%s", errmsg);
922       return;
923     }
924 
925   /* Check it.  */
926   if (CGEN_FIELDS_BITSIZE (&first.fields) != 16)
927     {
928       /* xgettext:c-format  */
929       as_bad (_("not a 16 bit instruction '%s'"), str1);
930       return;
931     }
932 #ifdef E_M32R2_ARCH
933   else if ((enable_m32rx == 1)
934            /* FIXME: Need standard macro to perform this test.  */
935            && ((CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_MACH)
936                 & (1 << MACH_M32R2))
937                && !((CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_MACH)
938                     & (1 << MACH_M32RX)))))
939     {
940       /* xgettext:c-format  */
941       as_bad (_("instruction '%s' is for the M32R2 only"), str1);
942       return;
943     }
944   else if ((! enable_special
945             && CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL))
946            || (! enable_special_m32r
947                && CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL_M32R)))
948 #else
949   else if (! enable_special
950       && CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL))
951 #endif
952     {
953       /* xgettext:c-format  */
954       as_bad (_("unknown instruction '%s'"), str1);
955       return;
956     }
957   else if (! enable_m32rx
958 	   /* FIXME: Need standard macro to perform this test.  */
959 	   && (CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_MACH)
960 	       == (1 << MACH_M32RX)))
961     {
962       /* xgettext:c-format  */
963       as_bad (_("instruction '%s' is for the M32RX only"), str1);
964       return;
965     }
966 
967   /* Check to see if this is an allowable parallel insn.  */
968   if (parallel_p
969       && CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_PIPE) == PIPE_NONE)
970     {
971       /* xgettext:c-format  */
972       as_bad (_("instruction '%s' cannot be executed in parallel."), str1);
973       return;
974     }
975 
976   /* Restore the original assembly text, just in case it is needed.  */
977   *str2 = save_str2;
978 
979   /* Save the original string pointer.  */
980   str3 = str1;
981 
982   /* Advanced past the parsed string.  */
983   str1 = str2 + 2;
984 
985   /* Remember the entire string in case it is needed for error
986      messages.  */
987   str2 = str3;
988 
989   /* Convert the opcode to lower case.  */
990   {
991     char *s2 = str1;
992 
993     while (ISSPACE (*s2++))
994       continue;
995 
996     --s2;
997 
998     while (ISALNUM (*s2))
999       {
1000 	*s2 = TOLOWER (*s2);
1001 	s2++;
1002       }
1003   }
1004 
1005   /* Preserve any fixups that have been generated and reset the list
1006      to empty.  */
1007   gas_cgen_save_fixups (0);
1008 
1009   /* Get the indices of the operands of the instruction.  */
1010   /* FIXME: CGEN_FIELDS is already recorded, but relying on that fact
1011      doesn't seem right.  Perhaps allow passing fields like we do insn.  */
1012   /* FIXME: ALIAS insns do not have operands, so we use this function
1013      to find the equivalent insn and overwrite the value stored in our
1014      structure.  We still need the original insn, however, since this
1015      may have certain attributes that are not present in the unaliased
1016      version (eg relaxability).  When aliases behave differently this
1017      may have to change.  */
1018   first.orig_insn = first.insn;
1019   {
1020     CGEN_FIELDS tmp_fields;
1021     first.insn = cgen_lookup_get_insn_operands
1022       (gas_cgen_cpu_desc, NULL, INSN_VALUE (first.buffer), NULL, 16,
1023        first.indices, &tmp_fields);
1024   }
1025 
1026   if (first.insn == NULL)
1027     as_fatal (_("internal error: lookup/get operands failed"));
1028 
1029   second.debug_sym_link = NULL;
1030 
1031   /* Parse the second instruction.  */
1032   if (! (second.insn = m32r_cgen_assemble_insn
1033 	 (gas_cgen_cpu_desc, str1, & second.fields, second.buffer, & errmsg)))
1034     {
1035       as_bad ("%s", errmsg);
1036       return;
1037     }
1038 
1039   /* Check it.  */
1040   if (CGEN_FIELDS_BITSIZE (&second.fields) != 16)
1041     {
1042       /* xgettext:c-format  */
1043       as_bad (_("not a 16 bit instruction '%s'"), str1);
1044       return;
1045     }
1046 #ifdef E_M32R2_ARCH
1047   else if ((enable_m32rx == 1)
1048            /* FIXME: Need standard macro to perform this test.  */
1049            && ((CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_MACH)
1050                 & (1 << MACH_M32R2))
1051                && !((CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_MACH)
1052                     & (1 << MACH_M32RX)))))
1053     {
1054       /* xgettext:c-format  */
1055       as_bad (_("instruction '%s' is for the M32R2 only"), str1);
1056       return;
1057     }
1058   else if ((! enable_special
1059             && CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL))
1060            || (! enable_special_m32r
1061                && CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL_M32R)))
1062 #else
1063   else if (! enable_special
1064       && CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL))
1065 #endif
1066     {
1067       /* xgettext:c-format  */
1068       as_bad (_("unknown instruction '%s'"), str1);
1069       return;
1070     }
1071   else if (! enable_m32rx
1072       && CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
1073     {
1074       /* xgettext:c-format  */
1075       as_bad (_("instruction '%s' is for the M32RX only"), str1);
1076       return;
1077     }
1078 
1079   /* Check to see if this is an allowable parallel insn.  */
1080   if (parallel_p
1081       && CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_PIPE) == PIPE_NONE)
1082     {
1083       /* xgettext:c-format  */
1084       as_bad (_("instruction '%s' cannot be executed in parallel."), str1);
1085       return;
1086     }
1087 
1088   if (parallel_p && ! enable_m32rx)
1089     {
1090       if (CGEN_INSN_NUM (first.insn) != M32R_INSN_NOP
1091 	  && CGEN_INSN_NUM (second.insn) != M32R_INSN_NOP)
1092 	{
1093 	  /* xgettext:c-format  */
1094 	  as_bad (_("'%s': only the NOP instruction can be issued in parallel on the m32r"), str2);
1095 	  return;
1096 	}
1097     }
1098 
1099   /* Get the indices of the operands of the instruction.  */
1100   second.orig_insn = second.insn;
1101   {
1102     CGEN_FIELDS tmp_fields;
1103     second.insn = cgen_lookup_get_insn_operands
1104       (gas_cgen_cpu_desc, NULL, INSN_VALUE (second.buffer), NULL, 16,
1105        second.indices, &tmp_fields);
1106   }
1107 
1108   if (second.insn == NULL)
1109     as_fatal (_("internal error: lookup/get operands failed"));
1110 
1111   /* We assume that if the first instruction writes to a register that is
1112      read by the second instruction it is because the programmer intended
1113      this to happen, (after all they have explicitly requested that these
1114      two instructions be executed in parallel).  Although if the global
1115      variable warn_explicit_parallel_conflicts is true then we do generate
1116      a warning message.  Similarly we assume that parallel branch and jump
1117      instructions are deliberate and should not produce errors.  */
1118 
1119   if (parallel_p && warn_explicit_parallel_conflicts)
1120     {
1121       if (first_writes_to_seconds_operands (&first, &second, false))
1122 	/* xgettext:c-format  */
1123 	as_warn (_("%s: output of 1st instruction is the same as an input to 2nd instruction - is this intentional ?"), str2);
1124 
1125       if (first_writes_to_seconds_operands (&second, &first, false))
1126 	/* xgettext:c-format  */
1127 	as_warn (_("%s: output of 2nd instruction is the same as an input to 1st instruction - is this intentional ?"), str2);
1128     }
1129 
1130   if (!parallel_p
1131       || (errmsg = (char *) can_make_parallel (&first, &second)) == NULL)
1132     {
1133       /* Get the fixups for the first instruction.  */
1134       gas_cgen_swap_fixups (0);
1135 
1136       /* Write it out.  */
1137       expand_debug_syms (first.debug_sym_link, 1);
1138       gas_cgen_finish_insn (first.orig_insn, first.buffer,
1139 			    CGEN_FIELDS_BITSIZE (&first.fields), 0, NULL);
1140 
1141       /* Force the top bit of the second insn to be set.  */
1142       if (parallel_p)
1143 	make_parallel (second.buffer);
1144 
1145       /* Get its fixups.  */
1146       gas_cgen_restore_fixups (0);
1147 
1148       /* Write it out.  */
1149       expand_debug_syms (second.debug_sym_link, 1);
1150       gas_cgen_finish_insn (second.orig_insn, second.buffer,
1151 			    CGEN_FIELDS_BITSIZE (&second.fields), 0, NULL);
1152     }
1153   /* Try swapping the instructions to see if they work that way.  */
1154   else if (can_make_parallel (&second, &first) == NULL)
1155     {
1156       /* Write out the second instruction first.  */
1157       expand_debug_syms (second.debug_sym_link, 1);
1158       gas_cgen_finish_insn (second.orig_insn, second.buffer,
1159 			    CGEN_FIELDS_BITSIZE (&second.fields), 0, NULL);
1160 
1161       /* Force the top bit of the first instruction to be set.  */
1162       make_parallel (first.buffer);
1163 
1164       /* Get the fixups for the first instruction.  */
1165       gas_cgen_restore_fixups (0);
1166 
1167       /* Write out the first instruction.  */
1168       expand_debug_syms (first.debug_sym_link, 1);
1169       gas_cgen_finish_insn (first.orig_insn, first.buffer,
1170 			    CGEN_FIELDS_BITSIZE (&first.fields), 0, NULL);
1171     }
1172   else
1173     {
1174       as_bad ("'%s': %s", str2, errmsg);
1175       return;
1176     }
1177 
1178   if (CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL)
1179       || CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL))
1180     m32r_flags |= E_M32R_HAS_HIDDEN_INST;
1181   if (CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL_M32R)
1182       || CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL_M32R))
1183     m32r_flags |= E_M32R_HAS_BIT_INST;
1184   if (CGEN_INSN_ATTR_VALUE (first.insn, CGEN_INSN_SPECIAL_FLOAT)
1185       || CGEN_INSN_ATTR_VALUE (second.insn, CGEN_INSN_SPECIAL_FLOAT))
1186     m32r_flags |= E_M32R_HAS_FLOAT_INST;
1187 
1188   /* Set these so m32r_fill_insn can use them.  */
1189   prev_seg    = now_seg;
1190   prev_subseg = now_subseg;
1191 }
1192 
1193 void
md_assemble(char * str)1194 md_assemble (char *str)
1195 {
1196   m32r_insn insn;
1197   char *errmsg;
1198   char *str2 = NULL;
1199 
1200   /* Initialize GAS's cgen interface for a new instruction.  */
1201   gas_cgen_init_parse ();
1202 
1203   /* Look for a parallel instruction separator.  */
1204   if ((str2 = strstr (str, "||")) != NULL)
1205     {
1206       assemble_two_insns (str, str2, 1);
1207       m32r_flags |= E_M32R_HAS_PARALLEL;
1208       return;
1209     }
1210 
1211   /* Also look for a sequential instruction separator.  */
1212   if ((str2 = strstr (str, "->")) != NULL)
1213     {
1214       assemble_two_insns (str, str2, 0);
1215       return;
1216     }
1217 
1218   insn.debug_sym_link = debug_sym_link;
1219   debug_sym_link = (sym_linkS *) 0;
1220 
1221   insn.insn = m32r_cgen_assemble_insn
1222     (gas_cgen_cpu_desc, str, &insn.fields, insn.buffer, & errmsg);
1223 
1224   if (!insn.insn)
1225     {
1226       as_bad ("%s", errmsg);
1227       return;
1228     }
1229 
1230 #ifdef E_M32R2_ARCH
1231   if ((enable_m32rx == 1)
1232        /* FIXME: Need standard macro to perform this test.  */
1233       && ((CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_MACH)
1234            & (1 << MACH_M32R2))
1235           && !((CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_MACH)
1236                & (1 << MACH_M32RX)))))
1237     {
1238       /* xgettext:c-format  */
1239       as_bad (_("instruction '%s' is for the M32R2 only"), str);
1240       return;
1241     }
1242   else if ((! enable_special
1243        && CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL))
1244       || (! enable_special_m32r
1245           && CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL_M32R)))
1246 #else
1247   if (! enable_special
1248       && CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL))
1249 #endif
1250     {
1251       /* xgettext:c-format  */
1252       as_bad (_("unknown instruction '%s'"), str);
1253       return;
1254     }
1255   else if (! enable_m32rx
1256 	   && CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
1257     {
1258       /* xgettext:c-format  */
1259       as_bad (_("instruction '%s' is for the M32RX only"), str);
1260       return;
1261     }
1262 
1263   if (CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL))
1264     m32r_flags |= E_M32R_HAS_HIDDEN_INST;
1265   if (CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL_M32R))
1266     m32r_flags |= E_M32R_HAS_BIT_INST;
1267   if (CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SPECIAL_FLOAT))
1268     m32r_flags |= E_M32R_HAS_FLOAT_INST;
1269 
1270   if (CGEN_INSN_BITSIZE (insn.insn) == 32)
1271     {
1272       /* 32 bit insns must live on 32 bit boundaries.  */
1273       if (prev_insn.insn || seen_relaxable_p)
1274 	{
1275 	  /* ??? If calling fill_insn too many times turns us into a memory
1276 	     pig, can we call a fn to assemble a nop instead of
1277 	     !seen_relaxable_p?  */
1278 	  fill_insn (0);
1279 	}
1280 
1281       expand_debug_syms (insn.debug_sym_link, 2);
1282 
1283       /* Doesn't really matter what we pass for RELAX_P here.  */
1284       gas_cgen_finish_insn (insn.insn, insn.buffer,
1285 			    CGEN_FIELDS_BITSIZE (&insn.fields), 1, NULL);
1286     }
1287   else
1288     {
1289       int on_32bit_boundary_p;
1290       int swap = false;
1291 
1292       if (CGEN_INSN_BITSIZE (insn.insn) != 16)
1293 	abort ();
1294 
1295       insn.orig_insn = insn.insn;
1296 
1297       /* If the previous insn was relaxable, then it may be expanded
1298 	 to fill the current 16 bit slot.  Emit a NOP here to occupy
1299 	 this slot, so that we can start at optimizing at a 32 bit
1300 	 boundary.  */
1301       if (prev_insn.insn && seen_relaxable_p && optimize)
1302 	fill_insn (0);
1303 
1304       if (enable_m32rx)
1305 	{
1306 	  /* Get the indices of the operands of the instruction.
1307 	     FIXME: See assemble_parallel for notes on orig_insn.  */
1308 	  {
1309 	    CGEN_FIELDS tmp_fields;
1310 	    insn.insn = cgen_lookup_get_insn_operands
1311 	      (gas_cgen_cpu_desc, NULL, INSN_VALUE (insn.buffer), NULL,
1312 	       16, insn.indices, &tmp_fields);
1313 	  }
1314 
1315 	  if (insn.insn == NULL)
1316 	    as_fatal (_("internal error: lookup/get operands failed"));
1317 	}
1318 
1319       /* Compute whether we're on a 32 bit boundary or not.
1320 	 prev_insn.insn is NULL when we're on a 32 bit boundary.  */
1321       on_32bit_boundary_p = prev_insn.insn == NULL;
1322 
1323       /* Change a frag to, if each insn to swap is in a different frag.
1324          It must keep only one instruction in a frag.  */
1325       if (parallel() && on_32bit_boundary_p)
1326         {
1327           frag_wane (frag_now);
1328           frag_new (0);
1329         }
1330 
1331       /* Look to see if this instruction can be combined with the
1332 	 previous instruction to make one, parallel, 32 bit instruction.
1333 	 If the previous instruction (potentially) changed the flow of
1334 	 program control, then it cannot be combined with the current
1335 	 instruction.  If the current instruction is relaxable, then it
1336 	 might be replaced with a longer version, so we cannot combine it.
1337 	 Also if the output of the previous instruction is used as an
1338 	 input to the current instruction then it cannot be combined.
1339 	 Otherwise call can_make_parallel() with both orderings of the
1340 	 instructions to see if they can be combined.  */
1341       if (! on_32bit_boundary_p
1342 	  && parallel ()
1343 	  && CGEN_INSN_ATTR_VALUE (insn.orig_insn, CGEN_INSN_RELAXABLE) == 0
1344 	  && ! writes_to_pc (&prev_insn)
1345 	  && ! first_writes_to_seconds_operands (&prev_insn, &insn, false))
1346 	{
1347 	  if (can_make_parallel (&prev_insn, &insn) == NULL)
1348 	    make_parallel (insn.buffer);
1349 	  else if (can_make_parallel (&insn, &prev_insn) == NULL)
1350 	    swap = true;
1351 	}
1352 
1353       expand_debug_syms (insn.debug_sym_link, 1);
1354 
1355       {
1356 	int i;
1357 	finished_insnS fi;
1358 
1359 	/* Ensure each pair of 16 bit insns is in the same frag.  */
1360 	frag_grow (4);
1361 
1362 	gas_cgen_finish_insn (insn.orig_insn, insn.buffer,
1363 			      CGEN_FIELDS_BITSIZE (&insn.fields),
1364 			      1 /* relax_p  */, &fi);
1365 	insn.addr = fi.addr;
1366 	insn.frag = fi.frag;
1367 	insn.num_fixups = fi.num_fixups;
1368 	for (i = 0; i < fi.num_fixups; ++i)
1369 	  insn.fixups[i] = fi.fixups[i];
1370       }
1371 
1372       if (swap)
1373 	{
1374 	  int i, tmp;
1375 
1376 #define SWAP_BYTES(a,b) tmp = a; a = b; b = tmp
1377 
1378 	  /* Swap the two insns */
1379 	  SWAP_BYTES (prev_insn.addr[0], insn.addr[0]);
1380 	  SWAP_BYTES (prev_insn.addr[1], insn.addr[1]);
1381 
1382 	  target_make_parallel (insn.addr);
1383 
1384 	  /* Swap any relaxable frags recorded for the two insns.  */
1385 	  /* FIXME: Clarify.  relaxation precludes parallel insns */
1386 	  if (prev_insn.frag->fr_opcode == prev_insn.addr)
1387 	    prev_insn.frag->fr_opcode = insn.addr;
1388 	  else if (insn.frag->fr_opcode == insn.addr)
1389 	    insn.frag->fr_opcode = prev_insn.addr;
1390 
1391           /* Change a frag to, if each insn is in a different frag.
1392 	     It must keep only one instruction in a frag.  */
1393           if (prev_insn.frag != insn.frag)
1394             {
1395               for (i = 0; i < prev_insn.num_fixups; ++i)
1396                 prev_insn.fixups[i]->fx_frag = insn.frag;
1397               for (i = 0; i < insn.num_fixups; ++i)
1398                 insn.fixups[i]->fx_frag = prev_insn.frag;
1399             }
1400           else
1401 	    {
1402 	      /* Update the addresses in any fixups.
1403 		 Note that we don't have to handle the case where each insn is in
1404 		 a different frag as we ensure they're in the same frag above.  */
1405 	      for (i = 0; i < prev_insn.num_fixups; ++i)
1406 		prev_insn.fixups[i]->fx_where += 2;
1407 	      for (i = 0; i < insn.num_fixups; ++i)
1408 		insn.fixups[i]->fx_where -= 2;
1409 	    }
1410 	}
1411 
1412       /* Keep track of whether we've seen a pair of 16 bit insns.
1413 	 prev_insn.insn is NULL when we're on a 32 bit boundary.  */
1414       if (on_32bit_boundary_p)
1415 	prev_insn = insn;
1416       else
1417 	prev_insn.insn = NULL;
1418 
1419       /* If the insn needs the following one to be on a 32 bit boundary
1420 	 (e.g. subroutine calls), fill this insn's slot.  */
1421       if (on_32bit_boundary_p
1422 	  && CGEN_INSN_ATTR_VALUE (insn.orig_insn, CGEN_INSN_FILL_SLOT) != 0)
1423 	fill_insn (0);
1424 
1425       /* If this is a relaxable insn (can be replaced with a larger version)
1426 	 mark the fact so that we can emit an alignment directive for a
1427 	 following 32 bit insn if we see one.   */
1428       if (CGEN_INSN_ATTR_VALUE (insn.orig_insn, CGEN_INSN_RELAXABLE) != 0)
1429 	seen_relaxable_p = 1;
1430     }
1431 
1432   /* Set these so m32r_fill_insn can use them.  */
1433   prev_seg    = now_seg;
1434   prev_subseg = now_subseg;
1435 }
1436 
1437 /* The syntax in the manual says constants begin with '#'.
1438    We just ignore it.  */
1439 
1440 void
md_operand(expressionS * expressionP)1441 md_operand (expressionS *expressionP)
1442 {
1443   if (*input_line_pointer == '#')
1444     {
1445       input_line_pointer++;
1446       expression (expressionP);
1447     }
1448 }
1449 
1450 valueT
md_section_align(segT segment,valueT size)1451 md_section_align (segT segment, valueT size)
1452 {
1453   int align = bfd_section_alignment (segment);
1454 
1455   return ((size + (1 << align) - 1) & -(1 << align));
1456 }
1457 
1458 symbolS *
md_undefined_symbol(char * name ATTRIBUTE_UNUSED)1459 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
1460 {
1461   return 0;
1462 }
1463 
1464 /* .scomm pseudo-op handler.
1465 
1466    This is a new pseudo-op to handle putting objects in .scommon.
1467    By doing this the linker won't need to do any work,
1468    and more importantly it removes the implicit -G arg necessary to
1469    correctly link the object file.  */
1470 
1471 static void
m32r_scomm(int ignore ATTRIBUTE_UNUSED)1472 m32r_scomm (int ignore ATTRIBUTE_UNUSED)
1473 {
1474   char *name;
1475   char c;
1476   char *p;
1477   offsetT size;
1478   symbolS *symbolP;
1479   offsetT align;
1480   int align2;
1481 
1482   c = get_symbol_name (&name);
1483 
1484   /* Just after name is now '\0'.  */
1485   p = input_line_pointer;
1486   *p = c;
1487   SKIP_WHITESPACE_AFTER_NAME ();
1488   if (*input_line_pointer != ',')
1489     {
1490       as_bad (_("Expected comma after symbol-name: rest of line ignored."));
1491       ignore_rest_of_line ();
1492       return;
1493     }
1494 
1495   /* Skip ','.  */
1496   input_line_pointer++;
1497   if ((size = get_absolute_expression ()) < 0)
1498     {
1499       /* xgettext:c-format  */
1500       as_warn (_(".SCOMMon length (%ld.) <0! Ignored."), (long) size);
1501       ignore_rest_of_line ();
1502       return;
1503     }
1504 
1505   /* The third argument to .scomm is the alignment.  */
1506   if (*input_line_pointer != ',')
1507     align = 8;
1508   else
1509     {
1510       ++input_line_pointer;
1511       align = get_absolute_expression ();
1512       if (align <= 0)
1513 	{
1514 	  as_warn (_("ignoring bad alignment"));
1515 	  align = 8;
1516 	}
1517     }
1518 
1519   /* Convert to a power of 2 alignment.  */
1520   if (align)
1521     {
1522       for (align2 = 0; (align & 1) == 0; align >>= 1, ++align2)
1523 	continue;
1524       if (align != 1)
1525 	{
1526 	  as_bad (_("Common alignment not a power of 2"));
1527 	  ignore_rest_of_line ();
1528 	  return;
1529 	}
1530     }
1531   else
1532     align2 = 0;
1533 
1534   *p = 0;
1535   symbolP = symbol_find_or_make (name);
1536   *p = c;
1537 
1538   if (S_IS_DEFINED (symbolP))
1539     {
1540       /* xgettext:c-format  */
1541       as_bad (_("Ignoring attempt to re-define symbol `%s'."),
1542 	      S_GET_NAME (symbolP));
1543       ignore_rest_of_line ();
1544       return;
1545     }
1546 
1547   if (S_GET_VALUE (symbolP) && S_GET_VALUE (symbolP) != (valueT) size)
1548     {
1549       /* xgettext:c-format  */
1550       as_bad (_("Length of .scomm \"%s\" is already %ld. Not changed to %ld."),
1551 	      S_GET_NAME (symbolP),
1552 	      (long) S_GET_VALUE (symbolP),
1553 	      (long) size);
1554 
1555       ignore_rest_of_line ();
1556       return;
1557     }
1558 
1559   if (symbol_get_obj (symbolP)->local)
1560     {
1561       segT old_sec = now_seg;
1562       int old_subsec = now_subseg;
1563       char *pfrag;
1564 
1565       record_alignment (sbss_section, align2);
1566       subseg_set (sbss_section, 0);
1567 
1568       if (align2)
1569 	frag_align (align2, 0, 0);
1570 
1571       if (S_GET_SEGMENT (symbolP) == sbss_section)
1572 	symbol_get_frag (symbolP)->fr_symbol = 0;
1573 
1574       symbol_set_frag (symbolP, frag_now);
1575 
1576       pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP, size,
1577 			(char *) 0);
1578       *pfrag = 0;
1579       S_SET_SIZE (symbolP, size);
1580       S_SET_SEGMENT (symbolP, sbss_section);
1581       S_CLEAR_EXTERNAL (symbolP);
1582       subseg_set (old_sec, old_subsec);
1583     }
1584   else
1585     {
1586       S_SET_VALUE (symbolP, (valueT) size);
1587       S_SET_ALIGN (symbolP, align2);
1588       S_SET_EXTERNAL (symbolP);
1589       S_SET_SEGMENT (symbolP, &scom_section);
1590     }
1591 
1592   demand_empty_rest_of_line ();
1593 }
1594 
1595 /* The target specific pseudo-ops which we support.  */
1596 const pseudo_typeS md_pseudo_table[] =
1597 {
1598   { "word",	cons,		4 },
1599   { "fillinsn", fill_insn,	0 },
1600   { "scomm",	m32r_scomm,	0 },
1601   { "debugsym",	debug_sym,	0 },
1602   { "m32r",	allow_m32rx,	0 },
1603   { "m32rx",	allow_m32rx,	1 },
1604   { "m32r2",	allow_m32rx,	2 },
1605   { "little",   little,         1 },
1606   { "big",      little,         0 },
1607   { NULL, NULL, 0 }
1608 };
1609 
1610 /* Interface to relax_segment.  */
1611 
1612 /* FIXME: Build table by hand, get it working, then machine generate.  */
1613 
1614 const relax_typeS md_relax_table[] =
1615 {
1616 /* The fields are:
1617    1) most positive reach of this state,
1618    2) most negative reach of this state,
1619    3) how many bytes this mode will add to the size of the current frag
1620    4) which index into the table to try if we can't fit into this one.  */
1621 
1622   /* The first entry must be unused because an `rlx_more' value of zero ends
1623      each list.  */
1624   {1, 1, 0, 0},
1625 
1626   /* The displacement used by GAS is from the end of the 2 byte insn,
1627      so we subtract 2 from the following.  */
1628   /* 16 bit insn, 8 bit disp -> 10 bit range.
1629      This doesn't handle a branch in the right slot at the border:
1630      the "& -4" isn't taken into account.  It's not important enough to
1631      complicate things over it, so we subtract an extra 2 (or + 2 in -ve
1632      case).  */
1633   {511 - 2 - 2, -512 - 2 + 2, 0, 2 },
1634   /* 32 bit insn, 24 bit disp -> 26 bit range.  */
1635   {0x2000000 - 1 - 2, -0x2000000 - 2, 2, 0 },
1636   /* Same thing, but with leading nop for alignment.  */
1637   {0x2000000 - 1 - 2, -0x2000000 - 2, 4, 0 }
1638 };
1639 
1640 long
m32r_relax_frag(segT segment,fragS * fragP,long stretch)1641 m32r_relax_frag (segT segment, fragS *fragP, long stretch)
1642 {
1643   /* Address of branch insn.  */
1644   long address = fragP->fr_address + fragP->fr_fix - 2;
1645   long growth = 0;
1646 
1647   /* Keep 32 bit insns aligned on 32 bit boundaries.  */
1648   if (fragP->fr_subtype == 2)
1649     {
1650       if ((address & 3) != 0)
1651 	{
1652 	  fragP->fr_subtype = 3;
1653 	  growth = 2;
1654 	}
1655     }
1656   else if (fragP->fr_subtype == 3)
1657     {
1658       if ((address & 3) == 0)
1659 	{
1660 	  fragP->fr_subtype = 2;
1661 	  growth = -2;
1662 	}
1663     }
1664   else
1665     {
1666       growth = relax_frag (segment, fragP, stretch);
1667 
1668       /* Long jump on odd halfword boundary?  */
1669       if (fragP->fr_subtype == 2 && (address & 3) != 0)
1670 	{
1671 	  fragP->fr_subtype = 3;
1672 	  growth += 2;
1673 	}
1674     }
1675 
1676   return growth;
1677 }
1678 
1679 /* Return an initial guess of the length by which a fragment must grow to
1680    hold a branch to reach its destination.
1681    Also updates fr_type/fr_subtype as necessary.
1682 
1683    Called just before doing relaxation.
1684    Any symbol that is now undefined will not become defined.
1685    The guess for fr_var is ACTUALLY the growth beyond fr_fix.
1686    Whatever we do to grow fr_fix or fr_var contributes to our returned value.
1687    Although it may not be explicit in the frag, pretend fr_var starts
1688    with a 0 value.  */
1689 
1690 int
md_estimate_size_before_relax(fragS * fragP,segT segment)1691 md_estimate_size_before_relax (fragS *fragP, segT segment)
1692 {
1693   /* The only thing we have to handle here are symbols outside of the
1694      current segment.  They may be undefined or in a different segment in
1695      which case linker scripts may place them anywhere.
1696      However, we can't finish the fragment here and emit the reloc as insn
1697      alignment requirements may move the insn about.  */
1698   if (S_GET_SEGMENT (fragP->fr_symbol) != segment
1699       || S_IS_EXTERNAL (fragP->fr_symbol)
1700       || S_IS_WEAK (fragP->fr_symbol))
1701     {
1702       /* The symbol is undefined in this segment.
1703 	 Change the relaxation subtype to the max allowable and leave
1704 	 all further handling to md_convert_frag.  */
1705       fragP->fr_subtype = 2;
1706 
1707       {
1708 	const CGEN_INSN *insn;
1709 	int i;
1710 
1711 	/* Update the recorded insn.
1712 	   Fortunately we don't have to look very far.
1713 	   FIXME: Change this to record in the instruction the next higher
1714 	   relaxable insn to use.  */
1715 	for (i = 0, insn = fragP->fr_cgen.insn; i < 4; i++, insn++)
1716 	  {
1717 	    if ((strcmp (CGEN_INSN_MNEMONIC (insn),
1718 			 CGEN_INSN_MNEMONIC (fragP->fr_cgen.insn))
1719 		 == 0)
1720 		&& CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAXED))
1721 	      break;
1722 	  }
1723 	if (i == 4)
1724 	  abort ();
1725 
1726 	fragP->fr_cgen.insn = insn;
1727 	return 2;
1728       }
1729     }
1730 
1731   return md_relax_table[fragP->fr_subtype].rlx_length;
1732 }
1733 
1734 /* *FRAGP has been relaxed to its final size, and now needs to have
1735    the bytes inside it modified to conform to the new size.
1736 
1737    Called after relaxation is finished.
1738    fragP->fr_type == rs_machine_dependent.
1739    fragP->fr_subtype is the subtype of what the address relaxed to.  */
1740 
1741 void
md_convert_frag(bfd * abfd ATTRIBUTE_UNUSED,segT sec,fragS * fragP)1742 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED,
1743 		 segT sec,
1744 		 fragS *fragP)
1745 {
1746   char *opcode;
1747   char *displacement;
1748   int target_address;
1749   int opcode_address;
1750   int extension;
1751   int addend;
1752 
1753   opcode = fragP->fr_opcode;
1754 
1755   /* Address opcode resides at in file space.  */
1756   opcode_address = fragP->fr_address + fragP->fr_fix - 2;
1757 
1758   switch (fragP->fr_subtype)
1759     {
1760     case 1:
1761       extension = 0;
1762       displacement = &opcode[1];
1763       break;
1764     case 2:
1765       opcode[0] |= 0x80;
1766       extension = 2;
1767       displacement = &opcode[1];
1768       break;
1769     case 3:
1770       opcode[2] = opcode[0] | 0x80;
1771       md_number_to_chars (opcode, PAR_NOP_INSN, 2);
1772       opcode_address += 2;
1773       extension = 4;
1774       displacement = &opcode[3];
1775       break;
1776     default:
1777       abort ();
1778     }
1779 
1780   if (S_GET_SEGMENT (fragP->fr_symbol) != sec
1781       || S_IS_EXTERNAL (fragP->fr_symbol)
1782       || S_IS_WEAK (fragP->fr_symbol))
1783     {
1784       /* Symbol must be resolved by linker.  */
1785       if (fragP->fr_offset & 3)
1786 	as_warn (_("Addend to unresolved symbol not on word boundary."));
1787 #ifdef USE_M32R_OLD_RELOC
1788       addend = fragP->fr_offset >> 2; /* Old M32R used USE_REL. */
1789 #else
1790       addend = 0;
1791 #endif
1792     }
1793   else
1794     {
1795       /* Address we want to reach in file space.  */
1796       target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
1797       addend = (target_address - (opcode_address & -4)) >> 2;
1798     }
1799 
1800   /* Create a relocation for symbols that must be resolved by the linker.
1801      Otherwise output the completed insn.  */
1802 
1803   if (S_GET_SEGMENT (fragP->fr_symbol) != sec
1804       || S_IS_EXTERNAL (fragP->fr_symbol)
1805       || S_IS_WEAK (fragP->fr_symbol))
1806     {
1807       fixS *fixP;
1808 
1809       gas_assert (fragP->fr_subtype != 1);
1810       gas_assert (fragP->fr_cgen.insn != 0);
1811 
1812       fixP = gas_cgen_record_fixup (fragP,
1813 				    /* Offset of branch insn in frag.  */
1814 				    fragP->fr_fix + extension - 4,
1815 				    fragP->fr_cgen.insn,
1816 				    4 /* Length.  */,
1817 				    /* FIXME: quick hack.  */
1818 				    cgen_operand_lookup_by_num (gas_cgen_cpu_desc,
1819 								M32R_OPERAND_DISP24),
1820 				    fragP->fr_cgen.opinfo,
1821 				    fragP->fr_symbol, fragP->fr_offset);
1822       if (fragP->fr_cgen.opinfo)
1823         fixP->fx_r_type = fragP->fr_cgen.opinfo;
1824     }
1825 
1826 #define SIZE_FROM_RELAX_STATE(n) ((n) == 1 ? 1 : 3)
1827 
1828   md_number_to_chars (displacement, (valueT) addend,
1829 		      SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
1830 
1831   fragP->fr_fix += extension;
1832 }
1833 
1834 /* Functions concerning relocs.  */
1835 
1836 /* The location from which a PC relative jump should be calculated,
1837    given a PC relative reloc.  */
1838 
1839 long
md_pcrel_from_section(fixS * fixP,segT sec)1840 md_pcrel_from_section (fixS *fixP, segT sec)
1841 {
1842   if (fixP->fx_addsy != (symbolS *) NULL
1843       && (! S_IS_DEFINED (fixP->fx_addsy)
1844 	  || S_GET_SEGMENT (fixP->fx_addsy) != sec
1845           || S_IS_EXTERNAL (fixP->fx_addsy)
1846           || S_IS_WEAK (fixP->fx_addsy)))
1847     {
1848       if (S_GET_SEGMENT (fixP->fx_addsy) != sec
1849           && S_IS_DEFINED (fixP->fx_addsy)
1850           && ! S_IS_EXTERNAL (fixP->fx_addsy)
1851           && ! S_IS_WEAK (fixP->fx_addsy))
1852         return fixP->fx_offset;
1853 
1854       /* The symbol is undefined (or is defined but not in this section).
1855 	 Let the linker figure it out.  */
1856       return 0;
1857     }
1858 
1859   return (fixP->fx_frag->fr_address + fixP->fx_where) & -4L;
1860 }
1861 
1862 /* Return the bfd reloc type for OPERAND of INSN at fixup FIXP.
1863    Returns BFD_RELOC_NONE if no reloc type can be found.
1864    *FIXP may be modified if desired.  */
1865 
1866 bfd_reloc_code_real_type
md_cgen_lookup_reloc(const CGEN_INSN * insn ATTRIBUTE_UNUSED,const CGEN_OPERAND * operand,fixS * fixP)1867 md_cgen_lookup_reloc (const CGEN_INSN *insn ATTRIBUTE_UNUSED,
1868 		      const CGEN_OPERAND *operand,
1869 		      fixS *fixP)
1870 {
1871   switch (operand->type)
1872     {
1873     case M32R_OPERAND_DISP8:  return BFD_RELOC_M32R_10_PCREL;
1874     case M32R_OPERAND_DISP16: return BFD_RELOC_M32R_18_PCREL;
1875     case M32R_OPERAND_DISP24: return BFD_RELOC_M32R_26_PCREL;
1876     case M32R_OPERAND_UIMM24: return BFD_RELOC_M32R_24;
1877     case M32R_OPERAND_HI16:
1878     case M32R_OPERAND_SLO16:
1879     case M32R_OPERAND_ULO16:
1880       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1881       if (fixP->fx_cgen.opinfo != 0)
1882 	return fixP->fx_cgen.opinfo;
1883       break;
1884     default:
1885       /* Avoid -Wall warning.  */
1886       break;
1887     }
1888   return BFD_RELOC_NONE;
1889 }
1890 
1891 /* Record a HI16 reloc for later matching with its LO16 cousin.  */
1892 
1893 static void
m32r_record_hi16(int reloc_type,fixS * fixP,segT seg ATTRIBUTE_UNUSED)1894 m32r_record_hi16 (int reloc_type,
1895 		  fixS *fixP,
1896 		  segT seg ATTRIBUTE_UNUSED)
1897 {
1898   struct m32r_hi_fixup *hi_fixup;
1899 
1900   gas_assert (reloc_type == BFD_RELOC_M32R_HI16_SLO
1901 	  || reloc_type == BFD_RELOC_M32R_HI16_ULO);
1902 
1903   hi_fixup = XNEW (struct m32r_hi_fixup);
1904   hi_fixup->fixp = fixP;
1905   hi_fixup->seg  = now_seg;
1906   hi_fixup->next = m32r_hi_fixup_list;
1907 
1908   m32r_hi_fixup_list = hi_fixup;
1909 }
1910 
1911 /* Called while parsing an instruction to create a fixup.
1912    We need to check for HI16 relocs and queue them up for later sorting.  */
1913 
1914 fixS *
m32r_cgen_record_fixup_exp(fragS * frag,int where,const CGEN_INSN * insn,int length,const CGEN_OPERAND * operand,int opinfo,expressionS * exp)1915 m32r_cgen_record_fixup_exp (fragS *frag,
1916 			    int where,
1917 			    const CGEN_INSN *insn,
1918 			    int length,
1919 			    const CGEN_OPERAND *operand,
1920 			    int opinfo,
1921 			    expressionS *exp)
1922 {
1923   fixS *fixP;
1924   bfd_reloc_code_real_type r_type = BFD_RELOC_UNUSED;
1925 
1926   if (m32r_check_fixup (exp, &r_type))
1927     as_bad (_("Invalid PIC expression."));
1928 
1929   fixP = gas_cgen_record_fixup_exp (frag, where, insn, length,
1930 				    operand, opinfo, exp);
1931 
1932   switch (operand->type)
1933     {
1934     case M32R_OPERAND_HI16:
1935       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1936       if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_SLO
1937 	  || fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_ULO)
1938 	m32r_record_hi16 (fixP->fx_cgen.opinfo, fixP, now_seg);
1939       break;
1940 
1941     default:
1942       /* Avoid -Wall warning.  */
1943       break;
1944     }
1945 
1946   switch (r_type)
1947     {
1948     case BFD_RELOC_UNUSED:
1949     default:
1950       return fixP;
1951 
1952     case BFD_RELOC_M32R_GOTPC24:
1953       if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_SLO)
1954         r_type = BFD_RELOC_M32R_GOTPC_HI_SLO;
1955       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_ULO)
1956         r_type = BFD_RELOC_M32R_GOTPC_HI_ULO;
1957       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_LO16)
1958         r_type = BFD_RELOC_M32R_GOTPC_LO;
1959       break;
1960 
1961     case BFD_RELOC_M32R_GOT24:
1962       if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_SLO)
1963         r_type = BFD_RELOC_M32R_GOT16_HI_SLO;
1964       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_ULO)
1965         r_type = BFD_RELOC_M32R_GOT16_HI_ULO;
1966       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_LO16)
1967         r_type = BFD_RELOC_M32R_GOT16_LO;
1968       break;
1969 
1970     case BFD_RELOC_M32R_GOTOFF:
1971       if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_SLO)
1972         r_type = BFD_RELOC_M32R_GOTOFF_HI_SLO;
1973       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_HI16_ULO)
1974         r_type = BFD_RELOC_M32R_GOTOFF_HI_ULO;
1975       else if (fixP->fx_cgen.opinfo == BFD_RELOC_M32R_LO16)
1976         r_type = BFD_RELOC_M32R_GOTOFF_LO;
1977       break;
1978 
1979     case BFD_RELOC_M32R_26_PLTREL:
1980       as_bad (_("Invalid PIC expression."));
1981       break;
1982     }
1983 
1984   fixP->fx_r_type = r_type;
1985 
1986   return fixP;
1987 }
1988 
1989 /* Return BFD reloc type from opinfo field in a fixS.
1990    It's tricky using fx_r_type in m32r_frob_file because the values
1991    are BFD_RELOC_UNUSED + operand number.  */
1992 #define FX_OPINFO_R_TYPE(f) ((f)->fx_cgen.opinfo)
1993 
1994 /* Sort any unmatched HI16 relocs so that they immediately precede
1995    the corresponding LO16 reloc.  This is called before md_apply_fix and
1996    tc_gen_reloc.  */
1997 
1998 void
m32r_frob_file(void)1999 m32r_frob_file (void)
2000 {
2001   struct m32r_hi_fixup *l;
2002 
2003   for (l = m32r_hi_fixup_list; l != NULL; l = l->next)
2004     {
2005       segment_info_type *seginfo;
2006       int pass;
2007 
2008       gas_assert (FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_SLO
2009 	      || FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_ULO);
2010 
2011       /* Check quickly whether the next fixup happens to be a matching low.  */
2012       if (l->fixp->fx_next != NULL
2013 	  && FX_OPINFO_R_TYPE (l->fixp->fx_next) == BFD_RELOC_M32R_LO16
2014 	  && l->fixp->fx_addsy == l->fixp->fx_next->fx_addsy
2015 	  && l->fixp->fx_offset == l->fixp->fx_next->fx_offset)
2016 	continue;
2017 
2018       /* Look through the fixups for this segment for a matching `low'.
2019          When we find one, move the high/shigh just in front of it.  We do
2020          this in two passes.  In the first pass, we try to find a
2021          unique `low'.  In the second pass, we permit multiple high's
2022          relocs for a single `low'.  */
2023       seginfo = seg_info (l->seg);
2024       for (pass = 0; pass < 2; pass++)
2025 	{
2026 	  fixS *f;
2027 	  fixS *prev;
2028 
2029 	  prev = NULL;
2030 	  for (f = seginfo->fix_root; f != NULL; f = f->fx_next)
2031 	    {
2032 	      /* Check whether this is a `low' fixup which matches l->fixp.  */
2033 	      if (FX_OPINFO_R_TYPE (f) == BFD_RELOC_M32R_LO16
2034 		  && f->fx_addsy == l->fixp->fx_addsy
2035 		  && f->fx_offset == l->fixp->fx_offset
2036 		  && (pass == 1
2037 		      || prev == NULL
2038 		      || (FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_SLO
2039 			  && FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_ULO)
2040 		      || prev->fx_addsy != f->fx_addsy
2041 		      || prev->fx_offset != f->fx_offset))
2042 		{
2043 		  fixS **pf;
2044 
2045 		  /* Move l->fixp before f.  */
2046 		  for (pf = &seginfo->fix_root;
2047 		       *pf != l->fixp;
2048 		       pf = & (*pf)->fx_next)
2049 		    gas_assert (*pf != NULL);
2050 
2051 		  *pf = l->fixp->fx_next;
2052 
2053 		  l->fixp->fx_next = f;
2054 		  if (prev == NULL)
2055 		    seginfo->fix_root = l->fixp;
2056 		  else
2057 		    prev->fx_next = l->fixp;
2058 
2059 		  break;
2060 		}
2061 
2062 	      prev = f;
2063 	    }
2064 
2065 	  if (f != NULL)
2066 	    break;
2067 
2068 	  if (pass == 1
2069 	      && warn_unmatched_high)
2070 	    as_warn_where (l->fixp->fx_file, l->fixp->fx_line,
2071 			   _("Unmatched high/shigh reloc"));
2072 	}
2073     }
2074 }
2075 
2076 /* See whether we need to force a relocation into the output file.
2077    This is used to force out switch and PC relative relocations when
2078    relaxing.  */
2079 
2080 int
m32r_force_relocation(fixS * fix)2081 m32r_force_relocation (fixS *fix)
2082 {
2083   if (generic_force_reloc (fix))
2084     return 1;
2085 
2086   if (! m32r_relax)
2087     return 0;
2088 
2089   return fix->fx_pcrel;
2090 }
2091 
2092 /* Write a value out to the object file, using the appropriate endianness.  */
2093 
2094 void
md_number_to_chars(char * buf,valueT val,int n)2095 md_number_to_chars (char *buf, valueT val, int n)
2096 {
2097   if (target_big_endian)
2098     number_to_chars_bigendian (buf, val, n);
2099   else
2100     number_to_chars_littleendian (buf, val, n);
2101 }
2102 
2103 /* Turn a string in input_line_pointer into a floating point constant
2104    of type TYPE, and store the appropriate bytes in *LITP.  The number
2105    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
2106    returned, or NULL on OK.  */
2107 
2108 const char *
md_atof(int type,char * litP,int * sizeP)2109 md_atof (int type, char *litP, int *sizeP)
2110 {
2111   return ieee_md_atof (type, litP, sizeP, target_big_endian);
2112 }
2113 
2114 void
m32r_elf_section_change_hook(void)2115 m32r_elf_section_change_hook (void)
2116 {
2117   /* If we have reached the end of a section and we have just emitted a
2118      16 bit insn, then emit a nop to make sure that the section ends on
2119      a 32 bit boundary.  */
2120 
2121   if (prev_insn.insn || seen_relaxable_p)
2122     (void) m32r_fill_insn (0);
2123 }
2124 
2125 /* Return true if can adjust the reloc to be relative to its section
2126    (such as .data) instead of relative to some symbol.  */
2127 
2128 bool
m32r_fix_adjustable(fixS * fixP)2129 m32r_fix_adjustable (fixS *fixP)
2130 {
2131   bfd_reloc_code_real_type reloc_type;
2132 
2133   if ((int) fixP->fx_r_type >= (int) BFD_RELOC_UNUSED)
2134     {
2135       const CGEN_INSN *insn = NULL;
2136       int opindex = (int) fixP->fx_r_type - (int) BFD_RELOC_UNUSED;
2137       const CGEN_OPERAND *operand =
2138 	cgen_operand_lookup_by_num(gas_cgen_cpu_desc, opindex);
2139 
2140       reloc_type = md_cgen_lookup_reloc (insn, operand, fixP);
2141     }
2142   else
2143     reloc_type = fixP->fx_r_type;
2144 
2145   if (fixP->fx_addsy == NULL)
2146     return 1;
2147 
2148   /* Prevent all adjustments to global symbols.  */
2149   if (S_IS_EXTERNAL (fixP->fx_addsy))
2150     return 0;
2151   if (S_IS_WEAK (fixP->fx_addsy))
2152     return 0;
2153 
2154   if (pic_code
2155       && (reloc_type == BFD_RELOC_M32R_24
2156           || reloc_type == BFD_RELOC_M32R_26_PCREL
2157           || reloc_type == BFD_RELOC_M32R_HI16_SLO
2158           || reloc_type == BFD_RELOC_M32R_HI16_ULO
2159           || reloc_type == BFD_RELOC_M32R_LO16))
2160     return 0;
2161 
2162   if (reloc_type == BFD_RELOC_M32R_GOT24
2163       || reloc_type == BFD_RELOC_M32R_26_PLTREL
2164       || reloc_type == BFD_RELOC_M32R_GOTPC_HI_SLO
2165       || reloc_type == BFD_RELOC_M32R_GOTPC_HI_ULO
2166       || reloc_type == BFD_RELOC_M32R_GOTPC_LO
2167       || reloc_type == BFD_RELOC_M32R_GOT16_HI_SLO
2168       || reloc_type == BFD_RELOC_M32R_GOT16_HI_ULO
2169       || reloc_type == BFD_RELOC_M32R_GOT16_LO)
2170     return 0;
2171 
2172   /* We need the symbol name for the VTABLE entries.  */
2173   if (reloc_type == BFD_RELOC_VTABLE_INHERIT
2174       || reloc_type == BFD_RELOC_VTABLE_ENTRY)
2175     return 0;
2176 
2177   return 1;
2178 }
2179 
2180 void
m32r_elf_final_processing(void)2181 m32r_elf_final_processing (void)
2182 {
2183   if (use_parallel)
2184     m32r_flags |= E_M32R_HAS_PARALLEL;
2185   elf_elfheader (stdoutput)->e_flags |= m32r_flags;
2186 }
2187 
2188 /* Translate internal representation of relocation info to BFD target
2189    format. */
2190 
2191 arelent *
tc_gen_reloc(asection * section,fixS * fixP)2192 tc_gen_reloc (asection * section, fixS * fixP)
2193 {
2194   arelent * reloc;
2195   bfd_reloc_code_real_type code;
2196 
2197   reloc = XNEW (arelent);
2198 
2199   reloc->sym_ptr_ptr = XNEW (asymbol *);
2200   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
2201   reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
2202 
2203   if (fixP->fx_pcrel)
2204     {
2205       if (fixP->fx_r_type == BFD_RELOC_32)
2206         fixP->fx_r_type = BFD_RELOC_32_PCREL;
2207       else if (fixP->fx_r_type == BFD_RELOC_16)
2208 	{
2209           fixP->fx_r_type = BFD_RELOC_16_PCREL;
2210           bfd_set_error (bfd_error_bad_value);
2211 	}
2212     }
2213 
2214   code = fixP->fx_r_type;
2215   if (pic_code)
2216     {
2217 #ifdef DEBUG_PIC
2218 printf("%s",bfd_get_reloc_code_name(code));
2219 #endif
2220       switch (code)
2221         {
2222         case BFD_RELOC_M32R_26_PCREL:
2223             code = BFD_RELOC_M32R_26_PLTREL;
2224           break;
2225 
2226         case BFD_RELOC_M32R_24:
2227           if (fixP->fx_addsy != NULL
2228               && strcmp (S_GET_NAME (fixP->fx_addsy), GOT_NAME) == 0)
2229             code = BFD_RELOC_M32R_GOTPC24;
2230           else
2231             code = BFD_RELOC_M32R_GOT24;
2232           break;
2233 
2234         case BFD_RELOC_M32R_HI16_ULO:
2235           if (fixP->fx_addsy != NULL
2236               && strcmp (S_GET_NAME (fixP->fx_addsy), GOT_NAME) == 0)
2237             code = BFD_RELOC_M32R_GOTPC_HI_ULO;
2238           else
2239             code = BFD_RELOC_M32R_GOT16_HI_ULO;
2240           break;
2241 
2242         case BFD_RELOC_M32R_HI16_SLO:
2243           if (fixP->fx_addsy != NULL
2244               && strcmp (S_GET_NAME (fixP->fx_addsy), GOT_NAME) == 0)
2245             code = BFD_RELOC_M32R_GOTPC_HI_SLO;
2246           else
2247             code = BFD_RELOC_M32R_GOT16_HI_SLO;
2248           break;
2249 
2250         case BFD_RELOC_M32R_LO16:
2251           if (fixP->fx_addsy != NULL
2252               && strcmp (S_GET_NAME (fixP->fx_addsy), GOT_NAME) == 0)
2253             code = BFD_RELOC_M32R_GOTPC_LO;
2254           else
2255             code = BFD_RELOC_M32R_GOT16_LO;
2256           break;
2257 
2258         default:
2259           break;
2260         }
2261 #ifdef DEBUG_PIC
2262 printf(" => %s",bfd_get_reloc_code_name(code));
2263 #endif
2264     }
2265 
2266   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
2267 
2268 #ifdef DEBUG_PIC
2269 printf(" => %s\n",reloc->howto->name);
2270 #endif
2271 
2272  if (reloc->howto == (reloc_howto_type *) NULL)
2273     {
2274       as_bad_where (fixP->fx_file, fixP->fx_line,
2275             _("internal error: can't export reloc type %d (`%s')"),
2276             fixP->fx_r_type, bfd_get_reloc_code_name (code));
2277       return NULL;
2278     }
2279 
2280   /* Use fx_offset for these cases.  */
2281   if (   fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
2282       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2283       || fixP->fx_r_type == BFD_RELOC_32_PCREL)
2284     reloc->addend  = fixP->fx_offset;
2285   else if ((!pic_code
2286             && code != BFD_RELOC_M32R_26_PLTREL)
2287            && fixP->fx_pcrel
2288            && fixP->fx_addsy != NULL
2289            && (S_GET_SEGMENT(fixP->fx_addsy) != section)
2290            && S_IS_DEFINED (fixP->fx_addsy)
2291            && ! S_IS_EXTERNAL(fixP->fx_addsy)
2292            && ! S_IS_WEAK(fixP->fx_addsy))
2293     /* Already used fx_offset in the opcode field itself.  */
2294     reloc->addend  = fixP->fx_offset;
2295   else
2296     reloc->addend  = fixP->fx_addnumber;
2297 
2298   return reloc;
2299 }
2300 
2301 inline static char *
m32r_end_of_match(char * cont,const char * what)2302 m32r_end_of_match (char *cont, const char *what)
2303 {
2304   int len = strlen (what);
2305 
2306   if (strncasecmp (cont, what, strlen (what)) == 0
2307       && ! is_part_of_name (cont[len]))
2308     return cont + len;
2309 
2310   return NULL;
2311 }
2312 
2313 int
m32r_parse_name(char const * name,expressionS * exprP,enum expr_mode mode,char * nextcharP)2314 m32r_parse_name (char const *name,
2315 		 expressionS *exprP,
2316 		 enum expr_mode mode,
2317 		 char *nextcharP)
2318 {
2319   char *next = input_line_pointer;
2320   char *next_end;
2321   int reloc_type;
2322   operatorT op_type;
2323   segT segment;
2324 
2325   exprP->X_op_symbol = NULL;
2326   exprP->X_md = BFD_RELOC_UNUSED;
2327 
2328   if (strcmp (name, GOT_NAME) == 0)
2329     {
2330       if (! GOT_symbol)
2331 	GOT_symbol = symbol_find_or_make (name);
2332 
2333       exprP->X_add_symbol = GOT_symbol;
2334     no_suffix:
2335       /* If we have an absolute symbol or a
2336 	 reg, then we know its value now.  */
2337       segment = S_GET_SEGMENT (exprP->X_add_symbol);
2338       if (mode != expr_defer && segment == absolute_section)
2339 	{
2340 	  exprP->X_op = O_constant;
2341 	  exprP->X_add_number = S_GET_VALUE (exprP->X_add_symbol);
2342 	  exprP->X_add_symbol = NULL;
2343 	}
2344       else if (mode != expr_defer && segment == reg_section)
2345 	{
2346 	  exprP->X_op = O_register;
2347 	  exprP->X_add_number = S_GET_VALUE (exprP->X_add_symbol);
2348 	  exprP->X_add_symbol = NULL;
2349 	}
2350       else
2351 	{
2352 	  exprP->X_op = O_symbol;
2353 	  exprP->X_add_number = 0;
2354 	}
2355 
2356       return 1;
2357     }
2358 
2359   exprP->X_add_symbol = symbol_find_or_make (name);
2360 
2361   if (*nextcharP != '@')
2362     goto no_suffix;
2363   else if ((next_end = m32r_end_of_match (next + 1, "GOTOFF")))
2364     {
2365       reloc_type = BFD_RELOC_M32R_GOTOFF;
2366       op_type = O_PIC_reloc;
2367     }
2368   else if ((next_end = m32r_end_of_match (next + 1, "GOT")))
2369     {
2370       reloc_type = BFD_RELOC_M32R_GOT24;
2371       op_type = O_PIC_reloc;
2372     }
2373   else if ((next_end = m32r_end_of_match (next + 1, "PLT")))
2374     {
2375       reloc_type = BFD_RELOC_M32R_26_PLTREL;
2376       op_type = O_PIC_reloc;
2377     }
2378   else
2379     goto no_suffix;
2380 
2381   *input_line_pointer = *nextcharP;
2382   input_line_pointer = next_end;
2383   *nextcharP = *input_line_pointer;
2384   *input_line_pointer = '\0';
2385 
2386   exprP->X_op = op_type;
2387   exprP->X_add_number = 0;
2388   exprP->X_md = reloc_type;
2389 
2390   return 1;
2391 }
2392 
2393 int
m32r_cgen_parse_fix_exp(int opinfo,expressionS * exp)2394 m32r_cgen_parse_fix_exp(int opinfo, expressionS *exp)
2395 {
2396   if (exp->X_op == O_PIC_reloc
2397       && exp->X_md == BFD_RELOC_M32R_26_PLTREL)
2398     {
2399       exp->X_op = O_symbol;
2400       opinfo = exp->X_md;
2401     }
2402 
2403   return opinfo;
2404 }
2405