2000-08-04 Kazu Hirata <kazu@hxi.com>
[platform/upstream/binutils.git] / gas / config / tc-sparc.c
1 /* tc-sparc.c -- Assemble for the SPARC
2    Copyright (C) 1989, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000
3    Free Software Foundation, Inc.
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public
17    License along with GAS; see the file COPYING.  If not, write
18    to the Free Software Foundation, 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA. */
20
21 #include <stdio.h>
22 #include <ctype.h>
23
24 #include "as.h"
25 #include "subsegs.h"
26
27 #include "opcode/sparc.h"
28
29 #ifdef OBJ_ELF
30 #include "elf/sparc.h"
31 #endif
32
33 static struct sparc_arch *lookup_arch PARAMS ((char *));
34 static void init_default_arch PARAMS ((void));
35 static int sparc_ip PARAMS ((char *, const struct sparc_opcode **));
36 static int in_signed_range PARAMS ((bfd_signed_vma, bfd_signed_vma));
37 static int in_unsigned_range PARAMS ((bfd_vma, bfd_vma));
38 static int in_bitfield_range PARAMS ((bfd_signed_vma, bfd_signed_vma));
39 static int sparc_ffs PARAMS ((unsigned int));
40 static void synthetize_setuw PARAMS ((const struct sparc_opcode *));
41 static void synthetize_setsw PARAMS ((const struct sparc_opcode *));
42 static void synthetize_setx PARAMS ((const struct sparc_opcode *));
43 static bfd_vma BSR PARAMS ((bfd_vma, int));
44 static int cmp_reg_entry PARAMS ((const PTR, const PTR));
45 static int parse_keyword_arg PARAMS ((int (*) (const char *), char **, int *));
46 static int parse_const_expr_arg PARAMS ((char **, int *));
47 static int get_expression PARAMS ((char *str));
48
49 /* Default architecture.  */
50 /* ??? The default value should be V8, but sparclite support was added
51    by making it the default.  GCC now passes -Asparclite, so maybe sometime in
52    the future we can set this to V8.  */
53 #ifndef DEFAULT_ARCH
54 #define DEFAULT_ARCH "sparclite"
55 #endif
56 static char *default_arch = DEFAULT_ARCH;
57
58 /* Non-zero if the initial values of `max_architecture' and `sparc_arch_size'
59    have been set.  */
60 static int default_init_p;
61
62 /* Current architecture.  We don't bump up unless necessary.  */
63 static enum sparc_opcode_arch_val current_architecture = SPARC_OPCODE_ARCH_V6;
64
65 /* The maximum architecture level we can bump up to.
66    In a 32 bit environment, don't allow bumping up to v9 by default.
67    The native assembler works this way.  The user is required to pass
68    an explicit argument before we'll create v9 object files.  However, if
69    we don't see any v9 insns, a v8plus object file is not created.  */
70 static enum sparc_opcode_arch_val max_architecture;
71
72 /* Either 32 or 64, selects file format.  */
73 static int sparc_arch_size;
74 /* Initial (default) value, recorded separately in case a user option
75    changes the value before md_show_usage is called.  */
76 static int default_arch_size;
77
78 #ifdef OBJ_ELF
79 /* The currently selected v9 memory model.  Currently only used for
80    ELF.  */
81 static enum { MM_TSO, MM_PSO, MM_RMO } sparc_memory_model = MM_RMO;
82 #endif
83
84 static int architecture_requested;
85 static int warn_on_bump;
86
87 /* If warn_on_bump and the needed architecture is higher than this
88    architecture, issue a warning.  */
89 static enum sparc_opcode_arch_val warn_after_architecture;
90
91 /* Non-zero if as should generate error if an undeclared g[23] register
92    has been used in -64.  */
93 static int no_undeclared_regs;
94
95 /* Non-zero if we should try to relax jumps and calls.  */
96 static int sparc_relax;
97
98 /* Non-zero if we are generating PIC code.  */
99 int sparc_pic_code;
100
101 /* Non-zero if we should give an error when misaligned data is seen.  */
102 static int enforce_aligned_data;
103
104 extern int target_big_endian;
105
106 static int target_little_endian_data;
107
108 /* Symbols for global registers on v9.  */
109 static symbolS *globals[8];
110
111 /* V9 and 86x have big and little endian data, but instructions are always big
112    endian.  The sparclet has bi-endian support but both data and insns have
113    the same endianness.  Global `target_big_endian' is used for data.
114    The following macro is used for instructions.  */
115 #ifndef INSN_BIG_ENDIAN
116 #define INSN_BIG_ENDIAN (target_big_endian \
117                          || default_arch_type == sparc86x \
118                          || SPARC_OPCODE_ARCH_V9_P (max_architecture))
119 #endif
120
121 /* Handle of the OPCODE hash table.  */
122 static struct hash_control *op_hash;
123
124 static int log2 PARAMS ((int));
125 static void s_data1 PARAMS ((void));
126 static void s_seg PARAMS ((int));
127 static void s_proc PARAMS ((int));
128 static void s_reserve PARAMS ((int));
129 static void s_common PARAMS ((int));
130 static void s_empty PARAMS ((int));
131 static void s_uacons PARAMS ((int));
132 static void s_ncons PARAMS ((int));
133 static void s_register PARAMS ((int));
134
135 const pseudo_typeS md_pseudo_table[] =
136 {
137   {"align", s_align_bytes, 0},  /* Defaulting is invalid (0).  */
138   {"common", s_common, 0},
139   {"empty", s_empty, 0},
140   {"global", s_globl, 0},
141   {"half", cons, 2},
142   {"nword", s_ncons, 0},
143   {"optim", s_ignore, 0},
144   {"proc", s_proc, 0},
145   {"reserve", s_reserve, 0},
146   {"seg", s_seg, 0},
147   {"skip", s_space, 0},
148   {"word", cons, 4},
149   {"xword", cons, 8},
150   {"uahalf", s_uacons, 2},
151   {"uaword", s_uacons, 4},
152   {"uaxword", s_uacons, 8},
153 #ifdef OBJ_ELF
154   /* These are specific to sparc/svr4.  */
155   {"2byte", s_uacons, 2},
156   {"4byte", s_uacons, 4},
157   {"8byte", s_uacons, 8},
158   {"register", s_register, 0},
159 #endif
160   {NULL, 0, 0},
161 };
162
163 /* Size of relocation record.  */
164 const int md_reloc_size = 12;
165
166 /* This array holds the chars that always start a comment.  If the
167    pre-processor is disabled, these aren't very useful.  */
168 const char comment_chars[] = "!";       /* JF removed '|' from
169                                            comment_chars.  */
170
171 /* This array holds the chars that only start a comment at the beginning of
172    a line.  If the line seems to have the form '# 123 filename'
173    .line and .file directives will appear in the pre-processed output.  */
174 /* Note that input_file.c hand checks for '#' at the beginning of the
175    first line of the input file.  This is because the compiler outputs
176    #NO_APP at the beginning of its output.  */
177 /* Also note that comments started like this one will always
178    work if '/' isn't otherwise defined.  */
179 const char line_comment_chars[] = "#";
180
181 const char line_separator_chars[] = ";";
182
183 /* Chars that can be used to separate mant from exp in floating point
184    nums.  */
185 const char EXP_CHARS[] = "eE";
186
187 /* Chars that mean this number is a floating point constant.
188    As in 0f12.456
189    or    0d1.2345e12  */
190 const char FLT_CHARS[] = "rRsSfFdDxXpP";
191
192 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
193    changed in read.c.  Ideally it shouldn't have to know about it at all,
194    but nothing is ideal around here.  */
195
196 #define isoctal(c)  ((unsigned)((c) - '0') < '8')
197
198 struct sparc_it
199   {
200     char *error;
201     unsigned long opcode;
202     struct nlist *nlistp;
203     expressionS exp;
204     expressionS exp2;
205     int pcrel;
206     bfd_reloc_code_real_type reloc;
207   };
208
209 struct sparc_it the_insn, set_insn;
210
211 static void output_insn
212   PARAMS ((const struct sparc_opcode *, struct sparc_it *));
213 \f
214 /* Table of arguments to -A.
215    The sparc_opcode_arch table in sparc-opc.c is insufficient and incorrect
216    for this use.  That table is for opcodes only.  This table is for opcodes
217    and file formats.  */
218
219 enum sparc_arch_types {v6, v7, v8, sparclet, sparclite, sparc86x, v8plus,
220                        v8plusa, v9, v9a, v9_64};
221
222 static struct sparc_arch {
223   char *name;
224   char *opcode_arch;
225   enum sparc_arch_types arch_type;
226   /* Default word size, as specified during configuration.
227      A value of zero means can't be used to specify default architecture.  */
228   int default_arch_size;
229   /* Allowable arg to -A?  */
230   int user_option_p;
231 } sparc_arch_table[] = {
232   { "v6", "v6", v6, 0, 1 },
233   { "v7", "v7", v7, 0, 1 },
234   { "v8", "v8", v8, 32, 1 },
235   { "sparclet", "sparclet", sparclet, 32, 1 },
236   { "sparclite", "sparclite", sparclite, 32, 1 },
237   { "sparc86x", "sparclite", sparc86x, 32, 1 },
238   { "v8plus", "v9", v9, 0, 1 },
239   { "v8plusa", "v9a", v9, 0, 1 },
240   { "v9", "v9", v9, 0, 1 },
241   { "v9a", "v9a", v9, 0, 1 },
242   /* This exists to allow configure.in/Makefile.in to pass one
243      value to specify both the default machine and default word size.  */
244   { "v9-64", "v9", v9, 64, 0 },
245   { NULL, NULL, v8, 0, 0 }
246 };
247
248 /* Variant of default_arch */
249 static enum sparc_arch_types default_arch_type;
250
251 static struct sparc_arch *
252 lookup_arch (name)
253      char *name;
254 {
255   struct sparc_arch *sa;
256
257   for (sa = &sparc_arch_table[0]; sa->name != NULL; sa++)
258     if (strcmp (sa->name, name) == 0)
259       break;
260   if (sa->name == NULL)
261     return NULL;
262   return sa;
263 }
264
265 /* Initialize the default opcode arch and word size from the default
266    architecture name.  */
267
268 static void
269 init_default_arch ()
270 {
271   struct sparc_arch *sa = lookup_arch (default_arch);
272
273   if (sa == NULL
274       || sa->default_arch_size == 0)
275     as_fatal (_("Invalid default architecture, broken assembler."));
276
277   max_architecture = sparc_opcode_lookup_arch (sa->opcode_arch);
278   if (max_architecture == SPARC_OPCODE_ARCH_BAD)
279     as_fatal (_("Bad opcode table, broken assembler."));
280   default_arch_size = sparc_arch_size = sa->default_arch_size;
281   default_init_p = 1;
282   default_arch_type = sa->arch_type;
283 }
284
285 /* Called by TARGET_FORMAT.  */
286
287 const char *
288 sparc_target_format ()
289 {
290   /* We don't get a chance to initialize anything before we're called,
291      so handle that now.  */
292   if (! default_init_p)
293     init_default_arch ();
294
295 #ifdef OBJ_AOUT
296 #ifdef TE_NetBSD
297   return "a.out-sparc-netbsd";
298 #else
299 #ifdef TE_SPARCAOUT
300   if (target_big_endian)
301     return "a.out-sunos-big";
302   else if (default_arch_type == sparc86x && target_little_endian_data)
303     return "a.out-sunos-big";
304   else
305     return "a.out-sparc-little";
306 #else
307   return "a.out-sunos-big";
308 #endif
309 #endif
310 #endif
311
312 #ifdef OBJ_BOUT
313   return "b.out.big";
314 #endif
315
316 #ifdef OBJ_COFF
317 #ifdef TE_LYNX
318   return "coff-sparc-lynx";
319 #else
320   return "coff-sparc";
321 #endif
322 #endif
323
324 #ifdef OBJ_ELF
325   return sparc_arch_size == 64 ? "elf64-sparc" : "elf32-sparc";
326 #endif
327
328   abort ();
329 }
330 \f
331 /* md_parse_option
332  *      Invocation line includes a switch not recognized by the base assembler.
333  *      See if it's a processor-specific option.  These are:
334  *
335  *      -bump
336  *              Warn on architecture bumps.  See also -A.
337  *
338  *      -Av6, -Av7, -Av8, -Asparclite, -Asparclet
339  *              Standard 32 bit architectures.
340  *      -Av8plus, -Av8plusa
341  *              Sparc64 in a 32 bit world.
342  *      -Av9, -Av9a
343  *              Sparc64 in either a 32 or 64 bit world (-32/-64 says which).
344  *              This used to only mean 64 bits, but properly specifying it
345  *              complicated gcc's ASM_SPECs, so now opcode selection is
346  *              specified orthogonally to word size (except when specifying
347  *              the default, but that is an internal implementation detail).
348  *      -xarch=v8plus, -xarch=v8plusa
349  *              Same as -Av8plus{,a}, for compatibility with Sun's assembler.
350  *
351  *              Select the architecture and possibly the file format.
352  *              Instructions or features not supported by the selected
353  *              architecture cause fatal errors.
354  *
355  *              The default is to start at v6, and bump the architecture up
356  *              whenever an instruction is seen at a higher level.  In 32 bit
357  *              environments, v9 is not bumped up to, the user must pass
358  *              -Av8plus{,a}.
359  *
360  *              If -bump is specified, a warning is printing when bumping to
361  *              higher levels.
362  *
363  *              If an architecture is specified, all instructions must match
364  *              that architecture.  Any higher level instructions are flagged
365  *              as errors.  Note that in the 32 bit environment specifying
366  *              -Av8plus does not automatically create a v8plus object file, a
367  *              v9 insn must be seen.
368  *
369  *              If both an architecture and -bump are specified, the
370  *              architecture starts at the specified level, but bumps are
371  *              warnings.  Note that we can't set `current_architecture' to
372  *              the requested level in this case: in the 32 bit environment,
373  *              we still must avoid creating v8plus object files unless v9
374  *              insns are seen.
375  *
376  * Note:
377  *              Bumping between incompatible architectures is always an
378  *              error.  For example, from sparclite to v9.
379  */
380
381 #ifdef OBJ_ELF
382 CONST char *md_shortopts = "A:K:VQ:sq";
383 #else
384 #ifdef OBJ_AOUT
385 CONST char *md_shortopts = "A:k";
386 #else
387 CONST char *md_shortopts = "A:";
388 #endif
389 #endif
390 struct option md_longopts[] = {
391 #define OPTION_BUMP (OPTION_MD_BASE)
392   {"bump", no_argument, NULL, OPTION_BUMP},
393 #define OPTION_SPARC (OPTION_MD_BASE + 1)
394   {"sparc", no_argument, NULL, OPTION_SPARC},
395 #define OPTION_XARCH (OPTION_MD_BASE + 2)
396   {"xarch", required_argument, NULL, OPTION_XARCH},
397 #ifdef OBJ_ELF
398 #define OPTION_32 (OPTION_MD_BASE + 3)
399   {"32", no_argument, NULL, OPTION_32},
400 #define OPTION_64 (OPTION_MD_BASE + 4)
401   {"64", no_argument, NULL, OPTION_64},
402 #define OPTION_TSO (OPTION_MD_BASE + 5)
403   {"TSO", no_argument, NULL, OPTION_TSO},
404 #define OPTION_PSO (OPTION_MD_BASE + 6)
405   {"PSO", no_argument, NULL, OPTION_PSO},
406 #define OPTION_RMO (OPTION_MD_BASE + 7)
407   {"RMO", no_argument, NULL, OPTION_RMO},
408 #endif
409 #ifdef SPARC_BIENDIAN
410 #define OPTION_LITTLE_ENDIAN (OPTION_MD_BASE + 8)
411   {"EL", no_argument, NULL, OPTION_LITTLE_ENDIAN},
412 #define OPTION_BIG_ENDIAN (OPTION_MD_BASE + 9)
413   {"EB", no_argument, NULL, OPTION_BIG_ENDIAN},
414 #endif
415 #define OPTION_ENFORCE_ALIGNED_DATA (OPTION_MD_BASE + 10)
416   {"enforce-aligned-data", no_argument, NULL, OPTION_ENFORCE_ALIGNED_DATA},
417 #define OPTION_LITTLE_ENDIAN_DATA (OPTION_MD_BASE + 11)
418   {"little-endian-data", no_argument, NULL, OPTION_LITTLE_ENDIAN_DATA},
419 #ifdef OBJ_ELF
420 #define OPTION_NO_UNDECLARED_REGS (OPTION_MD_BASE + 12)
421   {"no-undeclared-regs", no_argument, NULL, OPTION_NO_UNDECLARED_REGS},
422 #define OPTION_UNDECLARED_REGS (OPTION_MD_BASE + 13)
423   {"undeclared-regs", no_argument, NULL, OPTION_UNDECLARED_REGS},
424 #endif
425 #define OPTION_RELAX (OPTION_MD_BASE + 14)
426   {"relax", no_argument, NULL, OPTION_RELAX},
427 #define OPTION_NO_RELAX (OPTION_MD_BASE + 15)
428   {"no-relax", no_argument, NULL, OPTION_NO_RELAX},
429   {NULL, no_argument, NULL, 0}
430 };
431
432 size_t md_longopts_size = sizeof (md_longopts);
433
434 int
435 md_parse_option (c, arg)
436      int c;
437      char *arg;
438 {
439   /* We don't get a chance to initialize anything before we're called,
440      so handle that now.  */
441   if (! default_init_p)
442     init_default_arch ();
443
444   switch (c)
445     {
446     case OPTION_BUMP:
447       warn_on_bump = 1;
448       warn_after_architecture = SPARC_OPCODE_ARCH_V6;
449       break;
450
451     case OPTION_XARCH:
452       /* This is for compatibility with Sun's assembler.  */
453       if (strcmp (arg, "v8plus") != 0
454           && strcmp (arg, "v8plusa") != 0)
455         {
456           as_bad (_("invalid architecture -xarch=%s"), arg);
457           return 0;
458         }
459       /* Fall through.  */
460
461     case 'A':
462       {
463         struct sparc_arch *sa;
464         enum sparc_opcode_arch_val opcode_arch;
465
466         sa = lookup_arch (arg);
467         if (sa == NULL
468             || ! sa->user_option_p)
469           {
470             as_bad (_("invalid architecture -A%s"), arg);
471             return 0;
472           }
473
474         opcode_arch = sparc_opcode_lookup_arch (sa->opcode_arch);
475         if (opcode_arch == SPARC_OPCODE_ARCH_BAD)
476           as_fatal (_("Bad opcode table, broken assembler."));
477
478         max_architecture = opcode_arch;
479         architecture_requested = 1;
480       }
481       break;
482
483     case OPTION_SPARC:
484       /* Ignore -sparc, used by SunOS make default .s.o rule.  */
485       break;
486
487     case OPTION_ENFORCE_ALIGNED_DATA:
488       enforce_aligned_data = 1;
489       break;
490
491 #ifdef SPARC_BIENDIAN
492     case OPTION_LITTLE_ENDIAN:
493       target_big_endian = 0;
494       if (default_arch_type != sparclet)
495         as_fatal ("This target does not support -EL");
496       break;
497     case OPTION_LITTLE_ENDIAN_DATA:
498       target_little_endian_data = 1;
499       target_big_endian = 0;
500       if (default_arch_type != sparc86x
501           && default_arch_type != v9)
502         as_fatal ("This target does not support --little-endian-data");
503       break;
504     case OPTION_BIG_ENDIAN:
505       target_big_endian = 1;
506       break;
507 #endif
508
509 #ifdef OBJ_AOUT
510     case 'k':
511       sparc_pic_code = 1;
512       break;
513 #endif
514
515 #ifdef OBJ_ELF
516     case OPTION_32:
517     case OPTION_64:
518       {
519         const char **list, **l;
520
521         sparc_arch_size = c == OPTION_32 ? 32 : 64;
522         list = bfd_target_list ();
523         for (l = list; *l != NULL; l++)
524           {
525             if (sparc_arch_size == 32)
526               {
527                 if (strcmp (*l, "elf32-sparc") == 0)
528                   break;
529               }
530             else
531               {
532                 if (strcmp (*l, "elf64-sparc") == 0)
533                   break;
534               }
535           }
536         if (*l == NULL)
537           as_fatal (_("No compiled in support for %d bit object file format"),
538                     sparc_arch_size);
539         free (list);
540       }
541       break;
542
543     case OPTION_TSO:
544       sparc_memory_model = MM_TSO;
545       break;
546
547     case OPTION_PSO:
548       sparc_memory_model = MM_PSO;
549       break;
550
551     case OPTION_RMO:
552       sparc_memory_model = MM_RMO;
553       break;
554
555     case 'V':
556       print_version_id ();
557       break;
558
559     case 'Q':
560       /* Qy - do emit .comment
561          Qn - do not emit .comment.  */
562       break;
563
564     case 's':
565       /* Use .stab instead of .stab.excl.  */
566       break;
567
568     case 'q':
569       /* quick -- Native assembler does fewer checks.  */
570       break;
571
572     case 'K':
573       if (strcmp (arg, "PIC") != 0)
574         as_warn (_("Unrecognized option following -K"));
575       else
576         sparc_pic_code = 1;
577       break;
578
579     case OPTION_NO_UNDECLARED_REGS:
580       no_undeclared_regs = 1;
581       break;
582
583     case OPTION_UNDECLARED_REGS:
584       no_undeclared_regs = 0;
585       break;
586 #endif
587
588     case OPTION_RELAX:
589       sparc_relax = 1;
590       break;
591
592     case OPTION_NO_RELAX:
593       sparc_relax = 0;
594       break;
595
596     default:
597       return 0;
598     }
599
600   return 1;
601 }
602
603 void
604 md_show_usage (stream)
605      FILE *stream;
606 {
607   const struct sparc_arch *arch;
608
609   /* We don't get a chance to initialize anything before we're called,
610      so handle that now.  */
611   if (! default_init_p)
612     init_default_arch ();
613
614   fprintf (stream, _("SPARC options:\n"));
615   for (arch = &sparc_arch_table[0]; arch->name; arch++)
616     {
617       if (arch != &sparc_arch_table[0])
618         fprintf (stream, " | ");
619       if (arch->user_option_p)
620         fprintf (stream, "-A%s", arch->name);
621     }
622   fprintf (stream, _("\n-xarch=v8plus | -xarch=v8plusa\n"));
623   fprintf (stream, _("\
624                         specify variant of SPARC architecture\n\
625 -bump                   warn when assembler switches architectures\n\
626 -sparc                  ignored\n\
627 --enforce-aligned-data  force .long, etc., to be aligned correctly\n\
628 -relax                  relax jumps and branches (default)\n\
629 -no-relax               avoid changing any jumps and branches\n"));
630 #ifdef OBJ_AOUT
631   fprintf (stream, _("\
632 -k                      generate PIC\n"));
633 #endif
634 #ifdef OBJ_ELF
635   fprintf (stream, _("\
636 -32                     create 32 bit object file\n\
637 -64                     create 64 bit object file\n"));
638   fprintf (stream, _("\
639                         [default is %d]\n"), default_arch_size);
640   fprintf (stream, _("\
641 -TSO                    use Total Store Ordering\n\
642 -PSO                    use Partial Store Ordering\n\
643 -RMO                    use Relaxed Memory Ordering\n"));
644   fprintf (stream, _("\
645                         [default is %s]\n"), (default_arch_size == 64) ? "RMO" : "TSO");
646   fprintf (stream, _("\
647 -KPIC                   generate PIC\n\
648 -V                      print assembler version number\n\
649 -undeclared-regs        ignore application global register usage without\n\
650                         appropriate .register directive (default)\n\
651 -no-undeclared-regs     force error on application global register usage\n\
652                         without appropriate .register directive\n\
653 -q                      ignored\n\
654 -Qy, -Qn                ignored\n\
655 -s                      ignored\n"));
656 #endif
657 #ifdef SPARC_BIENDIAN
658   fprintf (stream, _("\
659 -EL                     generate code for a little endian machine\n\
660 -EB                     generate code for a big endian machine\n\
661 --little-endian-data    generate code for a machine having big endian\n\
662                         instructions and little endian data.\n"));
663 #endif
664 }
665 \f
666 /* Native operand size opcode translation.  */
667 struct
668   {
669     char *name;
670     char *name32;
671     char *name64;
672   } native_op_table[] =
673 {
674   {"ldn", "ld", "ldx"},
675   {"ldna", "lda", "ldxa"},
676   {"stn", "st", "stx"},
677   {"stna", "sta", "stxa"},
678   {"slln", "sll", "sllx"},
679   {"srln", "srl", "srlx"},
680   {"sran", "sra", "srax"},
681   {"casn", "cas", "casx"},
682   {"casna", "casa", "casxa"},
683   {"clrn", "clr", "clrx"},
684   {NULL, NULL, NULL},
685 };
686 \f
687 /* sparc64 priviledged registers.  */
688
689 struct priv_reg_entry
690 {
691   char *name;
692   int regnum;
693 };
694
695 struct priv_reg_entry priv_reg_table[] =
696 {
697   {"tpc", 0},
698   {"tnpc", 1},
699   {"tstate", 2},
700   {"tt", 3},
701   {"tick", 4},
702   {"tba", 5},
703   {"pstate", 6},
704   {"tl", 7},
705   {"pil", 8},
706   {"cwp", 9},
707   {"cansave", 10},
708   {"canrestore", 11},
709   {"cleanwin", 12},
710   {"otherwin", 13},
711   {"wstate", 14},
712   {"fq", 15},
713   {"ver", 31},
714   {"", -1},                     /* End marker.  */
715 };
716
717 /* v9a specific asrs.  */
718
719 struct priv_reg_entry v9a_asr_table[] =
720 {
721   {"tick_cmpr", 23},
722   {"softint", 22},
723   {"set_softint", 20},
724   {"pic", 17},
725   {"pcr", 16},
726   {"gsr", 19},
727   {"dcr", 18},
728   {"clear_softint", 21},
729   {"", -1},                     /* End marker.  */
730 };
731
732 static int
733 cmp_reg_entry (parg, qarg)
734      const PTR parg;
735      const PTR qarg;
736 {
737   const struct priv_reg_entry *p = (const struct priv_reg_entry *) parg;
738   const struct priv_reg_entry *q = (const struct priv_reg_entry *) qarg;
739
740   return strcmp (q->name, p->name);
741 }
742 \f
743 /* This function is called once, at assembler startup time.  It should
744    set up all the tables, etc. that the MD part of the assembler will
745    need.  */
746
747 void
748 md_begin ()
749 {
750   register const char *retval = NULL;
751   int lose = 0;
752   register unsigned int i = 0;
753
754   /* We don't get a chance to initialize anything before md_parse_option
755      is called, and it may not be called, so handle default initialization
756      now if not already done.  */
757   if (! default_init_p)
758     init_default_arch ();
759
760   op_hash = hash_new ();
761
762   while (i < (unsigned int) sparc_num_opcodes)
763     {
764       const char *name = sparc_opcodes[i].name;
765       retval = hash_insert (op_hash, name, (PTR) &sparc_opcodes[i]);
766       if (retval != NULL)
767         {
768           as_bad (_("Internal error: can't hash `%s': %s\n"),
769                   sparc_opcodes[i].name, retval);
770           lose = 1;
771         }
772       do
773         {
774           if (sparc_opcodes[i].match & sparc_opcodes[i].lose)
775             {
776               as_bad (_("Internal error: losing opcode: `%s' \"%s\"\n"),
777                       sparc_opcodes[i].name, sparc_opcodes[i].args);
778               lose = 1;
779             }
780           ++i;
781         }
782       while (i < (unsigned int) sparc_num_opcodes
783              && !strcmp (sparc_opcodes[i].name, name));
784     }
785
786   for (i = 0; native_op_table[i].name; i++)
787     {
788       const struct sparc_opcode *insn;
789       char *name = sparc_arch_size == (32
790                                        ? native_op_table[i].name32
791                                        : native_op_table[i].name64);
792       insn = (struct sparc_opcode *) hash_find (op_hash, name);
793       if (insn == NULL)
794         {
795           as_bad (_("Internal error: can't find opcode `%s' for `%s'\n"),
796                   name, native_op_table[i].name);
797           lose = 1;
798         }
799       else
800         {
801           retval = hash_insert (op_hash, native_op_table[i].name, (PTR) insn);
802           if (retval != NULL)
803             {
804               as_bad (_("Internal error: can't hash `%s': %s\n"),
805                       sparc_opcodes[i].name, retval);
806               lose = 1;
807             }
808         }
809     }
810
811   if (lose)
812     as_fatal (_("Broken assembler.  No assembly attempted."));
813
814   qsort (priv_reg_table, sizeof (priv_reg_table) / sizeof (priv_reg_table[0]),
815          sizeof (priv_reg_table[0]), cmp_reg_entry);
816
817   /* If -bump, record the architecture level at which we start issuing
818      warnings.  The behaviour is different depending upon whether an
819      architecture was explicitly specified.  If it wasn't, we issue warnings
820      for all upwards bumps.  If it was, we don't start issuing warnings until
821      we need to bump beyond the requested architecture or when we bump between
822      conflicting architectures.  */
823
824   if (warn_on_bump
825       && architecture_requested)
826     {
827       /* `max_architecture' records the requested architecture.
828          Issue warnings if we go above it.  */
829       warn_after_architecture = max_architecture;
830
831       /* Find the highest architecture level that doesn't conflict with
832          the requested one.  */
833       for (max_architecture = SPARC_OPCODE_ARCH_MAX;
834            max_architecture > warn_after_architecture;
835            --max_architecture)
836         if (! SPARC_OPCODE_CONFLICT_P (max_architecture,
837                                        warn_after_architecture))
838           break;
839     }
840 }
841
842 /* Called after all assembly has been done.  */
843
844 void
845 sparc_md_end ()
846 {
847   if (sparc_arch_size == 64)
848     {
849       if (current_architecture == SPARC_OPCODE_ARCH_V9A)
850         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_v9a);
851       else
852         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_v9);
853     }
854   else
855     {
856       if (current_architecture == SPARC_OPCODE_ARCH_V9)
857         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_v8plus);
858       else if (current_architecture == SPARC_OPCODE_ARCH_V9A)
859         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_v8plusa);
860       else if (current_architecture == SPARC_OPCODE_ARCH_SPARCLET)
861         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_sparclet);
862       else if (default_arch_type == sparc86x && target_little_endian_data)
863         bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc_sparclite_le);
864       else
865         {
866           /* The sparclite is treated like a normal sparc.  Perhaps it
867              shouldn't be but for now it is (since that's the way it's
868              always been treated).  */
869           bfd_set_arch_mach (stdoutput, bfd_arch_sparc, bfd_mach_sparc);
870         }
871     }
872 }
873 \f
874 /* Return non-zero if VAL is in the range -(MAX+1) to MAX.  */
875
876 static INLINE int
877 in_signed_range (val, max)
878      bfd_signed_vma val, max;
879 {
880   if (max <= 0)
881     abort ();
882   /* Sign-extend the value from the architecture word size, so that
883      0xffffffff is always considered -1 on sparc32.  */
884   if (sparc_arch_size == 32)
885     {
886       bfd_signed_vma sign = (bfd_signed_vma) 1 << 31;
887       val = ((val & 0xffffffff) ^ sign) - sign;
888     }
889   if (val > max)
890     return 0;
891   if (val < ~max)
892     return 0;
893   return 1;
894 }
895
896 /* Return non-zero if VAL is in the range 0 to MAX.  */
897
898 static INLINE int
899 in_unsigned_range (val, max)
900      bfd_vma val, max;
901 {
902   if (val > max)
903     return 0;
904   return 1;
905 }
906
907 /* Return non-zero if VAL is in the range -(MAX/2+1) to MAX.
908    (e.g. -15 to +31).  */
909
910 static INLINE int
911 in_bitfield_range (val, max)
912      bfd_signed_vma val, max;
913 {
914   if (max <= 0)
915     abort ();
916   if (val > max)
917     return 0;
918   if (val < ~(max >> 1))
919     return 0;
920   return 1;
921 }
922
923 static int
924 sparc_ffs (mask)
925      unsigned int mask;
926 {
927   int i;
928
929   if (mask == 0)
930     return -1;
931
932   for (i = 0; (mask & 1) == 0; ++i)
933     mask >>= 1;
934   return i;
935 }
936
937 /* Implement big shift right.  */
938 static bfd_vma
939 BSR (val, amount)
940      bfd_vma val;
941      int amount;
942 {
943   if (sizeof (bfd_vma) <= 4 && amount >= 32)
944     as_fatal (_("Support for 64-bit arithmetic not compiled in."));
945   return val >> amount;
946 }
947 \f
948 /* For communication between sparc_ip and get_expression.  */
949 static char *expr_end;
950
951 /* Values for `special_case'.
952    Instructions that require wierd handling because they're longer than
953    4 bytes.  */
954 #define SPECIAL_CASE_NONE       0
955 #define SPECIAL_CASE_SET        1
956 #define SPECIAL_CASE_SETSW      2
957 #define SPECIAL_CASE_SETX       3
958 /* FIXME: sparc-opc.c doesn't have necessary "S" trigger to enable this.  */
959 #define SPECIAL_CASE_FDIV       4
960
961 /* Bit masks of various insns.  */
962 #define NOP_INSN 0x01000000
963 #define OR_INSN 0x80100000
964 #define XOR_INSN 0x80180000
965 #define FMOVS_INSN 0x81A00020
966 #define SETHI_INSN 0x01000000
967 #define SLLX_INSN 0x81281000
968 #define SRA_INSN 0x81380000
969
970 /* The last instruction to be assembled.  */
971 static const struct sparc_opcode *last_insn;
972 /* The assembled opcode of `last_insn'.  */
973 static unsigned long last_opcode;
974 \f
975 /* Handle the set and setuw synthetic instructions.  */
976
977 static void
978 synthetize_setuw (insn)
979      const struct sparc_opcode *insn;
980 {
981   int need_hi22_p = 0;
982   int rd = (the_insn.opcode & RD (~0)) >> 25;
983
984   if (the_insn.exp.X_op == O_constant)
985     {
986       if (SPARC_OPCODE_ARCH_V9_P (max_architecture))
987         {
988           if (sizeof (offsetT) > 4
989               && (the_insn.exp.X_add_number < 0
990                   || the_insn.exp.X_add_number > (offsetT) 0xffffffff))
991             as_warn (_("set: number not in 0..4294967295 range"));
992         }
993       else
994         {
995           if (sizeof (offsetT) > 4
996               && (the_insn.exp.X_add_number < -(offsetT) 0x80000000
997                   || the_insn.exp.X_add_number > (offsetT) 0xffffffff))
998             as_warn (_("set: number not in -2147483648..4294967295 range"));
999           the_insn.exp.X_add_number = (int) the_insn.exp.X_add_number;
1000         }
1001     }
1002
1003   /* See if operand is absolute and small; skip sethi if so.  */
1004   if (the_insn.exp.X_op != O_constant
1005       || the_insn.exp.X_add_number >= (1 << 12)
1006       || the_insn.exp.X_add_number < -(1 << 12))
1007     {
1008       the_insn.opcode = (SETHI_INSN | RD (rd)
1009                          | ((the_insn.exp.X_add_number >> 10)
1010                             & (the_insn.exp.X_op == O_constant
1011                                ? 0x3fffff : 0)));
1012       the_insn.reloc = (the_insn.exp.X_op != O_constant
1013                         ? BFD_RELOC_HI22 : BFD_RELOC_NONE);
1014       output_insn (insn, &the_insn);
1015       need_hi22_p = 1;
1016     }
1017
1018   /* See if operand has no low-order bits; skip OR if so.  */
1019   if (the_insn.exp.X_op != O_constant
1020       || (need_hi22_p && (the_insn.exp.X_add_number & 0x3FF) != 0)
1021       || ! need_hi22_p)
1022     {
1023       the_insn.opcode = (OR_INSN | (need_hi22_p ? RS1 (rd) : 0)
1024                          | RD (rd) | IMMED
1025                          | (the_insn.exp.X_add_number
1026                             & (the_insn.exp.X_op != O_constant
1027                                ? 0 : need_hi22_p ? 0x3ff : 0x1fff)));
1028       the_insn.reloc = (the_insn.exp.X_op != O_constant
1029                         ? BFD_RELOC_LO10 : BFD_RELOC_NONE);
1030       output_insn (insn, &the_insn);
1031     }
1032 }
1033
1034 /* Handle the setsw synthetic instruction.  */
1035
1036 static void
1037 synthetize_setsw (insn)
1038      const struct sparc_opcode *insn;
1039 {
1040   int low32, rd, opc;
1041
1042   rd = (the_insn.opcode & RD (~0)) >> 25;
1043
1044   if (the_insn.exp.X_op != O_constant)
1045     {
1046       synthetize_setuw (insn);
1047
1048       /* Need to sign extend it.  */
1049       the_insn.opcode = (SRA_INSN | RS1 (rd) | RD (rd));
1050       the_insn.reloc = BFD_RELOC_NONE;
1051       output_insn (insn, &the_insn);
1052       return;
1053     }
1054
1055   if (sizeof (offsetT) > 4
1056       && (the_insn.exp.X_add_number < -(offsetT) 0x80000000
1057           || the_insn.exp.X_add_number > (offsetT) 0xffffffff))
1058     as_warn (_("setsw: number not in -2147483648..4294967295 range"));
1059
1060   low32 = the_insn.exp.X_add_number;
1061
1062   if (low32 >= 0)
1063     {
1064       synthetize_setuw (insn);
1065       return;
1066     }
1067
1068   opc = OR_INSN;
1069
1070   the_insn.reloc = BFD_RELOC_NONE;
1071   /* See if operand is absolute and small; skip sethi if so.  */
1072   if (low32 < -(1 << 12))
1073     {
1074       the_insn.opcode = (SETHI_INSN | RD (rd)
1075                          | (((~the_insn.exp.X_add_number) >> 10) & 0x3fffff));
1076       output_insn (insn, &the_insn);
1077       low32 = 0x1c00 | (low32 & 0x3ff);
1078       opc = RS1 (rd) | XOR_INSN;
1079     }
1080
1081   the_insn.opcode = (opc | RD (rd) | IMMED
1082                      | (low32 & 0x1fff));
1083   output_insn (insn, &the_insn);
1084 }
1085
1086 /* Handle the setsw synthetic instruction.  */
1087
1088 static void
1089 synthetize_setx (insn)
1090      const struct sparc_opcode *insn;
1091 {
1092   int upper32, lower32;
1093   int tmpreg = (the_insn.opcode & RS1 (~0)) >> 14;
1094   int dstreg = (the_insn.opcode & RD (~0)) >> 25;
1095   int upper_dstreg;
1096   int need_hh22_p = 0, need_hm10_p = 0, need_hi22_p = 0, need_lo10_p = 0;
1097   int need_xor10_p = 0;
1098
1099 #define SIGNEXT32(x) ((((x) & 0xffffffff) ^ 0x80000000) - 0x80000000)
1100   lower32 = SIGNEXT32 (the_insn.exp.X_add_number);
1101   upper32 = SIGNEXT32 (BSR (the_insn.exp.X_add_number, 32));
1102 #undef SIGNEXT32
1103
1104   upper_dstreg = tmpreg;
1105   /* The tmp reg should not be the dst reg.  */
1106   if (tmpreg == dstreg)
1107     as_warn (_("setx: temporary register same as destination register"));
1108
1109   /* ??? Obviously there are other optimizations we can do
1110      (e.g. sethi+shift for 0x1f0000000) and perhaps we shouldn't be
1111      doing some of these.  Later.  If you do change things, try to
1112      change all of this to be table driven as well.  */
1113   /* What to output depends on the number if it's constant.
1114      Compute that first, then output what we've decided upon.  */
1115   if (the_insn.exp.X_op != O_constant)
1116     {
1117       if (sparc_arch_size == 32)
1118         {
1119           /* When arch size is 32, we want setx to be equivalent
1120              to setuw for anything but constants.  */
1121           the_insn.exp.X_add_number &= 0xffffffff;
1122           synthetize_setuw (insn);
1123           return;
1124         }
1125       need_hh22_p = need_hm10_p = need_hi22_p = need_lo10_p = 1;
1126       lower32 = 0;
1127       upper32 = 0;
1128     }
1129   else
1130     {
1131       /* Reset X_add_number, we've extracted it as upper32/lower32.
1132          Otherwise fixup_segment will complain about not being able to
1133          write an 8 byte number in a 4 byte field.  */
1134       the_insn.exp.X_add_number = 0;
1135
1136       /* Only need hh22 if `or' insn can't handle constant.  */
1137       if (upper32 < -(1 << 12) || upper32 >= (1 << 12))
1138         need_hh22_p = 1;
1139
1140       /* Does bottom part (after sethi) have bits?  */
1141       if ((need_hh22_p && (upper32 & 0x3ff) != 0)
1142           /* No hh22, but does upper32 still have bits we can't set
1143              from lower32?  */
1144           || (! need_hh22_p && upper32 != 0 && upper32 != -1))
1145         need_hm10_p = 1;
1146
1147       /* If the lower half is all zero, we build the upper half directly
1148          into the dst reg.  */
1149       if (lower32 != 0
1150           /* Need lower half if number is zero or 0xffffffff00000000.  */
1151           || (! need_hh22_p && ! need_hm10_p))
1152         {
1153           /* No need for sethi if `or' insn can handle constant.  */
1154           if (lower32 < -(1 << 12) || lower32 >= (1 << 12)
1155               /* Note that we can't use a negative constant in the `or'
1156                  insn unless the upper 32 bits are all ones.  */
1157               || (lower32 < 0 && upper32 != -1)
1158               || (lower32 >= 0 && upper32 == -1))
1159             need_hi22_p = 1;
1160
1161           if (need_hi22_p && upper32 == -1)
1162             need_xor10_p = 1;
1163
1164           /* Does bottom part (after sethi) have bits?  */
1165           else if ((need_hi22_p && (lower32 & 0x3ff) != 0)
1166                    /* No sethi.  */
1167                    || (! need_hi22_p && (lower32 & 0x1fff) != 0)
1168                    /* Need `or' if we didn't set anything else.  */
1169                    || (! need_hi22_p && ! need_hh22_p && ! need_hm10_p))
1170             need_lo10_p = 1;
1171         }
1172       else
1173         /* Output directly to dst reg if lower 32 bits are all zero.  */
1174         upper_dstreg = dstreg;
1175     }
1176
1177   if (!upper_dstreg && dstreg)
1178     as_warn (_("setx: illegal temporary register g0"));
1179
1180   if (need_hh22_p)
1181     {
1182       the_insn.opcode = (SETHI_INSN | RD (upper_dstreg)
1183                          | ((upper32 >> 10) & 0x3fffff));
1184       the_insn.reloc = (the_insn.exp.X_op != O_constant
1185                         ? BFD_RELOC_SPARC_HH22 : BFD_RELOC_NONE);
1186       output_insn (insn, &the_insn);
1187     }
1188
1189   if (need_hi22_p)
1190     {
1191       the_insn.opcode = (SETHI_INSN | RD (dstreg)
1192                          | (((need_xor10_p ? ~lower32 : lower32)
1193                              >> 10) & 0x3fffff));
1194       the_insn.reloc = (the_insn.exp.X_op != O_constant
1195                         ? BFD_RELOC_SPARC_LM22 : BFD_RELOC_NONE);
1196       output_insn (insn, &the_insn);
1197     }
1198
1199   if (need_hm10_p)
1200     {
1201       the_insn.opcode = (OR_INSN
1202                          | (need_hh22_p ? RS1 (upper_dstreg) : 0)
1203                          | RD (upper_dstreg)
1204                          | IMMED
1205                          | (upper32 & (need_hh22_p ? 0x3ff : 0x1fff)));
1206       the_insn.reloc = (the_insn.exp.X_op != O_constant
1207                         ? BFD_RELOC_SPARC_HM10 : BFD_RELOC_NONE);
1208       output_insn (insn, &the_insn);
1209     }
1210
1211   if (need_lo10_p)
1212     {
1213       /* FIXME: One nice optimization to do here is to OR the low part
1214          with the highpart if hi22 isn't needed and the low part is
1215          positive.  */
1216       the_insn.opcode = (OR_INSN | (need_hi22_p ? RS1 (dstreg) : 0)
1217                          | RD (dstreg)
1218                          | IMMED
1219                          | (lower32 & (need_hi22_p ? 0x3ff : 0x1fff)));
1220       the_insn.reloc = (the_insn.exp.X_op != O_constant
1221                         ? BFD_RELOC_LO10 : BFD_RELOC_NONE);
1222       output_insn (insn, &the_insn);
1223     }
1224
1225   /* If we needed to build the upper part, shift it into place.  */
1226   if (need_hh22_p || need_hm10_p)
1227     {
1228       the_insn.opcode = (SLLX_INSN | RS1 (upper_dstreg) | RD (upper_dstreg)
1229                          | IMMED | 32);
1230       the_insn.reloc = BFD_RELOC_NONE;
1231       output_insn (insn, &the_insn);
1232     }
1233
1234   /* To get -1 in upper32, we do sethi %hi(~x), r; xor r, -0x400 | x, r.  */
1235   if (need_xor10_p)
1236     {
1237       the_insn.opcode = (XOR_INSN | RS1 (dstreg) | RD (dstreg) | IMMED
1238                          | 0x1c00 | (lower32 & 0x3ff));
1239       the_insn.reloc = BFD_RELOC_NONE;
1240       output_insn (insn, &the_insn);
1241     }
1242
1243   /* If we needed to build both upper and lower parts, OR them together.  */
1244   else if ((need_hh22_p || need_hm10_p) && (need_hi22_p || need_lo10_p))
1245     {
1246       the_insn.opcode = (OR_INSN | RS1 (dstreg) | RS2 (upper_dstreg)
1247                          | RD (dstreg));
1248       the_insn.reloc = BFD_RELOC_NONE;
1249       output_insn (insn, &the_insn);
1250     }
1251 }
1252 \f
1253 /* Main entry point to assemble one instruction.  */
1254
1255 void
1256 md_assemble (str)
1257      char *str;
1258 {
1259   const struct sparc_opcode *insn;
1260   int special_case;
1261
1262   know (str);
1263   special_case = sparc_ip (str, &insn);
1264
1265   /* We warn about attempts to put a floating point branch in a delay slot,
1266      unless the delay slot has been annulled.  */
1267   if (insn != NULL
1268       && last_insn != NULL
1269       && (insn->flags & F_FBR) != 0
1270       && (last_insn->flags & F_DELAYED) != 0
1271       /* ??? This test isn't completely accurate.  We assume anything with
1272          F_{UNBR,CONDBR,FBR} set is annullable.  */
1273       && ((last_insn->flags & (F_UNBR | F_CONDBR | F_FBR)) == 0
1274           || (last_opcode & ANNUL) == 0))
1275     as_warn (_("FP branch in delay slot"));
1276
1277   /* SPARC before v9 requires a nop instruction between a floating
1278      point instruction and a floating point branch.  We insert one
1279      automatically, with a warning.  */
1280   if (max_architecture < SPARC_OPCODE_ARCH_V9
1281       && insn != NULL
1282       && last_insn != NULL
1283       && (insn->flags & F_FBR) != 0
1284       && (last_insn->flags & F_FLOAT) != 0)
1285     {
1286       struct sparc_it nop_insn;
1287
1288       nop_insn.opcode = NOP_INSN;
1289       nop_insn.reloc = BFD_RELOC_NONE;
1290       output_insn (insn, &nop_insn);
1291       as_warn (_("FP branch preceded by FP instruction; NOP inserted"));
1292     }
1293
1294   switch (special_case)
1295     {
1296     case SPECIAL_CASE_NONE:
1297       /* Normal insn.  */
1298       output_insn (insn, &the_insn);
1299       break;
1300
1301     case SPECIAL_CASE_SETSW:
1302       synthetize_setsw (insn);
1303       break;
1304
1305     case SPECIAL_CASE_SET:
1306       synthetize_setuw (insn);
1307       break;
1308
1309     case SPECIAL_CASE_SETX:
1310       synthetize_setx (insn);
1311       break;
1312
1313     case SPECIAL_CASE_FDIV:
1314       {
1315         int rd = (the_insn.opcode >> 25) & 0x1f;
1316
1317         output_insn (insn, &the_insn);
1318
1319         /* According to information leaked from Sun, the "fdiv" instructions
1320            on early SPARC machines would produce incorrect results sometimes.
1321            The workaround is to add an fmovs of the destination register to
1322            itself just after the instruction.  This was true on machines
1323            with Weitek 1165 float chips, such as the Sun-4/260 and /280.  */
1324         assert (the_insn.reloc == BFD_RELOC_NONE);
1325         the_insn.opcode = FMOVS_INSN | rd | RD (rd);
1326         output_insn (insn, &the_insn);
1327         return;
1328       }
1329
1330     default:
1331       as_fatal (_("failed special case insn sanity check"));
1332     }
1333 }
1334
1335 /* Subroutine of md_assemble to do the actual parsing.  */
1336
1337 static int
1338 sparc_ip (str, pinsn)
1339      char *str;
1340      const struct sparc_opcode **pinsn;
1341 {
1342   char *error_message = "";
1343   char *s;
1344   const char *args;
1345   char c;
1346   const struct sparc_opcode *insn;
1347   char *argsStart;
1348   unsigned long opcode;
1349   unsigned int mask = 0;
1350   int match = 0;
1351   int comma = 0;
1352   int v9_arg_p;
1353   int special_case = SPECIAL_CASE_NONE;
1354
1355   s = str;
1356   if (islower ((unsigned char) *s))
1357     {
1358       do
1359         ++s;
1360       while (islower ((unsigned char) *s) || isdigit ((unsigned char) *s));
1361     }
1362
1363   switch (*s)
1364     {
1365     case '\0':
1366       break;
1367
1368     case ',':
1369       comma = 1;
1370       /* Fall through.  */
1371
1372     case ' ':
1373       *s++ = '\0';
1374       break;
1375
1376     default:
1377       as_fatal (_("Unknown opcode: `%s'"), str);
1378     }
1379   insn = (struct sparc_opcode *) hash_find (op_hash, str);
1380   *pinsn = insn;
1381   if (insn == NULL)
1382     {
1383       as_bad (_("Unknown opcode: `%s'"), str);
1384       return special_case;
1385     }
1386   if (comma)
1387     {
1388       *--s = ',';
1389     }
1390
1391   argsStart = s;
1392   for (;;)
1393     {
1394       opcode = insn->match;
1395       memset (&the_insn, '\0', sizeof (the_insn));
1396       the_insn.reloc = BFD_RELOC_NONE;
1397       v9_arg_p = 0;
1398
1399       /* Build the opcode, checking as we go to make sure that the
1400          operands match.  */
1401       for (args = insn->args;; ++args)
1402         {
1403           switch (*args)
1404             {
1405             case 'K':
1406               {
1407                 int kmask = 0;
1408
1409                 /* Parse a series of masks.  */
1410                 if (*s == '#')
1411                   {
1412                     while (*s == '#')
1413                       {
1414                         int mask;
1415
1416                         if (! parse_keyword_arg (sparc_encode_membar, &s,
1417                                                  &mask))
1418                           {
1419                             error_message = _(": invalid membar mask name");
1420                             goto error;
1421                           }
1422                         kmask |= mask;
1423                         while (*s == ' ') { ++s; continue; }
1424                         if (*s == '|' || *s == '+')
1425                           ++s;
1426                         while (*s == ' ') { ++s; continue; }
1427                       }
1428                   }
1429                 else
1430                   {
1431                     if (! parse_const_expr_arg (&s, &kmask))
1432                       {
1433                         error_message = _(": invalid membar mask expression");
1434                         goto error;
1435                       }
1436                     if (kmask < 0 || kmask > 127)
1437                       {
1438                         error_message = _(": invalid membar mask number");
1439                         goto error;
1440                       }
1441                   }
1442
1443                 opcode |= MEMBAR (kmask);
1444                 continue;
1445               }
1446
1447             case '*':
1448               {
1449                 int fcn = 0;
1450
1451                 /* Parse a prefetch function.  */
1452                 if (*s == '#')
1453                   {
1454                     if (! parse_keyword_arg (sparc_encode_prefetch, &s, &fcn))
1455                       {
1456                         error_message = _(": invalid prefetch function name");
1457                         goto error;
1458                       }
1459                   }
1460                 else
1461                   {
1462                     if (! parse_const_expr_arg (&s, &fcn))
1463                       {
1464                         error_message = _(": invalid prefetch function expression");
1465                         goto error;
1466                       }
1467                     if (fcn < 0 || fcn > 31)
1468                       {
1469                         error_message = _(": invalid prefetch function number");
1470                         goto error;
1471                       }
1472                   }
1473                 opcode |= RD (fcn);
1474                 continue;
1475               }
1476
1477             case '!':
1478             case '?':
1479               /* Parse a sparc64 privileged register.  */
1480               if (*s == '%')
1481                 {
1482                   struct priv_reg_entry *p = priv_reg_table;
1483                   unsigned int len = 9999999; /* Init to make gcc happy.  */
1484
1485                   s += 1;
1486                   while (p->name[0] > s[0])
1487                     p++;
1488                   while (p->name[0] == s[0])
1489                     {
1490                       len = strlen (p->name);
1491                       if (strncmp (p->name, s, len) == 0)
1492                         break;
1493                       p++;
1494                     }
1495                   if (p->name[0] != s[0])
1496                     {
1497                       error_message = _(": unrecognizable privileged register");
1498                       goto error;
1499                     }
1500                   if (*args == '?')
1501                     opcode |= (p->regnum << 14);
1502                   else
1503                     opcode |= (p->regnum << 25);
1504                   s += len;
1505                   continue;
1506                 }
1507               else
1508                 {
1509                   error_message = _(": unrecognizable privileged register");
1510                   goto error;
1511                 }
1512
1513             case '_':
1514             case '/':
1515               /* Parse a v9a ancillary state register.  */
1516               if (*s == '%')
1517                 {
1518                   struct priv_reg_entry *p = v9a_asr_table;
1519                   unsigned int len = 9999999; /* Init to make gcc happy.  */
1520
1521                   s += 1;
1522                   while (p->name[0] > s[0])
1523                     p++;
1524                   while (p->name[0] == s[0])
1525                     {
1526                       len = strlen (p->name);
1527                       if (strncmp (p->name, s, len) == 0)
1528                         break;
1529                       p++;
1530                     }
1531                   if (p->name[0] != s[0])
1532                     {
1533                       error_message = _(": unrecognizable v9a ancillary state register");
1534                       goto error;
1535                     }
1536                   if (*args == '/' && (p->regnum == 20 || p->regnum == 21))
1537                     {
1538                       error_message = _(": rd on write only ancillary state register");
1539                       goto error;
1540                     }
1541                   if (*args == '/')
1542                     opcode |= (p->regnum << 14);
1543                   else
1544                     opcode |= (p->regnum << 25);
1545                   s += len;
1546                   continue;
1547                 }
1548               else
1549                 {
1550                   error_message = _(": unrecognizable v9a ancillary state register");
1551                   goto error;
1552                 }
1553
1554             case 'M':
1555             case 'm':
1556               if (strncmp (s, "%asr", 4) == 0)
1557                 {
1558                   s += 4;
1559
1560                   if (isdigit ((unsigned char) *s))
1561                     {
1562                       long num = 0;
1563
1564                       while (isdigit ((unsigned char) *s))
1565                         {
1566                           num = num * 10 + *s - '0';
1567                           ++s;
1568                         }
1569
1570                       if (current_architecture >= SPARC_OPCODE_ARCH_V9)
1571                         {
1572                           if (num < 16 || 31 < num)
1573                             {
1574                               error_message = _(": asr number must be between 16 and 31");
1575                               goto error;
1576                             }
1577                         }
1578                       else
1579                         {
1580                           if (num < 0 || 31 < num)
1581                             {
1582                               error_message = _(": asr number must be between 0 and 31");
1583                               goto error;
1584                             }
1585                         }
1586
1587                       opcode |= (*args == 'M' ? RS1 (num) : RD (num));
1588                       continue;
1589                     }
1590                   else
1591                     {
1592                       error_message = _(": expecting %asrN");
1593                       goto error;
1594                     }
1595                 } /* if %asr  */
1596               break;
1597
1598             case 'I':
1599               the_insn.reloc = BFD_RELOC_SPARC_11;
1600               goto immediate;
1601
1602             case 'j':
1603               the_insn.reloc = BFD_RELOC_SPARC_10;
1604               goto immediate;
1605
1606             case 'X':
1607               /* V8 systems don't understand BFD_RELOC_SPARC_5.  */
1608               if (SPARC_OPCODE_ARCH_V9_P (max_architecture))
1609                 the_insn.reloc = BFD_RELOC_SPARC_5;
1610               else
1611                 the_insn.reloc = BFD_RELOC_SPARC13;
1612               /* These fields are unsigned, but for upward compatibility,
1613                  allow negative values as well.  */
1614               goto immediate;
1615
1616             case 'Y':
1617               /* V8 systems don't understand BFD_RELOC_SPARC_6.  */
1618               if (SPARC_OPCODE_ARCH_V9_P (max_architecture))
1619                 the_insn.reloc = BFD_RELOC_SPARC_6;
1620               else
1621                 the_insn.reloc = BFD_RELOC_SPARC13;
1622               /* These fields are unsigned, but for upward compatibility,
1623                  allow negative values as well.  */
1624               goto immediate;
1625
1626             case 'k':
1627               the_insn.reloc = /* RELOC_WDISP2_14 */ BFD_RELOC_SPARC_WDISP16;
1628               the_insn.pcrel = 1;
1629               goto immediate;
1630
1631             case 'G':
1632               the_insn.reloc = BFD_RELOC_SPARC_WDISP19;
1633               the_insn.pcrel = 1;
1634               goto immediate;
1635
1636             case 'N':
1637               if (*s == 'p' && s[1] == 'n')
1638                 {
1639                   s += 2;
1640                   continue;
1641                 }
1642               break;
1643
1644             case 'T':
1645               if (*s == 'p' && s[1] == 't')
1646                 {
1647                   s += 2;
1648                   continue;
1649                 }
1650               break;
1651
1652             case 'z':
1653               if (*s == ' ')
1654                 {
1655                   ++s;
1656                 }
1657               if (strncmp (s, "%icc", 4) == 0)
1658                 {
1659                   s += 4;
1660                   continue;
1661                 }
1662               break;
1663
1664             case 'Z':
1665               if (*s == ' ')
1666                 {
1667                   ++s;
1668                 }
1669               if (strncmp (s, "%xcc", 4) == 0)
1670                 {
1671                   s += 4;
1672                   continue;
1673                 }
1674               break;
1675
1676             case '6':
1677               if (*s == ' ')
1678                 {
1679                   ++s;
1680                 }
1681               if (strncmp (s, "%fcc0", 5) == 0)
1682                 {
1683                   s += 5;
1684                   continue;
1685                 }
1686               break;
1687
1688             case '7':
1689               if (*s == ' ')
1690                 {
1691                   ++s;
1692                 }
1693               if (strncmp (s, "%fcc1", 5) == 0)
1694                 {
1695                   s += 5;
1696                   continue;
1697                 }
1698               break;
1699
1700             case '8':
1701               if (*s == ' ')
1702                 {
1703                   ++s;
1704                 }
1705               if (strncmp (s, "%fcc2", 5) == 0)
1706                 {
1707                   s += 5;
1708                   continue;
1709                 }
1710               break;
1711
1712             case '9':
1713               if (*s == ' ')
1714                 {
1715                   ++s;
1716                 }
1717               if (strncmp (s, "%fcc3", 5) == 0)
1718                 {
1719                   s += 5;
1720                   continue;
1721                 }
1722               break;
1723
1724             case 'P':
1725               if (strncmp (s, "%pc", 3) == 0)
1726                 {
1727                   s += 3;
1728                   continue;
1729                 }
1730               break;
1731
1732             case 'W':
1733               if (strncmp (s, "%tick", 5) == 0)
1734                 {
1735                   s += 5;
1736                   continue;
1737                 }
1738               break;
1739
1740             case '\0':          /* End of args.  */
1741               if (*s == '\0')
1742                 {
1743                   match = 1;
1744                 }
1745               break;
1746
1747             case '+':
1748               if (*s == '+')
1749                 {
1750                   ++s;
1751                   continue;
1752                 }
1753               if (*s == '-')
1754                 {
1755                   continue;
1756                 }
1757               break;
1758
1759             case '[':           /* These must match exactly.  */
1760             case ']':
1761             case ',':
1762             case ' ':
1763               if (*s++ == *args)
1764                 continue;
1765               break;
1766
1767             case '#':           /* Must be at least one digit.  */
1768               if (isdigit ((unsigned char) *s++))
1769                 {
1770                   while (isdigit ((unsigned char) *s))
1771                     {
1772                       ++s;
1773                     }
1774                   continue;
1775                 }
1776               break;
1777
1778             case 'C':           /* Coprocessor state register.  */
1779               if (strncmp (s, "%csr", 4) == 0)
1780                 {
1781                   s += 4;
1782                   continue;
1783                 }
1784               break;
1785
1786             case 'b':           /* Next operand is a coprocessor register.  */
1787             case 'c':
1788             case 'D':
1789               if (*s++ == '%' && *s++ == 'c' && isdigit ((unsigned char) *s))
1790                 {
1791                   mask = *s++;
1792                   if (isdigit ((unsigned char) *s))
1793                     {
1794                       mask = 10 * (mask - '0') + (*s++ - '0');
1795                       if (mask >= 32)
1796                         {
1797                           break;
1798                         }
1799                     }
1800                   else
1801                     {
1802                       mask -= '0';
1803                     }
1804                   switch (*args)
1805                     {
1806
1807                     case 'b':
1808                       opcode |= mask << 14;
1809                       continue;
1810
1811                     case 'c':
1812                       opcode |= mask;
1813                       continue;
1814
1815                     case 'D':
1816                       opcode |= mask << 25;
1817                       continue;
1818                     }
1819                 }
1820               break;
1821
1822             case 'r':           /* next operand must be a register */
1823             case 'O':
1824             case '1':
1825             case '2':
1826             case 'd':
1827               if (*s++ == '%')
1828                 {
1829                   switch (c = *s++)
1830                     {
1831
1832                     case 'f':   /* frame pointer */
1833                       if (*s++ == 'p')
1834                         {
1835                           mask = 0x1e;
1836                           break;
1837                         }
1838                       goto error;
1839
1840                     case 'g':   /* global register */
1841                       c = *s++;
1842                       if (isoctal (c))
1843                         {
1844                           mask = c - '0';
1845                           break;
1846                         }
1847                       goto error;
1848
1849                     case 'i':   /* in register */
1850                       c = *s++;
1851                       if (isoctal (c))
1852                         {
1853                           mask = c - '0' + 24;
1854                           break;
1855                         }
1856                       goto error;
1857
1858                     case 'l':   /* local register */
1859                       c = *s++;
1860                       if (isoctal (c))
1861                         {
1862                           mask = (c - '0' + 16);
1863                           break;
1864                         }
1865                       goto error;
1866
1867                     case 'o':   /* out register */
1868                       c = *s++;
1869                       if (isoctal (c))
1870                         {
1871                           mask = (c - '0' + 8);
1872                           break;
1873                         }
1874                       goto error;
1875
1876                     case 's':   /* stack pointer */
1877                       if (*s++ == 'p')
1878                         {
1879                           mask = 0xe;
1880                           break;
1881                         }
1882                       goto error;
1883
1884                     case 'r':   /* any register */
1885                       if (!isdigit ((unsigned char) (c = *s++)))
1886                         {
1887                           goto error;
1888                         }
1889                       /* FALLTHROUGH */
1890                     case '0':
1891                     case '1':
1892                     case '2':
1893                     case '3':
1894                     case '4':
1895                     case '5':
1896                     case '6':
1897                     case '7':
1898                     case '8':
1899                     case '9':
1900                       if (isdigit ((unsigned char) *s))
1901                         {
1902                           if ((c = 10 * (c - '0') + (*s++ - '0')) >= 32)
1903                             {
1904                               goto error;
1905                             }
1906                         }
1907                       else
1908                         {
1909                           c -= '0';
1910                         }
1911                       mask = c;
1912                       break;
1913
1914                     default:
1915                       goto error;
1916                     }
1917
1918                   if ((mask & ~1) == 2 && sparc_arch_size == 64
1919                       && no_undeclared_regs && ! globals[mask])
1920                     as_bad (_("detected global register use not covered by .register pseudo-op"));
1921
1922                   /* Got the register, now figure out where
1923                      it goes in the opcode.  */
1924                   switch (*args)
1925                     {
1926                     case '1':
1927                       opcode |= mask << 14;
1928                       continue;
1929
1930                     case '2':
1931                       opcode |= mask;
1932                       continue;
1933
1934                     case 'd':
1935                       opcode |= mask << 25;
1936                       continue;
1937
1938                     case 'r':
1939                       opcode |= (mask << 25) | (mask << 14);
1940                       continue;
1941
1942                     case 'O':
1943                       opcode |= (mask << 25) | (mask << 0);
1944                       continue;
1945                     }
1946                 }
1947               break;
1948
1949             case 'e':           /* next operand is a floating point register */
1950             case 'v':
1951             case 'V':
1952
1953             case 'f':
1954             case 'B':
1955             case 'R':
1956
1957             case 'g':
1958             case 'H':
1959             case 'J':
1960               {
1961                 char format;
1962
1963                 if (*s++ == '%'
1964                     && ((format = *s) == 'f')
1965                     && isdigit ((unsigned char) *++s))
1966                   {
1967                     for (mask = 0; isdigit ((unsigned char) *s); ++s)
1968                       {
1969                         mask = 10 * mask + (*s - '0');
1970                       }         /* read the number */
1971
1972                     if ((*args == 'v'
1973                          || *args == 'B'
1974                          || *args == 'H')
1975                         && (mask & 1))
1976                       {
1977                         break;
1978                       }         /* register must be even numbered */
1979
1980                     if ((*args == 'V'
1981                          || *args == 'R'
1982                          || *args == 'J')
1983                         && (mask & 3))
1984                       {
1985                         break;
1986                       }         /* register must be multiple of 4 */
1987
1988                     if (mask >= 64)
1989                       {
1990                         if (SPARC_OPCODE_ARCH_V9_P (max_architecture))
1991                           error_message = _(": There are only 64 f registers; [0-63]");
1992                         else
1993                           error_message = _(": There are only 32 f registers; [0-31]");
1994                         goto error;
1995                       } /* on error */
1996                     else if (mask >= 32)
1997                       {
1998                         if (SPARC_OPCODE_ARCH_V9_P (max_architecture))
1999                           {
2000                             v9_arg_p = 1;
2001                             mask -= 31; /* wrap high bit */
2002                           }
2003                         else
2004                           {
2005                             error_message = _(": There are only 32 f registers; [0-31]");
2006                             goto error;
2007                           }
2008                       }
2009                   }
2010                 else
2011                   {
2012                     break;
2013                   }     /* if not an 'f' register.  */
2014
2015                 switch (*args)
2016                   {
2017                   case 'v':
2018                   case 'V':
2019                   case 'e':
2020                     opcode |= RS1 (mask);
2021                     continue;
2022
2023                   case 'f':
2024                   case 'B':
2025                   case 'R':
2026                     opcode |= RS2 (mask);
2027                     continue;
2028
2029                   case 'g':
2030                   case 'H':
2031                   case 'J':
2032                     opcode |= RD (mask);
2033                     continue;
2034                   }             /* Pack it in.  */
2035
2036                 know (0);
2037                 break;
2038               }                 /* float arg  */
2039
2040             case 'F':
2041               if (strncmp (s, "%fsr", 4) == 0)
2042                 {
2043                   s += 4;
2044                   continue;
2045                 }
2046               break;
2047
2048             case '0':           /* 64 bit immediate (set, setsw, setx insn)  */
2049               the_insn.reloc = BFD_RELOC_NONE; /* reloc handled elsewhere  */
2050               goto immediate;
2051
2052             case 'l':           /* 22 bit PC relative immediate  */
2053               the_insn.reloc = BFD_RELOC_SPARC_WDISP22;
2054               the_insn.pcrel = 1;
2055               goto immediate;
2056
2057             case 'L':           /* 30 bit immediate  */
2058               the_insn.reloc = BFD_RELOC_32_PCREL_S2;
2059               the_insn.pcrel = 1;
2060               goto immediate;
2061
2062             case 'h':
2063             case 'n':           /* 22 bit immediate  */
2064               the_insn.reloc = BFD_RELOC_SPARC22;
2065               goto immediate;
2066
2067             case 'i':           /* 13 bit immediate  */
2068               the_insn.reloc = BFD_RELOC_SPARC13;
2069
2070               /* fallthrough */
2071
2072             immediate:
2073               if (*s == ' ')
2074                 s++;
2075
2076               {
2077                 char *s1;
2078                 char *op_arg = NULL;
2079                 expressionS op_exp;
2080                 bfd_reloc_code_real_type old_reloc = the_insn.reloc;
2081
2082                 /* Check for %hi, etc.  */
2083                 if (*s == '%')
2084                   {
2085                     static const struct ops {
2086                       /* The name as it appears in assembler.  */
2087                       char *name;
2088                       /* strlen (name), precomputed for speed */
2089                       int len;
2090                       /* The reloc this pseudo-op translates to.  */
2091                       int reloc;
2092                       /* Non-zero if for v9 only.  */
2093                       int v9_p;
2094                       /* Non-zero if can be used in pc-relative contexts.  */
2095                       int pcrel_p;/*FIXME:wip*/
2096                     } ops[] = {
2097                       /* hix/lox must appear before hi/lo so %hix won't be
2098                          mistaken for %hi.  */
2099                       { "hix", 3, BFD_RELOC_SPARC_HIX22, 1, 0 },
2100                       { "lox", 3, BFD_RELOC_SPARC_LOX10, 1, 0 },
2101                       { "hi", 2, BFD_RELOC_HI22, 0, 1 },
2102                       { "lo", 2, BFD_RELOC_LO10, 0, 1 },
2103                       { "hh", 2, BFD_RELOC_SPARC_HH22, 1, 1 },
2104                       { "hm", 2, BFD_RELOC_SPARC_HM10, 1, 1 },
2105                       { "lm", 2, BFD_RELOC_SPARC_LM22, 1, 1 },
2106                       { "h44", 3, BFD_RELOC_SPARC_H44, 1, 0 },
2107                       { "m44", 3, BFD_RELOC_SPARC_M44, 1, 0 },
2108                       { "l44", 3, BFD_RELOC_SPARC_L44, 1, 0 },
2109                       { "uhi", 3, BFD_RELOC_SPARC_HH22, 1, 0 },
2110                       { "ulo", 3, BFD_RELOC_SPARC_HM10, 1, 0 },
2111                       { NULL }
2112                     };
2113                     const struct ops *o;
2114
2115                     for (o = ops; o->name; o++)
2116                       if (strncmp (s + 1, o->name, o->len) == 0)
2117                         break;
2118                     if (o->name == NULL)
2119                       break;
2120
2121                     if (s[o->len + 1] != '(')
2122                       {
2123                         as_bad (_("Illegal operands: %%%s requires arguments in ()"), o->name);
2124                         return special_case;
2125                       }
2126
2127                     op_arg = o->name;
2128                     the_insn.reloc = o->reloc;
2129                     s += o->len + 2;
2130                     v9_arg_p = o->v9_p;
2131                   }
2132
2133                 /* Note that if the get_expression() fails, we will still
2134                    have created U entries in the symbol table for the
2135                    'symbols' in the input string.  Try not to create U
2136                    symbols for registers, etc.  */
2137
2138                 /* This stuff checks to see if the expression ends in
2139                    +%reg.  If it does, it removes the register from
2140                    the expression, and re-sets 's' to point to the
2141                    right place.  */
2142
2143                 if (op_arg)
2144                   {
2145                     int npar = 0;
2146
2147                     for (s1 = s; *s1 && *s1 != ',' && *s1 != ']'; s1++)
2148                       if (*s1 == '(')
2149                         npar++;
2150                       else if (*s1 == ')')
2151                         {
2152                           if (!npar)
2153                             break;
2154                           npar--;
2155                         }
2156
2157                     if (*s1 != ')')
2158                       {
2159                         as_bad (_("Illegal operands: %%%s requires arguments in ()"), op_arg);
2160                         return special_case;
2161                       }
2162
2163                     *s1 = '\0';
2164                     (void) get_expression (s);
2165                     *s1 = ')';
2166                     s = s1 + 1;
2167                     if (*s == ',' || *s == ']' || !*s)
2168                       continue;
2169                     if (*s != '+' && *s != '-')
2170                       {
2171                         as_bad (_("Illegal operands: Can't do arithmetics other than + and - involving %%%s()"), op_arg);
2172                         return special_case;
2173                       }
2174                     *s1 = '0';
2175                     s = s1;
2176                     op_exp = the_insn.exp;
2177                     memset (&the_insn.exp, 0, sizeof (the_insn.exp));
2178                   }
2179
2180                 for (s1 = s; *s1 && *s1 != ',' && *s1 != ']'; s1++)
2181                   ;
2182
2183                 if (s1 != s && isdigit ((unsigned char) s1[-1]))
2184                   {
2185                     if (s1[-2] == '%' && s1[-3] == '+')
2186                       s1 -= 3;
2187                     else if (strchr ("goli0123456789", s1[-2]) && s1[-3] == '%' && s1[-4] == '+')
2188                       s1 -= 4;
2189                     else
2190                       s1 = NULL;
2191                     if (s1)
2192                       {
2193                         *s1 = '\0';
2194                         if (op_arg && s1 == s + 1)
2195                           the_insn.exp.X_op = O_absent;
2196                         else
2197                           (void) get_expression (s);
2198                         *s1 = '+';
2199                         if (op_arg)
2200                           *s = ')';
2201                         s = s1;
2202                       }
2203                   }
2204                 else
2205                   s1 = NULL;
2206
2207                 if (!s1)
2208                   {
2209                     (void) get_expression (s);
2210                     if (op_arg)
2211                       *s = ')';
2212                     s = expr_end;
2213                   }
2214
2215                 if (op_arg)
2216                   {
2217                     the_insn.exp2 = the_insn.exp;
2218                     the_insn.exp = op_exp;
2219                     if (the_insn.exp2.X_op == O_absent)
2220                       the_insn.exp2.X_op = O_illegal;
2221                     else if (the_insn.exp.X_op == O_absent)
2222                       {
2223                         the_insn.exp = the_insn.exp2;
2224                         the_insn.exp2.X_op = O_illegal;
2225                       }
2226                     else if (the_insn.exp.X_op == O_constant)
2227                       {
2228                         valueT val = the_insn.exp.X_add_number;
2229                         switch (the_insn.reloc)
2230                           {
2231                           default:
2232                             break;
2233
2234                           case BFD_RELOC_SPARC_HH22:
2235                             val = BSR (val, 32);
2236                             /* Fall through.  */
2237
2238                           case BFD_RELOC_SPARC_LM22:
2239                           case BFD_RELOC_HI22:
2240                             val = (val >> 10) & 0x3fffff;
2241                             break;
2242
2243                           case BFD_RELOC_SPARC_HM10:
2244                             val = BSR (val, 32);
2245                             /* Fall through.  */
2246
2247                           case BFD_RELOC_LO10:
2248                             val &= 0x3ff;
2249                             break;
2250
2251                           case BFD_RELOC_SPARC_H44:
2252                             val >>= 22;
2253                             val &= 0x3fffff;
2254                             break;
2255
2256                           case BFD_RELOC_SPARC_M44:
2257                             val >>= 12;
2258                             val &= 0x3ff;
2259                             break;
2260
2261                           case BFD_RELOC_SPARC_L44:
2262                             val &= 0xfff;
2263                             break;
2264
2265                           case BFD_RELOC_SPARC_HIX22:
2266                             val = ~val;
2267                             val = (val >> 10) & 0x3fffff;
2268                             break;
2269
2270                           case BFD_RELOC_SPARC_LOX10:
2271                             val = (val & 0x3ff) | 0x1c00;
2272                             break;
2273                           }
2274                         the_insn.exp = the_insn.exp2;
2275                         the_insn.exp.X_add_number += val;
2276                         the_insn.exp2.X_op = O_illegal;
2277                         the_insn.reloc = old_reloc;
2278                       }
2279                     else if (the_insn.exp2.X_op != O_constant)
2280                       {
2281                         as_bad (_("Illegal operands: Can't add non-constant expression to %%%s()"), op_arg);
2282                         return special_case;
2283                       }
2284                     else
2285                       {
2286                         if (old_reloc != BFD_RELOC_SPARC13
2287                             || the_insn.reloc != BFD_RELOC_LO10
2288                             || sparc_arch_size != 64
2289                             || sparc_pic_code)
2290                           {
2291                             as_bad (_("Illegal operands: Can't do arithmetics involving %%%s() of a relocatable symbol"), op_arg);
2292                             return special_case;
2293                           }
2294                         the_insn.reloc = BFD_RELOC_SPARC_OLO10;
2295                       }
2296                   }
2297               }
2298               /* Check for constants that don't require emitting a reloc.  */
2299               if (the_insn.exp.X_op == O_constant
2300                   && the_insn.exp.X_add_symbol == 0
2301                   && the_insn.exp.X_op_symbol == 0)
2302                 {
2303                   /* For pc-relative call instructions, we reject
2304                      constants to get better code.  */
2305                   if (the_insn.pcrel
2306                       && the_insn.reloc == BFD_RELOC_32_PCREL_S2
2307                       && in_signed_range (the_insn.exp.X_add_number, 0x3fff))
2308                     {
2309                       error_message = _(": PC-relative operand can't be a constant");
2310                       goto error;
2311                     }
2312
2313                   /* Constants that won't fit are checked in md_apply_fix3
2314                      and bfd_install_relocation.
2315                      ??? It would be preferable to install the constants
2316                      into the insn here and save having to create a fixS
2317                      for each one.  There already exists code to handle
2318                      all the various cases (e.g. in md_apply_fix3 and
2319                      bfd_install_relocation) so duplicating all that code
2320                      here isn't right.  */
2321                 }
2322
2323               continue;
2324
2325             case 'a':
2326               if (*s++ == 'a')
2327                 {
2328                   opcode |= ANNUL;
2329                   continue;
2330                 }
2331               break;
2332
2333             case 'A':
2334               {
2335                 int asi = 0;
2336
2337                 /* Parse an asi.  */
2338                 if (*s == '#')
2339                   {
2340                     if (! parse_keyword_arg (sparc_encode_asi, &s, &asi))
2341                       {
2342                         error_message = _(": invalid ASI name");
2343                         goto error;
2344                       }
2345                   }
2346                 else
2347                   {
2348                     if (! parse_const_expr_arg (&s, &asi))
2349                       {
2350                         error_message = _(": invalid ASI expression");
2351                         goto error;
2352                       }
2353                     if (asi < 0 || asi > 255)
2354                       {
2355                         error_message = _(": invalid ASI number");
2356                         goto error;
2357                       }
2358                   }
2359                 opcode |= ASI (asi);
2360                 continue;
2361               }                 /* Alternate space.  */
2362
2363             case 'p':
2364               if (strncmp (s, "%psr", 4) == 0)
2365                 {
2366                   s += 4;
2367                   continue;
2368                 }
2369               break;
2370
2371             case 'q':           /* Floating point queue.  */
2372               if (strncmp (s, "%fq", 3) == 0)
2373                 {
2374                   s += 3;
2375                   continue;
2376                 }
2377               break;
2378
2379             case 'Q':           /* Coprocessor queue.  */
2380               if (strncmp (s, "%cq", 3) == 0)
2381                 {
2382                   s += 3;
2383                   continue;
2384                 }
2385               break;
2386
2387             case 'S':
2388               if (strcmp (str, "set") == 0
2389                   || strcmp (str, "setuw") == 0)
2390                 {
2391                   special_case = SPECIAL_CASE_SET;
2392                   continue;
2393                 }
2394               else if (strcmp (str, "setsw") == 0)
2395                 {
2396                   special_case = SPECIAL_CASE_SETSW;
2397                   continue;
2398                 }
2399               else if (strcmp (str, "setx") == 0)
2400                 {
2401                   special_case = SPECIAL_CASE_SETX;
2402                   continue;
2403                 }
2404               else if (strncmp (str, "fdiv", 4) == 0)
2405                 {
2406                   special_case = SPECIAL_CASE_FDIV;
2407                   continue;
2408                 }
2409               break;
2410
2411             case 'o':
2412               if (strncmp (s, "%asi", 4) != 0)
2413                 break;
2414               s += 4;
2415               continue;
2416
2417             case 's':
2418               if (strncmp (s, "%fprs", 5) != 0)
2419                 break;
2420               s += 5;
2421               continue;
2422
2423             case 'E':
2424               if (strncmp (s, "%ccr", 4) != 0)
2425                 break;
2426               s += 4;
2427               continue;
2428
2429             case 't':
2430               if (strncmp (s, "%tbr", 4) != 0)
2431                 break;
2432               s += 4;
2433               continue;
2434
2435             case 'w':
2436               if (strncmp (s, "%wim", 4) != 0)
2437                 break;
2438               s += 4;
2439               continue;
2440
2441             case 'x':
2442               {
2443                 char *push = input_line_pointer;
2444                 expressionS e;
2445
2446                 input_line_pointer = s;
2447                 expression (&e);
2448                 if (e.X_op == O_constant)
2449                   {
2450                     int n = e.X_add_number;
2451                     if (n != e.X_add_number || (n & ~0x1ff) != 0)
2452                       as_bad (_("OPF immediate operand out of range (0-0x1ff)"));
2453                     else
2454                       opcode |= e.X_add_number << 5;
2455                   }
2456                 else
2457                   as_bad (_("non-immediate OPF operand, ignored"));
2458                 s = input_line_pointer;
2459                 input_line_pointer = push;
2460                 continue;
2461               }
2462
2463             case 'y':
2464               if (strncmp (s, "%y", 2) != 0)
2465                 break;
2466               s += 2;
2467               continue;
2468
2469             case 'u':
2470             case 'U':
2471               {
2472                 /* Parse a sparclet cpreg.  */
2473                 int cpreg;
2474                 if (! parse_keyword_arg (sparc_encode_sparclet_cpreg, &s, &cpreg))
2475                   {
2476                     error_message = _(": invalid cpreg name");
2477                     goto error;
2478                   }
2479                 opcode |= (*args == 'U' ? RS1 (cpreg) : RD (cpreg));
2480                 continue;
2481               }
2482
2483             default:
2484               as_fatal (_("failed sanity check."));
2485             }                   /* switch on arg code.  */
2486
2487           /* Break out of for() loop.  */
2488           break;
2489         }                       /* For each arg that we expect.  */
2490
2491     error:
2492       if (match == 0)
2493         {
2494           /* Args don't match.  */
2495           if (&insn[1] - sparc_opcodes < sparc_num_opcodes
2496               && (insn->name == insn[1].name
2497                   || !strcmp (insn->name, insn[1].name)))
2498             {
2499               ++insn;
2500               s = argsStart;
2501               continue;
2502             }
2503           else
2504             {
2505               as_bad (_("Illegal operands%s"), error_message);
2506               return special_case;
2507             }
2508         }
2509       else
2510         {
2511           /* We have a match.  Now see if the architecture is OK.  */
2512           int needed_arch_mask = insn->architecture;
2513
2514           if (v9_arg_p)
2515             {
2516               needed_arch_mask &= ~((1 << SPARC_OPCODE_ARCH_V9)
2517                                     | (1 << SPARC_OPCODE_ARCH_V9A));
2518               needed_arch_mask |= (1 << SPARC_OPCODE_ARCH_V9);
2519             }
2520
2521           if (needed_arch_mask
2522               & SPARC_OPCODE_SUPPORTED (current_architecture))
2523             /* OK.  */
2524             ;
2525           /* Can we bump up the architecture?  */
2526           else if (needed_arch_mask
2527                    & SPARC_OPCODE_SUPPORTED (max_architecture))
2528             {
2529               enum sparc_opcode_arch_val needed_architecture =
2530                 sparc_ffs (SPARC_OPCODE_SUPPORTED (max_architecture)
2531                            & needed_arch_mask);
2532
2533               assert (needed_architecture <= SPARC_OPCODE_ARCH_MAX);
2534               if (warn_on_bump
2535                   && needed_architecture > warn_after_architecture)
2536                 {
2537                   as_warn (_("architecture bumped from \"%s\" to \"%s\" on \"%s\""),
2538                            sparc_opcode_archs[current_architecture].name,
2539                            sparc_opcode_archs[needed_architecture].name,
2540                            str);
2541                   warn_after_architecture = needed_architecture;
2542                 }
2543               current_architecture = needed_architecture;
2544             }
2545           /* Conflict.  */
2546           /* ??? This seems to be a bit fragile.  What if the next entry in
2547              the opcode table is the one we want and it is supported?
2548              It is possible to arrange the table today so that this can't
2549              happen but what about tomorrow?  */
2550           else
2551             {
2552               int arch, printed_one_p = 0;
2553               char *p;
2554               char required_archs[SPARC_OPCODE_ARCH_MAX * 16];
2555
2556               /* Create a list of the architectures that support the insn.  */
2557               needed_arch_mask &= ~SPARC_OPCODE_SUPPORTED (max_architecture);
2558               p = required_archs;
2559               arch = sparc_ffs (needed_arch_mask);
2560               while ((1 << arch) <= needed_arch_mask)
2561                 {
2562                   if ((1 << arch) & needed_arch_mask)
2563                     {
2564                       if (printed_one_p)
2565                         *p++ = '|';
2566                       strcpy (p, sparc_opcode_archs[arch].name);
2567                       p += strlen (p);
2568                       printed_one_p = 1;
2569                     }
2570                   ++arch;
2571                 }
2572
2573               as_bad (_("Architecture mismatch on \"%s\"."), str);
2574               as_tsktsk (_(" (Requires %s; requested architecture is %s.)"),
2575                          required_archs,
2576                          sparc_opcode_archs[max_architecture].name);
2577               return special_case;
2578             }
2579         } /* If no match.  */
2580
2581       break;
2582     } /* Forever looking for a match.  */
2583
2584   the_insn.opcode = opcode;
2585   return special_case;
2586 }
2587
2588 /* Parse an argument that can be expressed as a keyword.
2589    (eg: #StoreStore or %ccfr).
2590    The result is a boolean indicating success.
2591    If successful, INPUT_POINTER is updated.  */
2592
2593 static int
2594 parse_keyword_arg (lookup_fn, input_pointerP, valueP)
2595      int (*lookup_fn) PARAMS ((const char *));
2596      char **input_pointerP;
2597      int *valueP;
2598 {
2599   int value;
2600   char c, *p, *q;
2601
2602   p = *input_pointerP;
2603   for (q = p + (*p == '#' || *p == '%');
2604        isalnum ((unsigned char) *q) || *q == '_';
2605        ++q)
2606     continue;
2607   c = *q;
2608   *q = 0;
2609   value = (*lookup_fn) (p);
2610   *q = c;
2611   if (value == -1)
2612     return 0;
2613   *valueP = value;
2614   *input_pointerP = q;
2615   return 1;
2616 }
2617
2618 /* Parse an argument that is a constant expression.
2619    The result is a boolean indicating success.  */
2620
2621 static int
2622 parse_const_expr_arg (input_pointerP, valueP)
2623      char **input_pointerP;
2624      int *valueP;
2625 {
2626   char *save = input_line_pointer;
2627   expressionS exp;
2628
2629   input_line_pointer = *input_pointerP;
2630   /* The next expression may be something other than a constant
2631      (say if we're not processing the right variant of the insn).
2632      Don't call expression unless we're sure it will succeed as it will
2633      signal an error (which we want to defer until later).  */
2634   /* FIXME: It might be better to define md_operand and have it recognize
2635      things like %asi, etc. but continuing that route through to the end
2636      is a lot of work.  */
2637   if (*input_line_pointer == '%')
2638     {
2639       input_line_pointer = save;
2640       return 0;
2641     }
2642   expression (&exp);
2643   *input_pointerP = input_line_pointer;
2644   input_line_pointer = save;
2645   if (exp.X_op != O_constant)
2646     return 0;
2647   *valueP = exp.X_add_number;
2648   return 1;
2649 }
2650
2651 /* Subroutine of sparc_ip to parse an expression.  */
2652
2653 static int
2654 get_expression (str)
2655      char *str;
2656 {
2657   char *save_in;
2658   segT seg;
2659
2660   save_in = input_line_pointer;
2661   input_line_pointer = str;
2662   seg = expression (&the_insn.exp);
2663   if (seg != absolute_section
2664       && seg != text_section
2665       && seg != data_section
2666       && seg != bss_section
2667       && seg != undefined_section)
2668     {
2669       the_insn.error = _("bad segment");
2670       expr_end = input_line_pointer;
2671       input_line_pointer = save_in;
2672       return 1;
2673     }
2674   expr_end = input_line_pointer;
2675   input_line_pointer = save_in;
2676   return 0;
2677 }
2678
2679 /* Subroutine of md_assemble to output one insn.  */
2680
2681 static void
2682 output_insn (insn, the_insn)
2683      const struct sparc_opcode *insn;
2684      struct sparc_it *the_insn;
2685 {
2686   char *toP = frag_more (4);
2687
2688   /* Put out the opcode.  */
2689   if (INSN_BIG_ENDIAN)
2690     number_to_chars_bigendian (toP, (valueT) the_insn->opcode, 4);
2691   else
2692     number_to_chars_littleendian (toP, (valueT) the_insn->opcode, 4);
2693
2694   /* Put out the symbol-dependent stuff.  */
2695   if (the_insn->reloc != BFD_RELOC_NONE)
2696     {
2697       fixS *fixP =  fix_new_exp (frag_now,      /* Which frag.  */
2698                                  (toP - frag_now->fr_literal),  /* Where.  */
2699                                  4,             /* Size.  */
2700                                  &the_insn->exp,
2701                                  the_insn->pcrel,
2702                                  the_insn->reloc);
2703       /* Turn off overflow checking in fixup_segment.  We'll do our
2704          own overflow checking in md_apply_fix3.  This is necessary because
2705          the insn size is 4 and fixup_segment will signal an overflow for
2706          large 8 byte quantities.  */
2707       fixP->fx_no_overflow = 1;
2708       if (the_insn->reloc == BFD_RELOC_SPARC_OLO10)
2709         fixP->tc_fix_data = the_insn->exp2.X_add_number;
2710     }
2711
2712   last_insn = insn;
2713   last_opcode = the_insn->opcode;
2714 }
2715 \f
2716 /* This is identical to the md_atof in m68k.c.  I think this is right,
2717    but I'm not sure.
2718
2719    Turn a string in input_line_pointer into a floating point constant
2720    of type TYPE, and store the appropriate bytes in *LITP.  The number
2721    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
2722    returned, or NULL on OK.  */
2723
2724 /* Equal to MAX_PRECISION in atof-ieee.c.  */
2725 #define MAX_LITTLENUMS 6
2726
2727 char *
2728 md_atof (type, litP, sizeP)
2729      char type;
2730      char *litP;
2731      int *sizeP;
2732 {
2733   int i, prec;
2734   LITTLENUM_TYPE words[MAX_LITTLENUMS];
2735   char *t;
2736
2737   switch (type)
2738     {
2739     case 'f':
2740     case 'F':
2741     case 's':
2742     case 'S':
2743       prec = 2;
2744       break;
2745
2746     case 'd':
2747     case 'D':
2748     case 'r':
2749     case 'R':
2750       prec = 4;
2751       break;
2752
2753     case 'x':
2754     case 'X':
2755       prec = 6;
2756       break;
2757
2758     case 'p':
2759     case 'P':
2760       prec = 6;
2761       break;
2762
2763     default:
2764       *sizeP = 0;
2765       return _("Bad call to MD_ATOF()");
2766     }
2767
2768   t = atof_ieee (input_line_pointer, type, words);
2769   if (t)
2770     input_line_pointer = t;
2771   *sizeP = prec * sizeof (LITTLENUM_TYPE);
2772
2773   if (target_big_endian)
2774     {
2775       for (i = 0; i < prec; i++)
2776         {
2777           md_number_to_chars (litP, (valueT) words[i],
2778                               sizeof (LITTLENUM_TYPE));
2779           litP += sizeof (LITTLENUM_TYPE);
2780         }
2781     }
2782   else
2783     {
2784       for (i = prec - 1; i >= 0; i--)
2785         {
2786           md_number_to_chars (litP, (valueT) words[i],
2787                               sizeof (LITTLENUM_TYPE));
2788           litP += sizeof (LITTLENUM_TYPE);
2789         }
2790     }
2791
2792   return 0;
2793 }
2794
2795 /* Write a value out to the object file, using the appropriate
2796    endianness.  */
2797
2798 void
2799 md_number_to_chars (buf, val, n)
2800      char *buf;
2801      valueT val;
2802      int n;
2803 {
2804   if (target_big_endian)
2805     number_to_chars_bigendian (buf, val, n);
2806   else if (target_little_endian_data
2807            && ((n == 4 || n == 2) && ~now_seg->flags & SEC_ALLOC))
2808     /* Output debug words, which are not in allocated sections, as big
2809        endian.  */
2810     number_to_chars_bigendian (buf, val, n);
2811   else if (target_little_endian_data || ! target_big_endian)
2812     number_to_chars_littleendian (buf, val, n);
2813 }
2814 \f
2815 /* Apply a fixS to the frags, now that we know the value it ought to
2816    hold. */
2817
2818 int
2819 md_apply_fix3 (fixP, value, segment)
2820      fixS *fixP;
2821      valueT *value;
2822      segT segment;
2823 {
2824   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
2825   offsetT val;
2826   long insn;
2827
2828   val = *value;
2829
2830   assert (fixP->fx_r_type < BFD_RELOC_UNUSED);
2831
2832   fixP->fx_addnumber = val;     /* Remember value for emit_reloc.  */
2833
2834 #ifdef OBJ_ELF
2835   /* FIXME: SPARC ELF relocations don't use an addend in the data
2836      field itself.  This whole approach should be somehow combined
2837      with the calls to bfd_install_relocation.  Also, the value passed
2838      in by fixup_segment includes the value of a defined symbol.  We
2839      don't want to include the value of an externally visible symbol.  */
2840   if (fixP->fx_addsy != NULL)
2841     {
2842       if (symbol_used_in_reloc_p (fixP->fx_addsy)
2843           && (S_IS_EXTERNAL (fixP->fx_addsy)
2844               || S_IS_WEAK (fixP->fx_addsy)
2845               || (sparc_pic_code && ! fixP->fx_pcrel)
2846               || (S_GET_SEGMENT (fixP->fx_addsy) != segment
2847                   && ((bfd_get_section_flags (stdoutput,
2848                                               S_GET_SEGMENT (fixP->fx_addsy))
2849                        & SEC_LINK_ONCE) != 0
2850                       || strncmp (segment_name (S_GET_SEGMENT (fixP->fx_addsy)),
2851                                   ".gnu.linkonce",
2852                                   sizeof ".gnu.linkonce" - 1) == 0)))
2853           && S_GET_SEGMENT (fixP->fx_addsy) != absolute_section
2854           && S_GET_SEGMENT (fixP->fx_addsy) != undefined_section
2855           && ! bfd_is_com_section (S_GET_SEGMENT (fixP->fx_addsy)))
2856         fixP->fx_addnumber -= S_GET_VALUE (fixP->fx_addsy);
2857       return 1;
2858     }
2859 #endif
2860
2861   /* This is a hack.  There should be a better way to
2862      handle this.  Probably in terms of howto fields, once
2863      we can look at these fixups in terms of howtos.  */
2864   if (fixP->fx_r_type == BFD_RELOC_32_PCREL_S2 && fixP->fx_addsy)
2865     val += fixP->fx_where + fixP->fx_frag->fr_address;
2866
2867 #ifdef OBJ_AOUT
2868   /* FIXME: More ridiculous gas reloc hacking.  If we are going to
2869      generate a reloc, then we just want to let the reloc addend set
2870      the value.  We do not want to also stuff the addend into the
2871      object file.  Including the addend in the object file works when
2872      doing a static link, because the linker will ignore the object
2873      file contents.  However, the dynamic linker does not ignore the
2874      object file contents.  */
2875   if (fixP->fx_addsy != NULL
2876       && fixP->fx_r_type != BFD_RELOC_32_PCREL_S2)
2877     val = 0;
2878
2879   /* When generating PIC code, we do not want an addend for a reloc
2880      against a local symbol.  We adjust fx_addnumber to cancel out the
2881      value already included in val, and to also cancel out the
2882      adjustment which bfd_install_relocation will create.  */
2883   if (sparc_pic_code
2884       && fixP->fx_r_type != BFD_RELOC_32_PCREL_S2
2885       && fixP->fx_addsy != NULL
2886       && ! S_IS_COMMON (fixP->fx_addsy)
2887       && symbol_section_p (fixP->fx_addsy))
2888     fixP->fx_addnumber -= 2 * S_GET_VALUE (fixP->fx_addsy);
2889
2890   /* When generating PIC code, we need to fiddle to get
2891      bfd_install_relocation to do the right thing for a PC relative
2892      reloc against a local symbol which we are going to keep.  */
2893   if (sparc_pic_code
2894       && fixP->fx_r_type == BFD_RELOC_32_PCREL_S2
2895       && fixP->fx_addsy != NULL
2896       && (S_IS_EXTERNAL (fixP->fx_addsy)
2897           || S_IS_WEAK (fixP->fx_addsy))
2898       && S_IS_DEFINED (fixP->fx_addsy)
2899       && ! S_IS_COMMON (fixP->fx_addsy))
2900     {
2901       val = 0;
2902       fixP->fx_addnumber -= 2 * S_GET_VALUE (fixP->fx_addsy);
2903     }
2904 #endif
2905
2906   /* If this is a data relocation, just output VAL.  */
2907
2908   if (fixP->fx_r_type == BFD_RELOC_16)
2909     {
2910       md_number_to_chars (buf, val, 2);
2911     }
2912   else if (fixP->fx_r_type == BFD_RELOC_32
2913            || fixP->fx_r_type == BFD_RELOC_SPARC_REV32)
2914     {
2915       md_number_to_chars (buf, val, 4);
2916     }
2917   else if (fixP->fx_r_type == BFD_RELOC_64)
2918     {
2919       md_number_to_chars (buf, val, 8);
2920     }
2921   else if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2922            || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
2923     {
2924       fixP->fx_done = 0;
2925       return 1;
2926     }
2927   else
2928     {
2929       /* It's a relocation against an instruction.  */
2930
2931       if (INSN_BIG_ENDIAN)
2932         insn = bfd_getb32 ((unsigned char *) buf);
2933       else
2934         insn = bfd_getl32 ((unsigned char *) buf);
2935
2936       switch (fixP->fx_r_type)
2937         {
2938         case BFD_RELOC_32_PCREL_S2:
2939           val = val >> 2;
2940           /* FIXME: This increment-by-one deserves a comment of why it's
2941              being done!  */
2942           if (! sparc_pic_code
2943               || fixP->fx_addsy == NULL
2944               || symbol_section_p (fixP->fx_addsy))
2945             ++val;
2946
2947           insn |= val & 0x3fffffff;
2948
2949           /* See if we have a delay slot.  */
2950           if (sparc_relax && fixP->fx_where + 8 <= fixP->fx_frag->fr_fix)
2951             {
2952 #define G0              0
2953 #define O7              15
2954 #define XCC             (2 << 20)
2955 #define COND(x)         (((x)&0xf)<<25)
2956 #define CONDA           COND(0x8)
2957 #define INSN_BPA        (F2(0,1) | CONDA | BPRED | XCC)
2958 #define INSN_BA         (F2(0,2) | CONDA)
2959 #define INSN_OR         F3(2, 0x2, 0)
2960 #define INSN_NOP        F2(0,4)
2961
2962               long delay;
2963
2964               /* If the instruction is a call with either:
2965                  restore
2966                  arithmetic instruction with rd == %o7
2967                  where rs1 != %o7 and rs2 if it is register != %o7
2968                  then we can optimize if the call destination is near
2969                  by changing the call into a branch always.  */
2970               if (INSN_BIG_ENDIAN)
2971                 delay = bfd_getb32 ((unsigned char *) buf + 4);
2972               else
2973                 delay = bfd_getl32 ((unsigned char *) buf + 4);
2974               if ((insn & OP (~0)) != OP (1) || (delay & OP (~0)) != OP (2))
2975                 break;
2976               if ((delay & OP3 (~0)) != OP3 (0x3d) /* Restore.  */
2977                   && ((delay & OP3 (0x28)) != 0 /* Arithmetic.  */
2978                       || ((delay & RD (~0)) != RD (O7))))
2979                 break;
2980               if ((delay & RS1 (~0)) == RS1 (O7)
2981                   || ((delay & F3I (~0)) == 0
2982                       && (delay & RS2 (~0)) == RS2 (O7)))
2983                 break;
2984               /* Ensure the branch will fit into simm22.  */
2985               if ((val & 0x3fe00000)
2986                   && (val & 0x3fe00000) != 0x3fe00000)
2987                 break;
2988               /* Check if the arch is v9 and branch will fit
2989                  into simm19.  */
2990               if (((val & 0x3c0000) == 0
2991                    || (val & 0x3c0000) == 0x3c0000)
2992                   && (sparc_arch_size == 64
2993                       || current_architecture >= SPARC_OPCODE_ARCH_V9))
2994                 /* ba,pt %xcc  */
2995                 insn = INSN_BPA | (val & 0x7ffff);
2996               else
2997                 /* ba  */
2998                 insn = INSN_BA | (val & 0x3fffff);
2999               if (fixP->fx_where >= 4
3000                   && ((delay & (0xffffffff ^ RS1 (~0)))
3001                       == (INSN_OR | RD (O7) | RS2 (G0))))
3002                 {
3003                   long setter;
3004                   int reg;
3005
3006                   if (INSN_BIG_ENDIAN)
3007                     setter = bfd_getb32 ((unsigned char *) buf - 4);
3008                   else
3009                     setter = bfd_getl32 ((unsigned char *) buf - 4);
3010                   if ((setter & (0xffffffff ^ RD (~0)))
3011                       != (INSN_OR | RS1 (O7) | RS2 (G0)))
3012                     break;
3013                   /* The sequence was
3014                      or %o7, %g0, %rN
3015                      call foo
3016                      or %rN, %g0, %o7
3017
3018                      If call foo was replaced with ba, replace
3019                      or %rN, %g0, %o7 with nop.  */
3020                   reg = (delay & RS1 (~0)) >> 14;
3021                   if (reg != ((setter & RD (~0)) >> 25)
3022                       || reg == G0 || reg == O7)
3023                     break;
3024
3025                   if (INSN_BIG_ENDIAN)
3026                     bfd_putb32 (INSN_NOP, (unsigned char *) buf + 4);
3027                   else
3028                     bfd_putl32 (INSN_NOP, (unsigned char *) buf + 4);
3029                 }
3030             }
3031           break;
3032
3033         case BFD_RELOC_SPARC_11:
3034           if (! in_signed_range (val, 0x7ff))
3035             as_bad_where (fixP->fx_file, fixP->fx_line,
3036                           _("relocation overflow"));
3037           insn |= val & 0x7ff;
3038           break;
3039
3040         case BFD_RELOC_SPARC_10:
3041           if (! in_signed_range (val, 0x3ff))
3042             as_bad_where (fixP->fx_file, fixP->fx_line,
3043                           _("relocation overflow"));
3044           insn |= val & 0x3ff;
3045           break;
3046
3047         case BFD_RELOC_SPARC_7:
3048           if (! in_bitfield_range (val, 0x7f))
3049             as_bad_where (fixP->fx_file, fixP->fx_line,
3050                           _("relocation overflow"));
3051           insn |= val & 0x7f;
3052           break;
3053
3054         case BFD_RELOC_SPARC_6:
3055           if (! in_bitfield_range (val, 0x3f))
3056             as_bad_where (fixP->fx_file, fixP->fx_line,
3057                           _("relocation overflow"));
3058           insn |= val & 0x3f;
3059           break;
3060
3061         case BFD_RELOC_SPARC_5:
3062           if (! in_bitfield_range (val, 0x1f))
3063             as_bad_where (fixP->fx_file, fixP->fx_line,
3064                           _("relocation overflow"));
3065           insn |= val & 0x1f;
3066           break;
3067
3068         case BFD_RELOC_SPARC_WDISP16:
3069           /* FIXME: simplify.  */
3070           if (((val > 0) && (val & ~0x3fffc))
3071               || ((val < 0) && (~(val - 1) & ~0x3fffc)))
3072             as_bad_where (fixP->fx_file, fixP->fx_line,
3073                           _("relocation overflow"));
3074           /* FIXME: The +1 deserves a comment.  */
3075           val = (val >> 2) + 1;
3076           insn |= ((val & 0xc000) << 6) | (val & 0x3fff);
3077           break;
3078
3079         case BFD_RELOC_SPARC_WDISP19:
3080           /* FIXME: simplify.  */
3081           if (((val > 0) && (val & ~0x1ffffc))
3082               || ((val < 0) && (~(val - 1) & ~0x1ffffc)))
3083             as_bad_where (fixP->fx_file, fixP->fx_line,
3084                           _("relocation overflow"));
3085           /* FIXME: The +1 deserves a comment.  */
3086           val = (val >> 2) + 1;
3087           insn |= val & 0x7ffff;
3088           break;
3089
3090         case BFD_RELOC_SPARC_HH22:
3091           val = BSR (val, 32);
3092           /* Fall through.  */
3093
3094         case BFD_RELOC_SPARC_LM22:
3095         case BFD_RELOC_HI22:
3096           if (!fixP->fx_addsy)
3097             {
3098               insn |= (val >> 10) & 0x3fffff;
3099             }
3100           else
3101             {
3102               /* FIXME: Need comment explaining why we do this.  */
3103               insn &= ~0xffff;
3104             }
3105           break;
3106
3107         case BFD_RELOC_SPARC22:
3108           if (val & ~0x003fffff)
3109             as_bad_where (fixP->fx_file, fixP->fx_line,
3110                           _("relocation overflow"));
3111           insn |= (val & 0x3fffff);
3112           break;
3113
3114         case BFD_RELOC_SPARC_HM10:
3115           val = BSR (val, 32);
3116           /* Fall through.  */
3117
3118         case BFD_RELOC_LO10:
3119           if (!fixP->fx_addsy)
3120             {
3121               insn |= val & 0x3ff;
3122             }
3123           else
3124             {
3125               /* FIXME: Need comment explaining why we do this.  */
3126               insn &= ~0xff;
3127             }
3128           break;
3129
3130         case BFD_RELOC_SPARC_OLO10:
3131           val &= 0x3ff;
3132           val += fixP->tc_fix_data;
3133           /* Fall through.  */
3134
3135         case BFD_RELOC_SPARC13:
3136           if (! in_signed_range (val, 0x1fff))
3137             as_bad_where (fixP->fx_file, fixP->fx_line,
3138                           _("relocation overflow"));
3139           insn |= val & 0x1fff;
3140           break;
3141
3142         case BFD_RELOC_SPARC_WDISP22:
3143           val = (val >> 2) + 1;
3144           /* Fall through.  */
3145         case BFD_RELOC_SPARC_BASE22:
3146           insn |= val & 0x3fffff;
3147           break;
3148
3149         case BFD_RELOC_SPARC_H44:
3150           if (!fixP->fx_addsy)
3151             {
3152               bfd_vma tval = val;
3153               tval >>= 22;
3154               insn |= tval & 0x3fffff;
3155             }
3156           break;
3157
3158         case BFD_RELOC_SPARC_M44:
3159           if (!fixP->fx_addsy)
3160             insn |= (val >> 12) & 0x3ff;
3161           break;
3162
3163         case BFD_RELOC_SPARC_L44:
3164           if (!fixP->fx_addsy)
3165             insn |= val & 0xfff;
3166           break;
3167
3168         case BFD_RELOC_SPARC_HIX22:
3169           if (!fixP->fx_addsy)
3170             {
3171               val ^= ~(offsetT) 0;
3172               insn |= (val >> 10) & 0x3fffff;
3173             }
3174           break;
3175
3176         case BFD_RELOC_SPARC_LOX10:
3177           if (!fixP->fx_addsy)
3178             insn |= 0x1c00 | (val & 0x3ff);
3179           break;
3180
3181         case BFD_RELOC_NONE:
3182         default:
3183           as_bad_where (fixP->fx_file, fixP->fx_line,
3184                         _("bad or unhandled relocation type: 0x%02x"),
3185                         fixP->fx_r_type);
3186           break;
3187         }
3188
3189       if (INSN_BIG_ENDIAN)
3190         bfd_putb32 (insn, (unsigned char *) buf);
3191       else
3192         bfd_putl32 (insn, (unsigned char *) buf);
3193     }
3194
3195   /* Are we finished with this relocation now?  */
3196   if (fixP->fx_addsy == 0 && !fixP->fx_pcrel)
3197     fixP->fx_done = 1;
3198
3199   return 1;
3200 }
3201
3202 /* Translate internal representation of relocation info to BFD target
3203    format.  */
3204
3205 arelent **
3206 tc_gen_reloc (section, fixp)
3207      asection *section;
3208      fixS *fixp;
3209 {
3210   static arelent *relocs[3];
3211   arelent *reloc;
3212   bfd_reloc_code_real_type code;
3213
3214   relocs[0] = reloc = (arelent *) xmalloc (sizeof (arelent));
3215   relocs[1] = NULL;
3216
3217   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3218   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
3219   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
3220
3221   switch (fixp->fx_r_type)
3222     {
3223     case BFD_RELOC_16:
3224     case BFD_RELOC_32:
3225     case BFD_RELOC_HI22:
3226     case BFD_RELOC_LO10:
3227     case BFD_RELOC_32_PCREL_S2:
3228     case BFD_RELOC_SPARC13:
3229     case BFD_RELOC_SPARC22:
3230     case BFD_RELOC_SPARC_BASE13:
3231     case BFD_RELOC_SPARC_WDISP16:
3232     case BFD_RELOC_SPARC_WDISP19:
3233     case BFD_RELOC_SPARC_WDISP22:
3234     case BFD_RELOC_64:
3235     case BFD_RELOC_SPARC_5:
3236     case BFD_RELOC_SPARC_6:
3237     case BFD_RELOC_SPARC_7:
3238     case BFD_RELOC_SPARC_10:
3239     case BFD_RELOC_SPARC_11:
3240     case BFD_RELOC_SPARC_HH22:
3241     case BFD_RELOC_SPARC_HM10:
3242     case BFD_RELOC_SPARC_LM22:
3243     case BFD_RELOC_SPARC_PC_HH22:
3244     case BFD_RELOC_SPARC_PC_HM10:
3245     case BFD_RELOC_SPARC_PC_LM22:
3246     case BFD_RELOC_SPARC_H44:
3247     case BFD_RELOC_SPARC_M44:
3248     case BFD_RELOC_SPARC_L44:
3249     case BFD_RELOC_SPARC_HIX22:
3250     case BFD_RELOC_SPARC_LOX10:
3251     case BFD_RELOC_SPARC_REV32:
3252     case BFD_RELOC_SPARC_OLO10:
3253     case BFD_RELOC_VTABLE_ENTRY:
3254     case BFD_RELOC_VTABLE_INHERIT:
3255       code = fixp->fx_r_type;
3256       break;
3257     default:
3258       abort ();
3259       return NULL;
3260     }
3261
3262 #if defined (OBJ_ELF) || defined (OBJ_AOUT)
3263   /* If we are generating PIC code, we need to generate a different
3264      set of relocs.  */
3265
3266 #ifdef OBJ_ELF
3267 #define GOT_NAME "_GLOBAL_OFFSET_TABLE_"
3268 #else
3269 #define GOT_NAME "__GLOBAL_OFFSET_TABLE_"
3270 #endif
3271
3272   /* This code must be parallel to the OBJ_ELF tc_fix_adjustable.  */
3273
3274   if (sparc_pic_code)
3275     {
3276       switch (code)
3277         {
3278         case BFD_RELOC_32_PCREL_S2:
3279           if (! S_IS_DEFINED (fixp->fx_addsy)
3280               || S_IS_COMMON (fixp->fx_addsy)
3281               || S_IS_EXTERNAL (fixp->fx_addsy)
3282               || S_IS_WEAK (fixp->fx_addsy))
3283             code = BFD_RELOC_SPARC_WPLT30;
3284           break;
3285         case BFD_RELOC_HI22:
3286           if (fixp->fx_addsy != NULL
3287               && strcmp (S_GET_NAME (fixp->fx_addsy), GOT_NAME) == 0)
3288             code = BFD_RELOC_SPARC_PC22;
3289           else
3290             code = BFD_RELOC_SPARC_GOT22;
3291           break;
3292         case BFD_RELOC_LO10:
3293           if (fixp->fx_addsy != NULL
3294               && strcmp (S_GET_NAME (fixp->fx_addsy), GOT_NAME) == 0)
3295             code = BFD_RELOC_SPARC_PC10;
3296           else
3297             code = BFD_RELOC_SPARC_GOT10;
3298           break;
3299         case BFD_RELOC_SPARC13:
3300           code = BFD_RELOC_SPARC_GOT13;
3301           break;
3302         default:
3303           break;
3304         }
3305     }
3306 #endif /* defined (OBJ_ELF) || defined (OBJ_AOUT)  */
3307
3308   if (code == BFD_RELOC_SPARC_OLO10)
3309     reloc->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_LO10);
3310   else
3311     reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
3312   if (reloc->howto == 0)
3313     {
3314       as_bad_where (fixp->fx_file, fixp->fx_line,
3315                     _("internal error: can't export reloc type %d (`%s')"),
3316                     fixp->fx_r_type, bfd_get_reloc_code_name (code));
3317       xfree (reloc);
3318       relocs[0] = NULL;
3319       return relocs;
3320     }
3321
3322   /* @@ Why fx_addnumber sometimes and fx_offset other times?  */
3323 #ifdef OBJ_AOUT
3324
3325   if (reloc->howto->pc_relative == 0
3326       || code == BFD_RELOC_SPARC_PC10
3327       || code == BFD_RELOC_SPARC_PC22)
3328     reloc->addend = fixp->fx_addnumber;
3329   else if (sparc_pic_code
3330            && fixp->fx_r_type == BFD_RELOC_32_PCREL_S2
3331            && fixp->fx_addsy != NULL
3332            && (S_IS_EXTERNAL (fixp->fx_addsy)
3333                || S_IS_WEAK (fixp->fx_addsy))
3334            && S_IS_DEFINED (fixp->fx_addsy)
3335            && ! S_IS_COMMON (fixp->fx_addsy))
3336     reloc->addend = fixp->fx_addnumber;
3337   else
3338     reloc->addend = fixp->fx_offset - reloc->address;
3339
3340 #else /* elf or coff  */
3341
3342   if (reloc->howto->pc_relative == 0
3343       || code == BFD_RELOC_SPARC_PC10
3344       || code == BFD_RELOC_SPARC_PC22)
3345     reloc->addend = fixp->fx_addnumber;
3346   else if (symbol_section_p (fixp->fx_addsy))
3347     reloc->addend = (section->vma
3348                      + fixp->fx_addnumber
3349                      + md_pcrel_from (fixp));
3350   else
3351     reloc->addend = fixp->fx_offset;
3352 #endif
3353
3354   /* We expand R_SPARC_OLO10 to R_SPARC_LO10 and R_SPARC_13
3355      on the same location.  */
3356   if (code == BFD_RELOC_SPARC_OLO10)
3357     {
3358       relocs[1] = reloc = (arelent *) xmalloc (sizeof (arelent));
3359       relocs[2] = NULL;
3360
3361       reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3362       *reloc->sym_ptr_ptr
3363         = symbol_get_bfdsym (section_symbol (absolute_section));
3364       reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
3365       reloc->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_SPARC13);
3366       reloc->addend = fixp->tc_fix_data;
3367     }
3368
3369   return relocs;
3370 }
3371 \f
3372 /* We have no need to default values of symbols.  */
3373
3374 symbolS *
3375 md_undefined_symbol (name)
3376      char *name;
3377 {
3378   return 0;
3379 }
3380
3381 /* Round up a section size to the appropriate boundary.  */
3382
3383 valueT
3384 md_section_align (segment, size)
3385      segT segment;
3386      valueT size;
3387 {
3388 #ifndef OBJ_ELF
3389   /* This is not right for ELF; a.out wants it, and COFF will force
3390      the alignment anyways.  */
3391   valueT align = ((valueT) 1
3392                   << (valueT) bfd_get_section_alignment (stdoutput, segment));
3393   valueT newsize;
3394
3395   /* Turn alignment value into a mask.  */
3396   align--;
3397   newsize = (size + align) & ~align;
3398   return newsize;
3399 #else
3400   return size;
3401 #endif
3402 }
3403
3404 /* Exactly what point is a PC-relative offset relative TO?
3405    On the sparc, they're relative to the address of the offset, plus
3406    its size.  This gets us to the following instruction.
3407    (??? Is this right?  FIXME-SOON)  */
3408 long
3409 md_pcrel_from (fixP)
3410      fixS *fixP;
3411 {
3412   long ret;
3413
3414   ret = fixP->fx_where + fixP->fx_frag->fr_address;
3415   if (! sparc_pic_code
3416       || fixP->fx_addsy == NULL
3417       || symbol_section_p (fixP->fx_addsy))
3418     ret += fixP->fx_size;
3419   return ret;
3420 }
3421 \f
3422 /* Return log2 (VALUE), or -1 if VALUE is not an exact positive power
3423    of two.  */
3424
3425 static int
3426 log2 (value)
3427      int value;
3428 {
3429   int shift;
3430
3431   if (value <= 0)
3432     return -1;
3433
3434   for (shift = 0; (value & 1) == 0; value >>= 1)
3435     ++shift;
3436
3437   return (value == 1) ? shift : -1;
3438 }
3439
3440 /* Sort of like s_lcomm.  */
3441
3442 #ifndef OBJ_ELF
3443 static int max_alignment = 15;
3444 #endif
3445
3446 static void
3447 s_reserve (ignore)
3448      int ignore;
3449 {
3450   char *name;
3451   char *p;
3452   char c;
3453   int align;
3454   int size;
3455   int temp;
3456   symbolS *symbolP;
3457
3458   name = input_line_pointer;
3459   c = get_symbol_end ();
3460   p = input_line_pointer;
3461   *p = c;
3462   SKIP_WHITESPACE ();
3463
3464   if (*input_line_pointer != ',')
3465     {
3466       as_bad (_("Expected comma after name"));
3467       ignore_rest_of_line ();
3468       return;
3469     }
3470
3471   ++input_line_pointer;
3472
3473   if ((size = get_absolute_expression ()) < 0)
3474     {
3475       as_bad (_("BSS length (%d.) <0! Ignored."), size);
3476       ignore_rest_of_line ();
3477       return;
3478     }                           /* Bad length.  */
3479
3480   *p = 0;
3481   symbolP = symbol_find_or_make (name);
3482   *p = c;
3483
3484   if (strncmp (input_line_pointer, ",\"bss\"", 6) != 0
3485       && strncmp (input_line_pointer, ",\".bss\"", 7) != 0)
3486     {
3487       as_bad (_("bad .reserve segment -- expected BSS segment"));
3488       return;
3489     }
3490
3491   if (input_line_pointer[2] == '.')
3492     input_line_pointer += 7;
3493   else
3494     input_line_pointer += 6;
3495   SKIP_WHITESPACE ();
3496
3497   if (*input_line_pointer == ',')
3498     {
3499       ++input_line_pointer;
3500
3501       SKIP_WHITESPACE ();
3502       if (*input_line_pointer == '\n')
3503         {
3504           as_bad (_("missing alignment"));
3505           ignore_rest_of_line ();
3506           return;
3507         }
3508
3509       align = (int) get_absolute_expression ();
3510
3511 #ifndef OBJ_ELF
3512       if (align > max_alignment)
3513         {
3514           align = max_alignment;
3515           as_warn (_("alignment too large; assuming %d"), align);
3516         }
3517 #endif
3518
3519       if (align < 0)
3520         {
3521           as_bad (_("negative alignment"));
3522           ignore_rest_of_line ();
3523           return;
3524         }
3525
3526       if (align != 0)
3527         {
3528           temp = log2 (align);
3529           if (temp < 0)
3530             {
3531               as_bad (_("alignment not a power of 2"));
3532               ignore_rest_of_line ();
3533               return;
3534             }
3535
3536           align = temp;
3537         }
3538
3539       record_alignment (bss_section, align);
3540     }
3541   else
3542     align = 0;
3543
3544   if (!S_IS_DEFINED (symbolP)
3545 #ifdef OBJ_AOUT
3546       && S_GET_OTHER (symbolP) == 0
3547       && S_GET_DESC (symbolP) == 0
3548 #endif
3549       )
3550     {
3551       if (! need_pass_2)
3552         {
3553           char *pfrag;
3554           segT current_seg = now_seg;
3555           subsegT current_subseg = now_subseg;
3556
3557           /* Switch to bss.  */
3558           subseg_set (bss_section, 1);
3559
3560           if (align)
3561             /* Do alignment.  */
3562             frag_align (align, 0, 0);
3563
3564           /* Detach from old frag.  */
3565           if (S_GET_SEGMENT (symbolP) == bss_section)
3566             symbol_get_frag (symbolP)->fr_symbol = NULL;
3567
3568           symbol_set_frag (symbolP, frag_now);
3569           pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP,
3570                             (offsetT) size, (char *) 0);
3571           *pfrag = 0;
3572
3573           S_SET_SEGMENT (symbolP, bss_section);
3574
3575           subseg_set (current_seg, current_subseg);
3576
3577 #ifdef OBJ_ELF
3578           S_SET_SIZE (symbolP, size);
3579 #endif
3580         }
3581     }
3582   else
3583     {
3584       as_warn ("Ignoring attempt to re-define symbol %s",
3585                S_GET_NAME (symbolP));
3586     }                           /* if not redefining.  */
3587
3588   demand_empty_rest_of_line ();
3589 }
3590
3591 static void
3592 s_common (ignore)
3593      int ignore;
3594 {
3595   char *name;
3596   char c;
3597   char *p;
3598   int temp, size;
3599   symbolS *symbolP;
3600
3601   name = input_line_pointer;
3602   c = get_symbol_end ();
3603   /* Just after name is now '\0'.  */
3604   p = input_line_pointer;
3605   *p = c;
3606   SKIP_WHITESPACE ();
3607   if (*input_line_pointer != ',')
3608     {
3609       as_bad (_("Expected comma after symbol-name"));
3610       ignore_rest_of_line ();
3611       return;
3612     }
3613
3614   /* Skip ','.  */
3615   input_line_pointer++;
3616
3617   if ((temp = get_absolute_expression ()) < 0)
3618     {
3619       as_bad (_(".COMMon length (%d.) <0! Ignored."), temp);
3620       ignore_rest_of_line ();
3621       return;
3622     }
3623   size = temp;
3624   *p = 0;
3625   symbolP = symbol_find_or_make (name);
3626   *p = c;
3627   if (S_IS_DEFINED (symbolP) && ! S_IS_COMMON (symbolP))
3628     {
3629       as_bad (_("Ignoring attempt to re-define symbol"));
3630       ignore_rest_of_line ();
3631       return;
3632     }
3633   if (S_GET_VALUE (symbolP) != 0)
3634     {
3635       if (S_GET_VALUE (symbolP) != (valueT) size)
3636         {
3637           as_warn (_("Length of .comm \"%s\" is already %ld. Not changed to %d."),
3638                    S_GET_NAME (symbolP), (long) S_GET_VALUE (symbolP), size);
3639         }
3640     }
3641   else
3642     {
3643 #ifndef OBJ_ELF
3644       S_SET_VALUE (symbolP, (valueT) size);
3645       S_SET_EXTERNAL (symbolP);
3646 #endif
3647     }
3648   know (symbol_get_frag (symbolP) == &zero_address_frag);
3649   if (*input_line_pointer != ',')
3650     {
3651       as_bad (_("Expected comma after common length"));
3652       ignore_rest_of_line ();
3653       return;
3654     }
3655   input_line_pointer++;
3656   SKIP_WHITESPACE ();
3657   if (*input_line_pointer != '"')
3658     {
3659       temp = get_absolute_expression ();
3660
3661 #ifndef OBJ_ELF
3662       if (temp > max_alignment)
3663         {
3664           temp = max_alignment;
3665           as_warn (_("alignment too large; assuming %d"), temp);
3666         }
3667 #endif
3668
3669       if (temp < 0)
3670         {
3671           as_bad (_("negative alignment"));
3672           ignore_rest_of_line ();
3673           return;
3674         }
3675
3676 #ifdef OBJ_ELF
3677       if (symbol_get_obj (symbolP)->local)
3678         {
3679           segT old_sec;
3680           int old_subsec;
3681           char *p;
3682           int align;
3683
3684           old_sec = now_seg;
3685           old_subsec = now_subseg;
3686
3687           if (temp == 0)
3688             align = 0;
3689           else
3690             align = log2 (temp);
3691
3692           if (align < 0)
3693             {
3694               as_bad (_("alignment not a power of 2"));
3695               ignore_rest_of_line ();
3696               return;
3697             }
3698
3699           record_alignment (bss_section, align);
3700           subseg_set (bss_section, 0);
3701           if (align)
3702             frag_align (align, 0, 0);
3703           if (S_GET_SEGMENT (symbolP) == bss_section)
3704             symbol_get_frag (symbolP)->fr_symbol = 0;
3705           symbol_set_frag (symbolP, frag_now);
3706           p = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP,
3707                         (offsetT) size, (char *) 0);
3708           *p = 0;
3709           S_SET_SEGMENT (symbolP, bss_section);
3710           S_CLEAR_EXTERNAL (symbolP);
3711           S_SET_SIZE (symbolP, size);
3712           subseg_set (old_sec, old_subsec);
3713         }
3714       else
3715 #endif /* OBJ_ELF  */
3716         {
3717         allocate_common:
3718           S_SET_VALUE (symbolP, (valueT) size);
3719 #ifdef OBJ_ELF
3720           S_SET_ALIGN (symbolP, temp);
3721           S_SET_SIZE (symbolP, size);
3722 #endif
3723           S_SET_EXTERNAL (symbolP);
3724           S_SET_SEGMENT (symbolP, bfd_com_section_ptr);
3725         }
3726     }
3727   else
3728     {
3729       input_line_pointer++;
3730       /* @@ Some use the dot, some don't.  Can we get some consistency??  */
3731       if (*input_line_pointer == '.')
3732         input_line_pointer++;
3733       /* @@ Some say data, some say bss.  */
3734       if (strncmp (input_line_pointer, "bss\"", 4)
3735           && strncmp (input_line_pointer, "data\"", 5))
3736         {
3737           while (*--input_line_pointer != '"')
3738             ;
3739           input_line_pointer--;
3740           goto bad_common_segment;
3741         }
3742       while (*input_line_pointer++ != '"')
3743         ;
3744       goto allocate_common;
3745     }
3746
3747 #ifdef BFD_ASSEMBLER
3748   symbol_get_bfdsym (symbolP)->flags |= BSF_OBJECT;
3749 #endif
3750
3751   demand_empty_rest_of_line ();
3752   return;
3753
3754   {
3755   bad_common_segment:
3756     p = input_line_pointer;
3757     while (*p && *p != '\n')
3758       p++;
3759     c = *p;
3760     *p = '\0';
3761     as_bad (_("bad .common segment %s"), input_line_pointer + 1);
3762     *p = c;
3763     input_line_pointer = p;
3764     ignore_rest_of_line ();
3765     return;
3766   }
3767 }
3768
3769 /* Handle the .empty pseudo-op.  This supresses the warnings about
3770    invalid delay slot usage.  */
3771
3772 static void
3773 s_empty (ignore)
3774      int ignore;
3775 {
3776   /* The easy way to implement is to just forget about the last
3777      instruction.  */
3778   last_insn = NULL;
3779 }
3780
3781 static void
3782 s_seg (ignore)
3783      int ignore;
3784 {
3785
3786   if (strncmp (input_line_pointer, "\"text\"", 6) == 0)
3787     {
3788       input_line_pointer += 6;
3789       s_text (0);
3790       return;
3791     }
3792   if (strncmp (input_line_pointer, "\"data\"", 6) == 0)
3793     {
3794       input_line_pointer += 6;
3795       s_data (0);
3796       return;
3797     }
3798   if (strncmp (input_line_pointer, "\"data1\"", 7) == 0)
3799     {
3800       input_line_pointer += 7;
3801       s_data1 ();
3802       return;
3803     }
3804   if (strncmp (input_line_pointer, "\"bss\"", 5) == 0)
3805     {
3806       input_line_pointer += 5;
3807       /* We only support 2 segments -- text and data -- for now, so
3808          things in the "bss segment" will have to go into data for now.
3809          You can still allocate SEG_BSS stuff with .lcomm or .reserve.  */
3810       subseg_set (data_section, 255);   /* FIXME-SOMEDAY.  */
3811       return;
3812     }
3813   as_bad (_("Unknown segment type"));
3814   demand_empty_rest_of_line ();
3815 }
3816
3817 static void
3818 s_data1 ()
3819 {
3820   subseg_set (data_section, 1);
3821   demand_empty_rest_of_line ();
3822 }
3823
3824 static void
3825 s_proc (ignore)
3826      int ignore;
3827 {
3828   while (!is_end_of_line[(unsigned char) *input_line_pointer])
3829     {
3830       ++input_line_pointer;
3831     }
3832   ++input_line_pointer;
3833 }
3834
3835 /* This static variable is set by s_uacons to tell sparc_cons_align
3836    that the expession does not need to be aligned.  */
3837
3838 static int sparc_no_align_cons = 0;
3839
3840 /* This handles the unaligned space allocation pseudo-ops, such as
3841    .uaword.  .uaword is just like .word, but the value does not need
3842    to be aligned.  */
3843
3844 static void
3845 s_uacons (bytes)
3846      int bytes;
3847 {
3848   /* Tell sparc_cons_align not to align this value.  */
3849   sparc_no_align_cons = 1;
3850   cons (bytes);
3851 }
3852
3853 /* This handles the native word allocation pseudo-op .nword.
3854    For sparc_arch_size 32 it is equivalent to .word,  for
3855    sparc_arch_size 64 it is equivalent to .xword.  */
3856
3857 static void
3858 s_ncons (bytes)
3859      int bytes;
3860 {
3861   cons (sparc_arch_size == 32 ? 4 : 8);
3862 }
3863
3864 #ifdef OBJ_ELF
3865 /* Handle the SPARC ELF .register pseudo-op.  This sets the binding of a
3866    global register.
3867    The syntax is:
3868
3869    .register %g[2367],{#scratch|symbolname|#ignore}
3870 */
3871
3872 static void
3873 s_register (ignore)
3874      int ignore;
3875 {
3876   char c;
3877   int reg;
3878   int flags;
3879   const char *regname;
3880
3881   if (input_line_pointer[0] != '%'
3882       || input_line_pointer[1] != 'g'
3883       || ((input_line_pointer[2] & ~1) != '2'
3884           && (input_line_pointer[2] & ~1) != '6')
3885       || input_line_pointer[3] != ',')
3886     as_bad (_("register syntax is .register %%g[2367],{#scratch|symbolname|#ignore}"));
3887   reg = input_line_pointer[2] - '0';
3888   input_line_pointer += 4;
3889
3890   if (*input_line_pointer == '#')
3891     {
3892       ++input_line_pointer;
3893       regname = input_line_pointer;
3894       c = get_symbol_end ();
3895       if (strcmp (regname, "scratch") && strcmp (regname, "ignore"))
3896         as_bad (_("register syntax is .register %%g[2367],{#scratch|symbolname|#ignore}"));
3897       if (regname[0] == 'i')
3898         regname = NULL;
3899       else
3900         regname = "";
3901     }
3902   else
3903     {
3904       regname = input_line_pointer;
3905       c = get_symbol_end ();
3906     }
3907   if (sparc_arch_size == 64)
3908     {
3909       if (globals[reg])
3910         {
3911           if ((regname && globals[reg] != (symbolS *) 1
3912                && strcmp (S_GET_NAME (globals[reg]), regname))
3913               || ((regname != NULL) ^ (globals[reg] != (symbolS *) 1)))
3914             as_bad (_("redefinition of global register"));
3915         }
3916       else
3917         {
3918           if (regname == NULL)
3919             globals[reg] = (symbolS *) 1;
3920           else
3921             {
3922               if (*regname)
3923                 {
3924                   if (symbol_find (regname))
3925                     as_bad (_("Register symbol %s already defined."),
3926                             regname);
3927                 }
3928               globals[reg] = symbol_make (regname);
3929               flags = symbol_get_bfdsym (globals[reg])->flags;
3930               if (! *regname)
3931                 flags = flags & ~(BSF_GLOBAL|BSF_LOCAL|BSF_WEAK);
3932               if (! (flags & (BSF_GLOBAL|BSF_LOCAL|BSF_WEAK)))
3933                 flags |= BSF_GLOBAL;
3934               symbol_get_bfdsym (globals[reg])->flags = flags;
3935               S_SET_VALUE (globals[reg], (valueT) reg);
3936               S_SET_ALIGN (globals[reg], reg);
3937               S_SET_SIZE (globals[reg], 0);
3938               /* Although we actually want undefined_section here,
3939                  we have to use absolute_section, because otherwise
3940                  generic as code will make it a COM section.
3941                  We fix this up in sparc_adjust_symtab.  */
3942               S_SET_SEGMENT (globals[reg], absolute_section);
3943               S_SET_OTHER (globals[reg], 0);
3944               elf_symbol (symbol_get_bfdsym (globals[reg]))
3945                 ->internal_elf_sym.st_info =
3946                   ELF_ST_INFO(STB_GLOBAL, STT_REGISTER);
3947               elf_symbol (symbol_get_bfdsym (globals[reg]))
3948                 ->internal_elf_sym.st_shndx = SHN_UNDEF;
3949             }
3950         }
3951     }
3952
3953   *input_line_pointer = c;
3954
3955   demand_empty_rest_of_line ();
3956 }
3957
3958 /* Adjust the symbol table.  We set undefined sections for STT_REGISTER
3959    symbols which need it.  */
3960
3961 void
3962 sparc_adjust_symtab ()
3963 {
3964   symbolS *sym;
3965
3966   for (sym = symbol_rootP; sym != NULL; sym = symbol_next (sym))
3967     {
3968       if (ELF_ST_TYPE (elf_symbol (symbol_get_bfdsym (sym))
3969                        ->internal_elf_sym.st_info) != STT_REGISTER)
3970         continue;
3971
3972       if (ELF_ST_TYPE (elf_symbol (symbol_get_bfdsym (sym))
3973                        ->internal_elf_sym.st_shndx != SHN_UNDEF))
3974         continue;
3975
3976       S_SET_SEGMENT (sym, undefined_section);
3977     }
3978 }
3979 #endif
3980
3981 /* If the --enforce-aligned-data option is used, we require .word,
3982    et. al., to be aligned correctly.  We do it by setting up an
3983    rs_align_code frag, and checking in HANDLE_ALIGN to make sure that
3984    no unexpected alignment was introduced.
3985
3986    The SunOS and Solaris native assemblers enforce aligned data by
3987    default.  We don't want to do that, because gcc can deliberately
3988    generate misaligned data if the packed attribute is used.  Instead,
3989    we permit misaligned data by default, and permit the user to set an
3990    option to check for it.  */
3991
3992 void
3993 sparc_cons_align (nbytes)
3994      int nbytes;
3995 {
3996   int nalign;
3997   char *p;
3998
3999   /* Only do this if we are enforcing aligned data.  */
4000   if (! enforce_aligned_data)
4001     return;
4002
4003   if (sparc_no_align_cons)
4004     {
4005       /* This is an unaligned pseudo-op.  */
4006       sparc_no_align_cons = 0;
4007       return;
4008     }
4009
4010   nalign = log2 (nbytes);
4011   if (nalign == 0)
4012     return;
4013
4014   assert (nalign > 0);
4015
4016   if (now_seg == absolute_section)
4017     {
4018       if ((abs_section_offset & ((1 << nalign) - 1)) != 0)
4019         as_bad (_("misaligned data"));
4020       return;
4021     }
4022
4023   p = frag_var (rs_align_code, 1, 1, (relax_substateT) 0,
4024                 (symbolS *) NULL, (offsetT) nalign, (char *) NULL);
4025
4026   record_alignment (now_seg, nalign);
4027 }
4028
4029 /* This is where we do the unexpected alignment check.
4030    This is called from HANDLE_ALIGN in tc-sparc.h.  */
4031
4032 void
4033 sparc_handle_align (fragp)
4034      fragS *fragp;
4035 {
4036   if (fragp->fr_type == rs_align_code && !fragp->fr_subtype
4037       && fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix != 0)
4038     as_bad_where (fragp->fr_file, fragp->fr_line, _("misaligned data"));
4039   if (fragp->fr_type == rs_align_code && fragp->fr_subtype == 1024)
4040     {
4041       int count =
4042         fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
4043
4044       if (count >= 4
4045           && !(count & 3)
4046           && count <= 1024
4047           && !((long) (fragp->fr_literal + fragp->fr_fix) & 3))
4048         {
4049           unsigned *p = (unsigned *) (fragp->fr_literal + fragp->fr_fix);
4050           int i;
4051
4052           for (i = 0; i < count; i += 4, p++)
4053             if (INSN_BIG_ENDIAN)
4054               /* Emit nops.  */
4055               number_to_chars_bigendian ((char *) p, 0x01000000, 4);
4056             else
4057               number_to_chars_littleendian ((char *) p, 0x10000000, 4);
4058
4059           if (SPARC_OPCODE_ARCH_V9_P (max_architecture) && count > 8)
4060             {
4061               char *waddr = &fragp->fr_literal[fragp->fr_fix];
4062               unsigned wval = (0x30680000 | count >> 2); /* ba,a,pt %xcc, 1f  */
4063               if (INSN_BIG_ENDIAN)
4064                 number_to_chars_bigendian (waddr, wval, 4);
4065               else
4066                 number_to_chars_littleendian (waddr, wval, 4);
4067             }
4068           fragp->fr_var = count;
4069         }
4070     }
4071 }
4072
4073 #ifdef OBJ_ELF
4074 /* Some special processing for a Sparc ELF file.  */
4075
4076 void
4077 sparc_elf_final_processing ()
4078 {
4079   /* Set the Sparc ELF flag bits.  FIXME: There should probably be some
4080      sort of BFD interface for this.  */
4081   if (sparc_arch_size == 64)
4082     {
4083       switch (sparc_memory_model)
4084         {
4085         case MM_RMO:
4086           elf_elfheader (stdoutput)->e_flags |= EF_SPARCV9_RMO;
4087           break;
4088         case MM_PSO:
4089           elf_elfheader (stdoutput)->e_flags |= EF_SPARCV9_PSO;
4090           break;
4091         default:
4092           break;
4093         }
4094     }
4095   else if (current_architecture >= SPARC_OPCODE_ARCH_V9)
4096     elf_elfheader (stdoutput)->e_flags |= EF_SPARC_32PLUS;
4097   if (current_architecture == SPARC_OPCODE_ARCH_V9A)
4098     elf_elfheader (stdoutput)->e_flags |= EF_SPARC_SUN_US1;
4099 }
4100 #endif
4101
4102 /* This is called by emit_expr via TC_CONS_FIX_NEW when creating a
4103    reloc for a cons.  We could use the definition there, except that
4104    we want to handle little endian relocs specially.  */
4105
4106 void
4107 cons_fix_new_sparc (frag, where, nbytes, exp)
4108      fragS *frag;
4109      int where;
4110      unsigned int nbytes;
4111      expressionS *exp;
4112 {
4113   bfd_reloc_code_real_type r;
4114
4115   r = (nbytes == 1 ? BFD_RELOC_8 :
4116        (nbytes == 2 ? BFD_RELOC_16 :
4117         (nbytes == 4 ? BFD_RELOC_32 : BFD_RELOC_64)));
4118
4119   if (target_little_endian_data && nbytes == 4
4120       && now_seg->flags & SEC_ALLOC)
4121     r = BFD_RELOC_SPARC_REV32;
4122   fix_new_exp (frag, where, (int) nbytes, exp, 0, r);
4123 }
4124
4125 #ifdef OBJ_ELF
4126 int
4127 elf32_sparc_force_relocation (fixp)
4128      struct fix *fixp;
4129 {
4130   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
4131       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
4132     return 1;
4133
4134   return 0;
4135 }
4136 #endif