1 /* tc-cr16.c -- Assembler code for the CR16 CPU core.
2    Copyright (C) 2007-2021 Free Software Foundation, Inc.
3 
4    Contributed by M R Swami Reddy <MR.Swami.Reddy@nsc.com>
5 
6    This file is part of GAS, the GNU Assembler.
7 
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12 
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17 
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the
20    Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22 
23 #include "as.h"
24 #include "safe-ctype.h"
25 #include "dwarf2dbg.h"
26 #include "opcode/cr16.h"
27 #include "elf/cr16.h"
28 
29 #include <limits.h>
30 #ifndef CHAR_BIT
31 #define CHAR_BIT 8
32 #endif
33 
34 /* Word is considered here as a 16-bit unsigned short int.  */
35 #define WORD_SHIFT  16
36 
37 /* Register is 2-byte size.  */
38 #define REG_SIZE   2
39 
40 /* Maximum size of a single instruction (in words).  */
41 #define INSN_MAX_SIZE   3
42 
43 /* Maximum bits which may be set in a `mask16' operand.  */
44 #define MAX_REGS_IN_MASK16  8
45 
46 /* Assign a number NUM, shifted by SHIFT bytes, into a location
47    pointed by index BYTE of array 'output_opcode'.  */
48 #define CR16_PRINT(BYTE, NUM, SHIFT)   output_opcode[BYTE] |= (NUM) << (SHIFT)
49 
50 /* Operand errors.  */
51 typedef enum
52   {
53     OP_LEGAL = 0,       /* Legal operand.  */
54     OP_OUT_OF_RANGE,    /* Operand not within permitted range.  */
55     OP_NOT_EVEN         /* Operand is Odd number, should be even.  */
56   }
57 op_err;
58 
59 /* Opcode mnemonics hash table.  */
60 static htab_t cr16_inst_hash;
61 /* CR16 registers hash table.  */
62 static htab_t reg_hash;
63 /* CR16 register pair hash table.  */
64 static htab_t regp_hash;
65 /* CR16 processor registers hash table.  */
66 static htab_t preg_hash;
67 /* CR16 processor registers 32 bit hash table.  */
68 static htab_t pregp_hash;
69 /* Current instruction we're assembling.  */
70 const inst *instruction;
71 
72 
73 static int code_label = 0;
74 
75 /* Global variables.  */
76 
77 /* Array to hold an instruction encoding.  */
78 long output_opcode[2];
79 
80 /* Nonzero means a relocatable symbol.  */
81 int relocatable;
82 
83 /* A copy of the original instruction (used in error messages).  */
84 char ins_parse[MAX_INST_LEN];
85 
86 /* The current processed argument number.  */
87 int cur_arg_num;
88 
89 /* Generic assembler global variables which must be defined by all targets.  */
90 
91 /* Characters which always start a comment.  */
92 const char comment_chars[] = "#";
93 
94 /* Characters which start a comment at the beginning of a line.  */
95 const char line_comment_chars[] = "#";
96 
97 /* This array holds machine specific line separator characters.  */
98 const char line_separator_chars[] = ";";
99 
100 /* Chars that can be used to separate mant from exp in floating point nums.  */
101 const char EXP_CHARS[] = "eE";
102 
103 /* Chars that mean this number is a floating point constant as in 0f12.456  */
104 const char FLT_CHARS[] = "f'";
105 
106 #ifdef OBJ_ELF
107 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"  */
108 symbolS * GOT_symbol;
109 #endif
110 
111 /* Target-specific multicharacter options, not const-declared at usage.  */
112 const char *md_shortopts = "";
113 struct option md_longopts[] =
114 {
115   {NULL, no_argument, NULL, 0}
116 };
117 size_t md_longopts_size = sizeof (md_longopts);
118 
119 static void
l_cons(int nbytes)120 l_cons (int nbytes)
121 {
122   int c;
123   expressionS exp;
124 
125 #ifdef md_flush_pending_output
126   md_flush_pending_output ();
127 #endif
128 
129   if (is_it_end_of_statement ())
130     {
131       demand_empty_rest_of_line ();
132       return;
133     }
134 
135 #ifdef TC_ADDRESS_BYTES
136   if (nbytes == 0)
137     nbytes = TC_ADDRESS_BYTES ();
138 #endif
139 
140 #ifdef md_cons_align
141   md_cons_align (nbytes);
142 #endif
143 
144   c = 0;
145   do
146     {
147       unsigned int bits_available = BITS_PER_CHAR * nbytes;
148       char *hold = input_line_pointer;
149 
150       expression (&exp);
151 
152       if (*input_line_pointer == ':')
153 	{
154 	  /* Bitfields.  */
155 	  long value = 0;
156 
157 	  for (;;)
158 	    {
159 	      unsigned long width;
160 
161 	      if (*input_line_pointer != ':')
162 		{
163 		  input_line_pointer = hold;
164 		  break;
165 		}
166 	      if (exp.X_op == O_absent)
167 		{
168 		  as_warn (_("using a bit field width of zero"));
169 		  exp.X_add_number = 0;
170 		  exp.X_op = O_constant;
171 		}
172 
173 	      if (exp.X_op != O_constant)
174 		{
175 		  *input_line_pointer = '\0';
176 		  as_bad (_("field width \"%s\" too complex for a bitfield"),
177 			  hold);
178 		  *input_line_pointer = ':';
179 		  demand_empty_rest_of_line ();
180 		  return;
181 		}
182 
183 	      if ((width = exp.X_add_number) >
184 		  (unsigned int)(BITS_PER_CHAR * nbytes))
185 		{
186 		  as_warn (ngettext ("field width %lu too big to fit in %d"
187 				     " byte: truncated to %d bits",
188 				     "field width %lu too big to fit in %d"
189 				     " bytes: truncated to %d bits",
190 				     nbytes),
191 			   width, nbytes, (BITS_PER_CHAR * nbytes));
192 		  width = BITS_PER_CHAR * nbytes;
193 		}
194 
195 	      if (width > bits_available)
196 		{
197 		  /* FIXME-SOMEDAY: backing up and reparsing is wasteful.  */
198 		  input_line_pointer = hold;
199 		  exp.X_add_number = value;
200 		  break;
201 		}
202 
203 	      /* Skip ':'.  */
204 	      hold = ++input_line_pointer;
205 
206 	      expression (&exp);
207 	      if (exp.X_op != O_constant)
208 		{
209 		  char cache = *input_line_pointer;
210 
211 		  *input_line_pointer = '\0';
212 		  as_bad (_("field value \"%s\" too complex for a bitfield"),
213 			  hold);
214 		  *input_line_pointer = cache;
215 		  demand_empty_rest_of_line ();
216 		  return;
217 		}
218 
219 	      value |= ((~(-(1 << width)) & exp.X_add_number)
220 			<< ((BITS_PER_CHAR * nbytes) - bits_available));
221 
222 	      if ((bits_available -= width) == 0
223 		  || is_it_end_of_statement ()
224 		  || *input_line_pointer != ',')
225 		break;
226 
227 	      hold = ++input_line_pointer;
228 	      expression (&exp);
229 	    }
230 
231 	  exp.X_add_number = value;
232 	  exp.X_op = O_constant;
233 	  exp.X_unsigned = 1;
234 	}
235 
236       if ((*(input_line_pointer) == '@') && (*(input_line_pointer +1) == 'c'))
237 	code_label = 1;
238       emit_expr (&exp, (unsigned int) nbytes);
239       ++c;
240       if ((*(input_line_pointer) == '@') && (*(input_line_pointer +1) == 'c'))
241 	{
242 	  input_line_pointer +=3;
243 	  break;
244 	}
245     }
246   while ((*input_line_pointer++ == ','));
247 
248   /* Put terminator back into stream.  */
249   input_line_pointer--;
250 
251   demand_empty_rest_of_line ();
252 }
253 
254 /* This table describes all the machine specific pseudo-ops
255    the assembler has to support.  The fields are:
256    *** Pseudo-op name without dot.
257    *** Function to call to execute this pseudo-op.
258    *** Integer arg to pass to the function.  */
259 
260 const pseudo_typeS md_pseudo_table[] =
261 {
262   /* In CR16 machine, align is in bytes (not a ptwo boundary).  */
263   {"align", s_align_bytes, 0},
264   {"long", l_cons,  4 },
265   {"4byte", l_cons, 4 },
266   {0, 0, 0}
267 };
268 
269 /* CR16 relaxation table.  */
270 const relax_typeS md_relax_table[] =
271 {
272   /* bCC  */
273   {0x7f, -0x80, 2, 1},                  /*  8 */
274   {0xfffe, -0x10000, 4, 2},             /* 16 */
275   {0xfffffe, -0x1000000, 6, 0},         /* 24 */
276 };
277 
278 /* Return the bit size for a given operand.  */
279 
280 static int
get_opbits(operand_type op)281 get_opbits (operand_type op)
282 {
283   if (op < MAX_OPRD)
284     return cr16_optab[op].bit_size;
285 
286   return 0;
287 }
288 
289 /* Return the argument type of a given operand.  */
290 
291 static argtype
get_optype(operand_type op)292 get_optype (operand_type op)
293 {
294   if (op < MAX_OPRD)
295     return cr16_optab[op].arg_type;
296   else
297     return nullargs;
298 }
299 
300 /* Return the flags of a given operand.  */
301 
302 static int
get_opflags(operand_type op)303 get_opflags (operand_type op)
304 {
305   if (op < MAX_OPRD)
306     return cr16_optab[op].flags;
307 
308   return 0;
309 }
310 
311 /* Get the cc code.  */
312 
313 static int
get_cc(char * cc_name)314 get_cc (char *cc_name)
315 {
316    unsigned int i;
317 
318    for (i = 0; i < cr16_num_cc; i++)
319      if (strcmp (cc_name, cr16_b_cond_tab[i]) == 0)
320        return i;
321 
322    return -1;
323 }
324 
325 /* Get the core processor register 'reg_name'.  */
326 
327 static reg
get_register(char * reg_name)328 get_register (char *reg_name)
329 {
330   const reg_entry *rreg;
331 
332   rreg = (const reg_entry *) str_hash_find (reg_hash, reg_name);
333 
334   if (rreg != NULL)
335     return rreg->value.reg_val;
336 
337   return nullregister;
338 }
339 /* Get the core processor register-pair 'reg_name'.  */
340 
341 static reg
get_register_pair(char * reg_name)342 get_register_pair (char *reg_name)
343 {
344   const reg_entry *rreg;
345   char tmp_rp[16]="\0";
346 
347   /* Add '(' and ')' to the reg pair, if it's not present.  */
348   if (reg_name[0] != '(')
349     {
350       tmp_rp[0] = '(';
351       strcat (tmp_rp, reg_name);
352       strcat (tmp_rp,")");
353       rreg = (const reg_entry *) str_hash_find (regp_hash, tmp_rp);
354     }
355   else
356     rreg = (const reg_entry *) str_hash_find (regp_hash, reg_name);
357 
358   if (rreg != NULL)
359     return rreg->value.reg_val;
360 
361   return nullregister;
362 }
363 
364 /* Get the index register 'reg_name'.  */
365 
366 static reg
get_index_register(char * reg_name)367 get_index_register (char *reg_name)
368 {
369   const reg_entry *rreg;
370 
371   rreg = (const reg_entry *) str_hash_find (reg_hash, reg_name);
372 
373   if ((rreg != NULL)
374       && ((rreg->value.reg_val == 12) || (rreg->value.reg_val == 13)))
375     return rreg->value.reg_val;
376 
377   return nullregister;
378 }
379 /* Get the core processor index register-pair 'reg_name'.  */
380 
381 static reg
get_index_register_pair(char * reg_name)382 get_index_register_pair (char *reg_name)
383 {
384   const reg_entry *rreg;
385 
386   rreg = (const reg_entry *) str_hash_find (regp_hash, reg_name);
387 
388   if (rreg != NULL)
389     {
390       if ((rreg->value.reg_val != 1) || (rreg->value.reg_val != 7)
391 	  || (rreg->value.reg_val != 9) || (rreg->value.reg_val > 10))
392 	return rreg->value.reg_val;
393 
394       as_bad (_("Unknown register pair - index relative mode: `%d'"), rreg->value.reg_val);
395     }
396 
397   return nullregister;
398 }
399 
400 /* Get the processor register 'preg_name'.  */
401 
402 static preg
get_pregister(char * preg_name)403 get_pregister (char *preg_name)
404 {
405   const reg_entry *prreg;
406 
407   prreg = (const reg_entry *) str_hash_find (preg_hash, preg_name);
408 
409   if (prreg != NULL)
410     return prreg->value.preg_val;
411 
412   return nullpregister;
413 }
414 
415 /* Get the processor register 'preg_name 32 bit'.  */
416 
417 static preg
get_pregisterp(char * preg_name)418 get_pregisterp (char *preg_name)
419 {
420   const reg_entry *prreg;
421 
422   prreg = (const reg_entry *) str_hash_find (pregp_hash, preg_name);
423 
424   if (prreg != NULL)
425     return prreg->value.preg_val;
426 
427   return nullpregister;
428 }
429 
430 
431 /* Round up a section size to the appropriate boundary.  */
432 
433 valueT
md_section_align(segT seg,valueT val)434 md_section_align (segT seg, valueT val)
435 {
436   /* Round .text section to a multiple of 2.  */
437   if (seg == text_section)
438     return (val + 1) & ~1;
439   return val;
440 }
441 
442 /* Parse an operand that is machine-specific (remove '*').  */
443 
444 void
md_operand(expressionS * exp)445 md_operand (expressionS * exp)
446 {
447   char c = *input_line_pointer;
448 
449   switch (c)
450     {
451     case '*':
452       input_line_pointer++;
453       expression (exp);
454       break;
455     default:
456       break;
457     }
458 }
459 
460 /* Reset global variables before parsing a new instruction.  */
461 
462 static void
reset_vars(char * op)463 reset_vars (char *op)
464 {
465   cur_arg_num = relocatable = 0;
466   memset (& output_opcode, '\0', sizeof (output_opcode));
467 
468   /* Save a copy of the original OP (used in error messages).  */
469   strncpy (ins_parse, op, sizeof ins_parse - 1);
470   ins_parse [sizeof ins_parse - 1] = 0;
471 }
472 
473 /* This macro decides whether a particular reloc is an entry in a
474    switch table.  It is used when relaxing, because the linker needs
475    to know about all such entries so that it can adjust them if
476    necessary.  */
477 
478 #define SWITCH_TABLE(fix)						\
479   ((fix)->fx_addsy != NULL						\
480    && (fix)->fx_subsy != NULL						\
481    && ((fix)->fx_r_type == BFD_RELOC_CR16_NUM8				\
482        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM16			\
483        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM32			\
484        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM32a)			\
485    && S_GET_SEGMENT ((fix)->fx_addsy) != undefined_section		\
486    && S_GET_SEGMENT ((fix)->fx_addsy) == S_GET_SEGMENT ((fix)->fx_subsy))
487 
488 /* See whether we need to force a relocation into the output file.
489    This is used to force out switch and PC relative relocations when
490    relaxing.  */
491 
492 int
cr16_force_relocation(fixS * fix)493 cr16_force_relocation (fixS *fix)
494 {
495   if (generic_force_reloc (fix) || SWITCH_TABLE (fix))
496     return 1;
497 
498   return 0;
499 }
500 
501 /* Record a fixup for a cons expression.  */
502 
503 void
cr16_cons_fix_new(fragS * frag,int offset,int len,expressionS * exp,bfd_reloc_code_real_type rtype)504 cr16_cons_fix_new (fragS *frag, int offset, int len, expressionS *exp,
505 		   bfd_reloc_code_real_type rtype)
506 {
507   switch (len)
508     {
509     default: rtype = BFD_RELOC_NONE; break;
510     case 1: rtype = BFD_RELOC_CR16_NUM8 ; break;
511     case 2: rtype = BFD_RELOC_CR16_NUM16; break;
512     case 4:
513       if (code_label)
514 	{
515 	  rtype = BFD_RELOC_CR16_NUM32a;
516 	  code_label = 0;
517 	}
518       else
519 	rtype = BFD_RELOC_CR16_NUM32;
520       break;
521     }
522 
523   fix_new_exp (frag, offset, len, exp, 0, rtype);
524 }
525 
526 /* Generate a relocation entry for a fixup.  */
527 
528 arelent *
tc_gen_reloc(asection * section ATTRIBUTE_UNUSED,fixS * fixP)529 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS * fixP)
530 {
531   arelent * reloc;
532 
533   /* If symbols are local and resolved, then no relocation needed.  */
534   if ( ((fixP->fx_addsy)
535 	&& (S_GET_SEGMENT (fixP->fx_addsy) == absolute_section))
536        || ((fixP->fx_subsy)
537 	   && (S_GET_SEGMENT (fixP->fx_subsy) == absolute_section)))
538     return NULL;
539 
540   reloc = XNEW (arelent);
541   reloc->sym_ptr_ptr  = XNEW (asymbol *);
542   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
543   reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
544   reloc->addend = fixP->fx_offset;
545 
546   if (fixP->fx_subsy != NULL)
547     {
548       if (SWITCH_TABLE (fixP))
549 	{
550 	  /* Keep the current difference in the addend.  */
551 	  reloc->addend = (S_GET_VALUE (fixP->fx_addsy)
552 			   - S_GET_VALUE (fixP->fx_subsy) + fixP->fx_offset);
553 
554 	  switch (fixP->fx_r_type)
555 	    {
556 	    case BFD_RELOC_CR16_NUM8:
557 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH8;
558 	      break;
559 	    case BFD_RELOC_CR16_NUM16:
560 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH16;
561 	      break;
562 	    case BFD_RELOC_CR16_NUM32:
563 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH32;
564 	      break;
565 	    case BFD_RELOC_CR16_NUM32a:
566 	      fixP->fx_r_type = BFD_RELOC_CR16_NUM32a;
567 	      break;
568 	    default:
569 	      abort ();
570 	      break;
571 	    }
572 	}
573       else
574 	{
575 	  /* We only resolve difference expressions in the same section.  */
576 	  as_bad_where (fixP->fx_file, fixP->fx_line,
577 			_("can't resolve `%s' {%s section} - `%s' {%s section}"),
578 			fixP->fx_addsy ? S_GET_NAME (fixP->fx_addsy) : "0",
579 			segment_name (fixP->fx_addsy
580 				      ? S_GET_SEGMENT (fixP->fx_addsy)
581 				      : absolute_section),
582 			S_GET_NAME (fixP->fx_subsy),
583 			segment_name (S_GET_SEGMENT (fixP->fx_addsy)));
584 	}
585     }
586 #ifdef OBJ_ELF
587   if ((fixP->fx_r_type == BFD_RELOC_CR16_GOT_REGREL20)
588       && GOT_symbol
589       && fixP->fx_addsy == GOT_symbol)
590     {
591       reloc->addend = fixP->fx_offset = reloc->address;
592     }
593   else if ((fixP->fx_r_type == BFD_RELOC_CR16_GOTC_REGREL20)
594 	   && GOT_symbol
595 	   && fixP->fx_addsy == GOT_symbol)
596     {
597       reloc->addend = fixP->fx_offset = reloc->address;
598     }
599 #endif
600 
601   gas_assert ((int) fixP->fx_r_type > 0);
602   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
603 
604   if (reloc->howto == NULL)
605     {
606       as_bad_where (fixP->fx_file, fixP->fx_line,
607 		    _("internal error: reloc %d (`%s') not supported by object file format"),
608 		    fixP->fx_r_type,
609 		    bfd_get_reloc_code_name (fixP->fx_r_type));
610       return NULL;
611     }
612   gas_assert (!fixP->fx_pcrel == !reloc->howto->pc_relative);
613 
614   return reloc;
615 }
616 
617 /* Prepare machine-dependent frags for relaxation.  */
618 
619 int
md_estimate_size_before_relax(fragS * fragp,asection * seg)620 md_estimate_size_before_relax (fragS *fragp, asection *seg)
621 {
622   /* If symbol is undefined or located in a different section,
623      select the largest supported relocation.  */
624   relax_substateT subtype;
625   relax_substateT rlx_state[] = {0, 2};
626 
627   for (subtype = 0; subtype < ARRAY_SIZE (rlx_state); subtype += 2)
628     {
629       if (fragp->fr_subtype == rlx_state[subtype]
630 	  && (!S_IS_DEFINED (fragp->fr_symbol)
631 	      || seg != S_GET_SEGMENT (fragp->fr_symbol)))
632 	{
633 	  fragp->fr_subtype = rlx_state[subtype + 1];
634 	  break;
635 	}
636     }
637 
638   if (fragp->fr_subtype >= ARRAY_SIZE (md_relax_table))
639     abort ();
640 
641   return md_relax_table[fragp->fr_subtype].rlx_length;
642 }
643 
644 void
md_convert_frag(bfd * abfd ATTRIBUTE_UNUSED,asection * sec,fragS * fragP)645 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, fragS *fragP)
646 {
647   /* 'opcode' points to the start of the instruction, whether
648      we need to change the instruction's fixed encoding.  */
649   char *opcode = &fragP->fr_literal[0] + fragP->fr_fix;
650   bfd_reloc_code_real_type reloc;
651 
652   subseg_change (sec, 0);
653 
654   switch (fragP->fr_subtype)
655     {
656     case 0:
657       reloc = BFD_RELOC_CR16_DISP8;
658       break;
659     case 1:
660       /* If the subtype is not changed due to :m operand qualifier,
661 	 then no need to update the opcode value.  */
662       if ((int)opcode[1] != 0x18)
663 	{
664 	  opcode[0] = (opcode[0] & 0xf0);
665 	  opcode[1] = 0x18;
666 	}
667       reloc = BFD_RELOC_CR16_DISP16;
668       break;
669     case 2:
670       /* If the subtype is not changed due to :l operand qualifier,
671 	 then no need to update the opcode value.  */
672       if ((int)opcode[1] != 0)
673 	{
674 	  opcode[2] = opcode[0];
675 	  opcode[0] = opcode[1];
676 	  opcode[1] = 0x0;
677 	}
678       reloc = BFD_RELOC_CR16_DISP24;
679       break;
680     default:
681       abort();
682     }
683 
684   fix_new (fragP, fragP->fr_fix,
685 	   bfd_get_reloc_size (bfd_reloc_type_lookup (stdoutput, reloc)),
686 	   fragP->fr_symbol, fragP->fr_offset, 1, reloc);
687   fragP->fr_var = 0;
688   fragP->fr_fix += md_relax_table[fragP->fr_subtype].rlx_length;
689 }
690 
691 symbolS *
md_undefined_symbol(char * name)692 md_undefined_symbol (char *name)
693 {
694   if (*name == '_' && *(name + 1) == 'G'
695       && strcmp (name, "_GLOBAL_OFFSET_TABLE_") == 0)
696     {
697       if (!GOT_symbol)
698 	{
699 	  if (symbol_find (name))
700 	    as_bad (_("GOT already in symbol table"));
701 	  GOT_symbol = symbol_new (name, undefined_section,
702 				   &zero_address_frag, 0);
703 	}
704       return GOT_symbol;
705     }
706   return 0;
707 }
708 
709 /* Process machine-dependent command line options.  Called once for
710    each option on the command line that the machine-independent part of
711    GAS does not understand.  */
712 
713 int
md_parse_option(int c ATTRIBUTE_UNUSED,const char * arg ATTRIBUTE_UNUSED)714 md_parse_option (int c ATTRIBUTE_UNUSED, const char *arg ATTRIBUTE_UNUSED)
715 {
716   return 0;
717 }
718 
719 /* Machine-dependent usage-output.  */
720 
721 void
md_show_usage(FILE * stream ATTRIBUTE_UNUSED)722 md_show_usage (FILE *stream ATTRIBUTE_UNUSED)
723 {
724   return;
725 }
726 
727 const char *
md_atof(int type,char * litP,int * sizeP)728 md_atof (int type, char *litP, int *sizeP)
729 {
730   return ieee_md_atof (type, litP, sizeP, target_big_endian);
731 }
732 
733 /* Apply a fixS (fixup of an instruction or data that we didn't have
734    enough info to complete immediately) to the data in a frag.
735    Since linkrelax is nonzero and TC_LINKRELAX_FIXUP is defined to disable
736    relaxation of debug sections, this function is called only when
737    fixuping relocations of debug sections.  */
738 
739 void
md_apply_fix(fixS * fixP,valueT * valP,segT seg)740 md_apply_fix (fixS *fixP, valueT *valP, segT seg)
741 {
742   valueT val = * valP;
743 
744   if (fixP->fx_addsy == NULL
745       && fixP->fx_pcrel == 0)
746     fixP->fx_done = 1;
747   else if (fixP->fx_pcrel == 1
748       && fixP->fx_addsy != NULL
749       && S_GET_SEGMENT (fixP->fx_addsy) == seg)
750     fixP->fx_done = 1;
751   else
752     fixP->fx_done = 0;
753 
754   if (fixP->fx_addsy != NULL && !fixP->fx_pcrel)
755     {
756       val = fixP->fx_offset;
757       fixP->fx_done = 1;
758     }
759 
760   if (fixP->fx_done)
761     {
762       char *buf = fixP->fx_frag->fr_literal + fixP->fx_where;
763 
764       fixP->fx_offset = 0;
765 
766       switch (fixP->fx_r_type)
767 	{
768 	case BFD_RELOC_CR16_NUM8:
769 	  bfd_put_8 (stdoutput, (unsigned char) val, buf);
770 	  break;
771 	case BFD_RELOC_CR16_NUM16:
772 	  bfd_put_16 (stdoutput, val, buf);
773 	  break;
774 	case BFD_RELOC_CR16_NUM32:
775 	  bfd_put_32 (stdoutput, val, buf);
776 	  break;
777 	case BFD_RELOC_CR16_NUM32a:
778 	  bfd_put_32 (stdoutput, val, buf);
779 	  break;
780 	default:
781 	  /* We shouldn't ever get here because linkrelax is nonzero.  */
782 	  abort ();
783 	  break;
784 	}
785       fixP->fx_done = 0;
786     }
787   else
788     fixP->fx_offset = * valP;
789 }
790 
791 /* The location from which a PC relative jump should be calculated,
792    given a PC relative reloc.  */
793 
794 long
md_pcrel_from(fixS * fixp)795 md_pcrel_from (fixS *fixp)
796 {
797   return fixp->fx_frag->fr_address + fixp->fx_where;
798 }
799 
800 static void
initialise_reg_hash_table(htab_t * hash_table,const reg_entry * register_table,const unsigned int num_entries)801 initialise_reg_hash_table (htab_t *hash_table,
802 			   const reg_entry *register_table,
803 			   const unsigned int num_entries)
804 {
805   const reg_entry *rreg;
806 
807   *hash_table = str_htab_create ();
808 
809   for (rreg = register_table;
810        rreg < (register_table + num_entries);
811        rreg++)
812     if (str_hash_insert (*hash_table, rreg->name, rreg, 0) != NULL)
813       as_fatal (_("duplicate %s"), rreg->name);
814 }
815 
816 /* This function is called once, at assembler startup time.  This should
817    set up all the tables, etc that the MD part of the assembler needs.  */
818 
819 void
md_begin(void)820 md_begin (void)
821 {
822   int i = 0;
823 
824   /* Set up a hash table for the instructions.  */
825   cr16_inst_hash = str_htab_create ();
826 
827   while (cr16_instruction[i].mnemonic != NULL)
828     {
829       const char *mnemonic = cr16_instruction[i].mnemonic;
830 
831       if (str_hash_insert (cr16_inst_hash, mnemonic, cr16_instruction + i, 0))
832 	as_fatal (_("duplicate %s"), mnemonic);
833 
834       /* Insert unique names into hash table.  The CR16 instruction set
835 	 has many identical opcode names that have different opcodes based
836 	 on the operands.  This hash table then provides a quick index to
837 	 the first opcode with a particular name in the opcode table.  */
838       do
839 	{
840 	  ++i;
841 	}
842       while (cr16_instruction[i].mnemonic != NULL
843 	     && streq (cr16_instruction[i].mnemonic, mnemonic));
844     }
845 
846   /* Initialize reg_hash hash table.  */
847   initialise_reg_hash_table (& reg_hash, cr16_regtab, NUMREGS);
848   /* Initialize regp_hash hash table.  */
849   initialise_reg_hash_table (& regp_hash, cr16_regptab, NUMREGPS);
850   /* Initialize preg_hash hash table.  */
851   initialise_reg_hash_table (& preg_hash, cr16_pregtab, NUMPREGS);
852   /* Initialize pregp_hash hash table.  */
853   initialise_reg_hash_table (& pregp_hash, cr16_pregptab, NUMPREGPS);
854 
855   /*  Set linkrelax here to avoid fixups in most sections.  */
856   linkrelax = 1;
857 }
858 
859 /* Process constants (immediate/absolute)
860    and labels (jump targets/Memory locations).  */
861 
862 static void
process_label_constant(char * str,ins * cr16_ins)863 process_label_constant (char *str, ins * cr16_ins)
864 {
865   char *saved_input_line_pointer;
866   int symbol_with_at = 0;
867   int symbol_with_s = 0;
868   int symbol_with_m = 0;
869   int symbol_with_l = 0;
870   int symbol_with_at_got = 0;
871   int symbol_with_at_gotc = 0;
872   argument *cur_arg = cr16_ins->arg + cur_arg_num;  /* Current argument.  */
873 
874   saved_input_line_pointer = input_line_pointer;
875   input_line_pointer = str;
876 
877   expression (&cr16_ins->exp);
878 
879   switch (cr16_ins->exp.X_op)
880     {
881     case O_big:
882     case O_absent:
883       /* Missing or bad expr becomes absolute 0.  */
884       as_bad (_("missing or invalid displacement expression `%s' taken as 0"),
885 	      str);
886       cr16_ins->exp.X_op = O_constant;
887       cr16_ins->exp.X_add_number = 0;
888       cr16_ins->exp.X_add_symbol = NULL;
889       cr16_ins->exp.X_op_symbol = NULL;
890       /* Fall through.  */
891 
892     case O_constant:
893       cur_arg->X_op = O_constant;
894       cur_arg->constant = cr16_ins->exp.X_add_number;
895       break;
896 
897     case O_symbol:
898     case O_subtract:
899     case O_add:
900       cur_arg->X_op = O_symbol;
901       cur_arg->constant = cr16_ins->exp.X_add_number;
902       cr16_ins->exp.X_add_number = 0;
903       cr16_ins->rtype = BFD_RELOC_NONE;
904       relocatable = 1;
905 
906       if (startswith (input_line_pointer, "@c"))
907 	symbol_with_at = 1;
908 
909       if (startswith (input_line_pointer, "@l")
910 	  || startswith (input_line_pointer, ":l"))
911 	symbol_with_l = 1;
912 
913       if (startswith (input_line_pointer, "@m")
914 	  || startswith (input_line_pointer, ":m"))
915 	symbol_with_m = 1;
916 
917       if (startswith (input_line_pointer, "@s")
918 	  || startswith (input_line_pointer, ":s"))
919 	symbol_with_s = 1;
920 
921       if (startswith (input_line_pointer, "@cGOT")
922 	  || startswith (input_line_pointer, "@cgot"))
923 	{
924 	  if (GOT_symbol == NULL)
925 	    GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
926 
927 	  symbol_with_at_gotc = 1;
928 	}
929       else if (startswith (input_line_pointer, "@GOT")
930 	       || startswith (input_line_pointer, "@got"))
931 	{
932 	  if ((startswith (input_line_pointer, "+"))
933 	      || (startswith (input_line_pointer, "-")))
934 	    as_warn (_("GOT bad expression with %s."), input_line_pointer);
935 
936 	  if (GOT_symbol == NULL)
937 	    GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
938 
939 	  symbol_with_at_got = 1;
940 	}
941 
942       switch (cur_arg->type)
943 	{
944 	case arg_cr:
945 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
946 	    {
947 	      if (symbol_with_at_got)
948 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
949 	      else if (symbol_with_at_gotc)
950 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
951 	      else if (cur_arg->size == 20)
952 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
953 	      else
954 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20a;
955 	    }
956 	  break;
957 
958 	case arg_crp:
959 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
960 	    {
961 	      if (symbol_with_at_got)
962 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
963 	      else if (symbol_with_at_gotc)
964 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
965 	    } else {
966 	    switch (instruction->size)
967 	      {
968 	      case 1:
969 		switch (cur_arg->size)
970 		  {
971 		  case 0:
972 		    cr16_ins->rtype = BFD_RELOC_CR16_REGREL0;
973 		    break;
974 		  case 4:
975 		    if (IS_INSN_MNEMONIC ("loadb") || IS_INSN_MNEMONIC ("storb"))
976 		      cr16_ins->rtype = BFD_RELOC_CR16_REGREL4;
977 		    else
978 		      cr16_ins->rtype = BFD_RELOC_CR16_REGREL4a;
979 		    break;
980 		  default: break;
981 		  }
982 		break;
983 	      case 2:
984 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL16;
985 		break;
986 	      case 3:
987 		if (cur_arg->size == 20)
988 		  cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
989 		else
990 		  cr16_ins->rtype = BFD_RELOC_CR16_REGREL20a;
991 		break;
992 	      default:
993 		break;
994 	      }
995 	  }
996 	  break;
997 
998 	case arg_idxr:
999 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
1000 	    {
1001 	      if (symbol_with_at_got)
1002 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
1003 	      else if (symbol_with_at_gotc)
1004 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
1005 	      else
1006 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
1007 	    }
1008 	  break;
1009 
1010 	case arg_idxrp:
1011 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
1012 	    {
1013 	      if (symbol_with_at_got)
1014 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
1015 	      else if (symbol_with_at_gotc)
1016 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
1017 	      else {
1018 		switch (instruction->size)
1019 		  {
1020 		  case 1: cr16_ins->rtype = BFD_RELOC_CR16_REGREL0; break;
1021 		  case 2: cr16_ins->rtype = BFD_RELOC_CR16_REGREL14; break;
1022 		  case 3: cr16_ins->rtype = BFD_RELOC_CR16_REGREL20; break;
1023 		  default: break;
1024 		  }
1025 	      }
1026 	    }
1027 	  break;
1028 
1029 	case arg_c:
1030 	  if (IS_INSN_MNEMONIC ("bal"))
1031 	    cr16_ins->rtype = BFD_RELOC_CR16_DISP24;
1032 	  else if (IS_INSN_TYPE (BRANCH_INS))
1033 	    {
1034 	      if (symbol_with_l)
1035 		cr16_ins->rtype = BFD_RELOC_CR16_DISP24;
1036 	      else if (symbol_with_m)
1037 		cr16_ins->rtype = BFD_RELOC_CR16_DISP16;
1038 	      else
1039 		cr16_ins->rtype = BFD_RELOC_CR16_DISP8;
1040 	    }
1041 	  else if (IS_INSN_TYPE (STOR_IMM_INS) || IS_INSN_TYPE (LD_STOR_INS)
1042 		   || IS_INSN_TYPE (CSTBIT_INS))
1043 	    {
1044 	      if (symbol_with_s)
1045 		as_bad (_("operand %d: illegal use expression: `%s`"), cur_arg_num + 1, str);
1046 	      if (symbol_with_at_got)
1047 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
1048 	      else if (symbol_with_at_gotc)
1049 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
1050 	      else if (symbol_with_m)
1051 		cr16_ins->rtype = BFD_RELOC_CR16_ABS20;
1052 	      else /* Default to (symbol_with_l) */
1053 		cr16_ins->rtype = BFD_RELOC_CR16_ABS24;
1054 	    }
1055 	  else if (IS_INSN_TYPE (BRANCH_NEQ_INS))
1056 	    cr16_ins->rtype = BFD_RELOC_CR16_DISP4;
1057 	  break;
1058 
1059 	case arg_ic:
1060 	  if (IS_INSN_TYPE (ARITH_INS))
1061 	    {
1062 	      if (symbol_with_at_got)
1063 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
1064 	      else if (symbol_with_at_gotc)
1065 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
1066 	      else if (symbol_with_s)
1067 		cr16_ins->rtype = BFD_RELOC_CR16_IMM4;
1068 	      else if (symbol_with_m)
1069 		cr16_ins->rtype = BFD_RELOC_CR16_IMM20;
1070 	      else if (symbol_with_at)
1071 		cr16_ins->rtype = BFD_RELOC_CR16_IMM32a;
1072 	      else /* Default to (symbol_with_l) */
1073 		cr16_ins->rtype = BFD_RELOC_CR16_IMM32;
1074 	    }
1075 	  else if (IS_INSN_TYPE (ARITH_BYTE_INS))
1076 	    {
1077 	      cr16_ins->rtype = BFD_RELOC_CR16_IMM16;
1078 	    }
1079 	  break;
1080 	default:
1081 	  break;
1082 	}
1083       break;
1084 
1085     default:
1086       cur_arg->X_op = cr16_ins->exp.X_op;
1087       break;
1088     }
1089 
1090   input_line_pointer = saved_input_line_pointer;
1091   return;
1092 }
1093 
1094 /* Retrieve the opcode image of a given register.
1095    If the register is illegal for the current instruction,
1096    issue an error.  */
1097 
1098 static int
getreg_image(reg r)1099 getreg_image (reg r)
1100 {
1101   const reg_entry *rreg;
1102   char *reg_name;
1103   int is_procreg = 0; /* Nonzero means argument should be processor reg.  */
1104 
1105   /* Check whether the register is in registers table.  */
1106   if (r < MAX_REG)
1107     rreg = cr16_regtab + r;
1108   else /* Register not found.  */
1109     {
1110       as_bad (_("Unknown register: `%d'"), r);
1111       return 0;
1112     }
1113 
1114   reg_name = rreg->name;
1115 
1116   /* Issue a error message when register is illegal.  */
1117 #define IMAGE_ERR						\
1118   as_bad (_("Illegal register (`%s') in Instruction: `%s'"),	\
1119 	  reg_name, ins_parse);
1120 
1121   switch (rreg->type)
1122     {
1123     case CR16_R_REGTYPE:
1124       if (! is_procreg)
1125 	return rreg->image;
1126       else
1127 	IMAGE_ERR;
1128       break;
1129 
1130     case CR16_P_REGTYPE:
1131       return rreg->image;
1132       break;
1133 
1134     default:
1135       IMAGE_ERR;
1136       break;
1137     }
1138 
1139   return 0;
1140 }
1141 
1142 /* Parsing different types of operands
1143    -> constants             Immediate/Absolute/Relative numbers
1144    -> Labels                Relocatable symbols
1145    -> (reg pair base)       Register pair base
1146    -> (rbase)               Register base
1147    -> disp(rbase)           Register relative
1148    -> [rinx]disp(reg pair)  Register index with reg pair mode
1149    -> disp(rbase,ridx,scl)  Register index mode.  */
1150 
1151 static void
set_operand(char * operand,ins * cr16_ins)1152 set_operand (char *operand, ins * cr16_ins)
1153 {
1154   char *operandS; /* Pointer to start of sub-operand.  */
1155   char *operandE; /* Pointer to end of sub-operand.  */
1156 
1157   argument *cur_arg = &cr16_ins->arg[cur_arg_num]; /* Current argument.  */
1158 
1159   /* Initialize pointers.  */
1160   operandS = operandE = operand;
1161 
1162   switch (cur_arg->type)
1163     {
1164     case arg_ic:    /* Case $0x18.  */
1165       operandS++;
1166       /* Fall through.  */
1167     case arg_c:     /* Case 0x18.  */
1168       /* Set constant.  */
1169       process_label_constant (operandS, cr16_ins);
1170 
1171       if (cur_arg->type != arg_ic)
1172 	cur_arg->type = arg_c;
1173       break;
1174 
1175     case arg_icr:   /* Case $0x18(r1).  */
1176       operandS++;
1177     case arg_cr:    /* Case 0x18(r1).   */
1178       /* Set displacement constant.  */
1179       while (*operandE != '(')
1180 	operandE++;
1181       *operandE = '\0';
1182       process_label_constant (operandS, cr16_ins);
1183       operandS = operandE;
1184       /* Fall through.  */
1185     case arg_rbase: /* Case (r1) or (r1,r0).  */
1186       operandS++;
1187       /* Set register base.  */
1188       while (*operandE != ')')
1189 	operandE++;
1190       *operandE = '\0';
1191       if ((cur_arg->r = get_register (operandS)) == nullregister)
1192 	as_bad (_("Illegal register `%s' in Instruction `%s'"),
1193 		operandS, ins_parse);
1194 
1195       /* set the arg->rp, if reg is "r12" or "r13" or "14" or "15" */
1196       if ((cur_arg->type != arg_rbase)
1197 	  && ((getreg_image (cur_arg->r) == 12)
1198 	      || (getreg_image (cur_arg->r) == 13)
1199 	      || (getreg_image (cur_arg->r) == 14)
1200 	      || (getreg_image (cur_arg->r) == 15)))
1201 	{
1202 	  cur_arg->type = arg_crp;
1203 	  cur_arg->rp = cur_arg->r;
1204 	}
1205       break;
1206 
1207     case arg_crp:    /* Case 0x18(r1,r0).   */
1208       /* Set displacement constant.  */
1209       while (*operandE != '(')
1210 	operandE++;
1211       *operandE = '\0';
1212       process_label_constant (operandS, cr16_ins);
1213       operandS = operandE;
1214       operandS++;
1215       /* Set register pair base.  */
1216       while (*operandE != ')')
1217 	operandE++;
1218       *operandE = '\0';
1219       if ((cur_arg->rp = get_register_pair (operandS)) == nullregister)
1220 	as_bad (_("Illegal register pair `%s' in Instruction `%s'"),
1221 		operandS, ins_parse);
1222       break;
1223 
1224     case arg_idxr:
1225       /* Set register pair base.  */
1226       if ((strchr (operandS,'(') != NULL))
1227 	{
1228 	  while ((*operandE != '(') && (! ISSPACE (*operandE)))
1229 	    operandE++;
1230 	  if ((cur_arg->rp = get_index_register_pair (operandE)) == nullregister)
1231 	    as_bad (_("Illegal register pair `%s' in Instruction `%s'"),
1232 		    operandS, ins_parse);
1233 	  *operandE++ = '\0';
1234 	  cur_arg->type = arg_idxrp;
1235 	}
1236       else
1237 	cur_arg->rp = -1;
1238 
1239       operandE = operandS;
1240       /* Set displacement constant.  */
1241       while (*operandE != ']')
1242 	operandE++;
1243       process_label_constant (++operandE, cr16_ins);
1244       *operandE++ = '\0';
1245       operandE = operandS;
1246 
1247       /* Set index register .  */
1248       operandS = strchr (operandE,'[');
1249       if (operandS != NULL)
1250 	{ /* Eliminate '[', detach from rest of operand.  */
1251 	  *operandS++ = '\0';
1252 
1253 	  operandE = strchr (operandS, ']');
1254 
1255 	  if (operandE == NULL)
1256 	    as_bad (_("unmatched '['"));
1257 	  else
1258 	    { /* Eliminate ']' and make sure it was the last thing
1259 		 in the string.  */
1260 	      *operandE = '\0';
1261 	      if (*(operandE + 1) != '\0')
1262 		as_bad (_("garbage after index spec ignored"));
1263 	    }
1264 	}
1265 
1266       if ((cur_arg->i_r = get_index_register (operandS)) == nullregister)
1267 	as_bad (_("Illegal register `%s' in Instruction `%s'"),
1268 		operandS, ins_parse);
1269       *operandE = '\0';
1270       *operandS = '\0';
1271       break;
1272 
1273     default:
1274       break;
1275     }
1276 }
1277 
1278 /* Parse a single operand.
1279    operand - Current operand to parse.
1280    cr16_ins - Current assembled instruction.  */
1281 
1282 static void
parse_operand(char * operand,ins * cr16_ins)1283 parse_operand (char *operand, ins * cr16_ins)
1284 {
1285   int ret_val;
1286   argument *cur_arg = cr16_ins->arg + cur_arg_num; /* Current argument.  */
1287 
1288   /* Initialize the type to NULL before parsing.  */
1289   cur_arg->type = nullargs;
1290 
1291   /* Check whether this is a condition code .  */
1292   if ((IS_INSN_MNEMONIC ("b")) && ((ret_val = get_cc (operand)) != -1))
1293     {
1294       cur_arg->type = arg_cc;
1295       cur_arg->cc = ret_val;
1296       cur_arg->X_op = O_register;
1297       return;
1298     }
1299 
1300   /* Check whether this is a general processor register.  */
1301   if ((ret_val = get_register (operand)) != nullregister)
1302     {
1303       cur_arg->type = arg_r;
1304       cur_arg->r = ret_val;
1305       cur_arg->X_op = 0;
1306       return;
1307     }
1308 
1309   /* Check whether this is a general processor register pair.  */
1310   if ((operand[0] == '(')
1311       && ((ret_val = get_register_pair (operand)) != nullregister))
1312     {
1313       cur_arg->type = arg_rp;
1314       cur_arg->rp = ret_val;
1315       cur_arg->X_op = O_register;
1316       return;
1317     }
1318 
1319   /* Check whether the operand is a processor register.
1320      For "lprd" and "sprd" instruction, only 32 bit
1321      processor registers used.  */
1322   if (!(IS_INSN_MNEMONIC ("lprd") || (IS_INSN_MNEMONIC ("sprd")))
1323       && ((ret_val = get_pregister (operand)) != nullpregister))
1324     {
1325       cur_arg->type = arg_pr;
1326       cur_arg->pr = ret_val;
1327       cur_arg->X_op = O_register;
1328       return;
1329     }
1330 
1331   /* Check whether this is a processor register - 32 bit.  */
1332   if ((ret_val = get_pregisterp (operand)) != nullpregister)
1333     {
1334       cur_arg->type = arg_prp;
1335       cur_arg->prp = ret_val;
1336       cur_arg->X_op = O_register;
1337       return;
1338     }
1339 
1340   /* Deal with special characters.  */
1341   switch (operand[0])
1342     {
1343     case '$':
1344       if (strchr (operand, '(') != NULL)
1345 	cur_arg->type = arg_icr;
1346       else
1347 	cur_arg->type = arg_ic;
1348       goto set_params;
1349       break;
1350 
1351     case '(':
1352       cur_arg->type = arg_rbase;
1353       goto set_params;
1354       break;
1355 
1356     case '[':
1357       cur_arg->type = arg_idxr;
1358       goto set_params;
1359       break;
1360 
1361     default:
1362       break;
1363     }
1364 
1365   if (strchr (operand, '(') != NULL)
1366     {
1367       if (strchr (operand, ',') != NULL
1368 	  && (strchr (operand, ',') > strchr (operand, '(')))
1369 	cur_arg->type = arg_crp;
1370       else
1371 	cur_arg->type = arg_cr;
1372     }
1373   else
1374     cur_arg->type = arg_c;
1375 
1376   /* Parse an operand according to its type.  */
1377  set_params:
1378   cur_arg->constant = 0;
1379   set_operand (operand, cr16_ins);
1380 }
1381 
1382 /* Parse the various operands. Each operand is then analyzed to fillup
1383    the fields in the cr16_ins data structure.  */
1384 
1385 static void
parse_operands(ins * cr16_ins,char * operands)1386 parse_operands (ins * cr16_ins, char *operands)
1387 {
1388   char *operandS;            /* Operands string.  */
1389   char *operandH, *operandT; /* Single operand head/tail pointers.  */
1390   int allocated = 0;         /* Indicates a new operands string was allocated.*/
1391   char *operand[MAX_OPERANDS];/* Separating the operands.  */
1392   int op_num = 0;             /* Current operand number we are parsing.  */
1393   int bracket_flag = 0;       /* Indicates a bracket '(' was found.  */
1394   int sq_bracket_flag = 0;    /* Indicates a square bracket '[' was found.  */
1395 
1396   /* Preprocess the list of registers, if necessary.  */
1397   operandS = operandH = operandT = operands;
1398 
1399   while (*operandT != '\0')
1400     {
1401       if (*operandT == ',' && bracket_flag != 1 && sq_bracket_flag != 1)
1402 	{
1403 	  *operandT++ = '\0';
1404 	  operand[op_num++] = strdup (operandH);
1405 	  operandH = operandT;
1406 	  continue;
1407 	}
1408 
1409       if (*operandT == ' ')
1410 	as_bad (_("Illegal operands (whitespace): `%s'"), ins_parse);
1411 
1412       if (*operandT == '(')
1413 	bracket_flag = 1;
1414       else if (*operandT == '[')
1415 	sq_bracket_flag = 1;
1416 
1417       if (*operandT == ')')
1418 	{
1419 	  if (bracket_flag)
1420 	    bracket_flag = 0;
1421 	  else
1422 	    as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
1423 	}
1424       else if (*operandT == ']')
1425 	{
1426 	  if (sq_bracket_flag)
1427 	    sq_bracket_flag = 0;
1428 	  else
1429 	    as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
1430 	}
1431 
1432       if (bracket_flag == 1 && *operandT == ')')
1433 	bracket_flag = 0;
1434       else if (sq_bracket_flag == 1 && *operandT == ']')
1435 	sq_bracket_flag = 0;
1436 
1437       operandT++;
1438     }
1439 
1440   /* Adding the last operand.  */
1441   operand[op_num++] = strdup (operandH);
1442   cr16_ins->nargs = op_num;
1443 
1444   /* Verifying correct syntax of operands (all brackets should be closed).  */
1445   if (bracket_flag || sq_bracket_flag)
1446     as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
1447 
1448   /* Now we parse each operand separately.  */
1449   for (op_num = 0; op_num < cr16_ins->nargs; op_num++)
1450     {
1451       cur_arg_num = op_num;
1452       parse_operand (operand[op_num], cr16_ins);
1453       free (operand[op_num]);
1454     }
1455 
1456   if (allocated)
1457     free (operandS);
1458 }
1459 
1460 /* Get the trap index in dispatch table, given its name.
1461    This routine is used by assembling the 'excp' instruction.  */
1462 
1463 static int
gettrap(char * s)1464 gettrap (char *s)
1465 {
1466   const trap_entry *trap;
1467 
1468   for (trap = cr16_traps; trap < (cr16_traps + NUMTRAPS); trap++)
1469     if (strcasecmp (trap->name, s) == 0)
1470       return trap->entry;
1471 
1472   /* To make compatible with CR16 4.1 tools, the below 3-lines of
1473    * code added. Refer: Development Tracker item #123 */
1474   for (trap = cr16_traps; trap < (cr16_traps + NUMTRAPS); trap++)
1475     if (trap->entry  == (unsigned int) atoi (s))
1476       return trap->entry;
1477 
1478   as_bad (_("Unknown exception: `%s'"), s);
1479   return 0;
1480 }
1481 
1482 /* Top level module where instruction parsing starts.
1483    cr16_ins - data structure holds some information.
1484    operands - holds the operands part of the whole instruction.  */
1485 
1486 static void
parse_insn(ins * insn,char * operands)1487 parse_insn (ins *insn, char *operands)
1488 {
1489   int i;
1490 
1491   /* Handle instructions with no operands.  */
1492   for (i = 0; cr16_no_op_insn[i] != NULL; i++)
1493   {
1494     if (streq (cr16_no_op_insn[i], instruction->mnemonic))
1495     {
1496       insn->nargs = 0;
1497       return;
1498     }
1499   }
1500 
1501   /* Handle 'excp' instructions.  */
1502   if (IS_INSN_MNEMONIC ("excp"))
1503     {
1504       insn->nargs = 1;
1505       insn->arg[0].type = arg_ic;
1506       insn->arg[0].constant = gettrap (operands);
1507       insn->arg[0].X_op = O_constant;
1508       return;
1509     }
1510 
1511   if (operands != NULL)
1512     parse_operands (insn, operands);
1513 }
1514 
1515 /* bCC instruction requires special handling.  */
1516 static char *
get_b_cc(char * op)1517 get_b_cc (char * op)
1518 {
1519   unsigned int i;
1520 
1521   if (op[1] == 0 || (op[2] != 0 && op[3] != 0))
1522     return NULL;
1523 
1524   for (i = 0; i < cr16_num_cc ; i++)
1525     if (streq (op + 1, cr16_b_cond_tab[i]))
1526       return (char *) cr16_b_cond_tab[i];
1527 
1528    return NULL;
1529 }
1530 
1531 /* bCC instruction requires special handling.  */
1532 static int
is_bcc_insn(char * op)1533 is_bcc_insn (char * op)
1534 {
1535   if (!(streq (op, "bal") || streq (op, "beq0b") || streq (op, "bnq0b")
1536 	|| streq (op, "beq0w") || streq (op, "bnq0w")))
1537     if ((op[0] == 'b') && (get_b_cc (op) != NULL))
1538       return 1;
1539   return 0;
1540 }
1541 
1542 /* Cinv instruction requires special handling.  */
1543 
1544 static void
check_cinv_options(char * operand)1545 check_cinv_options (char * operand)
1546 {
1547   char *p = operand;
1548 
1549   while (*++p != ']')
1550     {
1551       switch (*p)
1552 	{
1553 	case ',':
1554 	case ' ':
1555 	case 'i':
1556 	case 'u':
1557 	case 'd':
1558 	  break;
1559 	default:
1560 	  as_bad (_("Illegal `cinv' parameter: `%c'"), *p);
1561 	}
1562     }
1563 }
1564 
1565 /* Retrieve the opcode image of a given register pair.
1566    If the register is illegal for the current instruction,
1567    issue an error.  */
1568 
1569 static int
getregp_image(reg r)1570 getregp_image (reg r)
1571 {
1572   const reg_entry *rreg;
1573   char *reg_name;
1574 
1575   /* Check whether the register is in registers table.  */
1576   if (r < MAX_REG)
1577     rreg = cr16_regptab + r;
1578   /* Register not found.  */
1579   else
1580     {
1581       as_bad (_("Unknown register pair: `%d'"), r);
1582       return 0;
1583     }
1584 
1585   reg_name = rreg->name;
1586 
1587   /* Issue a error message when register  pair is illegal.  */
1588 #define RPAIR_IMAGE_ERR							\
1589   as_bad (_("Illegal register pair (`%s') in Instruction: `%s'"),	\
1590 	  reg_name, ins_parse);						\
1591   break;
1592 
1593   switch (rreg->type)
1594     {
1595     case CR16_RP_REGTYPE:
1596       return rreg->image;
1597     default:
1598       RPAIR_IMAGE_ERR;
1599     }
1600 
1601   return 0;
1602 }
1603 
1604 /* Retrieve the opcode image of a given index register pair.
1605    If the register is illegal for the current instruction,
1606    issue an error.  */
1607 
1608 static int
getidxregp_image(reg r)1609 getidxregp_image (reg r)
1610 {
1611   const reg_entry *rreg;
1612   char *reg_name;
1613 
1614   /* Check whether the register is in registers table.  */
1615   if (r < MAX_REG)
1616     rreg = cr16_regptab + r;
1617   /* Register not found.  */
1618   else
1619     {
1620       as_bad (_("Unknown register pair: `%d'"), r);
1621       return 0;
1622     }
1623 
1624   reg_name = rreg->name;
1625 
1626   /* Issue a error message when register  pair is illegal.  */
1627 #define IDX_RPAIR_IMAGE_ERR						\
1628   as_bad (_("Illegal index register pair (`%s') in Instruction: `%s'"), \
1629 	  reg_name, ins_parse);						\
1630 
1631   if (rreg->type == CR16_RP_REGTYPE)
1632     {
1633       switch (rreg->image)
1634 	{
1635 	case 0:  return 0; break;
1636 	case 2:  return 1; break;
1637 	case 4:  return 2; break;
1638 	case 6:  return 3; break;
1639 	case 8:  return 4; break;
1640 	case 10: return 5; break;
1641 	case 3:  return 6; break;
1642 	case 5:  return 7; break;
1643 	default:
1644 	  break;
1645 	}
1646     }
1647 
1648   IDX_RPAIR_IMAGE_ERR;
1649   return 0;
1650 }
1651 
1652 /* Retrieve the opcode image of a given processor register.
1653    If the register is illegal for the current instruction,
1654    issue an error.  */
1655 static int
getprocreg_image(int r)1656 getprocreg_image (int r)
1657 {
1658   const reg_entry *rreg;
1659   char *reg_name;
1660 
1661   /* Check whether the register is in registers table.  */
1662   if (r >= MAX_REG && r < MAX_PREG)
1663     rreg = &cr16_pregtab[r - MAX_REG];
1664   /* Register not found.  */
1665   else
1666     {
1667       as_bad (_("Unknown processor register : `%d'"), r);
1668       return 0;
1669     }
1670 
1671   reg_name = rreg->name;
1672 
1673   /* Issue a error message when register  pair is illegal.  */
1674 #define PROCREG_IMAGE_ERR						\
1675   as_bad (_("Illegal processor register (`%s') in Instruction: `%s'"),	\
1676 	  reg_name, ins_parse);						\
1677   break;
1678 
1679   switch (rreg->type)
1680     {
1681     case CR16_P_REGTYPE:
1682       return rreg->image;
1683     default:
1684       PROCREG_IMAGE_ERR;
1685     }
1686 
1687   return 0;
1688 }
1689 
1690 /* Retrieve the opcode image of a given processor register.
1691    If the register is illegal for the current instruction,
1692    issue an error.  */
1693 static int
getprocregp_image(int r)1694 getprocregp_image (int r)
1695 {
1696   const reg_entry *rreg;
1697   char *reg_name;
1698   int pregptab_disp = 0;
1699 
1700   /* Check whether the register is in registers table.  */
1701   if (r >= MAX_REG && r < MAX_PREG)
1702     {
1703       r = r - MAX_REG;
1704       switch (r)
1705 	{
1706 	case 4: pregptab_disp = 1;  break;
1707 	case 6: pregptab_disp = 2;  break;
1708 	case 8:
1709 	case 9:
1710 	case 10:
1711 	  pregptab_disp = 3;  break;
1712 	case 12:
1713 	  pregptab_disp = 4;  break;
1714 	case 14:
1715 	  pregptab_disp = 5;  break;
1716 	default: break;
1717 	}
1718       rreg = &cr16_pregptab[r - pregptab_disp];
1719     }
1720   /* Register not found.  */
1721   else
1722     {
1723       as_bad (_("Unknown processor register (32 bit) : `%d'"), r);
1724       return 0;
1725     }
1726 
1727   reg_name = rreg->name;
1728 
1729   /* Issue a error message when register  pair is illegal.  */
1730 #define PROCREGP_IMAGE_ERR						\
1731   as_bad (_("Illegal 32 bit - processor register (`%s') in Instruction: `%s'"), \
1732 	  reg_name, ins_parse);						\
1733   break;
1734 
1735   switch (rreg->type)
1736     {
1737     case CR16_P_REGTYPE:
1738       return rreg->image;
1739     default:
1740       PROCREGP_IMAGE_ERR;
1741     }
1742 
1743   return 0;
1744 }
1745 
1746 /* Routine used to represent integer X using NBITS bits.  */
1747 
1748 static long
getconstant(long x,int nbits)1749 getconstant (long x, int nbits)
1750 {
1751   if ((unsigned) nbits >= sizeof (x) * CHAR_BIT)
1752     return x;
1753   return x & ((1UL << nbits) - 1);
1754 }
1755 
1756 /* Print a constant value to 'output_opcode':
1757    ARG holds the operand's type and value.
1758    SHIFT represents the location of the operand to be print into.
1759    NBITS determines the size (in bits) of the constant.  */
1760 
1761 static void
print_constant(int nbits,int shift,argument * arg)1762 print_constant (int nbits, int shift, argument *arg)
1763 {
1764   unsigned long mask = 0;
1765   unsigned long constant = getconstant (arg->constant, nbits);
1766 
1767   switch (nbits)
1768     {
1769     case 32:
1770     case 28:
1771       /* mask the upper part of the constant, that is, the bits
1772 	 going to the lowest byte of output_opcode[0].
1773 	 The upper part of output_opcode[1] is always filled,
1774 	 therefore it is always masked with 0xFFFF.  */
1775       mask = (1 << (nbits - 16)) - 1;
1776       /* Divide the constant between two consecutive words :
1777 	 0        1         2         3
1778 	 +---------+---------+---------+---------+
1779 	 |         | X X X X | x X x X |         |
1780 	 +---------+---------+---------+---------+
1781 	 output_opcode[0]    output_opcode[1]     */
1782 
1783       CR16_PRINT (0, (constant >> WORD_SHIFT) & mask, 0);
1784       CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
1785       break;
1786 
1787     case 21:
1788       if ((nbits == 21) && (IS_INSN_TYPE (LD_STOR_INS)))
1789 	nbits = 20;
1790       /* Fall through.  */
1791     case 24:
1792     case 22:
1793     case 20:
1794       /* mask the upper part of the constant, that is, the bits
1795 	 going to the lowest byte of output_opcode[0].
1796 	 The upper part of output_opcode[1] is always filled,
1797 	 therefore it is always masked with 0xFFFF.  */
1798       mask = (1 << (nbits - 16)) - 1;
1799       /* Divide the constant between two consecutive words :
1800 	 0        1         2          3
1801 	 +---------+---------+---------+---------+
1802 	 |         | X X X X | - X - X |         |
1803 	 +---------+---------+---------+---------+
1804 	 output_opcode[0]    output_opcode[1]     */
1805 
1806       if (instruction->size > 2 && shift == WORD_SHIFT)
1807 	{
1808 	  if (arg->type == arg_idxrp)
1809 	    {
1810 	      CR16_PRINT (0, ((constant >> WORD_SHIFT) & mask) << 8, 0);
1811 	      CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
1812 	    }
1813 	  else
1814 	    {
1815 	      CR16_PRINT (0,
1816 			  ((((constant >> WORD_SHIFT) & mask & 0xf) << 8)
1817 			   | (((constant >> WORD_SHIFT) & mask & 0xf0) >> 4)),
1818 			  0);
1819 	      CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
1820 	    }
1821 	}
1822       else
1823 	CR16_PRINT (0, constant, shift);
1824       break;
1825 
1826     case 14:
1827       if (arg->type == arg_idxrp)
1828 	{
1829 	  if (instruction->size == 2)
1830 	    {
1831 	      CR16_PRINT (0, (constant)      & 0xf, shift);      /* 0-3 bits.  */
1832 	      CR16_PRINT (0, (constant >> 4) & 0x3, shift + 20); /* 4-5 bits.  */
1833 	      CR16_PRINT (0, (constant >> 6) & 0x3, shift + 14); /* 6-7 bits.  */
1834 	      CR16_PRINT (0, (constant >> 8) & 0x3f, shift + 8); /* 8-13 bits.  */
1835 	    }
1836 	  else
1837 	    CR16_PRINT (0, constant, shift);
1838 	}
1839       break;
1840 
1841     case 16:
1842     case 12:
1843       /* When instruction size is 3 and 'shift' is 16, a 16-bit constant is
1844 	 always filling the upper part of output_opcode[1]. If we mistakenly
1845 	 write it to output_opcode[0], the constant prefix (that is, 'match')
1846 	 will be overridden.
1847 	 0        1         2         3
1848 	 +---------+---------+---------+---------+
1849 	 | 'match' |         | X X X X |         |
1850 	 +---------+---------+---------+---------+
1851 	 output_opcode[0]    output_opcode[1]     */
1852 
1853       if (instruction->size > 2 && shift == WORD_SHIFT)
1854 	CR16_PRINT (1, constant, WORD_SHIFT);
1855       else
1856 	CR16_PRINT (0, constant, shift);
1857       break;
1858 
1859     case 8:
1860       CR16_PRINT (0, (constant / 2) & 0xf, shift);
1861       CR16_PRINT (0, (constant / 2) >> 4, shift + 8);
1862       break;
1863 
1864     default:
1865       CR16_PRINT (0, constant, shift);
1866       break;
1867     }
1868 }
1869 
1870 /* Print an operand to 'output_opcode', which later on will be
1871    printed to the object file:
1872    ARG holds the operand's type, size and value.
1873    SHIFT represents the printing location of operand.
1874    NBITS determines the size (in bits) of a constant operand.  */
1875 
1876 static void
print_operand(int nbits,int shift,argument * arg)1877 print_operand (int nbits, int shift, argument *arg)
1878 {
1879   switch (arg->type)
1880     {
1881     case arg_cc:
1882       CR16_PRINT (0, arg->cc, shift);
1883       break;
1884 
1885     case arg_r:
1886       CR16_PRINT (0, getreg_image (arg->r), shift);
1887       break;
1888 
1889     case arg_rp:
1890       CR16_PRINT (0, getregp_image (arg->rp), shift);
1891       break;
1892 
1893     case arg_pr:
1894       CR16_PRINT (0, getprocreg_image (arg->pr), shift);
1895       break;
1896 
1897     case arg_prp:
1898       CR16_PRINT (0, getprocregp_image (arg->prp), shift);
1899       break;
1900 
1901     case arg_idxrp:
1902       /*    16      12      8    6      0
1903 	    +-----------------------------+
1904 	    | r_index | disp  | rp_base   |
1905 	    +-----------------------------+          */
1906 
1907       if (instruction->size == 3)
1908 	{
1909 	  CR16_PRINT (0, getidxregp_image (arg->rp), 0);
1910 	  CR16_PRINT (0, getreg_image (arg->i_r) & 1, 3);
1911 	}
1912       else
1913 	{
1914 	  CR16_PRINT (0, getidxregp_image (arg->rp), 16);
1915 	  CR16_PRINT (0, getreg_image (arg->i_r) & 1, 19);
1916 	}
1917       print_constant (nbits, shift, arg);
1918       break;
1919 
1920     case arg_idxr:
1921       CR16_PRINT (0, getreg_image (arg->i_r) & 1,
1922 		  (IS_INSN_TYPE (CSTBIT_INS)
1923 		   && instruction->mnemonic[4] == 'b') ? 23 : 24);
1924       print_constant (nbits, shift, arg);
1925       break;
1926 
1927     case arg_ic:
1928     case arg_c:
1929       print_constant (nbits, shift, arg);
1930       break;
1931 
1932     case arg_rbase:
1933       CR16_PRINT (0, getreg_image (arg->r), shift);
1934       break;
1935 
1936     case arg_cr:
1937       print_constant (nbits, shift, arg);
1938       /* Add the register argument to the output_opcode.  */
1939       CR16_PRINT (0, getreg_image (arg->r), shift - 16);
1940       break;
1941 
1942     case arg_crp:
1943       print_constant (nbits, shift, arg);
1944       if ((IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
1945 	  && instruction->size == 1)
1946 	CR16_PRINT (0, getregp_image (arg->rp), 16);
1947       else if (instruction->size > 1)
1948 	CR16_PRINT (0, getregp_image (arg->rp), (shift + 16) & 31);
1949       else
1950 	CR16_PRINT (0, getregp_image (arg->rp), shift);
1951       break;
1952 
1953     default:
1954       break;
1955     }
1956 }
1957 
1958 /* Retrieve the number of operands for the current assembled instruction.  */
1959 
1960 static int
get_number_of_operands(void)1961 get_number_of_operands (void)
1962 {
1963   int i;
1964 
1965   for (i = 0; instruction->operands[i].op_type && i < MAX_OPERANDS; i++)
1966     ;
1967   return i;
1968 }
1969 
1970 /* Verify that the number NUM can be represented in BITS bits (that is,
1971    within its permitted range), based on the instruction's FLAGS.
1972    If UPDATE is nonzero, update the value of NUM if necessary.
1973    Return OP_LEGAL upon success, actual error type upon failure.  */
1974 
1975 static op_err
check_range(long * num,int bits,int unsigned flags,int update)1976 check_range (long *num, int bits, int unsigned flags, int update)
1977 {
1978   int32_t min, max;
1979   op_err retval = OP_LEGAL;
1980   int32_t value = *num;
1981 
1982   /* Verify operand value is even.  */
1983   if (flags & OP_EVEN)
1984     {
1985       if (value % 2)
1986 	return OP_NOT_EVEN;
1987     }
1988 
1989   if (flags & OP_DEC)
1990     {
1991       value -= 1;
1992       if (update)
1993 	*num = value;
1994     }
1995 
1996   if (flags & OP_SHIFT)
1997     {
1998       value >>= 1;
1999       if (update)
2000 	*num = value;
2001     }
2002   else if (flags & OP_SHIFT_DEC)
2003     {
2004       value = (value >> 1) - 1;
2005       if (update)
2006 	*num = value;
2007     }
2008 
2009   if (flags & OP_ABS20)
2010     {
2011       if (value > 0xEFFFF)
2012 	return OP_OUT_OF_RANGE;
2013     }
2014 
2015   if (flags & OP_ESC)
2016     {
2017       if (value == 0xB || value == 0x9)
2018 	return OP_OUT_OF_RANGE;
2019       else if (value == -1)
2020 	{
2021 	  if (update)
2022 	    *num = 9;
2023 	  return retval;
2024 	}
2025     }
2026 
2027   if (flags & OP_ESC1)
2028     {
2029       if (value > 13)
2030 	return OP_OUT_OF_RANGE;
2031     }
2032 
2033   if (bits == 0)
2034     {
2035       if (value != 0)
2036 	retval = OP_OUT_OF_RANGE;
2037       return retval;
2038     }
2039 
2040   if (flags & OP_SIGNED)
2041     {
2042       max = (1U << (bits - 1)) - 1;
2043       min = - (1U << (bits - 1));
2044       if (value > max || value < min)
2045 	retval = OP_OUT_OF_RANGE;
2046     }
2047   else if (flags & OP_UNSIGNED)
2048     {
2049       max = (1U << (bits - 1) << 1) - 1;
2050       if ((uint32_t) value > (uint32_t) max)
2051 	retval = OP_OUT_OF_RANGE;
2052     }
2053   else if (flags & OP_NEG)
2054     {
2055       min = - ((1U << (bits - 1)) - 1);
2056       if (value < min)
2057 	retval = OP_OUT_OF_RANGE;
2058     }
2059   return retval;
2060 }
2061 
2062 /* Bunch of error checking.
2063    The checks are made after a matching instruction was found.  */
2064 
2065 static void
warn_if_needed(ins * insn)2066 warn_if_needed (ins *insn)
2067 {
2068   /* If the post-increment address mode is used and the load/store
2069      source register is the same as rbase, the result of the
2070      instruction is undefined.  */
2071   if (IS_INSN_TYPE (LD_STOR_INS_INC))
2072     {
2073       /* Enough to verify that one of the arguments is a simple reg.  */
2074       if ((insn->arg[0].type == arg_r) || (insn->arg[1].type == arg_r))
2075 	if (insn->arg[0].r == insn->arg[1].r)
2076 	  as_bad (_("Same src/dest register is used (`r%d'), "
2077 		    "result is undefined"), insn->arg[0].r);
2078     }
2079 
2080   if (IS_INSN_MNEMONIC ("pop")
2081       || IS_INSN_MNEMONIC ("push")
2082       || IS_INSN_MNEMONIC ("popret"))
2083     {
2084       unsigned int count = insn->arg[0].constant, reg_val;
2085 
2086       /* Check if count operand caused to save/retrieve the RA twice
2087 	 to generate warning message.  */
2088       if (insn->nargs > 2)
2089 	{
2090 	  reg_val = getreg_image (insn->arg[1].r);
2091 
2092 	  if (   ((reg_val == 9) &&  (count > 7))
2093 		 || ((reg_val == 10) && (count > 6))
2094 		 || ((reg_val == 11) && (count > 5))
2095 		 || ((reg_val == 12) && (count > 4))
2096 		 || ((reg_val == 13) && (count > 2))
2097 		 || ((reg_val == 14) && (count > 0)))
2098 	    as_warn (_("RA register is saved twice."));
2099 
2100 	  /* Check if the third operand is "RA" or "ra" */
2101 	  if (!(((insn->arg[2].r) == ra) || ((insn->arg[2].r) == RA)))
2102 	    as_bad (_("`%s' Illegal use of registers."), ins_parse);
2103 	}
2104 
2105       if (insn->nargs > 1)
2106 	{
2107 	  reg_val = getreg_image (insn->arg[1].r);
2108 
2109 	  /* If register is a register pair ie r12/r13/r14 in operand1, then
2110 	     the count constant should be validated.  */
2111 	  if (((reg_val == 11) && (count > 7))
2112 	      || ((reg_val == 12) && (count > 6))
2113 	      || ((reg_val == 13) && (count > 4))
2114 	      || ((reg_val == 14) && (count > 2))
2115 	      || ((reg_val == 15) && (count > 0)))
2116 	    as_bad (_("`%s' Illegal count-register combination."), ins_parse);
2117 	}
2118       else
2119 	{
2120 	  /* Check if the operand is "RA" or "ra" */
2121 	  if (!(((insn->arg[0].r) == ra) || ((insn->arg[0].r) == RA)))
2122 	    as_bad (_("`%s' Illegal use of register."), ins_parse);
2123 	}
2124     }
2125 
2126   /* Some instruction assume the stack pointer as rptr operand.
2127      Issue an error when the register to be loaded is also SP.  */
2128   if (instruction->flags & NO_SP)
2129     {
2130       if (getreg_image (insn->arg[1].r) == getreg_image (sp))
2131 	as_bad (_("`%s' has undefined result"), ins_parse);
2132     }
2133 
2134   /* If the rptr register is specified as one of the registers to be loaded,
2135      the final contents of rptr are undefined. Thus, we issue an error.  */
2136   if (instruction->flags & NO_RPTR)
2137     {
2138       if ((1 << getreg_image (insn->arg[0].r)) & insn->arg[1].constant)
2139 	as_bad (_("Same src/dest register is used (`r%d'),result is undefined"),
2140 		getreg_image (insn->arg[0].r));
2141     }
2142 }
2143 
2144 /* In some cases, we need to adjust the instruction pointer although a
2145    match was already found. Here, we gather all these cases.
2146    Returns 1 if instruction pointer was adjusted, otherwise 0.  */
2147 
2148 static int
adjust_if_needed(ins * insn ATTRIBUTE_UNUSED)2149 adjust_if_needed (ins *insn ATTRIBUTE_UNUSED)
2150 {
2151   int ret_value = 0;
2152 
2153   if ((IS_INSN_TYPE (CSTBIT_INS)) || (IS_INSN_TYPE (LD_STOR_INS)))
2154     {
2155       if ((instruction->operands[0].op_type == abs24)
2156 	  && ((insn->arg[0].constant) > 0xF00000))
2157 	{
2158 	  insn->arg[0].constant &= 0xFFFFF;
2159 	  instruction--;
2160 	  ret_value = 1;
2161 	}
2162     }
2163 
2164   return ret_value;
2165 }
2166 
2167 /* Assemble a single instruction:
2168    INSN is already parsed (that is, all operand values and types are set).
2169    For instruction to be assembled, we need to find an appropriate template in
2170    the instruction table, meeting the following conditions:
2171     1: Has the same number of operands.
2172     2: Has the same operand types.
2173     3: Each operand size is sufficient to represent the instruction's values.
2174    Returns 1 upon success, 0 upon failure.  */
2175 
2176 static int
assemble_insn(const char * mnemonic,ins * insn)2177 assemble_insn (const char *mnemonic, ins *insn)
2178 {
2179   /* Type of each operand in the current template.  */
2180   argtype cur_type[MAX_OPERANDS];
2181   /* Size (in bits) of each operand in the current template.  */
2182   unsigned int cur_size[MAX_OPERANDS];
2183   /* Flags of each operand in the current template.  */
2184   unsigned int cur_flags[MAX_OPERANDS];
2185   /* Instruction type to match.  */
2186   unsigned int ins_type;
2187   /* Boolean flag to mark whether a match was found.  */
2188   int match = 0;
2189   int i;
2190   /* Nonzero if an instruction with same number of operands was found.  */
2191   int found_same_number_of_operands = 0;
2192   /* Nonzero if an instruction with same argument types was found.  */
2193   int found_same_argument_types = 0;
2194   /* Nonzero if a constant was found within the required range.  */
2195   int found_const_within_range  = 0;
2196   /* Argument number of an operand with invalid type.  */
2197   int invalid_optype = -1;
2198   /* Argument number of an operand with invalid constant value.  */
2199   int invalid_const  = -1;
2200   /* Operand error (used for issuing various constant error messages).  */
2201   op_err op_error, const_err = OP_LEGAL;
2202 
2203   /* Retrieve data (based on FUNC) for each operand of a given instruction.  */
2204 #define GET_CURRENT_DATA(FUNC, ARRAY)			\
2205   for (i = 0; i < insn->nargs; i++)			\
2206     ARRAY[i] = FUNC (instruction->operands[i].op_type)
2207 
2208 #define GET_CURRENT_TYPE    GET_CURRENT_DATA (get_optype, cur_type)
2209 #define GET_CURRENT_SIZE    GET_CURRENT_DATA (get_opbits, cur_size)
2210 #define GET_CURRENT_FLAGS   GET_CURRENT_DATA (get_opflags, cur_flags)
2211 
2212   /* Instruction has no operands -> only copy the constant opcode.   */
2213   if (insn->nargs == 0)
2214     {
2215       output_opcode[0] = BIN (instruction->match, instruction->match_bits);
2216       return 1;
2217     }
2218 
2219   /* In some case, same mnemonic can appear with different instruction types.
2220      For example, 'storb' is supported with 3 different types :
2221      LD_STOR_INS, LD_STOR_INS_INC, STOR_IMM_INS.
2222      We assume that when reaching this point, the instruction type was
2223      pre-determined. We need to make sure that the type stays the same
2224      during a search for matching instruction.  */
2225   ins_type = CR16_INS_TYPE (instruction->flags);
2226 
2227   while (/* Check that match is still not found.  */
2228 	 match != 1
2229 	 /* Check we didn't get to end of table.  */
2230 	 && instruction->mnemonic != NULL
2231 	 /* Check that the actual mnemonic is still available.  */
2232 	 && IS_INSN_MNEMONIC (mnemonic)
2233 	 /* Check that the instruction type wasn't changed.  */
2234 	 && IS_INSN_TYPE (ins_type))
2235     {
2236       /* Check whether number of arguments is legal.  */
2237       if (get_number_of_operands () != insn->nargs)
2238 	goto next_insn;
2239       found_same_number_of_operands = 1;
2240 
2241       /* Initialize arrays with data of each operand in current template.  */
2242       GET_CURRENT_TYPE;
2243       GET_CURRENT_SIZE;
2244       GET_CURRENT_FLAGS;
2245 
2246       /* Check for type compatibility.  */
2247       for (i = 0; i < insn->nargs; i++)
2248 	{
2249 	  if (cur_type[i] != insn->arg[i].type)
2250 	    {
2251 	      if (invalid_optype == -1)
2252 		invalid_optype = i + 1;
2253 	      goto next_insn;
2254 	    }
2255 	}
2256       found_same_argument_types = 1;
2257 
2258       for (i = 0; i < insn->nargs; i++)
2259 	{
2260 	  /* If 'bal' instruction size is '2' and reg operand is not 'ra'
2261 	     then goto next instruction.  */
2262 	  if (IS_INSN_MNEMONIC ("bal") && (i == 0)
2263 	      && (instruction->size == 2) && (insn->arg[i].rp != 14))
2264 	    goto next_insn;
2265 
2266 	  /* If 'storb' instruction with 'sp' reg and 16-bit disp of
2267 	   * reg-pair, leads to undefined trap, so this should use
2268 	   * 20-bit disp of reg-pair.  */
2269 	  if (IS_INSN_MNEMONIC ("storb") && (instruction->size == 2)
2270 	      && (insn->arg[i].r == 15) && (insn->arg[i + 1].type == arg_crp))
2271 	    goto next_insn;
2272 
2273 	  /* Only check range - don't update the constant's value, since the
2274 	     current instruction may not be the last we try to match.
2275 	     The constant's value will be updated later, right before printing
2276 	     it to the object file.  */
2277 	  if ((insn->arg[i].X_op == O_constant)
2278 	      && (op_error = check_range (&insn->arg[i].constant, cur_size[i],
2279 					  cur_flags[i], 0)))
2280 	    {
2281 	      if (invalid_const == -1)
2282 		{
2283 		  invalid_const = i + 1;
2284 		  const_err = op_error;
2285 		}
2286 	      goto next_insn;
2287 	    }
2288 	  /* For symbols, we make sure the relocation size (which was already
2289 	     determined) is sufficient.  */
2290 	  else if ((insn->arg[i].X_op == O_symbol)
2291 		   && ((bfd_reloc_type_lookup (stdoutput, insn->rtype))->bitsize
2292 		       > cur_size[i]))
2293 	    goto next_insn;
2294 	}
2295       found_const_within_range = 1;
2296 
2297       /* If we got till here -> Full match is found.  */
2298       match = 1;
2299       break;
2300 
2301       /* Try again with next instruction.  */
2302     next_insn:
2303       instruction++;
2304     }
2305 
2306   if (!match)
2307     {
2308       /* We haven't found a match - instruction can't be assembled.  */
2309       if (!found_same_number_of_operands)
2310 	as_bad (_("Incorrect number of operands"));
2311       else if (!found_same_argument_types)
2312 	as_bad (_("Illegal type of operand (arg %d)"), invalid_optype);
2313       else if (!found_const_within_range)
2314 	{
2315 	  switch (const_err)
2316 	    {
2317 	    case OP_OUT_OF_RANGE:
2318 	      as_bad (_("Operand out of range (arg %d)"), invalid_const);
2319 	      break;
2320 	    case OP_NOT_EVEN:
2321 	      as_bad (_("Operand has odd displacement (arg %d)"), invalid_const);
2322 	      break;
2323 	    default:
2324 	      as_bad (_("Illegal operand (arg %d)"), invalid_const);
2325 	      break;
2326 	    }
2327 	}
2328 
2329       return 0;
2330     }
2331   else
2332     /* Full match - print the encoding to output file.  */
2333     {
2334       /* Make further checking (such that couldn't be made earlier).
2335 	 Warn the user if necessary.  */
2336       warn_if_needed (insn);
2337 
2338       /* Check whether we need to adjust the instruction pointer.  */
2339       if (adjust_if_needed (insn))
2340 	/* If instruction pointer was adjusted, we need to update
2341 	   the size of the current template operands.  */
2342 	GET_CURRENT_SIZE;
2343 
2344       for (i = 0; i < insn->nargs; i++)
2345 	{
2346 	  int j = instruction->flags & REVERSE_MATCH ?
2347 	    i == 0 ? 1 :
2348 	    i == 1 ? 0 : i :
2349 	    i;
2350 
2351 	  /* This time, update constant value before printing it.  */
2352 	  if ((insn->arg[j].X_op == O_constant)
2353 	      && (check_range (&insn->arg[j].constant, cur_size[j],
2354 			       cur_flags[j], 1) != OP_LEGAL))
2355 	    as_fatal (_("Illegal operand (arg %d)"), j+1);
2356 	}
2357 
2358       /* First, copy the instruction's opcode.  */
2359       output_opcode[0] = BIN (instruction->match, instruction->match_bits);
2360 
2361       for (i = 0; i < insn->nargs; i++)
2362 	{
2363 	  /* For BAL (ra),disp17 instruction only. And also set the
2364 	     DISP24a relocation type.  */
2365 	  if (IS_INSN_MNEMONIC ("bal") && (instruction->size == 2) && i == 0)
2366 	    {
2367 	      insn->rtype = BFD_RELOC_CR16_DISP24a;
2368 	      continue;
2369 	    }
2370 	  cur_arg_num = i;
2371 	  print_operand (cur_size[i], instruction->operands[i].shift,
2372 			 &insn->arg[i]);
2373 	}
2374     }
2375 
2376   return 1;
2377 }
2378 
2379 /* Print the instruction.
2380    Handle also cases where the instruction is relaxable/relocatable.  */
2381 
2382 static void
print_insn(ins * insn)2383 print_insn (ins *insn)
2384 {
2385   unsigned int i, j, insn_size;
2386   char *this_frag;
2387   unsigned short words[4];
2388   int addr_mod;
2389 
2390   /* Arrange the insn encodings in a WORD size array.  */
2391   for (i = 0, j = 0; i < 2; i++)
2392     {
2393       words[j++] = (output_opcode[i] >> 16) & 0xFFFF;
2394       words[j++] = output_opcode[i] & 0xFFFF;
2395     }
2396 
2397   /* Handle relocation.  */
2398   if ((instruction->flags & RELAXABLE) && relocatable)
2399     {
2400       int relax_subtype;
2401       /* Write the maximal instruction size supported.  */
2402       insn_size = INSN_MAX_SIZE;
2403 
2404       if (IS_INSN_TYPE (BRANCH_INS))
2405 	{
2406 	  switch (insn->rtype)
2407 	    {
2408 	    case BFD_RELOC_CR16_DISP24:
2409 	      relax_subtype = 2;
2410 	      break;
2411 	    case BFD_RELOC_CR16_DISP16:
2412 	      relax_subtype = 1;
2413 	      break;
2414 	    default:
2415 	      relax_subtype = 0;
2416 	      break;
2417 	    }
2418 	}
2419       else
2420 	abort ();
2421 
2422       this_frag = frag_var (rs_machine_dependent, insn_size *2,
2423 			    4, relax_subtype,
2424 			    insn->exp.X_add_symbol,
2425 			    0,
2426 			    0);
2427     }
2428   else
2429     {
2430       insn_size = instruction->size;
2431       this_frag = frag_more (insn_size * 2);
2432 
2433       if ((relocatable) && (insn->rtype != BFD_RELOC_NONE))
2434 	{
2435 	  reloc_howto_type *reloc_howto;
2436 	  int size;
2437 
2438 	  reloc_howto = bfd_reloc_type_lookup (stdoutput, insn->rtype);
2439 
2440 	  if (!reloc_howto)
2441 	    abort ();
2442 
2443 	  size = bfd_get_reloc_size (reloc_howto);
2444 
2445 	  if (size < 1 || size > 4)
2446 	    abort ();
2447 
2448 	  fix_new_exp (frag_now, this_frag - frag_now->fr_literal,
2449 		       size, &insn->exp, reloc_howto->pc_relative,
2450 		       insn->rtype);
2451 	}
2452     }
2453 
2454   /* Verify a 2-byte code alignment.  */
2455   addr_mod = frag_now_fix () & 1;
2456   if (frag_now->has_code && frag_now->insn_addr != addr_mod)
2457     as_bad (_("instruction address is not a multiple of 2"));
2458   frag_now->insn_addr = addr_mod;
2459   frag_now->has_code = 1;
2460 
2461   /* Write the instruction encoding to frag.  */
2462   for (i = 0; i < insn_size; i++)
2463     {
2464       md_number_to_chars (this_frag, (valueT) words[i], 2);
2465       this_frag += 2;
2466     }
2467 }
2468 
2469 /* Actually assemble an instruction.  */
2470 
2471 static void
cr16_assemble(const char * op,char * param)2472 cr16_assemble (const char *op, char *param)
2473 {
2474   ins cr16_ins;
2475 
2476   /* Find the instruction.  */
2477   instruction = (const inst *) str_hash_find (cr16_inst_hash, op);
2478   if (instruction == NULL)
2479     {
2480       as_bad (_("Unknown opcode: `%s'"), op);
2481       return;
2482     }
2483 
2484   /* Tie dwarf2 debug info to the address at the start of the insn.  */
2485   dwarf2_emit_insn (0);
2486 
2487   /* Parse the instruction's operands.  */
2488   parse_insn (&cr16_ins, param);
2489 
2490   /* Assemble the instruction - return upon failure.  */
2491   if (assemble_insn (op, &cr16_ins) == 0)
2492     return;
2493 
2494   /* Print the instruction.  */
2495   print_insn (&cr16_ins);
2496 }
2497 
2498 /* This is the guts of the machine-dependent assembler.  OP points to a
2499    machine dependent instruction.  This function is supposed to emit
2500    the frags/bytes it assembles to.  */
2501 
2502 void
md_assemble(char * op)2503 md_assemble (char *op)
2504 {
2505   ins cr16_ins;
2506   char *param, param1[32];
2507 
2508   /* Reset global variables for a new instruction.  */
2509   reset_vars (op);
2510 
2511   /* Strip the mnemonic.  */
2512   for (param = op; *param != 0 && !ISSPACE (*param); param++)
2513     ;
2514   *param++ = '\0';
2515 
2516   /* bCC instructions and adjust the mnemonic by adding extra white spaces.  */
2517   if (is_bcc_insn (op))
2518     {
2519       strcpy (param1, get_b_cc (op));
2520       strcat (param1,",");
2521       strcat (param1, param);
2522       param = (char *) &param1;
2523       cr16_assemble ("b", param);
2524       return;
2525     }
2526 
2527   /* Checking the cinv options and adjust the mnemonic by removing the
2528      extra white spaces.  */
2529   if (streq ("cinv", op))
2530     {
2531       /* Validate the cinv options.  */
2532       unsigned int op_len, param_len;
2533       check_cinv_options (param);
2534       op_len = strlen (op);
2535       param_len = strlen (param) + 1;
2536       memmove (op + op_len, param, param_len);
2537     }
2538 
2539   /* MAPPING - SHIFT INSN, if imm4/imm16 positive values
2540      lsh[b/w] imm4/imm6, reg ==> ashu[b/w] imm4/imm16, reg
2541      as CR16 core doesn't support lsh[b/w] right shift operations.  */
2542   if ((streq ("lshb", op) || streq ("lshw", op) || streq ("lshd", op))
2543       && (param [0] == '$'))
2544     {
2545       strcpy (param1, param);
2546       /* Find the instruction.  */
2547       instruction = (const inst *) str_hash_find (cr16_inst_hash, op);
2548       parse_operands (&cr16_ins, param1);
2549       if (((&cr16_ins)->arg[0].type == arg_ic)
2550 	  && ((&cr16_ins)->arg[0].constant >= 0))
2551 	{
2552 	  if (streq ("lshb", op))
2553 	    cr16_assemble ("ashub", param);
2554 	  else if (streq ("lshd", op))
2555 	    cr16_assemble ("ashud", param);
2556 	  else
2557 	    cr16_assemble ("ashuw", param);
2558 	  return;
2559 	}
2560     }
2561 
2562   cr16_assemble (op, param);
2563 }
2564