1 /* Altera Nios II assembler.
2    Copyright (C) 2012-2014 Free Software Foundation, Inc.
3    Contributed by Nigel Gray (ngray@altera.com).
4    Contributed by Mentor Graphics, Inc.
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 Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22 
23 #include "as.h"
24 #include "opcode/nios2.h"
25 #include "elf/nios2.h"
26 #include "tc-nios2.h"
27 #include "bfd.h"
28 #include "dwarf2dbg.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31 #include "dw2gencfi.h"
32 
33 #ifndef OBJ_ELF
34 /* We are not supporting any other target so we throw a compile time error.  */
35 OBJ_ELF not defined
36 #endif
37 
38 /* We can choose our endianness at run-time, regardless of configuration.  */
39 extern int target_big_endian;
40 
41 /* This array holds the chars that always start a comment.  If the
42    pre-processor is disabled, these aren't very useful.  */
43 const char comment_chars[] = "#";
44 
45 /* This array holds the chars that only start a comment at the beginning of
46    a line.  If the line seems to have the form '# 123 filename'
47    .line and .file directives will appear in the pre-processed output.  */
48 /* Note that input_file.c hand checks for '#' at the beginning of the
49    first line of the input file.  This is because the compiler outputs
50    #NO_APP at the beginning of its output.  */
51 /* Also note that C style comments are always supported.  */
52 const char line_comment_chars[] = "#";
53 
54 /* This array holds machine specific line separator characters.  */
55 const char line_separator_chars[] = ";";
56 
57 /* Chars that can be used to separate mant from exp in floating point nums.  */
58 const char EXP_CHARS[] = "eE";
59 
60 /* Chars that mean this number is a floating point constant.  */
61 /* As in 0f12.456 */
62 /* or	 0d1.2345e12 */
63 const char FLT_CHARS[] = "rRsSfFdDxXpP";
64 
65 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
66    changed in read.c.  Ideally it shouldn't have to know about it at all,
67    but nothing is ideal around here.  */
68 
69 /* Machine-dependent command-line options.  */
70 
71 const char *md_shortopts = "r";
72 
73 struct option md_longopts[] = {
74 #define OPTION_RELAX_ALL (OPTION_MD_BASE + 0)
75   {"relax-all", no_argument, NULL, OPTION_RELAX_ALL},
76 #define OPTION_NORELAX (OPTION_MD_BASE + 1)
77   {"no-relax", no_argument, NULL, OPTION_NORELAX},
78 #define OPTION_RELAX_SECTION (OPTION_MD_BASE + 2)
79   {"relax-section", no_argument, NULL, OPTION_RELAX_SECTION},
80 #define OPTION_EB (OPTION_MD_BASE + 3)
81   {"EB", no_argument, NULL, OPTION_EB},
82 #define OPTION_EL (OPTION_MD_BASE + 4)
83   {"EL", no_argument, NULL, OPTION_EL}
84 };
85 
86 size_t md_longopts_size = sizeof (md_longopts);
87 
88 /* The assembler supports three different relaxation modes, controlled by
89    command-line options.  */
90 typedef enum
91 {
92   relax_section = 0,
93   relax_none,
94   relax_all
95 } relax_optionT;
96 
97 /* Struct contains all assembler options set with .set.  */
98 struct
99 {
100   /* .set noat -> noat = 1 allows assembly code to use at without warning
101      and macro expansions generate a warning.
102      .set at -> noat = 0, assembly code using at warn but macro expansions
103      do not generate warnings.  */
104   bfd_boolean noat;
105 
106   /* .set nobreak -> nobreak = 1 allows assembly code to use ba,bt without
107 				 warning.
108      .set break -> nobreak = 0, assembly code using ba,bt warns.  */
109   bfd_boolean nobreak;
110 
111   /* .cmd line option -relax-all allows all branches and calls to be replaced
112      with longer versions.
113      -no-relax inhibits branch/call conversion.
114      The default value is relax_section, which relaxes branches within
115      a section.  */
116   relax_optionT relax;
117 
118 } nios2_as_options = {FALSE, FALSE, relax_section};
119 
120 
121 typedef struct nios2_insn_reloc
122 {
123   /* Any expression in the instruction is parsed into this field,
124      which is passed to fix_new_exp() to generate a fixup.  */
125   expressionS reloc_expression;
126 
127   /* The type of the relocation to be applied.  */
128   bfd_reloc_code_real_type reloc_type;
129 
130   /* PC-relative.  */
131   unsigned int reloc_pcrel;
132 
133   /* The next relocation to be applied to the instruction.  */
134   struct nios2_insn_reloc *reloc_next;
135 } nios2_insn_relocS;
136 
137 /* This struct is used to hold state when assembling instructions.  */
138 typedef struct nios2_insn_info
139 {
140   /* Assembled instruction.  */
141   unsigned long insn_code;
142 
143   /* Constant bits masked into insn_code for self-check mode.  */
144   unsigned long constant_bits;
145 
146   /* Pointer to the relevant bit of the opcode table.  */
147   const struct nios2_opcode *insn_nios2_opcode;
148   /* After parsing ptrs to the tokens in the instruction fill this array
149      it is terminated with a null pointer (hence the first +1).
150      The second +1 is because in some parts of the code the opcode
151      is not counted as a token, but still placed in this array.  */
152   const char *insn_tokens[NIOS2_MAX_INSN_TOKENS + 1 + 1];
153 
154   /* This holds information used to generate fixups
155      and eventually relocations if it is not null.  */
156   nios2_insn_relocS *insn_reloc;
157 } nios2_insn_infoS;
158 
159 
160 /* This struct is used to convert Nios II pseudo-ops into the
161    corresponding real op.  */
162 typedef struct nios2_ps_insn_info
163 {
164   /* Map this pseudo_op... */
165   const char *pseudo_insn;
166 
167   /* ...to this real instruction.  */
168   const char *insn;
169 
170   /* Call this function to modify the operands....  */
171   void (*arg_modifer_func) (char ** parsed_args, const char *arg, int num,
172 			    int start);
173 
174   /* ...with these arguments.  */
175   const char *arg_modifier;
176   int num;
177   int index;
178 
179   /* If arg_modifier_func allocates new memory, provide this function
180      to free it afterwards.  */
181   void (*arg_cleanup_func) (char **parsed_args, int num, int start);
182 } nios2_ps_insn_infoS;
183 
184 /* Opcode hash table.  */
185 static struct hash_control *nios2_opcode_hash = NULL;
186 #define nios2_opcode_lookup(NAME) \
187   ((struct nios2_opcode *) hash_find (nios2_opcode_hash, (NAME)))
188 
189 /* Register hash table.  */
190 static struct hash_control *nios2_reg_hash = NULL;
191 #define nios2_reg_lookup(NAME) \
192   ((struct nios2_reg *) hash_find (nios2_reg_hash, (NAME)))
193 
194 
195 /* Pseudo-op hash table.  */
196 static struct hash_control *nios2_ps_hash = NULL;
197 #define nios2_ps_lookup(NAME) \
198   ((nios2_ps_insn_infoS *) hash_find (nios2_ps_hash, (NAME)))
199 
200 /* The known current alignment of the current section.  */
201 static int nios2_current_align;
202 static segT nios2_current_align_seg;
203 
204 static int nios2_auto_align_on = 1;
205 
206 /* The last seen label in the current section.  This is used to auto-align
207    labels preceeding instructions.  */
208 static symbolS *nios2_last_label;
209 
210 #ifdef OBJ_ELF
211 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"	*/
212 symbolS *GOT_symbol;
213 #endif
214 
215 
216 /** Utility routines.  */
217 /* Function md_chars_to_number takes the sequence of
218    bytes in buf and returns the corresponding value
219    in an int. n must be 1, 2 or 4.  */
220 static valueT
md_chars_to_number(char * buf,int n)221 md_chars_to_number (char *buf, int n)
222 {
223   int i;
224   valueT val;
225 
226   gas_assert (n == 1 || n == 2 || n == 4);
227 
228   val = 0;
229   if (target_big_endian)
230     for (i = 0; i < n; ++i)
231       val = val | ((buf[i] & 0xff) << 8 * (n - (i + 1)));
232   else
233     for (i = 0; i < n; ++i)
234       val = val | ((buf[i] & 0xff) << 8 * i);
235   return val;
236 }
237 
238 
239 /* This function turns a C long int, short int or char
240    into the series of bytes that represent the number
241    on the target machine.  */
242 void
md_number_to_chars(char * buf,valueT val,int n)243 md_number_to_chars (char *buf, valueT val, int n)
244 {
245   gas_assert (n == 1 || n == 2 || n == 4 || n == 8);
246   if (target_big_endian)
247     number_to_chars_bigendian (buf, val, n);
248   else
249     number_to_chars_littleendian (buf, val, n);
250 }
251 
252 /* Turn a string in input_line_pointer into a floating point constant
253    of type TYPE, and store the appropriate bytes in *LITP.  The number
254    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
255    returned, or NULL on OK.  */
256 char *
md_atof(int type,char * litP,int * sizeP)257 md_atof (int type, char *litP, int *sizeP)
258 {
259   int prec;
260   LITTLENUM_TYPE words[4];
261   char *t;
262   int i;
263 
264   switch (type)
265     {
266     case 'f':
267       prec = 2;
268       break;
269     case 'd':
270       prec = 4;
271       break;
272     default:
273       *sizeP = 0;
274       return _("bad call to md_atof");
275     }
276 
277   t = atof_ieee (input_line_pointer, type, words);
278   if (t)
279     input_line_pointer = t;
280 
281   *sizeP = prec * 2;
282 
283   if (! target_big_endian)
284     for (i = prec - 1; i >= 0; i--, litP += 2)
285       md_number_to_chars (litP, (valueT) words[i], 2);
286   else
287     for (i = 0; i < prec; i++, litP += 2)
288       md_number_to_chars (litP, (valueT) words[i], 2);
289 
290   return NULL;
291 }
292 
293 /* Return true if STR starts with PREFIX, which should be a string literal.  */
294 #define strprefix(STR, PREFIX) \
295   (strncmp ((STR), PREFIX, strlen (PREFIX)) == 0)
296 
297 
298 /* Return true if STR is prefixed with a special relocation operator.  */
299 static int
nios2_special_relocation_p(const char * str)300 nios2_special_relocation_p (const char *str)
301 {
302   return (strprefix (str, "%lo")
303 	  || strprefix (str, "%hi")
304 	  || strprefix (str, "%hiadj")
305 	  || strprefix (str, "%gprel")
306 	  || strprefix (str, "%got")
307 	  || strprefix (str, "%call")
308 	  || strprefix (str, "%gotoff_lo")
309 	  || strprefix (str, "%gotoff_hiadj")
310 	  || strprefix (str, "%tls_gd")
311 	  || strprefix (str, "%tls_ldm")
312 	  || strprefix (str, "%tls_ldo")
313 	  || strprefix (str, "%tls_ie")
314 	  || strprefix (str, "%tls_le")
315 	  || strprefix (str, "%gotoff"));
316 }
317 
318 
319 /* nop fill pattern for text section.  */
320 static char const nop[4] = { 0x3a, 0x88, 0x01, 0x00 };
321 
322 /* Handles all machine-dependent alignment needs.  */
323 static void
nios2_align(int log_size,const char * pfill,symbolS * label)324 nios2_align (int log_size, const char *pfill, symbolS *label)
325 {
326   int align;
327   long max_alignment = 15;
328 
329   /* The front end is prone to changing segments out from under us
330      temporarily when -g is in effect.  */
331   int switched_seg_p = (nios2_current_align_seg != now_seg);
332 
333   align = log_size;
334   if (align > max_alignment)
335     {
336       align = max_alignment;
337       as_bad (_("Alignment too large: %d. assumed"), align);
338     }
339   else if (align < 0)
340     {
341       as_warn (_("Alignment negative: 0 assumed"));
342       align = 0;
343     }
344 
345   if (align != 0)
346     {
347       if (subseg_text_p (now_seg) && align >= 2)
348 	{
349 	  /* First, make sure we're on a four-byte boundary, in case
350 	     someone has been putting .byte values the text section.  */
351 	  if (nios2_current_align < 2 || switched_seg_p)
352 	    frag_align (2, 0, 0);
353 
354 	  /* Now fill in the alignment pattern.  */
355 	  if (pfill != NULL)
356 	    frag_align_pattern (align, pfill, sizeof nop, 0);
357 	  else
358 	    frag_align (align, 0, 0);
359 	}
360       else
361 	frag_align (align, 0, 0);
362 
363       if (!switched_seg_p)
364 	nios2_current_align = align;
365 
366       /* If the last label was in a different section we can't align it.  */
367       if (label != NULL && !switched_seg_p)
368 	{
369 	  symbolS *sym;
370 	  int label_seen = FALSE;
371 	  struct frag *old_frag;
372 	  valueT old_value;
373 	  valueT new_value;
374 
375 	  gas_assert (S_GET_SEGMENT (label) == now_seg);
376 
377 	  old_frag = symbol_get_frag (label);
378 	  old_value = S_GET_VALUE (label);
379 	  new_value = (valueT) frag_now_fix ();
380 
381 	  /* It is possible to have more than one label at a particular
382 	     address, especially if debugging is enabled, so we must
383 	     take care to adjust all the labels at this address in this
384 	     fragment.  To save time we search from the end of the symbol
385 	     list, backwards, since the symbols we are interested in are
386 	     almost certainly the ones that were most recently added.
387 	     Also to save time we stop searching once we have seen at least
388 	     one matching label, and we encounter a label that is no longer
389 	     in the target fragment.  Note, this search is guaranteed to
390 	     find at least one match when sym == label, so no special case
391 	     code is necessary.  */
392 	  for (sym = symbol_lastP; sym != NULL; sym = symbol_previous (sym))
393 	    if (symbol_get_frag (sym) == old_frag
394 		&& S_GET_VALUE (sym) == old_value)
395 	      {
396 		label_seen = TRUE;
397 		symbol_set_frag (sym, frag_now);
398 		S_SET_VALUE (sym, new_value);
399 	      }
400 	    else if (label_seen && symbol_get_frag (sym) != old_frag)
401 	      break;
402 	}
403       record_alignment (now_seg, align);
404     }
405 }
406 
407 
408 /** Support for self-check mode.  */
409 
410 /* Mode of the assembler.  */
411 typedef enum
412 {
413   NIOS2_MODE_ASSEMBLE,		/* Ordinary operation.  */
414   NIOS2_MODE_TEST		/* Hidden mode used for self testing.  */
415 } NIOS2_MODE;
416 
417 static NIOS2_MODE nios2_mode = NIOS2_MODE_ASSEMBLE;
418 
419 /* This function is used to in self-checking mode
420    to check the assembled instruction
421    opcode should be the assembled opcode, and exp_opcode
422    the parsed string representing the expected opcode.  */
423 static void
nios2_check_assembly(unsigned int opcode,const char * exp_opcode)424 nios2_check_assembly (unsigned int opcode, const char *exp_opcode)
425 {
426   if (nios2_mode == NIOS2_MODE_TEST)
427     {
428       if (exp_opcode == NULL)
429 	as_bad (_("expecting opcode string in self test mode"));
430       else if (opcode != strtoul (exp_opcode, NULL, 16))
431 	as_bad (_("assembly 0x%08x, expected %s"), opcode, exp_opcode);
432     }
433 }
434 
435 
436 /** Support for machine-dependent assembler directives.  */
437 /* Handle the .align pseudo-op.  This aligns to a power of two.  It
438    also adjusts any current instruction label.  We treat this the same
439    way the MIPS port does: .align 0 turns off auto alignment.  */
440 static void
s_nios2_align(int ignore ATTRIBUTE_UNUSED)441 s_nios2_align (int ignore ATTRIBUTE_UNUSED)
442 {
443   int align;
444   char fill;
445   const char *pfill = NULL;
446   long max_alignment = 15;
447 
448   align = get_absolute_expression ();
449   if (align > max_alignment)
450     {
451       align = max_alignment;
452       as_bad (_("Alignment too large: %d. assumed"), align);
453     }
454   else if (align < 0)
455     {
456       as_warn (_("Alignment negative: 0 assumed"));
457       align = 0;
458     }
459 
460   if (*input_line_pointer == ',')
461     {
462       input_line_pointer++;
463       fill = get_absolute_expression ();
464       pfill = (const char *) &fill;
465     }
466   else if (subseg_text_p (now_seg))
467     pfill = (const char *) &nop;
468   else
469     {
470       pfill = NULL;
471       nios2_last_label = NULL;
472     }
473 
474   if (align != 0)
475     {
476       nios2_auto_align_on = 1;
477       nios2_align (align, pfill, nios2_last_label);
478       nios2_last_label = NULL;
479     }
480   else
481     nios2_auto_align_on = 0;
482 
483   demand_empty_rest_of_line ();
484 }
485 
486 /* Handle the .text pseudo-op.  This is like the usual one, but it
487    clears the saved last label and resets known alignment.  */
488 static void
s_nios2_text(int i)489 s_nios2_text (int i)
490 {
491   s_text (i);
492   nios2_last_label = NULL;
493   nios2_current_align = 0;
494   nios2_current_align_seg = now_seg;
495 }
496 
497 /* Handle the .data pseudo-op.  This is like the usual one, but it
498    clears the saved last label and resets known alignment.  */
499 static void
s_nios2_data(int i)500 s_nios2_data (int i)
501 {
502   s_data (i);
503   nios2_last_label = NULL;
504   nios2_current_align = 0;
505   nios2_current_align_seg = now_seg;
506 }
507 
508 /* Handle the .section pseudo-op.  This is like the usual one, but it
509    clears the saved last label and resets known alignment.  */
510 static void
s_nios2_section(int ignore)511 s_nios2_section (int ignore)
512 {
513   obj_elf_section (ignore);
514   nios2_last_label = NULL;
515   nios2_current_align = 0;
516   nios2_current_align_seg = now_seg;
517 }
518 
519 /* Explicitly unaligned cons.  */
520 static void
s_nios2_ucons(int nbytes)521 s_nios2_ucons (int nbytes)
522 {
523   int hold;
524   hold = nios2_auto_align_on;
525   nios2_auto_align_on = 0;
526   cons (nbytes);
527   nios2_auto_align_on = hold;
528 }
529 
530 /* Handle the .sdata directive.  */
531 static void
s_nios2_sdata(int ignore ATTRIBUTE_UNUSED)532 s_nios2_sdata (int ignore ATTRIBUTE_UNUSED)
533 {
534   get_absolute_expression ();  /* Ignored.  */
535   subseg_new (".sdata", 0);
536   demand_empty_rest_of_line ();
537 }
538 
539 /* .set sets assembler options eg noat/at and is also used
540    to set symbol values (.equ, .equiv ).  */
541 static void
s_nios2_set(int equiv)542 s_nios2_set (int equiv)
543 {
544   char *directive = input_line_pointer;
545   char delim = get_symbol_end ();
546   char *endline = input_line_pointer;
547   *endline = delim;
548 
549   /* We only want to handle ".set XXX" if the
550      user has tried ".set XXX, YYY" they are not
551      trying a directive.  This prevents
552      us from polluting the name space.  */
553   SKIP_WHITESPACE ();
554   if (is_end_of_line[(unsigned char) *input_line_pointer])
555     {
556       bfd_boolean done = TRUE;
557       *endline = 0;
558 
559       if (!strcmp (directive, "noat"))
560 	  nios2_as_options.noat = TRUE;
561       else if (!strcmp (directive, "at"))
562 	  nios2_as_options.noat = FALSE;
563       else if (!strcmp (directive, "nobreak"))
564 	  nios2_as_options.nobreak = TRUE;
565       else if (!strcmp (directive, "break"))
566 	  nios2_as_options.nobreak = FALSE;
567       else if (!strcmp (directive, "norelax"))
568 	  nios2_as_options.relax = relax_none;
569       else if (!strcmp (directive, "relaxsection"))
570 	  nios2_as_options.relax = relax_section;
571       else if (!strcmp (directive, "relaxall"))
572 	  nios2_as_options.relax = relax_all;
573       else
574 	done = FALSE;
575 
576       if (done)
577 	{
578 	  *endline = delim;
579 	  demand_empty_rest_of_line ();
580 	  return;
581 	}
582     }
583 
584   /* If we fall through to here, either we have ".set XXX, YYY"
585      or we have ".set XXX" where XXX is unknown or we have
586      a syntax error.  */
587   input_line_pointer = directive;
588   *endline = delim;
589   s_set (equiv);
590 }
591 
592 /* Machine-dependent assembler directives.
593    Format of each entry is:
594    { "directive", handler_func, param }	 */
595 const pseudo_typeS md_pseudo_table[] = {
596   {"align", s_nios2_align, 0},
597   {"text", s_nios2_text, 0},
598   {"data", s_nios2_data, 0},
599   {"section", s_nios2_section, 0},
600   {"section.s", s_nios2_section, 0},
601   {"sect", s_nios2_section, 0},
602   {"sect.s", s_nios2_section, 0},
603   /* .dword and .half are included for compatibility with MIPS.  */
604   {"dword", cons, 8},
605   {"half", cons, 2},
606   /* NIOS2 native word size is 4 bytes, so we override
607      the GAS default of 2.  */
608   {"word", cons, 4},
609   /* Explicitly unaligned directives.  */
610   {"2byte", s_nios2_ucons, 2},
611   {"4byte", s_nios2_ucons, 4},
612   {"8byte", s_nios2_ucons, 8},
613   {"16byte", s_nios2_ucons, 16},
614 #ifdef OBJ_ELF
615   {"sdata", s_nios2_sdata, 0},
616 #endif
617   {"set", s_nios2_set, 0},
618   {NULL, NULL, 0}
619 };
620 
621 
622 /** Relaxation support. */
623 
624 /* We support two relaxation modes:  a limited PC-relative mode with
625    -relax-section (the default), and an absolute jump mode with -relax-all.
626 
627    Nios II PC-relative branch instructions only support 16-bit offsets.
628    And, there's no good way to add a 32-bit constant to the PC without
629    using two registers.
630 
631    To deal with this, for the pc-relative relaxation mode we convert
632      br label
633    into a series of 16-bit adds, like:
634      nextpc at
635      addi at, at, 32767
636      ...
637      addi at, at, remainder
638      jmp at
639 
640    Similarly, conditional branches are converted from
641      b(condition) r, s, label
642    into a series like:
643      b(opposite condition) r, s, skip
644      nextpc at
645      addi at, at, 32767
646      ...
647      addi at, at, remainder
648      jmp at
649      skip:
650 
651    The compiler can do a better job, either by converting the branch
652    directly into a JMP (going through the GOT for PIC) or by allocating
653    a second register for the 32-bit displacement.
654 
655    For the -relax-all relaxation mode, the conversions are
656      movhi at, %hi(symbol+offset)
657      ori at, %lo(symbol+offset)
658      jmp at
659    and
660      b(opposite condition), r, s, skip
661      movhi at, %hi(symbol+offset)
662      ori at, %lo(symbol+offset)
663      jmp at
664      skip:
665    respectively.
666 */
667 
668 /* Arbitrarily limit the number of addis we can insert; we need to be able
669    to specify the maximum growth size for each frag that contains a
670    relaxable branch.  There's no point in specifying a huge number here
671    since that means the assembler needs to allocate that much extra
672    memory for every branch, and almost no real code will ever need it.
673    Plus, as already noted a better solution is to just use a jmp, or
674    allocate a second register to hold a 32-bit displacement.
675    FIXME:  Rather than making this a constant, it could be controlled by
676    a command-line argument.  */
677 #define RELAX_MAX_ADDI 32
678 
679 /* The fr_subtype field represents the target-specific relocation state.
680    It has type relax_substateT (unsigned int).  We use it to track the
681    number of addis necessary, plus a bit to track whether this is a
682    conditional branch.
683    Regardless of the smaller RELAX_MAX_ADDI limit, we reserve 16 bits
684    in the fr_subtype to encode the number of addis so that the whole
685    theoretically-valid range is representable.
686    For the -relax-all mode, N = 0 represents an in-range branch and N = 1
687    represents a branch that needs to be relaxed.  */
688 #define UBRANCH (0 << 16)
689 #define CBRANCH (1 << 16)
690 #define IS_CBRANCH(SUBTYPE) ((SUBTYPE) & CBRANCH)
691 #define IS_UBRANCH(SUBTYPE) (!IS_CBRANCH (SUBTYPE))
692 #define UBRANCH_SUBTYPE(N) (UBRANCH | (N))
693 #define CBRANCH_SUBTYPE(N) (CBRANCH | (N))
694 #define SUBTYPE_ADDIS(SUBTYPE) ((SUBTYPE) & 0xffff)
695 
696 /* For the -relax-section mode, unconditional branches require 2 extra i
697    nstructions besides the addis, conditional branches require 3.  */
698 #define UBRANCH_ADDIS_TO_SIZE(N) (((N) + 2) * 4)
699 #define CBRANCH_ADDIS_TO_SIZE(N) (((N) + 3) * 4)
700 
701 /* For the -relax-all mode, unconditional branches require 3 instructions
702    and conditional branches require 4.  */
703 #define UBRANCH_JUMP_SIZE 12
704 #define CBRANCH_JUMP_SIZE 16
705 
706 /* Maximum sizes of relaxation sequences.  */
707 #define UBRANCH_MAX_SIZE \
708   (nios2_as_options.relax == relax_all		\
709    ? UBRANCH_JUMP_SIZE				\
710    : UBRANCH_ADDIS_TO_SIZE (RELAX_MAX_ADDI))
711 #define CBRANCH_MAX_SIZE \
712   (nios2_as_options.relax == relax_all		\
713    ? CBRANCH_JUMP_SIZE				\
714    : CBRANCH_ADDIS_TO_SIZE (RELAX_MAX_ADDI))
715 
716 /* Register number of AT, the assembler temporary.  */
717 #define AT_REGNUM 1
718 
719 /* Determine how many bytes are required to represent the sequence
720    indicated by SUBTYPE.  */
721 static int
nios2_relax_subtype_size(relax_substateT subtype)722 nios2_relax_subtype_size (relax_substateT subtype)
723 {
724   int n = SUBTYPE_ADDIS (subtype);
725   if (n == 0)
726     /* Regular conditional/unconditional branch instruction.  */
727     return 4;
728   else if (nios2_as_options.relax == relax_all)
729     return (IS_CBRANCH (subtype) ? CBRANCH_JUMP_SIZE : UBRANCH_JUMP_SIZE);
730   else if (IS_CBRANCH (subtype))
731     return CBRANCH_ADDIS_TO_SIZE (n);
732   else
733     return UBRANCH_ADDIS_TO_SIZE (n);
734 }
735 
736 /* Estimate size of fragp before relaxation.
737    This could also examine the offset in fragp and adjust
738    fragp->fr_subtype, but we will do that in nios2_relax_frag anyway.  */
739 int
md_estimate_size_before_relax(fragS * fragp,segT segment ATTRIBUTE_UNUSED)740 md_estimate_size_before_relax (fragS *fragp, segT segment ATTRIBUTE_UNUSED)
741 {
742   return nios2_relax_subtype_size (fragp->fr_subtype);
743 }
744 
745 /* Implement md_relax_frag, returning the change in size of the frag.  */
746 long
nios2_relax_frag(segT segment,fragS * fragp,long stretch)747 nios2_relax_frag (segT segment, fragS *fragp, long stretch)
748 {
749   addressT target = fragp->fr_offset;
750   relax_substateT subtype = fragp->fr_subtype;
751   symbolS *symbolp = fragp->fr_symbol;
752 
753   if (symbolp)
754     {
755       fragS *sym_frag = symbol_get_frag (symbolp);
756       offsetT offset;
757       int n;
758 
759       target += S_GET_VALUE (symbolp);
760 
761       /* See comments in write.c:relax_frag about handling of stretch.  */
762       if (stretch != 0
763 	  && sym_frag->relax_marker != fragp->relax_marker)
764 	{
765 	  if (stretch < 0 || sym_frag->region == fragp->region)
766 	    target += stretch;
767 	  else if (target < fragp->fr_address)
768 	    target = fragp->fr_next->fr_address + stretch;
769 	}
770 
771       /* We subtract fr_var (4 for 32-bit insns) because all pc relative
772 	 branches are from the next instruction.  */
773       offset = target - fragp->fr_address - fragp->fr_fix - fragp->fr_var;
774       if (offset >= -32768 && offset <= 32764)
775 	/* Fits in PC-relative branch.  */
776 	n = 0;
777       else if (nios2_as_options.relax == relax_all)
778 	/* Convert to jump.  */
779 	n = 1;
780       else if (nios2_as_options.relax == relax_section
781 	       && S_GET_SEGMENT (symbolp) == segment
782 	       && S_IS_DEFINED (symbolp))
783 	/* Attempt a PC-relative relaxation on a branch to a defined
784 	   symbol in the same segment.  */
785 	{
786 	  /* The relaxation for conditional branches is offset by 4
787 	     bytes because we insert the inverted branch around the
788 	     sequence.  */
789 	  if (IS_CBRANCH (subtype))
790 	    offset = offset - 4;
791 	  if (offset > 0)
792 	    n = offset / 32767 + 1;
793 	  else
794 	    n = offset / -32768 + 1;
795 
796 	  /* Bail out immediately if relaxation has failed.  If we try to
797 	     defer the diagnostic to md_convert_frag, some pathological test
798 	     cases (e.g. gcc/testsuite/gcc.c-torture/compile/20001226-1.c)
799 	     apparently never converge.  By returning 0 here we could pretend
800 	     to the caller that nothing has changed, but that leaves things
801 	     in an inconsistent state when we get to md_convert_frag.  */
802 	  if (n > RELAX_MAX_ADDI)
803 	    {
804 	      as_bad_where (fragp->fr_file, fragp->fr_line,
805 			    _("branch offset out of range\n"));
806 	      as_fatal (_("branch relaxation failed\n"));
807 	    }
808 	}
809       else
810 	/* We cannot handle this case, diagnose overflow later.  */
811 	return 0;
812 
813       if (IS_CBRANCH (subtype))
814 	fragp->fr_subtype = CBRANCH_SUBTYPE (n);
815       else
816 	fragp->fr_subtype = UBRANCH_SUBTYPE (n);
817 
818       return (nios2_relax_subtype_size (fragp->fr_subtype)
819 	      - nios2_relax_subtype_size (subtype));
820     }
821 
822   /* If we got here, it's probably an error.  */
823   return 0;
824 }
825 
826 
827 /* Complete fragp using the data from the relaxation pass. */
828 void
md_convert_frag(bfd * headers ATTRIBUTE_UNUSED,segT segment ATTRIBUTE_UNUSED,fragS * fragp)829 md_convert_frag (bfd *headers ATTRIBUTE_UNUSED, segT segment ATTRIBUTE_UNUSED,
830 		 fragS *fragp)
831 {
832   char *buffer = fragp->fr_literal + fragp->fr_fix;
833   relax_substateT subtype = fragp->fr_subtype;
834   int n = SUBTYPE_ADDIS (subtype);
835   addressT target = fragp->fr_offset;
836   symbolS *symbolp = fragp->fr_symbol;
837   offsetT offset;
838   unsigned int addend_mask, addi_mask;
839   offsetT addend, remainder;
840   int i;
841 
842   /* If we didn't or can't relax, this is a regular branch instruction.
843      We just need to generate the fixup for the symbol and offset.  */
844   if (n == 0)
845     {
846       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset, 1,
847 	       BFD_RELOC_16_PCREL);
848       fragp->fr_fix += 4;
849       return;
850     }
851 
852   /* Replace the cbranch at fr_fix with one that has the opposite condition
853      in order to jump around the block of instructions we'll be adding.  */
854   if (IS_CBRANCH (subtype))
855     {
856       unsigned int br_opcode;
857       unsigned int old_op, new_op;
858       int nbytes;
859 
860       /* Account for the nextpc and jmp in the pc-relative case, or the two
861 	 load instructions and jump in the absolute case.  */
862       if (nios2_as_options.relax == relax_section)
863 	nbytes = (n + 2) * 4;
864       else
865 	nbytes = 12;
866 
867       br_opcode = md_chars_to_number (buffer, 4);
868       old_op = GET_IW_R1_OP (br_opcode);
869       switch (old_op)
870 	{
871 	case R1_OP_BEQ:
872 	  new_op = R1_OP_BNE;
873 	  break;
874 	case R1_OP_BNE:
875 	  new_op = R1_OP_BEQ;
876 	  break;
877 	case R1_OP_BGE:
878 	  new_op = R1_OP_BLT;
879 	  break;
880 	case R1_OP_BGEU:
881 	  new_op = R1_OP_BLTU;
882 	  break;
883 	case R1_OP_BLT:
884 	  new_op = R1_OP_BGE;
885 	  break;
886 	case R1_OP_BLTU:
887 	  new_op = R1_OP_BGEU;
888 	  break;
889 	default:
890 	  as_bad_where (fragp->fr_file, fragp->fr_line,
891 			_("expecting conditional branch for relaxation\n"));
892 	  abort ();
893 	}
894 
895       br_opcode = (br_opcode & ~IW_R1_OP_SHIFTED_MASK) | SET_IW_R1_OP (new_op);
896       br_opcode = br_opcode | SET_IW_I_IMM16 (nbytes);
897       md_number_to_chars (buffer, br_opcode, 4);
898       fragp->fr_fix += 4;
899       buffer += 4;
900     }
901 
902   /* Load at for the PC-relative case.  */
903   if (nios2_as_options.relax == relax_section)
904     {
905       /* Insert the nextpc instruction.  */
906       md_number_to_chars (buffer,
907 			  MATCH_R1_NEXTPC | SET_IW_R_C (AT_REGNUM), 4);
908       fragp->fr_fix += 4;
909       buffer += 4;
910 
911       /* We need to know whether the offset is positive or negative.  */
912       target += S_GET_VALUE (symbolp);
913       offset = target - fragp->fr_address - fragp->fr_fix;
914       if (offset > 0)
915 	addend = 32767;
916       else
917 	addend = -32768;
918       addend_mask = SET_IW_I_IMM16 ((unsigned int)addend);
919 
920       /* Insert n-1 addi instructions.  */
921       addi_mask = (MATCH_R1_ADDI
922 		   | SET_IW_I_B (AT_REGNUM)
923 		   | SET_IW_I_A (AT_REGNUM));
924       for (i = 0; i < n - 1; i ++)
925 	{
926 	  md_number_to_chars (buffer, addi_mask | addend_mask, 4);
927 	  fragp->fr_fix += 4;
928 	  buffer += 4;
929 	}
930 
931       /* Insert the last addi instruction to hold the remainder.  */
932       remainder = offset - addend * (n - 1);
933       gas_assert (remainder >= -32768 && remainder <= 32767);
934       addend_mask = SET_IW_I_IMM16 ((unsigned int)remainder);
935       md_number_to_chars (buffer, addi_mask | addend_mask, 4);
936       fragp->fr_fix += 4;
937       buffer += 4;
938     }
939 
940   /* Load at for the absolute case.  */
941   else
942     {
943       md_number_to_chars (buffer,
944 			  (MATCH_R1_ORHI | SET_IW_I_B (AT_REGNUM)
945 			   | SET_IW_I_A (0)),
946 			  4);
947       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset,
948 	       0, BFD_RELOC_NIOS2_HI16);
949       fragp->fr_fix += 4;
950       buffer += 4;
951       md_number_to_chars (buffer,
952 			  (MATCH_R1_ORI | SET_IW_I_B (AT_REGNUM)
953 			   | SET_IW_I_A (AT_REGNUM)),
954 			  4);
955       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset,
956 	       0, BFD_RELOC_NIOS2_LO16);
957       fragp->fr_fix += 4;
958       buffer += 4;
959     }
960 
961   /* Insert the jmp instruction.  */
962   md_number_to_chars (buffer, MATCH_R1_JMP | SET_IW_R_A (AT_REGNUM), 4);
963   fragp->fr_fix += 4;
964   buffer += 4;
965 }
966 
967 
968 /** Fixups and overflow checking.  */
969 
970 /* Check a fixup for overflow. */
971 static bfd_boolean
nios2_check_overflow(valueT fixup,reloc_howto_type * howto)972 nios2_check_overflow (valueT fixup, reloc_howto_type *howto)
973 {
974   /* Apply the rightshift before checking for overflow.  */
975   fixup = ((signed)fixup) >> howto->rightshift;
976 
977   /* Check for overflow - return TRUE if overflow, FALSE if not.  */
978   switch (howto->complain_on_overflow)
979     {
980     case complain_overflow_dont:
981       break;
982     case complain_overflow_bitfield:
983       if ((fixup >> howto->bitsize) != 0
984 	  && ((signed) fixup >> howto->bitsize) != -1)
985 	return TRUE;
986       break;
987     case complain_overflow_signed:
988       if ((fixup & 0x80000000) > 0)
989 	{
990 	  /* Check for negative overflow.  */
991 	  if ((signed) fixup < ((signed) 0x80000000 >> howto->bitsize))
992 	    return TRUE;
993 	}
994       else
995 	{
996 	  /* Check for positive overflow.  */
997 	  if (fixup >= ((unsigned) 1 << (howto->bitsize - 1)))
998 	    return TRUE;
999 	}
1000       break;
1001     case complain_overflow_unsigned:
1002       if ((fixup >> howto->bitsize) != 0)
1003 	return TRUE;
1004       break;
1005     default:
1006       as_bad (_("error checking for overflow - broken assembler"));
1007       break;
1008     }
1009   return FALSE;
1010 }
1011 
1012 /* Emit diagnostic for fixup overflow.  */
1013 static void
nios2_diagnose_overflow(valueT fixup,reloc_howto_type * howto,fixS * fixP,valueT value)1014 nios2_diagnose_overflow (valueT fixup, reloc_howto_type *howto,
1015 			 fixS *fixP, valueT value)
1016 {
1017   if (fixP->fx_r_type == BFD_RELOC_8
1018       || fixP->fx_r_type == BFD_RELOC_16
1019       || fixP->fx_r_type == BFD_RELOC_32)
1020     /* These relocs are against data, not instructions.  */
1021     as_bad_where (fixP->fx_file, fixP->fx_line,
1022 		  _("immediate value 0x%x truncated to 0x%x"),
1023 		  (unsigned int) fixup,
1024 		  (unsigned int) (~(~(valueT) 0 << howto->bitsize) & fixup));
1025   else
1026     {
1027       /* What opcode is the instruction?  This will determine
1028 	 whether we check for overflow in immediate values
1029 	 and what error message we get.  */
1030       const struct nios2_opcode *opcode;
1031       enum overflow_type overflow_msg_type;
1032       unsigned int range_min;
1033       unsigned int range_max;
1034       unsigned int address;
1035 
1036       opcode = nios2_find_opcode_hash (value, bfd_get_mach (stdoutput));
1037       gas_assert (opcode);
1038       gas_assert (fixP->fx_size == opcode->size);
1039       overflow_msg_type = opcode->overflow_msg;
1040       switch (overflow_msg_type)
1041 	{
1042 	case call_target_overflow:
1043 	  range_min
1044 	    = ((fixP->fx_frag->fr_address + fixP->fx_where) & 0xf0000000);
1045 	  range_max = range_min + 0x0fffffff;
1046 	  address = fixup | range_min;
1047 
1048 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1049 			_("call target address 0x%08x out of range 0x%08x to 0x%08x"),
1050 			address, range_min, range_max);
1051 	  break;
1052 	case branch_target_overflow:
1053 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1054 			_("branch offset %d out of range %d to %d"),
1055 			(int)fixup, -32768, 32767);
1056 	  break;
1057 	case address_offset_overflow:
1058 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1059 			_("%s offset %d out of range %d to %d"),
1060 			opcode->name, (int)fixup, -32768, 32767);
1061 	  break;
1062 	case signed_immed16_overflow:
1063 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1064 			_("immediate value %d out of range %d to %d"),
1065 			(int)fixup, -32768, 32767);
1066 	  break;
1067 	case unsigned_immed16_overflow:
1068 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1069 			_("immediate value %u out of range %u to %u"),
1070 			(unsigned int)fixup, 0, 65535);
1071 	  break;
1072 	case unsigned_immed5_overflow:
1073 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1074 			_("immediate value %u out of range %u to %u"),
1075 			(unsigned int)fixup, 0, 31);
1076 	  break;
1077 	case custom_opcode_overflow:
1078 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1079 			_("custom instruction opcode %u out of range %u to %u"),
1080 			(unsigned int)fixup, 0, 255);
1081 	  break;
1082 	default:
1083 	  as_bad_where (fixP->fx_file, fixP->fx_line,
1084 			_("overflow in immediate argument"));
1085 	  break;
1086 	}
1087     }
1088 }
1089 
1090 /* Apply a fixup to the object file.  */
1091 void
md_apply_fix(fixS * fixP,valueT * valP,segT seg ATTRIBUTE_UNUSED)1092 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
1093 {
1094   /* Assert that the fixup is one we can handle.  */
1095   gas_assert (fixP != NULL && valP != NULL
1096 	      && (fixP->fx_r_type == BFD_RELOC_8
1097 		  || fixP->fx_r_type == BFD_RELOC_16
1098 		  || fixP->fx_r_type == BFD_RELOC_32
1099 		  || fixP->fx_r_type == BFD_RELOC_64
1100 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_S16
1101 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_U16
1102 		  || fixP->fx_r_type == BFD_RELOC_16_PCREL
1103 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL26
1104 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM5
1105 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CACHE_OPX
1106 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM6
1107 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM8
1108 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_HI16
1109 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_LO16
1110 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_HIADJ16
1111 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GPREL
1112 		  || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
1113 		  || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
1114 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_UJMP
1115 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CJMP
1116 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALLR
1117 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_ALIGN
1118 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT16
1119 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL16
1120 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_LO
1121 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_HA
1122 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_GD16
1123 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LDM16
1124 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LDO16
1125 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_IE16
1126 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LE16
1127 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF
1128 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPREL
1129 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL26_NOAT
1130 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT_LO
1131 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT_HA
1132 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL_LO
1133 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL_HA
1134 		  /* Add other relocs here as we generate them.  */
1135 		  ));
1136 
1137   if (fixP->fx_r_type == BFD_RELOC_64)
1138     {
1139       /* We may reach here due to .8byte directives, but we never output
1140 	 BFD_RELOC_64; it must be resolved.  */
1141       if (fixP->fx_addsy != NULL)
1142 	as_bad_where (fixP->fx_file, fixP->fx_line,
1143 		      _("cannot create 64-bit relocation"));
1144       else
1145 	{
1146 	  md_number_to_chars (fixP->fx_frag->fr_literal + fixP->fx_where,
1147 			      *valP, 8);
1148 	  fixP->fx_done = 1;
1149 	}
1150       return;
1151     }
1152 
1153   /* The value passed in valP can be the value of a fully
1154      resolved expression, or it can be the value of a partially
1155      resolved expression.  In the former case, both fixP->fx_addsy
1156      and fixP->fx_subsy are NULL, and fixP->fx_offset == *valP, and
1157      we can fix up the instruction that fixP relates to.
1158      In the latter case, one or both of fixP->fx_addsy and
1159      fixP->fx_subsy are not NULL, and fixP->fx_offset may or may not
1160      equal *valP.  We don't need to check for fixP->fx_subsy being null
1161      because the generic part of the assembler generates an error if
1162      it is not an absolute symbol.  */
1163   if (fixP->fx_addsy != NULL)
1164     /* Partially resolved expression.  */
1165     {
1166       fixP->fx_addnumber = fixP->fx_offset;
1167       fixP->fx_done = 0;
1168 
1169       switch (fixP->fx_r_type)
1170 	{
1171 	case BFD_RELOC_NIOS2_TLS_GD16:
1172 	case BFD_RELOC_NIOS2_TLS_LDM16:
1173 	case BFD_RELOC_NIOS2_TLS_LDO16:
1174 	case BFD_RELOC_NIOS2_TLS_IE16:
1175 	case BFD_RELOC_NIOS2_TLS_LE16:
1176 	case BFD_RELOC_NIOS2_TLS_DTPMOD:
1177 	case BFD_RELOC_NIOS2_TLS_DTPREL:
1178 	case BFD_RELOC_NIOS2_TLS_TPREL:
1179 	  S_SET_THREAD_LOCAL (fixP->fx_addsy);
1180 	  break;
1181 	default:
1182 	  break;
1183 	}
1184     }
1185   else
1186     /* Fully resolved fixup.  */
1187     {
1188       reloc_howto_type *howto
1189 	= bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
1190 
1191       if (howto == NULL)
1192 	as_bad_where (fixP->fx_file, fixP->fx_line,
1193 		      _("relocation is not supported"));
1194       else
1195 	{
1196 	  valueT fixup = *valP;
1197 	  valueT value;
1198 	  char *buf;
1199 
1200 	  /* If this is a pc-relative relocation, we need to
1201 	     subtract the current offset within the object file
1202 	     FIXME : for some reason fixP->fx_pcrel isn't 1 when it should be
1203 	     so I'm using the howto structure instead to determine this.  */
1204 	  if (howto->pc_relative == 1)
1205 	    fixup = fixup - (fixP->fx_frag->fr_address + fixP->fx_where
1206 			     + fixP->fx_size);
1207 
1208 	  /* Get the instruction or data to be fixed up.  */
1209 	  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
1210 	  value = md_chars_to_number (buf, fixP->fx_size);
1211 
1212 	  /* Check for overflow, emitting a diagnostic if necessary.  */
1213 	  if (nios2_check_overflow (fixup, howto))
1214 	    nios2_diagnose_overflow (fixup, howto, fixP, value);
1215 
1216 	  /* Apply the right shift.  */
1217 	  fixup = ((signed)fixup) >> howto->rightshift;
1218 
1219 	  /* Truncate the fixup to right size.  */
1220 	  switch (fixP->fx_r_type)
1221 	    {
1222 	    case BFD_RELOC_NIOS2_HI16:
1223 	      fixup = (fixup >> 16) & 0xFFFF;
1224 	      break;
1225 	    case BFD_RELOC_NIOS2_LO16:
1226 	      fixup = fixup & 0xFFFF;
1227 	      break;
1228 	    case BFD_RELOC_NIOS2_HIADJ16:
1229 	      fixup = ((((fixup >> 16) & 0xFFFF) + ((fixup >> 15) & 0x01))
1230 		       & 0xFFFF);
1231 	      break;
1232 	    default:
1233 	      {
1234 		int n = sizeof (fixup) * 8 - howto->bitsize;
1235 		fixup = (fixup << n) >> n;
1236 		break;
1237 	      }
1238 	    }
1239 
1240 	  /* Fix up the instruction.  */
1241 	  value = (value & ~howto->dst_mask) | (fixup << howto->bitpos);
1242 	  md_number_to_chars (buf, value, fixP->fx_size);
1243 	}
1244 
1245       fixP->fx_done = 1;
1246     }
1247 
1248   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT)
1249     {
1250       fixP->fx_done = 0;
1251       if (fixP->fx_addsy
1252 	  && !S_IS_DEFINED (fixP->fx_addsy) && !S_IS_WEAK (fixP->fx_addsy))
1253 	S_SET_WEAK (fixP->fx_addsy);
1254     }
1255   else if (fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
1256     fixP->fx_done = 0;
1257 }
1258 
1259 
1260 
1261 /** Instruction parsing support. */
1262 
1263 /* General internal error routine.  */
1264 
1265 static void
bad_opcode(const struct nios2_opcode * op)1266 bad_opcode (const struct nios2_opcode *op)
1267 {
1268   fprintf (stderr, _("internal error: broken opcode descriptor for `%s %s'\n"),
1269 	   op->name, op->args);
1270   as_fatal (_("Broken assembler.  No assembly attempted."));
1271 }
1272 
1273 /* Special relocation directive strings.  */
1274 
1275 struct nios2_special_relocS
1276 {
1277   const char *string;
1278   bfd_reloc_code_real_type reloc_type;
1279 };
1280 
1281 /* This table is sorted so that prefix strings are listed after the longer
1282    strings that include them -- e.g., %got after %got_hiadj, etc.  */
1283 
1284 struct nios2_special_relocS nios2_special_reloc[] = {
1285   {"%hiadj", BFD_RELOC_NIOS2_HIADJ16},
1286   {"%hi", BFD_RELOC_NIOS2_HI16},
1287   {"%lo", BFD_RELOC_NIOS2_LO16},
1288   {"%gprel", BFD_RELOC_NIOS2_GPREL},
1289   {"%call_lo", BFD_RELOC_NIOS2_CALL_LO},
1290   {"%call_hiadj", BFD_RELOC_NIOS2_CALL_HA},
1291   {"%call", BFD_RELOC_NIOS2_CALL16},
1292   {"%gotoff_lo", BFD_RELOC_NIOS2_GOTOFF_LO},
1293   {"%gotoff_hiadj", BFD_RELOC_NIOS2_GOTOFF_HA},
1294   {"%gotoff", BFD_RELOC_NIOS2_GOTOFF},
1295   {"%got_hiadj", BFD_RELOC_NIOS2_GOT_HA},
1296   {"%got_lo", BFD_RELOC_NIOS2_GOT_LO},
1297   {"%got", BFD_RELOC_NIOS2_GOT16},
1298   {"%tls_gd", BFD_RELOC_NIOS2_TLS_GD16},
1299   {"%tls_ldm", BFD_RELOC_NIOS2_TLS_LDM16},
1300   {"%tls_ldo", BFD_RELOC_NIOS2_TLS_LDO16},
1301   {"%tls_ie", BFD_RELOC_NIOS2_TLS_IE16},
1302   {"%tls_le", BFD_RELOC_NIOS2_TLS_LE16},
1303 };
1304 
1305 #define NIOS2_NUM_SPECIAL_RELOCS \
1306 	(sizeof(nios2_special_reloc)/sizeof(nios2_special_reloc[0]))
1307 const int nios2_num_special_relocs = NIOS2_NUM_SPECIAL_RELOCS;
1308 
1309 /* Creates a new nios2_insn_relocS and returns a pointer to it.  */
1310 static nios2_insn_relocS *
nios2_insn_reloc_new(bfd_reloc_code_real_type reloc_type,unsigned int pcrel)1311 nios2_insn_reloc_new (bfd_reloc_code_real_type reloc_type, unsigned int pcrel)
1312 {
1313   nios2_insn_relocS *retval;
1314   retval = (nios2_insn_relocS *) malloc (sizeof (nios2_insn_relocS));
1315   if (retval == NULL)
1316     {
1317       as_bad (_("can't create relocation"));
1318       abort ();
1319     }
1320 
1321   /* Fill out the fields with default values.  */
1322   retval->reloc_next = NULL;
1323   retval->reloc_type = reloc_type;
1324   retval->reloc_pcrel = pcrel;
1325   return retval;
1326 }
1327 
1328 /* Frees up memory previously allocated by nios2_insn_reloc_new().  */
1329 /* FIXME:  this is never called; memory leak?  */
1330 #if 0
1331 static void
1332 nios2_insn_reloc_destroy (nios2_insn_relocS *reloc)
1333 {
1334   gas_assert (reloc != NULL);
1335   free (reloc);
1336 }
1337 #endif
1338 
1339 /* Look up a register name and validate it for the given regtype.
1340    Return the register mapping or NULL on failure.  */
1341 static struct nios2_reg *
nios2_parse_reg(const char * token,unsigned long regtype)1342 nios2_parse_reg (const char *token, unsigned long regtype)
1343 {
1344   struct nios2_reg *reg = nios2_reg_lookup (token);
1345 
1346   if (reg == NULL)
1347     {
1348       as_bad (_("unknown register %s"), token);
1349       return NULL;
1350     }
1351 
1352   /* Matched a register, but is it the wrong type?  */
1353   if (!(regtype & reg->regtype))
1354     {
1355       if (regtype & REG_CONTROL)
1356 	as_bad (_("expecting control register"));
1357       else if (reg->regtype & REG_CONTROL)
1358 	as_bad (_("illegal use of control register"));
1359       else if (reg->regtype & REG_COPROCESSOR)
1360 	as_bad (_("illegal use of coprocessor register"));
1361       else
1362 	as_bad (_("invalid register %s"), token);
1363       return NULL;
1364     }
1365 
1366   /* Warn for explicit use of special registers.  */
1367   if (reg->regtype & REG_NORMAL)
1368     {
1369       if (!nios2_as_options.noat && reg->index == 1)
1370 	as_warn (_("Register at (r1) can sometimes be corrupted by "
1371 		   "assembler optimizations.\n"
1372 		   "Use .set noat to turn off those optimizations "
1373 		   "(and this warning)."));
1374       if (!nios2_as_options.nobreak && reg->index == 25)
1375 	as_warn (_("The debugger will corrupt bt (r25).\n"
1376 		   "If you don't need to debug this "
1377 		   "code use .set nobreak to turn off this warning."));
1378       if (!nios2_as_options.nobreak && reg->index == 30)
1379 	as_warn (_("The debugger will corrupt sstatus/ba (r30).\n"
1380 		   "If you don't need to debug this "
1381 		   "code use .set nobreak to turn off this warning."));
1382     }
1383 
1384   return reg;
1385 }
1386 
1387 /* The various nios2_assemble_* functions call this
1388    function to generate an expression from a string representing an expression.
1389    It then tries to evaluate the expression, and if it can, returns its value.
1390    If not, it creates a new nios2_insn_relocS and stores the expression and
1391    reloc_type for future use.  */
1392 static unsigned long
nios2_assemble_expression(const char * exprstr,nios2_insn_infoS * insn,bfd_reloc_code_real_type reloc_type,unsigned int pcrel)1393 nios2_assemble_expression (const char *exprstr,
1394 			   nios2_insn_infoS *insn,
1395 			   bfd_reloc_code_real_type reloc_type,
1396 			   unsigned int pcrel)
1397 {
1398   nios2_insn_relocS *reloc;
1399   char *saved_line_ptr;
1400   unsigned short value;
1401   int i;
1402 
1403   gas_assert (exprstr != NULL);
1404   gas_assert (insn != NULL);
1405 
1406   /* Check for relocation operators.
1407      Change the relocation type and advance the ptr to the start of
1408      the expression proper. */
1409   for (i = 0; i < nios2_num_special_relocs; i++)
1410     if (strstr (exprstr, nios2_special_reloc[i].string) != NULL)
1411       {
1412 	reloc_type = nios2_special_reloc[i].reloc_type;
1413 	exprstr += strlen (nios2_special_reloc[i].string) + 1;
1414 
1415 	/* %lo and %hiadj have different meanings for PC-relative
1416 	   expressions.  */
1417 	if (pcrel)
1418 	  {
1419 	    if (reloc_type == BFD_RELOC_NIOS2_LO16)
1420 	      reloc_type = BFD_RELOC_NIOS2_PCREL_LO;
1421 	    if (reloc_type == BFD_RELOC_NIOS2_HIADJ16)
1422 	      reloc_type = BFD_RELOC_NIOS2_PCREL_HA;
1423 	  }
1424 
1425 	break;
1426       }
1427 
1428   /* We potentially have a relocation.  */
1429   reloc = nios2_insn_reloc_new (reloc_type, pcrel);
1430   reloc->reloc_next = insn->insn_reloc;
1431   insn->insn_reloc = reloc;
1432 
1433   /* Parse the expression string.  */
1434   saved_line_ptr = input_line_pointer;
1435   input_line_pointer = (char *) exprstr;
1436   expression (&reloc->reloc_expression);
1437   input_line_pointer = saved_line_ptr;
1438 
1439   /* This is redundant as the fixup will put this into
1440      the instruction, but it is included here so that
1441      self-test mode (-r) works.  */
1442   value = 0;
1443   if (nios2_mode == NIOS2_MODE_TEST
1444       && reloc->reloc_expression.X_op == O_constant)
1445     value = reloc->reloc_expression.X_add_number;
1446 
1447   return (unsigned long) value;
1448 }
1449 
1450 
1451 /* Argument assemble functions.  */
1452 static void
nios2_assemble_arg_c(const char * token,nios2_insn_infoS * insn)1453 nios2_assemble_arg_c (const char *token, nios2_insn_infoS *insn)
1454 {
1455   struct nios2_reg *reg = nios2_parse_reg (token, REG_CONTROL);
1456   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1457 
1458   if (reg == NULL)
1459     return;
1460 
1461   switch (op->format)
1462     {
1463     case iw_r_type:
1464       insn->insn_code |= SET_IW_R_IMM5 (reg->index);
1465       break;
1466     default:
1467       bad_opcode (op);
1468     }
1469 }
1470 
1471 static void
nios2_assemble_arg_d(const char * token,nios2_insn_infoS * insn)1472 nios2_assemble_arg_d (const char *token, nios2_insn_infoS *insn)
1473 {
1474   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1475   unsigned long regtype = REG_NORMAL;
1476   struct nios2_reg *reg;
1477 
1478   if (op->format == iw_custom_type)
1479     regtype |= REG_COPROCESSOR;
1480   reg = nios2_parse_reg (token, regtype);
1481   if (reg == NULL)
1482     return;
1483 
1484   switch (op->format)
1485     {
1486     case iw_r_type:
1487       insn->insn_code |= SET_IW_R_C (reg->index);
1488       break;
1489     case iw_custom_type:
1490       insn->insn_code |= SET_IW_CUSTOM_C (reg->index);
1491       if (reg->regtype & REG_COPROCESSOR)
1492 	insn->insn_code |= SET_IW_CUSTOM_READC (0);
1493       else
1494 	insn->insn_code |= SET_IW_CUSTOM_READC (1);
1495       break;
1496     default:
1497       bad_opcode (op);
1498     }
1499 }
1500 
1501 static void
nios2_assemble_arg_s(const char * token,nios2_insn_infoS * insn)1502 nios2_assemble_arg_s (const char *token, nios2_insn_infoS *insn)
1503 {
1504   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1505   unsigned long regtype = REG_NORMAL;
1506   struct nios2_reg *reg;
1507 
1508   if (op->format == iw_custom_type)
1509     regtype |= REG_COPROCESSOR;
1510   reg = nios2_parse_reg (token, regtype);
1511   if (reg == NULL)
1512     return;
1513 
1514   switch (op->format)
1515     {
1516     case iw_r_type:
1517       insn->insn_code |= SET_IW_R_A (reg->index);
1518       break;
1519     case iw_i_type:
1520       insn->insn_code |= SET_IW_I_A (reg->index);
1521       break;
1522     case iw_custom_type:
1523       insn->insn_code |= SET_IW_CUSTOM_A (reg->index);
1524       if (reg->regtype & REG_COPROCESSOR)
1525 	insn->insn_code |= SET_IW_CUSTOM_READA (0);
1526       else
1527 	insn->insn_code |= SET_IW_CUSTOM_READA (1);
1528       break;
1529     default:
1530       bad_opcode (op);
1531     }
1532 }
1533 
1534 static void
nios2_assemble_arg_t(const char * token,nios2_insn_infoS * insn)1535 nios2_assemble_arg_t (const char *token, nios2_insn_infoS *insn)
1536 {
1537   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1538   unsigned long regtype = REG_NORMAL;
1539   struct nios2_reg *reg;
1540 
1541   if (op->format == iw_custom_type)
1542     regtype |= REG_COPROCESSOR;
1543   reg = nios2_parse_reg (token, regtype);
1544   if (reg == NULL)
1545     return;
1546 
1547   switch (op->format)
1548     {
1549     case iw_r_type:
1550       insn->insn_code |= SET_IW_R_B (reg->index);
1551       break;
1552     case iw_i_type:
1553       insn->insn_code |= SET_IW_I_B (reg->index);
1554       break;
1555     case iw_custom_type:
1556       insn->insn_code |= SET_IW_CUSTOM_B (reg->index);
1557       if (reg->regtype & REG_COPROCESSOR)
1558 	insn->insn_code |= SET_IW_CUSTOM_READB (0);
1559       else
1560 	insn->insn_code |= SET_IW_CUSTOM_READB (1);
1561       break;
1562     default:
1563       bad_opcode (op);
1564     }
1565 }
1566 
1567 static void
nios2_assemble_arg_i(const char * token,nios2_insn_infoS * insn)1568 nios2_assemble_arg_i (const char *token, nios2_insn_infoS *insn)
1569 {
1570   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1571   unsigned int val;
1572 
1573   switch (op->format)
1574     {
1575     case iw_i_type:
1576       val = nios2_assemble_expression (token, insn,
1577 				       BFD_RELOC_NIOS2_S16, 0);
1578       insn->constant_bits |= SET_IW_I_IMM16 (val);
1579       break;
1580     default:
1581       bad_opcode (op);
1582     }
1583 }
1584 
1585 static void
nios2_assemble_arg_u(const char * token,nios2_insn_infoS * insn)1586 nios2_assemble_arg_u (const char *token, nios2_insn_infoS *insn)
1587 {
1588   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1589   unsigned int val;
1590 
1591   switch (op->format)
1592     {
1593     case iw_i_type:
1594       val = nios2_assemble_expression (token, insn,
1595 				       BFD_RELOC_NIOS2_U16, 0);
1596       insn->constant_bits |= SET_IW_I_IMM16 (val);
1597       break;
1598     default:
1599       bad_opcode (op);
1600     }
1601 }
1602 
1603 static void
nios2_assemble_arg_o(const char * token,nios2_insn_infoS * insn)1604 nios2_assemble_arg_o (const char *token, nios2_insn_infoS *insn)
1605 {
1606   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1607   unsigned int val;
1608 
1609   switch (op->format)
1610     {
1611     case iw_i_type:
1612       val = nios2_assemble_expression (token, insn,
1613 				       BFD_RELOC_16_PCREL, 1);
1614       insn->constant_bits |= SET_IW_I_IMM16 (val);
1615       break;
1616     default:
1617       bad_opcode (op);
1618     }
1619 }
1620 
1621 static void
nios2_assemble_arg_j(const char * token,nios2_insn_infoS * insn)1622 nios2_assemble_arg_j (const char *token, nios2_insn_infoS *insn)
1623 {
1624   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1625   unsigned int val;
1626 
1627   switch (op->format)
1628     {
1629     case iw_r_type:
1630       val = nios2_assemble_expression (token, insn,
1631 				       BFD_RELOC_NIOS2_IMM5, 0);
1632       insn->constant_bits |= SET_IW_R_IMM5 (val);
1633       break;
1634     default:
1635       bad_opcode (op);
1636     }
1637 }
1638 
1639 static void
nios2_assemble_arg_l(const char * token,nios2_insn_infoS * insn)1640 nios2_assemble_arg_l (const char *token, nios2_insn_infoS *insn)
1641 {
1642   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1643   unsigned int val;
1644 
1645   switch (op->format)
1646     {
1647     case iw_custom_type:
1648       val = nios2_assemble_expression (token, insn,
1649 				       BFD_RELOC_NIOS2_IMM8, 0);
1650       insn->constant_bits |= SET_IW_CUSTOM_N (val);
1651       break;
1652     default:
1653       bad_opcode (op);
1654     }
1655 }
1656 
1657 static void
nios2_assemble_arg_m(const char * token,nios2_insn_infoS * insn)1658 nios2_assemble_arg_m (const char *token, nios2_insn_infoS *insn)
1659 {
1660   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1661   unsigned int val;
1662 
1663   switch (op->format)
1664     {
1665     case iw_j_type:
1666       val = nios2_assemble_expression (token, insn,
1667 				       (nios2_as_options.noat
1668 					? BFD_RELOC_NIOS2_CALL26_NOAT
1669 					: BFD_RELOC_NIOS2_CALL26),
1670 				       0);
1671       insn->constant_bits |= SET_IW_J_IMM26 (val);
1672       break;
1673     default:
1674       bad_opcode (op);
1675     }
1676 }
1677 
1678 static void
nios2_assemble_args(nios2_insn_infoS * insn)1679 nios2_assemble_args (nios2_insn_infoS *insn)
1680 {
1681   const struct nios2_opcode *op = insn->insn_nios2_opcode;
1682   const char *argptr;
1683   unsigned int tokidx, ntok;
1684 
1685   /* Make sure there are enough arguments.  */
1686   ntok = (op->pinfo & NIOS2_INSN_OPTARG) ? op->num_args - 1 : op->num_args;
1687   for (tokidx = 1; tokidx <= ntok; tokidx++)
1688     if (insn->insn_tokens[tokidx] == NULL)
1689       {
1690 	as_bad ("missing argument");
1691 	return;
1692       }
1693 
1694   for (argptr = op->args, tokidx = 1;
1695        *argptr && insn->insn_tokens[tokidx];
1696        argptr++)
1697     switch (*argptr)
1698       {
1699       case ',':
1700       case '(':
1701       case ')':
1702 	break;
1703 
1704       case 'c':
1705 	nios2_assemble_arg_c (insn->insn_tokens[tokidx++], insn);
1706 	break;
1707 
1708       case 'd':
1709 	nios2_assemble_arg_d (insn->insn_tokens[tokidx++], insn);
1710 	break;
1711 
1712       case 's':
1713 	nios2_assemble_arg_s (insn->insn_tokens[tokidx++], insn);
1714 	break;
1715 
1716       case 't':
1717 	nios2_assemble_arg_t (insn->insn_tokens[tokidx++], insn);
1718 	break;
1719 
1720       case 'i':
1721 	nios2_assemble_arg_i (insn->insn_tokens[tokidx++], insn);
1722 	break;
1723 
1724       case 'u':
1725 	nios2_assemble_arg_u (insn->insn_tokens[tokidx++], insn);
1726 	break;
1727 
1728       case 'o':
1729 	nios2_assemble_arg_o (insn->insn_tokens[tokidx++], insn);
1730 	break;
1731 
1732       case 'j':
1733 	nios2_assemble_arg_j (insn->insn_tokens[tokidx++], insn);
1734 	break;
1735 
1736       case 'l':
1737 	nios2_assemble_arg_l (insn->insn_tokens[tokidx++], insn);
1738 	break;
1739 
1740       case 'm':
1741 	nios2_assemble_arg_m (insn->insn_tokens[tokidx++], insn);
1742 	break;
1743 
1744       default:
1745 	bad_opcode (op);
1746 	break;
1747       }
1748 
1749   /* Perform argument checking.  */
1750   nios2_check_assembly (insn->insn_code | insn->constant_bits,
1751 			insn->insn_tokens[tokidx]);
1752 }
1753 
1754 
1755 /* The function consume_arg takes a pointer into a string
1756    of instruction tokens (args) and a pointer into a string
1757    representing the expected sequence of tokens and separators.
1758    It checks whether the first argument in argstr is of the
1759    expected type, throwing an error if it is not, and returns
1760    the pointer argstr.  */
1761 static char *
nios2_consume_arg(char * argstr,const char * parsestr)1762 nios2_consume_arg (char *argstr, const char *parsestr)
1763 {
1764   char *temp;
1765 
1766   switch (*parsestr)
1767     {
1768     case 'c':
1769     case 'd':
1770     case 's':
1771     case 't':
1772       break;
1773 
1774     case 'i':
1775     case 'u':
1776       if (*argstr == '%')
1777 	{
1778 	  if (nios2_special_relocation_p (argstr))
1779 	    {
1780 	      /* We zap the parentheses because we don't want them confused
1781 		 with separators.  */
1782 	      temp = strchr (argstr, '(');
1783 	      if (temp != NULL)
1784 		*temp = ' ';
1785 	      temp = strchr (argstr, ')');
1786 	      if (temp != NULL)
1787 		*temp = ' ';
1788 	    }
1789 	  else
1790 	    as_bad (_("badly formed expression near %s"), argstr);
1791 	}
1792       break;
1793     case 'm':
1794     case 'j':
1795     case 'l':
1796       /* We can't have %hi, %lo or %hiadj here.  */
1797       if (*argstr == '%')
1798 	as_bad (_("badly formed expression near %s"), argstr);
1799       break;
1800     case 'o':
1801     case 'E':
1802       break;
1803     default:
1804       BAD_CASE (*parsestr);
1805       break;
1806     }
1807 
1808   return argstr;
1809 }
1810 
1811 /* The function consume_separator takes a pointer into a string
1812    of instruction tokens (args) and a pointer into a string representing
1813    the expected sequence of tokens and separators.  It finds the first
1814    instance of the character pointed to by separator in argstr, and
1815    returns a pointer to the next element of argstr, which is the
1816    following token in the sequence.  */
1817 static char *
nios2_consume_separator(char * argstr,const char * separator)1818 nios2_consume_separator (char *argstr, const char *separator)
1819 {
1820   char *p;
1821 
1822   /* If we have a opcode reg, expr(reg) type instruction, and
1823    * we are separating the expr from the (reg), we find the last
1824    * (, just in case the expression has parentheses.  */
1825 
1826   if (*separator == '(')
1827     p = strrchr (argstr, *separator);
1828   else
1829     p = strchr (argstr, *separator);
1830 
1831   if (p != NULL)
1832     *p++ = 0;
1833   return p;
1834 }
1835 
1836 
1837 /* The principal argument parsing function which takes a string argstr
1838    representing the instruction arguments for insn, and extracts the argument
1839    tokens matching parsestr into parsed_args.  */
1840 static void
nios2_parse_args(nios2_insn_infoS * insn,char * argstr,const char * parsestr,char ** parsed_args)1841 nios2_parse_args (nios2_insn_infoS *insn, char *argstr,
1842 		  const char *parsestr, char **parsed_args)
1843 {
1844   char *p;
1845   char *end = NULL;
1846   int i;
1847   p = argstr;
1848   i = 0;
1849   bfd_boolean terminate = FALSE;
1850 
1851   /* This rest of this function is it too fragile and it mostly works,
1852      therefore special case this one.  */
1853   if (*parsestr == 0 && argstr != 0)
1854     {
1855       as_bad (_("too many arguments"));
1856       parsed_args[0] = NULL;
1857       return;
1858     }
1859 
1860   while (p != NULL && !terminate && i < NIOS2_MAX_INSN_TOKENS)
1861     {
1862       parsed_args[i] = nios2_consume_arg (p, parsestr);
1863       ++parsestr;
1864       while (*parsestr == '(' || *parsestr == ')' || *parsestr == ',')
1865 	{
1866 	  char *context = p;
1867 	  p = nios2_consume_separator (p, parsestr);
1868 	  /* Check for missing separators.  */
1869 	  if (!p && !(insn->insn_nios2_opcode->pinfo & NIOS2_INSN_OPTARG))
1870 	    {
1871 	      as_bad (_("expecting %c near %s"), *parsestr, context);
1872 	      break;
1873 	    }
1874 	  ++parsestr;
1875 	}
1876 
1877       if (*parsestr == '\0')
1878 	{
1879 	  /* Check that the argument string has no trailing arguments.  */
1880 	  end = strpbrk (p, ",");
1881 	  if (end != NULL)
1882 	    as_bad (_("too many arguments"));
1883 	}
1884 
1885       if (*parsestr == '\0' || (p != NULL && *p == '\0'))
1886 	terminate = TRUE;
1887       ++i;
1888     }
1889 
1890   parsed_args[i] = NULL;
1891 }
1892 
1893 
1894 
1895 /** Support for pseudo-op parsing.  These are macro-like opcodes that
1896     expand into real insns by suitable fiddling with the operands.  */
1897 
1898 /* Append the string modifier to the string contained in the argument at
1899    parsed_args[ndx].  */
1900 static void
nios2_modify_arg(char ** parsed_args,const char * modifier,int unused ATTRIBUTE_UNUSED,int ndx)1901 nios2_modify_arg (char **parsed_args, const char *modifier,
1902 		  int unused ATTRIBUTE_UNUSED, int ndx)
1903 {
1904   char *tmp = parsed_args[ndx];
1905 
1906   parsed_args[ndx]
1907     = (char *) malloc (strlen (parsed_args[ndx]) + strlen (modifier) + 1);
1908   strcpy (parsed_args[ndx], tmp);
1909   strcat (parsed_args[ndx], modifier);
1910 }
1911 
1912 /* Modify parsed_args[ndx] by negating that argument.  */
1913 static void
nios2_negate_arg(char ** parsed_args,const char * modifier ATTRIBUTE_UNUSED,int unused ATTRIBUTE_UNUSED,int ndx)1914 nios2_negate_arg (char **parsed_args, const char *modifier ATTRIBUTE_UNUSED,
1915 		  int unused ATTRIBUTE_UNUSED, int ndx)
1916 {
1917   char *tmp = parsed_args[ndx];
1918 
1919   parsed_args[ndx]
1920     = (char *) malloc (strlen ("~(") + strlen (parsed_args[ndx]) +
1921 		       strlen (")+1") + 1);
1922 
1923   strcpy (parsed_args[ndx], "~(");
1924   strcat (parsed_args[ndx], tmp);
1925   strcat (parsed_args[ndx], ")+1");
1926 }
1927 
1928 /* The function nios2_swap_args swaps the pointers at indices index_1 and
1929    index_2 in the array parsed_args[] - this is used for operand swapping
1930    for comparison operations.  */
1931 static void
nios2_swap_args(char ** parsed_args,const char * unused ATTRIBUTE_UNUSED,int index_1,int index_2)1932 nios2_swap_args (char **parsed_args, const char *unused ATTRIBUTE_UNUSED,
1933 		 int index_1, int index_2)
1934 {
1935   char *tmp;
1936   gas_assert (index_1 < NIOS2_MAX_INSN_TOKENS
1937 	      && index_2 < NIOS2_MAX_INSN_TOKENS);
1938   tmp = parsed_args[index_1];
1939   parsed_args[index_1] = parsed_args[index_2];
1940   parsed_args[index_2] = tmp;
1941 }
1942 
1943 /* This function appends the string appnd to the array of strings in
1944    parsed_args num times starting at index start in the array.  */
1945 static void
nios2_append_arg(char ** parsed_args,const char * appnd,int num,int start)1946 nios2_append_arg (char **parsed_args, const char *appnd, int num,
1947 		  int start)
1948 {
1949   int i, count;
1950   char *tmp;
1951 
1952   gas_assert ((start + num) < NIOS2_MAX_INSN_TOKENS);
1953 
1954   if (nios2_mode == NIOS2_MODE_TEST)
1955     tmp = parsed_args[start];
1956   else
1957     tmp = NULL;
1958 
1959   for (i = start, count = num; count > 0; ++i, --count)
1960     parsed_args[i] = (char *) appnd;
1961 
1962   gas_assert (i == (start + num));
1963   parsed_args[i] = tmp;
1964   parsed_args[i + 1] = NULL;
1965 }
1966 
1967 /* This function inserts the string insert num times in the array
1968    parsed_args, starting at the index start.  */
1969 static void
nios2_insert_arg(char ** parsed_args,const char * insert,int num,int start)1970 nios2_insert_arg (char **parsed_args, const char *insert, int num,
1971 		  int start)
1972 {
1973   int i, count;
1974 
1975   gas_assert ((start + num) < NIOS2_MAX_INSN_TOKENS);
1976 
1977   /* Move the existing arguments up to create space.  */
1978   for (i = NIOS2_MAX_INSN_TOKENS; i - num >= start; --i)
1979     parsed_args[i] = parsed_args[i - num];
1980 
1981   for (i = start, count = num; count > 0; ++i, --count)
1982     parsed_args[i] = (char *) insert;
1983 }
1984 
1985 /* Cleanup function to free malloc'ed arg strings.  */
1986 static void
nios2_free_arg(char ** parsed_args,int num ATTRIBUTE_UNUSED,int start)1987 nios2_free_arg (char **parsed_args, int num ATTRIBUTE_UNUSED, int start)
1988 {
1989   if (parsed_args[start])
1990     {
1991       free (parsed_args[start]);
1992       parsed_args[start] = NULL;
1993     }
1994 }
1995 
1996 /* This function swaps the pseudo-op for a real op.  */
1997 static nios2_ps_insn_infoS*
nios2_translate_pseudo_insn(nios2_insn_infoS * insn)1998 nios2_translate_pseudo_insn (nios2_insn_infoS *insn)
1999 {
2000 
2001   nios2_ps_insn_infoS *ps_insn;
2002 
2003   /* Find which real insn the pseudo-op transates to and
2004      switch the insn_info ptr to point to it.  */
2005   ps_insn = nios2_ps_lookup (insn->insn_nios2_opcode->name);
2006 
2007   if (ps_insn != NULL)
2008     {
2009       insn->insn_nios2_opcode = nios2_opcode_lookup (ps_insn->insn);
2010       insn->insn_tokens[0] = insn->insn_nios2_opcode->name;
2011       /* Modify the args so they work with the real insn.  */
2012       ps_insn->arg_modifer_func ((char **) insn->insn_tokens,
2013 				 ps_insn->arg_modifier, ps_insn->num,
2014 				 ps_insn->index);
2015     }
2016   else
2017     /* we cannot recover from this.  */
2018     as_fatal (_("unrecognized pseudo-instruction %s"),
2019 	      ps_insn->pseudo_insn);
2020   return ps_insn;
2021 }
2022 
2023 /* Invoke the cleanup handler for pseudo-insn ps_insn on insn.  */
2024 static void
nios2_cleanup_pseudo_insn(nios2_insn_infoS * insn,nios2_ps_insn_infoS * ps_insn)2025 nios2_cleanup_pseudo_insn (nios2_insn_infoS *insn,
2026 			   nios2_ps_insn_infoS *ps_insn)
2027 {
2028   if (ps_insn->arg_cleanup_func)
2029     (ps_insn->arg_cleanup_func) ((char **) insn->insn_tokens,
2030 				 ps_insn->num, ps_insn->index);
2031 }
2032 
2033 const nios2_ps_insn_infoS nios2_ps_insn_info_structs[] = {
2034   /* pseudo-op, real-op, arg, arg_modifier_func, num, index, arg_cleanup_func */
2035   {"mov", "add", nios2_append_arg, "zero", 1, 3, NULL},
2036   {"movi", "addi", nios2_insert_arg, "zero", 1, 2, NULL},
2037   {"movhi", "orhi", nios2_insert_arg, "zero", 1, 2, NULL},
2038   {"movui", "ori", nios2_insert_arg, "zero", 1, 2, NULL},
2039   {"movia", "orhi", nios2_insert_arg, "zero", 1, 2, NULL},
2040   {"nop", "add", nios2_append_arg, "zero", 3, 1, NULL},
2041   {"bgt", "blt", nios2_swap_args, "", 1, 2, NULL},
2042   {"bgtu", "bltu", nios2_swap_args, "", 1, 2, NULL},
2043   {"ble", "bge", nios2_swap_args, "", 1, 2, NULL},
2044   {"bleu", "bgeu", nios2_swap_args, "", 1, 2, NULL},
2045   {"cmpgt", "cmplt", nios2_swap_args, "", 2, 3, NULL},
2046   {"cmpgtu", "cmpltu", nios2_swap_args, "", 2, 3, NULL},
2047   {"cmple", "cmpge", nios2_swap_args, "", 2, 3, NULL},
2048   {"cmpleu", "cmpgeu", nios2_swap_args, "", 2, 3, NULL},
2049   {"cmpgti", "cmpgei", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
2050   {"cmpgtui", "cmpgeui", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
2051   {"cmplei", "cmplti", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
2052   {"cmpleui", "cmpltui", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
2053   {"subi", "addi", nios2_negate_arg, "", 0, 3, nios2_free_arg}
2054   /* Add further pseudo-ops here.  */
2055 };
2056 
2057 #define NIOS2_NUM_PSEUDO_INSNS \
2058 	((sizeof(nios2_ps_insn_info_structs)/ \
2059 	  sizeof(nios2_ps_insn_info_structs[0])))
2060 const int nios2_num_ps_insn_info_structs = NIOS2_NUM_PSEUDO_INSNS;
2061 
2062 
2063 /** Assembler output support.  */
2064 
2065 static int
can_evaluate_expr(nios2_insn_infoS * insn)2066 can_evaluate_expr (nios2_insn_infoS *insn)
2067 {
2068   /* Remove this check for null and the invalid insn "ori r9, 1234" seg faults. */
2069   if (!insn->insn_reloc)
2070     /* ??? Ideally we should do something other than as_fatal here as we can
2071        continue to assemble.
2072        However this function (actually the output_* functions) should not
2073        have been called in the first place once an illegal instruction had
2074        been encountered.  */
2075     as_fatal (_("Invalid instruction encountered, cannot recover. No assembly attempted."));
2076 
2077   if (insn->insn_reloc->reloc_expression.X_op == O_constant)
2078     return 1;
2079 
2080   return 0;
2081 }
2082 
2083 static int
get_expr_value(nios2_insn_infoS * insn)2084 get_expr_value (nios2_insn_infoS *insn)
2085 {
2086   int value = 0;
2087 
2088   if (insn->insn_reloc->reloc_expression.X_op == O_constant)
2089     value = insn->insn_reloc->reloc_expression.X_add_number;
2090   return value;
2091 }
2092 
2093 /* Output a normal instruction.  */
2094 static void
output_insn(nios2_insn_infoS * insn)2095 output_insn (nios2_insn_infoS *insn)
2096 {
2097   char *f;
2098   nios2_insn_relocS *reloc;
2099   f = frag_more (insn->insn_nios2_opcode->size);
2100   /* This allocates enough space for the instruction
2101      and puts it in the current frag.  */
2102   md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
2103   /* Emit debug info.  */
2104   dwarf2_emit_insn (insn->insn_nios2_opcode->size);
2105   /* Create any fixups to be acted on later.  */
2106 
2107   for (reloc = insn->insn_reloc; reloc != NULL; reloc = reloc->reloc_next)
2108     fix_new_exp (frag_now, f - frag_now->fr_literal,
2109 		 insn->insn_nios2_opcode->size,
2110 		 &reloc->reloc_expression, reloc->reloc_pcrel,
2111 		 reloc->reloc_type);
2112 }
2113 
2114 /* Output an unconditional branch.  */
2115 static void
output_ubranch(nios2_insn_infoS * insn)2116 output_ubranch (nios2_insn_infoS *insn)
2117 {
2118   nios2_insn_relocS *reloc = insn->insn_reloc;
2119 
2120   /* If the reloc is NULL, there was an error assembling the branch.  */
2121   if (reloc != NULL)
2122     {
2123       symbolS *symp = reloc->reloc_expression.X_add_symbol;
2124       offsetT offset = reloc->reloc_expression.X_add_number;
2125       char *f;
2126 
2127       /* Tag dwarf2 debug info to the address at the start of the insn.
2128 	 We must do it before frag_var() below closes off the frag.  */
2129       dwarf2_emit_insn (0);
2130 
2131       /* We create a machine dependent frag which can grow
2132 	 to accommodate the largest possible instruction sequence
2133 	 this may generate.  */
2134       f = frag_var (rs_machine_dependent,
2135 		    UBRANCH_MAX_SIZE, insn->insn_nios2_opcode->size,
2136 		    UBRANCH_SUBTYPE (0), symp, offset, NULL);
2137 
2138       md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
2139 
2140       /* We leave fixup generation to md_convert_frag.  */
2141     }
2142 }
2143 
2144 /* Output a conditional branch.  */
2145 static void
output_cbranch(nios2_insn_infoS * insn)2146 output_cbranch (nios2_insn_infoS *insn)
2147 {
2148   nios2_insn_relocS *reloc = insn->insn_reloc;
2149 
2150   /* If the reloc is NULL, there was an error assembling the branch.  */
2151   if (reloc != NULL)
2152     {
2153       symbolS *symp = reloc->reloc_expression.X_add_symbol;
2154       offsetT offset = reloc->reloc_expression.X_add_number;
2155       char *f;
2156 
2157       /* Tag dwarf2 debug info to the address at the start of the insn.
2158 	 We must do it before frag_var() below closes off the frag.  */
2159       dwarf2_emit_insn (0);
2160 
2161       /* We create a machine dependent frag which can grow
2162 	 to accommodate the largest possible instruction sequence
2163 	 this may generate.  */
2164       f = frag_var (rs_machine_dependent,
2165 		    CBRANCH_MAX_SIZE, insn->insn_nios2_opcode->size,
2166 		    CBRANCH_SUBTYPE (0), symp, offset, NULL);
2167 
2168       md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
2169 
2170       /* We leave fixup generation to md_convert_frag.  */
2171     }
2172 }
2173 
2174 /* Output a call sequence.  Since calls are not pc-relative for NIOS2,
2175    but are page-relative, we cannot tell at any stage in assembly
2176    whether a call will be out of range since a section may be linked
2177    at any address.  So if we are relaxing, we convert all call instructions
2178    to long call sequences, and rely on the linker to relax them back to
2179    short calls.  */
2180 static void
output_call(nios2_insn_infoS * insn)2181 output_call (nios2_insn_infoS *insn)
2182 {
2183   /* This allocates enough space for the instruction
2184      and puts it in the current frag.  */
2185   char *f = frag_more (12);
2186   nios2_insn_relocS *reloc = insn->insn_reloc;
2187 
2188   md_number_to_chars (f,
2189 		      (MATCH_R1_ORHI | SET_IW_I_B (AT_REGNUM)
2190 		       | SET_IW_I_A (0)),
2191 		      4);
2192   dwarf2_emit_insn (4);
2193   fix_new_exp (frag_now, f - frag_now->fr_literal, 4,
2194 	       &reloc->reloc_expression, 0, BFD_RELOC_NIOS2_HI16);
2195   md_number_to_chars (f + 4,
2196 		      (MATCH_R1_ORI | SET_IW_I_B (AT_REGNUM)
2197 		       | SET_IW_I_A (AT_REGNUM)),
2198 		      4);
2199   dwarf2_emit_insn (4);
2200   fix_new_exp (frag_now, f - frag_now->fr_literal + 4, 4,
2201 	       &reloc->reloc_expression, 0, BFD_RELOC_NIOS2_LO16);
2202   md_number_to_chars (f + 8, MATCH_R1_CALLR | SET_IW_R_A (AT_REGNUM), 4);
2203   dwarf2_emit_insn (4);
2204 }
2205 
2206 /* Output an addi - will silently convert to
2207    orhi if rA = r0 and (expr & 0xffff0000) == 0.  */
2208 static void
output_addi(nios2_insn_infoS * insn)2209 output_addi (nios2_insn_infoS *insn)
2210 {
2211   if (can_evaluate_expr (insn))
2212     {
2213       int expr_val = get_expr_value (insn);
2214       unsigned int rega = GET_IW_I_A (insn->insn_code);
2215       unsigned int regb = GET_IW_I_B (insn->insn_code);
2216 
2217       if (rega == 0
2218 	  && (expr_val & 0xffff) == 0
2219 	  && expr_val != 0)
2220 	{
2221 	  /* We really want a movhi (orhi) here.  */
2222 	  insn->insn_code
2223 	    = MATCH_R1_ORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
2224 	  insn->insn_reloc->reloc_expression.X_add_number
2225 	    = (expr_val >> 16) & 0xffff;
2226 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
2227 	}
2228     }
2229 
2230   /* Output an instruction.  */
2231   output_insn (insn);
2232 }
2233 
2234 static void
output_andi(nios2_insn_infoS * insn)2235 output_andi (nios2_insn_infoS *insn)
2236 {
2237   if (can_evaluate_expr (insn))
2238     {
2239       int expr_val = get_expr_value (insn);
2240       if (expr_val != 0 && (expr_val & 0xffff) == 0)
2241 	{
2242 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
2243 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
2244 
2245 	  /* We really want an andhi here.  */
2246 	  insn->insn_code
2247 	    = MATCH_R1_ANDHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
2248 	  insn->insn_reloc->reloc_expression.X_add_number
2249 	    = (expr_val >> 16) & 0xffff;
2250 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
2251 	}
2252     }
2253 
2254   /* Output an instruction.  */
2255   output_insn (insn);
2256 }
2257 
2258 static void
output_ori(nios2_insn_infoS * insn)2259 output_ori (nios2_insn_infoS *insn)
2260 {
2261   if (can_evaluate_expr (insn))
2262     {
2263       int expr_val = get_expr_value (insn);
2264       if (expr_val != 0 && (expr_val & 0xffff) == 0)
2265 	{
2266 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
2267 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
2268 
2269 	  /* We really want a movhi (orhi) here.  */
2270 	  insn->insn_code
2271 	    = MATCH_R1_ORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
2272 	  insn->insn_reloc->reloc_expression.X_add_number
2273 	    = (expr_val >> 16) & 0xffff;
2274 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
2275 	}
2276     }
2277 
2278   /* Output an instruction.  */
2279   output_insn (insn);
2280 }
2281 
2282 static void
output_xori(nios2_insn_infoS * insn)2283 output_xori (nios2_insn_infoS *insn)
2284 {
2285   if (can_evaluate_expr (insn))
2286     {
2287       int expr_val = get_expr_value (insn);
2288       if (expr_val != 0 && (expr_val & 0xffff) == 0)
2289 	{
2290 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
2291 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
2292 
2293 	  /* We really want an xorhi here.  */
2294 	  insn->insn_code
2295 	    = MATCH_R1_XORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
2296 	  insn->insn_reloc->reloc_expression.X_add_number
2297 	    = (expr_val >> 16) & 0xffff;
2298 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
2299 	}
2300     }
2301 
2302   /* Output an instruction.  */
2303   output_insn (insn);
2304 }
2305 
2306 
2307 /* Output a movhi/addi pair for the movia pseudo-op.  */
2308 static void
output_movia(nios2_insn_infoS * insn)2309 output_movia (nios2_insn_infoS *insn)
2310 {
2311   /* This allocates enough space for the instruction
2312      and puts it in the current frag.  */
2313   char *f = frag_more (8);
2314   nios2_insn_relocS *reloc = insn->insn_reloc;
2315   unsigned long reg_index = GET_IW_I_B (insn->insn_code);
2316 
2317   /* If the reloc is NULL, there was an error assembling the movia.  */
2318   if (reloc != NULL)
2319     {
2320       md_number_to_chars (f, insn->insn_code, 4);
2321       dwarf2_emit_insn (4);
2322       fix_new (frag_now, f - frag_now->fr_literal, 4,
2323 	       reloc->reloc_expression.X_add_symbol,
2324 	       reloc->reloc_expression.X_add_number, 0,
2325 	       BFD_RELOC_NIOS2_HIADJ16);
2326       md_number_to_chars (f + 4,
2327 			  (MATCH_R1_ADDI | SET_IW_I_A (reg_index)
2328 			   | SET_IW_I_B (reg_index)),
2329 			  4);
2330       dwarf2_emit_insn (4);
2331       fix_new (frag_now, f + 4 - frag_now->fr_literal, 4,
2332 	       reloc->reloc_expression.X_add_symbol,
2333 	       reloc->reloc_expression.X_add_number, 0, BFD_RELOC_NIOS2_LO16);
2334     }
2335 }
2336 
2337 
2338 
2339 /** External interfaces.  */
2340 
2341 /* The following functions are called by machine-independent parts of
2342    the assembler. */
2343 int
md_parse_option(int c,char * arg ATTRIBUTE_UNUSED)2344 md_parse_option (int c, char *arg ATTRIBUTE_UNUSED)
2345 {
2346   switch (c)
2347     {
2348     case 'r':
2349       /* Hidden option for self-test mode.  */
2350       nios2_mode = NIOS2_MODE_TEST;
2351       break;
2352     case OPTION_RELAX_ALL:
2353       nios2_as_options.relax = relax_all;
2354       break;
2355     case OPTION_NORELAX:
2356       nios2_as_options.relax = relax_none;
2357       break;
2358     case OPTION_RELAX_SECTION:
2359       nios2_as_options.relax = relax_section;
2360       break;
2361     case OPTION_EB:
2362       target_big_endian = 1;
2363       break;
2364     case OPTION_EL:
2365       target_big_endian = 0;
2366       break;
2367     default:
2368       return 0;
2369       break;
2370     }
2371 
2372   return 1;
2373 }
2374 
2375 /* Implement TARGET_FORMAT.  We can choose to be big-endian or
2376    little-endian at runtime based on a switch.  */
2377 const char *
nios2_target_format(void)2378 nios2_target_format (void)
2379 {
2380   return target_big_endian ? "elf32-bignios2" : "elf32-littlenios2";
2381 }
2382 
2383 /* Machine-dependent usage message. */
2384 void
md_show_usage(FILE * stream)2385 md_show_usage (FILE *stream)
2386 {
2387   fprintf (stream, "	    NIOS2 options:\n"
2388 	   "  -relax-all	    replace all branch and call "
2389 	   "instructions with jmp and callr sequences\n"
2390 	   "  -relax-section	    replace identified out of range "
2391 	   "branches with jmp sequences (default)\n"
2392 	   "  -no-relax		    do not replace any branches or calls\n"
2393 	   "  -EB		    force big-endian byte ordering\n"
2394 	   "  -EL		    force little-endian byte ordering\n");
2395 }
2396 
2397 /* This function is called once, at assembler startup time.
2398    It should set up all the tables, etc. that the MD part of the
2399    assembler will need. */
2400 void
md_begin(void)2401 md_begin (void)
2402 {
2403   int i;
2404   const char *inserted;
2405 
2406   /* Create and fill a hashtable for the Nios II opcodes, registers and
2407      arguments.  */
2408   nios2_opcode_hash = hash_new ();
2409   nios2_reg_hash = hash_new ();
2410   nios2_ps_hash = hash_new ();
2411 
2412   for (i = 0; i < nios2_num_opcodes; ++i)
2413     {
2414       inserted
2415 	= hash_insert (nios2_opcode_hash, nios2_opcodes[i].name,
2416 		       (PTR) & nios2_opcodes[i]);
2417       if (inserted != NULL)
2418 	{
2419 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2420 		   nios2_opcodes[i].name, inserted);
2421 	  /* Probably a memory allocation problem?  Give up now.  */
2422 	  as_fatal (_("Broken assembler.  No assembly attempted."));
2423 	}
2424     }
2425 
2426   for (i = 0; i < nios2_num_regs; ++i)
2427     {
2428       inserted
2429 	= hash_insert (nios2_reg_hash, nios2_regs[i].name,
2430 		       (PTR) & nios2_regs[i]);
2431       if (inserted != NULL)
2432 	{
2433 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2434 		   nios2_regs[i].name, inserted);
2435 	  /* Probably a memory allocation problem?  Give up now.  */
2436 	  as_fatal (_("Broken assembler.  No assembly attempted."));
2437 	}
2438 
2439     }
2440 
2441   for (i = 0; i < nios2_num_ps_insn_info_structs; ++i)
2442     {
2443       inserted
2444 	= hash_insert (nios2_ps_hash, nios2_ps_insn_info_structs[i].pseudo_insn,
2445 		       (PTR) & nios2_ps_insn_info_structs[i]);
2446       if (inserted != NULL)
2447 	{
2448 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2449 		   nios2_ps_insn_info_structs[i].pseudo_insn, inserted);
2450 	  /* Probably a memory allocation problem?  Give up now.  */
2451 	  as_fatal (_("Broken assembler.  No assembly attempted."));
2452 	}
2453     }
2454 
2455   /* Assembler option defaults.  */
2456   nios2_as_options.noat = FALSE;
2457   nios2_as_options.nobreak = FALSE;
2458 
2459   /* Debug information is incompatible with relaxation.  */
2460   if (debug_type != DEBUG_UNSPECIFIED)
2461     nios2_as_options.relax = relax_none;
2462 
2463   /* Initialize the alignment data.  */
2464   nios2_current_align_seg = now_seg;
2465   nios2_last_label = NULL;
2466   nios2_current_align = 0;
2467 }
2468 
2469 
2470 /* Assembles a single line of Nios II assembly language.  */
2471 void
md_assemble(char * op_str)2472 md_assemble (char *op_str)
2473 {
2474   char *argstr;
2475   char *op_strdup = NULL;
2476   unsigned long saved_pinfo = 0;
2477   nios2_insn_infoS thisinsn;
2478   nios2_insn_infoS *insn = &thisinsn;
2479 
2480   /* Make sure we are aligned on a 4-byte boundary.  */
2481   if (nios2_current_align < 2)
2482     nios2_align (2, NULL, nios2_last_label);
2483   else if (nios2_current_align > 2)
2484     nios2_current_align = 2;
2485   nios2_last_label = NULL;
2486 
2487   /* We don't want to clobber to op_str
2488      because we want to be able to use it in messages.  */
2489   op_strdup = strdup (op_str);
2490   insn->insn_tokens[0] = strtok (op_strdup, " ");
2491   argstr = strtok (NULL, "");
2492 
2493   /* Assemble the opcode.  */
2494   insn->insn_nios2_opcode = nios2_opcode_lookup (insn->insn_tokens[0]);
2495   insn->insn_reloc = NULL;
2496 
2497   if (insn->insn_nios2_opcode != NULL)
2498     {
2499       nios2_ps_insn_infoS *ps_insn = NULL;
2500       /* Set the opcode for the instruction.  */
2501       insn->insn_code = insn->insn_nios2_opcode->match;
2502       insn->constant_bits = 0;
2503 
2504       /* Parse the arguments pointed to by argstr.  */
2505       if (nios2_mode == NIOS2_MODE_ASSEMBLE)
2506 	nios2_parse_args (insn, argstr, insn->insn_nios2_opcode->args,
2507 			  (char **) &insn->insn_tokens[1]);
2508       else
2509 	nios2_parse_args (insn, argstr, insn->insn_nios2_opcode->args_test,
2510 			  (char **) &insn->insn_tokens[1]);
2511 
2512       /* We need to preserve the MOVIA macro as this is clobbered by
2513 	 translate_pseudo_insn.  */
2514       if (insn->insn_nios2_opcode->pinfo == NIOS2_INSN_MACRO_MOVIA)
2515 	saved_pinfo = NIOS2_INSN_MACRO_MOVIA;
2516       /* If the instruction is an pseudo-instruction, we want to replace it
2517 	 with its real equivalent, and then continue.  */
2518       if ((insn->insn_nios2_opcode->pinfo & NIOS2_INSN_MACRO)
2519 	  == NIOS2_INSN_MACRO)
2520 	ps_insn = nios2_translate_pseudo_insn (insn);
2521 
2522       /* Assemble the parsed arguments into the instruction word.  */
2523       nios2_assemble_args (insn);
2524 
2525       /* Handle relaxation and other transformations.  */
2526       if (nios2_as_options.relax != relax_none
2527 	  && !nios2_as_options.noat
2528 	  && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_UBRANCH)
2529 	output_ubranch (insn);
2530       else if (nios2_as_options.relax != relax_none
2531 	       && !nios2_as_options.noat
2532 	       && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_CBRANCH)
2533 	output_cbranch (insn);
2534       else if (nios2_as_options.relax == relax_all
2535 	       && !nios2_as_options.noat
2536 	       && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_CALL
2537 	       && insn->insn_reloc
2538 	       && ((insn->insn_reloc->reloc_type
2539 		    == BFD_RELOC_NIOS2_CALL26)
2540 		   || (insn->insn_reloc->reloc_type
2541 		       == BFD_RELOC_NIOS2_CALL26_NOAT)))
2542 	output_call (insn);
2543       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ANDI)
2544 	output_andi (insn);
2545       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ORI)
2546 	output_ori (insn);
2547       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_XORI)
2548 	output_xori (insn);
2549       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ADDI)
2550 	output_addi (insn);
2551       else if (saved_pinfo == NIOS2_INSN_MACRO_MOVIA)
2552 	output_movia (insn);
2553       else
2554 	output_insn (insn);
2555       if (ps_insn)
2556 	nios2_cleanup_pseudo_insn (insn, ps_insn);
2557     }
2558   else
2559     /* Unrecognised instruction - error.  */
2560     as_bad (_("unrecognised instruction %s"), insn->insn_tokens[0]);
2561 
2562   /* Don't leak memory.  */
2563   free (op_strdup);
2564 }
2565 
2566 /* Round up section size.  */
2567 valueT
md_section_align(asection * seg ATTRIBUTE_UNUSED,valueT size)2568 md_section_align (asection *seg ATTRIBUTE_UNUSED, valueT size)
2569 {
2570   /* I think byte alignment is fine here.  */
2571   return size;
2572 }
2573 
2574 /* Implement TC_FORCE_RELOCATION.  */
2575 int
nios2_force_relocation(fixS * fixp)2576 nios2_force_relocation (fixS *fixp)
2577 {
2578   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2579       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY
2580       || fixp->fx_r_type == BFD_RELOC_NIOS2_ALIGN)
2581     return 1;
2582 
2583   return generic_force_reloc (fixp);
2584 }
2585 
2586 /* Implement tc_fix_adjustable.  */
2587 int
nios2_fix_adjustable(fixS * fixp)2588 nios2_fix_adjustable (fixS *fixp)
2589 {
2590   if (fixp->fx_addsy == NULL)
2591     return 1;
2592 
2593 #ifdef OBJ_ELF
2594   /* Prevent all adjustments to global symbols.  */
2595   if (OUTPUT_FLAVOR == bfd_target_elf_flavour
2596       && (S_IS_EXTERNAL (fixp->fx_addsy) || S_IS_WEAK (fixp->fx_addsy)))
2597     return 0;
2598 #endif
2599   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2600       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
2601     return 0;
2602 
2603   /* Preserve relocations against symbols with function type.  */
2604   if (symbol_get_bfdsym (fixp->fx_addsy)->flags & BSF_FUNCTION)
2605     return 0;
2606 
2607   /* Don't allow symbols to be discarded on GOT related relocs.  */
2608   if (fixp->fx_r_type == BFD_RELOC_NIOS2_GOT16
2609       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL16
2610       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_LO
2611       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_HA
2612       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_GD16
2613       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LDM16
2614       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LDO16
2615       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_IE16
2616       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LE16
2617       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPMOD
2618       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPREL
2619       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_TPREL
2620       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF
2621       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOT_LO
2622       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOT_HA
2623       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL_LO
2624       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL_HA
2625       )
2626     return 0;
2627 
2628   return 1;
2629 }
2630 
2631 /* Implement tc_frob_symbol.  This is called in adjust_reloc_syms;
2632    it is used to remove *ABS* references from the symbol table.  */
2633 int
nios2_frob_symbol(symbolS * symp)2634 nios2_frob_symbol (symbolS *symp)
2635 {
2636   if ((OUTPUT_FLAVOR == bfd_target_elf_flavour
2637        && symp == section_symbol (absolute_section))
2638       || !S_IS_DEFINED (symp))
2639     return 1;
2640   else
2641     return 0;
2642 }
2643 
2644 /* The function tc_gen_reloc creates a relocation structure for the
2645    fixup fixp, and returns a pointer to it.  This structure is passed
2646    to bfd_install_relocation so that it can be written to the object
2647    file for linking.  */
2648 arelent *
tc_gen_reloc(asection * section ATTRIBUTE_UNUSED,fixS * fixp)2649 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2650 {
2651   arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
2652   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2653   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2654 
2655   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2656   reloc->addend = fixp->fx_offset;  /* fixp->fx_addnumber; */
2657 
2658   if (fixp->fx_pcrel)
2659     {
2660       switch (fixp->fx_r_type)
2661 	{
2662 	case BFD_RELOC_16:
2663 	  fixp->fx_r_type = BFD_RELOC_16_PCREL;
2664 	  break;
2665 	case BFD_RELOC_NIOS2_LO16:
2666 	  fixp->fx_r_type = BFD_RELOC_NIOS2_PCREL_LO;
2667 	  break;
2668 	case BFD_RELOC_NIOS2_HIADJ16:
2669 	  fixp->fx_r_type = BFD_RELOC_NIOS2_PCREL_HA;
2670 	  break;
2671 	default:
2672 	  break;
2673 	}
2674     }
2675 
2676   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2677   if (reloc->howto == NULL)
2678     {
2679       as_bad_where (fixp->fx_file, fixp->fx_line,
2680 		    _("can't represent relocation type %s"),
2681 		    bfd_get_reloc_code_name (fixp->fx_r_type));
2682 
2683       /* Set howto to a garbage value so that we can keep going.  */
2684       reloc->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
2685       gas_assert (reloc->howto != NULL);
2686     }
2687   return reloc;
2688 }
2689 
2690 long
md_pcrel_from(fixS * fixP ATTRIBUTE_UNUSED)2691 md_pcrel_from (fixS *fixP ATTRIBUTE_UNUSED)
2692 {
2693   return 0;
2694 }
2695 
2696 /* Called just before the assembler exits.  */
2697 void
md_end()2698 md_end ()
2699 {
2700   /* FIXME - not yet implemented */
2701 }
2702 
2703 /* Under ELF we need to default _GLOBAL_OFFSET_TABLE.
2704    Otherwise we have no need to default values of symbols.  */
2705 symbolS *
md_undefined_symbol(char * name ATTRIBUTE_UNUSED)2706 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
2707 {
2708 #ifdef OBJ_ELF
2709   if (name[0] == '_' && name[1] == 'G'
2710       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
2711     {
2712       if (!GOT_symbol)
2713 	{
2714 	  if (symbol_find (name))
2715 	    as_bad ("GOT already in the symbol table");
2716 
2717 	  GOT_symbol = symbol_new (name, undefined_section,
2718 				   (valueT) 0, &zero_address_frag);
2719 	}
2720 
2721       return GOT_symbol;
2722     }
2723 #endif
2724 
2725   return 0;
2726 }
2727 
2728 /* Implement tc_frob_label.  */
2729 void
nios2_frob_label(symbolS * lab)2730 nios2_frob_label (symbolS *lab)
2731 {
2732   /* Emit dwarf information.  */
2733   dwarf2_emit_label (lab);
2734 
2735   /* Update the label's address with the current output pointer.  */
2736   symbol_set_frag (lab, frag_now);
2737   S_SET_VALUE (lab, (valueT) frag_now_fix ());
2738 
2739   /* Record this label for future adjustment after we find out what
2740      kind of data it references, and the required alignment therewith.  */
2741   nios2_last_label = lab;
2742 }
2743 
2744 /* Implement md_cons_align.  */
2745 void
nios2_cons_align(int size)2746 nios2_cons_align (int size)
2747 {
2748   int log_size = 0;
2749   const char *pfill = NULL;
2750 
2751   while ((size >>= 1) != 0)
2752     ++log_size;
2753 
2754   if (subseg_text_p (now_seg))
2755     pfill = (const char *) &nop;
2756   else
2757     pfill = NULL;
2758 
2759   if (nios2_auto_align_on)
2760     nios2_align (log_size, pfill, NULL);
2761 
2762   nios2_last_label = NULL;
2763 }
2764 
2765 /* Map 's' to SHF_NIOS2_GPREL.  */
2766 /* This is from the Alpha code tc-alpha.c.  */
2767 int
nios2_elf_section_letter(int letter,char ** ptr_msg)2768 nios2_elf_section_letter (int letter, char **ptr_msg)
2769 {
2770   if (letter == 's')
2771     return SHF_NIOS2_GPREL;
2772 
2773   *ptr_msg = _("Bad .section directive: want a,s,w,x,M,S,G,T in string");
2774   return -1;
2775 }
2776 
2777 /* Map SHF_ALPHA_GPREL to SEC_SMALL_DATA.  */
2778 /* This is from the Alpha code tc-alpha.c.  */
2779 flagword
nios2_elf_section_flags(flagword flags,int attr,int type ATTRIBUTE_UNUSED)2780 nios2_elf_section_flags (flagword flags, int attr, int type ATTRIBUTE_UNUSED)
2781 {
2782   if (attr & SHF_NIOS2_GPREL)
2783     flags |= SEC_SMALL_DATA;
2784   return flags;
2785 }
2786 
2787 /* Implement TC_PARSE_CONS_EXPRESSION to handle %tls_ldo(...) */
2788 bfd_reloc_code_real_type
nios2_cons(expressionS * exp,int size)2789 nios2_cons (expressionS *exp, int size)
2790 {
2791   bfd_reloc_code_real_type nios2_tls_ldo_reloc = BFD_RELOC_NONE;
2792 
2793   SKIP_WHITESPACE ();
2794   if (input_line_pointer[0] == '%')
2795     {
2796       if (strprefix (input_line_pointer + 1, "tls_ldo"))
2797 	{
2798 	  if (size != 4)
2799 	    as_bad (_("Illegal operands: %%tls_ldo in %d-byte data field"),
2800 		    size);
2801 	  else
2802 	    {
2803 	      input_line_pointer += 8;
2804 	      nios2_tls_ldo_reloc = BFD_RELOC_NIOS2_TLS_DTPREL;
2805 	    }
2806 	}
2807       if (nios2_tls_ldo_reloc != BFD_RELOC_NONE)
2808 	{
2809 	  SKIP_WHITESPACE ();
2810 	  if (input_line_pointer[0] != '(')
2811 	    as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
2812 	  else
2813 	    {
2814 	      int c;
2815 	      char *end = ++input_line_pointer;
2816 	      int npar = 0;
2817 
2818 	      for (c = *end; !is_end_of_line[c]; end++, c = *end)
2819 		if (c == '(')
2820 		  npar++;
2821 		else if (c == ')')
2822 		  {
2823 		    if (!npar)
2824 		      break;
2825 		    npar--;
2826 		  }
2827 
2828 	      if (c != ')')
2829 		as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
2830 	      else
2831 		{
2832 		  *end = '\0';
2833 		  expression (exp);
2834 		  *end = c;
2835 		  if (input_line_pointer != end)
2836 		    as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
2837 		  else
2838 		    {
2839 		      input_line_pointer++;
2840 		      SKIP_WHITESPACE ();
2841 		      c = *input_line_pointer;
2842 		      if (! is_end_of_line[c] && c != ',')
2843 			as_bad (_("Illegal operands: garbage after %%tls_ldo()"));
2844 		    }
2845 		}
2846 	    }
2847 	}
2848     }
2849   if (nios2_tls_ldo_reloc == BFD_RELOC_NONE)
2850     expression (exp);
2851   return nios2_tls_ldo_reloc;
2852 }
2853 
2854 /* Implement HANDLE_ALIGN.  */
2855 void
nios2_handle_align(fragS * fragp)2856 nios2_handle_align (fragS *fragp)
2857 {
2858   /* If we are expecting to relax in the linker, then we must output a
2859      relocation to tell the linker we are aligning code.  */
2860   if (nios2_as_options.relax == relax_all
2861       && (fragp->fr_type == rs_align || fragp->fr_type == rs_align_code)
2862       && fragp->fr_address + fragp->fr_fix > 0
2863       && fragp->fr_offset > 1
2864       && now_seg != bss_section)
2865     fix_new (fragp, fragp->fr_fix, 0, &abs_symbol, fragp->fr_offset, 0,
2866 	     BFD_RELOC_NIOS2_ALIGN);
2867 }
2868 
2869 /* Implement tc_regname_to_dw2regnum, to convert REGNAME to a DWARF-2
2870    register number.  */
2871 int
nios2_regname_to_dw2regnum(char * regname)2872 nios2_regname_to_dw2regnum (char *regname)
2873 {
2874   struct nios2_reg *r = nios2_reg_lookup (regname);
2875   if (r == NULL)
2876     return -1;
2877   return r->index;
2878 }
2879 
2880 /* Implement tc_cfi_frame_initial_instructions, to initialize the DWARF-2
2881    unwind information for this procedure.  */
2882 void
nios2_frame_initial_instructions(void)2883 nios2_frame_initial_instructions (void)
2884 {
2885   cfi_add_CFA_def_cfa (27, 0);
2886 }
2887