gas/
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
3    2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by the OSF and Ralph Campbell.
6    Written by Keith Knowles and Ralph Campbell, working independently.
7    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
8    Support.
9
10    This file is part of GAS.
11
12    GAS is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GAS is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with GAS; see the file COPYING.  If not, write to the Free
24    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
25    02110-1301, USA.  */
26
27 #include "as.h"
28 #include "config.h"
29 #include "subsegs.h"
30 #include "safe-ctype.h"
31
32 #include "opcode/mips.h"
33 #include "itbl-ops.h"
34 #include "dwarf2dbg.h"
35 #include "dw2gencfi.h"
36
37 #ifdef DEBUG
38 #define DBG(x) printf x
39 #else
40 #define DBG(x)
41 #endif
42
43 #ifdef OBJ_MAYBE_ELF
44 /* Clean up namespace so we can include obj-elf.h too.  */
45 static int mips_output_flavor (void);
46 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
47 #undef OBJ_PROCESS_STAB
48 #undef OUTPUT_FLAVOR
49 #undef S_GET_ALIGN
50 #undef S_GET_SIZE
51 #undef S_SET_ALIGN
52 #undef S_SET_SIZE
53 #undef obj_frob_file
54 #undef obj_frob_file_after_relocs
55 #undef obj_frob_symbol
56 #undef obj_pop_insert
57 #undef obj_sec_sym_ok_for_reloc
58 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
59
60 #include "obj-elf.h"
61 /* Fix any of them that we actually care about.  */
62 #undef OUTPUT_FLAVOR
63 #define OUTPUT_FLAVOR mips_output_flavor()
64 #endif
65
66 #if defined (OBJ_ELF)
67 #include "elf/mips.h"
68 #endif
69
70 #ifndef ECOFF_DEBUGGING
71 #define NO_ECOFF_DEBUGGING
72 #define ECOFF_DEBUGGING 0
73 #endif
74
75 int mips_flag_mdebug = -1;
76
77 /* Control generation of .pdr sections.  Off by default on IRIX: the native
78    linker doesn't know about and discards them, but relocations against them
79    remain, leading to rld crashes.  */
80 #ifdef TE_IRIX
81 int mips_flag_pdr = FALSE;
82 #else
83 int mips_flag_pdr = TRUE;
84 #endif
85
86 #include "ecoff.h"
87
88 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
89 static char *mips_regmask_frag;
90 #endif
91
92 #define ZERO 0
93 #define ATREG 1
94 #define TREG 24
95 #define PIC_CALL_REG 25
96 #define KT0 26
97 #define KT1 27
98 #define GP  28
99 #define SP  29
100 #define FP  30
101 #define RA  31
102
103 #define ILLEGAL_REG (32)
104
105 #define AT  mips_opts.at
106
107 /* Allow override of standard little-endian ECOFF format.  */
108
109 #ifndef ECOFF_LITTLE_FORMAT
110 #define ECOFF_LITTLE_FORMAT "ecoff-littlemips"
111 #endif
112
113 extern int target_big_endian;
114
115 /* The name of the readonly data section.  */
116 #define RDATA_SECTION_NAME (OUTPUT_FLAVOR == bfd_target_ecoff_flavour \
117                             ? ".rdata" \
118                             : OUTPUT_FLAVOR == bfd_target_coff_flavour \
119                             ? ".rdata" \
120                             : OUTPUT_FLAVOR == bfd_target_elf_flavour \
121                             ? ".rodata" \
122                             : (abort (), ""))
123
124 /* Information about an instruction, including its format, operands
125    and fixups.  */
126 struct mips_cl_insn
127 {
128   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
129   const struct mips_opcode *insn_mo;
130
131   /* True if this is a mips16 instruction and if we want the extended
132      form of INSN_MO.  */
133   bfd_boolean use_extend;
134
135   /* The 16-bit extension instruction to use when USE_EXTEND is true.  */
136   unsigned short extend;
137
138   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
139      a copy of INSN_MO->match with the operands filled in.  */
140   unsigned long insn_opcode;
141
142   /* The frag that contains the instruction.  */
143   struct frag *frag;
144
145   /* The offset into FRAG of the first instruction byte.  */
146   long where;
147
148   /* The relocs associated with the instruction, if any.  */
149   fixS *fixp[3];
150
151   /* True if this entry cannot be moved from its current position.  */
152   unsigned int fixed_p : 1;
153
154   /* True if this instruction occurred in a .set noreorder block.  */
155   unsigned int noreorder_p : 1;
156
157   /* True for mips16 instructions that jump to an absolute address.  */
158   unsigned int mips16_absolute_jump_p : 1;
159 };
160
161 /* The ABI to use.  */
162 enum mips_abi_level
163 {
164   NO_ABI = 0,
165   O32_ABI,
166   O64_ABI,
167   N32_ABI,
168   N64_ABI,
169   EABI_ABI
170 };
171
172 /* MIPS ABI we are using for this output file.  */
173 static enum mips_abi_level mips_abi = NO_ABI;
174
175 /* Whether or not we have code that can call pic code.  */
176 int mips_abicalls = FALSE;
177
178 /* Whether or not we have code which can be put into a shared
179    library.  */
180 static bfd_boolean mips_in_shared = TRUE;
181
182 /* This is the set of options which may be modified by the .set
183    pseudo-op.  We use a struct so that .set push and .set pop are more
184    reliable.  */
185
186 struct mips_set_options
187 {
188   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
189      if it has not been initialized.  Changed by `.set mipsN', and the
190      -mipsN command line option, and the default CPU.  */
191   int isa;
192   /* Enabled Application Specific Extensions (ASEs).  These are set to -1
193      if they have not been initialized.  Changed by `.set <asename>', by
194      command line options, and based on the default architecture.  */
195   int ase_mips3d;
196   int ase_mdmx;
197   int ase_smartmips;
198   int ase_dsp;
199   int ase_dspr2;
200   int ase_mt;
201   /* Whether we are assembling for the mips16 processor.  0 if we are
202      not, 1 if we are, and -1 if the value has not been initialized.
203      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
204      -nomips16 command line options, and the default CPU.  */
205   int mips16;
206   /* Non-zero if we should not reorder instructions.  Changed by `.set
207      reorder' and `.set noreorder'.  */
208   int noreorder;
209   /* Non-zero if we should not permit the register designated "assembler
210      temporary" to be used in instructions.  The value is the register
211      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
212      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
213   unsigned int at;
214   /* Non-zero if we should warn when a macro instruction expands into
215      more than one machine instruction.  Changed by `.set nomacro' and
216      `.set macro'.  */
217   int warn_about_macros;
218   /* Non-zero if we should not move instructions.  Changed by `.set
219      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
220   int nomove;
221   /* Non-zero if we should not optimize branches by moving the target
222      of the branch into the delay slot.  Actually, we don't perform
223      this optimization anyhow.  Changed by `.set bopt' and `.set
224      nobopt'.  */
225   int nobopt;
226   /* Non-zero if we should not autoextend mips16 instructions.
227      Changed by `.set autoextend' and `.set noautoextend'.  */
228   int noautoextend;
229   /* Restrict general purpose registers and floating point registers
230      to 32 bit.  This is initially determined when -mgp32 or -mfp32
231      is passed but can changed if the assembler code uses .set mipsN.  */
232   int gp32;
233   int fp32;
234   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
235      command line option, and the default CPU.  */
236   int arch;
237   /* True if ".set sym32" is in effect.  */
238   bfd_boolean sym32;
239   /* True if floating-point operations are not allowed.  Changed by .set
240      softfloat or .set hardfloat, by command line options -msoft-float or
241      -mhard-float.  The default is false.  */
242   bfd_boolean soft_float;
243
244   /* True if only single-precision floating-point operations are allowed.
245      Changed by .set singlefloat or .set doublefloat, command-line options
246      -msingle-float or -mdouble-float.  The default is false.  */
247   bfd_boolean single_float;
248 };
249
250 /* This is the struct we use to hold the current set of options.  Note
251    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
252    -1 to indicate that they have not been initialized.  */
253
254 /* True if -mgp32 was passed.  */
255 static int file_mips_gp32 = -1;
256
257 /* True if -mfp32 was passed.  */
258 static int file_mips_fp32 = -1;
259
260 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
261 static int file_mips_soft_float = 0;
262
263 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
264 static int file_mips_single_float = 0;
265
266 static struct mips_set_options mips_opts =
267 {
268   /* isa */ ISA_UNKNOWN, /* ase_mips3d */ -1, /* ase_mdmx */ -1,
269   /* ase_smartmips */ 0, /* ase_dsp */ -1, /* ase_dspr2 */ -1, /* ase_mt */ -1,
270   /* mips16 */ -1, /* noreorder */ 0, /* at */ ATREG,
271   /* warn_about_macros */ 0, /* nomove */ 0, /* nobopt */ 0,
272   /* noautoextend */ 0, /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN,
273   /* sym32 */ FALSE, /* soft_float */ FALSE, /* single_float */ FALSE
274 };
275
276 /* These variables are filled in with the masks of registers used.
277    The object format code reads them and puts them in the appropriate
278    place.  */
279 unsigned long mips_gprmask;
280 unsigned long mips_cprmask[4];
281
282 /* MIPS ISA we are using for this output file.  */
283 static int file_mips_isa = ISA_UNKNOWN;
284
285 /* True if any MIPS16 code was produced.  */
286 static int file_ase_mips16;
287
288 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
289                               || mips_opts.isa == ISA_MIPS32R2          \
290                               || mips_opts.isa == ISA_MIPS64            \
291                               || mips_opts.isa == ISA_MIPS64R2)
292
293 /* True if we want to create R_MIPS_JALR for jalr $25.  */
294 #ifdef TE_IRIX
295 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
296 #else
297 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
298    because there's no place for any addend, the only acceptable
299    expression is a bare symbol.  */
300 #define MIPS_JALR_HINT_P(EXPR) \
301   (!HAVE_IN_PLACE_ADDENDS \
302    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
303 #endif
304
305 /* True if -mips3d was passed or implied by arguments passed on the
306    command line (e.g., by -march).  */
307 static int file_ase_mips3d;
308
309 /* True if -mdmx was passed or implied by arguments passed on the
310    command line (e.g., by -march).  */
311 static int file_ase_mdmx;
312
313 /* True if -msmartmips was passed or implied by arguments passed on the
314    command line (e.g., by -march).  */
315 static int file_ase_smartmips;
316
317 #define ISA_SUPPORTS_SMARTMIPS (mips_opts.isa == ISA_MIPS32             \
318                                 || mips_opts.isa == ISA_MIPS32R2)
319
320 /* True if -mdsp was passed or implied by arguments passed on the
321    command line (e.g., by -march).  */
322 static int file_ase_dsp;
323
324 #define ISA_SUPPORTS_DSP_ASE (mips_opts.isa == ISA_MIPS32R2             \
325                               || mips_opts.isa == ISA_MIPS64R2)
326
327 #define ISA_SUPPORTS_DSP64_ASE (mips_opts.isa == ISA_MIPS64R2)
328
329 /* True if -mdspr2 was passed or implied by arguments passed on the
330    command line (e.g., by -march).  */
331 static int file_ase_dspr2;
332
333 #define ISA_SUPPORTS_DSPR2_ASE (mips_opts.isa == ISA_MIPS32R2           \
334                                 || mips_opts.isa == ISA_MIPS64R2)
335
336 /* True if -mmt was passed or implied by arguments passed on the
337    command line (e.g., by -march).  */
338 static int file_ase_mt;
339
340 #define ISA_SUPPORTS_MT_ASE (mips_opts.isa == ISA_MIPS32R2              \
341                              || mips_opts.isa == ISA_MIPS64R2)
342
343 /* The argument of the -march= flag.  The architecture we are assembling.  */
344 static int file_mips_arch = CPU_UNKNOWN;
345 static const char *mips_arch_string;
346
347 /* The argument of the -mtune= flag.  The architecture for which we
348    are optimizing.  */
349 static int mips_tune = CPU_UNKNOWN;
350 static const char *mips_tune_string;
351
352 /* True when generating 32-bit code for a 64-bit processor.  */
353 static int mips_32bitmode = 0;
354
355 /* True if the given ABI requires 32-bit registers.  */
356 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
357
358 /* Likewise 64-bit registers.  */
359 #define ABI_NEEDS_64BIT_REGS(ABI)       \
360   ((ABI) == N32_ABI                     \
361    || (ABI) == N64_ABI                  \
362    || (ABI) == O64_ABI)
363
364 /*  Return true if ISA supports 64 bit wide gp registers.  */
365 #define ISA_HAS_64BIT_REGS(ISA)         \
366   ((ISA) == ISA_MIPS3                   \
367    || (ISA) == ISA_MIPS4                \
368    || (ISA) == ISA_MIPS5                \
369    || (ISA) == ISA_MIPS64               \
370    || (ISA) == ISA_MIPS64R2)
371
372 /*  Return true if ISA supports 64 bit wide float registers.  */
373 #define ISA_HAS_64BIT_FPRS(ISA)         \
374   ((ISA) == ISA_MIPS3                   \
375    || (ISA) == ISA_MIPS4                \
376    || (ISA) == ISA_MIPS5                \
377    || (ISA) == ISA_MIPS32R2             \
378    || (ISA) == ISA_MIPS64               \
379    || (ISA) == ISA_MIPS64R2)
380
381 /* Return true if ISA supports 64-bit right rotate (dror et al.)
382    instructions.  */
383 #define ISA_HAS_DROR(ISA)               \
384   ((ISA) == ISA_MIPS64R2)
385
386 /* Return true if ISA supports 32-bit right rotate (ror et al.)
387    instructions.  */
388 #define ISA_HAS_ROR(ISA)                \
389   ((ISA) == ISA_MIPS32R2                \
390    || (ISA) == ISA_MIPS64R2             \
391    || mips_opts.ase_smartmips)
392
393 /* Return true if ISA supports single-precision floats in odd registers.  */
394 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
395   ((ISA) == ISA_MIPS32                  \
396    || (ISA) == ISA_MIPS32R2             \
397    || (ISA) == ISA_MIPS64               \
398    || (ISA) == ISA_MIPS64R2)
399
400 /* Return true if ISA supports move to/from high part of a 64-bit
401    floating-point register. */
402 #define ISA_HAS_MXHC1(ISA)              \
403   ((ISA) == ISA_MIPS32R2                \
404    || (ISA) == ISA_MIPS64R2)
405
406 #define HAVE_32BIT_GPRS                            \
407     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
408
409 #define HAVE_32BIT_FPRS                            \
410     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
411
412 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
413 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
414
415 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
416
417 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
418
419 /* True if relocations are stored in-place.  */
420 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
421
422 /* The ABI-derived address size.  */
423 #define HAVE_64BIT_ADDRESSES \
424   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
425 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
426
427 /* The size of symbolic constants (i.e., expressions of the form
428    "SYMBOL" or "SYMBOL + OFFSET").  */
429 #define HAVE_32BIT_SYMBOLS \
430   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
431 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
432
433 /* Addresses are loaded in different ways, depending on the address size
434    in use.  The n32 ABI Documentation also mandates the use of additions
435    with overflow checking, but existing implementations don't follow it.  */
436 #define ADDRESS_ADD_INSN                                                \
437    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
438
439 #define ADDRESS_ADDI_INSN                                               \
440    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
441
442 #define ADDRESS_LOAD_INSN                                               \
443    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
444
445 #define ADDRESS_STORE_INSN                                              \
446    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
447
448 /* Return true if the given CPU supports the MIPS16 ASE.  */
449 #define CPU_HAS_MIPS16(cpu)                                             \
450    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
451     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
452
453 /* True if CPU has a dror instruction.  */
454 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
455
456 /* True if CPU has a ror instruction.  */
457 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
458
459 /* True if CPU has seq/sne and seqi/snei instructions.  */
460 #define CPU_HAS_SEQ(CPU)        ((CPU) == CPU_OCTEON)
461
462 /* True if CPU does not implement the all the coprocessor insns.  For these
463    CPUs only those COP insns are accepted that are explicitly marked to be
464    available on the CPU.  ISA membership for COP insns is ignored.  */
465 #define NO_ISA_COP(CPU)         ((CPU) == CPU_OCTEON)
466
467 /* True if mflo and mfhi can be immediately followed by instructions
468    which write to the HI and LO registers.
469
470    According to MIPS specifications, MIPS ISAs I, II, and III need
471    (at least) two instructions between the reads of HI/LO and
472    instructions which write them, and later ISAs do not.  Contradicting
473    the MIPS specifications, some MIPS IV processor user manuals (e.g.
474    the UM for the NEC Vr5000) document needing the instructions between
475    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
476    MIPS64 and later ISAs to have the interlocks, plus any specific
477    earlier-ISA CPUs for which CPU documentation declares that the
478    instructions are really interlocked.  */
479 #define hilo_interlocks \
480   (mips_opts.isa == ISA_MIPS32                        \
481    || mips_opts.isa == ISA_MIPS32R2                   \
482    || mips_opts.isa == ISA_MIPS64                     \
483    || mips_opts.isa == ISA_MIPS64R2                   \
484    || mips_opts.arch == CPU_R4010                     \
485    || mips_opts.arch == CPU_R10000                    \
486    || mips_opts.arch == CPU_R12000                    \
487    || mips_opts.arch == CPU_R14000                    \
488    || mips_opts.arch == CPU_R16000                    \
489    || mips_opts.arch == CPU_RM7000                    \
490    || mips_opts.arch == CPU_VR5500                    \
491    )
492
493 /* Whether the processor uses hardware interlocks to protect reads
494    from the GPRs after they are loaded from memory, and thus does not
495    require nops to be inserted.  This applies to instructions marked
496    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
497    level I.  */
498 #define gpr_interlocks \
499   (mips_opts.isa != ISA_MIPS1  \
500    || mips_opts.arch == CPU_R3900)
501
502 /* Whether the processor uses hardware interlocks to avoid delays
503    required by coprocessor instructions, and thus does not require
504    nops to be inserted.  This applies to instructions marked
505    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
506    between instructions marked INSN_WRITE_COND_CODE and ones marked
507    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
508    levels I, II, and III.  */
509 /* Itbl support may require additional care here.  */
510 #define cop_interlocks                                \
511   ((mips_opts.isa != ISA_MIPS1                        \
512     && mips_opts.isa != ISA_MIPS2                     \
513     && mips_opts.isa != ISA_MIPS3)                    \
514    || mips_opts.arch == CPU_R4300                     \
515    )
516
517 /* Whether the processor uses hardware interlocks to protect reads
518    from coprocessor registers after they are loaded from memory, and
519    thus does not require nops to be inserted.  This applies to
520    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
521    requires at MIPS ISA level I.  */
522 #define cop_mem_interlocks (mips_opts.isa != ISA_MIPS1)
523
524 /* Is this a mfhi or mflo instruction?  */
525 #define MF_HILO_INSN(PINFO) \
526   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
527
528 /* Returns true for a (non floating-point) coprocessor instruction.  Reading
529    or writing the condition code is only possible on the coprocessors and
530    these insns are not marked with INSN_COP.  Thus for these insns use the
531    condition-code flags.  */
532 #define COP_INSN(PINFO)                                                 \
533   (PINFO != INSN_MACRO                                                  \
534    && ((PINFO) & (FP_S | FP_D)) == 0                                    \
535    && ((PINFO) & (INSN_COP | INSN_READ_COND_CODE | INSN_WRITE_COND_CODE)))
536
537 /* MIPS PIC level.  */
538
539 enum mips_pic_level mips_pic;
540
541 /* 1 if we should generate 32 bit offsets from the $gp register in
542    SVR4_PIC mode.  Currently has no meaning in other modes.  */
543 static int mips_big_got = 0;
544
545 /* 1 if trap instructions should used for overflow rather than break
546    instructions.  */
547 static int mips_trap = 0;
548
549 /* 1 if double width floating point constants should not be constructed
550    by assembling two single width halves into two single width floating
551    point registers which just happen to alias the double width destination
552    register.  On some architectures this aliasing can be disabled by a bit
553    in the status register, and the setting of this bit cannot be determined
554    automatically at assemble time.  */
555 static int mips_disable_float_construction;
556
557 /* Non-zero if any .set noreorder directives were used.  */
558
559 static int mips_any_noreorder;
560
561 /* Non-zero if nops should be inserted when the register referenced in
562    an mfhi/mflo instruction is read in the next two instructions.  */
563 static int mips_7000_hilo_fix;
564
565 /* The size of objects in the small data section.  */
566 static unsigned int g_switch_value = 8;
567 /* Whether the -G option was used.  */
568 static int g_switch_seen = 0;
569
570 #define N_RMASK 0xc4
571 #define N_VFP   0xd4
572
573 /* If we can determine in advance that GP optimization won't be
574    possible, we can skip the relaxation stuff that tries to produce
575    GP-relative references.  This makes delay slot optimization work
576    better.
577
578    This function can only provide a guess, but it seems to work for
579    gcc output.  It needs to guess right for gcc, otherwise gcc
580    will put what it thinks is a GP-relative instruction in a branch
581    delay slot.
582
583    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
584    fixed it for the non-PIC mode.  KR 95/04/07  */
585 static int nopic_need_relax (symbolS *, int);
586
587 /* handle of the OPCODE hash table */
588 static struct hash_control *op_hash = NULL;
589
590 /* The opcode hash table we use for the mips16.  */
591 static struct hash_control *mips16_op_hash = NULL;
592
593 /* This array holds the chars that always start a comment.  If the
594     pre-processor is disabled, these aren't very useful */
595 const char comment_chars[] = "#";
596
597 /* This array holds the chars that only start a comment at the beginning of
598    a line.  If the line seems to have the form '# 123 filename'
599    .line and .file directives will appear in the pre-processed output */
600 /* Note that input_file.c hand checks for '#' at the beginning of the
601    first line of the input file.  This is because the compiler outputs
602    #NO_APP at the beginning of its output.  */
603 /* Also note that C style comments are always supported.  */
604 const char line_comment_chars[] = "#";
605
606 /* This array holds machine specific line separator characters.  */
607 const char line_separator_chars[] = ";";
608
609 /* Chars that can be used to separate mant from exp in floating point nums */
610 const char EXP_CHARS[] = "eE";
611
612 /* Chars that mean this number is a floating point constant */
613 /* As in 0f12.456 */
614 /* or    0d1.2345e12 */
615 const char FLT_CHARS[] = "rRsSfFdDxXpP";
616
617 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
618    changed in read.c .  Ideally it shouldn't have to know about it at all,
619    but nothing is ideal around here.
620  */
621
622 static char *insn_error;
623
624 static int auto_align = 1;
625
626 /* When outputting SVR4 PIC code, the assembler needs to know the
627    offset in the stack frame from which to restore the $gp register.
628    This is set by the .cprestore pseudo-op, and saved in this
629    variable.  */
630 static offsetT mips_cprestore_offset = -1;
631
632 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
633    more optimizations, it can use a register value instead of a memory-saved
634    offset and even an other register than $gp as global pointer.  */
635 static offsetT mips_cpreturn_offset = -1;
636 static int mips_cpreturn_register = -1;
637 static int mips_gp_register = GP;
638 static int mips_gprel_offset = 0;
639
640 /* Whether mips_cprestore_offset has been set in the current function
641    (or whether it has already been warned about, if not).  */
642 static int mips_cprestore_valid = 0;
643
644 /* This is the register which holds the stack frame, as set by the
645    .frame pseudo-op.  This is needed to implement .cprestore.  */
646 static int mips_frame_reg = SP;
647
648 /* Whether mips_frame_reg has been set in the current function
649    (or whether it has already been warned about, if not).  */
650 static int mips_frame_reg_valid = 0;
651
652 /* To output NOP instructions correctly, we need to keep information
653    about the previous two instructions.  */
654
655 /* Whether we are optimizing.  The default value of 2 means to remove
656    unneeded NOPs and swap branch instructions when possible.  A value
657    of 1 means to not swap branches.  A value of 0 means to always
658    insert NOPs.  */
659 static int mips_optimize = 2;
660
661 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
662    equivalent to seeing no -g option at all.  */
663 static int mips_debug = 0;
664
665 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
666 #define MAX_VR4130_NOPS 4
667
668 /* The maximum number of NOPs needed to fill delay slots.  */
669 #define MAX_DELAY_NOPS 2
670
671 /* The maximum number of NOPs needed for any purpose.  */
672 #define MAX_NOPS 4
673
674 /* A list of previous instructions, with index 0 being the most recent.
675    We need to look back MAX_NOPS instructions when filling delay slots
676    or working around processor errata.  We need to look back one
677    instruction further if we're thinking about using history[0] to
678    fill a branch delay slot.  */
679 static struct mips_cl_insn history[1 + MAX_NOPS];
680
681 /* Nop instructions used by emit_nop.  */
682 static struct mips_cl_insn nop_insn, mips16_nop_insn;
683
684 /* The appropriate nop for the current mode.  */
685 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn : &nop_insn)
686
687 /* If this is set, it points to a frag holding nop instructions which
688    were inserted before the start of a noreorder section.  If those
689    nops turn out to be unnecessary, the size of the frag can be
690    decreased.  */
691 static fragS *prev_nop_frag;
692
693 /* The number of nop instructions we created in prev_nop_frag.  */
694 static int prev_nop_frag_holds;
695
696 /* The number of nop instructions that we know we need in
697    prev_nop_frag.  */
698 static int prev_nop_frag_required;
699
700 /* The number of instructions we've seen since prev_nop_frag.  */
701 static int prev_nop_frag_since;
702
703 /* For ECOFF and ELF, relocations against symbols are done in two
704    parts, with a HI relocation and a LO relocation.  Each relocation
705    has only 16 bits of space to store an addend.  This means that in
706    order for the linker to handle carries correctly, it must be able
707    to locate both the HI and the LO relocation.  This means that the
708    relocations must appear in order in the relocation table.
709
710    In order to implement this, we keep track of each unmatched HI
711    relocation.  We then sort them so that they immediately precede the
712    corresponding LO relocation.  */
713
714 struct mips_hi_fixup
715 {
716   /* Next HI fixup.  */
717   struct mips_hi_fixup *next;
718   /* This fixup.  */
719   fixS *fixp;
720   /* The section this fixup is in.  */
721   segT seg;
722 };
723
724 /* The list of unmatched HI relocs.  */
725
726 static struct mips_hi_fixup *mips_hi_fixup_list;
727
728 /* The frag containing the last explicit relocation operator.
729    Null if explicit relocations have not been used.  */
730
731 static fragS *prev_reloc_op_frag;
732
733 /* Map normal MIPS register numbers to mips16 register numbers.  */
734
735 #define X ILLEGAL_REG
736 static const int mips32_to_16_reg_map[] =
737 {
738   X, X, 2, 3, 4, 5, 6, 7,
739   X, X, X, X, X, X, X, X,
740   0, 1, X, X, X, X, X, X,
741   X, X, X, X, X, X, X, X
742 };
743 #undef X
744
745 /* Map mips16 register numbers to normal MIPS register numbers.  */
746
747 static const unsigned int mips16_to_32_reg_map[] =
748 {
749   16, 17, 2, 3, 4, 5, 6, 7
750 };
751
752 /* Classifies the kind of instructions we're interested in when
753    implementing -mfix-vr4120.  */
754 enum fix_vr4120_class
755 {
756   FIX_VR4120_MACC,
757   FIX_VR4120_DMACC,
758   FIX_VR4120_MULT,
759   FIX_VR4120_DMULT,
760   FIX_VR4120_DIV,
761   FIX_VR4120_MTHILO,
762   NUM_FIX_VR4120_CLASSES
763 };
764
765 /* ...likewise -mfix-loongson2f-jump.  */
766 static bfd_boolean mips_fix_loongson2f_jump;
767
768 /* ...likewise -mfix-loongson2f-nop.  */
769 static bfd_boolean mips_fix_loongson2f_nop;
770
771 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
772 static bfd_boolean mips_fix_loongson2f;
773
774 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
775    there must be at least one other instruction between an instruction
776    of type X and an instruction of type Y.  */
777 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
778
779 /* True if -mfix-vr4120 is in force.  */
780 static int mips_fix_vr4120;
781
782 /* ...likewise -mfix-vr4130.  */
783 static int mips_fix_vr4130;
784
785 /* ...likewise -mfix-24k.  */
786 static int mips_fix_24k;
787
788 /* ...likewise -mfix-cn63xxp1 */
789 static bfd_boolean mips_fix_cn63xxp1;
790
791 /* We don't relax branches by default, since this causes us to expand
792    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
793    fail to compute the offset before expanding the macro to the most
794    efficient expansion.  */
795
796 static int mips_relax_branch;
797 \f
798 /* The expansion of many macros depends on the type of symbol that
799    they refer to.  For example, when generating position-dependent code,
800    a macro that refers to a symbol may have two different expansions,
801    one which uses GP-relative addresses and one which uses absolute
802    addresses.  When generating SVR4-style PIC, a macro may have
803    different expansions for local and global symbols.
804
805    We handle these situations by generating both sequences and putting
806    them in variant frags.  In position-dependent code, the first sequence
807    will be the GP-relative one and the second sequence will be the
808    absolute one.  In SVR4 PIC, the first sequence will be for global
809    symbols and the second will be for local symbols.
810
811    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
812    SECOND are the lengths of the two sequences in bytes.  These fields
813    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
814    the subtype has the following flags:
815
816    RELAX_USE_SECOND
817         Set if it has been decided that we should use the second
818         sequence instead of the first.
819
820    RELAX_SECOND_LONGER
821         Set in the first variant frag if the macro's second implementation
822         is longer than its first.  This refers to the macro as a whole,
823         not an individual relaxation.
824
825    RELAX_NOMACRO
826         Set in the first variant frag if the macro appeared in a .set nomacro
827         block and if one alternative requires a warning but the other does not.
828
829    RELAX_DELAY_SLOT
830         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
831         delay slot.
832
833    The frag's "opcode" points to the first fixup for relaxable code.
834
835    Relaxable macros are generated using a sequence such as:
836
837       relax_start (SYMBOL);
838       ... generate first expansion ...
839       relax_switch ();
840       ... generate second expansion ...
841       relax_end ();
842
843    The code and fixups for the unwanted alternative are discarded
844    by md_convert_frag.  */
845 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
846
847 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
848 #define RELAX_SECOND(X) ((X) & 0xff)
849 #define RELAX_USE_SECOND 0x10000
850 #define RELAX_SECOND_LONGER 0x20000
851 #define RELAX_NOMACRO 0x40000
852 #define RELAX_DELAY_SLOT 0x80000
853
854 /* Branch without likely bit.  If label is out of range, we turn:
855
856         beq reg1, reg2, label
857         delay slot
858
859    into
860
861         bne reg1, reg2, 0f
862         nop
863         j label
864      0: delay slot
865
866    with the following opcode replacements:
867
868         beq <-> bne
869         blez <-> bgtz
870         bltz <-> bgez
871         bc1f <-> bc1t
872
873         bltzal <-> bgezal  (with jal label instead of j label)
874
875    Even though keeping the delay slot instruction in the delay slot of
876    the branch would be more efficient, it would be very tricky to do
877    correctly, because we'd have to introduce a variable frag *after*
878    the delay slot instruction, and expand that instead.  Let's do it
879    the easy way for now, even if the branch-not-taken case now costs
880    one additional instruction.  Out-of-range branches are not supposed
881    to be common, anyway.
882
883    Branch likely.  If label is out of range, we turn:
884
885         beql reg1, reg2, label
886         delay slot (annulled if branch not taken)
887
888    into
889
890         beql reg1, reg2, 1f
891         nop
892         beql $0, $0, 2f
893         nop
894      1: j[al] label
895         delay slot (executed only if branch taken)
896      2:
897
898    It would be possible to generate a shorter sequence by losing the
899    likely bit, generating something like:
900
901         bne reg1, reg2, 0f
902         nop
903         j[al] label
904         delay slot (executed only if branch taken)
905      0:
906
907         beql -> bne
908         bnel -> beq
909         blezl -> bgtz
910         bgtzl -> blez
911         bltzl -> bgez
912         bgezl -> bltz
913         bc1fl -> bc1t
914         bc1tl -> bc1f
915
916         bltzall -> bgezal  (with jal label instead of j label)
917         bgezall -> bltzal  (ditto)
918
919
920    but it's not clear that it would actually improve performance.  */
921 #define RELAX_BRANCH_ENCODE(uncond, likely, link, toofar) \
922   ((relax_substateT) \
923    (0xc0000000 \
924     | ((toofar) ? 1 : 0) \
925     | ((link) ? 2 : 0) \
926     | ((likely) ? 4 : 0) \
927     | ((uncond) ? 8 : 0)))
928 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
929 #define RELAX_BRANCH_UNCOND(i) (((i) & 8) != 0)
930 #define RELAX_BRANCH_LIKELY(i) (((i) & 4) != 0)
931 #define RELAX_BRANCH_LINK(i) (((i) & 2) != 0)
932 #define RELAX_BRANCH_TOOFAR(i) (((i) & 1) != 0)
933
934 /* For mips16 code, we use an entirely different form of relaxation.
935    mips16 supports two versions of most instructions which take
936    immediate values: a small one which takes some small value, and a
937    larger one which takes a 16 bit value.  Since branches also follow
938    this pattern, relaxing these values is required.
939
940    We can assemble both mips16 and normal MIPS code in a single
941    object.  Therefore, we need to support this type of relaxation at
942    the same time that we support the relaxation described above.  We
943    use the high bit of the subtype field to distinguish these cases.
944
945    The information we store for this type of relaxation is the
946    argument code found in the opcode file for this relocation, whether
947    the user explicitly requested a small or extended form, and whether
948    the relocation is in a jump or jal delay slot.  That tells us the
949    size of the value, and how it should be stored.  We also store
950    whether the fragment is considered to be extended or not.  We also
951    store whether this is known to be a branch to a different section,
952    whether we have tried to relax this frag yet, and whether we have
953    ever extended a PC relative fragment because of a shift count.  */
954 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
955   (0x80000000                                                   \
956    | ((type) & 0xff)                                            \
957    | ((small) ? 0x100 : 0)                                      \
958    | ((ext) ? 0x200 : 0)                                        \
959    | ((dslot) ? 0x400 : 0)                                      \
960    | ((jal_dslot) ? 0x800 : 0))
961 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
962 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
963 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
964 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
965 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
966 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
967 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
968 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
969 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
970 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
971 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
972 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
973
974 /* Is the given value a sign-extended 32-bit value?  */
975 #define IS_SEXT_32BIT_NUM(x)                                            \
976   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
977    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
978
979 /* Is the given value a sign-extended 16-bit value?  */
980 #define IS_SEXT_16BIT_NUM(x)                                            \
981   (((x) &~ (offsetT) 0x7fff) == 0                                       \
982    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
983
984 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
985 #define IS_ZEXT_32BIT_NUM(x)                                            \
986   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
987    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
988
989 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
990    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
991 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
992   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
993               | (((VALUE) & (MASK)) << (SHIFT)))
994
995 /* Extract bits MASK << SHIFT from STRUCT and shift them right
996    SHIFT places.  */
997 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
998   (((STRUCT) >> (SHIFT)) & (MASK))
999
1000 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1001    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1002
1003    include/opcode/mips.h specifies operand fields using the macros
1004    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1005    with "MIPS16OP" instead of "OP".  */
1006 #define INSERT_OPERAND(FIELD, INSN, VALUE) \
1007   INSERT_BITS ((INSN).insn_opcode, VALUE, OP_MASK_##FIELD, OP_SH_##FIELD)
1008 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1009   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1010                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1011
1012 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1013 #define EXTRACT_OPERAND(FIELD, INSN) \
1014   EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD)
1015 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1016   EXTRACT_BITS ((INSN).insn_opcode, \
1017                 MIPS16OP_MASK_##FIELD, \
1018                 MIPS16OP_SH_##FIELD)
1019 \f
1020 /* Global variables used when generating relaxable macros.  See the
1021    comment above RELAX_ENCODE for more details about how relaxation
1022    is used.  */
1023 static struct {
1024   /* 0 if we're not emitting a relaxable macro.
1025      1 if we're emitting the first of the two relaxation alternatives.
1026      2 if we're emitting the second alternative.  */
1027   int sequence;
1028
1029   /* The first relaxable fixup in the current frag.  (In other words,
1030      the first fixup that refers to relaxable code.)  */
1031   fixS *first_fixup;
1032
1033   /* sizes[0] says how many bytes of the first alternative are stored in
1034      the current frag.  Likewise sizes[1] for the second alternative.  */
1035   unsigned int sizes[2];
1036
1037   /* The symbol on which the choice of sequence depends.  */
1038   symbolS *symbol;
1039 } mips_relax;
1040 \f
1041 /* Global variables used to decide whether a macro needs a warning.  */
1042 static struct {
1043   /* True if the macro is in a branch delay slot.  */
1044   bfd_boolean delay_slot_p;
1045
1046   /* For relaxable macros, sizes[0] is the length of the first alternative
1047      in bytes and sizes[1] is the length of the second alternative.
1048      For non-relaxable macros, both elements give the length of the
1049      macro in bytes.  */
1050   unsigned int sizes[2];
1051
1052   /* The first variant frag for this macro.  */
1053   fragS *first_frag;
1054 } mips_macro_warning;
1055 \f
1056 /* Prototypes for static functions.  */
1057
1058 #define internalError()                                                 \
1059     as_fatal (_("internal Error, line %d, %s"), __LINE__, __FILE__)
1060
1061 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1062
1063 static void append_insn
1064   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *);
1065 static void mips_no_prev_insn (void);
1066 static void macro_build (expressionS *, const char *, const char *, ...);
1067 static void mips16_macro_build
1068   (expressionS *, const char *, const char *, va_list *);
1069 static void load_register (int, expressionS *, int);
1070 static void macro_start (void);
1071 static void macro_end (void);
1072 static void macro (struct mips_cl_insn * ip);
1073 static void mips16_macro (struct mips_cl_insn * ip);
1074 static void mips_ip (char *str, struct mips_cl_insn * ip);
1075 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1076 static void mips16_immed
1077   (char *, unsigned int, int, offsetT, bfd_boolean, bfd_boolean, bfd_boolean,
1078    unsigned long *, bfd_boolean *, unsigned short *);
1079 static size_t my_getSmallExpression
1080   (expressionS *, bfd_reloc_code_real_type *, char *);
1081 static void my_getExpression (expressionS *, char *);
1082 static void s_align (int);
1083 static void s_change_sec (int);
1084 static void s_change_section (int);
1085 static void s_cons (int);
1086 static void s_float_cons (int);
1087 static void s_mips_globl (int);
1088 static void s_option (int);
1089 static void s_mipsset (int);
1090 static void s_abicalls (int);
1091 static void s_cpload (int);
1092 static void s_cpsetup (int);
1093 static void s_cplocal (int);
1094 static void s_cprestore (int);
1095 static void s_cpreturn (int);
1096 static void s_dtprelword (int);
1097 static void s_dtpreldword (int);
1098 static void s_gpvalue (int);
1099 static void s_gpword (int);
1100 static void s_gpdword (int);
1101 static void s_cpadd (int);
1102 static void s_insn (int);
1103 static void md_obj_begin (void);
1104 static void md_obj_end (void);
1105 static void s_mips_ent (int);
1106 static void s_mips_end (int);
1107 static void s_mips_frame (int);
1108 static void s_mips_mask (int reg_type);
1109 static void s_mips_stab (int);
1110 static void s_mips_weakext (int);
1111 static void s_mips_file (int);
1112 static void s_mips_loc (int);
1113 static bfd_boolean pic_need_relax (symbolS *, asection *);
1114 static int relaxed_branch_length (fragS *, asection *, int);
1115 static int validate_mips_insn (const struct mips_opcode *);
1116
1117 /* Table and functions used to map between CPU/ISA names, and
1118    ISA levels, and CPU numbers.  */
1119
1120 struct mips_cpu_info
1121 {
1122   const char *name;           /* CPU or ISA name.  */
1123   int flags;                  /* ASEs available, or ISA flag.  */
1124   int isa;                    /* ISA level.  */
1125   int cpu;                    /* CPU number (default CPU if ISA).  */
1126 };
1127
1128 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1129 #define MIPS_CPU_ASE_SMARTMIPS  0x0002  /* CPU implements SmartMIPS ASE */
1130 #define MIPS_CPU_ASE_DSP        0x0004  /* CPU implements DSP ASE */
1131 #define MIPS_CPU_ASE_MT         0x0008  /* CPU implements MT ASE */
1132 #define MIPS_CPU_ASE_MIPS3D     0x0010  /* CPU implements MIPS-3D ASE */
1133 #define MIPS_CPU_ASE_MDMX       0x0020  /* CPU implements MDMX ASE */
1134 #define MIPS_CPU_ASE_DSPR2      0x0040  /* CPU implements DSP R2 ASE */
1135
1136 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1137 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1138 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1139 \f
1140 /* Pseudo-op table.
1141
1142    The following pseudo-ops from the Kane and Heinrich MIPS book
1143    should be defined here, but are currently unsupported: .alias,
1144    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1145
1146    The following pseudo-ops from the Kane and Heinrich MIPS book are
1147    specific to the type of debugging information being generated, and
1148    should be defined by the object format: .aent, .begin, .bend,
1149    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1150    .vreg.
1151
1152    The following pseudo-ops from the Kane and Heinrich MIPS book are
1153    not MIPS CPU specific, but are also not specific to the object file
1154    format.  This file is probably the best place to define them, but
1155    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1156
1157 static const pseudo_typeS mips_pseudo_table[] =
1158 {
1159   /* MIPS specific pseudo-ops.  */
1160   {"option", s_option, 0},
1161   {"set", s_mipsset, 0},
1162   {"rdata", s_change_sec, 'r'},
1163   {"sdata", s_change_sec, 's'},
1164   {"livereg", s_ignore, 0},
1165   {"abicalls", s_abicalls, 0},
1166   {"cpload", s_cpload, 0},
1167   {"cpsetup", s_cpsetup, 0},
1168   {"cplocal", s_cplocal, 0},
1169   {"cprestore", s_cprestore, 0},
1170   {"cpreturn", s_cpreturn, 0},
1171   {"dtprelword", s_dtprelword, 0},
1172   {"dtpreldword", s_dtpreldword, 0},
1173   {"gpvalue", s_gpvalue, 0},
1174   {"gpword", s_gpword, 0},
1175   {"gpdword", s_gpdword, 0},
1176   {"cpadd", s_cpadd, 0},
1177   {"insn", s_insn, 0},
1178
1179   /* Relatively generic pseudo-ops that happen to be used on MIPS
1180      chips.  */
1181   {"asciiz", stringer, 8 + 1},
1182   {"bss", s_change_sec, 'b'},
1183   {"err", s_err, 0},
1184   {"half", s_cons, 1},
1185   {"dword", s_cons, 3},
1186   {"weakext", s_mips_weakext, 0},
1187   {"origin", s_org, 0},
1188   {"repeat", s_rept, 0},
1189
1190   /* For MIPS this is non-standard, but we define it for consistency.  */
1191   {"sbss", s_change_sec, 'B'},
1192
1193   /* These pseudo-ops are defined in read.c, but must be overridden
1194      here for one reason or another.  */
1195   {"align", s_align, 0},
1196   {"byte", s_cons, 0},
1197   {"data", s_change_sec, 'd'},
1198   {"double", s_float_cons, 'd'},
1199   {"float", s_float_cons, 'f'},
1200   {"globl", s_mips_globl, 0},
1201   {"global", s_mips_globl, 0},
1202   {"hword", s_cons, 1},
1203   {"int", s_cons, 2},
1204   {"long", s_cons, 2},
1205   {"octa", s_cons, 4},
1206   {"quad", s_cons, 3},
1207   {"section", s_change_section, 0},
1208   {"short", s_cons, 1},
1209   {"single", s_float_cons, 'f'},
1210   {"stabn", s_mips_stab, 'n'},
1211   {"text", s_change_sec, 't'},
1212   {"word", s_cons, 2},
1213
1214   { "extern", ecoff_directive_extern, 0},
1215
1216   { NULL, NULL, 0 },
1217 };
1218
1219 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1220 {
1221   /* These pseudo-ops should be defined by the object file format.
1222      However, a.out doesn't support them, so we have versions here.  */
1223   {"aent", s_mips_ent, 1},
1224   {"bgnb", s_ignore, 0},
1225   {"end", s_mips_end, 0},
1226   {"endb", s_ignore, 0},
1227   {"ent", s_mips_ent, 0},
1228   {"file", s_mips_file, 0},
1229   {"fmask", s_mips_mask, 'F'},
1230   {"frame", s_mips_frame, 0},
1231   {"loc", s_mips_loc, 0},
1232   {"mask", s_mips_mask, 'R'},
1233   {"verstamp", s_ignore, 0},
1234   { NULL, NULL, 0 },
1235 };
1236
1237 extern void pop_insert (const pseudo_typeS *);
1238
1239 void
1240 mips_pop_insert (void)
1241 {
1242   pop_insert (mips_pseudo_table);
1243   if (! ECOFF_DEBUGGING)
1244     pop_insert (mips_nonecoff_pseudo_table);
1245 }
1246 \f
1247 /* Symbols labelling the current insn.  */
1248
1249 struct insn_label_list
1250 {
1251   struct insn_label_list *next;
1252   symbolS *label;
1253 };
1254
1255 static struct insn_label_list *free_insn_labels;
1256 #define label_list tc_segment_info_data.labels
1257
1258 static void mips_clear_insn_labels (void);
1259
1260 static inline void
1261 mips_clear_insn_labels (void)
1262 {
1263   register struct insn_label_list **pl;
1264   segment_info_type *si;
1265
1266   if (now_seg)
1267     {
1268       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1269         ;
1270       
1271       si = seg_info (now_seg);
1272       *pl = si->label_list;
1273       si->label_list = NULL;
1274     }
1275 }
1276
1277 \f
1278 static char *expr_end;
1279
1280 /* Expressions which appear in instructions.  These are set by
1281    mips_ip.  */
1282
1283 static expressionS imm_expr;
1284 static expressionS imm2_expr;
1285 static expressionS offset_expr;
1286
1287 /* Relocs associated with imm_expr and offset_expr.  */
1288
1289 static bfd_reloc_code_real_type imm_reloc[3]
1290   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1291 static bfd_reloc_code_real_type offset_reloc[3]
1292   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1293
1294 /* These are set by mips16_ip if an explicit extension is used.  */
1295
1296 static bfd_boolean mips16_small, mips16_ext;
1297
1298 #ifdef OBJ_ELF
1299 /* The pdr segment for per procedure frame/regmask info.  Not used for
1300    ECOFF debugging.  */
1301
1302 static segT pdr_seg;
1303 #endif
1304
1305 /* The default target format to use.  */
1306
1307 const char *
1308 mips_target_format (void)
1309 {
1310   switch (OUTPUT_FLAVOR)
1311     {
1312     case bfd_target_ecoff_flavour:
1313       return target_big_endian ? "ecoff-bigmips" : ECOFF_LITTLE_FORMAT;
1314     case bfd_target_coff_flavour:
1315       return "pe-mips";
1316     case bfd_target_elf_flavour:
1317 #ifdef TE_VXWORKS
1318       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1319         return (target_big_endian
1320                 ? "elf32-bigmips-vxworks"
1321                 : "elf32-littlemips-vxworks");
1322 #endif
1323 #ifdef TE_TMIPS
1324       /* This is traditional mips.  */
1325       return (target_big_endian
1326               ? (HAVE_64BIT_OBJECTS
1327                  ? "elf64-tradbigmips"
1328                  : (HAVE_NEWABI
1329                     ? "elf32-ntradbigmips" : "elf32-tradbigmips"))
1330               : (HAVE_64BIT_OBJECTS
1331                  ? "elf64-tradlittlemips"
1332                  : (HAVE_NEWABI
1333                     ? "elf32-ntradlittlemips" : "elf32-tradlittlemips")));
1334 #else
1335       return (target_big_endian
1336               ? (HAVE_64BIT_OBJECTS
1337                  ? "elf64-bigmips"
1338                  : (HAVE_NEWABI
1339                     ? "elf32-nbigmips" : "elf32-bigmips"))
1340               : (HAVE_64BIT_OBJECTS
1341                  ? "elf64-littlemips"
1342                  : (HAVE_NEWABI
1343                     ? "elf32-nlittlemips" : "elf32-littlemips")));
1344 #endif
1345     default:
1346       abort ();
1347       return NULL;
1348     }
1349 }
1350
1351 /* Return the length of instruction INSN.  */
1352
1353 static inline unsigned int
1354 insn_length (const struct mips_cl_insn *insn)
1355 {
1356   if (!mips_opts.mips16)
1357     return 4;
1358   return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1359 }
1360
1361 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1362
1363 static void
1364 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1365 {
1366   size_t i;
1367
1368   insn->insn_mo = mo;
1369   insn->use_extend = FALSE;
1370   insn->extend = 0;
1371   insn->insn_opcode = mo->match;
1372   insn->frag = NULL;
1373   insn->where = 0;
1374   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1375     insn->fixp[i] = NULL;
1376   insn->fixed_p = (mips_opts.noreorder > 0);
1377   insn->noreorder_p = (mips_opts.noreorder > 0);
1378   insn->mips16_absolute_jump_p = 0;
1379 }
1380
1381 /* Record the current MIPS16 mode in now_seg.  */
1382
1383 static void
1384 mips_record_mips16_mode (void)
1385 {
1386   segment_info_type *si;
1387
1388   si = seg_info (now_seg);
1389   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
1390     si->tc_segment_info_data.mips16 = mips_opts.mips16;
1391 }
1392
1393 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1394
1395 static void
1396 install_insn (const struct mips_cl_insn *insn)
1397 {
1398   char *f = insn->frag->fr_literal + insn->where;
1399   if (!mips_opts.mips16)
1400     md_number_to_chars (f, insn->insn_opcode, 4);
1401   else if (insn->mips16_absolute_jump_p)
1402     {
1403       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1404       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1405     }
1406   else
1407     {
1408       if (insn->use_extend)
1409         {
1410           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1411           f += 2;
1412         }
1413       md_number_to_chars (f, insn->insn_opcode, 2);
1414     }
1415   mips_record_mips16_mode ();
1416 }
1417
1418 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1419    and install the opcode in the new location.  */
1420
1421 static void
1422 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1423 {
1424   size_t i;
1425
1426   insn->frag = frag;
1427   insn->where = where;
1428   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1429     if (insn->fixp[i] != NULL)
1430       {
1431         insn->fixp[i]->fx_frag = frag;
1432         insn->fixp[i]->fx_where = where;
1433       }
1434   install_insn (insn);
1435 }
1436
1437 /* Add INSN to the end of the output.  */
1438
1439 static void
1440 add_fixed_insn (struct mips_cl_insn *insn)
1441 {
1442   char *f = frag_more (insn_length (insn));
1443   move_insn (insn, frag_now, f - frag_now->fr_literal);
1444 }
1445
1446 /* Start a variant frag and move INSN to the start of the variant part,
1447    marking it as fixed.  The other arguments are as for frag_var.  */
1448
1449 static void
1450 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1451                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1452 {
1453   frag_grow (max_chars);
1454   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1455   insn->fixed_p = 1;
1456   frag_var (rs_machine_dependent, max_chars, var,
1457             subtype, symbol, offset, NULL);
1458 }
1459
1460 /* Insert N copies of INSN into the history buffer, starting at
1461    position FIRST.  Neither FIRST nor N need to be clipped.  */
1462
1463 static void
1464 insert_into_history (unsigned int first, unsigned int n,
1465                      const struct mips_cl_insn *insn)
1466 {
1467   if (mips_relax.sequence != 2)
1468     {
1469       unsigned int i;
1470
1471       for (i = ARRAY_SIZE (history); i-- > first;)
1472         if (i >= first + n)
1473           history[i] = history[i - n];
1474         else
1475           history[i] = *insn;
1476     }
1477 }
1478
1479 /* Emit a nop instruction, recording it in the history buffer.  */
1480
1481 static void
1482 emit_nop (void)
1483 {
1484   add_fixed_insn (NOP_INSN);
1485   insert_into_history (0, 1, NOP_INSN);
1486 }
1487
1488 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1489    the idea is to make it obvious at a glance that each errata is
1490    included.  */
1491
1492 static void
1493 init_vr4120_conflicts (void)
1494 {
1495 #define CONFLICT(FIRST, SECOND) \
1496     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1497
1498   /* Errata 21 - [D]DIV[U] after [D]MACC */
1499   CONFLICT (MACC, DIV);
1500   CONFLICT (DMACC, DIV);
1501
1502   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1503   CONFLICT (DMULT, DMULT);
1504   CONFLICT (DMULT, DMACC);
1505   CONFLICT (DMACC, DMULT);
1506   CONFLICT (DMACC, DMACC);
1507
1508   /* Errata 24 - MT{LO,HI} after [D]MACC */
1509   CONFLICT (MACC, MTHILO);
1510   CONFLICT (DMACC, MTHILO);
1511
1512   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1513      instruction is executed immediately after a MACC or DMACC
1514      instruction, the result of [either instruction] is incorrect."  */
1515   CONFLICT (MACC, MULT);
1516   CONFLICT (MACC, DMULT);
1517   CONFLICT (DMACC, MULT);
1518   CONFLICT (DMACC, DMULT);
1519
1520   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1521      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1522      DDIV or DDIVU instruction, the result of the MACC or
1523      DMACC instruction is incorrect.".  */
1524   CONFLICT (DMULT, MACC);
1525   CONFLICT (DMULT, DMACC);
1526   CONFLICT (DIV, MACC);
1527   CONFLICT (DIV, DMACC);
1528
1529 #undef CONFLICT
1530 }
1531
1532 struct regname {
1533   const char *name;
1534   unsigned int num;
1535 };
1536
1537 #define RTYPE_MASK      0x1ff00
1538 #define RTYPE_NUM       0x00100
1539 #define RTYPE_FPU       0x00200
1540 #define RTYPE_FCC       0x00400
1541 #define RTYPE_VEC       0x00800
1542 #define RTYPE_GP        0x01000
1543 #define RTYPE_CP0       0x02000
1544 #define RTYPE_PC        0x04000
1545 #define RTYPE_ACC       0x08000
1546 #define RTYPE_CCC       0x10000
1547 #define RNUM_MASK       0x000ff
1548 #define RWARN           0x80000
1549
1550 #define GENERIC_REGISTER_NUMBERS \
1551     {"$0",      RTYPE_NUM | 0},  \
1552     {"$1",      RTYPE_NUM | 1},  \
1553     {"$2",      RTYPE_NUM | 2},  \
1554     {"$3",      RTYPE_NUM | 3},  \
1555     {"$4",      RTYPE_NUM | 4},  \
1556     {"$5",      RTYPE_NUM | 5},  \
1557     {"$6",      RTYPE_NUM | 6},  \
1558     {"$7",      RTYPE_NUM | 7},  \
1559     {"$8",      RTYPE_NUM | 8},  \
1560     {"$9",      RTYPE_NUM | 9},  \
1561     {"$10",     RTYPE_NUM | 10}, \
1562     {"$11",     RTYPE_NUM | 11}, \
1563     {"$12",     RTYPE_NUM | 12}, \
1564     {"$13",     RTYPE_NUM | 13}, \
1565     {"$14",     RTYPE_NUM | 14}, \
1566     {"$15",     RTYPE_NUM | 15}, \
1567     {"$16",     RTYPE_NUM | 16}, \
1568     {"$17",     RTYPE_NUM | 17}, \
1569     {"$18",     RTYPE_NUM | 18}, \
1570     {"$19",     RTYPE_NUM | 19}, \
1571     {"$20",     RTYPE_NUM | 20}, \
1572     {"$21",     RTYPE_NUM | 21}, \
1573     {"$22",     RTYPE_NUM | 22}, \
1574     {"$23",     RTYPE_NUM | 23}, \
1575     {"$24",     RTYPE_NUM | 24}, \
1576     {"$25",     RTYPE_NUM | 25}, \
1577     {"$26",     RTYPE_NUM | 26}, \
1578     {"$27",     RTYPE_NUM | 27}, \
1579     {"$28",     RTYPE_NUM | 28}, \
1580     {"$29",     RTYPE_NUM | 29}, \
1581     {"$30",     RTYPE_NUM | 30}, \
1582     {"$31",     RTYPE_NUM | 31} 
1583
1584 #define FPU_REGISTER_NAMES       \
1585     {"$f0",     RTYPE_FPU | 0},  \
1586     {"$f1",     RTYPE_FPU | 1},  \
1587     {"$f2",     RTYPE_FPU | 2},  \
1588     {"$f3",     RTYPE_FPU | 3},  \
1589     {"$f4",     RTYPE_FPU | 4},  \
1590     {"$f5",     RTYPE_FPU | 5},  \
1591     {"$f6",     RTYPE_FPU | 6},  \
1592     {"$f7",     RTYPE_FPU | 7},  \
1593     {"$f8",     RTYPE_FPU | 8},  \
1594     {"$f9",     RTYPE_FPU | 9},  \
1595     {"$f10",    RTYPE_FPU | 10}, \
1596     {"$f11",    RTYPE_FPU | 11}, \
1597     {"$f12",    RTYPE_FPU | 12}, \
1598     {"$f13",    RTYPE_FPU | 13}, \
1599     {"$f14",    RTYPE_FPU | 14}, \
1600     {"$f15",    RTYPE_FPU | 15}, \
1601     {"$f16",    RTYPE_FPU | 16}, \
1602     {"$f17",    RTYPE_FPU | 17}, \
1603     {"$f18",    RTYPE_FPU | 18}, \
1604     {"$f19",    RTYPE_FPU | 19}, \
1605     {"$f20",    RTYPE_FPU | 20}, \
1606     {"$f21",    RTYPE_FPU | 21}, \
1607     {"$f22",    RTYPE_FPU | 22}, \
1608     {"$f23",    RTYPE_FPU | 23}, \
1609     {"$f24",    RTYPE_FPU | 24}, \
1610     {"$f25",    RTYPE_FPU | 25}, \
1611     {"$f26",    RTYPE_FPU | 26}, \
1612     {"$f27",    RTYPE_FPU | 27}, \
1613     {"$f28",    RTYPE_FPU | 28}, \
1614     {"$f29",    RTYPE_FPU | 29}, \
1615     {"$f30",    RTYPE_FPU | 30}, \
1616     {"$f31",    RTYPE_FPU | 31}
1617
1618 #define FPU_CONDITION_CODE_NAMES \
1619     {"$fcc0",   RTYPE_FCC | 0},  \
1620     {"$fcc1",   RTYPE_FCC | 1},  \
1621     {"$fcc2",   RTYPE_FCC | 2},  \
1622     {"$fcc3",   RTYPE_FCC | 3},  \
1623     {"$fcc4",   RTYPE_FCC | 4},  \
1624     {"$fcc5",   RTYPE_FCC | 5},  \
1625     {"$fcc6",   RTYPE_FCC | 6},  \
1626     {"$fcc7",   RTYPE_FCC | 7}
1627
1628 #define COPROC_CONDITION_CODE_NAMES         \
1629     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
1630     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
1631     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
1632     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
1633     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
1634     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
1635     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
1636     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
1637
1638 #define N32N64_SYMBOLIC_REGISTER_NAMES \
1639     {"$a4",     RTYPE_GP | 8},  \
1640     {"$a5",     RTYPE_GP | 9},  \
1641     {"$a6",     RTYPE_GP | 10}, \
1642     {"$a7",     RTYPE_GP | 11}, \
1643     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
1644     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
1645     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
1646     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
1647     {"$t0",     RTYPE_GP | 12}, \
1648     {"$t1",     RTYPE_GP | 13}, \
1649     {"$t2",     RTYPE_GP | 14}, \
1650     {"$t3",     RTYPE_GP | 15}
1651
1652 #define O32_SYMBOLIC_REGISTER_NAMES \
1653     {"$t0",     RTYPE_GP | 8},  \
1654     {"$t1",     RTYPE_GP | 9},  \
1655     {"$t2",     RTYPE_GP | 10}, \
1656     {"$t3",     RTYPE_GP | 11}, \
1657     {"$t4",     RTYPE_GP | 12}, \
1658     {"$t5",     RTYPE_GP | 13}, \
1659     {"$t6",     RTYPE_GP | 14}, \
1660     {"$t7",     RTYPE_GP | 15}, \
1661     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
1662     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
1663     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
1664     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
1665
1666 /* Remaining symbolic register names */
1667 #define SYMBOLIC_REGISTER_NAMES \
1668     {"$zero",   RTYPE_GP | 0},  \
1669     {"$at",     RTYPE_GP | 1},  \
1670     {"$AT",     RTYPE_GP | 1},  \
1671     {"$v0",     RTYPE_GP | 2},  \
1672     {"$v1",     RTYPE_GP | 3},  \
1673     {"$a0",     RTYPE_GP | 4},  \
1674     {"$a1",     RTYPE_GP | 5},  \
1675     {"$a2",     RTYPE_GP | 6},  \
1676     {"$a3",     RTYPE_GP | 7},  \
1677     {"$s0",     RTYPE_GP | 16}, \
1678     {"$s1",     RTYPE_GP | 17}, \
1679     {"$s2",     RTYPE_GP | 18}, \
1680     {"$s3",     RTYPE_GP | 19}, \
1681     {"$s4",     RTYPE_GP | 20}, \
1682     {"$s5",     RTYPE_GP | 21}, \
1683     {"$s6",     RTYPE_GP | 22}, \
1684     {"$s7",     RTYPE_GP | 23}, \
1685     {"$t8",     RTYPE_GP | 24}, \
1686     {"$t9",     RTYPE_GP | 25}, \
1687     {"$k0",     RTYPE_GP | 26}, \
1688     {"$kt0",    RTYPE_GP | 26}, \
1689     {"$k1",     RTYPE_GP | 27}, \
1690     {"$kt1",    RTYPE_GP | 27}, \
1691     {"$gp",     RTYPE_GP | 28}, \
1692     {"$sp",     RTYPE_GP | 29}, \
1693     {"$s8",     RTYPE_GP | 30}, \
1694     {"$fp",     RTYPE_GP | 30}, \
1695     {"$ra",     RTYPE_GP | 31}
1696
1697 #define MIPS16_SPECIAL_REGISTER_NAMES \
1698     {"$pc",     RTYPE_PC | 0}
1699
1700 #define MDMX_VECTOR_REGISTER_NAMES \
1701     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
1702     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
1703     {"$v2",     RTYPE_VEC | 2},  \
1704     {"$v3",     RTYPE_VEC | 3},  \
1705     {"$v4",     RTYPE_VEC | 4},  \
1706     {"$v5",     RTYPE_VEC | 5},  \
1707     {"$v6",     RTYPE_VEC | 6},  \
1708     {"$v7",     RTYPE_VEC | 7},  \
1709     {"$v8",     RTYPE_VEC | 8},  \
1710     {"$v9",     RTYPE_VEC | 9},  \
1711     {"$v10",    RTYPE_VEC | 10}, \
1712     {"$v11",    RTYPE_VEC | 11}, \
1713     {"$v12",    RTYPE_VEC | 12}, \
1714     {"$v13",    RTYPE_VEC | 13}, \
1715     {"$v14",    RTYPE_VEC | 14}, \
1716     {"$v15",    RTYPE_VEC | 15}, \
1717     {"$v16",    RTYPE_VEC | 16}, \
1718     {"$v17",    RTYPE_VEC | 17}, \
1719     {"$v18",    RTYPE_VEC | 18}, \
1720     {"$v19",    RTYPE_VEC | 19}, \
1721     {"$v20",    RTYPE_VEC | 20}, \
1722     {"$v21",    RTYPE_VEC | 21}, \
1723     {"$v22",    RTYPE_VEC | 22}, \
1724     {"$v23",    RTYPE_VEC | 23}, \
1725     {"$v24",    RTYPE_VEC | 24}, \
1726     {"$v25",    RTYPE_VEC | 25}, \
1727     {"$v26",    RTYPE_VEC | 26}, \
1728     {"$v27",    RTYPE_VEC | 27}, \
1729     {"$v28",    RTYPE_VEC | 28}, \
1730     {"$v29",    RTYPE_VEC | 29}, \
1731     {"$v30",    RTYPE_VEC | 30}, \
1732     {"$v31",    RTYPE_VEC | 31}
1733
1734 #define MIPS_DSP_ACCUMULATOR_NAMES \
1735     {"$ac0",    RTYPE_ACC | 0}, \
1736     {"$ac1",    RTYPE_ACC | 1}, \
1737     {"$ac2",    RTYPE_ACC | 2}, \
1738     {"$ac3",    RTYPE_ACC | 3}
1739
1740 static const struct regname reg_names[] = {
1741   GENERIC_REGISTER_NUMBERS,
1742   FPU_REGISTER_NAMES,
1743   FPU_CONDITION_CODE_NAMES,
1744   COPROC_CONDITION_CODE_NAMES,
1745
1746   /* The $txx registers depends on the abi,
1747      these will be added later into the symbol table from
1748      one of the tables below once mips_abi is set after 
1749      parsing of arguments from the command line. */
1750   SYMBOLIC_REGISTER_NAMES,
1751
1752   MIPS16_SPECIAL_REGISTER_NAMES,
1753   MDMX_VECTOR_REGISTER_NAMES,
1754   MIPS_DSP_ACCUMULATOR_NAMES,
1755   {0, 0}
1756 };
1757
1758 static const struct regname reg_names_o32[] = {
1759   O32_SYMBOLIC_REGISTER_NAMES,
1760   {0, 0}
1761 };
1762
1763 static const struct regname reg_names_n32n64[] = {
1764   N32N64_SYMBOLIC_REGISTER_NAMES,
1765   {0, 0}
1766 };
1767
1768 static int
1769 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
1770 {
1771   symbolS *symbolP;
1772   char *e;
1773   char save_c;
1774   int reg = -1;
1775
1776   /* Find end of name.  */
1777   e = *s;
1778   if (is_name_beginner (*e))
1779     ++e;
1780   while (is_part_of_name (*e))
1781     ++e;
1782
1783   /* Terminate name.  */
1784   save_c = *e;
1785   *e = '\0';
1786
1787   /* Look for a register symbol.  */
1788   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
1789     {
1790       int r = S_GET_VALUE (symbolP);
1791       if (r & types)
1792         reg = r & RNUM_MASK;
1793       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
1794         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
1795         reg = (r & RNUM_MASK) - 2;
1796     }
1797   /* Else see if this is a register defined in an itbl entry.  */
1798   else if ((types & RTYPE_GP) && itbl_have_entries)
1799     {
1800       char *n = *s;
1801       unsigned long r;
1802
1803       if (*n == '$')
1804         ++n;
1805       if (itbl_get_reg_val (n, &r))
1806         reg = r & RNUM_MASK;
1807     }
1808
1809   /* Advance to next token if a register was recognised.  */
1810   if (reg >= 0)
1811     *s = e;
1812   else if (types & RWARN)
1813     as_warn (_("Unrecognized register name `%s'"), *s);
1814
1815   *e = save_c;
1816   if (regnop)
1817     *regnop = reg;
1818   return reg >= 0;
1819 }
1820
1821 /* Return TRUE if opcode MO is valid on the currently selected ISA and
1822    architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
1823
1824 static bfd_boolean
1825 is_opcode_valid (const struct mips_opcode *mo)
1826 {
1827   int isa = mips_opts.isa;
1828   int fp_s, fp_d;
1829
1830   if (mips_opts.ase_mdmx)
1831     isa |= INSN_MDMX;
1832   if (mips_opts.ase_dsp)
1833     isa |= INSN_DSP;
1834   if (mips_opts.ase_dsp && ISA_SUPPORTS_DSP64_ASE)
1835     isa |= INSN_DSP64;
1836   if (mips_opts.ase_dspr2)
1837     isa |= INSN_DSPR2;
1838   if (mips_opts.ase_mt)
1839     isa |= INSN_MT;
1840   if (mips_opts.ase_mips3d)
1841     isa |= INSN_MIPS3D;
1842   if (mips_opts.ase_smartmips)
1843     isa |= INSN_SMARTMIPS;
1844
1845   /* Don't accept instructions based on the ISA if the CPU does not implement
1846      all the coprocessor insns. */
1847   if (NO_ISA_COP (mips_opts.arch)
1848       && COP_INSN (mo->pinfo))
1849     isa = 0;
1850
1851   if (!OPCODE_IS_MEMBER (mo, isa, mips_opts.arch))
1852     return FALSE;
1853
1854   /* Check whether the instruction or macro requires single-precision or
1855      double-precision floating-point support.  Note that this information is
1856      stored differently in the opcode table for insns and macros.  */
1857   if (mo->pinfo == INSN_MACRO)
1858     {
1859       fp_s = mo->pinfo2 & INSN2_M_FP_S;
1860       fp_d = mo->pinfo2 & INSN2_M_FP_D;
1861     }
1862   else
1863     {
1864       fp_s = mo->pinfo & FP_S;
1865       fp_d = mo->pinfo & FP_D;
1866     }
1867
1868   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
1869     return FALSE;
1870
1871   if (fp_s && mips_opts.soft_float)
1872     return FALSE;
1873
1874   return TRUE;
1875 }
1876
1877 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
1878    selected ISA and architecture.  */
1879
1880 static bfd_boolean
1881 is_opcode_valid_16 (const struct mips_opcode *mo)
1882 {
1883   return OPCODE_IS_MEMBER (mo, mips_opts.isa, mips_opts.arch) ? TRUE : FALSE;
1884 }
1885
1886 /* This function is called once, at assembler startup time.  It should set up
1887    all the tables, etc. that the MD part of the assembler will need.  */
1888
1889 void
1890 md_begin (void)
1891 {
1892   const char *retval = NULL;
1893   int i = 0;
1894   int broken = 0;
1895
1896   if (mips_pic != NO_PIC)
1897     {
1898       if (g_switch_seen && g_switch_value != 0)
1899         as_bad (_("-G may not be used in position-independent code"));
1900       g_switch_value = 0;
1901     }
1902
1903   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
1904     as_warn (_("Could not set architecture and machine"));
1905
1906   op_hash = hash_new ();
1907
1908   for (i = 0; i < NUMOPCODES;)
1909     {
1910       const char *name = mips_opcodes[i].name;
1911
1912       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
1913       if (retval != NULL)
1914         {
1915           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
1916                    mips_opcodes[i].name, retval);
1917           /* Probably a memory allocation problem?  Give up now.  */
1918           as_fatal (_("Broken assembler.  No assembly attempted."));
1919         }
1920       do
1921         {
1922           if (mips_opcodes[i].pinfo != INSN_MACRO)
1923             {
1924               if (!validate_mips_insn (&mips_opcodes[i]))
1925                 broken = 1;
1926               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1927                 {
1928                   create_insn (&nop_insn, mips_opcodes + i);
1929                   if (mips_fix_loongson2f_nop)
1930                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
1931                   nop_insn.fixed_p = 1;
1932                 }
1933             }
1934           ++i;
1935         }
1936       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
1937     }
1938
1939   mips16_op_hash = hash_new ();
1940
1941   i = 0;
1942   while (i < bfd_mips16_num_opcodes)
1943     {
1944       const char *name = mips16_opcodes[i].name;
1945
1946       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
1947       if (retval != NULL)
1948         as_fatal (_("internal: can't hash `%s': %s"),
1949                   mips16_opcodes[i].name, retval);
1950       do
1951         {
1952           if (mips16_opcodes[i].pinfo != INSN_MACRO
1953               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
1954                   != mips16_opcodes[i].match))
1955             {
1956               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
1957                        mips16_opcodes[i].name, mips16_opcodes[i].args);
1958               broken = 1;
1959             }
1960           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
1961             {
1962               create_insn (&mips16_nop_insn, mips16_opcodes + i);
1963               mips16_nop_insn.fixed_p = 1;
1964             }
1965           ++i;
1966         }
1967       while (i < bfd_mips16_num_opcodes
1968              && strcmp (mips16_opcodes[i].name, name) == 0);
1969     }
1970
1971   if (broken)
1972     as_fatal (_("Broken assembler.  No assembly attempted."));
1973
1974   /* We add all the general register names to the symbol table.  This
1975      helps us detect invalid uses of them.  */
1976   for (i = 0; reg_names[i].name; i++) 
1977     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
1978                                      reg_names[i].num, /* & RNUM_MASK, */
1979                                      &zero_address_frag));
1980   if (HAVE_NEWABI)
1981     for (i = 0; reg_names_n32n64[i].name; i++) 
1982       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
1983                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
1984                                        &zero_address_frag));
1985   else
1986     for (i = 0; reg_names_o32[i].name; i++) 
1987       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
1988                                        reg_names_o32[i].num, /* & RNUM_MASK, */
1989                                        &zero_address_frag));
1990
1991   mips_no_prev_insn ();
1992
1993   mips_gprmask = 0;
1994   mips_cprmask[0] = 0;
1995   mips_cprmask[1] = 0;
1996   mips_cprmask[2] = 0;
1997   mips_cprmask[3] = 0;
1998
1999   /* set the default alignment for the text section (2**2) */
2000   record_alignment (text_section, 2);
2001
2002   bfd_set_gp_size (stdoutput, g_switch_value);
2003
2004 #ifdef OBJ_ELF
2005   if (IS_ELF)
2006     {
2007       /* On a native system other than VxWorks, sections must be aligned
2008          to 16 byte boundaries.  When configured for an embedded ELF
2009          target, we don't bother.  */
2010       if (strncmp (TARGET_OS, "elf", 3) != 0
2011           && strncmp (TARGET_OS, "vxworks", 7) != 0)
2012         {
2013           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2014           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2015           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2016         }
2017
2018       /* Create a .reginfo section for register masks and a .mdebug
2019          section for debugging information.  */
2020       {
2021         segT seg;
2022         subsegT subseg;
2023         flagword flags;
2024         segT sec;
2025
2026         seg = now_seg;
2027         subseg = now_subseg;
2028
2029         /* The ABI says this section should be loaded so that the
2030            running program can access it.  However, we don't load it
2031            if we are configured for an embedded target */
2032         flags = SEC_READONLY | SEC_DATA;
2033         if (strncmp (TARGET_OS, "elf", 3) != 0)
2034           flags |= SEC_ALLOC | SEC_LOAD;
2035
2036         if (mips_abi != N64_ABI)
2037           {
2038             sec = subseg_new (".reginfo", (subsegT) 0);
2039
2040             bfd_set_section_flags (stdoutput, sec, flags);
2041             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2042
2043             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2044           }
2045         else
2046           {
2047             /* The 64-bit ABI uses a .MIPS.options section rather than
2048                .reginfo section.  */
2049             sec = subseg_new (".MIPS.options", (subsegT) 0);
2050             bfd_set_section_flags (stdoutput, sec, flags);
2051             bfd_set_section_alignment (stdoutput, sec, 3);
2052
2053             /* Set up the option header.  */
2054             {
2055               Elf_Internal_Options opthdr;
2056               char *f;
2057
2058               opthdr.kind = ODK_REGINFO;
2059               opthdr.size = (sizeof (Elf_External_Options)
2060                              + sizeof (Elf64_External_RegInfo));
2061               opthdr.section = 0;
2062               opthdr.info = 0;
2063               f = frag_more (sizeof (Elf_External_Options));
2064               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2065                                              (Elf_External_Options *) f);
2066
2067               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2068             }
2069           }
2070
2071         if (ECOFF_DEBUGGING)
2072           {
2073             sec = subseg_new (".mdebug", (subsegT) 0);
2074             (void) bfd_set_section_flags (stdoutput, sec,
2075                                           SEC_HAS_CONTENTS | SEC_READONLY);
2076             (void) bfd_set_section_alignment (stdoutput, sec, 2);
2077           }
2078         else if (mips_flag_pdr)
2079           {
2080             pdr_seg = subseg_new (".pdr", (subsegT) 0);
2081             (void) bfd_set_section_flags (stdoutput, pdr_seg,
2082                                           SEC_READONLY | SEC_RELOC
2083                                           | SEC_DEBUGGING);
2084             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2085           }
2086
2087         subseg_set (seg, subseg);
2088       }
2089     }
2090 #endif /* OBJ_ELF */
2091
2092   if (! ECOFF_DEBUGGING)
2093     md_obj_begin ();
2094
2095   if (mips_fix_vr4120)
2096     init_vr4120_conflicts ();
2097 }
2098
2099 void
2100 md_mips_end (void)
2101 {
2102   if (! ECOFF_DEBUGGING)
2103     md_obj_end ();
2104 }
2105
2106 void
2107 md_assemble (char *str)
2108 {
2109   struct mips_cl_insn insn;
2110   bfd_reloc_code_real_type unused_reloc[3]
2111     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2112
2113   imm_expr.X_op = O_absent;
2114   imm2_expr.X_op = O_absent;
2115   offset_expr.X_op = O_absent;
2116   imm_reloc[0] = BFD_RELOC_UNUSED;
2117   imm_reloc[1] = BFD_RELOC_UNUSED;
2118   imm_reloc[2] = BFD_RELOC_UNUSED;
2119   offset_reloc[0] = BFD_RELOC_UNUSED;
2120   offset_reloc[1] = BFD_RELOC_UNUSED;
2121   offset_reloc[2] = BFD_RELOC_UNUSED;
2122
2123   if (mips_opts.mips16)
2124     mips16_ip (str, &insn);
2125   else
2126     {
2127       mips_ip (str, &insn);
2128       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
2129             str, insn.insn_opcode));
2130     }
2131
2132   if (insn_error)
2133     {
2134       as_bad ("%s `%s'", insn_error, str);
2135       return;
2136     }
2137
2138   if (insn.insn_mo->pinfo == INSN_MACRO)
2139     {
2140       macro_start ();
2141       if (mips_opts.mips16)
2142         mips16_macro (&insn);
2143       else
2144         macro (&insn);
2145       macro_end ();
2146     }
2147   else
2148     {
2149       if (imm_expr.X_op != O_absent)
2150         append_insn (&insn, &imm_expr, imm_reloc);
2151       else if (offset_expr.X_op != O_absent)
2152         append_insn (&insn, &offset_expr, offset_reloc);
2153       else
2154         append_insn (&insn, NULL, unused_reloc);
2155     }
2156 }
2157
2158 /* Convenience functions for abstracting away the differences between
2159    MIPS16 and non-MIPS16 relocations.  */
2160
2161 static inline bfd_boolean
2162 mips16_reloc_p (bfd_reloc_code_real_type reloc)
2163 {
2164   switch (reloc)
2165     {
2166     case BFD_RELOC_MIPS16_JMP:
2167     case BFD_RELOC_MIPS16_GPREL:
2168     case BFD_RELOC_MIPS16_GOT16:
2169     case BFD_RELOC_MIPS16_CALL16:
2170     case BFD_RELOC_MIPS16_HI16_S:
2171     case BFD_RELOC_MIPS16_HI16:
2172     case BFD_RELOC_MIPS16_LO16:
2173       return TRUE;
2174
2175     default:
2176       return FALSE;
2177     }
2178 }
2179
2180 static inline bfd_boolean
2181 got16_reloc_p (bfd_reloc_code_real_type reloc)
2182 {
2183   return reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16;
2184 }
2185
2186 static inline bfd_boolean
2187 hi16_reloc_p (bfd_reloc_code_real_type reloc)
2188 {
2189   return reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S;
2190 }
2191
2192 static inline bfd_boolean
2193 lo16_reloc_p (bfd_reloc_code_real_type reloc)
2194 {
2195   return reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16;
2196 }
2197
2198 /* Return true if the given relocation might need a matching %lo().
2199    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
2200    need a matching %lo() when applied to local symbols.  */
2201
2202 static inline bfd_boolean
2203 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
2204 {
2205   return (HAVE_IN_PLACE_ADDENDS
2206           && (hi16_reloc_p (reloc)
2207               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
2208                  all GOT16 relocations evaluate to "G".  */
2209               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
2210 }
2211
2212 /* Return the type of %lo() reloc needed by RELOC, given that
2213    reloc_needs_lo_p.  */
2214
2215 static inline bfd_reloc_code_real_type
2216 matching_lo_reloc (bfd_reloc_code_real_type reloc)
2217 {
2218   return mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16 : BFD_RELOC_LO16;
2219 }
2220
2221 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
2222    relocation.  */
2223
2224 static inline bfd_boolean
2225 fixup_has_matching_lo_p (fixS *fixp)
2226 {
2227   return (fixp->fx_next != NULL
2228           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
2229           && fixp->fx_addsy == fixp->fx_next->fx_addsy
2230           && fixp->fx_offset == fixp->fx_next->fx_offset);
2231 }
2232
2233 /* See whether instruction IP reads register REG.  CLASS is the type
2234    of register.  */
2235
2236 static int
2237 insn_uses_reg (const struct mips_cl_insn *ip, unsigned int reg,
2238                enum mips_regclass regclass)
2239 {
2240   if (regclass == MIPS16_REG)
2241     {
2242       gas_assert (mips_opts.mips16);
2243       reg = mips16_to_32_reg_map[reg];
2244       regclass = MIPS_GR_REG;
2245     }
2246
2247   /* Don't report on general register ZERO, since it never changes.  */
2248   if (regclass == MIPS_GR_REG && reg == ZERO)
2249     return 0;
2250
2251   if (regclass == MIPS_FP_REG)
2252     {
2253       gas_assert (! mips_opts.mips16);
2254       /* If we are called with either $f0 or $f1, we must check $f0.
2255          This is not optimal, because it will introduce an unnecessary
2256          NOP between "lwc1 $f0" and "swc1 $f1".  To fix this we would
2257          need to distinguish reading both $f0 and $f1 or just one of
2258          them.  Note that we don't have to check the other way,
2259          because there is no instruction that sets both $f0 and $f1
2260          and requires a delay.  */
2261       if ((ip->insn_mo->pinfo & INSN_READ_FPR_S)
2262           && ((EXTRACT_OPERAND (FS, *ip) & ~(unsigned) 1)
2263               == (reg &~ (unsigned) 1)))
2264         return 1;
2265       if ((ip->insn_mo->pinfo & INSN_READ_FPR_T)
2266           && ((EXTRACT_OPERAND (FT, *ip) & ~(unsigned) 1)
2267               == (reg &~ (unsigned) 1)))
2268         return 1;
2269     }
2270   else if (! mips_opts.mips16)
2271     {
2272       if ((ip->insn_mo->pinfo & INSN_READ_GPR_S)
2273           && EXTRACT_OPERAND (RS, *ip) == reg)
2274         return 1;
2275       if ((ip->insn_mo->pinfo & INSN_READ_GPR_T)
2276           && EXTRACT_OPERAND (RT, *ip) == reg)
2277         return 1;
2278     }
2279   else
2280     {
2281       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_X)
2282           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)] == reg)
2283         return 1;
2284       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Y)
2285           && mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)] == reg)
2286         return 1;
2287       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_Z)
2288           && (mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]
2289               == reg))
2290         return 1;
2291       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_T) && reg == TREG)
2292         return 1;
2293       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_SP) && reg == SP)
2294         return 1;
2295       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_31) && reg == RA)
2296         return 1;
2297       if ((ip->insn_mo->pinfo & MIPS16_INSN_READ_GPR_X)
2298           && MIPS16_EXTRACT_OPERAND (REGR32, *ip) == reg)
2299         return 1;
2300     }
2301
2302   return 0;
2303 }
2304
2305 /* This function returns true if modifying a register requires a
2306    delay.  */
2307
2308 static int
2309 reg_needs_delay (unsigned int reg)
2310 {
2311   unsigned long prev_pinfo;
2312
2313   prev_pinfo = history[0].insn_mo->pinfo;
2314   if (! mips_opts.noreorder
2315       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
2316            && ! gpr_interlocks)
2317           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
2318               && ! cop_interlocks)))
2319     {
2320       /* A load from a coprocessor or from memory.  All load delays
2321          delay the use of general register rt for one instruction.  */
2322       /* Itbl support may require additional care here.  */
2323       know (prev_pinfo & INSN_WRITE_GPR_T);
2324       if (reg == EXTRACT_OPERAND (RT, history[0]))
2325         return 1;
2326     }
2327
2328   return 0;
2329 }
2330
2331 /* Move all labels in insn_labels to the current insertion point.  */
2332
2333 static void
2334 mips_move_labels (void)
2335 {
2336   segment_info_type *si = seg_info (now_seg);
2337   struct insn_label_list *l;
2338   valueT val;
2339
2340   for (l = si->label_list; l != NULL; l = l->next)
2341     {
2342       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
2343       symbol_set_frag (l->label, frag_now);
2344       val = (valueT) frag_now_fix ();
2345       /* mips16 text labels are stored as odd.  */
2346       if (mips_opts.mips16)
2347         ++val;
2348       S_SET_VALUE (l->label, val);
2349     }
2350 }
2351
2352 static bfd_boolean
2353 s_is_linkonce (symbolS *sym, segT from_seg)
2354 {
2355   bfd_boolean linkonce = FALSE;
2356   segT symseg = S_GET_SEGMENT (sym);
2357
2358   if (symseg != from_seg && !S_IS_LOCAL (sym))
2359     {
2360       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
2361         linkonce = TRUE;
2362 #ifdef OBJ_ELF
2363       /* The GNU toolchain uses an extension for ELF: a section
2364          beginning with the magic string .gnu.linkonce is a
2365          linkonce section.  */
2366       if (strncmp (segment_name (symseg), ".gnu.linkonce",
2367                    sizeof ".gnu.linkonce" - 1) == 0)
2368         linkonce = TRUE;
2369 #endif
2370     }
2371   return linkonce;
2372 }
2373
2374 /* Mark instruction labels in mips16 mode.  This permits the linker to
2375    handle them specially, such as generating jalx instructions when
2376    needed.  We also make them odd for the duration of the assembly, in
2377    order to generate the right sort of code.  We will make them even
2378    in the adjust_symtab routine, while leaving them marked.  This is
2379    convenient for the debugger and the disassembler.  The linker knows
2380    to make them odd again.  */
2381
2382 static void
2383 mips16_mark_labels (void)
2384 {
2385   segment_info_type *si = seg_info (now_seg);
2386   struct insn_label_list *l;
2387
2388   if (!mips_opts.mips16)
2389     return;
2390
2391   for (l = si->label_list; l != NULL; l = l->next)
2392    {
2393       symbolS *label = l->label;
2394
2395 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
2396       if (IS_ELF)
2397         S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
2398 #endif
2399       if ((S_GET_VALUE (label) & 1) == 0
2400         /* Don't adjust the address if the label is global or weak, or
2401            in a link-once section, since we'll be emitting symbol reloc
2402            references to it which will be patched up by the linker, and
2403            the final value of the symbol may or may not be MIPS16.  */
2404           && ! S_IS_WEAK (label)
2405           && ! S_IS_EXTERNAL (label)
2406           && ! s_is_linkonce (label, now_seg))
2407         S_SET_VALUE (label, S_GET_VALUE (label) | 1);
2408     }
2409 }
2410
2411 /* End the current frag.  Make it a variant frag and record the
2412    relaxation info.  */
2413
2414 static void
2415 relax_close_frag (void)
2416 {
2417   mips_macro_warning.first_frag = frag_now;
2418   frag_var (rs_machine_dependent, 0, 0,
2419             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
2420             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
2421
2422   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
2423   mips_relax.first_fixup = 0;
2424 }
2425
2426 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
2427    See the comment above RELAX_ENCODE for more details.  */
2428
2429 static void
2430 relax_start (symbolS *symbol)
2431 {
2432   gas_assert (mips_relax.sequence == 0);
2433   mips_relax.sequence = 1;
2434   mips_relax.symbol = symbol;
2435 }
2436
2437 /* Start generating the second version of a relaxable sequence.
2438    See the comment above RELAX_ENCODE for more details.  */
2439
2440 static void
2441 relax_switch (void)
2442 {
2443   gas_assert (mips_relax.sequence == 1);
2444   mips_relax.sequence = 2;
2445 }
2446
2447 /* End the current relaxable sequence.  */
2448
2449 static void
2450 relax_end (void)
2451 {
2452   gas_assert (mips_relax.sequence == 2);
2453   relax_close_frag ();
2454   mips_relax.sequence = 0;
2455 }
2456
2457 /* Classify an instruction according to the FIX_VR4120_* enumeration.
2458    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
2459    by VR4120 errata.  */
2460
2461 static unsigned int
2462 classify_vr4120_insn (const char *name)
2463 {
2464   if (strncmp (name, "macc", 4) == 0)
2465     return FIX_VR4120_MACC;
2466   if (strncmp (name, "dmacc", 5) == 0)
2467     return FIX_VR4120_DMACC;
2468   if (strncmp (name, "mult", 4) == 0)
2469     return FIX_VR4120_MULT;
2470   if (strncmp (name, "dmult", 5) == 0)
2471     return FIX_VR4120_DMULT;
2472   if (strstr (name, "div"))
2473     return FIX_VR4120_DIV;
2474   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
2475     return FIX_VR4120_MTHILO;
2476   return NUM_FIX_VR4120_CLASSES;
2477 }
2478
2479 #define INSN_ERET  0x42000018
2480 #define INSN_DERET 0x4200001f
2481
2482 /* Return the number of instructions that must separate INSN1 and INSN2,
2483    where INSN1 is the earlier instruction.  Return the worst-case value
2484    for any INSN2 if INSN2 is null.  */
2485
2486 static unsigned int
2487 insns_between (const struct mips_cl_insn *insn1,
2488                const struct mips_cl_insn *insn2)
2489 {
2490   unsigned long pinfo1, pinfo2;
2491
2492   /* This function needs to know which pinfo flags are set for INSN2
2493      and which registers INSN2 uses.  The former is stored in PINFO2 and
2494      the latter is tested via INSN2_USES_REG.  If INSN2 is null, PINFO2
2495      will have every flag set and INSN2_USES_REG will always return true.  */
2496   pinfo1 = insn1->insn_mo->pinfo;
2497   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
2498
2499 #define INSN2_USES_REG(REG, CLASS) \
2500    (insn2 == NULL || insn_uses_reg (insn2, REG, CLASS))
2501
2502   /* For most targets, write-after-read dependencies on the HI and LO
2503      registers must be separated by at least two instructions.  */
2504   if (!hilo_interlocks)
2505     {
2506       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
2507         return 2;
2508       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
2509         return 2;
2510     }
2511
2512   /* If we're working around r7000 errata, there must be two instructions
2513      between an mfhi or mflo and any instruction that uses the result.  */
2514   if (mips_7000_hilo_fix
2515       && MF_HILO_INSN (pinfo1)
2516       && INSN2_USES_REG (EXTRACT_OPERAND (RD, *insn1), MIPS_GR_REG))
2517     return 2;
2518
2519   /* If we're working around 24K errata, one instruction is required
2520      if an ERET or DERET is followed by a branch instruction.  */
2521   if (mips_fix_24k)
2522     {
2523       if (insn1->insn_opcode == INSN_ERET
2524           || insn1->insn_opcode == INSN_DERET)
2525         {
2526           if (insn2 == NULL
2527               || insn2->insn_opcode == INSN_ERET
2528               || insn2->insn_opcode == INSN_DERET
2529               || (insn2->insn_mo->pinfo
2530                   & (INSN_UNCOND_BRANCH_DELAY
2531                      | INSN_COND_BRANCH_DELAY
2532                      | INSN_COND_BRANCH_LIKELY)) != 0)
2533             return 1;
2534         }
2535     }
2536
2537   /* If working around VR4120 errata, check for combinations that need
2538      a single intervening instruction.  */
2539   if (mips_fix_vr4120)
2540     {
2541       unsigned int class1, class2;
2542
2543       class1 = classify_vr4120_insn (insn1->insn_mo->name);
2544       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
2545         {
2546           if (insn2 == NULL)
2547             return 1;
2548           class2 = classify_vr4120_insn (insn2->insn_mo->name);
2549           if (vr4120_conflicts[class1] & (1 << class2))
2550             return 1;
2551         }
2552     }
2553
2554   if (!mips_opts.mips16)
2555     {
2556       /* Check for GPR or coprocessor load delays.  All such delays
2557          are on the RT register.  */
2558       /* Itbl support may require additional care here.  */
2559       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
2560           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
2561         {
2562           know (pinfo1 & INSN_WRITE_GPR_T);
2563           if (INSN2_USES_REG (EXTRACT_OPERAND (RT, *insn1), MIPS_GR_REG))
2564             return 1;
2565         }
2566
2567       /* Check for generic coprocessor hazards.
2568
2569          This case is not handled very well.  There is no special
2570          knowledge of CP0 handling, and the coprocessors other than
2571          the floating point unit are not distinguished at all.  */
2572       /* Itbl support may require additional care here. FIXME!
2573          Need to modify this to include knowledge about
2574          user specified delays!  */
2575       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
2576                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
2577         {
2578           /* Handle cases where INSN1 writes to a known general coprocessor
2579              register.  There must be a one instruction delay before INSN2
2580              if INSN2 reads that register, otherwise no delay is needed.  */
2581           if (pinfo1 & INSN_WRITE_FPR_T)
2582             {
2583               if (INSN2_USES_REG (EXTRACT_OPERAND (FT, *insn1), MIPS_FP_REG))
2584                 return 1;
2585             }
2586           else if (pinfo1 & INSN_WRITE_FPR_S)
2587             {
2588               if (INSN2_USES_REG (EXTRACT_OPERAND (FS, *insn1), MIPS_FP_REG))
2589                 return 1;
2590             }
2591           else
2592             {
2593               /* Read-after-write dependencies on the control registers
2594                  require a two-instruction gap.  */
2595               if ((pinfo1 & INSN_WRITE_COND_CODE)
2596                   && (pinfo2 & INSN_READ_COND_CODE))
2597                 return 2;
2598
2599               /* We don't know exactly what INSN1 does.  If INSN2 is
2600                  also a coprocessor instruction, assume there must be
2601                  a one instruction gap.  */
2602               if (pinfo2 & INSN_COP)
2603                 return 1;
2604             }
2605         }
2606
2607       /* Check for read-after-write dependencies on the coprocessor
2608          control registers in cases where INSN1 does not need a general
2609          coprocessor delay.  This means that INSN1 is a floating point
2610          comparison instruction.  */
2611       /* Itbl support may require additional care here.  */
2612       else if (!cop_interlocks
2613                && (pinfo1 & INSN_WRITE_COND_CODE)
2614                && (pinfo2 & INSN_READ_COND_CODE))
2615         return 1;
2616     }
2617
2618 #undef INSN2_USES_REG
2619
2620   return 0;
2621 }
2622
2623 /* Return the number of nops that would be needed to work around the
2624    VR4130 mflo/mfhi errata if instruction INSN immediately followed
2625    the MAX_VR4130_NOPS instructions described by HIST.  */
2626
2627 static int
2628 nops_for_vr4130 (const struct mips_cl_insn *hist,
2629                  const struct mips_cl_insn *insn)
2630 {
2631   int i, j, reg;
2632
2633   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
2634      are not affected by the errata.  */
2635   if (insn != 0
2636       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
2637           || strcmp (insn->insn_mo->name, "mtlo") == 0
2638           || strcmp (insn->insn_mo->name, "mthi") == 0))
2639     return 0;
2640
2641   /* Search for the first MFLO or MFHI.  */
2642   for (i = 0; i < MAX_VR4130_NOPS; i++)
2643     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
2644       {
2645         /* Extract the destination register.  */
2646         if (mips_opts.mips16)
2647           reg = mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, hist[i])];
2648         else
2649           reg = EXTRACT_OPERAND (RD, hist[i]);
2650
2651         /* No nops are needed if INSN reads that register.  */
2652         if (insn != NULL && insn_uses_reg (insn, reg, MIPS_GR_REG))
2653           return 0;
2654
2655         /* ...or if any of the intervening instructions do.  */
2656         for (j = 0; j < i; j++)
2657           if (insn_uses_reg (&hist[j], reg, MIPS_GR_REG))
2658             return 0;
2659
2660         return MAX_VR4130_NOPS - i;
2661       }
2662   return 0;
2663 }
2664
2665 /* Return the number of nops that would be needed if instruction INSN
2666    immediately followed the MAX_NOPS instructions given by HIST,
2667    where HIST[0] is the most recent instruction.  If INSN is null,
2668    return the worse-case number of nops for any instruction.  */
2669
2670 static int
2671 nops_for_insn (const struct mips_cl_insn *hist,
2672                const struct mips_cl_insn *insn)
2673 {
2674   int i, nops, tmp_nops;
2675
2676   nops = 0;
2677   for (i = 0; i < MAX_DELAY_NOPS; i++)
2678     {
2679       tmp_nops = insns_between (hist + i, insn) - i;
2680       if (tmp_nops > nops)
2681         nops = tmp_nops;
2682     }
2683
2684   if (mips_fix_vr4130)
2685     {
2686       tmp_nops = nops_for_vr4130 (hist, insn);
2687       if (tmp_nops > nops)
2688         nops = tmp_nops;
2689     }
2690
2691   return nops;
2692 }
2693
2694 /* The variable arguments provide NUM_INSNS extra instructions that
2695    might be added to HIST.  Return the largest number of nops that
2696    would be needed after the extended sequence.  */
2697
2698 static int
2699 nops_for_sequence (int num_insns, const struct mips_cl_insn *hist, ...)
2700 {
2701   va_list args;
2702   struct mips_cl_insn buffer[MAX_NOPS];
2703   struct mips_cl_insn *cursor;
2704   int nops;
2705
2706   va_start (args, hist);
2707   cursor = buffer + num_insns;
2708   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
2709   while (cursor > buffer)
2710     *--cursor = *va_arg (args, const struct mips_cl_insn *);
2711
2712   nops = nops_for_insn (buffer, NULL);
2713   va_end (args);
2714   return nops;
2715 }
2716
2717 /* Like nops_for_insn, but if INSN is a branch, take into account the
2718    worst-case delay for the branch target.  */
2719
2720 static int
2721 nops_for_insn_or_target (const struct mips_cl_insn *hist,
2722                          const struct mips_cl_insn *insn)
2723 {
2724   int nops, tmp_nops;
2725
2726   nops = nops_for_insn (hist, insn);
2727   if (insn->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
2728                               | INSN_COND_BRANCH_DELAY
2729                               | INSN_COND_BRANCH_LIKELY))
2730     {
2731       tmp_nops = nops_for_sequence (2, hist, insn, NOP_INSN);
2732       if (tmp_nops > nops)
2733         nops = tmp_nops;
2734     }
2735   else if (mips_opts.mips16
2736            && (insn->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
2737                                        | MIPS16_INSN_COND_BRANCH)))
2738     {
2739       tmp_nops = nops_for_sequence (1, hist, insn);
2740       if (tmp_nops > nops)
2741         nops = tmp_nops;
2742     }
2743   return nops;
2744 }
2745
2746 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
2747
2748 static void
2749 fix_loongson2f_nop (struct mips_cl_insn * ip)
2750 {
2751   if (strcmp (ip->insn_mo->name, "nop") == 0)
2752     ip->insn_opcode = LOONGSON2F_NOP_INSN;
2753 }
2754
2755 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
2756                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
2757
2758 static void
2759 fix_loongson2f_jump (struct mips_cl_insn * ip)
2760 {
2761   if (strcmp (ip->insn_mo->name, "j") == 0
2762       || strcmp (ip->insn_mo->name, "jr") == 0
2763       || strcmp (ip->insn_mo->name, "jalr") == 0)
2764     {
2765       int sreg;
2766       expressionS ep;
2767
2768       if (! mips_opts.at)
2769         return;
2770
2771       sreg = EXTRACT_OPERAND (RS, *ip);
2772       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
2773         return;
2774
2775       ep.X_op = O_constant;
2776       ep.X_add_number = 0xcfff0000;
2777       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
2778       ep.X_add_number = 0xffff;
2779       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
2780       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
2781     }
2782 }
2783
2784 static void
2785 fix_loongson2f (struct mips_cl_insn * ip)
2786 {
2787   if (mips_fix_loongson2f_nop)
2788     fix_loongson2f_nop (ip);
2789
2790   if (mips_fix_loongson2f_jump)
2791     fix_loongson2f_jump (ip);
2792 }
2793
2794 /* Output an instruction.  IP is the instruction information.
2795    ADDRESS_EXPR is an operand of the instruction to be used with
2796    RELOC_TYPE.  */
2797
2798 static void
2799 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
2800              bfd_reloc_code_real_type *reloc_type)
2801 {
2802   unsigned long prev_pinfo, pinfo;
2803   relax_stateT prev_insn_frag_type = 0;
2804   bfd_boolean relaxed_branch = FALSE;
2805   segment_info_type *si = seg_info (now_seg);
2806
2807   if (mips_fix_loongson2f)
2808     fix_loongson2f (ip);
2809
2810   /* Mark instruction labels in mips16 mode.  */
2811   mips16_mark_labels ();
2812
2813   file_ase_mips16 |= mips_opts.mips16;
2814
2815   prev_pinfo = history[0].insn_mo->pinfo;
2816   pinfo = ip->insn_mo->pinfo;
2817
2818   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
2819     {
2820       /* There are a lot of optimizations we could do that we don't.
2821          In particular, we do not, in general, reorder instructions.
2822          If you use gcc with optimization, it will reorder
2823          instructions and generally do much more optimization then we
2824          do here; repeating all that work in the assembler would only
2825          benefit hand written assembly code, and does not seem worth
2826          it.  */
2827       int nops = (mips_optimize == 0
2828                   ? nops_for_insn (history, NULL)
2829                   : nops_for_insn_or_target (history, ip));
2830       if (nops > 0)
2831         {
2832           fragS *old_frag;
2833           unsigned long old_frag_offset;
2834           int i;
2835
2836           old_frag = frag_now;
2837           old_frag_offset = frag_now_fix ();
2838
2839           for (i = 0; i < nops; i++)
2840             emit_nop ();
2841
2842           if (listing)
2843             {
2844               listing_prev_line ();
2845               /* We may be at the start of a variant frag.  In case we
2846                  are, make sure there is enough space for the frag
2847                  after the frags created by listing_prev_line.  The
2848                  argument to frag_grow here must be at least as large
2849                  as the argument to all other calls to frag_grow in
2850                  this file.  We don't have to worry about being in the
2851                  middle of a variant frag, because the variants insert
2852                  all needed nop instructions themselves.  */
2853               frag_grow (40);
2854             }
2855
2856           mips_move_labels ();
2857
2858 #ifndef NO_ECOFF_DEBUGGING
2859           if (ECOFF_DEBUGGING)
2860             ecoff_fix_loc (old_frag, old_frag_offset);
2861 #endif
2862         }
2863     }
2864   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
2865     {
2866       /* Work out how many nops in prev_nop_frag are needed by IP.  */
2867       int nops = nops_for_insn_or_target (history, ip);
2868       gas_assert (nops <= prev_nop_frag_holds);
2869
2870       /* Enforce NOPS as a minimum.  */
2871       if (nops > prev_nop_frag_required)
2872         prev_nop_frag_required = nops;
2873
2874       if (prev_nop_frag_holds == prev_nop_frag_required)
2875         {
2876           /* Settle for the current number of nops.  Update the history
2877              accordingly (for the benefit of any future .set reorder code).  */
2878           prev_nop_frag = NULL;
2879           insert_into_history (prev_nop_frag_since,
2880                                prev_nop_frag_holds, NOP_INSN);
2881         }
2882       else
2883         {
2884           /* Allow this instruction to replace one of the nops that was
2885              tentatively added to prev_nop_frag.  */
2886           prev_nop_frag->fr_fix -= mips_opts.mips16 ? 2 : 4;
2887           prev_nop_frag_holds--;
2888           prev_nop_frag_since++;
2889         }
2890     }
2891
2892 #ifdef OBJ_ELF
2893   /* The value passed to dwarf2_emit_insn is the distance between
2894      the beginning of the current instruction and the address that
2895      should be recorded in the debug tables.  For MIPS16 debug info
2896      we want to use ISA-encoded addresses, so we pass -1 for an
2897      address higher by one than the current.  */
2898   dwarf2_emit_insn (mips_opts.mips16 ? -1 : 0);
2899 #endif
2900
2901   /* Record the frag type before frag_var.  */
2902   if (history[0].frag)
2903     prev_insn_frag_type = history[0].frag->fr_type;
2904
2905   if (address_expr
2906       && *reloc_type == BFD_RELOC_16_PCREL_S2
2907       && (pinfo & INSN_UNCOND_BRANCH_DELAY || pinfo & INSN_COND_BRANCH_DELAY
2908           || pinfo & INSN_COND_BRANCH_LIKELY)
2909       && mips_relax_branch
2910       /* Don't try branch relaxation within .set nomacro, or within
2911          .set noat if we use $at for PIC computations.  If it turns
2912          out that the branch was out-of-range, we'll get an error.  */
2913       && !mips_opts.warn_about_macros
2914       && (mips_opts.at || mips_pic == NO_PIC)
2915       && !mips_opts.mips16)
2916     {
2917       relaxed_branch = TRUE;
2918       add_relaxed_insn (ip, (relaxed_branch_length
2919                              (NULL, NULL,
2920                               (pinfo & INSN_UNCOND_BRANCH_DELAY) ? -1
2921                               : (pinfo & INSN_COND_BRANCH_LIKELY) ? 1
2922                               : 0)), 4,
2923                         RELAX_BRANCH_ENCODE
2924                         (pinfo & INSN_UNCOND_BRANCH_DELAY,
2925                          pinfo & INSN_COND_BRANCH_LIKELY,
2926                          pinfo & INSN_WRITE_GPR_31,
2927                          0),
2928                         address_expr->X_add_symbol,
2929                         address_expr->X_add_number);
2930       *reloc_type = BFD_RELOC_UNUSED;
2931     }
2932   else if (*reloc_type > BFD_RELOC_UNUSED)
2933     {
2934       /* We need to set up a variant frag.  */
2935       gas_assert (mips_opts.mips16 && address_expr != NULL);
2936       add_relaxed_insn (ip, 4, 0,
2937                         RELAX_MIPS16_ENCODE
2938                         (*reloc_type - BFD_RELOC_UNUSED,
2939                          mips16_small, mips16_ext,
2940                          prev_pinfo & INSN_UNCOND_BRANCH_DELAY,
2941                          history[0].mips16_absolute_jump_p),
2942                         make_expr_symbol (address_expr), 0);
2943     }
2944   else if (mips_opts.mips16
2945            && ! ip->use_extend
2946            && *reloc_type != BFD_RELOC_MIPS16_JMP)
2947     {
2948       if ((pinfo & INSN_UNCOND_BRANCH_DELAY) == 0)
2949         /* Make sure there is enough room to swap this instruction with
2950            a following jump instruction.  */
2951         frag_grow (6);
2952       add_fixed_insn (ip);
2953     }
2954   else
2955     {
2956       if (mips_opts.mips16
2957           && mips_opts.noreorder
2958           && (prev_pinfo & INSN_UNCOND_BRANCH_DELAY) != 0)
2959         as_warn (_("extended instruction in delay slot"));
2960
2961       if (mips_relax.sequence)
2962         {
2963           /* If we've reached the end of this frag, turn it into a variant
2964              frag and record the information for the instructions we've
2965              written so far.  */
2966           if (frag_room () < 4)
2967             relax_close_frag ();
2968           mips_relax.sizes[mips_relax.sequence - 1] += 4;
2969         }
2970
2971       if (mips_relax.sequence != 2)
2972         mips_macro_warning.sizes[0] += 4;
2973       if (mips_relax.sequence != 1)
2974         mips_macro_warning.sizes[1] += 4;
2975
2976       if (mips_opts.mips16)
2977         {
2978           ip->fixed_p = 1;
2979           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
2980         }
2981       add_fixed_insn (ip);
2982     }
2983
2984   if (address_expr != NULL && *reloc_type <= BFD_RELOC_UNUSED)
2985     {
2986       if (address_expr->X_op == O_constant)
2987         {
2988           unsigned int tmp;
2989
2990           switch (*reloc_type)
2991             {
2992             case BFD_RELOC_32:
2993               ip->insn_opcode |= address_expr->X_add_number;
2994               break;
2995
2996             case BFD_RELOC_MIPS_HIGHEST:
2997               tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
2998               ip->insn_opcode |= tmp & 0xffff;
2999               break;
3000
3001             case BFD_RELOC_MIPS_HIGHER:
3002               tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
3003               ip->insn_opcode |= tmp & 0xffff;
3004               break;
3005
3006             case BFD_RELOC_HI16_S:
3007               tmp = (address_expr->X_add_number + 0x8000) >> 16;
3008               ip->insn_opcode |= tmp & 0xffff;
3009               break;
3010
3011             case BFD_RELOC_HI16:
3012               ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
3013               break;
3014
3015             case BFD_RELOC_UNUSED:
3016             case BFD_RELOC_LO16:
3017             case BFD_RELOC_MIPS_GOT_DISP:
3018               ip->insn_opcode |= address_expr->X_add_number & 0xffff;
3019               break;
3020
3021             case BFD_RELOC_MIPS_JMP:
3022               if ((address_expr->X_add_number & 3) != 0)
3023                 as_bad (_("jump to misaligned address (0x%lx)"),
3024                         (unsigned long) address_expr->X_add_number);
3025               ip->insn_opcode |= (address_expr->X_add_number >> 2) & 0x3ffffff;
3026               break;
3027
3028             case BFD_RELOC_MIPS16_JMP:
3029               if ((address_expr->X_add_number & 3) != 0)
3030                 as_bad (_("jump to misaligned address (0x%lx)"),
3031                         (unsigned long) address_expr->X_add_number);
3032               ip->insn_opcode |=
3033                 (((address_expr->X_add_number & 0x7c0000) << 3)
3034                  | ((address_expr->X_add_number & 0xf800000) >> 7)
3035                  | ((address_expr->X_add_number & 0x3fffc) >> 2));
3036               break;
3037
3038             case BFD_RELOC_16_PCREL_S2:
3039               if ((address_expr->X_add_number & 3) != 0)
3040                 as_bad (_("branch to misaligned address (0x%lx)"),
3041                         (unsigned long) address_expr->X_add_number);
3042               if (mips_relax_branch)
3043                 goto need_reloc;
3044               if ((address_expr->X_add_number + 0x20000) & ~0x3ffff)
3045                 as_bad (_("branch address range overflow (0x%lx)"),
3046                         (unsigned long) address_expr->X_add_number);
3047               ip->insn_opcode |= (address_expr->X_add_number >> 2) & 0xffff;
3048               break;
3049
3050             default:
3051               internalError ();
3052             }
3053         }
3054       else if (*reloc_type < BFD_RELOC_UNUSED)
3055         need_reloc:
3056         {
3057           reloc_howto_type *howto;
3058           int i;
3059
3060           /* In a compound relocation, it is the final (outermost)
3061              operator that determines the relocated field.  */
3062           for (i = 1; i < 3; i++)
3063             if (reloc_type[i] == BFD_RELOC_UNUSED)
3064               break;
3065
3066           howto = bfd_reloc_type_lookup (stdoutput, reloc_type[i - 1]);
3067           if (howto == NULL)
3068             {
3069               /* To reproduce this failure try assembling gas/testsuites/
3070                  gas/mips/mips16-intermix.s with a mips-ecoff targeted
3071                  assembler.  */
3072               as_bad (_("Unsupported MIPS relocation number %d"), reloc_type[i - 1]);
3073               howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16);
3074             }
3075           
3076           ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
3077                                      bfd_get_reloc_size (howto),
3078                                      address_expr,
3079                                      reloc_type[0] == BFD_RELOC_16_PCREL_S2,
3080                                      reloc_type[0]);
3081
3082           /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
3083           if (reloc_type[0] == BFD_RELOC_MIPS16_JMP
3084               && ip->fixp[0]->fx_addsy)
3085             *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
3086
3087           /* These relocations can have an addend that won't fit in
3088              4 octets for 64bit assembly.  */
3089           if (HAVE_64BIT_GPRS
3090               && ! howto->partial_inplace
3091               && (reloc_type[0] == BFD_RELOC_16
3092                   || reloc_type[0] == BFD_RELOC_32
3093                   || reloc_type[0] == BFD_RELOC_MIPS_JMP
3094                   || reloc_type[0] == BFD_RELOC_GPREL16
3095                   || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
3096                   || reloc_type[0] == BFD_RELOC_GPREL32
3097                   || reloc_type[0] == BFD_RELOC_64
3098                   || reloc_type[0] == BFD_RELOC_CTOR
3099                   || reloc_type[0] == BFD_RELOC_MIPS_SUB
3100                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
3101                   || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
3102                   || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
3103                   || reloc_type[0] == BFD_RELOC_MIPS_REL16
3104                   || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
3105                   || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
3106                   || hi16_reloc_p (reloc_type[0])
3107                   || lo16_reloc_p (reloc_type[0])))
3108             ip->fixp[0]->fx_no_overflow = 1;
3109
3110           if (mips_relax.sequence)
3111             {
3112               if (mips_relax.first_fixup == 0)
3113                 mips_relax.first_fixup = ip->fixp[0];
3114             }
3115           else if (reloc_needs_lo_p (*reloc_type))
3116             {
3117               struct mips_hi_fixup *hi_fixup;
3118
3119               /* Reuse the last entry if it already has a matching %lo.  */
3120               hi_fixup = mips_hi_fixup_list;
3121               if (hi_fixup == 0
3122                   || !fixup_has_matching_lo_p (hi_fixup->fixp))
3123                 {
3124                   hi_fixup = ((struct mips_hi_fixup *)
3125                               xmalloc (sizeof (struct mips_hi_fixup)));
3126                   hi_fixup->next = mips_hi_fixup_list;
3127                   mips_hi_fixup_list = hi_fixup;
3128                 }
3129               hi_fixup->fixp = ip->fixp[0];
3130               hi_fixup->seg = now_seg;
3131             }
3132
3133           /* Add fixups for the second and third relocations, if given.
3134              Note that the ABI allows the second relocation to be
3135              against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
3136              moment we only use RSS_UNDEF, but we could add support
3137              for the others if it ever becomes necessary.  */
3138           for (i = 1; i < 3; i++)
3139             if (reloc_type[i] != BFD_RELOC_UNUSED)
3140               {
3141                 ip->fixp[i] = fix_new (ip->frag, ip->where,
3142                                        ip->fixp[0]->fx_size, NULL, 0,
3143                                        FALSE, reloc_type[i]);
3144
3145                 /* Use fx_tcbit to mark compound relocs.  */
3146                 ip->fixp[0]->fx_tcbit = 1;
3147                 ip->fixp[i]->fx_tcbit = 1;
3148               }
3149         }
3150     }
3151   install_insn (ip);
3152
3153   /* Update the register mask information.  */
3154   if (! mips_opts.mips16)
3155     {
3156       if (pinfo & INSN_WRITE_GPR_D)
3157         mips_gprmask |= 1 << EXTRACT_OPERAND (RD, *ip);
3158       if ((pinfo & (INSN_WRITE_GPR_T | INSN_READ_GPR_T)) != 0)
3159         mips_gprmask |= 1 << EXTRACT_OPERAND (RT, *ip);
3160       if (pinfo & INSN_READ_GPR_S)
3161         mips_gprmask |= 1 << EXTRACT_OPERAND (RS, *ip);
3162       if (pinfo & INSN_WRITE_GPR_31)
3163         mips_gprmask |= 1 << RA;
3164       if (pinfo & INSN_WRITE_FPR_D)
3165         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FD, *ip);
3166       if ((pinfo & (INSN_WRITE_FPR_S | INSN_READ_FPR_S)) != 0)
3167         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FS, *ip);
3168       if ((pinfo & (INSN_WRITE_FPR_T | INSN_READ_FPR_T)) != 0)
3169         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FT, *ip);
3170       if ((pinfo & INSN_READ_FPR_R) != 0)
3171         mips_cprmask[1] |= 1 << EXTRACT_OPERAND (FR, *ip);
3172       if (pinfo & INSN_COP)
3173         {
3174           /* We don't keep enough information to sort these cases out.
3175              The itbl support does keep this information however, although
3176              we currently don't support itbl fprmats as part of the cop
3177              instruction.  May want to add this support in the future.  */
3178         }
3179       /* Never set the bit for $0, which is always zero.  */
3180       mips_gprmask &= ~1 << 0;
3181     }
3182   else
3183     {
3184       if (pinfo & (MIPS16_INSN_WRITE_X | MIPS16_INSN_READ_X))
3185         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RX, *ip);
3186       if (pinfo & (MIPS16_INSN_WRITE_Y | MIPS16_INSN_READ_Y))
3187         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RY, *ip);
3188       if (pinfo & MIPS16_INSN_WRITE_Z)
3189         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (RZ, *ip);
3190       if (pinfo & (MIPS16_INSN_WRITE_T | MIPS16_INSN_READ_T))
3191         mips_gprmask |= 1 << TREG;
3192       if (pinfo & (MIPS16_INSN_WRITE_SP | MIPS16_INSN_READ_SP))
3193         mips_gprmask |= 1 << SP;
3194       if (pinfo & (MIPS16_INSN_WRITE_31 | MIPS16_INSN_READ_31))
3195         mips_gprmask |= 1 << RA;
3196       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3197         mips_gprmask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3198       if (pinfo & MIPS16_INSN_READ_Z)
3199         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip);
3200       if (pinfo & MIPS16_INSN_READ_GPR_X)
3201         mips_gprmask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3202     }
3203
3204   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
3205     {
3206       /* Filling the branch delay slot is more complex.  We try to
3207          switch the branch with the previous instruction, which we can
3208          do if the previous instruction does not set up a condition
3209          that the branch tests and if the branch is not itself the
3210          target of any branch.  */
3211       if ((pinfo & INSN_UNCOND_BRANCH_DELAY)
3212           || (pinfo & INSN_COND_BRANCH_DELAY))
3213         {
3214           if (mips_optimize < 2
3215               /* If we have seen .set volatile or .set nomove, don't
3216                  optimize.  */
3217               || mips_opts.nomove != 0
3218               /* We can't swap if the previous instruction's position
3219                  is fixed.  */
3220               || history[0].fixed_p
3221               /* If the previous previous insn was in a .set
3222                  noreorder, we can't swap.  Actually, the MIPS
3223                  assembler will swap in this situation.  However, gcc
3224                  configured -with-gnu-as will generate code like
3225                    .set noreorder
3226                    lw   $4,XXX
3227                    .set reorder
3228                    INSN
3229                    bne  $4,$0,foo
3230                  in which we can not swap the bne and INSN.  If gcc is
3231                  not configured -with-gnu-as, it does not output the
3232                  .set pseudo-ops.  */
3233               || history[1].noreorder_p
3234               /* If the branch is itself the target of a branch, we
3235                  can not swap.  We cheat on this; all we check for is
3236                  whether there is a label on this instruction.  If
3237                  there are any branches to anything other than a
3238                  label, users must use .set noreorder.  */
3239               || si->label_list != NULL
3240               /* If the previous instruction is in a variant frag
3241                  other than this branch's one, we cannot do the swap.
3242                  This does not apply to the mips16, which uses variant
3243                  frags for different purposes.  */
3244               || (! mips_opts.mips16
3245                   && prev_insn_frag_type == rs_machine_dependent)
3246               /* Check for conflicts between the branch and the instructions
3247                  before the candidate delay slot.  */
3248               || nops_for_insn (history + 1, ip) > 0
3249               /* Check for conflicts between the swapped sequence and the
3250                  target of the branch.  */
3251               || nops_for_sequence (2, history + 1, ip, history) > 0
3252               /* We do not swap with a trap instruction, since it
3253                  complicates trap handlers to have the trap
3254                  instruction be in a delay slot.  */
3255               || (prev_pinfo & INSN_TRAP)
3256               /* If the branch reads a register that the previous
3257                  instruction sets, we can not swap.  */
3258               || (! mips_opts.mips16
3259                   && (prev_pinfo & INSN_WRITE_GPR_T)
3260                   && insn_uses_reg (ip, EXTRACT_OPERAND (RT, history[0]),
3261                                     MIPS_GR_REG))
3262               || (! mips_opts.mips16
3263                   && (prev_pinfo & INSN_WRITE_GPR_D)
3264                   && insn_uses_reg (ip, EXTRACT_OPERAND (RD, history[0]),
3265                                     MIPS_GR_REG))
3266               || (mips_opts.mips16
3267                   && (((prev_pinfo & MIPS16_INSN_WRITE_X)
3268                        && (insn_uses_reg
3269                            (ip, MIPS16_EXTRACT_OPERAND (RX, history[0]),
3270                             MIPS16_REG)))
3271                       || ((prev_pinfo & MIPS16_INSN_WRITE_Y)
3272                           && (insn_uses_reg
3273                               (ip, MIPS16_EXTRACT_OPERAND (RY, history[0]),
3274                                MIPS16_REG)))
3275                       || ((prev_pinfo & MIPS16_INSN_WRITE_Z)
3276                           && (insn_uses_reg
3277                               (ip, MIPS16_EXTRACT_OPERAND (RZ, history[0]),
3278                                MIPS16_REG)))
3279                       || ((prev_pinfo & MIPS16_INSN_WRITE_T)
3280                           && insn_uses_reg (ip, TREG, MIPS_GR_REG))
3281                       || ((prev_pinfo & MIPS16_INSN_WRITE_31)
3282                           && insn_uses_reg (ip, RA, MIPS_GR_REG))
3283                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
3284                           && insn_uses_reg (ip,
3285                                             MIPS16OP_EXTRACT_REG32R
3286                                               (history[0].insn_opcode),
3287                                             MIPS_GR_REG))))
3288               /* If the branch writes a register that the previous
3289                  instruction sets, we can not swap (we know that
3290                  branches write only to RD or to $31).  */
3291               || (! mips_opts.mips16
3292                   && (prev_pinfo & INSN_WRITE_GPR_T)
3293                   && (((pinfo & INSN_WRITE_GPR_D)
3294                        && (EXTRACT_OPERAND (RT, history[0])
3295                            == EXTRACT_OPERAND (RD, *ip)))
3296                       || ((pinfo & INSN_WRITE_GPR_31)
3297                           && EXTRACT_OPERAND (RT, history[0]) == RA)))
3298               || (! mips_opts.mips16
3299                   && (prev_pinfo & INSN_WRITE_GPR_D)
3300                   && (((pinfo & INSN_WRITE_GPR_D)
3301                        && (EXTRACT_OPERAND (RD, history[0])
3302                            == EXTRACT_OPERAND (RD, *ip)))
3303                       || ((pinfo & INSN_WRITE_GPR_31)
3304                           && EXTRACT_OPERAND (RD, history[0]) == RA)))
3305               || (mips_opts.mips16
3306                   && (pinfo & MIPS16_INSN_WRITE_31)
3307                   && ((prev_pinfo & MIPS16_INSN_WRITE_31)
3308                       || ((prev_pinfo & MIPS16_INSN_WRITE_GPR_Y)
3309                           && (MIPS16OP_EXTRACT_REG32R (history[0].insn_opcode)
3310                               == RA))))
3311               /* If the branch writes a register that the previous
3312                  instruction reads, we can not swap (we know that
3313                  branches only write to RD or to $31).  */
3314               || (! mips_opts.mips16
3315                   && (pinfo & INSN_WRITE_GPR_D)
3316                   && insn_uses_reg (&history[0],
3317                                     EXTRACT_OPERAND (RD, *ip),
3318                                     MIPS_GR_REG))
3319               || (! mips_opts.mips16
3320                   && (pinfo & INSN_WRITE_GPR_31)
3321                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
3322               || (mips_opts.mips16
3323                   && (pinfo & MIPS16_INSN_WRITE_31)
3324                   && insn_uses_reg (&history[0], RA, MIPS_GR_REG))
3325               /* If one instruction sets a condition code and the
3326                  other one uses a condition code, we can not swap.  */
3327               || ((pinfo & INSN_READ_COND_CODE)
3328                   && (prev_pinfo & INSN_WRITE_COND_CODE))
3329               || ((pinfo & INSN_WRITE_COND_CODE)
3330                   && (prev_pinfo & INSN_READ_COND_CODE))
3331               /* If the previous instruction uses the PC, we can not
3332                  swap.  */
3333               || (mips_opts.mips16
3334                   && (prev_pinfo & MIPS16_INSN_READ_PC))
3335               /* If the previous instruction had a fixup in mips16
3336                  mode, we can not swap.  This normally means that the
3337                  previous instruction was a 4 byte branch anyhow.  */
3338               || (mips_opts.mips16 && history[0].fixp[0])
3339               /* If the previous instruction is a sync, sync.l, or
3340                  sync.p, we can not swap.  */
3341               || (prev_pinfo & INSN_SYNC)
3342               /* If the previous instruction is an ERET or
3343                  DERET, avoid the swap.  */
3344               || (history[0].insn_opcode == INSN_ERET)
3345               || (history[0].insn_opcode == INSN_DERET))
3346             {
3347               if (mips_opts.mips16
3348                   && (pinfo & INSN_UNCOND_BRANCH_DELAY)
3349                   && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31))
3350                   && ISA_SUPPORTS_MIPS16E)
3351                 {
3352                   /* Convert MIPS16 jr/jalr into a "compact" jump.  */
3353                   ip->insn_opcode |= 0x0080;
3354                   install_insn (ip);
3355                   insert_into_history (0, 1, ip);
3356                 } 
3357               else
3358                 {
3359                   /* We could do even better for unconditional branches to
3360                      portions of this object file; we could pick up the
3361                      instruction at the destination, put it in the delay
3362                      slot, and bump the destination address.  */
3363                   insert_into_history (0, 1, ip);
3364                   emit_nop ();
3365                 }
3366                 
3367               if (mips_relax.sequence)
3368                 mips_relax.sizes[mips_relax.sequence - 1] += 4;
3369             }
3370           else
3371             {
3372               /* It looks like we can actually do the swap.  */
3373               struct mips_cl_insn delay = history[0];
3374               if (mips_opts.mips16)
3375                 {
3376                   know (delay.frag == ip->frag);
3377                   move_insn (ip, delay.frag, delay.where);
3378                   move_insn (&delay, ip->frag, ip->where + insn_length (ip));
3379                 }
3380               else if (relaxed_branch)
3381                 {
3382                   /* Add the delay slot instruction to the end of the
3383                      current frag and shrink the fixed part of the
3384                      original frag.  If the branch occupies the tail of
3385                      the latter, move it backwards to cover the gap.  */
3386                   delay.frag->fr_fix -= 4;
3387                   if (delay.frag == ip->frag)
3388                     move_insn (ip, ip->frag, ip->where - 4);
3389                   add_fixed_insn (&delay);
3390                 }
3391               else
3392                 {
3393                   move_insn (&delay, ip->frag, ip->where);
3394                   move_insn (ip, history[0].frag, history[0].where);
3395                 }
3396               history[0] = *ip;
3397               delay.fixed_p = 1;
3398               insert_into_history (0, 1, &delay);
3399             }
3400
3401           /* If that was an unconditional branch, forget the previous
3402              insn information.  */
3403           if (pinfo & INSN_UNCOND_BRANCH_DELAY)
3404             {
3405               mips_no_prev_insn ();
3406             }
3407         }
3408       else if (pinfo & INSN_COND_BRANCH_LIKELY)
3409         {
3410           /* We don't yet optimize a branch likely.  What we should do
3411              is look at the target, copy the instruction found there
3412              into the delay slot, and increment the branch to jump to
3413              the next instruction.  */
3414           insert_into_history (0, 1, ip);
3415           emit_nop ();
3416         }
3417       else
3418         insert_into_history (0, 1, ip);
3419     }
3420   else
3421     insert_into_history (0, 1, ip);
3422
3423   /* We just output an insn, so the next one doesn't have a label.  */
3424   mips_clear_insn_labels ();
3425 }
3426
3427 /* Forget that there was any previous instruction or label.  */
3428
3429 static void
3430 mips_no_prev_insn (void)
3431 {
3432   prev_nop_frag = NULL;
3433   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
3434   mips_clear_insn_labels ();
3435 }
3436
3437 /* This function must be called before we emit something other than
3438    instructions.  It is like mips_no_prev_insn except that it inserts
3439    any NOPS that might be needed by previous instructions.  */
3440
3441 void
3442 mips_emit_delays (void)
3443 {
3444   if (! mips_opts.noreorder)
3445     {
3446       int nops = nops_for_insn (history, NULL);
3447       if (nops > 0)
3448         {
3449           while (nops-- > 0)
3450             add_fixed_insn (NOP_INSN);
3451           mips_move_labels ();
3452         }
3453     }
3454   mips_no_prev_insn ();
3455 }
3456
3457 /* Start a (possibly nested) noreorder block.  */
3458
3459 static void
3460 start_noreorder (void)
3461 {
3462   if (mips_opts.noreorder == 0)
3463     {
3464       unsigned int i;
3465       int nops;
3466
3467       /* None of the instructions before the .set noreorder can be moved.  */
3468       for (i = 0; i < ARRAY_SIZE (history); i++)
3469         history[i].fixed_p = 1;
3470
3471       /* Insert any nops that might be needed between the .set noreorder
3472          block and the previous instructions.  We will later remove any
3473          nops that turn out not to be needed.  */
3474       nops = nops_for_insn (history, NULL);
3475       if (nops > 0)
3476         {
3477           if (mips_optimize != 0)
3478             {
3479               /* Record the frag which holds the nop instructions, so
3480                  that we can remove them if we don't need them.  */
3481               frag_grow (mips_opts.mips16 ? nops * 2 : nops * 4);
3482               prev_nop_frag = frag_now;
3483               prev_nop_frag_holds = nops;
3484               prev_nop_frag_required = 0;
3485               prev_nop_frag_since = 0;
3486             }
3487
3488           for (; nops > 0; --nops)
3489             add_fixed_insn (NOP_INSN);
3490
3491           /* Move on to a new frag, so that it is safe to simply
3492              decrease the size of prev_nop_frag.  */
3493           frag_wane (frag_now);
3494           frag_new (0);
3495           mips_move_labels ();
3496         }
3497       mips16_mark_labels ();
3498       mips_clear_insn_labels ();
3499     }
3500   mips_opts.noreorder++;
3501   mips_any_noreorder = 1;
3502 }
3503
3504 /* End a nested noreorder block.  */
3505
3506 static void
3507 end_noreorder (void)
3508 {
3509
3510   mips_opts.noreorder--;
3511   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
3512     {
3513       /* Commit to inserting prev_nop_frag_required nops and go back to
3514          handling nop insertion the .set reorder way.  */
3515       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
3516                                 * (mips_opts.mips16 ? 2 : 4));
3517       insert_into_history (prev_nop_frag_since,
3518                            prev_nop_frag_required, NOP_INSN);
3519       prev_nop_frag = NULL;
3520     }
3521 }
3522
3523 /* Set up global variables for the start of a new macro.  */
3524
3525 static void
3526 macro_start (void)
3527 {
3528   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
3529   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
3530                                      && (history[0].insn_mo->pinfo
3531                                          & (INSN_UNCOND_BRANCH_DELAY
3532                                             | INSN_COND_BRANCH_DELAY
3533                                             | INSN_COND_BRANCH_LIKELY)) != 0);
3534 }
3535
3536 /* Given that a macro is longer than 4 bytes, return the appropriate warning
3537    for it.  Return null if no warning is needed.  SUBTYPE is a bitmask of
3538    RELAX_DELAY_SLOT and RELAX_NOMACRO.  */
3539
3540 static const char *
3541 macro_warning (relax_substateT subtype)
3542 {
3543   if (subtype & RELAX_DELAY_SLOT)
3544     return _("Macro instruction expanded into multiple instructions"
3545              " in a branch delay slot");
3546   else if (subtype & RELAX_NOMACRO)
3547     return _("Macro instruction expanded into multiple instructions");
3548   else
3549     return 0;
3550 }
3551
3552 /* Finish up a macro.  Emit warnings as appropriate.  */
3553
3554 static void
3555 macro_end (void)
3556 {
3557   if (mips_macro_warning.sizes[0] > 4 || mips_macro_warning.sizes[1] > 4)
3558     {
3559       relax_substateT subtype;
3560
3561       /* Set up the relaxation warning flags.  */
3562       subtype = 0;
3563       if (mips_macro_warning.sizes[1] > mips_macro_warning.sizes[0])
3564         subtype |= RELAX_SECOND_LONGER;
3565       if (mips_opts.warn_about_macros)
3566         subtype |= RELAX_NOMACRO;
3567       if (mips_macro_warning.delay_slot_p)
3568         subtype |= RELAX_DELAY_SLOT;
3569
3570       if (mips_macro_warning.sizes[0] > 4 && mips_macro_warning.sizes[1] > 4)
3571         {
3572           /* Either the macro has a single implementation or both
3573              implementations are longer than 4 bytes.  Emit the
3574              warning now.  */
3575           const char *msg = macro_warning (subtype);
3576           if (msg != 0)
3577             as_warn ("%s", msg);
3578         }
3579       else
3580         {
3581           /* One implementation might need a warning but the other
3582              definitely doesn't.  */
3583           mips_macro_warning.first_frag->fr_subtype |= subtype;
3584         }
3585     }
3586 }
3587
3588 /* Read a macro's relocation codes from *ARGS and store them in *R.
3589    The first argument in *ARGS will be either the code for a single
3590    relocation or -1 followed by the three codes that make up a
3591    composite relocation.  */
3592
3593 static void
3594 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
3595 {
3596   int i, next;
3597
3598   next = va_arg (*args, int);
3599   if (next >= 0)
3600     r[0] = (bfd_reloc_code_real_type) next;
3601   else
3602     for (i = 0; i < 3; i++)
3603       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
3604 }
3605
3606 /* Build an instruction created by a macro expansion.  This is passed
3607    a pointer to the count of instructions created so far, an
3608    expression, the name of the instruction to build, an operand format
3609    string, and corresponding arguments.  */
3610
3611 static void
3612 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
3613 {
3614   const struct mips_opcode *mo;
3615   struct mips_cl_insn insn;
3616   bfd_reloc_code_real_type r[3];
3617   va_list args;
3618
3619   va_start (args, fmt);
3620
3621   if (mips_opts.mips16)
3622     {
3623       mips16_macro_build (ep, name, fmt, &args);
3624       va_end (args);
3625       return;
3626     }
3627
3628   r[0] = BFD_RELOC_UNUSED;
3629   r[1] = BFD_RELOC_UNUSED;
3630   r[2] = BFD_RELOC_UNUSED;
3631   mo = (struct mips_opcode *) hash_find (op_hash, name);
3632   gas_assert (mo);
3633   gas_assert (strcmp (name, mo->name) == 0);
3634
3635   while (1)
3636     {
3637       /* Search until we get a match for NAME.  It is assumed here that
3638          macros will never generate MDMX, MIPS-3D, or MT instructions.  */
3639       if (strcmp (fmt, mo->args) == 0
3640           && mo->pinfo != INSN_MACRO
3641           && is_opcode_valid (mo))
3642         break;
3643
3644       ++mo;
3645       gas_assert (mo->name);
3646       gas_assert (strcmp (name, mo->name) == 0);
3647     }
3648
3649   create_insn (&insn, mo);
3650   for (;;)
3651     {
3652       switch (*fmt++)
3653         {
3654         case '\0':
3655           break;
3656
3657         case ',':
3658         case '(':
3659         case ')':
3660           continue;
3661
3662         case '+':
3663           switch (*fmt++)
3664             {
3665             case 'A':
3666             case 'E':
3667               INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3668               continue;
3669
3670             case 'B':
3671             case 'F':
3672               /* Note that in the macro case, these arguments are already
3673                  in MSB form.  (When handling the instruction in the
3674                  non-macro case, these arguments are sizes from which
3675                  MSB values must be calculated.)  */
3676               INSERT_OPERAND (INSMSB, insn, va_arg (args, int));
3677               continue;
3678
3679             case 'C':
3680             case 'G':
3681             case 'H':
3682               /* Note that in the macro case, these arguments are already
3683                  in MSBD form.  (When handling the instruction in the
3684                  non-macro case, these arguments are sizes from which
3685                  MSBD values must be calculated.)  */
3686               INSERT_OPERAND (EXTMSBD, insn, va_arg (args, int));
3687               continue;
3688
3689             case 'Q':
3690               INSERT_OPERAND (SEQI, insn, va_arg (args, int));
3691               continue;
3692
3693             default:
3694               internalError ();
3695             }
3696           continue;
3697
3698         case '2':
3699           INSERT_OPERAND (BP, insn, va_arg (args, int));
3700           continue;
3701
3702         case 't':
3703         case 'w':
3704         case 'E':
3705           INSERT_OPERAND (RT, insn, va_arg (args, int));
3706           continue;
3707
3708         case 'c':
3709           INSERT_OPERAND (CODE, insn, va_arg (args, int));
3710           continue;
3711
3712         case 'T':
3713         case 'W':
3714           INSERT_OPERAND (FT, insn, va_arg (args, int));
3715           continue;
3716
3717         case 'd':
3718         case 'G':
3719         case 'K':
3720           INSERT_OPERAND (RD, insn, va_arg (args, int));
3721           continue;
3722
3723         case 'U':
3724           {
3725             int tmp = va_arg (args, int);
3726
3727             INSERT_OPERAND (RT, insn, tmp);
3728             INSERT_OPERAND (RD, insn, tmp);
3729             continue;
3730           }
3731
3732         case 'V':
3733         case 'S':
3734           INSERT_OPERAND (FS, insn, va_arg (args, int));
3735           continue;
3736
3737         case 'z':
3738           continue;
3739
3740         case '<':
3741           INSERT_OPERAND (SHAMT, insn, va_arg (args, int));
3742           continue;
3743
3744         case 'D':
3745           INSERT_OPERAND (FD, insn, va_arg (args, int));
3746           continue;
3747
3748         case 'B':
3749           INSERT_OPERAND (CODE20, insn, va_arg (args, int));
3750           continue;
3751
3752         case 'J':
3753           INSERT_OPERAND (CODE19, insn, va_arg (args, int));
3754           continue;
3755
3756         case 'q':
3757           INSERT_OPERAND (CODE2, insn, va_arg (args, int));
3758           continue;
3759
3760         case 'b':
3761         case 's':
3762         case 'r':
3763         case 'v':
3764           INSERT_OPERAND (RS, insn, va_arg (args, int));
3765           continue;
3766
3767         case 'i':
3768         case 'j':
3769           macro_read_relocs (&args, r);
3770           gas_assert (*r == BFD_RELOC_GPREL16
3771                       || *r == BFD_RELOC_MIPS_HIGHER
3772                       || *r == BFD_RELOC_HI16_S
3773                       || *r == BFD_RELOC_LO16
3774                       || *r == BFD_RELOC_MIPS_GOT_OFST);
3775           continue;
3776
3777         case 'o':
3778           macro_read_relocs (&args, r);
3779           continue;
3780
3781         case 'u':
3782           macro_read_relocs (&args, r);
3783           gas_assert (ep != NULL
3784                       && (ep->X_op == O_constant
3785                           || (ep->X_op == O_symbol
3786                               && (*r == BFD_RELOC_MIPS_HIGHEST
3787                                   || *r == BFD_RELOC_HI16_S
3788                                   || *r == BFD_RELOC_HI16
3789                                   || *r == BFD_RELOC_GPREL16
3790                                   || *r == BFD_RELOC_MIPS_GOT_HI16
3791                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
3792           continue;
3793
3794         case 'p':
3795           gas_assert (ep != NULL);
3796
3797           /*
3798            * This allows macro() to pass an immediate expression for
3799            * creating short branches without creating a symbol.
3800            *
3801            * We don't allow branch relaxation for these branches, as
3802            * they should only appear in ".set nomacro" anyway.
3803            */
3804           if (ep->X_op == O_constant)
3805             {
3806               if ((ep->X_add_number & 3) != 0)
3807                 as_bad (_("branch to misaligned address (0x%lx)"),
3808                         (unsigned long) ep->X_add_number);
3809               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
3810                 as_bad (_("branch address range overflow (0x%lx)"),
3811                         (unsigned long) ep->X_add_number);
3812               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
3813               ep = NULL;
3814             }
3815           else
3816             *r = BFD_RELOC_16_PCREL_S2;
3817           continue;
3818
3819         case 'a':
3820           gas_assert (ep != NULL);
3821           *r = BFD_RELOC_MIPS_JMP;
3822           continue;
3823
3824         case 'C':
3825           INSERT_OPERAND (COPZ, insn, va_arg (args, unsigned long));
3826           continue;
3827
3828         case 'k':
3829           INSERT_OPERAND (CACHE, insn, va_arg (args, unsigned long));
3830           continue;
3831
3832         default:
3833           internalError ();
3834         }
3835       break;
3836     }
3837   va_end (args);
3838   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3839
3840   append_insn (&insn, ep, r);
3841 }
3842
3843 static void
3844 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
3845                     va_list *args)
3846 {
3847   struct mips_opcode *mo;
3848   struct mips_cl_insn insn;
3849   bfd_reloc_code_real_type r[3]
3850     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3851
3852   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
3853   gas_assert (mo);
3854   gas_assert (strcmp (name, mo->name) == 0);
3855
3856   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
3857     {
3858       ++mo;
3859       gas_assert (mo->name);
3860       gas_assert (strcmp (name, mo->name) == 0);
3861     }
3862
3863   create_insn (&insn, mo);
3864   for (;;)
3865     {
3866       int c;
3867
3868       c = *fmt++;
3869       switch (c)
3870         {
3871         case '\0':
3872           break;
3873
3874         case ',':
3875         case '(':
3876         case ')':
3877           continue;
3878
3879         case 'y':
3880         case 'w':
3881           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
3882           continue;
3883
3884         case 'x':
3885         case 'v':
3886           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
3887           continue;
3888
3889         case 'z':
3890           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
3891           continue;
3892
3893         case 'Z':
3894           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
3895           continue;
3896
3897         case '0':
3898         case 'S':
3899         case 'P':
3900         case 'R':
3901           continue;
3902
3903         case 'X':
3904           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
3905           continue;
3906
3907         case 'Y':
3908           {
3909             int regno;
3910
3911             regno = va_arg (*args, int);
3912             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
3913             MIPS16_INSERT_OPERAND (REG32R, insn, regno);
3914           }
3915           continue;
3916
3917         case '<':
3918         case '>':
3919         case '4':
3920         case '5':
3921         case 'H':
3922         case 'W':
3923         case 'D':
3924         case 'j':
3925         case '8':
3926         case 'V':
3927         case 'C':
3928         case 'U':
3929         case 'k':
3930         case 'K':
3931         case 'p':
3932         case 'q':
3933           {
3934             gas_assert (ep != NULL);
3935
3936             if (ep->X_op != O_constant)
3937               *r = (int) BFD_RELOC_UNUSED + c;
3938             else
3939               {
3940                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
3941                               FALSE, &insn.insn_opcode, &insn.use_extend,
3942                               &insn.extend);
3943                 ep = NULL;
3944                 *r = BFD_RELOC_UNUSED;
3945               }
3946           }
3947           continue;
3948
3949         case '6':
3950           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
3951           continue;
3952         }
3953
3954       break;
3955     }
3956
3957   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
3958
3959   append_insn (&insn, ep, r);
3960 }
3961
3962 /*
3963  * Sign-extend 32-bit mode constants that have bit 31 set and all
3964  * higher bits unset.
3965  */
3966 static void
3967 normalize_constant_expr (expressionS *ex)
3968 {
3969   if (ex->X_op == O_constant
3970       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3971     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3972                         - 0x80000000);
3973 }
3974
3975 /*
3976  * Sign-extend 32-bit mode address offsets that have bit 31 set and
3977  * all higher bits unset.
3978  */
3979 static void
3980 normalize_address_expr (expressionS *ex)
3981 {
3982   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
3983         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
3984       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
3985     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
3986                         - 0x80000000);
3987 }
3988
3989 /*
3990  * Generate a "jalr" instruction with a relocation hint to the called
3991  * function.  This occurs in NewABI PIC code.
3992  */
3993 static void
3994 macro_build_jalr (expressionS *ep)
3995 {
3996   char *f = NULL;
3997
3998   if (MIPS_JALR_HINT_P (ep))
3999     {
4000       frag_grow (8);
4001       f = frag_more (0);
4002     }
4003   macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
4004   if (MIPS_JALR_HINT_P (ep))
4005     fix_new_exp (frag_now, f - frag_now->fr_literal,
4006                  4, ep, FALSE, BFD_RELOC_MIPS_JALR);
4007 }
4008
4009 /*
4010  * Generate a "lui" instruction.
4011  */
4012 static void
4013 macro_build_lui (expressionS *ep, int regnum)
4014 {
4015   expressionS high_expr;
4016   const struct mips_opcode *mo;
4017   struct mips_cl_insn insn;
4018   bfd_reloc_code_real_type r[3]
4019     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4020   const char *name = "lui";
4021   const char *fmt = "t,u";
4022
4023   gas_assert (! mips_opts.mips16);
4024
4025   high_expr = *ep;
4026
4027   if (high_expr.X_op == O_constant)
4028     {
4029       /* We can compute the instruction now without a relocation entry.  */
4030       high_expr.X_add_number = ((high_expr.X_add_number + 0x8000)
4031                                 >> 16) & 0xffff;
4032       *r = BFD_RELOC_UNUSED;
4033     }
4034   else
4035     {
4036       gas_assert (ep->X_op == O_symbol);
4037       /* _gp_disp is a special case, used from s_cpload.
4038          __gnu_local_gp is used if mips_no_shared.  */
4039       gas_assert (mips_pic == NO_PIC
4040               || (! HAVE_NEWABI
4041                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
4042               || (! mips_in_shared
4043                   && strcmp (S_GET_NAME (ep->X_add_symbol),
4044                              "__gnu_local_gp") == 0));
4045       *r = BFD_RELOC_HI16_S;
4046     }
4047
4048   mo = hash_find (op_hash, name);
4049   gas_assert (strcmp (name, mo->name) == 0);
4050   gas_assert (strcmp (fmt, mo->args) == 0);
4051   create_insn (&insn, mo);
4052
4053   insn.insn_opcode = insn.insn_mo->match;
4054   INSERT_OPERAND (RT, insn, regnum);
4055   if (*r == BFD_RELOC_UNUSED)
4056     {
4057       insn.insn_opcode |= high_expr.X_add_number;
4058       append_insn (&insn, NULL, r);
4059     }
4060   else
4061     append_insn (&insn, &high_expr, r);
4062 }
4063
4064 /* Generate a sequence of instructions to do a load or store from a constant
4065    offset off of a base register (breg) into/from a target register (treg),
4066    using AT if necessary.  */
4067 static void
4068 macro_build_ldst_constoffset (expressionS *ep, const char *op,
4069                               int treg, int breg, int dbl)
4070 {
4071   gas_assert (ep->X_op == O_constant);
4072
4073   /* Sign-extending 32-bit constants makes their handling easier.  */
4074   if (!dbl)
4075     normalize_constant_expr (ep);
4076
4077   /* Right now, this routine can only handle signed 32-bit constants.  */
4078   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
4079     as_warn (_("operand overflow"));
4080
4081   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
4082     {
4083       /* Signed 16-bit offset will fit in the op.  Easy!  */
4084       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
4085     }
4086   else
4087     {
4088       /* 32-bit offset, need multiple instructions and AT, like:
4089            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
4090            addu     $tempreg,$tempreg,$breg
4091            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
4092          to handle the complete offset.  */
4093       macro_build_lui (ep, AT);
4094       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
4095       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
4096
4097       if (!mips_opts.at)
4098         as_bad (_("Macro used $at after \".set noat\""));
4099     }
4100 }
4101
4102 /*                      set_at()
4103  * Generates code to set the $at register to true (one)
4104  * if reg is less than the immediate expression.
4105  */
4106 static void
4107 set_at (int reg, int unsignedp)
4108 {
4109   if (imm_expr.X_op == O_constant
4110       && imm_expr.X_add_number >= -0x8000
4111       && imm_expr.X_add_number < 0x8000)
4112     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
4113                  AT, reg, BFD_RELOC_LO16);
4114   else
4115     {
4116       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4117       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
4118     }
4119 }
4120
4121 /* Warn if an expression is not a constant.  */
4122
4123 static void
4124 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
4125 {
4126   if (ex->X_op == O_big)
4127     as_bad (_("unsupported large constant"));
4128   else if (ex->X_op != O_constant)
4129     as_bad (_("Instruction %s requires absolute expression"),
4130             ip->insn_mo->name);
4131
4132   if (HAVE_32BIT_GPRS)
4133     normalize_constant_expr (ex);
4134 }
4135
4136 /* Count the leading zeroes by performing a binary chop. This is a
4137    bulky bit of source, but performance is a LOT better for the
4138    majority of values than a simple loop to count the bits:
4139        for (lcnt = 0; (lcnt < 32); lcnt++)
4140          if ((v) & (1 << (31 - lcnt)))
4141            break;
4142   However it is not code size friendly, and the gain will drop a bit
4143   on certain cached systems.
4144 */
4145 #define COUNT_TOP_ZEROES(v)             \
4146   (((v) & ~0xffff) == 0                 \
4147    ? ((v) & ~0xff) == 0                 \
4148      ? ((v) & ~0xf) == 0                \
4149        ? ((v) & ~0x3) == 0              \
4150          ? ((v) & ~0x1) == 0            \
4151            ? !(v)                       \
4152              ? 32                       \
4153              : 31                       \
4154            : 30                         \
4155          : ((v) & ~0x7) == 0            \
4156            ? 29                         \
4157            : 28                         \
4158        : ((v) & ~0x3f) == 0             \
4159          ? ((v) & ~0x1f) == 0           \
4160            ? 27                         \
4161            : 26                         \
4162          : ((v) & ~0x7f) == 0           \
4163            ? 25                         \
4164            : 24                         \
4165      : ((v) & ~0xfff) == 0              \
4166        ? ((v) & ~0x3ff) == 0            \
4167          ? ((v) & ~0x1ff) == 0          \
4168            ? 23                         \
4169            : 22                         \
4170          : ((v) & ~0x7ff) == 0          \
4171            ? 21                         \
4172            : 20                         \
4173        : ((v) & ~0x3fff) == 0           \
4174          ? ((v) & ~0x1fff) == 0         \
4175            ? 19                         \
4176            : 18                         \
4177          : ((v) & ~0x7fff) == 0         \
4178            ? 17                         \
4179            : 16                         \
4180    : ((v) & ~0xffffff) == 0             \
4181      ? ((v) & ~0xfffff) == 0            \
4182        ? ((v) & ~0x3ffff) == 0          \
4183          ? ((v) & ~0x1ffff) == 0        \
4184            ? 15                         \
4185            : 14                         \
4186          : ((v) & ~0x7ffff) == 0        \
4187            ? 13                         \
4188            : 12                         \
4189        : ((v) & ~0x3fffff) == 0         \
4190          ? ((v) & ~0x1fffff) == 0       \
4191            ? 11                         \
4192            : 10                         \
4193          : ((v) & ~0x7fffff) == 0       \
4194            ? 9                          \
4195            : 8                          \
4196      : ((v) & ~0xfffffff) == 0          \
4197        ? ((v) & ~0x3ffffff) == 0        \
4198          ? ((v) & ~0x1ffffff) == 0      \
4199            ? 7                          \
4200            : 6                          \
4201          : ((v) & ~0x7ffffff) == 0      \
4202            ? 5                          \
4203            : 4                          \
4204        : ((v) & ~0x3fffffff) == 0       \
4205          ? ((v) & ~0x1fffffff) == 0     \
4206            ? 3                          \
4207            : 2                          \
4208          : ((v) & ~0x7fffffff) == 0     \
4209            ? 1                          \
4210            : 0)
4211
4212 /*                      load_register()
4213  *  This routine generates the least number of instructions necessary to load
4214  *  an absolute expression value into a register.
4215  */
4216 static void
4217 load_register (int reg, expressionS *ep, int dbl)
4218 {
4219   int freg;
4220   expressionS hi32, lo32;
4221
4222   if (ep->X_op != O_big)
4223     {
4224       gas_assert (ep->X_op == O_constant);
4225
4226       /* Sign-extending 32-bit constants makes their handling easier.  */
4227       if (!dbl)
4228         normalize_constant_expr (ep);
4229
4230       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
4231         {
4232           /* We can handle 16 bit signed values with an addiu to
4233              $zero.  No need to ever use daddiu here, since $zero and
4234              the result are always correct in 32 bit mode.  */
4235           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
4236           return;
4237         }
4238       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
4239         {
4240           /* We can handle 16 bit unsigned values with an ori to
4241              $zero.  */
4242           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
4243           return;
4244         }
4245       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
4246         {
4247           /* 32 bit values require an lui.  */
4248           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_HI16);
4249           if ((ep->X_add_number & 0xffff) != 0)
4250             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
4251           return;
4252         }
4253     }
4254
4255   /* The value is larger than 32 bits.  */
4256
4257   if (!dbl || HAVE_32BIT_GPRS)
4258     {
4259       char value[32];
4260
4261       sprintf_vma (value, ep->X_add_number);
4262       as_bad (_("Number (0x%s) larger than 32 bits"), value);
4263       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
4264       return;
4265     }
4266
4267   if (ep->X_op != O_big)
4268     {
4269       hi32 = *ep;
4270       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
4271       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
4272       hi32.X_add_number &= 0xffffffff;
4273       lo32 = *ep;
4274       lo32.X_add_number &= 0xffffffff;
4275     }
4276   else
4277     {
4278       gas_assert (ep->X_add_number > 2);
4279       if (ep->X_add_number == 3)
4280         generic_bignum[3] = 0;
4281       else if (ep->X_add_number > 4)
4282         as_bad (_("Number larger than 64 bits"));
4283       lo32.X_op = O_constant;
4284       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
4285       hi32.X_op = O_constant;
4286       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
4287     }
4288
4289   if (hi32.X_add_number == 0)
4290     freg = 0;
4291   else
4292     {
4293       int shift, bit;
4294       unsigned long hi, lo;
4295
4296       if (hi32.X_add_number == (offsetT) 0xffffffff)
4297         {
4298           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
4299             {
4300               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
4301               return;
4302             }
4303           if (lo32.X_add_number & 0x80000000)
4304             {
4305               macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
4306               if (lo32.X_add_number & 0xffff)
4307                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
4308               return;
4309             }
4310         }
4311
4312       /* Check for 16bit shifted constant.  We know that hi32 is
4313          non-zero, so start the mask on the first bit of the hi32
4314          value.  */
4315       shift = 17;
4316       do
4317         {
4318           unsigned long himask, lomask;
4319
4320           if (shift < 32)
4321             {
4322               himask = 0xffff >> (32 - shift);
4323               lomask = (0xffff << shift) & 0xffffffff;
4324             }
4325           else
4326             {
4327               himask = 0xffff << (shift - 32);
4328               lomask = 0;
4329             }
4330           if ((hi32.X_add_number & ~(offsetT) himask) == 0
4331               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
4332             {
4333               expressionS tmp;
4334
4335               tmp.X_op = O_constant;
4336               if (shift < 32)
4337                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
4338                                     | (lo32.X_add_number >> shift));
4339               else
4340                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
4341               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
4342               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", "d,w,<",
4343                            reg, reg, (shift >= 32) ? shift - 32 : shift);
4344               return;
4345             }
4346           ++shift;
4347         }
4348       while (shift <= (64 - 16));
4349
4350       /* Find the bit number of the lowest one bit, and store the
4351          shifted value in hi/lo.  */
4352       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
4353       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
4354       if (lo != 0)
4355         {
4356           bit = 0;
4357           while ((lo & 1) == 0)
4358             {
4359               lo >>= 1;
4360               ++bit;
4361             }
4362           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
4363           hi >>= bit;
4364         }
4365       else
4366         {
4367           bit = 32;
4368           while ((hi & 1) == 0)
4369             {
4370               hi >>= 1;
4371               ++bit;
4372             }
4373           lo = hi;
4374           hi = 0;
4375         }
4376
4377       /* Optimize if the shifted value is a (power of 2) - 1.  */
4378       if ((hi == 0 && ((lo + 1) & lo) == 0)
4379           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
4380         {
4381           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
4382           if (shift != 0)
4383             {
4384               expressionS tmp;
4385
4386               /* This instruction will set the register to be all
4387                  ones.  */
4388               tmp.X_op = O_constant;
4389               tmp.X_add_number = (offsetT) -1;
4390               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
4391               if (bit != 0)
4392                 {
4393                   bit += shift;
4394                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", "d,w,<",
4395                                reg, reg, (bit >= 32) ? bit - 32 : bit);
4396                 }
4397               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", "d,w,<",
4398                            reg, reg, (shift >= 32) ? shift - 32 : shift);
4399               return;
4400             }
4401         }
4402
4403       /* Sign extend hi32 before calling load_register, because we can
4404          generally get better code when we load a sign extended value.  */
4405       if ((hi32.X_add_number & 0x80000000) != 0)
4406         hi32.X_add_number |= ~(offsetT) 0xffffffff;
4407       load_register (reg, &hi32, 0);
4408       freg = reg;
4409     }
4410   if ((lo32.X_add_number & 0xffff0000) == 0)
4411     {
4412       if (freg != 0)
4413         {
4414           macro_build (NULL, "dsll32", "d,w,<", reg, freg, 0);
4415           freg = reg;
4416         }
4417     }
4418   else
4419     {
4420       expressionS mid16;
4421
4422       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
4423         {
4424           macro_build (&lo32, "lui", "t,u", reg, BFD_RELOC_HI16);
4425           macro_build (NULL, "dsrl32", "d,w,<", reg, reg, 0);
4426           return;
4427         }
4428
4429       if (freg != 0)
4430         {
4431           macro_build (NULL, "dsll", "d,w,<", reg, freg, 16);
4432           freg = reg;
4433         }
4434       mid16 = lo32;
4435       mid16.X_add_number >>= 16;
4436       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
4437       macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
4438       freg = reg;
4439     }
4440   if ((lo32.X_add_number & 0xffff) != 0)
4441     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
4442 }
4443
4444 static inline void
4445 load_delay_nop (void)
4446 {
4447   if (!gpr_interlocks)
4448     macro_build (NULL, "nop", "");
4449 }
4450
4451 /* Load an address into a register.  */
4452
4453 static void
4454 load_address (int reg, expressionS *ep, int *used_at)
4455 {
4456   if (ep->X_op != O_constant
4457       && ep->X_op != O_symbol)
4458     {
4459       as_bad (_("expression too complex"));
4460       ep->X_op = O_constant;
4461     }
4462
4463   if (ep->X_op == O_constant)
4464     {
4465       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
4466       return;
4467     }
4468
4469   if (mips_pic == NO_PIC)
4470     {
4471       /* If this is a reference to a GP relative symbol, we want
4472            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
4473          Otherwise we want
4474            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
4475            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
4476          If we have an addend, we always use the latter form.
4477
4478          With 64bit address space and a usable $at we want
4479            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
4480            lui          $at,<sym>               (BFD_RELOC_HI16_S)
4481            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
4482            daddiu       $at,<sym>               (BFD_RELOC_LO16)
4483            dsll32       $reg,0
4484            daddu        $reg,$reg,$at
4485
4486          If $at is already in use, we use a path which is suboptimal
4487          on superscalar processors.
4488            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
4489            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
4490            dsll         $reg,16
4491            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
4492            dsll         $reg,16
4493            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
4494
4495          For GP relative symbols in 64bit address space we can use
4496          the same sequence as in 32bit address space.  */
4497       if (HAVE_64BIT_SYMBOLS)
4498         {
4499           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
4500               && !nopic_need_relax (ep->X_add_symbol, 1))
4501             {
4502               relax_start (ep->X_add_symbol);
4503               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
4504                            mips_gp_register, BFD_RELOC_GPREL16);
4505               relax_switch ();
4506             }
4507
4508           if (*used_at == 0 && mips_opts.at)
4509             {
4510               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
4511               macro_build (ep, "lui", "t,u", AT, BFD_RELOC_HI16_S);
4512               macro_build (ep, "daddiu", "t,r,j", reg, reg,
4513                            BFD_RELOC_MIPS_HIGHER);
4514               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
4515               macro_build (NULL, "dsll32", "d,w,<", reg, reg, 0);
4516               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
4517               *used_at = 1;
4518             }
4519           else
4520             {
4521               macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_HIGHEST);
4522               macro_build (ep, "daddiu", "t,r,j", reg, reg,
4523                            BFD_RELOC_MIPS_HIGHER);
4524               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
4525               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
4526               macro_build (NULL, "dsll", "d,w,<", reg, reg, 16);
4527               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
4528             }
4529
4530           if (mips_relax.sequence)
4531             relax_end ();
4532         }
4533       else
4534         {
4535           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
4536               && !nopic_need_relax (ep->X_add_symbol, 1))
4537             {
4538               relax_start (ep->X_add_symbol);
4539               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
4540                            mips_gp_register, BFD_RELOC_GPREL16);
4541               relax_switch ();
4542             }
4543           macro_build_lui (ep, reg);
4544           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
4545                        reg, reg, BFD_RELOC_LO16);
4546           if (mips_relax.sequence)
4547             relax_end ();
4548         }
4549     }
4550   else if (!mips_big_got)
4551     {
4552       expressionS ex;
4553
4554       /* If this is a reference to an external symbol, we want
4555            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
4556          Otherwise we want
4557            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
4558            nop
4559            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
4560          If there is a constant, it must be added in after.
4561
4562          If we have NewABI, we want
4563            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
4564          unless we're referencing a global symbol with a non-zero
4565          offset, in which case cst must be added separately.  */
4566       if (HAVE_NEWABI)
4567         {
4568           if (ep->X_add_number)
4569             {
4570               ex.X_add_number = ep->X_add_number;
4571               ep->X_add_number = 0;
4572               relax_start (ep->X_add_symbol);
4573               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4574                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
4575               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4576                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4577               ex.X_op = O_constant;
4578               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
4579                            reg, reg, BFD_RELOC_LO16);
4580               ep->X_add_number = ex.X_add_number;
4581               relax_switch ();
4582             }
4583           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4584                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
4585           if (mips_relax.sequence)
4586             relax_end ();
4587         }
4588       else
4589         {
4590           ex.X_add_number = ep->X_add_number;
4591           ep->X_add_number = 0;
4592           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4593                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
4594           load_delay_nop ();
4595           relax_start (ep->X_add_symbol);
4596           relax_switch ();
4597           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4598                        BFD_RELOC_LO16);
4599           relax_end ();
4600
4601           if (ex.X_add_number != 0)
4602             {
4603               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4604                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4605               ex.X_op = O_constant;
4606               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
4607                            reg, reg, BFD_RELOC_LO16);
4608             }
4609         }
4610     }
4611   else if (mips_big_got)
4612     {
4613       expressionS ex;
4614
4615       /* This is the large GOT case.  If this is a reference to an
4616          external symbol, we want
4617            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
4618            addu         $reg,$reg,$gp
4619            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
4620
4621          Otherwise, for a reference to a local symbol in old ABI, we want
4622            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
4623            nop
4624            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
4625          If there is a constant, it must be added in after.
4626
4627          In the NewABI, for local symbols, with or without offsets, we want:
4628            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
4629            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
4630       */
4631       if (HAVE_NEWABI)
4632         {
4633           ex.X_add_number = ep->X_add_number;
4634           ep->X_add_number = 0;
4635           relax_start (ep->X_add_symbol);
4636           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
4637           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
4638                        reg, reg, mips_gp_register);
4639           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
4640                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
4641           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4642             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4643           else if (ex.X_add_number)
4644             {
4645               ex.X_op = O_constant;
4646               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4647                            BFD_RELOC_LO16);
4648             }
4649
4650           ep->X_add_number = ex.X_add_number;
4651           relax_switch ();
4652           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4653                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
4654           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4655                        BFD_RELOC_MIPS_GOT_OFST);
4656           relax_end ();
4657         }
4658       else
4659         {
4660           ex.X_add_number = ep->X_add_number;
4661           ep->X_add_number = 0;
4662           relax_start (ep->X_add_symbol);
4663           macro_build (ep, "lui", "t,u", reg, BFD_RELOC_MIPS_GOT_HI16);
4664           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
4665                        reg, reg, mips_gp_register);
4666           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
4667                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
4668           relax_switch ();
4669           if (reg_needs_delay (mips_gp_register))
4670             {
4671               /* We need a nop before loading from $gp.  This special
4672                  check is required because the lui which starts the main
4673                  instruction stream does not refer to $gp, and so will not
4674                  insert the nop which may be required.  */
4675               macro_build (NULL, "nop", "");
4676             }
4677           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
4678                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
4679           load_delay_nop ();
4680           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4681                        BFD_RELOC_LO16);
4682           relax_end ();
4683
4684           if (ex.X_add_number != 0)
4685             {
4686               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
4687                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
4688               ex.X_op = O_constant;
4689               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
4690                            BFD_RELOC_LO16);
4691             }
4692         }
4693     }
4694   else
4695     abort ();
4696
4697   if (!mips_opts.at && *used_at == 1)
4698     as_bad (_("Macro used $at after \".set noat\""));
4699 }
4700
4701 /* Move the contents of register SOURCE into register DEST.  */
4702
4703 static void
4704 move_register (int dest, int source)
4705 {
4706   macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
4707                dest, source, 0);
4708 }
4709
4710 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
4711    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
4712    The two alternatives are:
4713
4714    Global symbol                Local sybmol
4715    -------------                ------------
4716    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
4717    ...                          ...
4718    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
4719
4720    load_got_offset emits the first instruction and add_got_offset
4721    emits the second for a 16-bit offset or add_got_offset_hilo emits
4722    a sequence to add a 32-bit offset using a scratch register.  */
4723
4724 static void
4725 load_got_offset (int dest, expressionS *local)
4726 {
4727   expressionS global;
4728
4729   global = *local;
4730   global.X_add_number = 0;
4731
4732   relax_start (local->X_add_symbol);
4733   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4734                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4735   relax_switch ();
4736   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
4737                BFD_RELOC_MIPS_GOT16, mips_gp_register);
4738   relax_end ();
4739 }
4740
4741 static void
4742 add_got_offset (int dest, expressionS *local)
4743 {
4744   expressionS global;
4745
4746   global.X_op = O_constant;
4747   global.X_op_symbol = NULL;
4748   global.X_add_symbol = NULL;
4749   global.X_add_number = local->X_add_number;
4750
4751   relax_start (local->X_add_symbol);
4752   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
4753                dest, dest, BFD_RELOC_LO16);
4754   relax_switch ();
4755   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
4756   relax_end ();
4757 }
4758
4759 static void
4760 add_got_offset_hilo (int dest, expressionS *local, int tmp)
4761 {
4762   expressionS global;
4763   int hold_mips_optimize;
4764
4765   global.X_op = O_constant;
4766   global.X_op_symbol = NULL;
4767   global.X_add_symbol = NULL;
4768   global.X_add_number = local->X_add_number;
4769
4770   relax_start (local->X_add_symbol);
4771   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
4772   relax_switch ();
4773   /* Set mips_optimize around the lui instruction to avoid
4774      inserting an unnecessary nop after the lw.  */
4775   hold_mips_optimize = mips_optimize;
4776   mips_optimize = 2;
4777   macro_build_lui (&global, tmp);
4778   mips_optimize = hold_mips_optimize;
4779   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
4780   relax_end ();
4781
4782   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
4783 }
4784
4785 /*
4786  *                      Build macros
4787  *   This routine implements the seemingly endless macro or synthesized
4788  * instructions and addressing modes in the mips assembly language. Many
4789  * of these macros are simple and are similar to each other. These could
4790  * probably be handled by some kind of table or grammar approach instead of
4791  * this verbose method. Others are not simple macros but are more like
4792  * optimizing code generation.
4793  *   One interesting optimization is when several store macros appear
4794  * consecutively that would load AT with the upper half of the same address.
4795  * The ensuing load upper instructions are ommited. This implies some kind
4796  * of global optimization. We currently only optimize within a single macro.
4797  *   For many of the load and store macros if the address is specified as a
4798  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
4799  * first load register 'at' with zero and use it as the base register. The
4800  * mips assembler simply uses register $zero. Just one tiny optimization
4801  * we're missing.
4802  */
4803 static void
4804 macro (struct mips_cl_insn *ip)
4805 {
4806   unsigned int treg, sreg, dreg, breg;
4807   unsigned int tempreg;
4808   int mask;
4809   int used_at = 0;
4810   expressionS expr1;
4811   const char *s;
4812   const char *s2;
4813   const char *fmt;
4814   int likely = 0;
4815   int dbl = 0;
4816   int coproc = 0;
4817   int lr = 0;
4818   int imm = 0;
4819   int call = 0;
4820   int off;
4821   offsetT maxnum;
4822   bfd_reloc_code_real_type r;
4823   int hold_mips_optimize;
4824
4825   gas_assert (! mips_opts.mips16);
4826
4827   treg = EXTRACT_OPERAND (RT, *ip);
4828   dreg = EXTRACT_OPERAND (RD, *ip);
4829   sreg = breg = EXTRACT_OPERAND (RS, *ip);
4830   mask = ip->insn_mo->mask;
4831
4832   expr1.X_op = O_constant;
4833   expr1.X_op_symbol = NULL;
4834   expr1.X_add_symbol = NULL;
4835   expr1.X_add_number = 1;
4836
4837   switch (mask)
4838     {
4839     case M_DABS:
4840       dbl = 1;
4841     case M_ABS:
4842       /* bgez $a0,.+12
4843          move v0,$a0
4844          sub v0,$zero,$a0
4845          */
4846
4847       start_noreorder ();
4848
4849       expr1.X_add_number = 8;
4850       macro_build (&expr1, "bgez", "s,p", sreg);
4851       if (dreg == sreg)
4852         macro_build (NULL, "nop", "");
4853       else
4854         move_register (dreg, sreg);
4855       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
4856
4857       end_noreorder ();
4858       break;
4859
4860     case M_ADD_I:
4861       s = "addi";
4862       s2 = "add";
4863       goto do_addi;
4864     case M_ADDU_I:
4865       s = "addiu";
4866       s2 = "addu";
4867       goto do_addi;
4868     case M_DADD_I:
4869       dbl = 1;
4870       s = "daddi";
4871       s2 = "dadd";
4872       goto do_addi;
4873     case M_DADDU_I:
4874       dbl = 1;
4875       s = "daddiu";
4876       s2 = "daddu";
4877     do_addi:
4878       if (imm_expr.X_op == O_constant
4879           && imm_expr.X_add_number >= -0x8000
4880           && imm_expr.X_add_number < 0x8000)
4881         {
4882           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
4883           break;
4884         }
4885       used_at = 1;
4886       load_register (AT, &imm_expr, dbl);
4887       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4888       break;
4889
4890     case M_AND_I:
4891       s = "andi";
4892       s2 = "and";
4893       goto do_bit;
4894     case M_OR_I:
4895       s = "ori";
4896       s2 = "or";
4897       goto do_bit;
4898     case M_NOR_I:
4899       s = "";
4900       s2 = "nor";
4901       goto do_bit;
4902     case M_XOR_I:
4903       s = "xori";
4904       s2 = "xor";
4905     do_bit:
4906       if (imm_expr.X_op == O_constant
4907           && imm_expr.X_add_number >= 0
4908           && imm_expr.X_add_number < 0x10000)
4909         {
4910           if (mask != M_NOR_I)
4911             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
4912           else
4913             {
4914               macro_build (&imm_expr, "ori", "t,r,i",
4915                            treg, sreg, BFD_RELOC_LO16);
4916               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
4917             }
4918           break;
4919         }
4920
4921       used_at = 1;
4922       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4923       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
4924       break;
4925
4926     case M_BALIGN:
4927       switch (imm_expr.X_add_number)
4928         {
4929         case 0:
4930           macro_build (NULL, "nop", "");
4931           break;
4932         case 2:
4933           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
4934           break;
4935         default:
4936           macro_build (NULL, "balign", "t,s,2", treg, sreg,
4937                        (int) imm_expr.X_add_number);
4938           break;
4939         }
4940       break;
4941
4942     case M_BEQ_I:
4943       s = "beq";
4944       goto beq_i;
4945     case M_BEQL_I:
4946       s = "beql";
4947       likely = 1;
4948       goto beq_i;
4949     case M_BNE_I:
4950       s = "bne";
4951       goto beq_i;
4952     case M_BNEL_I:
4953       s = "bnel";
4954       likely = 1;
4955     beq_i:
4956       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
4957         {
4958           macro_build (&offset_expr, s, "s,t,p", sreg, ZERO);
4959           break;
4960         }
4961       used_at = 1;
4962       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
4963       macro_build (&offset_expr, s, "s,t,p", sreg, AT);
4964       break;
4965
4966     case M_BGEL:
4967       likely = 1;
4968     case M_BGE:
4969       if (treg == 0)
4970         {
4971           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
4972           break;
4973         }
4974       if (sreg == 0)
4975         {
4976           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", treg);
4977           break;
4978         }
4979       used_at = 1;
4980       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
4981       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
4982       break;
4983
4984     case M_BGTL_I:
4985       likely = 1;
4986     case M_BGT_I:
4987       /* Check for > max integer.  */
4988       maxnum = 0x7fffffff;
4989       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
4990         {
4991           maxnum <<= 16;
4992           maxnum |= 0xffff;
4993           maxnum <<= 16;
4994           maxnum |= 0xffff;
4995         }
4996       if (imm_expr.X_op == O_constant
4997           && imm_expr.X_add_number >= maxnum
4998           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
4999         {
5000         do_false:
5001           /* Result is always false.  */
5002           if (! likely)
5003             macro_build (NULL, "nop", "");
5004           else
5005             macro_build (&offset_expr, "bnel", "s,t,p", ZERO, ZERO);
5006           break;
5007         }
5008       if (imm_expr.X_op != O_constant)
5009         as_bad (_("Unsupported large constant"));
5010       ++imm_expr.X_add_number;
5011       /* FALLTHROUGH */
5012     case M_BGE_I:
5013     case M_BGEL_I:
5014       if (mask == M_BGEL_I)
5015         likely = 1;
5016       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
5017         {
5018           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", sreg);
5019           break;
5020         }
5021       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
5022         {
5023           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
5024           break;
5025         }
5026       maxnum = 0x7fffffff;
5027       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
5028         {
5029           maxnum <<= 16;
5030           maxnum |= 0xffff;
5031           maxnum <<= 16;
5032           maxnum |= 0xffff;
5033         }
5034       maxnum = - maxnum - 1;
5035       if (imm_expr.X_op == O_constant
5036           && imm_expr.X_add_number <= maxnum
5037           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
5038         {
5039         do_true:
5040           /* result is always true */
5041           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
5042           macro_build (&offset_expr, "b", "p");
5043           break;
5044         }
5045       used_at = 1;
5046       set_at (sreg, 0);
5047       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
5048       break;
5049
5050     case M_BGEUL:
5051       likely = 1;
5052     case M_BGEU:
5053       if (treg == 0)
5054         goto do_true;
5055       if (sreg == 0)
5056         {
5057           macro_build (&offset_expr, likely ? "beql" : "beq",
5058                        "s,t,p", ZERO, treg);
5059           break;
5060         }
5061       used_at = 1;
5062       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
5063       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
5064       break;
5065
5066     case M_BGTUL_I:
5067       likely = 1;
5068     case M_BGTU_I:
5069       if (sreg == 0
5070           || (HAVE_32BIT_GPRS
5071               && imm_expr.X_op == O_constant
5072               && imm_expr.X_add_number == -1))
5073         goto do_false;
5074       if (imm_expr.X_op != O_constant)
5075         as_bad (_("Unsupported large constant"));
5076       ++imm_expr.X_add_number;
5077       /* FALLTHROUGH */
5078     case M_BGEU_I:
5079     case M_BGEUL_I:
5080       if (mask == M_BGEUL_I)
5081         likely = 1;
5082       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
5083         goto do_true;
5084       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
5085         {
5086           macro_build (&offset_expr, likely ? "bnel" : "bne",
5087                        "s,t,p", sreg, ZERO);
5088           break;
5089         }
5090       used_at = 1;
5091       set_at (sreg, 1);
5092       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
5093       break;
5094
5095     case M_BGTL:
5096       likely = 1;
5097     case M_BGT:
5098       if (treg == 0)
5099         {
5100           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", sreg);
5101           break;
5102         }
5103       if (sreg == 0)
5104         {
5105           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", treg);
5106           break;
5107         }
5108       used_at = 1;
5109       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
5110       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5111       break;
5112
5113     case M_BGTUL:
5114       likely = 1;
5115     case M_BGTU:
5116       if (treg == 0)
5117         {
5118           macro_build (&offset_expr, likely ? "bnel" : "bne",
5119                        "s,t,p", sreg, ZERO);
5120           break;
5121         }
5122       if (sreg == 0)
5123         goto do_false;
5124       used_at = 1;
5125       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
5126       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5127       break;
5128
5129     case M_BLEL:
5130       likely = 1;
5131     case M_BLE:
5132       if (treg == 0)
5133         {
5134           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
5135           break;
5136         }
5137       if (sreg == 0)
5138         {
5139           macro_build (&offset_expr, likely ? "bgezl" : "bgez", "s,p", treg);
5140           break;
5141         }
5142       used_at = 1;
5143       macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
5144       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
5145       break;
5146
5147     case M_BLEL_I:
5148       likely = 1;
5149     case M_BLE_I:
5150       maxnum = 0x7fffffff;
5151       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
5152         {
5153           maxnum <<= 16;
5154           maxnum |= 0xffff;
5155           maxnum <<= 16;
5156           maxnum |= 0xffff;
5157         }
5158       if (imm_expr.X_op == O_constant
5159           && imm_expr.X_add_number >= maxnum
5160           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
5161         goto do_true;
5162       if (imm_expr.X_op != O_constant)
5163         as_bad (_("Unsupported large constant"));
5164       ++imm_expr.X_add_number;
5165       /* FALLTHROUGH */
5166     case M_BLT_I:
5167     case M_BLTL_I:
5168       if (mask == M_BLTL_I)
5169         likely = 1;
5170       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
5171         {
5172           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
5173           break;
5174         }
5175       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
5176         {
5177           macro_build (&offset_expr, likely ? "blezl" : "blez", "s,p", sreg);
5178           break;
5179         }
5180       used_at = 1;
5181       set_at (sreg, 0);
5182       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5183       break;
5184
5185     case M_BLEUL:
5186       likely = 1;
5187     case M_BLEU:
5188       if (treg == 0)
5189         {
5190           macro_build (&offset_expr, likely ? "beql" : "beq",
5191                        "s,t,p", sreg, ZERO);
5192           break;
5193         }
5194       if (sreg == 0)
5195         goto do_true;
5196       used_at = 1;
5197       macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
5198       macro_build (&offset_expr, likely ? "beql" : "beq", "s,t,p", AT, ZERO);
5199       break;
5200
5201     case M_BLEUL_I:
5202       likely = 1;
5203     case M_BLEU_I:
5204       if (sreg == 0
5205           || (HAVE_32BIT_GPRS
5206               && imm_expr.X_op == O_constant
5207               && imm_expr.X_add_number == -1))
5208         goto do_true;
5209       if (imm_expr.X_op != O_constant)
5210         as_bad (_("Unsupported large constant"));
5211       ++imm_expr.X_add_number;
5212       /* FALLTHROUGH */
5213     case M_BLTU_I:
5214     case M_BLTUL_I:
5215       if (mask == M_BLTUL_I)
5216         likely = 1;
5217       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
5218         goto do_false;
5219       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
5220         {
5221           macro_build (&offset_expr, likely ? "beql" : "beq",
5222                        "s,t,p", sreg, ZERO);
5223           break;
5224         }
5225       used_at = 1;
5226       set_at (sreg, 1);
5227       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5228       break;
5229
5230     case M_BLTL:
5231       likely = 1;
5232     case M_BLT:
5233       if (treg == 0)
5234         {
5235           macro_build (&offset_expr, likely ? "bltzl" : "bltz", "s,p", sreg);
5236           break;
5237         }
5238       if (sreg == 0)
5239         {
5240           macro_build (&offset_expr, likely ? "bgtzl" : "bgtz", "s,p", treg);
5241           break;
5242         }
5243       used_at = 1;
5244       macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
5245       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5246       break;
5247
5248     case M_BLTUL:
5249       likely = 1;
5250     case M_BLTU:
5251       if (treg == 0)
5252         goto do_false;
5253       if (sreg == 0)
5254         {
5255           macro_build (&offset_expr, likely ? "bnel" : "bne",
5256                        "s,t,p", ZERO, treg);
5257           break;
5258         }
5259       used_at = 1;
5260       macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
5261       macro_build (&offset_expr, likely ? "bnel" : "bne", "s,t,p", AT, ZERO);
5262       break;
5263
5264     case M_DEXT:
5265       {
5266         /* Use unsigned arithmetic.  */
5267         addressT pos;
5268         addressT size;
5269
5270         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
5271           {
5272             as_bad (_("Unsupported large constant"));
5273             pos = size = 1;
5274           }
5275         else
5276           {
5277             pos = imm_expr.X_add_number;
5278             size = imm2_expr.X_add_number;
5279           }
5280
5281         if (pos > 63)
5282           {
5283             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
5284             pos = 1;
5285           }
5286         if (size == 0 || size > 64 || (pos + size - 1) > 63)
5287           {
5288             as_bad (_("Improper extract size (%lu, position %lu)"),
5289                     (unsigned long) size, (unsigned long) pos);
5290             size = 1;
5291           }
5292
5293         if (size <= 32 && pos < 32)
5294           {
5295             s = "dext";
5296             fmt = "t,r,+A,+C";
5297           }
5298         else if (size <= 32)
5299           {
5300             s = "dextu";
5301             fmt = "t,r,+E,+H";
5302           }
5303         else
5304           {
5305             s = "dextm";
5306             fmt = "t,r,+A,+G";
5307           }
5308         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
5309                      (int) (size - 1));
5310       }
5311       break;
5312
5313     case M_DINS:
5314       {
5315         /* Use unsigned arithmetic.  */
5316         addressT pos;
5317         addressT size;
5318
5319         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
5320           {
5321             as_bad (_("Unsupported large constant"));
5322             pos = size = 1;
5323           }
5324         else
5325           {
5326             pos = imm_expr.X_add_number;
5327             size = imm2_expr.X_add_number;
5328           }
5329
5330         if (pos > 63)
5331           {
5332             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
5333             pos = 1;
5334           }
5335         if (size == 0 || size > 64 || (pos + size - 1) > 63)
5336           {
5337             as_bad (_("Improper insert size (%lu, position %lu)"),
5338                     (unsigned long) size, (unsigned long) pos);
5339             size = 1;
5340           }
5341
5342         if (pos < 32 && (pos + size - 1) < 32)
5343           {
5344             s = "dins";
5345             fmt = "t,r,+A,+B";
5346           }
5347         else if (pos >= 32)
5348           {
5349             s = "dinsu";
5350             fmt = "t,r,+E,+F";
5351           }
5352         else
5353           {
5354             s = "dinsm";
5355             fmt = "t,r,+A,+F";
5356           }
5357         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
5358                      (int) (pos + size - 1));
5359       }
5360       break;
5361
5362     case M_DDIV_3:
5363       dbl = 1;
5364     case M_DIV_3:
5365       s = "mflo";
5366       goto do_div3;
5367     case M_DREM_3:
5368       dbl = 1;
5369     case M_REM_3:
5370       s = "mfhi";
5371     do_div3:
5372       if (treg == 0)
5373         {
5374           as_warn (_("Divide by zero."));
5375           if (mips_trap)
5376             macro_build (NULL, "teq", "s,t,q", ZERO, ZERO, 7);
5377           else
5378             macro_build (NULL, "break", "c", 7);
5379           break;
5380         }
5381
5382       start_noreorder ();
5383       if (mips_trap)
5384         {
5385           macro_build (NULL, "teq", "s,t,q", treg, ZERO, 7);
5386           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
5387         }
5388       else
5389         {
5390           expr1.X_add_number = 8;
5391           macro_build (&expr1, "bne", "s,t,p", treg, ZERO);
5392           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
5393           macro_build (NULL, "break", "c", 7);
5394         }
5395       expr1.X_add_number = -1;
5396       used_at = 1;
5397       load_register (AT, &expr1, dbl);
5398       expr1.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
5399       macro_build (&expr1, "bne", "s,t,p", treg, AT);
5400       if (dbl)
5401         {
5402           expr1.X_add_number = 1;
5403           load_register (AT, &expr1, dbl);
5404           macro_build (NULL, "dsll32", "d,w,<", AT, AT, 31);
5405         }
5406       else
5407         {
5408           expr1.X_add_number = 0x80000000;
5409           macro_build (&expr1, "lui", "t,u", AT, BFD_RELOC_HI16);
5410         }
5411       if (mips_trap)
5412         {
5413           macro_build (NULL, "teq", "s,t,q", sreg, AT, 6);
5414           /* We want to close the noreorder block as soon as possible, so
5415              that later insns are available for delay slot filling.  */
5416           end_noreorder ();
5417         }
5418       else
5419         {
5420           expr1.X_add_number = 8;
5421           macro_build (&expr1, "bne", "s,t,p", sreg, AT);
5422           macro_build (NULL, "nop", "");
5423
5424           /* We want to close the noreorder block as soon as possible, so
5425              that later insns are available for delay slot filling.  */
5426           end_noreorder ();
5427
5428           macro_build (NULL, "break", "c", 6);
5429         }
5430       macro_build (NULL, s, "d", dreg);
5431       break;
5432
5433     case M_DIV_3I:
5434       s = "div";
5435       s2 = "mflo";
5436       goto do_divi;
5437     case M_DIVU_3I:
5438       s = "divu";
5439       s2 = "mflo";
5440       goto do_divi;
5441     case M_REM_3I:
5442       s = "div";
5443       s2 = "mfhi";
5444       goto do_divi;
5445     case M_REMU_3I:
5446       s = "divu";
5447       s2 = "mfhi";
5448       goto do_divi;
5449     case M_DDIV_3I:
5450       dbl = 1;
5451       s = "ddiv";
5452       s2 = "mflo";
5453       goto do_divi;
5454     case M_DDIVU_3I:
5455       dbl = 1;
5456       s = "ddivu";
5457       s2 = "mflo";
5458       goto do_divi;
5459     case M_DREM_3I:
5460       dbl = 1;
5461       s = "ddiv";
5462       s2 = "mfhi";
5463       goto do_divi;
5464     case M_DREMU_3I:
5465       dbl = 1;
5466       s = "ddivu";
5467       s2 = "mfhi";
5468     do_divi:
5469       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
5470         {
5471           as_warn (_("Divide by zero."));
5472           if (mips_trap)
5473             macro_build (NULL, "teq", "s,t,q", ZERO, ZERO, 7);
5474           else
5475             macro_build (NULL, "break", "c", 7);
5476           break;
5477         }
5478       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
5479         {
5480           if (strcmp (s2, "mflo") == 0)
5481             move_register (dreg, sreg);
5482           else
5483             move_register (dreg, ZERO);
5484           break;
5485         }
5486       if (imm_expr.X_op == O_constant
5487           && imm_expr.X_add_number == -1
5488           && s[strlen (s) - 1] != 'u')
5489         {
5490           if (strcmp (s2, "mflo") == 0)
5491             {
5492               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
5493             }
5494           else
5495             move_register (dreg, ZERO);
5496           break;
5497         }
5498
5499       used_at = 1;
5500       load_register (AT, &imm_expr, dbl);
5501       macro_build (NULL, s, "z,s,t", sreg, AT);
5502       macro_build (NULL, s2, "d", dreg);
5503       break;
5504
5505     case M_DIVU_3:
5506       s = "divu";
5507       s2 = "mflo";
5508       goto do_divu3;
5509     case M_REMU_3:
5510       s = "divu";
5511       s2 = "mfhi";
5512       goto do_divu3;
5513     case M_DDIVU_3:
5514       s = "ddivu";
5515       s2 = "mflo";
5516       goto do_divu3;
5517     case M_DREMU_3:
5518       s = "ddivu";
5519       s2 = "mfhi";
5520     do_divu3:
5521       start_noreorder ();
5522       if (mips_trap)
5523         {
5524           macro_build (NULL, "teq", "s,t,q", treg, ZERO, 7);
5525           macro_build (NULL, s, "z,s,t", sreg, treg);
5526           /* We want to close the noreorder block as soon as possible, so
5527              that later insns are available for delay slot filling.  */
5528           end_noreorder ();
5529         }
5530       else
5531         {
5532           expr1.X_add_number = 8;
5533           macro_build (&expr1, "bne", "s,t,p", treg, ZERO);
5534           macro_build (NULL, s, "z,s,t", sreg, treg);
5535
5536           /* We want to close the noreorder block as soon as possible, so
5537              that later insns are available for delay slot filling.  */
5538           end_noreorder ();
5539           macro_build (NULL, "break", "c", 7);
5540         }
5541       macro_build (NULL, s2, "d", dreg);
5542       break;
5543
5544     case M_DLCA_AB:
5545       dbl = 1;
5546     case M_LCA_AB:
5547       call = 1;
5548       goto do_la;
5549     case M_DLA_AB:
5550       dbl = 1;
5551     case M_LA_AB:
5552     do_la:
5553       /* Load the address of a symbol into a register.  If breg is not
5554          zero, we then add a base register to it.  */
5555
5556       if (dbl && HAVE_32BIT_GPRS)
5557         as_warn (_("dla used to load 32-bit register"));
5558
5559       if (!dbl && HAVE_64BIT_OBJECTS)
5560         as_warn (_("la used to load 64-bit address"));
5561
5562       if (offset_expr.X_op == O_constant
5563           && offset_expr.X_add_number >= -0x8000
5564           && offset_expr.X_add_number < 0x8000)
5565         {
5566           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
5567                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
5568           break;
5569         }
5570
5571       if (mips_opts.at && (treg == breg))
5572         {
5573           tempreg = AT;
5574           used_at = 1;
5575         }
5576       else
5577         {
5578           tempreg = treg;
5579         }
5580
5581       if (offset_expr.X_op != O_symbol
5582           && offset_expr.X_op != O_constant)
5583         {
5584           as_bad (_("Expression too complex"));
5585           offset_expr.X_op = O_constant;
5586         }
5587
5588       if (offset_expr.X_op == O_constant)
5589         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
5590       else if (mips_pic == NO_PIC)
5591         {
5592           /* If this is a reference to a GP relative symbol, we want
5593                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
5594              Otherwise we want
5595                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
5596                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5597              If we have a constant, we need two instructions anyhow,
5598              so we may as well always use the latter form.
5599
5600              With 64bit address space and a usable $at we want
5601                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5602                lui      $at,<sym>               (BFD_RELOC_HI16_S)
5603                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5604                daddiu   $at,<sym>               (BFD_RELOC_LO16)
5605                dsll32   $tempreg,0
5606                daddu    $tempreg,$tempreg,$at
5607
5608              If $at is already in use, we use a path which is suboptimal
5609              on superscalar processors.
5610                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
5611                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
5612                dsll     $tempreg,16
5613                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
5614                dsll     $tempreg,16
5615                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
5616
5617              For GP relative symbols in 64bit address space we can use
5618              the same sequence as in 32bit address space.  */
5619           if (HAVE_64BIT_SYMBOLS)
5620             {
5621               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5622                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5623                 {
5624                   relax_start (offset_expr.X_add_symbol);
5625                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5626                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
5627                   relax_switch ();
5628                 }
5629
5630               if (used_at == 0 && mips_opts.at)
5631                 {
5632                   macro_build (&offset_expr, "lui", "t,u",
5633                                tempreg, BFD_RELOC_MIPS_HIGHEST);
5634                   macro_build (&offset_expr, "lui", "t,u",
5635                                AT, BFD_RELOC_HI16_S);
5636                   macro_build (&offset_expr, "daddiu", "t,r,j",
5637                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
5638                   macro_build (&offset_expr, "daddiu", "t,r,j",
5639                                AT, AT, BFD_RELOC_LO16);
5640                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
5641                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
5642                   used_at = 1;
5643                 }
5644               else
5645                 {
5646                   macro_build (&offset_expr, "lui", "t,u",
5647                                tempreg, BFD_RELOC_MIPS_HIGHEST);
5648                   macro_build (&offset_expr, "daddiu", "t,r,j",
5649                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
5650                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5651                   macro_build (&offset_expr, "daddiu", "t,r,j",
5652                                tempreg, tempreg, BFD_RELOC_HI16_S);
5653                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
5654                   macro_build (&offset_expr, "daddiu", "t,r,j",
5655                                tempreg, tempreg, BFD_RELOC_LO16);
5656                 }
5657
5658               if (mips_relax.sequence)
5659                 relax_end ();
5660             }
5661           else
5662             {
5663               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
5664                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
5665                 {
5666                   relax_start (offset_expr.X_add_symbol);
5667                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5668                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
5669                   relax_switch ();
5670                 }
5671               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
5672                 as_bad (_("Offset too large"));
5673               macro_build_lui (&offset_expr, tempreg);
5674               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5675                            tempreg, tempreg, BFD_RELOC_LO16);
5676               if (mips_relax.sequence)
5677                 relax_end ();
5678             }
5679         }
5680       else if (!mips_big_got && !HAVE_NEWABI)
5681         {
5682           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5683
5684           /* If this is a reference to an external symbol, and there
5685              is no constant, we want
5686                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5687              or for lca or if tempreg is PIC_CALL_REG
5688                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5689              For a local symbol, we want
5690                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5691                nop
5692                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5693
5694              If we have a small constant, and this is a reference to
5695              an external symbol, we want
5696                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5697                nop
5698                addiu    $tempreg,$tempreg,<constant>
5699              For a local symbol, we want the same instruction
5700              sequence, but we output a BFD_RELOC_LO16 reloc on the
5701              addiu instruction.
5702
5703              If we have a large constant, and this is a reference to
5704              an external symbol, we want
5705                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5706                lui      $at,<hiconstant>
5707                addiu    $at,$at,<loconstant>
5708                addu     $tempreg,$tempreg,$at
5709              For a local symbol, we want the same instruction
5710              sequence, but we output a BFD_RELOC_LO16 reloc on the
5711              addiu instruction.
5712            */
5713
5714           if (offset_expr.X_add_number == 0)
5715             {
5716               if (mips_pic == SVR4_PIC
5717                   && breg == 0
5718                   && (call || tempreg == PIC_CALL_REG))
5719                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
5720
5721               relax_start (offset_expr.X_add_symbol);
5722               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5723                            lw_reloc_type, mips_gp_register);
5724               if (breg != 0)
5725                 {
5726                   /* We're going to put in an addu instruction using
5727                      tempreg, so we may as well insert the nop right
5728                      now.  */
5729                   load_delay_nop ();
5730                 }
5731               relax_switch ();
5732               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5733                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
5734               load_delay_nop ();
5735               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5736                            tempreg, tempreg, BFD_RELOC_LO16);
5737               relax_end ();
5738               /* FIXME: If breg == 0, and the next instruction uses
5739                  $tempreg, then if this variant case is used an extra
5740                  nop will be generated.  */
5741             }
5742           else if (offset_expr.X_add_number >= -0x8000
5743                    && offset_expr.X_add_number < 0x8000)
5744             {
5745               load_got_offset (tempreg, &offset_expr);
5746               load_delay_nop ();
5747               add_got_offset (tempreg, &offset_expr);
5748             }
5749           else
5750             {
5751               expr1.X_add_number = offset_expr.X_add_number;
5752               offset_expr.X_add_number =
5753                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
5754               load_got_offset (tempreg, &offset_expr);
5755               offset_expr.X_add_number = expr1.X_add_number;
5756               /* If we are going to add in a base register, and the
5757                  target register and the base register are the same,
5758                  then we are using AT as a temporary register.  Since
5759                  we want to load the constant into AT, we add our
5760                  current AT (from the global offset table) and the
5761                  register into the register now, and pretend we were
5762                  not using a base register.  */
5763               if (breg == treg)
5764                 {
5765                   load_delay_nop ();
5766                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5767                                treg, AT, breg);
5768                   breg = 0;
5769                   tempreg = treg;
5770                 }
5771               add_got_offset_hilo (tempreg, &offset_expr, AT);
5772               used_at = 1;
5773             }
5774         }
5775       else if (!mips_big_got && HAVE_NEWABI)
5776         {
5777           int add_breg_early = 0;
5778
5779           /* If this is a reference to an external, and there is no
5780              constant, or local symbol (*), with or without a
5781              constant, we want
5782                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5783              or for lca or if tempreg is PIC_CALL_REG
5784                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
5785
5786              If we have a small constant, and this is a reference to
5787              an external symbol, we want
5788                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5789                addiu    $tempreg,$tempreg,<constant>
5790
5791              If we have a large constant, and this is a reference to
5792              an external symbol, we want
5793                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5794                lui      $at,<hiconstant>
5795                addiu    $at,$at,<loconstant>
5796                addu     $tempreg,$tempreg,$at
5797
5798              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
5799              local symbols, even though it introduces an additional
5800              instruction.  */
5801
5802           if (offset_expr.X_add_number)
5803             {
5804               expr1.X_add_number = offset_expr.X_add_number;
5805               offset_expr.X_add_number = 0;
5806
5807               relax_start (offset_expr.X_add_symbol);
5808               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5809                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5810
5811               if (expr1.X_add_number >= -0x8000
5812                   && expr1.X_add_number < 0x8000)
5813                 {
5814                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5815                                tempreg, tempreg, BFD_RELOC_LO16);
5816                 }
5817               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
5818                 {
5819                   /* If we are going to add in a base register, and the
5820                      target register and the base register are the same,
5821                      then we are using AT as a temporary register.  Since
5822                      we want to load the constant into AT, we add our
5823                      current AT (from the global offset table) and the
5824                      register into the register now, and pretend we were
5825                      not using a base register.  */
5826                   if (breg != treg)
5827                     dreg = tempreg;
5828                   else
5829                     {
5830                       gas_assert (tempreg == AT);
5831                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5832                                    treg, AT, breg);
5833                       dreg = treg;
5834                       add_breg_early = 1;
5835                     }
5836
5837                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5838                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5839                                dreg, dreg, AT);
5840
5841                   used_at = 1;
5842                 }
5843               else
5844                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
5845
5846               relax_switch ();
5847               offset_expr.X_add_number = expr1.X_add_number;
5848
5849               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5850                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5851               if (add_breg_early)
5852                 {
5853                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5854                                treg, tempreg, breg);
5855                   breg = 0;
5856                   tempreg = treg;
5857                 }
5858               relax_end ();
5859             }
5860           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
5861             {
5862               relax_start (offset_expr.X_add_symbol);
5863               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5864                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
5865               relax_switch ();
5866               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5867                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5868               relax_end ();
5869             }
5870           else
5871             {
5872               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5873                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5874             }
5875         }
5876       else if (mips_big_got && !HAVE_NEWABI)
5877         {
5878           int gpdelay;
5879           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
5880           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
5881           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
5882
5883           /* This is the large GOT case.  If this is a reference to an
5884              external symbol, and there is no constant, we want
5885                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5886                addu     $tempreg,$tempreg,$gp
5887                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5888              or for lca or if tempreg is PIC_CALL_REG
5889                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
5890                addu     $tempreg,$tempreg,$gp
5891                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
5892              For a local symbol, we want
5893                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5894                nop
5895                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
5896
5897              If we have a small constant, and this is a reference to
5898              an external symbol, we want
5899                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5900                addu     $tempreg,$tempreg,$gp
5901                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5902                nop
5903                addiu    $tempreg,$tempreg,<constant>
5904              For a local symbol, we want
5905                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5906                nop
5907                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
5908
5909              If we have a large constant, and this is a reference to
5910              an external symbol, we want
5911                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
5912                addu     $tempreg,$tempreg,$gp
5913                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
5914                lui      $at,<hiconstant>
5915                addiu    $at,$at,<loconstant>
5916                addu     $tempreg,$tempreg,$at
5917              For a local symbol, we want
5918                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
5919                lui      $at,<hiconstant>
5920                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
5921                addu     $tempreg,$tempreg,$at
5922           */
5923
5924           expr1.X_add_number = offset_expr.X_add_number;
5925           offset_expr.X_add_number = 0;
5926           relax_start (offset_expr.X_add_symbol);
5927           gpdelay = reg_needs_delay (mips_gp_register);
5928           if (expr1.X_add_number == 0 && breg == 0
5929               && (call || tempreg == PIC_CALL_REG))
5930             {
5931               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
5932               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
5933             }
5934           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
5935           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5936                        tempreg, tempreg, mips_gp_register);
5937           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
5938                        tempreg, lw_reloc_type, tempreg);
5939           if (expr1.X_add_number == 0)
5940             {
5941               if (breg != 0)
5942                 {
5943                   /* We're going to put in an addu instruction using
5944                      tempreg, so we may as well insert the nop right
5945                      now.  */
5946                   load_delay_nop ();
5947                 }
5948             }
5949           else if (expr1.X_add_number >= -0x8000
5950                    && expr1.X_add_number < 0x8000)
5951             {
5952               load_delay_nop ();
5953               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
5954                            tempreg, tempreg, BFD_RELOC_LO16);
5955             }
5956           else
5957             {
5958               /* If we are going to add in a base register, and the
5959                  target register and the base register are the same,
5960                  then we are using AT as a temporary register.  Since
5961                  we want to load the constant into AT, we add our
5962                  current AT (from the global offset table) and the
5963                  register into the register now, and pretend we were
5964                  not using a base register.  */
5965               if (breg != treg)
5966                 dreg = tempreg;
5967               else
5968                 {
5969                   gas_assert (tempreg == AT);
5970                   load_delay_nop ();
5971                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5972                                treg, AT, breg);
5973                   dreg = treg;
5974                 }
5975
5976               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
5977               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
5978
5979               used_at = 1;
5980             }
5981           offset_expr.X_add_number =
5982             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
5983           relax_switch ();
5984
5985           if (gpdelay)
5986             {
5987               /* This is needed because this instruction uses $gp, but
5988                  the first instruction on the main stream does not.  */
5989               macro_build (NULL, "nop", "");
5990             }
5991
5992           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
5993                        local_reloc_type, mips_gp_register);
5994           if (expr1.X_add_number >= -0x8000
5995               && expr1.X_add_number < 0x8000)
5996             {
5997               load_delay_nop ();
5998               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
5999                            tempreg, tempreg, BFD_RELOC_LO16);
6000               /* FIXME: If add_number is 0, and there was no base
6001                  register, the external symbol case ended with a load,
6002                  so if the symbol turns out to not be external, and
6003                  the next instruction uses tempreg, an unnecessary nop
6004                  will be inserted.  */
6005             }
6006           else
6007             {
6008               if (breg == treg)
6009                 {
6010                   /* We must add in the base register now, as in the
6011                      external symbol case.  */
6012                   gas_assert (tempreg == AT);
6013                   load_delay_nop ();
6014                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6015                                treg, AT, breg);
6016                   tempreg = treg;
6017                   /* We set breg to 0 because we have arranged to add
6018                      it in in both cases.  */
6019                   breg = 0;
6020                 }
6021
6022               macro_build_lui (&expr1, AT);
6023               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
6024                            AT, AT, BFD_RELOC_LO16);
6025               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6026                            tempreg, tempreg, AT);
6027               used_at = 1;
6028             }
6029           relax_end ();
6030         }
6031       else if (mips_big_got && HAVE_NEWABI)
6032         {
6033           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
6034           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
6035           int add_breg_early = 0;
6036
6037           /* This is the large GOT case.  If this is a reference to an
6038              external symbol, and there is no constant, we want
6039                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6040                add      $tempreg,$tempreg,$gp
6041                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6042              or for lca or if tempreg is PIC_CALL_REG
6043                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
6044                add      $tempreg,$tempreg,$gp
6045                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
6046
6047              If we have a small constant, and this is a reference to
6048              an external symbol, we want
6049                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6050                add      $tempreg,$tempreg,$gp
6051                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6052                addi     $tempreg,$tempreg,<constant>
6053
6054              If we have a large constant, and this is a reference to
6055              an external symbol, we want
6056                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6057                addu     $tempreg,$tempreg,$gp
6058                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6059                lui      $at,<hiconstant>
6060                addi     $at,$at,<loconstant>
6061                add      $tempreg,$tempreg,$at
6062
6063              If we have NewABI, and we know it's a local symbol, we want
6064                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
6065                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
6066              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
6067
6068           relax_start (offset_expr.X_add_symbol);
6069
6070           expr1.X_add_number = offset_expr.X_add_number;
6071           offset_expr.X_add_number = 0;
6072
6073           if (expr1.X_add_number == 0 && breg == 0
6074               && (call || tempreg == PIC_CALL_REG))
6075             {
6076               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
6077               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
6078             }
6079           macro_build (&offset_expr, "lui", "t,u", tempreg, lui_reloc_type);
6080           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6081                        tempreg, tempreg, mips_gp_register);
6082           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6083                        tempreg, lw_reloc_type, tempreg);
6084
6085           if (expr1.X_add_number == 0)
6086             ;
6087           else if (expr1.X_add_number >= -0x8000
6088                    && expr1.X_add_number < 0x8000)
6089             {
6090               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
6091                            tempreg, tempreg, BFD_RELOC_LO16);
6092             }
6093           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
6094             {
6095               /* If we are going to add in a base register, and the
6096                  target register and the base register are the same,
6097                  then we are using AT as a temporary register.  Since
6098                  we want to load the constant into AT, we add our
6099                  current AT (from the global offset table) and the
6100                  register into the register now, and pretend we were
6101                  not using a base register.  */
6102               if (breg != treg)
6103                 dreg = tempreg;
6104               else
6105                 {
6106                   gas_assert (tempreg == AT);
6107                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6108                                treg, AT, breg);
6109                   dreg = treg;
6110                   add_breg_early = 1;
6111                 }
6112
6113               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
6114               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
6115
6116               used_at = 1;
6117             }
6118           else
6119             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
6120
6121           relax_switch ();
6122           offset_expr.X_add_number = expr1.X_add_number;
6123           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6124                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6125           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6126                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
6127           if (add_breg_early)
6128             {
6129               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6130                            treg, tempreg, breg);
6131               breg = 0;
6132               tempreg = treg;
6133             }
6134           relax_end ();
6135         }
6136       else
6137         abort ();
6138
6139       if (breg != 0)
6140         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
6141       break;
6142
6143     case M_MSGSND:
6144       {
6145         unsigned long temp = (treg << 16) | (0x01);
6146         macro_build (NULL, "c2", "C", temp);
6147       }
6148       break;
6149
6150     case M_MSGLD:
6151       {
6152         unsigned long temp = (0x02);
6153         macro_build (NULL, "c2", "C", temp);
6154       }
6155       break;
6156
6157     case M_MSGLD_T:
6158       {
6159         unsigned long temp = (treg << 16) | (0x02);
6160         macro_build (NULL, "c2", "C", temp);
6161       }
6162       break;
6163
6164     case M_MSGWAIT:
6165       macro_build (NULL, "c2", "C", 3);
6166       break;
6167
6168     case M_MSGWAIT_T:
6169       {
6170         unsigned long temp = (treg << 16) | 0x03;
6171         macro_build (NULL, "c2", "C", temp);
6172       }
6173       break;
6174
6175     case M_J_A:
6176       /* The j instruction may not be used in PIC code, since it
6177          requires an absolute address.  We convert it to a b
6178          instruction.  */
6179       if (mips_pic == NO_PIC)
6180         macro_build (&offset_expr, "j", "a");
6181       else
6182         macro_build (&offset_expr, "b", "p");
6183       break;
6184
6185       /* The jal instructions must be handled as macros because when
6186          generating PIC code they expand to multi-instruction
6187          sequences.  Normally they are simple instructions.  */
6188     case M_JAL_1:
6189       dreg = RA;
6190       /* Fall through.  */
6191     case M_JAL_2:
6192       if (mips_pic == NO_PIC)
6193         macro_build (NULL, "jalr", "d,s", dreg, sreg);
6194       else
6195         {
6196           if (sreg != PIC_CALL_REG)
6197             as_warn (_("MIPS PIC call to register other than $25"));
6198
6199           macro_build (NULL, "jalr", "d,s", dreg, sreg);
6200           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
6201             {
6202               if (mips_cprestore_offset < 0)
6203                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
6204               else
6205                 {
6206                   if (!mips_frame_reg_valid)
6207                     {
6208                       as_warn (_("No .frame pseudo-op used in PIC code"));
6209                       /* Quiet this warning.  */
6210                       mips_frame_reg_valid = 1;
6211                     }
6212                   if (!mips_cprestore_valid)
6213                     {
6214                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
6215                       /* Quiet this warning.  */
6216                       mips_cprestore_valid = 1;
6217                     }
6218                   if (mips_opts.noreorder)
6219                     macro_build (NULL, "nop", "");
6220                   expr1.X_add_number = mips_cprestore_offset;
6221                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
6222                                                 mips_gp_register,
6223                                                 mips_frame_reg,
6224                                                 HAVE_64BIT_ADDRESSES);
6225                 }
6226             }
6227         }
6228
6229       break;
6230
6231     case M_JAL_A:
6232       if (mips_pic == NO_PIC)
6233         macro_build (&offset_expr, "jal", "a");
6234       else if (mips_pic == SVR4_PIC)
6235         {
6236           /* If this is a reference to an external symbol, and we are
6237              using a small GOT, we want
6238                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
6239                nop
6240                jalr     $ra,$25
6241                nop
6242                lw       $gp,cprestore($sp)
6243              The cprestore value is set using the .cprestore
6244              pseudo-op.  If we are using a big GOT, we want
6245                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
6246                addu     $25,$25,$gp
6247                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
6248                nop
6249                jalr     $ra,$25
6250                nop
6251                lw       $gp,cprestore($sp)
6252              If the symbol is not external, we want
6253                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
6254                nop
6255                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
6256                jalr     $ra,$25
6257                nop
6258                lw $gp,cprestore($sp)
6259
6260              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
6261              sequences above, minus nops, unless the symbol is local,
6262              which enables us to use GOT_PAGE/GOT_OFST (big got) or
6263              GOT_DISP.  */
6264           if (HAVE_NEWABI)
6265             {
6266               if (!mips_big_got)
6267                 {
6268                   relax_start (offset_expr.X_add_symbol);
6269                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6270                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
6271                                mips_gp_register);
6272                   relax_switch ();
6273                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6274                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
6275                                mips_gp_register);
6276                   relax_end ();
6277                 }
6278               else
6279                 {
6280                   relax_start (offset_expr.X_add_symbol);
6281                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
6282                                BFD_RELOC_MIPS_CALL_HI16);
6283                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
6284                                PIC_CALL_REG, mips_gp_register);
6285                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6286                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
6287                                PIC_CALL_REG);
6288                   relax_switch ();
6289                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6290                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
6291                                mips_gp_register);
6292                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
6293                                PIC_CALL_REG, PIC_CALL_REG,
6294                                BFD_RELOC_MIPS_GOT_OFST);
6295                   relax_end ();
6296                 }
6297
6298               macro_build_jalr (&offset_expr);
6299             }
6300           else
6301             {
6302               relax_start (offset_expr.X_add_symbol);
6303               if (!mips_big_got)
6304                 {
6305                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6306                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
6307                                mips_gp_register);
6308                   load_delay_nop ();
6309                   relax_switch ();
6310                 }
6311               else
6312                 {
6313                   int gpdelay;
6314
6315                   gpdelay = reg_needs_delay (mips_gp_register);
6316                   macro_build (&offset_expr, "lui", "t,u", PIC_CALL_REG,
6317                                BFD_RELOC_MIPS_CALL_HI16);
6318                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
6319                                PIC_CALL_REG, mips_gp_register);
6320                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6321                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
6322                                PIC_CALL_REG);
6323                   load_delay_nop ();
6324                   relax_switch ();
6325                   if (gpdelay)
6326                     macro_build (NULL, "nop", "");
6327                 }
6328               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
6329                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
6330                            mips_gp_register);
6331               load_delay_nop ();
6332               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
6333                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
6334               relax_end ();
6335               macro_build_jalr (&offset_expr);
6336
6337               if (mips_cprestore_offset < 0)
6338                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
6339               else
6340                 {
6341                   if (!mips_frame_reg_valid)
6342                     {
6343                       as_warn (_("No .frame pseudo-op used in PIC code"));
6344                       /* Quiet this warning.  */
6345                       mips_frame_reg_valid = 1;
6346                     }
6347                   if (!mips_cprestore_valid)
6348                     {
6349                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
6350                       /* Quiet this warning.  */
6351                       mips_cprestore_valid = 1;
6352                     }
6353                   if (mips_opts.noreorder)
6354                     macro_build (NULL, "nop", "");
6355                   expr1.X_add_number = mips_cprestore_offset;
6356                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
6357                                                 mips_gp_register,
6358                                                 mips_frame_reg,
6359                                                 HAVE_64BIT_ADDRESSES);
6360                 }
6361             }
6362         }
6363       else if (mips_pic == VXWORKS_PIC)
6364         as_bad (_("Non-PIC jump used in PIC library"));
6365       else
6366         abort ();
6367
6368       break;
6369
6370     case M_LB_AB:
6371       s = "lb";
6372       goto ld;
6373     case M_LBU_AB:
6374       s = "lbu";
6375       goto ld;
6376     case M_LH_AB:
6377       s = "lh";
6378       goto ld;
6379     case M_LHU_AB:
6380       s = "lhu";
6381       goto ld;
6382     case M_LW_AB:
6383       s = "lw";
6384       goto ld;
6385     case M_LWC0_AB:
6386       s = "lwc0";
6387       /* Itbl support may require additional care here.  */
6388       coproc = 1;
6389       goto ld;
6390     case M_LWC1_AB:
6391       s = "lwc1";
6392       /* Itbl support may require additional care here.  */
6393       coproc = 1;
6394       goto ld;
6395     case M_LWC2_AB:
6396       s = "lwc2";
6397       /* Itbl support may require additional care here.  */
6398       coproc = 1;
6399       goto ld;
6400     case M_LWC3_AB:
6401       s = "lwc3";
6402       /* Itbl support may require additional care here.  */
6403       coproc = 1;
6404       goto ld;
6405     case M_LWL_AB:
6406       s = "lwl";
6407       lr = 1;
6408       goto ld;
6409     case M_LWR_AB:
6410       s = "lwr";
6411       lr = 1;
6412       goto ld;
6413     case M_LDC1_AB:
6414       s = "ldc1";
6415       /* Itbl support may require additional care here.  */
6416       coproc = 1;
6417       goto ld;
6418     case M_LDC2_AB:
6419       s = "ldc2";
6420       /* Itbl support may require additional care here.  */
6421       coproc = 1;
6422       goto ld;
6423     case M_LDC3_AB:
6424       s = "ldc3";
6425       /* Itbl support may require additional care here.  */
6426       coproc = 1;
6427       goto ld;
6428     case M_LDL_AB:
6429       s = "ldl";
6430       lr = 1;
6431       goto ld;
6432     case M_LDR_AB:
6433       s = "ldr";
6434       lr = 1;
6435       goto ld;
6436     case M_LL_AB:
6437       s = "ll";
6438       goto ld;
6439     case M_LLD_AB:
6440       s = "lld";
6441       goto ld;
6442     case M_LWU_AB:
6443       s = "lwu";
6444     ld:
6445       if (breg == treg || coproc || lr)
6446         {
6447           tempreg = AT;
6448           used_at = 1;
6449         }
6450       else
6451         {
6452           tempreg = treg;
6453         }
6454       goto ld_st;
6455     case M_SB_AB:
6456       s = "sb";
6457       goto st;
6458     case M_SH_AB:
6459       s = "sh";
6460       goto st;
6461     case M_SW_AB:
6462       s = "sw";
6463       goto st;
6464     case M_SWC0_AB:
6465       s = "swc0";
6466       /* Itbl support may require additional care here.  */
6467       coproc = 1;
6468       goto st;
6469     case M_SWC1_AB:
6470       s = "swc1";
6471       /* Itbl support may require additional care here.  */
6472       coproc = 1;
6473       goto st;
6474     case M_SWC2_AB:
6475       s = "swc2";
6476       /* Itbl support may require additional care here.  */
6477       coproc = 1;
6478       goto st;
6479     case M_SWC3_AB:
6480       s = "swc3";
6481       /* Itbl support may require additional care here.  */
6482       coproc = 1;
6483       goto st;
6484     case M_SWL_AB:
6485       s = "swl";
6486       goto st;
6487     case M_SWR_AB:
6488       s = "swr";
6489       goto st;
6490     case M_SC_AB:
6491       s = "sc";
6492       goto st;
6493     case M_SCD_AB:
6494       s = "scd";
6495       goto st;
6496     case M_CACHE_AB:
6497       s = "cache";
6498       goto st;
6499     case M_SDC1_AB:
6500       s = "sdc1";
6501       coproc = 1;
6502       /* Itbl support may require additional care here.  */
6503       goto st;
6504     case M_SDC2_AB:
6505       s = "sdc2";
6506       /* Itbl support may require additional care here.  */
6507       coproc = 1;
6508       goto st;
6509     case M_SDC3_AB:
6510       s = "sdc3";
6511       /* Itbl support may require additional care here.  */
6512       coproc = 1;
6513       goto st;
6514     case M_SDL_AB:
6515       s = "sdl";
6516       goto st;
6517     case M_SDR_AB:
6518       s = "sdr";
6519     st:
6520       tempreg = AT;
6521       used_at = 1;
6522     ld_st:
6523       if (coproc
6524           && NO_ISA_COP (mips_opts.arch)
6525           && (ip->insn_mo->pinfo2 & (INSN2_M_FP_S | INSN2_M_FP_D)) == 0)
6526         {
6527           as_bad (_("Opcode not supported on this processor: %s"),
6528                   mips_cpu_info_from_arch (mips_opts.arch)->name);
6529           break;
6530         }
6531
6532       /* Itbl support may require additional care here.  */
6533       if (mask == M_LWC1_AB
6534           || mask == M_SWC1_AB
6535           || mask == M_LDC1_AB
6536           || mask == M_SDC1_AB
6537           || mask == M_L_DAB
6538           || mask == M_S_DAB)
6539         fmt = "T,o(b)";
6540       else if (mask == M_CACHE_AB)
6541         fmt = "k,o(b)";
6542       else if (coproc)
6543         fmt = "E,o(b)";
6544       else
6545         fmt = "t,o(b)";
6546
6547       if (offset_expr.X_op != O_constant
6548           && offset_expr.X_op != O_symbol)
6549         {
6550           as_bad (_("Expression too complex"));
6551           offset_expr.X_op = O_constant;
6552         }
6553
6554       if (HAVE_32BIT_ADDRESSES
6555           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
6556         {
6557           char value [32];
6558
6559           sprintf_vma (value, offset_expr.X_add_number);
6560           as_bad (_("Number (0x%s) larger than 32 bits"), value);
6561         }
6562
6563       /* A constant expression in PIC code can be handled just as it
6564          is in non PIC code.  */
6565       if (offset_expr.X_op == O_constant)
6566         {
6567           expr1.X_add_number = offset_expr.X_add_number;
6568           normalize_address_expr (&expr1);
6569           if (!IS_SEXT_16BIT_NUM (expr1.X_add_number))
6570             {
6571               expr1.X_add_number = ((expr1.X_add_number + 0x8000)
6572                                     & ~(bfd_vma) 0xffff);
6573               load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
6574               if (breg != 0)
6575                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6576                              tempreg, tempreg, breg);
6577               breg = tempreg;
6578             }
6579           macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, breg);
6580         }
6581       else if (mips_pic == NO_PIC)
6582         {
6583           /* If this is a reference to a GP relative symbol, and there
6584              is no base register, we want
6585                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
6586              Otherwise, if there is no base register, we want
6587                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
6588                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6589              If we have a constant, we need two instructions anyhow,
6590              so we always use the latter form.
6591
6592              If we have a base register, and this is a reference to a
6593              GP relative symbol, we want
6594                addu     $tempreg,$breg,$gp
6595                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
6596              Otherwise we want
6597                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
6598                addu     $tempreg,$tempreg,$breg
6599                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6600              With a constant we always use the latter case.
6601
6602              With 64bit address space and no base register and $at usable,
6603              we want
6604                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
6605                lui      $at,<sym>               (BFD_RELOC_HI16_S)
6606                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
6607                dsll32   $tempreg,0
6608                daddu    $tempreg,$at
6609                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6610              If we have a base register, we want
6611                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
6612                lui      $at,<sym>               (BFD_RELOC_HI16_S)
6613                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
6614                daddu    $at,$breg
6615                dsll32   $tempreg,0
6616                daddu    $tempreg,$at
6617                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6618
6619              Without $at we can't generate the optimal path for superscalar
6620              processors here since this would require two temporary registers.
6621                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
6622                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
6623                dsll     $tempreg,16
6624                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
6625                dsll     $tempreg,16
6626                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6627              If we have a base register, we want
6628                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
6629                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
6630                dsll     $tempreg,16
6631                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
6632                dsll     $tempreg,16
6633                daddu    $tempreg,$tempreg,$breg
6634                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
6635
6636              For GP relative symbols in 64bit address space we can use
6637              the same sequence as in 32bit address space.  */
6638           if (HAVE_64BIT_SYMBOLS)
6639             {
6640               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6641                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6642                 {
6643                   relax_start (offset_expr.X_add_symbol);
6644                   if (breg == 0)
6645                     {
6646                       macro_build (&offset_expr, s, fmt, treg,
6647                                    BFD_RELOC_GPREL16, mips_gp_register);
6648                     }
6649                   else
6650                     {
6651                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6652                                    tempreg, breg, mips_gp_register);
6653                       macro_build (&offset_expr, s, fmt, treg,
6654                                    BFD_RELOC_GPREL16, tempreg);
6655                     }
6656                   relax_switch ();
6657                 }
6658
6659               if (used_at == 0 && mips_opts.at)
6660                 {
6661                   macro_build (&offset_expr, "lui", "t,u", tempreg,
6662                                BFD_RELOC_MIPS_HIGHEST);
6663                   macro_build (&offset_expr, "lui", "t,u", AT,
6664                                BFD_RELOC_HI16_S);
6665                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
6666                                tempreg, BFD_RELOC_MIPS_HIGHER);
6667                   if (breg != 0)
6668                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
6669                   macro_build (NULL, "dsll32", "d,w,<", tempreg, tempreg, 0);
6670                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
6671                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
6672                                tempreg);
6673                   used_at = 1;
6674                 }
6675               else
6676                 {
6677                   macro_build (&offset_expr, "lui", "t,u", tempreg,
6678                                BFD_RELOC_MIPS_HIGHEST);
6679                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
6680                                tempreg, BFD_RELOC_MIPS_HIGHER);
6681                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
6682                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
6683                                tempreg, BFD_RELOC_HI16_S);
6684                   macro_build (NULL, "dsll", "d,w,<", tempreg, tempreg, 16);
6685                   if (breg != 0)
6686                     macro_build (NULL, "daddu", "d,v,t",
6687                                  tempreg, tempreg, breg);
6688                   macro_build (&offset_expr, s, fmt, treg,
6689                                BFD_RELOC_LO16, tempreg);
6690                 }
6691
6692               if (mips_relax.sequence)
6693                 relax_end ();
6694               break;
6695             }
6696
6697           if (breg == 0)
6698             {
6699               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6700                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6701                 {
6702                   relax_start (offset_expr.X_add_symbol);
6703                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
6704                                mips_gp_register);
6705                   relax_switch ();
6706                 }
6707               macro_build_lui (&offset_expr, tempreg);
6708               macro_build (&offset_expr, s, fmt, treg,
6709                            BFD_RELOC_LO16, tempreg);
6710               if (mips_relax.sequence)
6711                 relax_end ();
6712             }
6713           else
6714             {
6715               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
6716                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
6717                 {
6718                   relax_start (offset_expr.X_add_symbol);
6719                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6720                                tempreg, breg, mips_gp_register);
6721                   macro_build (&offset_expr, s, fmt, treg,
6722                                BFD_RELOC_GPREL16, tempreg);
6723                   relax_switch ();
6724                 }
6725               macro_build_lui (&offset_expr, tempreg);
6726               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6727                            tempreg, tempreg, breg);
6728               macro_build (&offset_expr, s, fmt, treg,
6729                            BFD_RELOC_LO16, tempreg);
6730               if (mips_relax.sequence)
6731                 relax_end ();
6732             }
6733         }
6734       else if (!mips_big_got)
6735         {
6736           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
6737
6738           /* If this is a reference to an external symbol, we want
6739                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6740                nop
6741                <op>     $treg,0($tempreg)
6742              Otherwise we want
6743                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6744                nop
6745                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6746                <op>     $treg,0($tempreg)
6747
6748              For NewABI, we want
6749                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6750                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
6751
6752              If there is a base register, we add it to $tempreg before
6753              the <op>.  If there is a constant, we stick it in the
6754              <op> instruction.  We don't handle constants larger than
6755              16 bits, because we have no way to load the upper 16 bits
6756              (actually, we could handle them for the subset of cases
6757              in which we are not using $at).  */
6758           gas_assert (offset_expr.X_op == O_symbol);
6759           if (HAVE_NEWABI)
6760             {
6761               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6762                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6763               if (breg != 0)
6764                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6765                              tempreg, tempreg, breg);
6766               macro_build (&offset_expr, s, fmt, treg,
6767                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
6768               break;
6769             }
6770           expr1.X_add_number = offset_expr.X_add_number;
6771           offset_expr.X_add_number = 0;
6772           if (expr1.X_add_number < -0x8000
6773               || expr1.X_add_number >= 0x8000)
6774             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6775           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6776                        lw_reloc_type, mips_gp_register);
6777           load_delay_nop ();
6778           relax_start (offset_expr.X_add_symbol);
6779           relax_switch ();
6780           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6781                        tempreg, BFD_RELOC_LO16);
6782           relax_end ();
6783           if (breg != 0)
6784             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6785                          tempreg, tempreg, breg);
6786           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6787         }
6788       else if (mips_big_got && !HAVE_NEWABI)
6789         {
6790           int gpdelay;
6791
6792           /* If this is a reference to an external symbol, we want
6793                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6794                addu     $tempreg,$tempreg,$gp
6795                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6796                <op>     $treg,0($tempreg)
6797              Otherwise we want
6798                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
6799                nop
6800                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
6801                <op>     $treg,0($tempreg)
6802              If there is a base register, we add it to $tempreg before
6803              the <op>.  If there is a constant, we stick it in the
6804              <op> instruction.  We don't handle constants larger than
6805              16 bits, because we have no way to load the upper 16 bits
6806              (actually, we could handle them for the subset of cases
6807              in which we are not using $at).  */
6808           gas_assert (offset_expr.X_op == O_symbol);
6809           expr1.X_add_number = offset_expr.X_add_number;
6810           offset_expr.X_add_number = 0;
6811           if (expr1.X_add_number < -0x8000
6812               || expr1.X_add_number >= 0x8000)
6813             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6814           gpdelay = reg_needs_delay (mips_gp_register);
6815           relax_start (offset_expr.X_add_symbol);
6816           macro_build (&offset_expr, "lui", "t,u", tempreg,
6817                        BFD_RELOC_MIPS_GOT_HI16);
6818           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6819                        mips_gp_register);
6820           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6821                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6822           relax_switch ();
6823           if (gpdelay)
6824             macro_build (NULL, "nop", "");
6825           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6826                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6827           load_delay_nop ();
6828           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
6829                        tempreg, BFD_RELOC_LO16);
6830           relax_end ();
6831
6832           if (breg != 0)
6833             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6834                          tempreg, tempreg, breg);
6835           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6836         }
6837       else if (mips_big_got && HAVE_NEWABI)
6838         {
6839           /* If this is a reference to an external symbol, we want
6840                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
6841                add      $tempreg,$tempreg,$gp
6842                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
6843                <op>     $treg,<ofst>($tempreg)
6844              Otherwise, for local symbols, we want:
6845                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
6846                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
6847           gas_assert (offset_expr.X_op == O_symbol);
6848           expr1.X_add_number = offset_expr.X_add_number;
6849           offset_expr.X_add_number = 0;
6850           if (expr1.X_add_number < -0x8000
6851               || expr1.X_add_number >= 0x8000)
6852             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6853           relax_start (offset_expr.X_add_symbol);
6854           macro_build (&offset_expr, "lui", "t,u", tempreg,
6855                        BFD_RELOC_MIPS_GOT_HI16);
6856           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
6857                        mips_gp_register);
6858           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6859                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
6860           if (breg != 0)
6861             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6862                          tempreg, tempreg, breg);
6863           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
6864
6865           relax_switch ();
6866           offset_expr.X_add_number = expr1.X_add_number;
6867           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
6868                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6869           if (breg != 0)
6870             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6871                          tempreg, tempreg, breg);
6872           macro_build (&offset_expr, s, fmt, treg,
6873                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
6874           relax_end ();
6875         }
6876       else
6877         abort ();
6878
6879       break;
6880
6881     case M_LI:
6882     case M_LI_S:
6883       load_register (treg, &imm_expr, 0);
6884       break;
6885
6886     case M_DLI:
6887       load_register (treg, &imm_expr, 1);
6888       break;
6889
6890     case M_LI_SS:
6891       if (imm_expr.X_op == O_constant)
6892         {
6893           used_at = 1;
6894           load_register (AT, &imm_expr, 0);
6895           macro_build (NULL, "mtc1", "t,G", AT, treg);
6896           break;
6897         }
6898       else
6899         {
6900           gas_assert (offset_expr.X_op == O_symbol
6901                       && strcmp (segment_name (S_GET_SEGMENT
6902                                                (offset_expr.X_add_symbol)),
6903                                  ".lit4") == 0
6904                       && offset_expr.X_add_number == 0);
6905           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
6906                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
6907           break;
6908         }
6909
6910     case M_LI_D:
6911       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
6912          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
6913          order 32 bits of the value and the low order 32 bits are either
6914          zero or in OFFSET_EXPR.  */
6915       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6916         {
6917           if (HAVE_64BIT_GPRS)
6918             load_register (treg, &imm_expr, 1);
6919           else
6920             {
6921               int hreg, lreg;
6922
6923               if (target_big_endian)
6924                 {
6925                   hreg = treg;
6926                   lreg = treg + 1;
6927                 }
6928               else
6929                 {
6930                   hreg = treg + 1;
6931                   lreg = treg;
6932                 }
6933
6934               if (hreg <= 31)
6935                 load_register (hreg, &imm_expr, 0);
6936               if (lreg <= 31)
6937                 {
6938                   if (offset_expr.X_op == O_absent)
6939                     move_register (lreg, 0);
6940                   else
6941                     {
6942                       gas_assert (offset_expr.X_op == O_constant);
6943                       load_register (lreg, &offset_expr, 0);
6944                     }
6945                 }
6946             }
6947           break;
6948         }
6949
6950       /* We know that sym is in the .rdata section.  First we get the
6951          upper 16 bits of the address.  */
6952       if (mips_pic == NO_PIC)
6953         {
6954           macro_build_lui (&offset_expr, AT);
6955           used_at = 1;
6956         }
6957       else
6958         {
6959           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
6960                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6961           used_at = 1;
6962         }
6963
6964       /* Now we load the register(s).  */
6965       if (HAVE_64BIT_GPRS)
6966         {
6967           used_at = 1;
6968           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6969         }
6970       else
6971         {
6972           used_at = 1;
6973           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
6974           if (treg != RA)
6975             {
6976               /* FIXME: How in the world do we deal with the possible
6977                  overflow here?  */
6978               offset_expr.X_add_number += 4;
6979               macro_build (&offset_expr, "lw", "t,o(b)",
6980                            treg + 1, BFD_RELOC_LO16, AT);
6981             }
6982         }
6983       break;
6984
6985     case M_LI_DD:
6986       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
6987          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
6988          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
6989          the value and the low order 32 bits are either zero or in
6990          OFFSET_EXPR.  */
6991       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
6992         {
6993           used_at = 1;
6994           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
6995           if (HAVE_64BIT_FPRS)
6996             {
6997               gas_assert (HAVE_64BIT_GPRS);
6998               macro_build (NULL, "dmtc1", "t,S", AT, treg);
6999             }
7000           else
7001             {
7002               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
7003               if (offset_expr.X_op == O_absent)
7004                 macro_build (NULL, "mtc1", "t,G", 0, treg);
7005               else
7006                 {
7007                   gas_assert (offset_expr.X_op == O_constant);
7008                   load_register (AT, &offset_expr, 0);
7009                   macro_build (NULL, "mtc1", "t,G", AT, treg);
7010                 }
7011             }
7012           break;
7013         }
7014
7015       gas_assert (offset_expr.X_op == O_symbol
7016                   && offset_expr.X_add_number == 0);
7017       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
7018       if (strcmp (s, ".lit8") == 0)
7019         {
7020           if (mips_opts.isa != ISA_MIPS1)
7021             {
7022               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
7023                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
7024               break;
7025             }
7026           breg = mips_gp_register;
7027           r = BFD_RELOC_MIPS_LITERAL;
7028           goto dob;
7029         }
7030       else
7031         {
7032           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
7033           used_at = 1;
7034           if (mips_pic != NO_PIC)
7035             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
7036                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
7037           else
7038             {
7039               /* FIXME: This won't work for a 64 bit address.  */
7040               macro_build_lui (&offset_expr, AT);
7041             }
7042
7043           if (mips_opts.isa != ISA_MIPS1)
7044             {
7045               macro_build (&offset_expr, "ldc1", "T,o(b)",
7046                            treg, BFD_RELOC_LO16, AT);
7047               break;
7048             }
7049           breg = AT;
7050           r = BFD_RELOC_LO16;
7051           goto dob;
7052         }
7053
7054     case M_L_DOB:
7055       /* Even on a big endian machine $fn comes before $fn+1.  We have
7056          to adjust when loading from memory.  */
7057       r = BFD_RELOC_LO16;
7058     dob:
7059       gas_assert (mips_opts.isa == ISA_MIPS1);
7060       macro_build (&offset_expr, "lwc1", "T,o(b)",
7061                    target_big_endian ? treg + 1 : treg, r, breg);
7062       /* FIXME: A possible overflow which I don't know how to deal
7063          with.  */
7064       offset_expr.X_add_number += 4;
7065       macro_build (&offset_expr, "lwc1", "T,o(b)",
7066                    target_big_endian ? treg : treg + 1, r, breg);
7067       break;
7068
7069     case M_S_DOB:
7070       gas_assert (mips_opts.isa == ISA_MIPS1);
7071       /* Even on a big endian machine $fn comes before $fn+1.  We have
7072          to adjust when storing to memory.  */
7073       macro_build (&offset_expr, "swc1", "T,o(b)",
7074                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
7075       offset_expr.X_add_number += 4;
7076       macro_build (&offset_expr, "swc1", "T,o(b)",
7077                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
7078       break;
7079
7080     case M_L_DAB:
7081       /*
7082        * The MIPS assembler seems to check for X_add_number not
7083        * being double aligned and generating:
7084        *        lui     at,%hi(foo+1)
7085        *        addu    at,at,v1
7086        *        addiu   at,at,%lo(foo+1)
7087        *        lwc1    f2,0(at)
7088        *        lwc1    f3,4(at)
7089        * But, the resulting address is the same after relocation so why
7090        * generate the extra instruction?
7091        */
7092       /* Itbl support may require additional care here.  */
7093       coproc = 1;
7094       if (mips_opts.isa != ISA_MIPS1)
7095         {
7096           s = "ldc1";
7097           goto ld;
7098         }
7099
7100       s = "lwc1";
7101       fmt = "T,o(b)";
7102       goto ldd_std;
7103
7104     case M_S_DAB:
7105       if (mips_opts.isa != ISA_MIPS1)
7106         {
7107           s = "sdc1";
7108           goto st;
7109         }
7110
7111       s = "swc1";
7112       fmt = "T,o(b)";
7113       /* Itbl support may require additional care here.  */
7114       coproc = 1;
7115       goto ldd_std;
7116
7117     case M_LD_AB:
7118       if (HAVE_64BIT_GPRS)
7119         {
7120           s = "ld";
7121           goto ld;
7122         }
7123
7124       s = "lw";
7125       fmt = "t,o(b)";
7126       goto ldd_std;
7127
7128     case M_SD_AB:
7129       if (HAVE_64BIT_GPRS)
7130         {
7131           s = "sd";
7132           goto st;
7133         }
7134
7135       s = "sw";
7136       fmt = "t,o(b)";
7137
7138     ldd_std:
7139       if (offset_expr.X_op != O_symbol
7140           && offset_expr.X_op != O_constant)
7141         {
7142           as_bad (_("Expression too complex"));
7143           offset_expr.X_op = O_constant;
7144         }
7145
7146       if (HAVE_32BIT_ADDRESSES
7147           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7148         {
7149           char value [32];
7150
7151           sprintf_vma (value, offset_expr.X_add_number);
7152           as_bad (_("Number (0x%s) larger than 32 bits"), value);
7153         }
7154
7155       /* Even on a big endian machine $fn comes before $fn+1.  We have
7156          to adjust when loading from memory.  We set coproc if we must
7157          load $fn+1 first.  */
7158       /* Itbl support may require additional care here.  */
7159       if (!target_big_endian)
7160         coproc = 0;
7161
7162       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
7163         {
7164           /* If this is a reference to a GP relative symbol, we want
7165                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
7166                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
7167              If we have a base register, we use this
7168                addu     $at,$breg,$gp
7169                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
7170                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
7171              If this is not a GP relative symbol, we want
7172                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7173                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
7174                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
7175              If there is a base register, we add it to $at after the
7176              lui instruction.  If there is a constant, we always use
7177              the last case.  */
7178           if (offset_expr.X_op == O_symbol
7179               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7180               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7181             {
7182               relax_start (offset_expr.X_add_symbol);
7183               if (breg == 0)
7184                 {
7185                   tempreg = mips_gp_register;
7186                 }
7187               else
7188                 {
7189                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7190                                AT, breg, mips_gp_register);
7191                   tempreg = AT;
7192                   used_at = 1;
7193                 }
7194
7195               /* Itbl support may require additional care here.  */
7196               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
7197                            BFD_RELOC_GPREL16, tempreg);
7198               offset_expr.X_add_number += 4;
7199
7200               /* Set mips_optimize to 2 to avoid inserting an
7201                  undesired nop.  */
7202               hold_mips_optimize = mips_optimize;
7203               mips_optimize = 2;
7204               /* Itbl support may require additional care here.  */
7205               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
7206                            BFD_RELOC_GPREL16, tempreg);
7207               mips_optimize = hold_mips_optimize;
7208
7209               relax_switch ();
7210
7211               offset_expr.X_add_number -= 4;
7212             }
7213           used_at = 1;
7214           macro_build_lui (&offset_expr, AT);
7215           if (breg != 0)
7216             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
7217           /* Itbl support may require additional care here.  */
7218           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
7219                        BFD_RELOC_LO16, AT);
7220           /* FIXME: How do we handle overflow here?  */
7221           offset_expr.X_add_number += 4;
7222           /* Itbl support may require additional care here.  */
7223           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
7224                        BFD_RELOC_LO16, AT);
7225           if (mips_relax.sequence)
7226             relax_end ();
7227         }
7228       else if (!mips_big_got)
7229         {
7230           /* If this is a reference to an external symbol, we want
7231                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7232                nop
7233                <op>     $treg,0($at)
7234                <op>     $treg+1,4($at)
7235              Otherwise we want
7236                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7237                nop
7238                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
7239                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
7240              If there is a base register we add it to $at before the
7241              lwc1 instructions.  If there is a constant we include it
7242              in the lwc1 instructions.  */
7243           used_at = 1;
7244           expr1.X_add_number = offset_expr.X_add_number;
7245           if (expr1.X_add_number < -0x8000
7246               || expr1.X_add_number >= 0x8000 - 4)
7247             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7248           load_got_offset (AT, &offset_expr);
7249           load_delay_nop ();
7250           if (breg != 0)
7251             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
7252
7253           /* Set mips_optimize to 2 to avoid inserting an undesired
7254              nop.  */
7255           hold_mips_optimize = mips_optimize;
7256           mips_optimize = 2;
7257
7258           /* Itbl support may require additional care here.  */
7259           relax_start (offset_expr.X_add_symbol);
7260           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
7261                        BFD_RELOC_LO16, AT);
7262           expr1.X_add_number += 4;
7263           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
7264                        BFD_RELOC_LO16, AT);
7265           relax_switch ();
7266           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
7267                        BFD_RELOC_LO16, AT);
7268           offset_expr.X_add_number += 4;
7269           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
7270                        BFD_RELOC_LO16, AT);
7271           relax_end ();
7272
7273           mips_optimize = hold_mips_optimize;
7274         }
7275       else if (mips_big_got)
7276         {
7277           int gpdelay;
7278
7279           /* If this is a reference to an external symbol, we want
7280                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
7281                addu     $at,$at,$gp
7282                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
7283                nop
7284                <op>     $treg,0($at)
7285                <op>     $treg+1,4($at)
7286              Otherwise we want
7287                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7288                nop
7289                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
7290                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
7291              If there is a base register we add it to $at before the
7292              lwc1 instructions.  If there is a constant we include it
7293              in the lwc1 instructions.  */
7294           used_at = 1;
7295           expr1.X_add_number = offset_expr.X_add_number;
7296           offset_expr.X_add_number = 0;
7297           if (expr1.X_add_number < -0x8000
7298               || expr1.X_add_number >= 0x8000 - 4)
7299             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7300           gpdelay = reg_needs_delay (mips_gp_register);
7301           relax_start (offset_expr.X_add_symbol);
7302           macro_build (&offset_expr, "lui", "t,u",
7303                        AT, BFD_RELOC_MIPS_GOT_HI16);
7304           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7305                        AT, AT, mips_gp_register);
7306           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7307                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
7308           load_delay_nop ();
7309           if (breg != 0)
7310             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
7311           /* Itbl support may require additional care here.  */
7312           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
7313                        BFD_RELOC_LO16, AT);
7314           expr1.X_add_number += 4;
7315
7316           /* Set mips_optimize to 2 to avoid inserting an undesired
7317              nop.  */
7318           hold_mips_optimize = mips_optimize;
7319           mips_optimize = 2;
7320           /* Itbl support may require additional care here.  */
7321           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
7322                        BFD_RELOC_LO16, AT);
7323           mips_optimize = hold_mips_optimize;
7324           expr1.X_add_number -= 4;
7325
7326           relax_switch ();
7327           offset_expr.X_add_number = expr1.X_add_number;
7328           if (gpdelay)
7329             macro_build (NULL, "nop", "");
7330           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
7331                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7332           load_delay_nop ();
7333           if (breg != 0)
7334             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
7335           /* Itbl support may require additional care here.  */
7336           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
7337                        BFD_RELOC_LO16, AT);
7338           offset_expr.X_add_number += 4;
7339
7340           /* Set mips_optimize to 2 to avoid inserting an undesired
7341              nop.  */
7342           hold_mips_optimize = mips_optimize;
7343           mips_optimize = 2;
7344           /* Itbl support may require additional care here.  */
7345           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
7346                        BFD_RELOC_LO16, AT);
7347           mips_optimize = hold_mips_optimize;
7348           relax_end ();
7349         }
7350       else
7351         abort ();
7352
7353       break;
7354
7355     case M_LD_OB:
7356       s = HAVE_64BIT_GPRS ? "ld" : "lw";
7357       goto sd_ob;
7358     case M_SD_OB:
7359       s = HAVE_64BIT_GPRS ? "sd" : "sw";
7360     sd_ob:
7361       macro_build (&offset_expr, s, "t,o(b)", treg,
7362                    -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
7363                    breg);
7364       if (!HAVE_64BIT_GPRS)
7365         {
7366           offset_expr.X_add_number += 4;
7367           macro_build (&offset_expr, s, "t,o(b)", treg + 1,
7368                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
7369                        breg);
7370         }
7371       break;
7372
7373    /* New code added to support COPZ instructions.
7374       This code builds table entries out of the macros in mip_opcodes.
7375       R4000 uses interlocks to handle coproc delays.
7376       Other chips (like the R3000) require nops to be inserted for delays.
7377
7378       FIXME: Currently, we require that the user handle delays.
7379       In order to fill delay slots for non-interlocked chips,
7380       we must have a way to specify delays based on the coprocessor.
7381       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
7382       What are the side-effects of the cop instruction?
7383       What cache support might we have and what are its effects?
7384       Both coprocessor & memory require delays. how long???
7385       What registers are read/set/modified?
7386
7387       If an itbl is provided to interpret cop instructions,
7388       this knowledge can be encoded in the itbl spec.  */
7389
7390     case M_COP0:
7391       s = "c0";
7392       goto copz;
7393     case M_COP1:
7394       s = "c1";
7395       goto copz;
7396     case M_COP2:
7397       s = "c2";
7398       goto copz;
7399     case M_COP3:
7400       s = "c3";
7401     copz:
7402       if (NO_ISA_COP (mips_opts.arch)
7403           && (ip->insn_mo->pinfo2 & INSN2_M_FP_S) == 0)
7404         {
7405           as_bad (_("opcode not supported on this processor: %s"),
7406                   mips_cpu_info_from_arch (mips_opts.arch)->name);
7407           break;
7408         }
7409
7410       /* For now we just do C (same as Cz).  The parameter will be
7411          stored in insn_opcode by mips_ip.  */
7412       macro_build (NULL, s, "C", ip->insn_opcode);
7413       break;
7414
7415     case M_MOVE:
7416       move_register (dreg, sreg);
7417       break;
7418
7419     case M_DMUL:
7420       dbl = 1;
7421     case M_MUL:
7422       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
7423       macro_build (NULL, "mflo", "d", dreg);
7424       break;
7425
7426     case M_DMUL_I:
7427       dbl = 1;
7428     case M_MUL_I:
7429       /* The MIPS assembler some times generates shifts and adds.  I'm
7430          not trying to be that fancy. GCC should do this for us
7431          anyway.  */
7432       used_at = 1;
7433       load_register (AT, &imm_expr, dbl);
7434       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
7435       macro_build (NULL, "mflo", "d", dreg);
7436       break;
7437
7438     case M_DMULO_I:
7439       dbl = 1;
7440     case M_MULO_I:
7441       imm = 1;
7442       goto do_mulo;
7443
7444     case M_DMULO:
7445       dbl = 1;
7446     case M_MULO:
7447     do_mulo:
7448       start_noreorder ();
7449       used_at = 1;
7450       if (imm)
7451         load_register (AT, &imm_expr, dbl);
7452       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
7453       macro_build (NULL, "mflo", "d", dreg);
7454       macro_build (NULL, dbl ? "dsra32" : "sra", "d,w,<", dreg, dreg, RA);
7455       macro_build (NULL, "mfhi", "d", AT);
7456       if (mips_trap)
7457         macro_build (NULL, "tne", "s,t,q", dreg, AT, 6);
7458       else
7459         {
7460           expr1.X_add_number = 8;
7461           macro_build (&expr1, "beq", "s,t,p", dreg, AT);
7462           macro_build (NULL, "nop", "");
7463           macro_build (NULL, "break", "c", 6);
7464         }
7465       end_noreorder ();
7466       macro_build (NULL, "mflo", "d", dreg);
7467       break;
7468
7469     case M_DMULOU_I:
7470       dbl = 1;
7471     case M_MULOU_I:
7472       imm = 1;
7473       goto do_mulou;
7474
7475     case M_DMULOU:
7476       dbl = 1;
7477     case M_MULOU:
7478     do_mulou:
7479       start_noreorder ();
7480       used_at = 1;
7481       if (imm)
7482         load_register (AT, &imm_expr, dbl);
7483       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
7484                    sreg, imm ? AT : treg);
7485       macro_build (NULL, "mfhi", "d", AT);
7486       macro_build (NULL, "mflo", "d", dreg);
7487       if (mips_trap)
7488         macro_build (NULL, "tne", "s,t,q", AT, ZERO, 6);
7489       else
7490         {
7491           expr1.X_add_number = 8;
7492           macro_build (&expr1, "beq", "s,t,p", AT, ZERO);
7493           macro_build (NULL, "nop", "");
7494           macro_build (NULL, "break", "c", 6);
7495         }
7496       end_noreorder ();
7497       break;
7498
7499     case M_DROL:
7500       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
7501         {
7502           if (dreg == sreg)
7503             {
7504               tempreg = AT;
7505               used_at = 1;
7506             }
7507           else
7508             {
7509               tempreg = dreg;
7510             }
7511           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
7512           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
7513           break;
7514         }
7515       used_at = 1;
7516       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
7517       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
7518       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
7519       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7520       break;
7521
7522     case M_ROL:
7523       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7524         {
7525           if (dreg == sreg)
7526             {
7527               tempreg = AT;
7528               used_at = 1;
7529             }
7530           else
7531             {
7532               tempreg = dreg;
7533             }
7534           macro_build (NULL, "negu", "d,w", tempreg, treg);
7535           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
7536           break;
7537         }
7538       used_at = 1;
7539       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
7540       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
7541       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
7542       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7543       break;
7544
7545     case M_DROL_I:
7546       {
7547         unsigned int rot;
7548         char *l;
7549         char *rr;
7550
7551         if (imm_expr.X_op != O_constant)
7552           as_bad (_("Improper rotate count"));
7553         rot = imm_expr.X_add_number & 0x3f;
7554         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
7555           {
7556             rot = (64 - rot) & 0x3f;
7557             if (rot >= 32)
7558               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
7559             else
7560               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
7561             break;
7562           }
7563         if (rot == 0)
7564           {
7565             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
7566             break;
7567           }
7568         l = (rot < 0x20) ? "dsll" : "dsll32";
7569         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
7570         rot &= 0x1f;
7571         used_at = 1;
7572         macro_build (NULL, l, "d,w,<", AT, sreg, rot);
7573         macro_build (NULL, rr, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7574         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7575       }
7576       break;
7577
7578     case M_ROL_I:
7579       {
7580         unsigned int rot;
7581
7582         if (imm_expr.X_op != O_constant)
7583           as_bad (_("Improper rotate count"));
7584         rot = imm_expr.X_add_number & 0x1f;
7585         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7586           {
7587             macro_build (NULL, "ror", "d,w,<", dreg, sreg, (32 - rot) & 0x1f);
7588             break;
7589           }
7590         if (rot == 0)
7591           {
7592             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
7593             break;
7594           }
7595         used_at = 1;
7596         macro_build (NULL, "sll", "d,w,<", AT, sreg, rot);
7597         macro_build (NULL, "srl", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7598         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7599       }
7600       break;
7601
7602     case M_DROR:
7603       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
7604         {
7605           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
7606           break;
7607         }
7608       used_at = 1;
7609       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
7610       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
7611       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
7612       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7613       break;
7614
7615     case M_ROR:
7616       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7617         {
7618           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
7619           break;
7620         }
7621       used_at = 1;
7622       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
7623       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
7624       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
7625       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7626       break;
7627
7628     case M_DROR_I:
7629       {
7630         unsigned int rot;
7631         char *l;
7632         char *rr;
7633
7634         if (imm_expr.X_op != O_constant)
7635           as_bad (_("Improper rotate count"));
7636         rot = imm_expr.X_add_number & 0x3f;
7637         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
7638           {
7639             if (rot >= 32)
7640               macro_build (NULL, "dror32", "d,w,<", dreg, sreg, rot - 32);
7641             else
7642               macro_build (NULL, "dror", "d,w,<", dreg, sreg, rot);
7643             break;
7644           }
7645         if (rot == 0)
7646           {
7647             macro_build (NULL, "dsrl", "d,w,<", dreg, sreg, 0);
7648             break;
7649           }
7650         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
7651         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
7652         rot &= 0x1f;
7653         used_at = 1;
7654         macro_build (NULL, rr, "d,w,<", AT, sreg, rot);
7655         macro_build (NULL, l, "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7656         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7657       }
7658       break;
7659
7660     case M_ROR_I:
7661       {
7662         unsigned int rot;
7663
7664         if (imm_expr.X_op != O_constant)
7665           as_bad (_("Improper rotate count"));
7666         rot = imm_expr.X_add_number & 0x1f;
7667         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
7668           {
7669             macro_build (NULL, "ror", "d,w,<", dreg, sreg, rot);
7670             break;
7671           }
7672         if (rot == 0)
7673           {
7674             macro_build (NULL, "srl", "d,w,<", dreg, sreg, 0);
7675             break;
7676           }
7677         used_at = 1;
7678         macro_build (NULL, "srl", "d,w,<", AT, sreg, rot);
7679         macro_build (NULL, "sll", "d,w,<", dreg, sreg, (0x20 - rot) & 0x1f);
7680         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
7681       }
7682       break;
7683
7684     case M_SEQ:
7685       if (sreg == 0)
7686         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
7687       else if (treg == 0)
7688         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7689       else
7690         {
7691           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7692           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7693         }
7694       break;
7695
7696     case M_SEQ_I:
7697       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7698         {
7699           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7700           break;
7701         }
7702       if (sreg == 0)
7703         {
7704           as_warn (_("Instruction %s: result is always false"),
7705                    ip->insn_mo->name);
7706           move_register (dreg, 0);
7707           break;
7708         }
7709       if (CPU_HAS_SEQ (mips_opts.arch)
7710           && -512 <= imm_expr.X_add_number
7711           && imm_expr.X_add_number < 512)
7712         {
7713           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
7714                        (int) imm_expr.X_add_number);
7715           break;
7716         }
7717       if (imm_expr.X_op == O_constant
7718           && imm_expr.X_add_number >= 0
7719           && imm_expr.X_add_number < 0x10000)
7720         {
7721           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7722         }
7723       else if (imm_expr.X_op == O_constant
7724                && imm_expr.X_add_number > -0x8000
7725                && imm_expr.X_add_number < 0)
7726         {
7727           imm_expr.X_add_number = -imm_expr.X_add_number;
7728           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7729                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7730         }
7731       else if (CPU_HAS_SEQ (mips_opts.arch))
7732         {
7733           used_at = 1;
7734           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7735           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
7736           break;
7737         }
7738       else
7739         {
7740           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7741           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7742           used_at = 1;
7743         }
7744       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
7745       break;
7746
7747     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
7748       s = "slt";
7749       goto sge;
7750     case M_SGEU:
7751       s = "sltu";
7752     sge:
7753       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
7754       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7755       break;
7756
7757     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
7758     case M_SGEU_I:
7759       if (imm_expr.X_op == O_constant
7760           && imm_expr.X_add_number >= -0x8000
7761           && imm_expr.X_add_number < 0x8000)
7762         {
7763           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
7764                        dreg, sreg, BFD_RELOC_LO16);
7765         }
7766       else
7767         {
7768           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7769           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
7770                        dreg, sreg, AT);
7771           used_at = 1;
7772         }
7773       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7774       break;
7775
7776     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
7777       s = "slt";
7778       goto sgt;
7779     case M_SGTU:
7780       s = "sltu";
7781     sgt:
7782       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7783       break;
7784
7785     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
7786       s = "slt";
7787       goto sgti;
7788     case M_SGTU_I:
7789       s = "sltu";
7790     sgti:
7791       used_at = 1;
7792       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7793       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7794       break;
7795
7796     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
7797       s = "slt";
7798       goto sle;
7799     case M_SLEU:
7800       s = "sltu";
7801     sle:
7802       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
7803       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7804       break;
7805
7806     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
7807       s = "slt";
7808       goto slei;
7809     case M_SLEU_I:
7810       s = "sltu";
7811     slei:
7812       used_at = 1;
7813       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7814       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
7815       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
7816       break;
7817
7818     case M_SLT_I:
7819       if (imm_expr.X_op == O_constant
7820           && imm_expr.X_add_number >= -0x8000
7821           && imm_expr.X_add_number < 0x8000)
7822         {
7823           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7824           break;
7825         }
7826       used_at = 1;
7827       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7828       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
7829       break;
7830
7831     case M_SLTU_I:
7832       if (imm_expr.X_op == O_constant
7833           && imm_expr.X_add_number >= -0x8000
7834           && imm_expr.X_add_number < 0x8000)
7835         {
7836           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
7837                        BFD_RELOC_LO16);
7838           break;
7839         }
7840       used_at = 1;
7841       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7842       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
7843       break;
7844
7845     case M_SNE:
7846       if (sreg == 0)
7847         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
7848       else if (treg == 0)
7849         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7850       else
7851         {
7852           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
7853           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7854         }
7855       break;
7856
7857     case M_SNE_I:
7858       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7859         {
7860           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
7861           break;
7862         }
7863       if (sreg == 0)
7864         {
7865           as_warn (_("Instruction %s: result is always true"),
7866                    ip->insn_mo->name);
7867           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
7868                        dreg, 0, BFD_RELOC_LO16);
7869           break;
7870         }
7871       if (CPU_HAS_SEQ (mips_opts.arch)
7872           && -512 <= imm_expr.X_add_number
7873           && imm_expr.X_add_number < 512)
7874         {
7875           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
7876                        (int) imm_expr.X_add_number);
7877           break;
7878         }
7879       if (imm_expr.X_op == O_constant
7880           && imm_expr.X_add_number >= 0
7881           && imm_expr.X_add_number < 0x10000)
7882         {
7883           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
7884         }
7885       else if (imm_expr.X_op == O_constant
7886                && imm_expr.X_add_number > -0x8000
7887                && imm_expr.X_add_number < 0)
7888         {
7889           imm_expr.X_add_number = -imm_expr.X_add_number;
7890           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
7891                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
7892         }
7893       else if (CPU_HAS_SEQ (mips_opts.arch))
7894         {
7895           used_at = 1;
7896           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7897           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
7898           break;
7899         }
7900       else
7901         {
7902           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7903           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
7904           used_at = 1;
7905         }
7906       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
7907       break;
7908
7909     case M_DSUB_I:
7910       dbl = 1;
7911     case M_SUB_I:
7912       if (imm_expr.X_op == O_constant
7913           && imm_expr.X_add_number > -0x8000
7914           && imm_expr.X_add_number <= 0x8000)
7915         {
7916           imm_expr.X_add_number = -imm_expr.X_add_number;
7917           macro_build (&imm_expr, dbl ? "daddi" : "addi", "t,r,j",
7918                        dreg, sreg, BFD_RELOC_LO16);
7919           break;
7920         }
7921       used_at = 1;
7922       load_register (AT, &imm_expr, dbl);
7923       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, sreg, AT);
7924       break;
7925
7926     case M_DSUBU_I:
7927       dbl = 1;
7928     case M_SUBU_I:
7929       if (imm_expr.X_op == O_constant
7930           && imm_expr.X_add_number > -0x8000
7931           && imm_expr.X_add_number <= 0x8000)
7932         {
7933           imm_expr.X_add_number = -imm_expr.X_add_number;
7934           macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "t,r,j",
7935                        dreg, sreg, BFD_RELOC_LO16);
7936           break;
7937         }
7938       used_at = 1;
7939       load_register (AT, &imm_expr, dbl);
7940       macro_build (NULL, dbl ? "dsubu" : "subu", "d,v,t", dreg, sreg, AT);
7941       break;
7942
7943     case M_TEQ_I:
7944       s = "teq";
7945       goto trap;
7946     case M_TGE_I:
7947       s = "tge";
7948       goto trap;
7949     case M_TGEU_I:
7950       s = "tgeu";
7951       goto trap;
7952     case M_TLT_I:
7953       s = "tlt";
7954       goto trap;
7955     case M_TLTU_I:
7956       s = "tltu";
7957       goto trap;
7958     case M_TNE_I:
7959       s = "tne";
7960     trap:
7961       used_at = 1;
7962       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7963       macro_build (NULL, s, "s,t", sreg, AT);
7964       break;
7965
7966     case M_TRUNCWS:
7967     case M_TRUNCWD:
7968       gas_assert (mips_opts.isa == ISA_MIPS1);
7969       used_at = 1;
7970       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
7971       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
7972
7973       /*
7974        * Is the double cfc1 instruction a bug in the mips assembler;
7975        * or is there a reason for it?
7976        */
7977       start_noreorder ();
7978       macro_build (NULL, "cfc1", "t,G", treg, RA);
7979       macro_build (NULL, "cfc1", "t,G", treg, RA);
7980       macro_build (NULL, "nop", "");
7981       expr1.X_add_number = 3;
7982       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
7983       expr1.X_add_number = 2;
7984       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
7985       macro_build (NULL, "ctc1", "t,G", AT, RA);
7986       macro_build (NULL, "nop", "");
7987       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
7988                    dreg, sreg);
7989       macro_build (NULL, "ctc1", "t,G", treg, RA);
7990       macro_build (NULL, "nop", "");
7991       end_noreorder ();
7992       break;
7993
7994     case M_ULH:
7995       s = "lb";
7996       goto ulh;
7997     case M_ULHU:
7998       s = "lbu";
7999     ulh:
8000       used_at = 1;
8001       if (offset_expr.X_add_number >= 0x7fff)
8002         as_bad (_("Operand overflow"));
8003       if (!target_big_endian)
8004         ++offset_expr.X_add_number;
8005       macro_build (&offset_expr, s, "t,o(b)", AT, BFD_RELOC_LO16, breg);
8006       if (!target_big_endian)
8007         --offset_expr.X_add_number;
8008       else
8009         ++offset_expr.X_add_number;
8010       macro_build (&offset_expr, "lbu", "t,o(b)", treg, BFD_RELOC_LO16, breg);
8011       macro_build (NULL, "sll", "d,w,<", AT, AT, 8);
8012       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
8013       break;
8014
8015     case M_ULD:
8016       s = "ldl";
8017       s2 = "ldr";
8018       off = 7;
8019       goto ulw;
8020     case M_ULW:
8021       s = "lwl";
8022       s2 = "lwr";
8023       off = 3;
8024     ulw:
8025       if (offset_expr.X_add_number >= 0x8000 - off)
8026         as_bad (_("Operand overflow"));
8027       if (treg != breg)
8028         tempreg = treg;
8029       else
8030         {
8031           used_at = 1;
8032           tempreg = AT;
8033         }
8034       if (!target_big_endian)
8035         offset_expr.X_add_number += off;
8036       macro_build (&offset_expr, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
8037       if (!target_big_endian)
8038         offset_expr.X_add_number -= off;
8039       else
8040         offset_expr.X_add_number += off;
8041       macro_build (&offset_expr, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
8042
8043       /* If necessary, move the result in tempreg to the final destination.  */
8044       if (treg == tempreg)
8045         break;
8046       /* Protect second load's delay slot.  */
8047       load_delay_nop ();
8048       move_register (treg, tempreg);
8049       break;
8050
8051     case M_ULD_A:
8052       s = "ldl";
8053       s2 = "ldr";
8054       off = 7;
8055       goto ulwa;
8056     case M_ULW_A:
8057       s = "lwl";
8058       s2 = "lwr";
8059       off = 3;
8060     ulwa:
8061       used_at = 1;
8062       load_address (AT, &offset_expr, &used_at);
8063       if (breg != 0)
8064         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8065       if (!target_big_endian)
8066         expr1.X_add_number = off;
8067       else
8068         expr1.X_add_number = 0;
8069       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8070       if (!target_big_endian)
8071         expr1.X_add_number = 0;
8072       else
8073         expr1.X_add_number = off;
8074       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8075       break;
8076
8077     case M_ULH_A:
8078     case M_ULHU_A:
8079       used_at = 1;
8080       load_address (AT, &offset_expr, &used_at);
8081       if (breg != 0)
8082         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8083       if (target_big_endian)
8084         expr1.X_add_number = 0;
8085       macro_build (&expr1, mask == M_ULH_A ? "lb" : "lbu", "t,o(b)",
8086                    treg, BFD_RELOC_LO16, AT);
8087       if (target_big_endian)
8088         expr1.X_add_number = 1;
8089       else
8090         expr1.X_add_number = 0;
8091       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
8092       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
8093       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
8094       break;
8095
8096     case M_USH:
8097       used_at = 1;
8098       if (offset_expr.X_add_number >= 0x7fff)
8099         as_bad (_("Operand overflow"));
8100       if (target_big_endian)
8101         ++offset_expr.X_add_number;
8102       macro_build (&offset_expr, "sb", "t,o(b)", treg, BFD_RELOC_LO16, breg);
8103       macro_build (NULL, "srl", "d,w,<", AT, treg, 8);
8104       if (target_big_endian)
8105         --offset_expr.X_add_number;
8106       else
8107         ++offset_expr.X_add_number;
8108       macro_build (&offset_expr, "sb", "t,o(b)", AT, BFD_RELOC_LO16, breg);
8109       break;
8110
8111     case M_USD:
8112       s = "sdl";
8113       s2 = "sdr";
8114       off = 7;
8115       goto usw;
8116     case M_USW:
8117       s = "swl";
8118       s2 = "swr";
8119       off = 3;
8120     usw:
8121       if (offset_expr.X_add_number >= 0x8000 - off)
8122         as_bad (_("Operand overflow"));
8123       if (!target_big_endian)
8124         offset_expr.X_add_number += off;
8125       macro_build (&offset_expr, s, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8126       if (!target_big_endian)
8127         offset_expr.X_add_number -= off;
8128       else
8129         offset_expr.X_add_number += off;
8130       macro_build (&offset_expr, s2, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8131       break;
8132
8133     case M_USD_A:
8134       s = "sdl";
8135       s2 = "sdr";
8136       off = 7;
8137       goto uswa;
8138     case M_USW_A:
8139       s = "swl";
8140       s2 = "swr";
8141       off = 3;
8142     uswa:
8143       used_at = 1;
8144       load_address (AT, &offset_expr, &used_at);
8145       if (breg != 0)
8146         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8147       if (!target_big_endian)
8148         expr1.X_add_number = off;
8149       else
8150         expr1.X_add_number = 0;
8151       macro_build (&expr1, s, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8152       if (!target_big_endian)
8153         expr1.X_add_number = 0;
8154       else
8155         expr1.X_add_number = off;
8156       macro_build (&expr1, s2, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8157       break;
8158
8159     case M_USH_A:
8160       used_at = 1;
8161       load_address (AT, &offset_expr, &used_at);
8162       if (breg != 0)
8163         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8164       if (!target_big_endian)
8165         expr1.X_add_number = 0;
8166       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8167       macro_build (NULL, "srl", "d,w,<", treg, treg, 8);
8168       if (!target_big_endian)
8169         expr1.X_add_number = 1;
8170       else
8171         expr1.X_add_number = 0;
8172       macro_build (&expr1, "sb", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8173       if (!target_big_endian)
8174         expr1.X_add_number = 0;
8175       else
8176         expr1.X_add_number = 1;
8177       macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
8178       macro_build (NULL, "sll", "d,w,<", treg, treg, 8);
8179       macro_build (NULL, "or", "d,v,t", treg, treg, AT);
8180       break;
8181
8182     default:
8183       /* FIXME: Check if this is one of the itbl macros, since they
8184          are added dynamically.  */
8185       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
8186       break;
8187     }
8188   if (!mips_opts.at && used_at)
8189     as_bad (_("Macro used $at after \".set noat\""));
8190 }
8191
8192 /* Implement macros in mips16 mode.  */
8193
8194 static void
8195 mips16_macro (struct mips_cl_insn *ip)
8196 {
8197   int mask;
8198   int xreg, yreg, zreg, tmp;
8199   expressionS expr1;
8200   int dbl;
8201   const char *s, *s2, *s3;
8202
8203   mask = ip->insn_mo->mask;
8204
8205   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
8206   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
8207   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
8208
8209   expr1.X_op = O_constant;
8210   expr1.X_op_symbol = NULL;
8211   expr1.X_add_symbol = NULL;
8212   expr1.X_add_number = 1;
8213
8214   dbl = 0;
8215
8216   switch (mask)
8217     {
8218     default:
8219       internalError ();
8220
8221     case M_DDIV_3:
8222       dbl = 1;
8223     case M_DIV_3:
8224       s = "mflo";
8225       goto do_div3;
8226     case M_DREM_3:
8227       dbl = 1;
8228     case M_REM_3:
8229       s = "mfhi";
8230     do_div3:
8231       start_noreorder ();
8232       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
8233       expr1.X_add_number = 2;
8234       macro_build (&expr1, "bnez", "x,p", yreg);
8235       macro_build (NULL, "break", "6", 7);
8236
8237       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
8238          since that causes an overflow.  We should do that as well,
8239          but I don't see how to do the comparisons without a temporary
8240          register.  */
8241       end_noreorder ();
8242       macro_build (NULL, s, "x", zreg);
8243       break;
8244
8245     case M_DIVU_3:
8246       s = "divu";
8247       s2 = "mflo";
8248       goto do_divu3;
8249     case M_REMU_3:
8250       s = "divu";
8251       s2 = "mfhi";
8252       goto do_divu3;
8253     case M_DDIVU_3:
8254       s = "ddivu";
8255       s2 = "mflo";
8256       goto do_divu3;
8257     case M_DREMU_3:
8258       s = "ddivu";
8259       s2 = "mfhi";
8260     do_divu3:
8261       start_noreorder ();
8262       macro_build (NULL, s, "0,x,y", xreg, yreg);
8263       expr1.X_add_number = 2;
8264       macro_build (&expr1, "bnez", "x,p", yreg);
8265       macro_build (NULL, "break", "6", 7);
8266       end_noreorder ();
8267       macro_build (NULL, s2, "x", zreg);
8268       break;
8269
8270     case M_DMUL:
8271       dbl = 1;
8272     case M_MUL:
8273       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
8274       macro_build (NULL, "mflo", "x", zreg);
8275       break;
8276
8277     case M_DSUBU_I:
8278       dbl = 1;
8279       goto do_subu;
8280     case M_SUBU_I:
8281     do_subu:
8282       if (imm_expr.X_op != O_constant)
8283         as_bad (_("Unsupported large constant"));
8284       imm_expr.X_add_number = -imm_expr.X_add_number;
8285       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
8286       break;
8287
8288     case M_SUBU_I_2:
8289       if (imm_expr.X_op != O_constant)
8290         as_bad (_("Unsupported large constant"));
8291       imm_expr.X_add_number = -imm_expr.X_add_number;
8292       macro_build (&imm_expr, "addiu", "x,k", xreg);
8293       break;
8294
8295     case M_DSUBU_I_2:
8296       if (imm_expr.X_op != O_constant)
8297         as_bad (_("Unsupported large constant"));
8298       imm_expr.X_add_number = -imm_expr.X_add_number;
8299       macro_build (&imm_expr, "daddiu", "y,j", yreg);
8300       break;
8301
8302     case M_BEQ:
8303       s = "cmp";
8304       s2 = "bteqz";
8305       goto do_branch;
8306     case M_BNE:
8307       s = "cmp";
8308       s2 = "btnez";
8309       goto do_branch;
8310     case M_BLT:
8311       s = "slt";
8312       s2 = "btnez";
8313       goto do_branch;
8314     case M_BLTU:
8315       s = "sltu";
8316       s2 = "btnez";
8317       goto do_branch;
8318     case M_BLE:
8319       s = "slt";
8320       s2 = "bteqz";
8321       goto do_reverse_branch;
8322     case M_BLEU:
8323       s = "sltu";
8324       s2 = "bteqz";
8325       goto do_reverse_branch;
8326     case M_BGE:
8327       s = "slt";
8328       s2 = "bteqz";
8329       goto do_branch;
8330     case M_BGEU:
8331       s = "sltu";
8332       s2 = "bteqz";
8333       goto do_branch;
8334     case M_BGT:
8335       s = "slt";
8336       s2 = "btnez";
8337       goto do_reverse_branch;
8338     case M_BGTU:
8339       s = "sltu";
8340       s2 = "btnez";
8341
8342     do_reverse_branch:
8343       tmp = xreg;
8344       xreg = yreg;
8345       yreg = tmp;
8346
8347     do_branch:
8348       macro_build (NULL, s, "x,y", xreg, yreg);
8349       macro_build (&offset_expr, s2, "p");
8350       break;
8351
8352     case M_BEQ_I:
8353       s = "cmpi";
8354       s2 = "bteqz";
8355       s3 = "x,U";
8356       goto do_branch_i;
8357     case M_BNE_I:
8358       s = "cmpi";
8359       s2 = "btnez";
8360       s3 = "x,U";
8361       goto do_branch_i;
8362     case M_BLT_I:
8363       s = "slti";
8364       s2 = "btnez";
8365       s3 = "x,8";
8366       goto do_branch_i;
8367     case M_BLTU_I:
8368       s = "sltiu";
8369       s2 = "btnez";
8370       s3 = "x,8";
8371       goto do_branch_i;
8372     case M_BLE_I:
8373       s = "slti";
8374       s2 = "btnez";
8375       s3 = "x,8";
8376       goto do_addone_branch_i;
8377     case M_BLEU_I:
8378       s = "sltiu";
8379       s2 = "btnez";
8380       s3 = "x,8";
8381       goto do_addone_branch_i;
8382     case M_BGE_I:
8383       s = "slti";
8384       s2 = "bteqz";
8385       s3 = "x,8";
8386       goto do_branch_i;
8387     case M_BGEU_I:
8388       s = "sltiu";
8389       s2 = "bteqz";
8390       s3 = "x,8";
8391       goto do_branch_i;
8392     case M_BGT_I:
8393       s = "slti";
8394       s2 = "bteqz";
8395       s3 = "x,8";
8396       goto do_addone_branch_i;
8397     case M_BGTU_I:
8398       s = "sltiu";
8399       s2 = "bteqz";
8400       s3 = "x,8";
8401
8402     do_addone_branch_i:
8403       if (imm_expr.X_op != O_constant)
8404         as_bad (_("Unsupported large constant"));
8405       ++imm_expr.X_add_number;
8406
8407     do_branch_i:
8408       macro_build (&imm_expr, s, s3, xreg);
8409       macro_build (&offset_expr, s2, "p");
8410       break;
8411
8412     case M_ABS:
8413       expr1.X_add_number = 0;
8414       macro_build (&expr1, "slti", "x,8", yreg);
8415       if (xreg != yreg)
8416         move_register (xreg, yreg);
8417       expr1.X_add_number = 2;
8418       macro_build (&expr1, "bteqz", "p");
8419       macro_build (NULL, "neg", "x,w", xreg, xreg);
8420     }
8421 }
8422
8423 /* For consistency checking, verify that all bits are specified either
8424    by the match/mask part of the instruction definition, or by the
8425    operand list.  */
8426 static int
8427 validate_mips_insn (const struct mips_opcode *opc)
8428 {
8429   const char *p = opc->args;
8430   char c;
8431   unsigned long used_bits = opc->mask;
8432
8433   if ((used_bits & opc->match) != opc->match)
8434     {
8435       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
8436               opc->name, opc->args);
8437       return 0;
8438     }
8439 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
8440   while (*p)
8441     switch (c = *p++)
8442       {
8443       case ',': break;
8444       case '(': break;
8445       case ')': break;
8446       case '+':
8447         switch (c = *p++)
8448           {
8449           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
8450           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
8451           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
8452           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
8453           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
8454           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
8455           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
8456           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
8457                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
8458           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
8459           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
8460           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
8461           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
8462           case 'I': break;
8463           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
8464           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
8465                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
8466           case 'x': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
8467           case 'X': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
8468           case 'p': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
8469           case 'P': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
8470           case 'Q': USE_BITS (OP_MASK_SEQI,     OP_SH_SEQI);    break;
8471           case 's': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
8472           case 'S': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
8473
8474           default:
8475             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
8476                     c, opc->name, opc->args);
8477             return 0;
8478           }
8479         break;
8480       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
8481       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
8482       case 'A': break;
8483       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
8484       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
8485       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
8486       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
8487       case 'F': break;
8488       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
8489       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
8490       case 'I': break;
8491       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
8492       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
8493       case 'L': break;
8494       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
8495       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
8496       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
8497       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
8498                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
8499       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
8500       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
8501       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
8502       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
8503       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
8504       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
8505       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
8506       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
8507       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
8508       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
8509       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
8510       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
8511       case 'f': break;
8512       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
8513       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
8514       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
8515       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
8516       case 'l': break;
8517       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
8518       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
8519       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
8520       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
8521       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
8522       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
8523       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
8524       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
8525       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
8526       case 'x': break;
8527       case 'z': break;
8528       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
8529       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
8530                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
8531       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
8532       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
8533       case '[': break;
8534       case ']': break;
8535       case '1': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
8536       case '2': USE_BITS (OP_MASK_BP,           OP_SH_BP);      break;
8537       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
8538       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
8539       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
8540       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
8541       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
8542       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
8543       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
8544       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
8545       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
8546       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
8547       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
8548       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
8549       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
8550       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
8551       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
8552       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
8553       default:
8554         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
8555                 c, opc->name, opc->args);
8556         return 0;
8557       }
8558 #undef USE_BITS
8559   if (used_bits != 0xffffffff)
8560     {
8561       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
8562               ~used_bits & 0xffffffff, opc->name, opc->args);
8563       return 0;
8564     }
8565   return 1;
8566 }
8567
8568 /* UDI immediates.  */
8569 struct mips_immed {
8570   char          type;
8571   unsigned int  shift;
8572   unsigned long mask;
8573   const char *  desc;
8574 };
8575
8576 static const struct mips_immed mips_immed[] = {
8577   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
8578   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
8579   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
8580   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
8581   { 0,0,0,0 }
8582 };
8583
8584 /* Check whether an odd floating-point register is allowed.  */
8585 static int
8586 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
8587 {
8588   const char *s = insn->name;
8589
8590   if (insn->pinfo == INSN_MACRO)
8591     /* Let a macro pass, we'll catch it later when it is expanded.  */
8592     return 1;
8593
8594   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa))
8595     {
8596       /* Allow odd registers for single-precision ops.  */
8597       switch (insn->pinfo & (FP_S | FP_D))
8598         {
8599         case FP_S:
8600         case 0:
8601           return 1;     /* both single precision - ok */
8602         case FP_D:
8603           return 0;     /* both double precision - fail */
8604         default:
8605           break;
8606         }
8607
8608       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
8609       s = strchr (insn->name, '.');
8610       if (argnum == 2)
8611         s = s != NULL ? strchr (s + 1, '.') : NULL;
8612       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
8613     } 
8614
8615   /* Single-precision coprocessor loads and moves are OK too.  */
8616   if ((insn->pinfo & FP_S)
8617       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
8618                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
8619     return 1;
8620
8621   return 0;
8622 }
8623
8624 /* This routine assembles an instruction into its binary format.  As a
8625    side effect, it sets one of the global variables imm_reloc or
8626    offset_reloc to the type of relocation to do if one of the operands
8627    is an address expression.  */
8628
8629 static void
8630 mips_ip (char *str, struct mips_cl_insn *ip)
8631 {
8632   char *s;
8633   const char *args;
8634   char c = 0;
8635   struct mips_opcode *insn;
8636   char *argsStart;
8637   unsigned int regno;
8638   unsigned int lastregno;
8639   unsigned int lastpos = 0;
8640   unsigned int limlo, limhi;
8641   char *s_reset;
8642   char save_c = 0;
8643   offsetT min_range, max_range;
8644   int argnum;
8645   unsigned int rtype;
8646
8647   insn_error = NULL;
8648
8649   /* If the instruction contains a '.', we first try to match an instruction
8650      including the '.'.  Then we try again without the '.'.  */
8651   insn = NULL;
8652   for (s = str; *s != '\0' && !ISSPACE (*s); ++s)
8653     continue;
8654
8655   /* If we stopped on whitespace, then replace the whitespace with null for
8656      the call to hash_find.  Save the character we replaced just in case we
8657      have to re-parse the instruction.  */
8658   if (ISSPACE (*s))
8659     {
8660       save_c = *s;
8661       *s++ = '\0';
8662     }
8663
8664   insn = (struct mips_opcode *) hash_find (op_hash, str);
8665
8666   /* If we didn't find the instruction in the opcode table, try again, but
8667      this time with just the instruction up to, but not including the
8668      first '.'.  */
8669   if (insn == NULL)
8670     {
8671       /* Restore the character we overwrite above (if any).  */
8672       if (save_c)
8673         *(--s) = save_c;
8674
8675       /* Scan up to the first '.' or whitespace.  */
8676       for (s = str;
8677            *s != '\0' && *s != '.' && !ISSPACE (*s);
8678            ++s)
8679         continue;
8680
8681       /* If we did not find a '.', then we can quit now.  */
8682       if (*s != '.')
8683         {
8684           insn_error = _("Unrecognized opcode");
8685           return;
8686         }
8687
8688       /* Lookup the instruction in the hash table.  */
8689       *s++ = '\0';
8690       if ((insn = (struct mips_opcode *) hash_find (op_hash, str)) == NULL)
8691         {
8692           insn_error = _("Unrecognized opcode");
8693           return;
8694         }
8695     }
8696
8697   argsStart = s;
8698   for (;;)
8699     {
8700       bfd_boolean ok;
8701
8702       gas_assert (strcmp (insn->name, str) == 0);
8703
8704       ok = is_opcode_valid (insn);
8705       if (! ok)
8706         {
8707           if (insn + 1 < &mips_opcodes[NUMOPCODES]
8708               && strcmp (insn->name, insn[1].name) == 0)
8709             {
8710               ++insn;
8711               continue;
8712             }
8713           else
8714             {
8715               if (!insn_error)
8716                 {
8717                   static char buf[100];
8718                   sprintf (buf,
8719                            _("opcode not supported on this processor: %s (%s)"),
8720                            mips_cpu_info_from_arch (mips_opts.arch)->name,
8721                            mips_cpu_info_from_isa (mips_opts.isa)->name);
8722                   insn_error = buf;
8723                 }
8724               if (save_c)
8725                 *(--s) = save_c;
8726               return;
8727             }
8728         }
8729
8730       create_insn (ip, insn);
8731       insn_error = NULL;
8732       argnum = 1;
8733       lastregno = 0xffffffff;
8734       for (args = insn->args;; ++args)
8735         {
8736           int is_mdmx;
8737
8738           s += strspn (s, " \t");
8739           is_mdmx = 0;
8740           switch (*args)
8741             {
8742             case '\0':          /* end of args */
8743               if (*s == '\0')
8744                 return;
8745               break;
8746
8747             case '2': /* DSP 2-bit unsigned immediate in bit 11.  */
8748               my_getExpression (&imm_expr, s);
8749               check_absolute_expr (ip, &imm_expr);
8750               if ((unsigned long) imm_expr.X_add_number != 1
8751                   && (unsigned long) imm_expr.X_add_number != 3)
8752                 {
8753                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
8754                           (unsigned long) imm_expr.X_add_number);
8755                 }
8756               INSERT_OPERAND (BP, *ip, imm_expr.X_add_number);
8757               imm_expr.X_op = O_absent;
8758               s = expr_end;
8759               continue;
8760
8761             case '3': /* DSP 3-bit unsigned immediate in bit 21.  */
8762               my_getExpression (&imm_expr, s);
8763               check_absolute_expr (ip, &imm_expr);
8764               if (imm_expr.X_add_number & ~OP_MASK_SA3)
8765                 {
8766                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8767                           OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
8768                 }
8769               INSERT_OPERAND (SA3, *ip, imm_expr.X_add_number);
8770               imm_expr.X_op = O_absent;
8771               s = expr_end;
8772               continue;
8773
8774             case '4': /* DSP 4-bit unsigned immediate in bit 21.  */
8775               my_getExpression (&imm_expr, s);
8776               check_absolute_expr (ip, &imm_expr);
8777               if (imm_expr.X_add_number & ~OP_MASK_SA4)
8778                 {
8779                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8780                           OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
8781                 }
8782               INSERT_OPERAND (SA4, *ip, imm_expr.X_add_number);
8783               imm_expr.X_op = O_absent;
8784               s = expr_end;
8785               continue;
8786
8787             case '5': /* DSP 8-bit unsigned immediate in bit 16.  */
8788               my_getExpression (&imm_expr, s);
8789               check_absolute_expr (ip, &imm_expr);
8790               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
8791                 {
8792                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8793                           OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
8794                 }
8795               INSERT_OPERAND (IMM8, *ip, imm_expr.X_add_number);
8796               imm_expr.X_op = O_absent;
8797               s = expr_end;
8798               continue;
8799
8800             case '6': /* DSP 5-bit unsigned immediate in bit 21.  */
8801               my_getExpression (&imm_expr, s);
8802               check_absolute_expr (ip, &imm_expr);
8803               if (imm_expr.X_add_number & ~OP_MASK_RS)
8804                 {
8805                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8806                           OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
8807                 }
8808               INSERT_OPERAND (RS, *ip, imm_expr.X_add_number);
8809               imm_expr.X_op = O_absent;
8810               s = expr_end;
8811               continue;
8812
8813             case '7': /* Four DSP accumulators in bits 11,12.  */
8814               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8815                   s[3] >= '0' && s[3] <= '3')
8816                 {
8817                   regno = s[3] - '0';
8818                   s += 4;
8819                   INSERT_OPERAND (DSPACC, *ip, regno);
8820                   continue;
8821                 }
8822               else
8823                 as_bad (_("Invalid dsp acc register"));
8824               break;
8825
8826             case '8': /* DSP 6-bit unsigned immediate in bit 11.  */
8827               my_getExpression (&imm_expr, s);
8828               check_absolute_expr (ip, &imm_expr);
8829               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
8830                 {
8831                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8832                           OP_MASK_WRDSP,
8833                           (unsigned long) imm_expr.X_add_number);
8834                 }
8835               INSERT_OPERAND (WRDSP, *ip, imm_expr.X_add_number);
8836               imm_expr.X_op = O_absent;
8837               s = expr_end;
8838               continue;
8839
8840             case '9': /* Four DSP accumulators in bits 21,22.  */
8841               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8842                   s[3] >= '0' && s[3] <= '3')
8843                 {
8844                   regno = s[3] - '0';
8845                   s += 4;
8846                   INSERT_OPERAND (DSPACC_S, *ip, regno);
8847                   continue;
8848                 }
8849               else
8850                 as_bad (_("Invalid dsp acc register"));
8851               break;
8852
8853             case '0': /* DSP 6-bit signed immediate in bit 20.  */
8854               my_getExpression (&imm_expr, s);
8855               check_absolute_expr (ip, &imm_expr);
8856               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
8857               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
8858               if (imm_expr.X_add_number < min_range ||
8859                   imm_expr.X_add_number > max_range)
8860                 {
8861                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
8862                           (long) min_range, (long) max_range,
8863                           (long) imm_expr.X_add_number);
8864                 }
8865               INSERT_OPERAND (DSPSFT, *ip, imm_expr.X_add_number);
8866               imm_expr.X_op = O_absent;
8867               s = expr_end;
8868               continue;
8869
8870             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
8871               my_getExpression (&imm_expr, s);
8872               check_absolute_expr (ip, &imm_expr);
8873               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
8874                 {
8875                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
8876                           OP_MASK_RDDSP,
8877                           (unsigned long) imm_expr.X_add_number);
8878                 }
8879               INSERT_OPERAND (RDDSP, *ip, imm_expr.X_add_number);
8880               imm_expr.X_op = O_absent;
8881               s = expr_end;
8882               continue;
8883
8884             case ':': /* DSP 7-bit signed immediate in bit 19.  */
8885               my_getExpression (&imm_expr, s);
8886               check_absolute_expr (ip, &imm_expr);
8887               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
8888               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
8889               if (imm_expr.X_add_number < min_range ||
8890                   imm_expr.X_add_number > max_range)
8891                 {
8892                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
8893                           (long) min_range, (long) max_range,
8894                           (long) imm_expr.X_add_number);
8895                 }
8896               INSERT_OPERAND (DSPSFT_7, *ip, imm_expr.X_add_number);
8897               imm_expr.X_op = O_absent;
8898               s = expr_end;
8899               continue;
8900
8901             case '@': /* DSP 10-bit signed immediate in bit 16.  */
8902               my_getExpression (&imm_expr, s);
8903               check_absolute_expr (ip, &imm_expr);
8904               min_range = -((OP_MASK_IMM10 + 1) >> 1);
8905               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
8906               if (imm_expr.X_add_number < min_range ||
8907                   imm_expr.X_add_number > max_range)
8908                 {
8909                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
8910                           (long) min_range, (long) max_range,
8911                           (long) imm_expr.X_add_number);
8912                 }
8913               INSERT_OPERAND (IMM10, *ip, imm_expr.X_add_number);
8914               imm_expr.X_op = O_absent;
8915               s = expr_end;
8916               continue;
8917
8918             case '!': /* MT usermode flag bit.  */
8919               my_getExpression (&imm_expr, s);
8920               check_absolute_expr (ip, &imm_expr);
8921               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
8922                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
8923                         (unsigned long) imm_expr.X_add_number);
8924               INSERT_OPERAND (MT_U, *ip, imm_expr.X_add_number);
8925               imm_expr.X_op = O_absent;
8926               s = expr_end;
8927               continue;
8928
8929             case '$': /* MT load high flag bit.  */
8930               my_getExpression (&imm_expr, s);
8931               check_absolute_expr (ip, &imm_expr);
8932               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
8933                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
8934                         (unsigned long) imm_expr.X_add_number);
8935               INSERT_OPERAND (MT_H, *ip, imm_expr.X_add_number);
8936               imm_expr.X_op = O_absent;
8937               s = expr_end;
8938               continue;
8939
8940             case '*': /* Four DSP accumulators in bits 18,19.  */
8941               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8942                   s[3] >= '0' && s[3] <= '3')
8943                 {
8944                   regno = s[3] - '0';
8945                   s += 4;
8946                   INSERT_OPERAND (MTACC_T, *ip, regno);
8947                   continue;
8948                 }
8949               else
8950                 as_bad (_("Invalid dsp/smartmips acc register"));
8951               break;
8952
8953             case '&': /* Four DSP accumulators in bits 13,14.  */
8954               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
8955                   s[3] >= '0' && s[3] <= '3')
8956                 {
8957                   regno = s[3] - '0';
8958                   s += 4;
8959                   INSERT_OPERAND (MTACC_D, *ip, regno);
8960                   continue;
8961                 }
8962               else
8963                 as_bad (_("Invalid dsp/smartmips acc register"));
8964               break;
8965
8966             case ',':
8967               ++argnum;
8968               if (*s++ == *args)
8969                 continue;
8970               s--;
8971               switch (*++args)
8972                 {
8973                 case 'r':
8974                 case 'v':
8975                   INSERT_OPERAND (RS, *ip, lastregno);
8976                   continue;
8977
8978                 case 'w':
8979                   INSERT_OPERAND (RT, *ip, lastregno);
8980                   continue;
8981
8982                 case 'W':
8983                   INSERT_OPERAND (FT, *ip, lastregno);
8984                   continue;
8985
8986                 case 'V':
8987                   INSERT_OPERAND (FS, *ip, lastregno);
8988                   continue;
8989                 }
8990               break;
8991
8992             case '(':
8993               /* Handle optional base register.
8994                  Either the base register is omitted or
8995                  we must have a left paren.  */
8996               /* This is dependent on the next operand specifier
8997                  is a base register specification.  */
8998               gas_assert (args[1] == 'b');
8999               if (*s == '\0')
9000                 return;
9001
9002             case ')':           /* These must match exactly.  */
9003             case '[':
9004             case ']':
9005               if (*s++ == *args)
9006                 continue;
9007               break;
9008
9009             case '+':           /* Opcode extension character.  */
9010               switch (*++args)
9011                 {
9012                 case '1':       /* UDI immediates.  */
9013                 case '2':
9014                 case '3':
9015                 case '4':
9016                   {
9017                     const struct mips_immed *imm = mips_immed;
9018
9019                     while (imm->type && imm->type != *args)
9020                       ++imm;
9021                     if (! imm->type)
9022                       internalError ();
9023                     my_getExpression (&imm_expr, s);
9024                     check_absolute_expr (ip, &imm_expr);
9025                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
9026                       {
9027                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
9028                                  imm->desc ? imm->desc : ip->insn_mo->name,
9029                                  (unsigned long) imm_expr.X_add_number,
9030                                  (unsigned long) imm_expr.X_add_number);
9031                         imm_expr.X_add_number &= imm->mask;
9032                       }
9033                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
9034                                         << imm->shift);
9035                     imm_expr.X_op = O_absent;
9036                     s = expr_end;
9037                   }
9038                   continue;
9039
9040                 case 'A':               /* ins/ext position, becomes LSB.  */
9041                   limlo = 0;
9042                   limhi = 31;
9043                   goto do_lsb;
9044                 case 'E':
9045                   limlo = 32;
9046                   limhi = 63;
9047                   goto do_lsb;
9048                 do_lsb:
9049                   my_getExpression (&imm_expr, s);
9050                   check_absolute_expr (ip, &imm_expr);
9051                   if ((unsigned long) imm_expr.X_add_number < limlo
9052                       || (unsigned long) imm_expr.X_add_number > limhi)
9053                     {
9054                       as_bad (_("Improper position (%lu)"),
9055                               (unsigned long) imm_expr.X_add_number);
9056                       imm_expr.X_add_number = limlo;
9057                     }
9058                   lastpos = imm_expr.X_add_number;
9059                   INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
9060                   imm_expr.X_op = O_absent;
9061                   s = expr_end;
9062                   continue;
9063
9064                 case 'B':               /* ins size, becomes MSB.  */
9065                   limlo = 1;
9066                   limhi = 32;
9067                   goto do_msb;
9068                 case 'F':
9069                   limlo = 33;
9070                   limhi = 64;
9071                   goto do_msb;
9072                 do_msb:
9073                   my_getExpression (&imm_expr, s);
9074                   check_absolute_expr (ip, &imm_expr);
9075                   /* Check for negative input so that small negative numbers
9076                      will not succeed incorrectly.  The checks against
9077                      (pos+size) transitively check "size" itself,
9078                      assuming that "pos" is reasonable.  */
9079                   if ((long) imm_expr.X_add_number < 0
9080                       || ((unsigned long) imm_expr.X_add_number
9081                           + lastpos) < limlo
9082                       || ((unsigned long) imm_expr.X_add_number
9083                           + lastpos) > limhi)
9084                     {
9085                       as_bad (_("Improper insert size (%lu, position %lu)"),
9086                               (unsigned long) imm_expr.X_add_number,
9087                               (unsigned long) lastpos);
9088                       imm_expr.X_add_number = limlo - lastpos;
9089                     }
9090                   INSERT_OPERAND (INSMSB, *ip,
9091                                  lastpos + imm_expr.X_add_number - 1);
9092                   imm_expr.X_op = O_absent;
9093                   s = expr_end;
9094                   continue;
9095
9096                 case 'C':               /* ext size, becomes MSBD.  */
9097                   limlo = 1;
9098                   limhi = 32;
9099                   goto do_msbd;
9100                 case 'G':
9101                   limlo = 33;
9102                   limhi = 64;
9103                   goto do_msbd;
9104                 case 'H':
9105                   limlo = 33;
9106                   limhi = 64;
9107                   goto do_msbd;
9108                 do_msbd:
9109                   my_getExpression (&imm_expr, s);
9110                   check_absolute_expr (ip, &imm_expr);
9111                   /* Check for negative input so that small negative numbers
9112                      will not succeed incorrectly.  The checks against
9113                      (pos+size) transitively check "size" itself,
9114                      assuming that "pos" is reasonable.  */
9115                   if ((long) imm_expr.X_add_number < 0
9116                       || ((unsigned long) imm_expr.X_add_number
9117                           + lastpos) < limlo
9118                       || ((unsigned long) imm_expr.X_add_number
9119                           + lastpos) > limhi)
9120                     {
9121                       as_bad (_("Improper extract size (%lu, position %lu)"),
9122                               (unsigned long) imm_expr.X_add_number,
9123                               (unsigned long) lastpos);
9124                       imm_expr.X_add_number = limlo - lastpos;
9125                     }
9126                   INSERT_OPERAND (EXTMSBD, *ip, imm_expr.X_add_number - 1);
9127                   imm_expr.X_op = O_absent;
9128                   s = expr_end;
9129                   continue;
9130
9131                 case 'D':
9132                   /* +D is for disassembly only; never match.  */
9133                   break;
9134
9135                 case 'I':
9136                   /* "+I" is like "I", except that imm2_expr is used.  */
9137                   my_getExpression (&imm2_expr, s);
9138                   if (imm2_expr.X_op != O_big
9139                       && imm2_expr.X_op != O_constant)
9140                   insn_error = _("absolute expression required");
9141                   if (HAVE_32BIT_GPRS)
9142                     normalize_constant_expr (&imm2_expr);
9143                   s = expr_end;
9144                   continue;
9145
9146                 case 'T': /* Coprocessor register.  */
9147                   /* +T is for disassembly only; never match.  */
9148                   break;
9149
9150                 case 't': /* Coprocessor register number.  */
9151                   if (s[0] == '$' && ISDIGIT (s[1]))
9152                     {
9153                       ++s;
9154                       regno = 0;
9155                       do
9156                         {
9157                           regno *= 10;
9158                           regno += *s - '0';
9159                           ++s;
9160                         }
9161                       while (ISDIGIT (*s));
9162                       if (regno > 31)
9163                         as_bad (_("Invalid register number (%d)"), regno);
9164                       else
9165                         {
9166                           INSERT_OPERAND (RT, *ip, regno);
9167                           continue;
9168                         }
9169                     }
9170                   else
9171                     as_bad (_("Invalid coprocessor 0 register number"));
9172                   break;
9173
9174                 case 'x':
9175                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
9176                      is not in the valid range.  */
9177                   my_getExpression (&imm_expr, s);
9178                   check_absolute_expr (ip, &imm_expr);
9179                   if ((unsigned) imm_expr.X_add_number > 31)
9180                     {
9181                       as_bad (_("Improper bit index (%lu)"),
9182                               (unsigned long) imm_expr.X_add_number);
9183                       imm_expr.X_add_number = 0;
9184                     }
9185                   INSERT_OPERAND (BBITIND, *ip, imm_expr.X_add_number);
9186                   imm_expr.X_op = O_absent;
9187                   s = expr_end;
9188                   continue;
9189
9190                 case 'X':
9191                   /* bbit[01] bit index when bbit is used but we generate
9192                      bbit[01]32 because the index is over 32.  Move to the
9193                      next candidate if index is not in the valid range.  */
9194                   my_getExpression (&imm_expr, s);
9195                   check_absolute_expr (ip, &imm_expr);
9196                   if ((unsigned) imm_expr.X_add_number < 32
9197                       || (unsigned) imm_expr.X_add_number > 63)
9198                     break;
9199                   INSERT_OPERAND (BBITIND, *ip, imm_expr.X_add_number - 32);
9200                   imm_expr.X_op = O_absent;
9201                   s = expr_end;
9202                   continue;
9203
9204                 case 'p':
9205                   /* cins, cins32, exts and exts32 position field.  Give error
9206                      if it's not in the valid range.  */
9207                   my_getExpression (&imm_expr, s);
9208                   check_absolute_expr (ip, &imm_expr);
9209                   if ((unsigned) imm_expr.X_add_number > 31)
9210                     {
9211                       as_bad (_("Improper position (%lu)"),
9212                               (unsigned long) imm_expr.X_add_number);
9213                       imm_expr.X_add_number = 0;
9214                     }
9215                   /* Make the pos explicit to simplify +S.  */
9216                   lastpos = imm_expr.X_add_number + 32;
9217                   INSERT_OPERAND (CINSPOS, *ip, imm_expr.X_add_number);
9218                   imm_expr.X_op = O_absent;
9219                   s = expr_end;
9220                   continue;
9221
9222                 case 'P':
9223                   /* cins, cins32, exts and exts32 position field.  Move to
9224                      the next candidate if it's not in the valid range.  */
9225                   my_getExpression (&imm_expr, s);
9226                   check_absolute_expr (ip, &imm_expr);
9227                   if ((unsigned) imm_expr.X_add_number < 32
9228                       || (unsigned) imm_expr.X_add_number > 63)
9229                     break;
9230                   lastpos = imm_expr.X_add_number;
9231                   INSERT_OPERAND (CINSPOS, *ip, imm_expr.X_add_number - 32);
9232                   imm_expr.X_op = O_absent;
9233                   s = expr_end;
9234                   continue;
9235
9236                 case 's':
9237                   /* cins and exts length-minus-one field.  */
9238                   my_getExpression (&imm_expr, s);
9239                   check_absolute_expr (ip, &imm_expr);
9240                   if ((unsigned long) imm_expr.X_add_number > 31)
9241                     {
9242                       as_bad (_("Improper size (%lu)"),
9243                               (unsigned long) imm_expr.X_add_number);
9244                       imm_expr.X_add_number = 0;
9245                     }
9246                   INSERT_OPERAND (CINSLM1, *ip, imm_expr.X_add_number);
9247                   imm_expr.X_op = O_absent;
9248                   s = expr_end;
9249                   continue;
9250
9251                 case 'S':
9252                   /* cins32/exts32 and cins/exts aliasing cint32/exts32
9253                      length-minus-one field.  */
9254                   my_getExpression (&imm_expr, s);
9255                   check_absolute_expr (ip, &imm_expr);
9256                   if ((long) imm_expr.X_add_number < 0
9257                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
9258                     {
9259                       as_bad (_("Improper size (%lu)"),
9260                               (unsigned long) imm_expr.X_add_number);
9261                       imm_expr.X_add_number = 0;
9262                     }
9263                   INSERT_OPERAND (CINSLM1, *ip, imm_expr.X_add_number);
9264                   imm_expr.X_op = O_absent;
9265                   s = expr_end;
9266                   continue;
9267
9268                 case 'Q':
9269                   /* seqi/snei immediate field.  */
9270                   my_getExpression (&imm_expr, s);
9271                   check_absolute_expr (ip, &imm_expr);
9272                   if ((long) imm_expr.X_add_number < -512
9273                       || (long) imm_expr.X_add_number >= 512)
9274                     {
9275                       as_bad (_("Improper immediate (%ld)"),
9276                                (long) imm_expr.X_add_number);
9277                       imm_expr.X_add_number = 0;
9278                     }
9279                   INSERT_OPERAND (SEQI, *ip, imm_expr.X_add_number);
9280                   imm_expr.X_op = O_absent;
9281                   s = expr_end;
9282                   continue;
9283
9284                 default:
9285                   as_bad (_("Internal error: bad mips opcode "
9286                             "(unknown extension operand type `+%c'): %s %s"),
9287                           *args, insn->name, insn->args);
9288                   /* Further processing is fruitless.  */
9289                   return;
9290                 }
9291               break;
9292
9293             case '<':           /* must be at least one digit */
9294               /*
9295                * According to the manual, if the shift amount is greater
9296                * than 31 or less than 0, then the shift amount should be
9297                * mod 32.  In reality the mips assembler issues an error.
9298                * We issue a warning and mask out all but the low 5 bits.
9299                */
9300               my_getExpression (&imm_expr, s);
9301               check_absolute_expr (ip, &imm_expr);
9302               if ((unsigned long) imm_expr.X_add_number > 31)
9303                 as_warn (_("Improper shift amount (%lu)"),
9304                          (unsigned long) imm_expr.X_add_number);
9305               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
9306               imm_expr.X_op = O_absent;
9307               s = expr_end;
9308               continue;
9309
9310             case '>':           /* shift amount minus 32 */
9311               my_getExpression (&imm_expr, s);
9312               check_absolute_expr (ip, &imm_expr);
9313               if ((unsigned long) imm_expr.X_add_number < 32
9314                   || (unsigned long) imm_expr.X_add_number > 63)
9315                 break;
9316               INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number - 32);
9317               imm_expr.X_op = O_absent;
9318               s = expr_end;
9319               continue;
9320
9321             case 'k':           /* CACHE code.  */
9322             case 'h':           /* PREFX code.  */
9323             case '1':           /* SYNC type.  */
9324               my_getExpression (&imm_expr, s);
9325               check_absolute_expr (ip, &imm_expr);
9326               if ((unsigned long) imm_expr.X_add_number > 31)
9327                 as_warn (_("Invalid value for `%s' (%lu)"),
9328                          ip->insn_mo->name,
9329                          (unsigned long) imm_expr.X_add_number);
9330               if (*args == 'k')
9331                 {
9332                   if (mips_fix_cn63xxp1 && strcmp ("pref", insn->name) == 0)
9333                     switch (imm_expr.X_add_number)
9334                       {
9335                       case 5:
9336                       case 25:
9337                       case 26:
9338                       case 27:
9339                       case 28:
9340                       case 29:
9341                       case 30:
9342                       case 31:  /* These are ok.  */
9343                         break;
9344
9345                       default:  /* The rest must be changed to 28.  */
9346                         imm_expr.X_add_number = 28;
9347                         break;
9348                       }
9349                   INSERT_OPERAND (CACHE, *ip, imm_expr.X_add_number);
9350                 }
9351               else if (*args == 'h')
9352                 INSERT_OPERAND (PREFX, *ip, imm_expr.X_add_number);
9353               else
9354                 INSERT_OPERAND (SHAMT, *ip, imm_expr.X_add_number);
9355               imm_expr.X_op = O_absent;
9356               s = expr_end;
9357               continue;
9358
9359             case 'c':           /* BREAK code.  */
9360               my_getExpression (&imm_expr, s);
9361               check_absolute_expr (ip, &imm_expr);
9362               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE)
9363                 as_warn (_("Code for %s not in range 0..1023 (%lu)"),
9364                          ip->insn_mo->name,
9365                          (unsigned long) imm_expr.X_add_number);
9366               INSERT_OPERAND (CODE, *ip, imm_expr.X_add_number);
9367               imm_expr.X_op = O_absent;
9368               s = expr_end;
9369               continue;
9370
9371             case 'q':           /* Lower BREAK code.  */
9372               my_getExpression (&imm_expr, s);
9373               check_absolute_expr (ip, &imm_expr);
9374               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE2)
9375                 as_warn (_("Lower code for %s not in range 0..1023 (%lu)"),
9376                          ip->insn_mo->name,
9377                          (unsigned long) imm_expr.X_add_number);
9378               INSERT_OPERAND (CODE2, *ip, imm_expr.X_add_number);
9379               imm_expr.X_op = O_absent;
9380               s = expr_end;
9381               continue;
9382
9383             case 'B':           /* 20-bit SYSCALL/BREAK code.  */
9384               my_getExpression (&imm_expr, s);
9385               check_absolute_expr (ip, &imm_expr);
9386               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE20)
9387                 as_warn (_("Code for %s not in range 0..1048575 (%lu)"),
9388                          ip->insn_mo->name,
9389                          (unsigned long) imm_expr.X_add_number);
9390               INSERT_OPERAND (CODE20, *ip, imm_expr.X_add_number);
9391               imm_expr.X_op = O_absent;
9392               s = expr_end;
9393               continue;
9394
9395             case 'C':           /* Coprocessor code.  */
9396               my_getExpression (&imm_expr, s);
9397               check_absolute_expr (ip, &imm_expr);
9398               if ((unsigned long) imm_expr.X_add_number > OP_MASK_COPZ)
9399                 {
9400                   as_warn (_("Coproccesor code > 25 bits (%lu)"),
9401                            (unsigned long) imm_expr.X_add_number);
9402                   imm_expr.X_add_number &= OP_MASK_COPZ;
9403                 }
9404               INSERT_OPERAND (COPZ, *ip, imm_expr.X_add_number);
9405               imm_expr.X_op = O_absent;
9406               s = expr_end;
9407               continue;
9408
9409             case 'J':           /* 19-bit WAIT code.  */
9410               my_getExpression (&imm_expr, s);
9411               check_absolute_expr (ip, &imm_expr);
9412               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
9413                 {
9414                   as_warn (_("Illegal 19-bit code (%lu)"),
9415                            (unsigned long) imm_expr.X_add_number);
9416                   imm_expr.X_add_number &= OP_MASK_CODE19;
9417                 }
9418               INSERT_OPERAND (CODE19, *ip, imm_expr.X_add_number);
9419               imm_expr.X_op = O_absent;
9420               s = expr_end;
9421               continue;
9422
9423             case 'P':           /* Performance register.  */
9424               my_getExpression (&imm_expr, s);
9425               check_absolute_expr (ip, &imm_expr);
9426               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
9427                 as_warn (_("Invalid performance register (%lu)"),
9428                          (unsigned long) imm_expr.X_add_number);
9429               INSERT_OPERAND (PERFREG, *ip, imm_expr.X_add_number);
9430               imm_expr.X_op = O_absent;
9431               s = expr_end;
9432               continue;
9433
9434             case 'G':           /* Coprocessor destination register.  */
9435               if (((ip->insn_opcode >> OP_SH_OP) & OP_MASK_OP) == OP_OP_COP0)
9436                 ok = reg_lookup (&s, RTYPE_NUM | RTYPE_CP0, &regno);
9437               else
9438                 ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
9439               INSERT_OPERAND (RD, *ip, regno);
9440               if (ok) 
9441                 {
9442                   lastregno = regno;
9443                   continue;
9444                 }
9445               else
9446                 break;
9447
9448             case 'b':           /* Base register.  */
9449             case 'd':           /* Destination register.  */
9450             case 's':           /* Source register.  */
9451             case 't':           /* Target register.  */
9452             case 'r':           /* Both target and source.  */
9453             case 'v':           /* Both dest and source.  */
9454             case 'w':           /* Both dest and target.  */
9455             case 'E':           /* Coprocessor target register.  */
9456             case 'K':           /* RDHWR destination register.  */
9457             case 'x':           /* Ignore register name.  */
9458             case 'z':           /* Must be zero register.  */
9459             case 'U':           /* Destination register (CLO/CLZ).  */
9460             case 'g':           /* Coprocessor destination register.  */
9461               s_reset = s;
9462               if (*args == 'E' || *args == 'K')
9463                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
9464               else
9465                 {
9466                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
9467                   if (regno == AT && mips_opts.at)
9468                     {
9469                       if (mips_opts.at == ATREG)
9470                         as_warn (_("Used $at without \".set noat\""));
9471                       else
9472                         as_warn (_("Used $%u with \".set at=$%u\""),
9473                                  regno, mips_opts.at);
9474                     }
9475                 }
9476               if (ok)
9477                 {
9478                   c = *args;
9479                   if (*s == ' ')
9480                     ++s;
9481                   if (args[1] != *s)
9482                     {
9483                       if (c == 'r' || c == 'v' || c == 'w')
9484                         {
9485                           regno = lastregno;
9486                           s = s_reset;
9487                           ++args;
9488                         }
9489                     }
9490                   /* 'z' only matches $0.  */
9491                   if (c == 'z' && regno != 0)
9492                     break;
9493
9494                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
9495                     {
9496                       if (regno == lastregno)
9497                         {
9498                           insn_error
9499                             = _("Source and destination must be different");
9500                           continue;
9501                         }
9502                       if (regno == 31 && lastregno == 0xffffffff)
9503                         {
9504                           insn_error
9505                             = _("A destination register must be supplied");
9506                           continue;
9507                         }
9508                     }
9509                   /* Now that we have assembled one operand, we use the args
9510                      string to figure out where it goes in the instruction.  */
9511                   switch (c)
9512                     {
9513                     case 'r':
9514                     case 's':
9515                     case 'v':
9516                     case 'b':
9517                       INSERT_OPERAND (RS, *ip, regno);
9518                       break;
9519                     case 'd':
9520                     case 'G':
9521                     case 'K':
9522                     case 'g':
9523                       INSERT_OPERAND (RD, *ip, regno);
9524                       break;
9525                     case 'U':
9526                       INSERT_OPERAND (RD, *ip, regno);
9527                       INSERT_OPERAND (RT, *ip, regno);
9528                       break;
9529                     case 'w':
9530                     case 't':
9531                     case 'E':
9532                       INSERT_OPERAND (RT, *ip, regno);
9533                       break;
9534                     case 'x':
9535                       /* This case exists because on the r3000 trunc
9536                          expands into a macro which requires a gp
9537                          register.  On the r6000 or r4000 it is
9538                          assembled into a single instruction which
9539                          ignores the register.  Thus the insn version
9540                          is MIPS_ISA2 and uses 'x', and the macro
9541                          version is MIPS_ISA1 and uses 't'.  */
9542                       break;
9543                     case 'z':
9544                       /* This case is for the div instruction, which
9545                          acts differently if the destination argument
9546                          is $0.  This only matches $0, and is checked
9547                          outside the switch.  */
9548                       break;
9549                     case 'D':
9550                       /* Itbl operand; not yet implemented. FIXME ?? */
9551                       break;
9552                       /* What about all other operands like 'i', which
9553                          can be specified in the opcode table? */
9554                     }
9555                   lastregno = regno;
9556                   continue;
9557                 }
9558               switch (*args++)
9559                 {
9560                 case 'r':
9561                 case 'v':
9562                   INSERT_OPERAND (RS, *ip, lastregno);
9563                   continue;
9564                 case 'w':
9565                   INSERT_OPERAND (RT, *ip, lastregno);
9566                   continue;
9567                 }
9568               break;
9569
9570             case 'O':           /* MDMX alignment immediate constant.  */
9571               my_getExpression (&imm_expr, s);
9572               check_absolute_expr (ip, &imm_expr);
9573               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
9574                 as_warn (_("Improper align amount (%ld), using low bits"),
9575                          (long) imm_expr.X_add_number);
9576               INSERT_OPERAND (ALN, *ip, imm_expr.X_add_number);
9577               imm_expr.X_op = O_absent;
9578               s = expr_end;
9579               continue;
9580
9581             case 'Q':           /* MDMX vector, element sel, or const.  */
9582               if (s[0] != '$')
9583                 {
9584                   /* MDMX Immediate.  */
9585                   my_getExpression (&imm_expr, s);
9586                   check_absolute_expr (ip, &imm_expr);
9587                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
9588                     as_warn (_("Invalid MDMX Immediate (%ld)"),
9589                              (long) imm_expr.X_add_number);
9590                   INSERT_OPERAND (FT, *ip, imm_expr.X_add_number);
9591                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
9592                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
9593                   else
9594                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
9595                   imm_expr.X_op = O_absent;
9596                   s = expr_end;
9597                   continue;
9598                 }
9599               /* Not MDMX Immediate.  Fall through.  */
9600             case 'X':           /* MDMX destination register.  */
9601             case 'Y':           /* MDMX source register.  */
9602             case 'Z':           /* MDMX target register.  */
9603               is_mdmx = 1;
9604             case 'D':           /* Floating point destination register.  */
9605             case 'S':           /* Floating point source register.  */
9606             case 'T':           /* Floating point target register.  */
9607             case 'R':           /* Floating point source register.  */
9608             case 'V':
9609             case 'W':
9610               rtype = RTYPE_FPU;
9611               if (is_mdmx
9612                   || (mips_opts.ase_mdmx
9613                       && (ip->insn_mo->pinfo & FP_D)
9614                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
9615                                                 | INSN_COPROC_MEMORY_DELAY
9616                                                 | INSN_LOAD_COPROC_DELAY
9617                                                 | INSN_LOAD_MEMORY_DELAY
9618                                                 | INSN_STORE_MEMORY))))
9619                 rtype |= RTYPE_VEC;
9620               s_reset = s;
9621               if (reg_lookup (&s, rtype, &regno))
9622                 {
9623                   if ((regno & 1) != 0
9624                       && HAVE_32BIT_FPRS
9625                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
9626                     as_warn (_("Float register should be even, was %d"),
9627                              regno);
9628
9629                   c = *args;
9630                   if (*s == ' ')
9631                     ++s;
9632                   if (args[1] != *s)
9633                     {
9634                       if (c == 'V' || c == 'W')
9635                         {
9636                           regno = lastregno;
9637                           s = s_reset;
9638                           ++args;
9639                         }
9640                     }
9641                   switch (c)
9642                     {
9643                     case 'D':
9644                     case 'X':
9645                       INSERT_OPERAND (FD, *ip, regno);
9646                       break;
9647                     case 'V':
9648                     case 'S':
9649                     case 'Y':
9650                       INSERT_OPERAND (FS, *ip, regno);
9651                       break;
9652                     case 'Q':
9653                       /* This is like 'Z', but also needs to fix the MDMX
9654                          vector/scalar select bits.  Note that the
9655                          scalar immediate case is handled above.  */
9656                       if (*s == '[')
9657                         {
9658                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
9659                           int max_el = (is_qh ? 3 : 7);
9660                           s++;
9661                           my_getExpression(&imm_expr, s);
9662                           check_absolute_expr (ip, &imm_expr);
9663                           s = expr_end;
9664                           if (imm_expr.X_add_number > max_el)
9665                             as_bad (_("Bad element selector %ld"),
9666                                     (long) imm_expr.X_add_number);
9667                           imm_expr.X_add_number &= max_el;
9668                           ip->insn_opcode |= (imm_expr.X_add_number
9669                                               << (OP_SH_VSEL +
9670                                                   (is_qh ? 2 : 1)));
9671                           imm_expr.X_op = O_absent;
9672                           if (*s != ']')
9673                             as_warn (_("Expecting ']' found '%s'"), s);
9674                           else
9675                             s++;
9676                         }
9677                       else
9678                         {
9679                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
9680                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
9681                                                 << OP_SH_VSEL);
9682                           else
9683                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
9684                                                 OP_SH_VSEL);
9685                         }
9686                       /* Fall through.  */
9687                     case 'W':
9688                     case 'T':
9689                     case 'Z':
9690                       INSERT_OPERAND (FT, *ip, regno);
9691                       break;
9692                     case 'R':
9693                       INSERT_OPERAND (FR, *ip, regno);
9694                       break;
9695                     }
9696                   lastregno = regno;
9697                   continue;
9698                 }
9699
9700               switch (*args++)
9701                 {
9702                 case 'V':
9703                   INSERT_OPERAND (FS, *ip, lastregno);
9704                   continue;
9705                 case 'W':
9706                   INSERT_OPERAND (FT, *ip, lastregno);
9707                   continue;
9708                 }
9709               break;
9710
9711             case 'I':
9712               my_getExpression (&imm_expr, s);
9713               if (imm_expr.X_op != O_big
9714                   && imm_expr.X_op != O_constant)
9715                 insn_error = _("absolute expression required");
9716               if (HAVE_32BIT_GPRS)
9717                 normalize_constant_expr (&imm_expr);
9718               s = expr_end;
9719               continue;
9720
9721             case 'A':
9722               my_getExpression (&offset_expr, s);
9723               normalize_address_expr (&offset_expr);
9724               *imm_reloc = BFD_RELOC_32;
9725               s = expr_end;
9726               continue;
9727
9728             case 'F':
9729             case 'L':
9730             case 'f':
9731             case 'l':
9732               {
9733                 int f64;
9734                 int using_gprs;
9735                 char *save_in;
9736                 char *err;
9737                 unsigned char temp[8];
9738                 int len;
9739                 unsigned int length;
9740                 segT seg;
9741                 subsegT subseg;
9742                 char *p;
9743
9744                 /* These only appear as the last operand in an
9745                    instruction, and every instruction that accepts
9746                    them in any variant accepts them in all variants.
9747                    This means we don't have to worry about backing out
9748                    any changes if the instruction does not match.
9749
9750                    The difference between them is the size of the
9751                    floating point constant and where it goes.  For 'F'
9752                    and 'L' the constant is 64 bits; for 'f' and 'l' it
9753                    is 32 bits.  Where the constant is placed is based
9754                    on how the MIPS assembler does things:
9755                     F -- .rdata
9756                     L -- .lit8
9757                     f -- immediate value
9758                     l -- .lit4
9759
9760                     The .lit4 and .lit8 sections are only used if
9761                     permitted by the -G argument.
9762
9763                     The code below needs to know whether the target register
9764                     is 32 or 64 bits wide.  It relies on the fact 'f' and
9765                     'F' are used with GPR-based instructions and 'l' and
9766                     'L' are used with FPR-based instructions.  */
9767
9768                 f64 = *args == 'F' || *args == 'L';
9769                 using_gprs = *args == 'F' || *args == 'f';
9770
9771                 save_in = input_line_pointer;
9772                 input_line_pointer = s;
9773                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
9774                 length = len;
9775                 s = input_line_pointer;
9776                 input_line_pointer = save_in;
9777                 if (err != NULL && *err != '\0')
9778                   {
9779                     as_bad (_("Bad floating point constant: %s"), err);
9780                     memset (temp, '\0', sizeof temp);
9781                     length = f64 ? 8 : 4;
9782                   }
9783
9784                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
9785
9786                 if (*args == 'f'
9787                     || (*args == 'l'
9788                         && (g_switch_value < 4
9789                             || (temp[0] == 0 && temp[1] == 0)
9790                             || (temp[2] == 0 && temp[3] == 0))))
9791                   {
9792                     imm_expr.X_op = O_constant;
9793                     if (!target_big_endian)
9794                       imm_expr.X_add_number = bfd_getl32 (temp);
9795                     else
9796                       imm_expr.X_add_number = bfd_getb32 (temp);
9797                   }
9798                 else if (length > 4
9799                          && !mips_disable_float_construction
9800                          /* Constants can only be constructed in GPRs and
9801                             copied to FPRs if the GPRs are at least as wide
9802                             as the FPRs.  Force the constant into memory if
9803                             we are using 64-bit FPRs but the GPRs are only
9804                             32 bits wide.  */
9805                          && (using_gprs
9806                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
9807                          && ((temp[0] == 0 && temp[1] == 0)
9808                              || (temp[2] == 0 && temp[3] == 0))
9809                          && ((temp[4] == 0 && temp[5] == 0)
9810                              || (temp[6] == 0 && temp[7] == 0)))
9811                   {
9812                     /* The value is simple enough to load with a couple of
9813                        instructions.  If using 32-bit registers, set
9814                        imm_expr to the high order 32 bits and offset_expr to
9815                        the low order 32 bits.  Otherwise, set imm_expr to
9816                        the entire 64 bit constant.  */
9817                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
9818                       {
9819                         imm_expr.X_op = O_constant;
9820                         offset_expr.X_op = O_constant;
9821                         if (!target_big_endian)
9822                           {
9823                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
9824                             offset_expr.X_add_number = bfd_getl32 (temp);
9825                           }
9826                         else
9827                           {
9828                             imm_expr.X_add_number = bfd_getb32 (temp);
9829                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
9830                           }
9831                         if (offset_expr.X_add_number == 0)
9832                           offset_expr.X_op = O_absent;
9833                       }
9834                     else if (sizeof (imm_expr.X_add_number) > 4)
9835                       {
9836                         imm_expr.X_op = O_constant;
9837                         if (!target_big_endian)
9838                           imm_expr.X_add_number = bfd_getl64 (temp);
9839                         else
9840                           imm_expr.X_add_number = bfd_getb64 (temp);
9841                       }
9842                     else
9843                       {
9844                         imm_expr.X_op = O_big;
9845                         imm_expr.X_add_number = 4;
9846                         if (!target_big_endian)
9847                           {
9848                             generic_bignum[0] = bfd_getl16 (temp);
9849                             generic_bignum[1] = bfd_getl16 (temp + 2);
9850                             generic_bignum[2] = bfd_getl16 (temp + 4);
9851                             generic_bignum[3] = bfd_getl16 (temp + 6);
9852                           }
9853                         else
9854                           {
9855                             generic_bignum[0] = bfd_getb16 (temp + 6);
9856                             generic_bignum[1] = bfd_getb16 (temp + 4);
9857                             generic_bignum[2] = bfd_getb16 (temp + 2);
9858                             generic_bignum[3] = bfd_getb16 (temp);
9859                           }
9860                       }
9861                   }
9862                 else
9863                   {
9864                     const char *newname;
9865                     segT new_seg;
9866
9867                     /* Switch to the right section.  */
9868                     seg = now_seg;
9869                     subseg = now_subseg;
9870                     switch (*args)
9871                       {
9872                       default: /* unused default case avoids warnings.  */
9873                       case 'L':
9874                         newname = RDATA_SECTION_NAME;
9875                         if (g_switch_value >= 8)
9876                           newname = ".lit8";
9877                         break;
9878                       case 'F':
9879                         newname = RDATA_SECTION_NAME;
9880                         break;
9881                       case 'l':
9882                         gas_assert (g_switch_value >= 4);
9883                         newname = ".lit4";
9884                         break;
9885                       }
9886                     new_seg = subseg_new (newname, (subsegT) 0);
9887                     if (IS_ELF)
9888                       bfd_set_section_flags (stdoutput, new_seg,
9889                                              (SEC_ALLOC
9890                                               | SEC_LOAD
9891                                               | SEC_READONLY
9892                                               | SEC_DATA));
9893                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
9894                     if (IS_ELF && strncmp (TARGET_OS, "elf", 3) != 0)
9895                       record_alignment (new_seg, 4);
9896                     else
9897                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
9898                     if (seg == now_seg)
9899                       as_bad (_("Can't use floating point insn in this section"));
9900
9901                     /* Set the argument to the current address in the
9902                        section.  */
9903                     offset_expr.X_op = O_symbol;
9904                     offset_expr.X_add_symbol = symbol_temp_new_now ();
9905                     offset_expr.X_add_number = 0;
9906
9907                     /* Put the floating point number into the section.  */
9908                     p = frag_more ((int) length);
9909                     memcpy (p, temp, length);
9910
9911                     /* Switch back to the original section.  */
9912                     subseg_set (seg, subseg);
9913                   }
9914               }
9915               continue;
9916
9917             case 'i':           /* 16-bit unsigned immediate.  */
9918             case 'j':           /* 16-bit signed immediate.  */
9919               *imm_reloc = BFD_RELOC_LO16;
9920               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
9921                 {
9922                   int more;
9923                   offsetT minval, maxval;
9924
9925                   more = (insn + 1 < &mips_opcodes[NUMOPCODES]
9926                           && strcmp (insn->name, insn[1].name) == 0);
9927
9928                   /* If the expression was written as an unsigned number,
9929                      only treat it as signed if there are no more
9930                      alternatives.  */
9931                   if (more
9932                       && *args == 'j'
9933                       && sizeof (imm_expr.X_add_number) <= 4
9934                       && imm_expr.X_op == O_constant
9935                       && imm_expr.X_add_number < 0
9936                       && imm_expr.X_unsigned
9937                       && HAVE_64BIT_GPRS)
9938                     break;
9939
9940                   /* For compatibility with older assemblers, we accept
9941                      0x8000-0xffff as signed 16-bit numbers when only
9942                      signed numbers are allowed.  */
9943                   if (*args == 'i')
9944                     minval = 0, maxval = 0xffff;
9945                   else if (more)
9946                     minval = -0x8000, maxval = 0x7fff;
9947                   else
9948                     minval = -0x8000, maxval = 0xffff;
9949
9950                   if (imm_expr.X_op != O_constant
9951                       || imm_expr.X_add_number < minval
9952                       || imm_expr.X_add_number > maxval)
9953                     {
9954                       if (more)
9955                         break;
9956                       if (imm_expr.X_op == O_constant
9957                           || imm_expr.X_op == O_big)
9958                         as_bad (_("Expression out of range"));
9959                     }
9960                 }
9961               s = expr_end;
9962               continue;
9963
9964             case 'o':           /* 16-bit offset.  */
9965               offset_reloc[0] = BFD_RELOC_LO16;
9966               offset_reloc[1] = BFD_RELOC_UNUSED;
9967               offset_reloc[2] = BFD_RELOC_UNUSED;
9968
9969               /* Check whether there is only a single bracketed expression
9970                  left.  If so, it must be the base register and the
9971                  constant must be zero.  */
9972               offset_reloc[0] = BFD_RELOC_LO16;
9973               offset_reloc[1] = BFD_RELOC_UNUSED;
9974               offset_reloc[2] = BFD_RELOC_UNUSED;
9975               if (*s == '(' && strchr (s + 1, '(') == 0)
9976                 {
9977                   offset_expr.X_op = O_constant;
9978                   offset_expr.X_add_number = 0;
9979                   continue;
9980                 }
9981
9982               /* If this value won't fit into a 16 bit offset, then go
9983                  find a macro that will generate the 32 bit offset
9984                  code pattern.  */
9985               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
9986                   && (offset_expr.X_op != O_constant
9987                       || offset_expr.X_add_number >= 0x8000
9988                       || offset_expr.X_add_number < -0x8000))
9989                 break;
9990
9991               s = expr_end;
9992               continue;
9993
9994             case 'p':           /* PC-relative offset.  */
9995               *offset_reloc = BFD_RELOC_16_PCREL_S2;
9996               my_getExpression (&offset_expr, s);
9997               s = expr_end;
9998               continue;
9999
10000             case 'u':           /* Upper 16 bits.  */
10001               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
10002                   && imm_expr.X_op == O_constant
10003                   && (imm_expr.X_add_number < 0
10004                       || imm_expr.X_add_number >= 0x10000))
10005                 as_bad (_("lui expression (%lu) not in range 0..65535"),
10006                         (unsigned long) imm_expr.X_add_number);
10007               s = expr_end;
10008               continue;
10009
10010             case 'a':           /* 26-bit address.  */
10011               my_getExpression (&offset_expr, s);
10012               s = expr_end;
10013               *offset_reloc = BFD_RELOC_MIPS_JMP;
10014               continue;
10015
10016             case 'N':           /* 3-bit branch condition code.  */
10017             case 'M':           /* 3-bit compare condition code.  */
10018               rtype = RTYPE_CCC;
10019               if (ip->insn_mo->pinfo & (FP_D | FP_S))
10020                 rtype |= RTYPE_FCC;
10021               if (!reg_lookup (&s, rtype, &regno))
10022                 break;
10023               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
10024                    || strcmp (str + strlen (str) - 5, "any2f") == 0
10025                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
10026                   && (regno & 1) != 0)
10027                 as_warn (_("Condition code register should be even for %s, "
10028                            "was %d"),
10029                          str, regno);
10030               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
10031                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
10032                   && (regno & 3) != 0)
10033                 as_warn (_("Condition code register should be 0 or 4 for %s, "
10034                            "was %d"),
10035                          str, regno);
10036               if (*args == 'N')
10037                 INSERT_OPERAND (BCC, *ip, regno);
10038               else
10039                 INSERT_OPERAND (CCC, *ip, regno);
10040               continue;
10041
10042             case 'H':
10043               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
10044                 s += 2;
10045               if (ISDIGIT (*s))
10046                 {
10047                   c = 0;
10048                   do
10049                     {
10050                       c *= 10;
10051                       c += *s - '0';
10052                       ++s;
10053                     }
10054                   while (ISDIGIT (*s));
10055                 }
10056               else
10057                 c = 8; /* Invalid sel value.  */
10058
10059               if (c > 7)
10060                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
10061               ip->insn_opcode |= c;
10062               continue;
10063
10064             case 'e':
10065               /* Must be at least one digit.  */
10066               my_getExpression (&imm_expr, s);
10067               check_absolute_expr (ip, &imm_expr);
10068
10069               if ((unsigned long) imm_expr.X_add_number
10070                   > (unsigned long) OP_MASK_VECBYTE)
10071                 {
10072                   as_bad (_("bad byte vector index (%ld)"),
10073                            (long) imm_expr.X_add_number);
10074                   imm_expr.X_add_number = 0;
10075                 }
10076
10077               INSERT_OPERAND (VECBYTE, *ip, imm_expr.X_add_number);
10078               imm_expr.X_op = O_absent;
10079               s = expr_end;
10080               continue;
10081
10082             case '%':
10083               my_getExpression (&imm_expr, s);
10084               check_absolute_expr (ip, &imm_expr);
10085
10086               if ((unsigned long) imm_expr.X_add_number
10087                   > (unsigned long) OP_MASK_VECALIGN)
10088                 {
10089                   as_bad (_("bad byte vector index (%ld)"),
10090                            (long) imm_expr.X_add_number);
10091                   imm_expr.X_add_number = 0;
10092                 }
10093
10094               INSERT_OPERAND (VECALIGN, *ip, imm_expr.X_add_number);
10095               imm_expr.X_op = O_absent;
10096               s = expr_end;
10097               continue;
10098
10099             default:
10100               as_bad (_("Bad char = '%c'\n"), *args);
10101               internalError ();
10102             }
10103           break;
10104         }
10105       /* Args don't match.  */
10106       if (insn + 1 < &mips_opcodes[NUMOPCODES] &&
10107           !strcmp (insn->name, insn[1].name))
10108         {
10109           ++insn;
10110           s = argsStart;
10111           insn_error = _("Illegal operands");
10112           continue;
10113         }
10114       if (save_c)
10115         *(--argsStart) = save_c;
10116       insn_error = _("Illegal operands");
10117       return;
10118     }
10119 }
10120
10121 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
10122
10123 /* This routine assembles an instruction into its binary format when
10124    assembling for the mips16.  As a side effect, it sets one of the
10125    global variables imm_reloc or offset_reloc to the type of
10126    relocation to do if one of the operands is an address expression.
10127    It also sets mips16_small and mips16_ext if the user explicitly
10128    requested a small or extended instruction.  */
10129
10130 static void
10131 mips16_ip (char *str, struct mips_cl_insn *ip)
10132 {
10133   char *s;
10134   const char *args;
10135   struct mips_opcode *insn;
10136   char *argsstart;
10137   unsigned int regno;
10138   unsigned int lastregno = 0;
10139   char *s_reset;
10140   size_t i;
10141
10142   insn_error = NULL;
10143
10144   mips16_small = FALSE;
10145   mips16_ext = FALSE;
10146
10147   for (s = str; ISLOWER (*s); ++s)
10148     ;
10149   switch (*s)
10150     {
10151     case '\0':
10152       break;
10153
10154     case ' ':
10155       *s++ = '\0';
10156       break;
10157
10158     case '.':
10159       if (s[1] == 't' && s[2] == ' ')
10160         {
10161           *s = '\0';
10162           mips16_small = TRUE;
10163           s += 3;
10164           break;
10165         }
10166       else if (s[1] == 'e' && s[2] == ' ')
10167         {
10168           *s = '\0';
10169           mips16_ext = TRUE;
10170           s += 3;
10171           break;
10172         }
10173       /* Fall through.  */
10174     default:
10175       insn_error = _("unknown opcode");
10176       return;
10177     }
10178
10179   if (mips_opts.noautoextend && ! mips16_ext)
10180     mips16_small = TRUE;
10181
10182   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
10183     {
10184       insn_error = _("unrecognized opcode");
10185       return;
10186     }
10187
10188   argsstart = s;
10189   for (;;)
10190     {
10191       bfd_boolean ok;
10192
10193       gas_assert (strcmp (insn->name, str) == 0);
10194
10195       ok = is_opcode_valid_16 (insn);
10196       if (! ok)
10197         {
10198           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
10199               && strcmp (insn->name, insn[1].name) == 0)
10200             {
10201               ++insn;
10202               continue;
10203             }
10204           else
10205             {
10206               if (!insn_error)
10207                 {
10208                   static char buf[100];
10209                   sprintf (buf,
10210                            _("opcode not supported on this processor: %s (%s)"),
10211                            mips_cpu_info_from_arch (mips_opts.arch)->name,
10212                            mips_cpu_info_from_isa (mips_opts.isa)->name);
10213                   insn_error = buf;
10214                 }
10215               return;
10216             }
10217         }
10218
10219       create_insn (ip, insn);
10220       imm_expr.X_op = O_absent;
10221       imm_reloc[0] = BFD_RELOC_UNUSED;
10222       imm_reloc[1] = BFD_RELOC_UNUSED;
10223       imm_reloc[2] = BFD_RELOC_UNUSED;
10224       imm2_expr.X_op = O_absent;
10225       offset_expr.X_op = O_absent;
10226       offset_reloc[0] = BFD_RELOC_UNUSED;
10227       offset_reloc[1] = BFD_RELOC_UNUSED;
10228       offset_reloc[2] = BFD_RELOC_UNUSED;
10229       for (args = insn->args; 1; ++args)
10230         {
10231           int c;
10232
10233           if (*s == ' ')
10234             ++s;
10235
10236           /* In this switch statement we call break if we did not find
10237              a match, continue if we did find a match, or return if we
10238              are done.  */
10239
10240           c = *args;
10241           switch (c)
10242             {
10243             case '\0':
10244               if (*s == '\0')
10245                 {
10246                   /* Stuff the immediate value in now, if we can.  */
10247                   if (imm_expr.X_op == O_constant
10248                       && *imm_reloc > BFD_RELOC_UNUSED
10249                       && *imm_reloc != BFD_RELOC_MIPS16_GOT16
10250                       && *imm_reloc != BFD_RELOC_MIPS16_CALL16
10251                       && insn->pinfo != INSN_MACRO)
10252                     {
10253                       valueT tmp;
10254
10255                       switch (*offset_reloc)
10256                         {
10257                           case BFD_RELOC_MIPS16_HI16_S:
10258                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
10259                             break;
10260
10261                           case BFD_RELOC_MIPS16_HI16:
10262                             tmp = imm_expr.X_add_number >> 16;
10263                             break;
10264
10265                           case BFD_RELOC_MIPS16_LO16:
10266                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
10267                                   - 0x8000;
10268                             break;
10269
10270                           case BFD_RELOC_UNUSED:
10271                             tmp = imm_expr.X_add_number;
10272                             break;
10273
10274                           default:
10275                             internalError ();
10276                         }
10277                       *offset_reloc = BFD_RELOC_UNUSED;
10278
10279                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
10280                                     tmp, TRUE, mips16_small,
10281                                     mips16_ext, &ip->insn_opcode,
10282                                     &ip->use_extend, &ip->extend);
10283                       imm_expr.X_op = O_absent;
10284                       *imm_reloc = BFD_RELOC_UNUSED;
10285                     }
10286
10287                   return;
10288                 }
10289               break;
10290
10291             case ',':
10292               if (*s++ == c)
10293                 continue;
10294               s--;
10295               switch (*++args)
10296                 {
10297                 case 'v':
10298                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
10299                   continue;
10300                 case 'w':
10301                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
10302                   continue;
10303                 }
10304               break;
10305
10306             case '(':
10307             case ')':
10308               if (*s++ == c)
10309                 continue;
10310               break;
10311
10312             case 'v':
10313             case 'w':
10314               if (s[0] != '$')
10315                 {
10316                   if (c == 'v')
10317                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
10318                   else
10319                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
10320                   ++args;
10321                   continue;
10322                 }
10323               /* Fall through.  */
10324             case 'x':
10325             case 'y':
10326             case 'z':
10327             case 'Z':
10328             case '0':
10329             case 'S':
10330             case 'R':
10331             case 'X':
10332             case 'Y':
10333               s_reset = s;
10334               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
10335                 {
10336                   if (c == 'v' || c == 'w')
10337                     {
10338                       if (c == 'v')
10339                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
10340                       else
10341                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
10342                       ++args;
10343                       continue;
10344                     }
10345                   break;
10346                 }
10347
10348               if (*s == ' ')
10349                 ++s;
10350               if (args[1] != *s)
10351                 {
10352                   if (c == 'v' || c == 'w')
10353                     {
10354                       regno = mips16_to_32_reg_map[lastregno];
10355                       s = s_reset;
10356                       ++args;
10357                     }
10358                 }
10359
10360               switch (c)
10361                 {
10362                 case 'x':
10363                 case 'y':
10364                 case 'z':
10365                 case 'v':
10366                 case 'w':
10367                 case 'Z':
10368                   regno = mips32_to_16_reg_map[regno];
10369                   break;
10370
10371                 case '0':
10372                   if (regno != 0)
10373                     regno = ILLEGAL_REG;
10374                   break;
10375
10376                 case 'S':
10377                   if (regno != SP)
10378                     regno = ILLEGAL_REG;
10379                   break;
10380
10381                 case 'R':
10382                   if (regno != RA)
10383                     regno = ILLEGAL_REG;
10384                   break;
10385
10386                 case 'X':
10387                 case 'Y':
10388                   if (regno == AT && mips_opts.at)
10389                     {
10390                       if (mips_opts.at == ATREG)
10391                         as_warn (_("used $at without \".set noat\""));
10392                       else
10393                         as_warn (_("used $%u with \".set at=$%u\""),
10394                                  regno, mips_opts.at);
10395                     }
10396                   break;
10397
10398                 default:
10399                   internalError ();
10400                 }
10401
10402               if (regno == ILLEGAL_REG)
10403                 break;
10404
10405               switch (c)
10406                 {
10407                 case 'x':
10408                 case 'v':
10409                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
10410                   break;
10411                 case 'y':
10412                 case 'w':
10413                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
10414                   break;
10415                 case 'z':
10416                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
10417                   break;
10418                 case 'Z':
10419                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
10420                 case '0':
10421                 case 'S':
10422                 case 'R':
10423                   break;
10424                 case 'X':
10425                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
10426                   break;
10427                 case 'Y':
10428                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
10429                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
10430                   break;
10431                 default:
10432                   internalError ();
10433                 }
10434
10435               lastregno = regno;
10436               continue;
10437
10438             case 'P':
10439               if (strncmp (s, "$pc", 3) == 0)
10440                 {
10441                   s += 3;
10442                   continue;
10443                 }
10444               break;
10445
10446             case '5':
10447             case 'H':
10448             case 'W':
10449             case 'D':
10450             case 'j':
10451             case 'V':
10452             case 'C':
10453             case 'U':
10454             case 'k':
10455             case 'K':
10456               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
10457               if (i > 0)
10458                 {
10459                   if (imm_expr.X_op != O_constant)
10460                     {
10461                       mips16_ext = TRUE;
10462                       ip->use_extend = TRUE;
10463                       ip->extend = 0;
10464                     }
10465                   else
10466                     {
10467                       /* We need to relax this instruction.  */
10468                       *offset_reloc = *imm_reloc;
10469                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
10470                     }
10471                   s = expr_end;
10472                   continue;
10473                 }
10474               *imm_reloc = BFD_RELOC_UNUSED;
10475               /* Fall through.  */
10476             case '<':
10477             case '>':
10478             case '[':
10479             case ']':
10480             case '4':
10481             case '8':
10482               my_getExpression (&imm_expr, s);
10483               if (imm_expr.X_op == O_register)
10484                 {
10485                   /* What we thought was an expression turned out to
10486                      be a register.  */
10487
10488                   if (s[0] == '(' && args[1] == '(')
10489                     {
10490                       /* It looks like the expression was omitted
10491                          before a register indirection, which means
10492                          that the expression is implicitly zero.  We
10493                          still set up imm_expr, so that we handle
10494                          explicit extensions correctly.  */
10495                       imm_expr.X_op = O_constant;
10496                       imm_expr.X_add_number = 0;
10497                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
10498                       continue;
10499                     }
10500
10501                   break;
10502                 }
10503
10504               /* We need to relax this instruction.  */
10505               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
10506               s = expr_end;
10507               continue;
10508
10509             case 'p':
10510             case 'q':
10511             case 'A':
10512             case 'B':
10513             case 'E':
10514               /* We use offset_reloc rather than imm_reloc for the PC
10515                  relative operands.  This lets macros with both
10516                  immediate and address operands work correctly.  */
10517               my_getExpression (&offset_expr, s);
10518
10519               if (offset_expr.X_op == O_register)
10520                 break;
10521
10522               /* We need to relax this instruction.  */
10523               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
10524               s = expr_end;
10525               continue;
10526
10527             case '6':           /* break code */
10528               my_getExpression (&imm_expr, s);
10529               check_absolute_expr (ip, &imm_expr);
10530               if ((unsigned long) imm_expr.X_add_number > 63)
10531                 as_warn (_("Invalid value for `%s' (%lu)"),
10532                          ip->insn_mo->name,
10533                          (unsigned long) imm_expr.X_add_number);
10534               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
10535               imm_expr.X_op = O_absent;
10536               s = expr_end;
10537               continue;
10538
10539             case 'a':           /* 26 bit address */
10540               my_getExpression (&offset_expr, s);
10541               s = expr_end;
10542               *offset_reloc = BFD_RELOC_MIPS16_JMP;
10543               ip->insn_opcode <<= 16;
10544               continue;
10545
10546             case 'l':           /* register list for entry macro */
10547             case 'L':           /* register list for exit macro */
10548               {
10549                 int mask;
10550
10551                 if (c == 'l')
10552                   mask = 0;
10553                 else
10554                   mask = 7 << 3;
10555                 while (*s != '\0')
10556                   {
10557                     unsigned int freg, reg1, reg2;
10558
10559                     while (*s == ' ' || *s == ',')
10560                       ++s;
10561                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
10562                       freg = 0;
10563                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
10564                       freg = 1;
10565                     else
10566                       {
10567                         as_bad (_("can't parse register list"));
10568                         break;
10569                       }
10570                     if (*s == ' ')
10571                       ++s;
10572                     if (*s != '-')
10573                       reg2 = reg1;
10574                     else
10575                       {
10576                         ++s;
10577                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
10578                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
10579                           {
10580                             as_bad (_("invalid register list"));
10581                             break;
10582                           }
10583                       }
10584                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
10585                       {
10586                         mask &= ~ (7 << 3);
10587                         mask |= 5 << 3;
10588                       }
10589                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
10590                       {
10591                         mask &= ~ (7 << 3);
10592                         mask |= 6 << 3;
10593                       }
10594                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
10595                       mask |= (reg2 - 3) << 3;
10596                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
10597                       mask |= (reg2 - 15) << 1;
10598                     else if (reg1 == RA && reg2 == RA)
10599                       mask |= 1;
10600                     else
10601                       {
10602                         as_bad (_("invalid register list"));
10603                         break;
10604                       }
10605                   }
10606                 /* The mask is filled in in the opcode table for the
10607                    benefit of the disassembler.  We remove it before
10608                    applying the actual mask.  */
10609                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
10610                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
10611               }
10612             continue;
10613
10614             case 'm':           /* Register list for save insn.  */
10615             case 'M':           /* Register list for restore insn.  */
10616               {
10617                 int opcode = 0;
10618                 int framesz = 0, seen_framesz = 0;
10619                 int nargs = 0, statics = 0, sregs = 0;
10620
10621                 while (*s != '\0')
10622                   {
10623                     unsigned int reg1, reg2;
10624
10625                     SKIP_SPACE_TABS (s);
10626                     while (*s == ',')
10627                       ++s;
10628                     SKIP_SPACE_TABS (s);
10629
10630                     my_getExpression (&imm_expr, s);
10631                     if (imm_expr.X_op == O_constant)
10632                       {
10633                         /* Handle the frame size.  */
10634                         if (seen_framesz)
10635                           {
10636                             as_bad (_("more than one frame size in list"));
10637                             break;
10638                           }
10639                         seen_framesz = 1;
10640                         framesz = imm_expr.X_add_number;
10641                         imm_expr.X_op = O_absent;
10642                         s = expr_end;
10643                         continue;
10644                       }
10645
10646                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
10647                       {
10648                         as_bad (_("can't parse register list"));
10649                         break;
10650                       }
10651
10652                     while (*s == ' ')
10653                       ++s;
10654
10655                     if (*s != '-')
10656                       reg2 = reg1;
10657                     else
10658                       {
10659                         ++s;
10660                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
10661                             || reg2 < reg1)
10662                           {
10663                             as_bad (_("can't parse register list"));
10664                             break;
10665                           }
10666                       }
10667
10668                     while (reg1 <= reg2)
10669                       {
10670                         if (reg1 >= 4 && reg1 <= 7)
10671                           {
10672                             if (!seen_framesz)
10673                                 /* args $a0-$a3 */
10674                                 nargs |= 1 << (reg1 - 4);
10675                             else
10676                                 /* statics $a0-$a3 */
10677                                 statics |= 1 << (reg1 - 4);
10678                           }
10679                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
10680                           {
10681                             /* $s0-$s8 */
10682                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
10683                           }
10684                         else if (reg1 == 31)
10685                           {
10686                             /* Add $ra to insn.  */
10687                             opcode |= 0x40;
10688                           }
10689                         else
10690                           {
10691                             as_bad (_("unexpected register in list"));
10692                             break;
10693                           }
10694                         if (++reg1 == 24)
10695                           reg1 = 30;
10696                       }
10697                   }
10698
10699                 /* Encode args/statics combination.  */
10700                 if (nargs & statics)
10701                   as_bad (_("arg/static registers overlap"));
10702                 else if (nargs == 0xf)
10703                   /* All $a0-$a3 are args.  */
10704                   opcode |= MIPS16_ALL_ARGS << 16;
10705                 else if (statics == 0xf)
10706                   /* All $a0-$a3 are statics.  */
10707                   opcode |= MIPS16_ALL_STATICS << 16;
10708                 else 
10709                   {
10710                     int narg = 0, nstat = 0;
10711
10712                     /* Count arg registers.  */
10713                     while (nargs & 0x1)
10714                       {
10715                         nargs >>= 1;
10716                         narg++;
10717                       }
10718                     if (nargs != 0)
10719                       as_bad (_("invalid arg register list"));
10720
10721                     /* Count static registers.  */
10722                     while (statics & 0x8)
10723                       {
10724                         statics = (statics << 1) & 0xf;
10725                         nstat++;
10726                       }
10727                     if (statics != 0) 
10728                       as_bad (_("invalid static register list"));
10729
10730                     /* Encode args/statics.  */
10731                     opcode |= ((narg << 2) | nstat) << 16;
10732                   }
10733
10734                 /* Encode $s0/$s1.  */
10735                 if (sregs & (1 << 0))           /* $s0 */
10736                   opcode |= 0x20;
10737                 if (sregs & (1 << 1))           /* $s1 */
10738                   opcode |= 0x10;
10739                 sregs >>= 2;
10740
10741                 if (sregs != 0)
10742                   {
10743                     /* Count regs $s2-$s8.  */
10744                     int nsreg = 0;
10745                     while (sregs & 1)
10746                       {
10747                         sregs >>= 1;
10748                         nsreg++;
10749                       }
10750                     if (sregs != 0)
10751                       as_bad (_("invalid static register list"));
10752                     /* Encode $s2-$s8. */
10753                     opcode |= nsreg << 24;
10754                   }
10755
10756                 /* Encode frame size.  */
10757                 if (!seen_framesz)
10758                   as_bad (_("missing frame size"));
10759                 else if ((framesz & 7) != 0 || framesz < 0
10760                          || framesz > 0xff * 8)
10761                   as_bad (_("invalid frame size"));
10762                 else if (framesz != 128 || (opcode >> 16) != 0)
10763                   {
10764                     framesz /= 8;
10765                     opcode |= (((framesz & 0xf0) << 16)
10766                              | (framesz & 0x0f));
10767                   }
10768
10769                 /* Finally build the instruction.  */
10770                 if ((opcode >> 16) != 0 || framesz == 0)
10771                   {
10772                     ip->use_extend = TRUE;
10773                     ip->extend = opcode >> 16;
10774                   }
10775                 ip->insn_opcode |= opcode & 0x7f;
10776               }
10777             continue;
10778
10779             case 'e':           /* extend code */
10780               my_getExpression (&imm_expr, s);
10781               check_absolute_expr (ip, &imm_expr);
10782               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
10783                 {
10784                   as_warn (_("Invalid value for `%s' (%lu)"),
10785                            ip->insn_mo->name,
10786                            (unsigned long) imm_expr.X_add_number);
10787                   imm_expr.X_add_number &= 0x7ff;
10788                 }
10789               ip->insn_opcode |= imm_expr.X_add_number;
10790               imm_expr.X_op = O_absent;
10791               s = expr_end;
10792               continue;
10793
10794             default:
10795               internalError ();
10796             }
10797           break;
10798         }
10799
10800       /* Args don't match.  */
10801       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
10802           strcmp (insn->name, insn[1].name) == 0)
10803         {
10804           ++insn;
10805           s = argsstart;
10806           continue;
10807         }
10808
10809       insn_error = _("illegal operands");
10810
10811       return;
10812     }
10813 }
10814
10815 /* This structure holds information we know about a mips16 immediate
10816    argument type.  */
10817
10818 struct mips16_immed_operand
10819 {
10820   /* The type code used in the argument string in the opcode table.  */
10821   int type;
10822   /* The number of bits in the short form of the opcode.  */
10823   int nbits;
10824   /* The number of bits in the extended form of the opcode.  */
10825   int extbits;
10826   /* The amount by which the short form is shifted when it is used;
10827      for example, the sw instruction has a shift count of 2.  */
10828   int shift;
10829   /* The amount by which the short form is shifted when it is stored
10830      into the instruction code.  */
10831   int op_shift;
10832   /* Non-zero if the short form is unsigned.  */
10833   int unsp;
10834   /* Non-zero if the extended form is unsigned.  */
10835   int extu;
10836   /* Non-zero if the value is PC relative.  */
10837   int pcrel;
10838 };
10839
10840 /* The mips16 immediate operand types.  */
10841
10842 static const struct mips16_immed_operand mips16_immed_operands[] =
10843 {
10844   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10845   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10846   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
10847   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
10848   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
10849   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
10850   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
10851   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
10852   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
10853   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
10854   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
10855   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
10856   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
10857   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
10858   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
10859   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
10860   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10861   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
10862   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
10863   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
10864   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
10865 };
10866
10867 #define MIPS16_NUM_IMMED \
10868   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
10869
10870 /* Handle a mips16 instruction with an immediate value.  This or's the
10871    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
10872    whether an extended value is needed; if one is needed, it sets
10873    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
10874    If SMALL is true, an unextended opcode was explicitly requested.
10875    If EXT is true, an extended opcode was explicitly requested.  If
10876    WARN is true, warn if EXT does not match reality.  */
10877
10878 static void
10879 mips16_immed (char *file, unsigned int line, int type, offsetT val,
10880               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
10881               unsigned long *insn, bfd_boolean *use_extend,
10882               unsigned short *extend)
10883 {
10884   const struct mips16_immed_operand *op;
10885   int mintiny, maxtiny;
10886   bfd_boolean needext;
10887
10888   op = mips16_immed_operands;
10889   while (op->type != type)
10890     {
10891       ++op;
10892       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
10893     }
10894
10895   if (op->unsp)
10896     {
10897       if (type == '<' || type == '>' || type == '[' || type == ']')
10898         {
10899           mintiny = 1;
10900           maxtiny = 1 << op->nbits;
10901         }
10902       else
10903         {
10904           mintiny = 0;
10905           maxtiny = (1 << op->nbits) - 1;
10906         }
10907     }
10908   else
10909     {
10910       mintiny = - (1 << (op->nbits - 1));
10911       maxtiny = (1 << (op->nbits - 1)) - 1;
10912     }
10913
10914   /* Branch offsets have an implicit 0 in the lowest bit.  */
10915   if (type == 'p' || type == 'q')
10916     val /= 2;
10917
10918   if ((val & ((1 << op->shift) - 1)) != 0
10919       || val < (mintiny << op->shift)
10920       || val > (maxtiny << op->shift))
10921     needext = TRUE;
10922   else
10923     needext = FALSE;
10924
10925   if (warn && ext && ! needext)
10926     as_warn_where (file, line,
10927                    _("extended operand requested but not required"));
10928   if (small && needext)
10929     as_bad_where (file, line, _("invalid unextended operand value"));
10930
10931   if (small || (! ext && ! needext))
10932     {
10933       int insnval;
10934
10935       *use_extend = FALSE;
10936       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
10937       insnval <<= op->op_shift;
10938       *insn |= insnval;
10939     }
10940   else
10941     {
10942       long minext, maxext;
10943       int extval;
10944
10945       if (op->extu)
10946         {
10947           minext = 0;
10948           maxext = (1 << op->extbits) - 1;
10949         }
10950       else
10951         {
10952           minext = - (1 << (op->extbits - 1));
10953           maxext = (1 << (op->extbits - 1)) - 1;
10954         }
10955       if (val < minext || val > maxext)
10956         as_bad_where (file, line,
10957                       _("operand value out of range for instruction"));
10958
10959       *use_extend = TRUE;
10960       if (op->extbits == 16)
10961         {
10962           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
10963           val &= 0x1f;
10964         }
10965       else if (op->extbits == 15)
10966         {
10967           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
10968           val &= 0xf;
10969         }
10970       else
10971         {
10972           extval = ((val & 0x1f) << 6) | (val & 0x20);
10973           val = 0;
10974         }
10975
10976       *extend = (unsigned short) extval;
10977       *insn |= val;
10978     }
10979 }
10980 \f
10981 struct percent_op_match
10982 {
10983   const char *str;
10984   bfd_reloc_code_real_type reloc;
10985 };
10986
10987 static const struct percent_op_match mips_percent_op[] =
10988 {
10989   {"%lo", BFD_RELOC_LO16},
10990 #ifdef OBJ_ELF
10991   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
10992   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
10993   {"%call16", BFD_RELOC_MIPS_CALL16},
10994   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
10995   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
10996   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
10997   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
10998   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
10999   {"%got", BFD_RELOC_MIPS_GOT16},
11000   {"%gp_rel", BFD_RELOC_GPREL16},
11001   {"%half", BFD_RELOC_16},
11002   {"%highest", BFD_RELOC_MIPS_HIGHEST},
11003   {"%higher", BFD_RELOC_MIPS_HIGHER},
11004   {"%neg", BFD_RELOC_MIPS_SUB},
11005   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
11006   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
11007   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
11008   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
11009   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
11010   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
11011   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
11012 #endif
11013   {"%hi", BFD_RELOC_HI16_S}
11014 };
11015
11016 static const struct percent_op_match mips16_percent_op[] =
11017 {
11018   {"%lo", BFD_RELOC_MIPS16_LO16},
11019   {"%gprel", BFD_RELOC_MIPS16_GPREL},
11020   {"%got", BFD_RELOC_MIPS16_GOT16},
11021   {"%call16", BFD_RELOC_MIPS16_CALL16},
11022   {"%hi", BFD_RELOC_MIPS16_HI16_S}
11023 };
11024
11025
11026 /* Return true if *STR points to a relocation operator.  When returning true,
11027    move *STR over the operator and store its relocation code in *RELOC.
11028    Leave both *STR and *RELOC alone when returning false.  */
11029
11030 static bfd_boolean
11031 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
11032 {
11033   const struct percent_op_match *percent_op;
11034   size_t limit, i;
11035
11036   if (mips_opts.mips16)
11037     {
11038       percent_op = mips16_percent_op;
11039       limit = ARRAY_SIZE (mips16_percent_op);
11040     }
11041   else
11042     {
11043       percent_op = mips_percent_op;
11044       limit = ARRAY_SIZE (mips_percent_op);
11045     }
11046
11047   for (i = 0; i < limit; i++)
11048     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
11049       {
11050         int len = strlen (percent_op[i].str);
11051
11052         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
11053           continue;
11054
11055         *str += strlen (percent_op[i].str);
11056         *reloc = percent_op[i].reloc;
11057
11058         /* Check whether the output BFD supports this relocation.
11059            If not, issue an error and fall back on something safe.  */
11060         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
11061           {
11062             as_bad (_("relocation %s isn't supported by the current ABI"),
11063                     percent_op[i].str);
11064             *reloc = BFD_RELOC_UNUSED;
11065           }
11066         return TRUE;
11067       }
11068   return FALSE;
11069 }
11070
11071
11072 /* Parse string STR as a 16-bit relocatable operand.  Store the
11073    expression in *EP and the relocations in the array starting
11074    at RELOC.  Return the number of relocation operators used.
11075
11076    On exit, EXPR_END points to the first character after the expression.  */
11077
11078 static size_t
11079 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
11080                        char *str)
11081 {
11082   bfd_reloc_code_real_type reversed_reloc[3];
11083   size_t reloc_index, i;
11084   int crux_depth, str_depth;
11085   char *crux;
11086
11087   /* Search for the start of the main expression, recoding relocations
11088      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
11089      of the main expression and with CRUX_DEPTH containing the number
11090      of open brackets at that point.  */
11091   reloc_index = -1;
11092   str_depth = 0;
11093   do
11094     {
11095       reloc_index++;
11096       crux = str;
11097       crux_depth = str_depth;
11098
11099       /* Skip over whitespace and brackets, keeping count of the number
11100          of brackets.  */
11101       while (*str == ' ' || *str == '\t' || *str == '(')
11102         if (*str++ == '(')
11103           str_depth++;
11104     }
11105   while (*str == '%'
11106          && reloc_index < (HAVE_NEWABI ? 3 : 1)
11107          && parse_relocation (&str, &reversed_reloc[reloc_index]));
11108
11109   my_getExpression (ep, crux);
11110   str = expr_end;
11111
11112   /* Match every open bracket.  */
11113   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
11114     if (*str++ == ')')
11115       crux_depth--;
11116
11117   if (crux_depth > 0)
11118     as_bad (_("unclosed '('"));
11119
11120   expr_end = str;
11121
11122   if (reloc_index != 0)
11123     {
11124       prev_reloc_op_frag = frag_now;
11125       for (i = 0; i < reloc_index; i++)
11126         reloc[i] = reversed_reloc[reloc_index - 1 - i];
11127     }
11128
11129   return reloc_index;
11130 }
11131
11132 static void
11133 my_getExpression (expressionS *ep, char *str)
11134 {
11135   char *save_in;
11136   valueT val;
11137
11138   save_in = input_line_pointer;
11139   input_line_pointer = str;
11140   expression (ep);
11141   expr_end = input_line_pointer;
11142   input_line_pointer = save_in;
11143
11144   /* If we are in mips16 mode, and this is an expression based on `.',
11145      then we bump the value of the symbol by 1 since that is how other
11146      text symbols are handled.  We don't bother to handle complex
11147      expressions, just `.' plus or minus a constant.  */
11148   if (mips_opts.mips16
11149       && ep->X_op == O_symbol
11150       && strcmp (S_GET_NAME (ep->X_add_symbol), FAKE_LABEL_NAME) == 0
11151       && S_GET_SEGMENT (ep->X_add_symbol) == now_seg
11152       && symbol_get_frag (ep->X_add_symbol) == frag_now
11153       && symbol_constant_p (ep->X_add_symbol)
11154       && (val = S_GET_VALUE (ep->X_add_symbol)) == frag_now_fix ())
11155     S_SET_VALUE (ep->X_add_symbol, val + 1);
11156 }
11157
11158 char *
11159 md_atof (int type, char *litP, int *sizeP)
11160 {
11161   return ieee_md_atof (type, litP, sizeP, target_big_endian);
11162 }
11163
11164 void
11165 md_number_to_chars (char *buf, valueT val, int n)
11166 {
11167   if (target_big_endian)
11168     number_to_chars_bigendian (buf, val, n);
11169   else
11170     number_to_chars_littleendian (buf, val, n);
11171 }
11172 \f
11173 #ifdef OBJ_ELF
11174 static int support_64bit_objects(void)
11175 {
11176   const char **list, **l;
11177   int yes;
11178
11179   list = bfd_target_list ();
11180   for (l = list; *l != NULL; l++)
11181 #ifdef TE_TMIPS
11182     /* This is traditional mips */
11183     if (strcmp (*l, "elf64-tradbigmips") == 0
11184         || strcmp (*l, "elf64-tradlittlemips") == 0)
11185 #else
11186     if (strcmp (*l, "elf64-bigmips") == 0
11187         || strcmp (*l, "elf64-littlemips") == 0)
11188 #endif
11189       break;
11190   yes = (*l != NULL);
11191   free (list);
11192   return yes;
11193 }
11194 #endif /* OBJ_ELF */
11195
11196 const char *md_shortopts = "O::g::G:";
11197
11198 enum options
11199   {
11200     OPTION_MARCH = OPTION_MD_BASE,
11201     OPTION_MTUNE,
11202     OPTION_MIPS1,
11203     OPTION_MIPS2,
11204     OPTION_MIPS3,
11205     OPTION_MIPS4,
11206     OPTION_MIPS5,
11207     OPTION_MIPS32,
11208     OPTION_MIPS64,
11209     OPTION_MIPS32R2,
11210     OPTION_MIPS64R2,
11211     OPTION_MIPS16,
11212     OPTION_NO_MIPS16,
11213     OPTION_MIPS3D,
11214     OPTION_NO_MIPS3D,
11215     OPTION_MDMX,
11216     OPTION_NO_MDMX,
11217     OPTION_DSP,
11218     OPTION_NO_DSP,
11219     OPTION_MT,
11220     OPTION_NO_MT,
11221     OPTION_SMARTMIPS,
11222     OPTION_NO_SMARTMIPS,
11223     OPTION_DSPR2,
11224     OPTION_NO_DSPR2,
11225     OPTION_COMPAT_ARCH_BASE,
11226     OPTION_M4650,
11227     OPTION_NO_M4650,
11228     OPTION_M4010,
11229     OPTION_NO_M4010,
11230     OPTION_M4100,
11231     OPTION_NO_M4100,
11232     OPTION_M3900,
11233     OPTION_NO_M3900,
11234     OPTION_M7000_HILO_FIX,
11235     OPTION_MNO_7000_HILO_FIX, 
11236     OPTION_FIX_24K,
11237     OPTION_NO_FIX_24K,
11238     OPTION_FIX_LOONGSON2F_JUMP,
11239     OPTION_NO_FIX_LOONGSON2F_JUMP,
11240     OPTION_FIX_LOONGSON2F_NOP,
11241     OPTION_NO_FIX_LOONGSON2F_NOP,
11242     OPTION_FIX_VR4120,
11243     OPTION_NO_FIX_VR4120,
11244     OPTION_FIX_VR4130,
11245     OPTION_NO_FIX_VR4130,
11246     OPTION_FIX_CN63XXP1,
11247     OPTION_NO_FIX_CN63XXP1,
11248     OPTION_TRAP,
11249     OPTION_BREAK,
11250     OPTION_EB,
11251     OPTION_EL,
11252     OPTION_FP32,
11253     OPTION_GP32,
11254     OPTION_CONSTRUCT_FLOATS,
11255     OPTION_NO_CONSTRUCT_FLOATS,
11256     OPTION_FP64,
11257     OPTION_GP64,
11258     OPTION_RELAX_BRANCH,
11259     OPTION_NO_RELAX_BRANCH,
11260     OPTION_MSHARED,
11261     OPTION_MNO_SHARED,
11262     OPTION_MSYM32,
11263     OPTION_MNO_SYM32,
11264     OPTION_SOFT_FLOAT,
11265     OPTION_HARD_FLOAT,
11266     OPTION_SINGLE_FLOAT,
11267     OPTION_DOUBLE_FLOAT,
11268     OPTION_32,
11269 #ifdef OBJ_ELF
11270     OPTION_CALL_SHARED,
11271     OPTION_CALL_NONPIC,
11272     OPTION_NON_SHARED,
11273     OPTION_XGOT,
11274     OPTION_MABI,
11275     OPTION_N32,
11276     OPTION_64,
11277     OPTION_MDEBUG,
11278     OPTION_NO_MDEBUG,
11279     OPTION_PDR,
11280     OPTION_NO_PDR,
11281     OPTION_MVXWORKS_PIC,
11282 #endif /* OBJ_ELF */
11283     OPTION_END_OF_ENUM    
11284   };
11285   
11286 struct option md_longopts[] =
11287 {
11288   /* Options which specify architecture.  */
11289   {"march", required_argument, NULL, OPTION_MARCH},
11290   {"mtune", required_argument, NULL, OPTION_MTUNE},
11291   {"mips0", no_argument, NULL, OPTION_MIPS1},
11292   {"mips1", no_argument, NULL, OPTION_MIPS1},
11293   {"mips2", no_argument, NULL, OPTION_MIPS2},
11294   {"mips3", no_argument, NULL, OPTION_MIPS3},
11295   {"mips4", no_argument, NULL, OPTION_MIPS4},
11296   {"mips5", no_argument, NULL, OPTION_MIPS5},
11297   {"mips32", no_argument, NULL, OPTION_MIPS32},
11298   {"mips64", no_argument, NULL, OPTION_MIPS64},
11299   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
11300   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
11301
11302   /* Options which specify Application Specific Extensions (ASEs).  */
11303   {"mips16", no_argument, NULL, OPTION_MIPS16},
11304   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
11305   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
11306   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
11307   {"mdmx", no_argument, NULL, OPTION_MDMX},
11308   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
11309   {"mdsp", no_argument, NULL, OPTION_DSP},
11310   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
11311   {"mmt", no_argument, NULL, OPTION_MT},
11312   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
11313   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
11314   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
11315   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
11316   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
11317
11318   /* Old-style architecture options.  Don't add more of these.  */
11319   {"m4650", no_argument, NULL, OPTION_M4650},
11320   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
11321   {"m4010", no_argument, NULL, OPTION_M4010},
11322   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
11323   {"m4100", no_argument, NULL, OPTION_M4100},
11324   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
11325   {"m3900", no_argument, NULL, OPTION_M3900},
11326   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
11327
11328   /* Options which enable bug fixes.  */
11329   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
11330   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
11331   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
11332   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
11333   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
11334   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
11335   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
11336   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
11337   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
11338   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
11339   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
11340   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
11341   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
11342   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
11343   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
11344
11345   /* Miscellaneous options.  */
11346   {"trap", no_argument, NULL, OPTION_TRAP},
11347   {"no-break", no_argument, NULL, OPTION_TRAP},
11348   {"break", no_argument, NULL, OPTION_BREAK},
11349   {"no-trap", no_argument, NULL, OPTION_BREAK},
11350   {"EB", no_argument, NULL, OPTION_EB},
11351   {"EL", no_argument, NULL, OPTION_EL},
11352   {"mfp32", no_argument, NULL, OPTION_FP32},
11353   {"mgp32", no_argument, NULL, OPTION_GP32},
11354   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
11355   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
11356   {"mfp64", no_argument, NULL, OPTION_FP64},
11357   {"mgp64", no_argument, NULL, OPTION_GP64},
11358   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
11359   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
11360   {"mshared", no_argument, NULL, OPTION_MSHARED},
11361   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
11362   {"msym32", no_argument, NULL, OPTION_MSYM32},
11363   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
11364   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
11365   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
11366   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
11367   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
11368
11369   /* Strictly speaking this next option is ELF specific,
11370      but we allow it for other ports as well in order to
11371      make testing easier.  */
11372   {"32",          no_argument, NULL, OPTION_32},
11373   
11374   /* ELF-specific options.  */
11375 #ifdef OBJ_ELF
11376   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
11377   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
11378   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
11379   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
11380   {"xgot",        no_argument, NULL, OPTION_XGOT},
11381   {"mabi", required_argument, NULL, OPTION_MABI},
11382   {"n32",         no_argument, NULL, OPTION_N32},
11383   {"64",          no_argument, NULL, OPTION_64},
11384   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
11385   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
11386   {"mpdr", no_argument, NULL, OPTION_PDR},
11387   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
11388   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
11389 #endif /* OBJ_ELF */
11390
11391   {NULL, no_argument, NULL, 0}
11392 };
11393 size_t md_longopts_size = sizeof (md_longopts);
11394
11395 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
11396    NEW_VALUE.  Warn if another value was already specified.  Note:
11397    we have to defer parsing the -march and -mtune arguments in order
11398    to handle 'from-abi' correctly, since the ABI might be specified
11399    in a later argument.  */
11400
11401 static void
11402 mips_set_option_string (const char **string_ptr, const char *new_value)
11403 {
11404   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
11405     as_warn (_("A different %s was already specified, is now %s"),
11406              string_ptr == &mips_arch_string ? "-march" : "-mtune",
11407              new_value);
11408
11409   *string_ptr = new_value;
11410 }
11411
11412 int
11413 md_parse_option (int c, char *arg)
11414 {
11415   switch (c)
11416     {
11417     case OPTION_CONSTRUCT_FLOATS:
11418       mips_disable_float_construction = 0;
11419       break;
11420
11421     case OPTION_NO_CONSTRUCT_FLOATS:
11422       mips_disable_float_construction = 1;
11423       break;
11424
11425     case OPTION_TRAP:
11426       mips_trap = 1;
11427       break;
11428
11429     case OPTION_BREAK:
11430       mips_trap = 0;
11431       break;
11432
11433     case OPTION_EB:
11434       target_big_endian = 1;
11435       break;
11436
11437     case OPTION_EL:
11438       target_big_endian = 0;
11439       break;
11440
11441     case 'O':
11442       if (arg == NULL)
11443         mips_optimize = 1;
11444       else if (arg[0] == '0')
11445         mips_optimize = 0;
11446       else if (arg[0] == '1')
11447         mips_optimize = 1;
11448       else
11449         mips_optimize = 2;
11450       break;
11451
11452     case 'g':
11453       if (arg == NULL)
11454         mips_debug = 2;
11455       else
11456         mips_debug = atoi (arg);
11457       break;
11458
11459     case OPTION_MIPS1:
11460       file_mips_isa = ISA_MIPS1;
11461       break;
11462
11463     case OPTION_MIPS2:
11464       file_mips_isa = ISA_MIPS2;
11465       break;
11466
11467     case OPTION_MIPS3:
11468       file_mips_isa = ISA_MIPS3;
11469       break;
11470
11471     case OPTION_MIPS4:
11472       file_mips_isa = ISA_MIPS4;
11473       break;
11474
11475     case OPTION_MIPS5:
11476       file_mips_isa = ISA_MIPS5;
11477       break;
11478
11479     case OPTION_MIPS32:
11480       file_mips_isa = ISA_MIPS32;
11481       break;
11482
11483     case OPTION_MIPS32R2:
11484       file_mips_isa = ISA_MIPS32R2;
11485       break;
11486
11487     case OPTION_MIPS64R2:
11488       file_mips_isa = ISA_MIPS64R2;
11489       break;
11490
11491     case OPTION_MIPS64:
11492       file_mips_isa = ISA_MIPS64;
11493       break;
11494
11495     case OPTION_MTUNE:
11496       mips_set_option_string (&mips_tune_string, arg);
11497       break;
11498
11499     case OPTION_MARCH:
11500       mips_set_option_string (&mips_arch_string, arg);
11501       break;
11502
11503     case OPTION_M4650:
11504       mips_set_option_string (&mips_arch_string, "4650");
11505       mips_set_option_string (&mips_tune_string, "4650");
11506       break;
11507
11508     case OPTION_NO_M4650:
11509       break;
11510
11511     case OPTION_M4010:
11512       mips_set_option_string (&mips_arch_string, "4010");
11513       mips_set_option_string (&mips_tune_string, "4010");
11514       break;
11515
11516     case OPTION_NO_M4010:
11517       break;
11518
11519     case OPTION_M4100:
11520       mips_set_option_string (&mips_arch_string, "4100");
11521       mips_set_option_string (&mips_tune_string, "4100");
11522       break;
11523
11524     case OPTION_NO_M4100:
11525       break;
11526
11527     case OPTION_M3900:
11528       mips_set_option_string (&mips_arch_string, "3900");
11529       mips_set_option_string (&mips_tune_string, "3900");
11530       break;
11531
11532     case OPTION_NO_M3900:
11533       break;
11534
11535     case OPTION_MDMX:
11536       mips_opts.ase_mdmx = 1;
11537       break;
11538
11539     case OPTION_NO_MDMX:
11540       mips_opts.ase_mdmx = 0;
11541       break;
11542
11543     case OPTION_DSP:
11544       mips_opts.ase_dsp = 1;
11545       mips_opts.ase_dspr2 = 0;
11546       break;
11547
11548     case OPTION_NO_DSP:
11549       mips_opts.ase_dsp = 0;
11550       mips_opts.ase_dspr2 = 0;
11551       break;
11552
11553     case OPTION_DSPR2:
11554       mips_opts.ase_dspr2 = 1;
11555       mips_opts.ase_dsp = 1;
11556       break;
11557
11558     case OPTION_NO_DSPR2:
11559       mips_opts.ase_dspr2 = 0;
11560       mips_opts.ase_dsp = 0;
11561       break;
11562
11563     case OPTION_MT:
11564       mips_opts.ase_mt = 1;
11565       break;
11566
11567     case OPTION_NO_MT:
11568       mips_opts.ase_mt = 0;
11569       break;
11570
11571     case OPTION_MIPS16:
11572       mips_opts.mips16 = 1;
11573       mips_no_prev_insn ();
11574       break;
11575
11576     case OPTION_NO_MIPS16:
11577       mips_opts.mips16 = 0;
11578       mips_no_prev_insn ();
11579       break;
11580
11581     case OPTION_MIPS3D:
11582       mips_opts.ase_mips3d = 1;
11583       break;
11584
11585     case OPTION_NO_MIPS3D:
11586       mips_opts.ase_mips3d = 0;
11587       break;
11588
11589     case OPTION_SMARTMIPS:
11590       mips_opts.ase_smartmips = 1;
11591       break;
11592
11593     case OPTION_NO_SMARTMIPS:
11594       mips_opts.ase_smartmips = 0;
11595       break;
11596
11597     case OPTION_FIX_24K:
11598       mips_fix_24k = 1;
11599       break;
11600
11601     case OPTION_NO_FIX_24K:
11602       mips_fix_24k = 0;
11603       break;
11604
11605     case OPTION_FIX_LOONGSON2F_JUMP:
11606       mips_fix_loongson2f_jump = TRUE;
11607       break;
11608
11609     case OPTION_NO_FIX_LOONGSON2F_JUMP:
11610       mips_fix_loongson2f_jump = FALSE;
11611       break;
11612
11613     case OPTION_FIX_LOONGSON2F_NOP:
11614       mips_fix_loongson2f_nop = TRUE;
11615       break;
11616
11617     case OPTION_NO_FIX_LOONGSON2F_NOP:
11618       mips_fix_loongson2f_nop = FALSE;
11619       break;
11620
11621     case OPTION_FIX_VR4120:
11622       mips_fix_vr4120 = 1;
11623       break;
11624
11625     case OPTION_NO_FIX_VR4120:
11626       mips_fix_vr4120 = 0;
11627       break;
11628
11629     case OPTION_FIX_VR4130:
11630       mips_fix_vr4130 = 1;
11631       break;
11632
11633     case OPTION_NO_FIX_VR4130:
11634       mips_fix_vr4130 = 0;
11635       break;
11636
11637     case OPTION_FIX_CN63XXP1:
11638       mips_fix_cn63xxp1 = TRUE;
11639       break;
11640
11641     case OPTION_NO_FIX_CN63XXP1:
11642       mips_fix_cn63xxp1 = FALSE;
11643       break;
11644
11645     case OPTION_RELAX_BRANCH:
11646       mips_relax_branch = 1;
11647       break;
11648
11649     case OPTION_NO_RELAX_BRANCH:
11650       mips_relax_branch = 0;
11651       break;
11652
11653     case OPTION_MSHARED:
11654       mips_in_shared = TRUE;
11655       break;
11656
11657     case OPTION_MNO_SHARED:
11658       mips_in_shared = FALSE;
11659       break;
11660
11661     case OPTION_MSYM32:
11662       mips_opts.sym32 = TRUE;
11663       break;
11664
11665     case OPTION_MNO_SYM32:
11666       mips_opts.sym32 = FALSE;
11667       break;
11668
11669 #ifdef OBJ_ELF
11670       /* When generating ELF code, we permit -KPIC and -call_shared to
11671          select SVR4_PIC, and -non_shared to select no PIC.  This is
11672          intended to be compatible with Irix 5.  */
11673     case OPTION_CALL_SHARED:
11674       if (!IS_ELF)
11675         {
11676           as_bad (_("-call_shared is supported only for ELF format"));
11677           return 0;
11678         }
11679       mips_pic = SVR4_PIC;
11680       mips_abicalls = TRUE;
11681       break;
11682
11683     case OPTION_CALL_NONPIC:
11684       if (!IS_ELF)
11685         {
11686           as_bad (_("-call_nonpic is supported only for ELF format"));
11687           return 0;
11688         }
11689       mips_pic = NO_PIC;
11690       mips_abicalls = TRUE;
11691       break;
11692
11693     case OPTION_NON_SHARED:
11694       if (!IS_ELF)
11695         {
11696           as_bad (_("-non_shared is supported only for ELF format"));
11697           return 0;
11698         }
11699       mips_pic = NO_PIC;
11700       mips_abicalls = FALSE;
11701       break;
11702
11703       /* The -xgot option tells the assembler to use 32 bit offsets
11704          when accessing the got in SVR4_PIC mode.  It is for Irix
11705          compatibility.  */
11706     case OPTION_XGOT:
11707       mips_big_got = 1;
11708       break;
11709 #endif /* OBJ_ELF */
11710
11711     case 'G':
11712       g_switch_value = atoi (arg);
11713       g_switch_seen = 1;
11714       break;
11715
11716       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
11717          and -mabi=64.  */
11718     case OPTION_32:
11719       if (IS_ELF)
11720         mips_abi = O32_ABI;
11721       /* We silently ignore -32 for non-ELF targets.  This greatly
11722          simplifies the construction of the MIPS GAS test cases.  */
11723       break;
11724
11725 #ifdef OBJ_ELF
11726     case OPTION_N32:
11727       if (!IS_ELF)
11728         {
11729           as_bad (_("-n32 is supported for ELF format only"));
11730           return 0;
11731         }
11732       mips_abi = N32_ABI;
11733       break;
11734
11735     case OPTION_64:
11736       if (!IS_ELF)
11737         {
11738           as_bad (_("-64 is supported for ELF format only"));
11739           return 0;
11740         }
11741       mips_abi = N64_ABI;
11742       if (!support_64bit_objects())
11743         as_fatal (_("No compiled in support for 64 bit object file format"));
11744       break;
11745 #endif /* OBJ_ELF */
11746
11747     case OPTION_GP32:
11748       file_mips_gp32 = 1;
11749       break;
11750
11751     case OPTION_GP64:
11752       file_mips_gp32 = 0;
11753       break;
11754
11755     case OPTION_FP32:
11756       file_mips_fp32 = 1;
11757       break;
11758
11759     case OPTION_FP64:
11760       file_mips_fp32 = 0;
11761       break;
11762
11763     case OPTION_SINGLE_FLOAT:
11764       file_mips_single_float = 1;
11765       break;
11766
11767     case OPTION_DOUBLE_FLOAT:
11768       file_mips_single_float = 0;
11769       break;
11770
11771     case OPTION_SOFT_FLOAT:
11772       file_mips_soft_float = 1;
11773       break;
11774
11775     case OPTION_HARD_FLOAT:
11776       file_mips_soft_float = 0;
11777       break;
11778
11779 #ifdef OBJ_ELF
11780     case OPTION_MABI:
11781       if (!IS_ELF)
11782         {
11783           as_bad (_("-mabi is supported for ELF format only"));
11784           return 0;
11785         }
11786       if (strcmp (arg, "32") == 0)
11787         mips_abi = O32_ABI;
11788       else if (strcmp (arg, "o64") == 0)
11789         mips_abi = O64_ABI;
11790       else if (strcmp (arg, "n32") == 0)
11791         mips_abi = N32_ABI;
11792       else if (strcmp (arg, "64") == 0)
11793         {
11794           mips_abi = N64_ABI;
11795           if (! support_64bit_objects())
11796             as_fatal (_("No compiled in support for 64 bit object file "
11797                         "format"));
11798         }
11799       else if (strcmp (arg, "eabi") == 0)
11800         mips_abi = EABI_ABI;
11801       else
11802         {
11803           as_fatal (_("invalid abi -mabi=%s"), arg);
11804           return 0;
11805         }
11806       break;
11807 #endif /* OBJ_ELF */
11808
11809     case OPTION_M7000_HILO_FIX:
11810       mips_7000_hilo_fix = TRUE;
11811       break;
11812
11813     case OPTION_MNO_7000_HILO_FIX:
11814       mips_7000_hilo_fix = FALSE;
11815       break;
11816
11817 #ifdef OBJ_ELF
11818     case OPTION_MDEBUG:
11819       mips_flag_mdebug = TRUE;
11820       break;
11821
11822     case OPTION_NO_MDEBUG:
11823       mips_flag_mdebug = FALSE;
11824       break;
11825
11826     case OPTION_PDR:
11827       mips_flag_pdr = TRUE;
11828       break;
11829
11830     case OPTION_NO_PDR:
11831       mips_flag_pdr = FALSE;
11832       break;
11833
11834     case OPTION_MVXWORKS_PIC:
11835       mips_pic = VXWORKS_PIC;
11836       break;
11837 #endif /* OBJ_ELF */
11838
11839     default:
11840       return 0;
11841     }
11842
11843     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
11844
11845   return 1;
11846 }
11847 \f
11848 /* Set up globals to generate code for the ISA or processor
11849    described by INFO.  */
11850
11851 static void
11852 mips_set_architecture (const struct mips_cpu_info *info)
11853 {
11854   if (info != 0)
11855     {
11856       file_mips_arch = info->cpu;
11857       mips_opts.arch = info->cpu;
11858       mips_opts.isa = info->isa;
11859     }
11860 }
11861
11862
11863 /* Likewise for tuning.  */
11864
11865 static void
11866 mips_set_tune (const struct mips_cpu_info *info)
11867 {
11868   if (info != 0)
11869     mips_tune = info->cpu;
11870 }
11871
11872
11873 void
11874 mips_after_parse_args (void)
11875 {
11876   const struct mips_cpu_info *arch_info = 0;
11877   const struct mips_cpu_info *tune_info = 0;
11878
11879   /* GP relative stuff not working for PE */
11880   if (strncmp (TARGET_OS, "pe", 2) == 0)
11881     {
11882       if (g_switch_seen && g_switch_value != 0)
11883         as_bad (_("-G not supported in this configuration."));
11884       g_switch_value = 0;
11885     }
11886
11887   if (mips_abi == NO_ABI)
11888     mips_abi = MIPS_DEFAULT_ABI;
11889
11890   /* The following code determines the architecture and register size.
11891      Similar code was added to GCC 3.3 (see override_options() in
11892      config/mips/mips.c).  The GAS and GCC code should be kept in sync
11893      as much as possible.  */
11894
11895   if (mips_arch_string != 0)
11896     arch_info = mips_parse_cpu ("-march", mips_arch_string);
11897
11898   if (file_mips_isa != ISA_UNKNOWN)
11899     {
11900       /* Handle -mipsN.  At this point, file_mips_isa contains the
11901          ISA level specified by -mipsN, while arch_info->isa contains
11902          the -march selection (if any).  */
11903       if (arch_info != 0)
11904         {
11905           /* -march takes precedence over -mipsN, since it is more descriptive.
11906              There's no harm in specifying both as long as the ISA levels
11907              are the same.  */
11908           if (file_mips_isa != arch_info->isa)
11909             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
11910                     mips_cpu_info_from_isa (file_mips_isa)->name,
11911                     mips_cpu_info_from_isa (arch_info->isa)->name);
11912         }
11913       else
11914         arch_info = mips_cpu_info_from_isa (file_mips_isa);
11915     }
11916
11917   if (arch_info == 0)
11918     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
11919
11920   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
11921     as_bad (_("-march=%s is not compatible with the selected ABI"),
11922             arch_info->name);
11923
11924   mips_set_architecture (arch_info);
11925
11926   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
11927   if (mips_tune_string != 0)
11928     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
11929
11930   if (tune_info == 0)
11931     mips_set_tune (arch_info);
11932   else
11933     mips_set_tune (tune_info);
11934
11935   if (file_mips_gp32 >= 0)
11936     {
11937       /* The user specified the size of the integer registers.  Make sure
11938          it agrees with the ABI and ISA.  */
11939       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
11940         as_bad (_("-mgp64 used with a 32-bit processor"));
11941       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
11942         as_bad (_("-mgp32 used with a 64-bit ABI"));
11943       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
11944         as_bad (_("-mgp64 used with a 32-bit ABI"));
11945     }
11946   else
11947     {
11948       /* Infer the integer register size from the ABI and processor.
11949          Restrict ourselves to 32-bit registers if that's all the
11950          processor has, or if the ABI cannot handle 64-bit registers.  */
11951       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
11952                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
11953     }
11954
11955   switch (file_mips_fp32)
11956     {
11957     default:
11958     case -1:
11959       /* No user specified float register size.
11960          ??? GAS treats single-float processors as though they had 64-bit
11961          float registers (although it complains when double-precision
11962          instructions are used).  As things stand, saying they have 32-bit
11963          registers would lead to spurious "register must be even" messages.
11964          So here we assume float registers are never smaller than the
11965          integer ones.  */
11966       if (file_mips_gp32 == 0)
11967         /* 64-bit integer registers implies 64-bit float registers.  */
11968         file_mips_fp32 = 0;
11969       else if ((mips_opts.ase_mips3d > 0 || mips_opts.ase_mdmx > 0)
11970                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
11971         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
11972         file_mips_fp32 = 0;
11973       else
11974         /* 32-bit float registers.  */
11975         file_mips_fp32 = 1;
11976       break;
11977
11978     /* The user specified the size of the float registers.  Check if it
11979        agrees with the ABI and ISA.  */
11980     case 0:
11981       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
11982         as_bad (_("-mfp64 used with a 32-bit fpu"));
11983       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
11984                && !ISA_HAS_MXHC1 (mips_opts.isa))
11985         as_warn (_("-mfp64 used with a 32-bit ABI"));
11986       break;
11987     case 1:
11988       if (ABI_NEEDS_64BIT_REGS (mips_abi))
11989         as_warn (_("-mfp32 used with a 64-bit ABI"));
11990       break;
11991     }
11992
11993   /* End of GCC-shared inference code.  */
11994
11995   /* This flag is set when we have a 64-bit capable CPU but use only
11996      32-bit wide registers.  Note that EABI does not use it.  */
11997   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
11998       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
11999           || mips_abi == O32_ABI))
12000     mips_32bitmode = 1;
12001
12002   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
12003     as_bad (_("trap exception not supported at ISA 1"));
12004
12005   /* If the selected architecture includes support for ASEs, enable
12006      generation of code for them.  */
12007   if (mips_opts.mips16 == -1)
12008     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
12009   if (mips_opts.ase_mips3d == -1)
12010     mips_opts.ase_mips3d = ((arch_info->flags & MIPS_CPU_ASE_MIPS3D)
12011                             && file_mips_fp32 == 0) ? 1 : 0;
12012   if (mips_opts.ase_mips3d && file_mips_fp32 == 1)
12013     as_bad (_("-mfp32 used with -mips3d"));
12014
12015   if (mips_opts.ase_mdmx == -1)
12016     mips_opts.ase_mdmx = ((arch_info->flags & MIPS_CPU_ASE_MDMX)
12017                           && file_mips_fp32 == 0) ? 1 : 0;
12018   if (mips_opts.ase_mdmx && file_mips_fp32 == 1)
12019     as_bad (_("-mfp32 used with -mdmx"));
12020
12021   if (mips_opts.ase_smartmips == -1)
12022     mips_opts.ase_smartmips = (arch_info->flags & MIPS_CPU_ASE_SMARTMIPS) ? 1 : 0;
12023   if (mips_opts.ase_smartmips && !ISA_SUPPORTS_SMARTMIPS)
12024     as_warn (_("%s ISA does not support SmartMIPS"), 
12025              mips_cpu_info_from_isa (mips_opts.isa)->name);
12026
12027   if (mips_opts.ase_dsp == -1)
12028     mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
12029   if (mips_opts.ase_dsp && !ISA_SUPPORTS_DSP_ASE)
12030     as_warn (_("%s ISA does not support DSP ASE"), 
12031              mips_cpu_info_from_isa (mips_opts.isa)->name);
12032
12033   if (mips_opts.ase_dspr2 == -1)
12034     {
12035       mips_opts.ase_dspr2 = (arch_info->flags & MIPS_CPU_ASE_DSPR2) ? 1 : 0;
12036       mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
12037     }
12038   if (mips_opts.ase_dspr2 && !ISA_SUPPORTS_DSPR2_ASE)
12039     as_warn (_("%s ISA does not support DSP R2 ASE"),
12040              mips_cpu_info_from_isa (mips_opts.isa)->name);
12041
12042   if (mips_opts.ase_mt == -1)
12043     mips_opts.ase_mt = (arch_info->flags & MIPS_CPU_ASE_MT) ? 1 : 0;
12044   if (mips_opts.ase_mt && !ISA_SUPPORTS_MT_ASE)
12045     as_warn (_("%s ISA does not support MT ASE"),
12046              mips_cpu_info_from_isa (mips_opts.isa)->name);
12047
12048   file_mips_isa = mips_opts.isa;
12049   file_ase_mips3d = mips_opts.ase_mips3d;
12050   file_ase_mdmx = mips_opts.ase_mdmx;
12051   file_ase_smartmips = mips_opts.ase_smartmips;
12052   file_ase_dsp = mips_opts.ase_dsp;
12053   file_ase_dspr2 = mips_opts.ase_dspr2;
12054   file_ase_mt = mips_opts.ase_mt;
12055   mips_opts.gp32 = file_mips_gp32;
12056   mips_opts.fp32 = file_mips_fp32;
12057   mips_opts.soft_float = file_mips_soft_float;
12058   mips_opts.single_float = file_mips_single_float;
12059
12060   if (mips_flag_mdebug < 0)
12061     {
12062 #ifdef OBJ_MAYBE_ECOFF
12063       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
12064         mips_flag_mdebug = 1;
12065       else
12066 #endif /* OBJ_MAYBE_ECOFF */
12067         mips_flag_mdebug = 0;
12068     }
12069 }
12070 \f
12071 void
12072 mips_init_after_args (void)
12073 {
12074   /* initialize opcodes */
12075   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
12076   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
12077 }
12078
12079 long
12080 md_pcrel_from (fixS *fixP)
12081 {
12082   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
12083   switch (fixP->fx_r_type)
12084     {
12085     case BFD_RELOC_16_PCREL_S2:
12086     case BFD_RELOC_MIPS_JMP:
12087       /* Return the address of the delay slot.  */
12088       return addr + 4;
12089     default:
12090       /* We have no relocation type for PC relative MIPS16 instructions.  */
12091       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
12092         as_bad_where (fixP->fx_file, fixP->fx_line,
12093                       _("PC relative MIPS16 instruction references a different section"));
12094       return addr;
12095     }
12096 }
12097
12098 /* This is called before the symbol table is processed.  In order to
12099    work with gcc when using mips-tfile, we must keep all local labels.
12100    However, in other cases, we want to discard them.  If we were
12101    called with -g, but we didn't see any debugging information, it may
12102    mean that gcc is smuggling debugging information through to
12103    mips-tfile, in which case we must generate all local labels.  */
12104
12105 void
12106 mips_frob_file_before_adjust (void)
12107 {
12108 #ifndef NO_ECOFF_DEBUGGING
12109   if (ECOFF_DEBUGGING
12110       && mips_debug != 0
12111       && ! ecoff_debugging_seen)
12112     flag_keep_locals = 1;
12113 #endif
12114 }
12115
12116 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
12117    the corresponding LO16 reloc.  This is called before md_apply_fix and
12118    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
12119    relocation operators.
12120
12121    For our purposes, a %lo() expression matches a %got() or %hi()
12122    expression if:
12123
12124       (a) it refers to the same symbol; and
12125       (b) the offset applied in the %lo() expression is no lower than
12126           the offset applied in the %got() or %hi().
12127
12128    (b) allows us to cope with code like:
12129
12130         lui     $4,%hi(foo)
12131         lh      $4,%lo(foo+2)($4)
12132
12133    ...which is legal on RELA targets, and has a well-defined behaviour
12134    if the user knows that adding 2 to "foo" will not induce a carry to
12135    the high 16 bits.
12136
12137    When several %lo()s match a particular %got() or %hi(), we use the
12138    following rules to distinguish them:
12139
12140      (1) %lo()s with smaller offsets are a better match than %lo()s with
12141          higher offsets.
12142
12143      (2) %lo()s with no matching %got() or %hi() are better than those
12144          that already have a matching %got() or %hi().
12145
12146      (3) later %lo()s are better than earlier %lo()s.
12147
12148    These rules are applied in order.
12149
12150    (1) means, among other things, that %lo()s with identical offsets are
12151    chosen if they exist.
12152
12153    (2) means that we won't associate several high-part relocations with
12154    the same low-part relocation unless there's no alternative.  Having
12155    several high parts for the same low part is a GNU extension; this rule
12156    allows careful users to avoid it.
12157
12158    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
12159    with the last high-part relocation being at the front of the list.
12160    It therefore makes sense to choose the last matching low-part
12161    relocation, all other things being equal.  It's also easier
12162    to code that way.  */
12163
12164 void
12165 mips_frob_file (void)
12166 {
12167   struct mips_hi_fixup *l;
12168   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
12169
12170   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
12171     {
12172       segment_info_type *seginfo;
12173       bfd_boolean matched_lo_p;
12174       fixS **hi_pos, **lo_pos, **pos;
12175
12176       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
12177
12178       /* If a GOT16 relocation turns out to be against a global symbol,
12179          there isn't supposed to be a matching LO.  */
12180       if (got16_reloc_p (l->fixp->fx_r_type)
12181           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
12182         continue;
12183
12184       /* Check quickly whether the next fixup happens to be a matching %lo.  */
12185       if (fixup_has_matching_lo_p (l->fixp))
12186         continue;
12187
12188       seginfo = seg_info (l->seg);
12189
12190       /* Set HI_POS to the position of this relocation in the chain.
12191          Set LO_POS to the position of the chosen low-part relocation.
12192          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
12193          relocation that matches an immediately-preceding high-part
12194          relocation.  */
12195       hi_pos = NULL;
12196       lo_pos = NULL;
12197       matched_lo_p = FALSE;
12198       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
12199
12200       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
12201         {
12202           if (*pos == l->fixp)
12203             hi_pos = pos;
12204
12205           if ((*pos)->fx_r_type == looking_for_rtype
12206               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
12207               && (*pos)->fx_offset >= l->fixp->fx_offset
12208               && (lo_pos == NULL
12209                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
12210                   || (!matched_lo_p
12211                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
12212             lo_pos = pos;
12213
12214           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
12215                           && fixup_has_matching_lo_p (*pos));
12216         }
12217
12218       /* If we found a match, remove the high-part relocation from its
12219          current position and insert it before the low-part relocation.
12220          Make the offsets match so that fixup_has_matching_lo_p()
12221          will return true.
12222
12223          We don't warn about unmatched high-part relocations since some
12224          versions of gcc have been known to emit dead "lui ...%hi(...)"
12225          instructions.  */
12226       if (lo_pos != NULL)
12227         {
12228           l->fixp->fx_offset = (*lo_pos)->fx_offset;
12229           if (l->fixp->fx_next != *lo_pos)
12230             {
12231               *hi_pos = l->fixp->fx_next;
12232               l->fixp->fx_next = *lo_pos;
12233               *lo_pos = l->fixp;
12234             }
12235         }
12236     }
12237 }
12238
12239 /* We may have combined relocations without symbols in the N32/N64 ABI.
12240    We have to prevent gas from dropping them.  */
12241
12242 int
12243 mips_force_relocation (fixS *fixp)
12244 {
12245   if (generic_force_reloc (fixp))
12246     return 1;
12247
12248   if (HAVE_NEWABI
12249       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
12250       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
12251           || hi16_reloc_p (fixp->fx_r_type)
12252           || lo16_reloc_p (fixp->fx_r_type)))
12253     return 1;
12254
12255   return 0;
12256 }
12257
12258 /* Apply a fixup to the object file.  */
12259
12260 void
12261 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
12262 {
12263   bfd_byte *buf;
12264   long insn;
12265   reloc_howto_type *howto;
12266
12267   /* We ignore generic BFD relocations we don't know about.  */
12268   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
12269   if (! howto)
12270     return;
12271
12272   gas_assert (fixP->fx_size == 4
12273               || fixP->fx_r_type == BFD_RELOC_16
12274               || fixP->fx_r_type == BFD_RELOC_64
12275               || fixP->fx_r_type == BFD_RELOC_CTOR
12276               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
12277               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
12278               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
12279               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
12280
12281   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
12282
12283   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2);
12284
12285   /* Don't treat parts of a composite relocation as done.  There are two
12286      reasons for this:
12287
12288      (1) The second and third parts will be against 0 (RSS_UNDEF) but
12289          should nevertheless be emitted if the first part is.
12290
12291      (2) In normal usage, composite relocations are never assembly-time
12292          constants.  The easiest way of dealing with the pathological
12293          exceptions is to generate a relocation against STN_UNDEF and
12294          leave everything up to the linker.  */
12295   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
12296     fixP->fx_done = 1;
12297
12298   switch (fixP->fx_r_type)
12299     {
12300     case BFD_RELOC_MIPS_TLS_GD:
12301     case BFD_RELOC_MIPS_TLS_LDM:
12302     case BFD_RELOC_MIPS_TLS_DTPREL32:
12303     case BFD_RELOC_MIPS_TLS_DTPREL64:
12304     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
12305     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
12306     case BFD_RELOC_MIPS_TLS_GOTTPREL:
12307     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
12308     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
12309       S_SET_THREAD_LOCAL (fixP->fx_addsy);
12310       /* fall through */
12311
12312     case BFD_RELOC_MIPS_JMP:
12313     case BFD_RELOC_MIPS_SHIFT5:
12314     case BFD_RELOC_MIPS_SHIFT6:
12315     case BFD_RELOC_MIPS_GOT_DISP:
12316     case BFD_RELOC_MIPS_GOT_PAGE:
12317     case BFD_RELOC_MIPS_GOT_OFST:
12318     case BFD_RELOC_MIPS_SUB:
12319     case BFD_RELOC_MIPS_INSERT_A:
12320     case BFD_RELOC_MIPS_INSERT_B:
12321     case BFD_RELOC_MIPS_DELETE:
12322     case BFD_RELOC_MIPS_HIGHEST:
12323     case BFD_RELOC_MIPS_HIGHER:
12324     case BFD_RELOC_MIPS_SCN_DISP:
12325     case BFD_RELOC_MIPS_REL16:
12326     case BFD_RELOC_MIPS_RELGOT:
12327     case BFD_RELOC_MIPS_JALR:
12328     case BFD_RELOC_HI16:
12329     case BFD_RELOC_HI16_S:
12330     case BFD_RELOC_GPREL16:
12331     case BFD_RELOC_MIPS_LITERAL:
12332     case BFD_RELOC_MIPS_CALL16:
12333     case BFD_RELOC_MIPS_GOT16:
12334     case BFD_RELOC_GPREL32:
12335     case BFD_RELOC_MIPS_GOT_HI16:
12336     case BFD_RELOC_MIPS_GOT_LO16:
12337     case BFD_RELOC_MIPS_CALL_HI16:
12338     case BFD_RELOC_MIPS_CALL_LO16:
12339     case BFD_RELOC_MIPS16_GPREL:
12340     case BFD_RELOC_MIPS16_GOT16:
12341     case BFD_RELOC_MIPS16_CALL16:
12342     case BFD_RELOC_MIPS16_HI16:
12343     case BFD_RELOC_MIPS16_HI16_S:
12344     case BFD_RELOC_MIPS16_JMP:
12345       /* Nothing needed to do.  The value comes from the reloc entry.  */
12346       break;
12347
12348     case BFD_RELOC_64:
12349       /* This is handled like BFD_RELOC_32, but we output a sign
12350          extended value if we are only 32 bits.  */
12351       if (fixP->fx_done)
12352         {
12353           if (8 <= sizeof (valueT))
12354             md_number_to_chars ((char *) buf, *valP, 8);
12355           else
12356             {
12357               valueT hiv;
12358
12359               if ((*valP & 0x80000000) != 0)
12360                 hiv = 0xffffffff;
12361               else
12362                 hiv = 0;
12363               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
12364                                   *valP, 4);
12365               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
12366                                   hiv, 4);
12367             }
12368         }
12369       break;
12370
12371     case BFD_RELOC_RVA:
12372     case BFD_RELOC_32:
12373     case BFD_RELOC_16:
12374       /* If we are deleting this reloc entry, we must fill in the
12375          value now.  This can happen if we have a .word which is not
12376          resolved when it appears but is later defined.  */
12377       if (fixP->fx_done)
12378         md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
12379       break;
12380
12381     case BFD_RELOC_LO16:
12382     case BFD_RELOC_MIPS16_LO16:
12383       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
12384          may be safe to remove, but if so it's not obvious.  */
12385       /* When handling an embedded PIC switch statement, we can wind
12386          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
12387       if (fixP->fx_done)
12388         {
12389           if (*valP + 0x8000 > 0xffff)
12390             as_bad_where (fixP->fx_file, fixP->fx_line,
12391                           _("relocation overflow"));
12392           if (target_big_endian)
12393             buf += 2;
12394           md_number_to_chars ((char *) buf, *valP, 2);
12395         }
12396       break;
12397
12398     case BFD_RELOC_16_PCREL_S2:
12399       if ((*valP & 0x3) != 0)
12400         as_bad_where (fixP->fx_file, fixP->fx_line,
12401                       _("Branch to misaligned address (%lx)"), (long) *valP);
12402
12403       /* We need to save the bits in the instruction since fixup_segment()
12404          might be deleting the relocation entry (i.e., a branch within
12405          the current segment).  */
12406       if (! fixP->fx_done)
12407         break;
12408
12409       /* Update old instruction data.  */
12410       if (target_big_endian)
12411         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
12412       else
12413         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
12414
12415       if (*valP + 0x20000 <= 0x3ffff)
12416         {
12417           insn |= (*valP >> 2) & 0xffff;
12418           md_number_to_chars ((char *) buf, insn, 4);
12419         }
12420       else if (mips_pic == NO_PIC
12421                && fixP->fx_done
12422                && fixP->fx_frag->fr_address >= text_section->vma
12423                && (fixP->fx_frag->fr_address
12424                    < text_section->vma + bfd_get_section_size (text_section))
12425                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
12426                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
12427                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
12428         {
12429           /* The branch offset is too large.  If this is an
12430              unconditional branch, and we are not generating PIC code,
12431              we can convert it to an absolute jump instruction.  */
12432           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
12433             insn = 0x0c000000;  /* jal */
12434           else
12435             insn = 0x08000000;  /* j */
12436           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
12437           fixP->fx_done = 0;
12438           fixP->fx_addsy = section_symbol (text_section);
12439           *valP += md_pcrel_from (fixP);
12440           md_number_to_chars ((char *) buf, insn, 4);
12441         }
12442       else
12443         {
12444           /* If we got here, we have branch-relaxation disabled,
12445              and there's nothing we can do to fix this instruction
12446              without turning it into a longer sequence.  */
12447           as_bad_where (fixP->fx_file, fixP->fx_line,
12448                         _("Branch out of range"));
12449         }
12450       break;
12451
12452     case BFD_RELOC_VTABLE_INHERIT:
12453       fixP->fx_done = 0;
12454       if (fixP->fx_addsy
12455           && !S_IS_DEFINED (fixP->fx_addsy)
12456           && !S_IS_WEAK (fixP->fx_addsy))
12457         S_SET_WEAK (fixP->fx_addsy);
12458       break;
12459
12460     case BFD_RELOC_VTABLE_ENTRY:
12461       fixP->fx_done = 0;
12462       break;
12463
12464     default:
12465       internalError ();
12466     }
12467
12468   /* Remember value for tc_gen_reloc.  */
12469   fixP->fx_addnumber = *valP;
12470 }
12471
12472 static symbolS *
12473 get_symbol (void)
12474 {
12475   int c;
12476   char *name;
12477   symbolS *p;
12478
12479   name = input_line_pointer;
12480   c = get_symbol_end ();
12481   p = (symbolS *) symbol_find_or_make (name);
12482   *input_line_pointer = c;
12483   return p;
12484 }
12485
12486 /* Align the current frag to a given power of two.  If a particular
12487    fill byte should be used, FILL points to an integer that contains
12488    that byte, otherwise FILL is null.
12489
12490    The MIPS assembler also automatically adjusts any preceding
12491    label.  */
12492
12493 static void
12494 mips_align (int to, int *fill, symbolS *label)
12495 {
12496   mips_emit_delays ();
12497   mips_record_mips16_mode ();
12498   if (fill == NULL && subseg_text_p (now_seg))
12499     frag_align_code (to, 0);
12500   else
12501     frag_align (to, fill ? *fill : 0, 0);
12502   record_alignment (now_seg, to);
12503   if (label != NULL)
12504     {
12505       gas_assert (S_GET_SEGMENT (label) == now_seg);
12506       symbol_set_frag (label, frag_now);
12507       S_SET_VALUE (label, (valueT) frag_now_fix ());
12508     }
12509 }
12510
12511 /* Align to a given power of two.  .align 0 turns off the automatic
12512    alignment used by the data creating pseudo-ops.  */
12513
12514 static void
12515 s_align (int x ATTRIBUTE_UNUSED)
12516 {
12517   int temp, fill_value, *fill_ptr;
12518   long max_alignment = 28;
12519
12520   /* o Note that the assembler pulls down any immediately preceding label
12521        to the aligned address.
12522      o It's not documented but auto alignment is reinstated by
12523        a .align pseudo instruction.
12524      o Note also that after auto alignment is turned off the mips assembler
12525        issues an error on attempt to assemble an improperly aligned data item.
12526        We don't.  */
12527
12528   temp = get_absolute_expression ();
12529   if (temp > max_alignment)
12530     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
12531   else if (temp < 0)
12532     {
12533       as_warn (_("Alignment negative: 0 assumed."));
12534       temp = 0;
12535     }
12536   if (*input_line_pointer == ',')
12537     {
12538       ++input_line_pointer;
12539       fill_value = get_absolute_expression ();
12540       fill_ptr = &fill_value;
12541     }
12542   else
12543     fill_ptr = 0;
12544   if (temp)
12545     {
12546       segment_info_type *si = seg_info (now_seg);
12547       struct insn_label_list *l = si->label_list;
12548       /* Auto alignment should be switched on by next section change.  */
12549       auto_align = 1;
12550       mips_align (temp, fill_ptr, l != NULL ? l->label : NULL);
12551     }
12552   else
12553     {
12554       auto_align = 0;
12555     }
12556
12557   demand_empty_rest_of_line ();
12558 }
12559
12560 static void
12561 s_change_sec (int sec)
12562 {
12563   segT seg;
12564
12565 #ifdef OBJ_ELF
12566   /* The ELF backend needs to know that we are changing sections, so
12567      that .previous works correctly.  We could do something like check
12568      for an obj_section_change_hook macro, but that might be confusing
12569      as it would not be appropriate to use it in the section changing
12570      functions in read.c, since obj-elf.c intercepts those.  FIXME:
12571      This should be cleaner, somehow.  */
12572   if (IS_ELF)
12573     obj_elf_section_change_hook ();
12574 #endif
12575
12576   mips_emit_delays ();
12577
12578   switch (sec)
12579     {
12580     case 't':
12581       s_text (0);
12582       break;
12583     case 'd':
12584       s_data (0);
12585       break;
12586     case 'b':
12587       subseg_set (bss_section, (subsegT) get_absolute_expression ());
12588       demand_empty_rest_of_line ();
12589       break;
12590
12591     case 'r':
12592       seg = subseg_new (RDATA_SECTION_NAME,
12593                         (subsegT) get_absolute_expression ());
12594       if (IS_ELF)
12595         {
12596           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
12597                                                   | SEC_READONLY | SEC_RELOC
12598                                                   | SEC_DATA));
12599           if (strncmp (TARGET_OS, "elf", 3) != 0)
12600             record_alignment (seg, 4);
12601         }
12602       demand_empty_rest_of_line ();
12603       break;
12604
12605     case 's':
12606       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
12607       if (IS_ELF)
12608         {
12609           bfd_set_section_flags (stdoutput, seg,
12610                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
12611           if (strncmp (TARGET_OS, "elf", 3) != 0)
12612             record_alignment (seg, 4);
12613         }
12614       demand_empty_rest_of_line ();
12615       break;
12616
12617     case 'B':
12618       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
12619       if (IS_ELF)
12620         {
12621           bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
12622           if (strncmp (TARGET_OS, "elf", 3) != 0)
12623             record_alignment (seg, 4);
12624         }
12625       demand_empty_rest_of_line ();
12626       break;
12627     }
12628
12629   auto_align = 1;
12630 }
12631
12632 void
12633 s_change_section (int ignore ATTRIBUTE_UNUSED)
12634 {
12635 #ifdef OBJ_ELF
12636   char *section_name;
12637   char c;
12638   char next_c = 0;
12639   int section_type;
12640   int section_flag;
12641   int section_entry_size;
12642   int section_alignment;
12643
12644   if (!IS_ELF)
12645     return;
12646
12647   section_name = input_line_pointer;
12648   c = get_symbol_end ();
12649   if (c)
12650     next_c = *(input_line_pointer + 1);
12651
12652   /* Do we have .section Name<,"flags">?  */
12653   if (c != ',' || (c == ',' && next_c == '"'))
12654     {
12655       /* just after name is now '\0'.  */
12656       *input_line_pointer = c;
12657       input_line_pointer = section_name;
12658       obj_elf_section (ignore);
12659       return;
12660     }
12661   input_line_pointer++;
12662
12663   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
12664   if (c == ',')
12665     section_type = get_absolute_expression ();
12666   else
12667     section_type = 0;
12668   if (*input_line_pointer++ == ',')
12669     section_flag = get_absolute_expression ();
12670   else
12671     section_flag = 0;
12672   if (*input_line_pointer++ == ',')
12673     section_entry_size = get_absolute_expression ();
12674   else
12675     section_entry_size = 0;
12676   if (*input_line_pointer++ == ',')
12677     section_alignment = get_absolute_expression ();
12678   else
12679     section_alignment = 0;
12680   /* FIXME: really ignore?  */
12681   (void) section_alignment;
12682
12683   section_name = xstrdup (section_name);
12684
12685   /* When using the generic form of .section (as implemented by obj-elf.c),
12686      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
12687      traditionally had to fall back on the more common @progbits instead.
12688
12689      There's nothing really harmful in this, since bfd will correct
12690      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
12691      means that, for backwards compatibility, the special_section entries
12692      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
12693
12694      Even so, we shouldn't force users of the MIPS .section syntax to
12695      incorrectly label the sections as SHT_PROGBITS.  The best compromise
12696      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
12697      generic type-checking code.  */
12698   if (section_type == SHT_MIPS_DWARF)
12699     section_type = SHT_PROGBITS;
12700
12701   obj_elf_change_section (section_name, section_type, section_flag,
12702                           section_entry_size, 0, 0, 0);
12703
12704   if (now_seg->name != section_name)
12705     free (section_name);
12706 #endif /* OBJ_ELF */
12707 }
12708
12709 void
12710 mips_enable_auto_align (void)
12711 {
12712   auto_align = 1;
12713 }
12714
12715 static void
12716 s_cons (int log_size)
12717 {
12718   segment_info_type *si = seg_info (now_seg);
12719   struct insn_label_list *l = si->label_list;
12720   symbolS *label;
12721
12722   label = l != NULL ? l->label : NULL;
12723   mips_emit_delays ();
12724   if (log_size > 0 && auto_align)
12725     mips_align (log_size, 0, label);
12726   mips_clear_insn_labels ();
12727   cons (1 << log_size);
12728 }
12729
12730 static void
12731 s_float_cons (int type)
12732 {
12733   segment_info_type *si = seg_info (now_seg);
12734   struct insn_label_list *l = si->label_list;
12735   symbolS *label;
12736
12737   label = l != NULL ? l->label : NULL;
12738
12739   mips_emit_delays ();
12740
12741   if (auto_align)
12742     {
12743       if (type == 'd')
12744         mips_align (3, 0, label);
12745       else
12746         mips_align (2, 0, label);
12747     }
12748
12749   mips_clear_insn_labels ();
12750
12751   float_cons (type);
12752 }
12753
12754 /* Handle .globl.  We need to override it because on Irix 5 you are
12755    permitted to say
12756        .globl foo .text
12757    where foo is an undefined symbol, to mean that foo should be
12758    considered to be the address of a function.  */
12759
12760 static void
12761 s_mips_globl (int x ATTRIBUTE_UNUSED)
12762 {
12763   char *name;
12764   int c;
12765   symbolS *symbolP;
12766   flagword flag;
12767
12768   do
12769     {
12770       name = input_line_pointer;
12771       c = get_symbol_end ();
12772       symbolP = symbol_find_or_make (name);
12773       S_SET_EXTERNAL (symbolP);
12774
12775       *input_line_pointer = c;
12776       SKIP_WHITESPACE ();
12777
12778       /* On Irix 5, every global symbol that is not explicitly labelled as
12779          being a function is apparently labelled as being an object.  */
12780       flag = BSF_OBJECT;
12781
12782       if (!is_end_of_line[(unsigned char) *input_line_pointer]
12783           && (*input_line_pointer != ','))
12784         {
12785           char *secname;
12786           asection *sec;
12787
12788           secname = input_line_pointer;
12789           c = get_symbol_end ();
12790           sec = bfd_get_section_by_name (stdoutput, secname);
12791           if (sec == NULL)
12792             as_bad (_("%s: no such section"), secname);
12793           *input_line_pointer = c;
12794
12795           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
12796             flag = BSF_FUNCTION;
12797         }
12798
12799       symbol_get_bfdsym (symbolP)->flags |= flag;
12800
12801       c = *input_line_pointer;
12802       if (c == ',')
12803         {
12804           input_line_pointer++;
12805           SKIP_WHITESPACE ();
12806           if (is_end_of_line[(unsigned char) *input_line_pointer])
12807             c = '\n';
12808         }
12809     }
12810   while (c == ',');
12811
12812   demand_empty_rest_of_line ();
12813 }
12814
12815 static void
12816 s_option (int x ATTRIBUTE_UNUSED)
12817 {
12818   char *opt;
12819   char c;
12820
12821   opt = input_line_pointer;
12822   c = get_symbol_end ();
12823
12824   if (*opt == 'O')
12825     {
12826       /* FIXME: What does this mean?  */
12827     }
12828   else if (strncmp (opt, "pic", 3) == 0)
12829     {
12830       int i;
12831
12832       i = atoi (opt + 3);
12833       if (i == 0)
12834         mips_pic = NO_PIC;
12835       else if (i == 2)
12836         {
12837         mips_pic = SVR4_PIC;
12838           mips_abicalls = TRUE;
12839         }
12840       else
12841         as_bad (_(".option pic%d not supported"), i);
12842
12843       if (mips_pic == SVR4_PIC)
12844         {
12845           if (g_switch_seen && g_switch_value != 0)
12846             as_warn (_("-G may not be used with SVR4 PIC code"));
12847           g_switch_value = 0;
12848           bfd_set_gp_size (stdoutput, 0);
12849         }
12850     }
12851   else
12852     as_warn (_("Unrecognized option \"%s\""), opt);
12853
12854   *input_line_pointer = c;
12855   demand_empty_rest_of_line ();
12856 }
12857
12858 /* This structure is used to hold a stack of .set values.  */
12859
12860 struct mips_option_stack
12861 {
12862   struct mips_option_stack *next;
12863   struct mips_set_options options;
12864 };
12865
12866 static struct mips_option_stack *mips_opts_stack;
12867
12868 /* Handle the .set pseudo-op.  */
12869
12870 static void
12871 s_mipsset (int x ATTRIBUTE_UNUSED)
12872 {
12873   char *name = input_line_pointer, ch;
12874
12875   while (!is_end_of_line[(unsigned char) *input_line_pointer])
12876     ++input_line_pointer;
12877   ch = *input_line_pointer;
12878   *input_line_pointer = '\0';
12879
12880   if (strcmp (name, "reorder") == 0)
12881     {
12882       if (mips_opts.noreorder)
12883         end_noreorder ();
12884     }
12885   else if (strcmp (name, "noreorder") == 0)
12886     {
12887       if (!mips_opts.noreorder)
12888         start_noreorder ();
12889     }
12890   else if (strncmp (name, "at=", 3) == 0)
12891     {
12892       char *s = name + 3;
12893
12894       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
12895         as_bad (_("Unrecognized register name `%s'"), s);
12896     }
12897   else if (strcmp (name, "at") == 0)
12898     {
12899       mips_opts.at = ATREG;
12900     }
12901   else if (strcmp (name, "noat") == 0)
12902     {
12903       mips_opts.at = ZERO;
12904     }
12905   else if (strcmp (name, "macro") == 0)
12906     {
12907       mips_opts.warn_about_macros = 0;
12908     }
12909   else if (strcmp (name, "nomacro") == 0)
12910     {
12911       if (mips_opts.noreorder == 0)
12912         as_bad (_("`noreorder' must be set before `nomacro'"));
12913       mips_opts.warn_about_macros = 1;
12914     }
12915   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
12916     {
12917       mips_opts.nomove = 0;
12918     }
12919   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
12920     {
12921       mips_opts.nomove = 1;
12922     }
12923   else if (strcmp (name, "bopt") == 0)
12924     {
12925       mips_opts.nobopt = 0;
12926     }
12927   else if (strcmp (name, "nobopt") == 0)
12928     {
12929       mips_opts.nobopt = 1;
12930     }
12931   else if (strcmp (name, "gp=default") == 0)
12932     mips_opts.gp32 = file_mips_gp32;
12933   else if (strcmp (name, "gp=32") == 0)
12934     mips_opts.gp32 = 1;
12935   else if (strcmp (name, "gp=64") == 0)
12936     {
12937       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
12938         as_warn (_("%s isa does not support 64-bit registers"),
12939                  mips_cpu_info_from_isa (mips_opts.isa)->name);
12940       mips_opts.gp32 = 0;
12941     }
12942   else if (strcmp (name, "fp=default") == 0)
12943     mips_opts.fp32 = file_mips_fp32;
12944   else if (strcmp (name, "fp=32") == 0)
12945     mips_opts.fp32 = 1;
12946   else if (strcmp (name, "fp=64") == 0)
12947     {
12948       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
12949         as_warn (_("%s isa does not support 64-bit floating point registers"),
12950                  mips_cpu_info_from_isa (mips_opts.isa)->name);
12951       mips_opts.fp32 = 0;
12952     }
12953   else if (strcmp (name, "softfloat") == 0)
12954     mips_opts.soft_float = 1;
12955   else if (strcmp (name, "hardfloat") == 0)
12956     mips_opts.soft_float = 0;
12957   else if (strcmp (name, "singlefloat") == 0)
12958     mips_opts.single_float = 1;
12959   else if (strcmp (name, "doublefloat") == 0)
12960     mips_opts.single_float = 0;
12961   else if (strcmp (name, "mips16") == 0
12962            || strcmp (name, "MIPS-16") == 0)
12963     mips_opts.mips16 = 1;
12964   else if (strcmp (name, "nomips16") == 0
12965            || strcmp (name, "noMIPS-16") == 0)
12966     mips_opts.mips16 = 0;
12967   else if (strcmp (name, "smartmips") == 0)
12968     {
12969       if (!ISA_SUPPORTS_SMARTMIPS)
12970         as_warn (_("%s ISA does not support SmartMIPS ASE"), 
12971                  mips_cpu_info_from_isa (mips_opts.isa)->name);
12972       mips_opts.ase_smartmips = 1;
12973     }
12974   else if (strcmp (name, "nosmartmips") == 0)
12975     mips_opts.ase_smartmips = 0;
12976   else if (strcmp (name, "mips3d") == 0)
12977     mips_opts.ase_mips3d = 1;
12978   else if (strcmp (name, "nomips3d") == 0)
12979     mips_opts.ase_mips3d = 0;
12980   else if (strcmp (name, "mdmx") == 0)
12981     mips_opts.ase_mdmx = 1;
12982   else if (strcmp (name, "nomdmx") == 0)
12983     mips_opts.ase_mdmx = 0;
12984   else if (strcmp (name, "dsp") == 0)
12985     {
12986       if (!ISA_SUPPORTS_DSP_ASE)
12987         as_warn (_("%s ISA does not support DSP ASE"), 
12988                  mips_cpu_info_from_isa (mips_opts.isa)->name);
12989       mips_opts.ase_dsp = 1;
12990       mips_opts.ase_dspr2 = 0;
12991     }
12992   else if (strcmp (name, "nodsp") == 0)
12993     {
12994       mips_opts.ase_dsp = 0;
12995       mips_opts.ase_dspr2 = 0;
12996     }
12997   else if (strcmp (name, "dspr2") == 0)
12998     {
12999       if (!ISA_SUPPORTS_DSPR2_ASE)
13000         as_warn (_("%s ISA does not support DSP R2 ASE"),
13001                  mips_cpu_info_from_isa (mips_opts.isa)->name);
13002       mips_opts.ase_dspr2 = 1;
13003       mips_opts.ase_dsp = 1;
13004     }
13005   else if (strcmp (name, "nodspr2") == 0)
13006     {
13007       mips_opts.ase_dspr2 = 0;
13008       mips_opts.ase_dsp = 0;
13009     }
13010   else if (strcmp (name, "mt") == 0)
13011     {
13012       if (!ISA_SUPPORTS_MT_ASE)
13013         as_warn (_("%s ISA does not support MT ASE"), 
13014                  mips_cpu_info_from_isa (mips_opts.isa)->name);
13015       mips_opts.ase_mt = 1;
13016     }
13017   else if (strcmp (name, "nomt") == 0)
13018     mips_opts.ase_mt = 0;
13019   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
13020     {
13021       int reset = 0;
13022
13023       /* Permit the user to change the ISA and architecture on the fly.
13024          Needless to say, misuse can cause serious problems.  */
13025       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
13026         {
13027           reset = 1;
13028           mips_opts.isa = file_mips_isa;
13029           mips_opts.arch = file_mips_arch;
13030         }
13031       else if (strncmp (name, "arch=", 5) == 0)
13032         {
13033           const struct mips_cpu_info *p;
13034
13035           p = mips_parse_cpu("internal use", name + 5);
13036           if (!p)
13037             as_bad (_("unknown architecture %s"), name + 5);
13038           else
13039             {
13040               mips_opts.arch = p->cpu;
13041               mips_opts.isa = p->isa;
13042             }
13043         }
13044       else if (strncmp (name, "mips", 4) == 0)
13045         {
13046           const struct mips_cpu_info *p;
13047
13048           p = mips_parse_cpu("internal use", name);
13049           if (!p)
13050             as_bad (_("unknown ISA level %s"), name + 4);
13051           else
13052             {
13053               mips_opts.arch = p->cpu;
13054               mips_opts.isa = p->isa;
13055             }
13056         }
13057       else
13058         as_bad (_("unknown ISA or architecture %s"), name);
13059
13060       switch (mips_opts.isa)
13061         {
13062         case  0:
13063           break;
13064         case ISA_MIPS1:
13065         case ISA_MIPS2:
13066         case ISA_MIPS32:
13067         case ISA_MIPS32R2:
13068           mips_opts.gp32 = 1;
13069           mips_opts.fp32 = 1;
13070           break;
13071         case ISA_MIPS3:
13072         case ISA_MIPS4:
13073         case ISA_MIPS5:
13074         case ISA_MIPS64:
13075         case ISA_MIPS64R2:
13076           mips_opts.gp32 = 0;
13077           mips_opts.fp32 = 0;
13078           break;
13079         default:
13080           as_bad (_("unknown ISA level %s"), name + 4);
13081           break;
13082         }
13083       if (reset)
13084         {
13085           mips_opts.gp32 = file_mips_gp32;
13086           mips_opts.fp32 = file_mips_fp32;
13087         }
13088     }
13089   else if (strcmp (name, "autoextend") == 0)
13090     mips_opts.noautoextend = 0;
13091   else if (strcmp (name, "noautoextend") == 0)
13092     mips_opts.noautoextend = 1;
13093   else if (strcmp (name, "push") == 0)
13094     {
13095       struct mips_option_stack *s;
13096
13097       s = (struct mips_option_stack *) xmalloc (sizeof *s);
13098       s->next = mips_opts_stack;
13099       s->options = mips_opts;
13100       mips_opts_stack = s;
13101     }
13102   else if (strcmp (name, "pop") == 0)
13103     {
13104       struct mips_option_stack *s;
13105
13106       s = mips_opts_stack;
13107       if (s == NULL)
13108         as_bad (_(".set pop with no .set push"));
13109       else
13110         {
13111           /* If we're changing the reorder mode we need to handle
13112              delay slots correctly.  */
13113           if (s->options.noreorder && ! mips_opts.noreorder)
13114             start_noreorder ();
13115           else if (! s->options.noreorder && mips_opts.noreorder)
13116             end_noreorder ();
13117
13118           mips_opts = s->options;
13119           mips_opts_stack = s->next;
13120           free (s);
13121         }
13122     }
13123   else if (strcmp (name, "sym32") == 0)
13124     mips_opts.sym32 = TRUE;
13125   else if (strcmp (name, "nosym32") == 0)
13126     mips_opts.sym32 = FALSE;
13127   else if (strchr (name, ','))
13128     {
13129       /* Generic ".set" directive; use the generic handler.  */
13130       *input_line_pointer = ch;
13131       input_line_pointer = name;
13132       s_set (0);
13133       return;
13134     }
13135   else
13136     {
13137       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
13138     }
13139   *input_line_pointer = ch;
13140   demand_empty_rest_of_line ();
13141 }
13142
13143 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
13144    .option pic2.  It means to generate SVR4 PIC calls.  */
13145
13146 static void
13147 s_abicalls (int ignore ATTRIBUTE_UNUSED)
13148 {
13149   mips_pic = SVR4_PIC;
13150   mips_abicalls = TRUE;
13151
13152   if (g_switch_seen && g_switch_value != 0)
13153     as_warn (_("-G may not be used with SVR4 PIC code"));
13154   g_switch_value = 0;
13155
13156   bfd_set_gp_size (stdoutput, 0);
13157   demand_empty_rest_of_line ();
13158 }
13159
13160 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
13161    PIC code.  It sets the $gp register for the function based on the
13162    function address, which is in the register named in the argument.
13163    This uses a relocation against _gp_disp, which is handled specially
13164    by the linker.  The result is:
13165         lui     $gp,%hi(_gp_disp)
13166         addiu   $gp,$gp,%lo(_gp_disp)
13167         addu    $gp,$gp,.cpload argument
13168    The .cpload argument is normally $25 == $t9.
13169
13170    The -mno-shared option changes this to:
13171         lui     $gp,%hi(__gnu_local_gp)
13172         addiu   $gp,$gp,%lo(__gnu_local_gp)
13173    and the argument is ignored.  This saves an instruction, but the
13174    resulting code is not position independent; it uses an absolute
13175    address for __gnu_local_gp.  Thus code assembled with -mno-shared
13176    can go into an ordinary executable, but not into a shared library.  */
13177
13178 static void
13179 s_cpload (int ignore ATTRIBUTE_UNUSED)
13180 {
13181   expressionS ex;
13182   int reg;
13183   int in_shared;
13184
13185   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
13186      .cpload is ignored.  */
13187   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
13188     {
13189       s_ignore (0);
13190       return;
13191     }
13192
13193   /* .cpload should be in a .set noreorder section.  */
13194   if (mips_opts.noreorder == 0)
13195     as_warn (_(".cpload not in noreorder section"));
13196
13197   reg = tc_get_register (0);
13198
13199   /* If we need to produce a 64-bit address, we are better off using
13200      the default instruction sequence.  */
13201   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
13202
13203   ex.X_op = O_symbol;
13204   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
13205                                          "__gnu_local_gp");
13206   ex.X_op_symbol = NULL;
13207   ex.X_add_number = 0;
13208
13209   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
13210   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
13211
13212   macro_start ();
13213   macro_build_lui (&ex, mips_gp_register);
13214   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
13215                mips_gp_register, BFD_RELOC_LO16);
13216   if (in_shared)
13217     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
13218                  mips_gp_register, reg);
13219   macro_end ();
13220
13221   demand_empty_rest_of_line ();
13222 }
13223
13224 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
13225      .cpsetup $reg1, offset|$reg2, label
13226
13227    If offset is given, this results in:
13228      sd         $gp, offset($sp)
13229      lui        $gp, %hi(%neg(%gp_rel(label)))
13230      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
13231      daddu      $gp, $gp, $reg1
13232
13233    If $reg2 is given, this results in:
13234      daddu      $reg2, $gp, $0
13235      lui        $gp, %hi(%neg(%gp_rel(label)))
13236      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
13237      daddu      $gp, $gp, $reg1
13238    $reg1 is normally $25 == $t9.
13239
13240    The -mno-shared option replaces the last three instructions with
13241         lui     $gp,%hi(_gp)
13242         addiu   $gp,$gp,%lo(_gp)  */
13243
13244 static void
13245 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
13246 {
13247   expressionS ex_off;
13248   expressionS ex_sym;
13249   int reg1;
13250
13251   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
13252      We also need NewABI support.  */
13253   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
13254     {
13255       s_ignore (0);
13256       return;
13257     }
13258
13259   reg1 = tc_get_register (0);
13260   SKIP_WHITESPACE ();
13261   if (*input_line_pointer != ',')
13262     {
13263       as_bad (_("missing argument separator ',' for .cpsetup"));
13264       return;
13265     }
13266   else
13267     ++input_line_pointer;
13268   SKIP_WHITESPACE ();
13269   if (*input_line_pointer == '$')
13270     {
13271       mips_cpreturn_register = tc_get_register (0);
13272       mips_cpreturn_offset = -1;
13273     }
13274   else
13275     {
13276       mips_cpreturn_offset = get_absolute_expression ();
13277       mips_cpreturn_register = -1;
13278     }
13279   SKIP_WHITESPACE ();
13280   if (*input_line_pointer != ',')
13281     {
13282       as_bad (_("missing argument separator ',' for .cpsetup"));
13283       return;
13284     }
13285   else
13286     ++input_line_pointer;
13287   SKIP_WHITESPACE ();
13288   expression (&ex_sym);
13289
13290   macro_start ();
13291   if (mips_cpreturn_register == -1)
13292     {
13293       ex_off.X_op = O_constant;
13294       ex_off.X_add_symbol = NULL;
13295       ex_off.X_op_symbol = NULL;
13296       ex_off.X_add_number = mips_cpreturn_offset;
13297
13298       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
13299                    BFD_RELOC_LO16, SP);
13300     }
13301   else
13302     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
13303                  mips_gp_register, 0);
13304
13305   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
13306     {
13307       macro_build (&ex_sym, "lui", "t,u", mips_gp_register,
13308                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
13309                    BFD_RELOC_HI16_S);
13310
13311       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
13312                    mips_gp_register, -1, BFD_RELOC_GPREL16,
13313                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
13314
13315       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
13316                    mips_gp_register, reg1);
13317     }
13318   else
13319     {
13320       expressionS ex;
13321
13322       ex.X_op = O_symbol;
13323       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
13324       ex.X_op_symbol = NULL;
13325       ex.X_add_number = 0;
13326
13327       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
13328       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
13329
13330       macro_build_lui (&ex, mips_gp_register);
13331       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
13332                    mips_gp_register, BFD_RELOC_LO16);
13333     }
13334
13335   macro_end ();
13336
13337   demand_empty_rest_of_line ();
13338 }
13339
13340 static void
13341 s_cplocal (int ignore ATTRIBUTE_UNUSED)
13342 {
13343   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
13344      .cplocal is ignored.  */
13345   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
13346     {
13347       s_ignore (0);
13348       return;
13349     }
13350
13351   mips_gp_register = tc_get_register (0);
13352   demand_empty_rest_of_line ();
13353 }
13354
13355 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
13356    offset from $sp.  The offset is remembered, and after making a PIC
13357    call $gp is restored from that location.  */
13358
13359 static void
13360 s_cprestore (int ignore ATTRIBUTE_UNUSED)
13361 {
13362   expressionS ex;
13363
13364   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
13365      .cprestore is ignored.  */
13366   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
13367     {
13368       s_ignore (0);
13369       return;
13370     }
13371
13372   mips_cprestore_offset = get_absolute_expression ();
13373   mips_cprestore_valid = 1;
13374
13375   ex.X_op = O_constant;
13376   ex.X_add_symbol = NULL;
13377   ex.X_op_symbol = NULL;
13378   ex.X_add_number = mips_cprestore_offset;
13379
13380   macro_start ();
13381   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
13382                                 SP, HAVE_64BIT_ADDRESSES);
13383   macro_end ();
13384
13385   demand_empty_rest_of_line ();
13386 }
13387
13388 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
13389    was given in the preceding .cpsetup, it results in:
13390      ld         $gp, offset($sp)
13391
13392    If a register $reg2 was given there, it results in:
13393      daddu      $gp, $reg2, $0  */
13394
13395 static void
13396 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
13397 {
13398   expressionS ex;
13399
13400   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
13401      We also need NewABI support.  */
13402   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
13403     {
13404       s_ignore (0);
13405       return;
13406     }
13407
13408   macro_start ();
13409   if (mips_cpreturn_register == -1)
13410     {
13411       ex.X_op = O_constant;
13412       ex.X_add_symbol = NULL;
13413       ex.X_op_symbol = NULL;
13414       ex.X_add_number = mips_cpreturn_offset;
13415
13416       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
13417     }
13418   else
13419     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
13420                  mips_cpreturn_register, 0);
13421   macro_end ();
13422
13423   demand_empty_rest_of_line ();
13424 }
13425
13426 /* Handle the .dtprelword and .dtpreldword pseudo-ops.  They generate
13427    a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
13428    use in DWARF debug information.  */
13429
13430 static void
13431 s_dtprel_internal (size_t bytes)
13432 {
13433   expressionS ex;
13434   char *p;
13435
13436   expression (&ex);
13437
13438   if (ex.X_op != O_symbol)
13439     {
13440       as_bad (_("Unsupported use of %s"), (bytes == 8
13441                                            ? ".dtpreldword"
13442                                            : ".dtprelword"));
13443       ignore_rest_of_line ();
13444     }
13445
13446   p = frag_more (bytes);
13447   md_number_to_chars (p, 0, bytes);
13448   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
13449                (bytes == 8
13450                 ? BFD_RELOC_MIPS_TLS_DTPREL64
13451                 : BFD_RELOC_MIPS_TLS_DTPREL32));
13452
13453   demand_empty_rest_of_line ();
13454 }
13455
13456 /* Handle .dtprelword.  */
13457
13458 static void
13459 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
13460 {
13461   s_dtprel_internal (4);
13462 }
13463
13464 /* Handle .dtpreldword.  */
13465
13466 static void
13467 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
13468 {
13469   s_dtprel_internal (8);
13470 }
13471
13472 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
13473    code.  It sets the offset to use in gp_rel relocations.  */
13474
13475 static void
13476 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
13477 {
13478   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
13479      We also need NewABI support.  */
13480   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
13481     {
13482       s_ignore (0);
13483       return;
13484     }
13485
13486   mips_gprel_offset = get_absolute_expression ();
13487
13488   demand_empty_rest_of_line ();
13489 }
13490
13491 /* Handle the .gpword pseudo-op.  This is used when generating PIC
13492    code.  It generates a 32 bit GP relative reloc.  */
13493
13494 static void
13495 s_gpword (int ignore ATTRIBUTE_UNUSED)
13496 {
13497   segment_info_type *si;
13498   struct insn_label_list *l;
13499   symbolS *label;
13500   expressionS ex;
13501   char *p;
13502
13503   /* When not generating PIC code, this is treated as .word.  */
13504   if (mips_pic != SVR4_PIC)
13505     {
13506       s_cons (2);
13507       return;
13508     }
13509
13510   si = seg_info (now_seg);
13511   l = si->label_list;
13512   label = l != NULL ? l->label : NULL;
13513   mips_emit_delays ();
13514   if (auto_align)
13515     mips_align (2, 0, label);
13516   mips_clear_insn_labels ();
13517
13518   expression (&ex);
13519
13520   if (ex.X_op != O_symbol || ex.X_add_number != 0)
13521     {
13522       as_bad (_("Unsupported use of .gpword"));
13523       ignore_rest_of_line ();
13524     }
13525
13526   p = frag_more (4);
13527   md_number_to_chars (p, 0, 4);
13528   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
13529                BFD_RELOC_GPREL32);
13530
13531   demand_empty_rest_of_line ();
13532 }
13533
13534 static void
13535 s_gpdword (int ignore ATTRIBUTE_UNUSED)
13536 {
13537   segment_info_type *si;
13538   struct insn_label_list *l;
13539   symbolS *label;
13540   expressionS ex;
13541   char *p;
13542
13543   /* When not generating PIC code, this is treated as .dword.  */
13544   if (mips_pic != SVR4_PIC)
13545     {
13546       s_cons (3);
13547       return;
13548     }
13549
13550   si = seg_info (now_seg);
13551   l = si->label_list;
13552   label = l != NULL ? l->label : NULL;
13553   mips_emit_delays ();
13554   if (auto_align)
13555     mips_align (3, 0, label);
13556   mips_clear_insn_labels ();
13557
13558   expression (&ex);
13559
13560   if (ex.X_op != O_symbol || ex.X_add_number != 0)
13561     {
13562       as_bad (_("Unsupported use of .gpdword"));
13563       ignore_rest_of_line ();
13564     }
13565
13566   p = frag_more (8);
13567   md_number_to_chars (p, 0, 8);
13568   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
13569                BFD_RELOC_GPREL32)->fx_tcbit = 1;
13570
13571   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
13572   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
13573            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
13574
13575   demand_empty_rest_of_line ();
13576 }
13577
13578 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
13579    tables in SVR4 PIC code.  */
13580
13581 static void
13582 s_cpadd (int ignore ATTRIBUTE_UNUSED)
13583 {
13584   int reg;
13585
13586   /* This is ignored when not generating SVR4 PIC code.  */
13587   if (mips_pic != SVR4_PIC)
13588     {
13589       s_ignore (0);
13590       return;
13591     }
13592
13593   /* Add $gp to the register named as an argument.  */
13594   macro_start ();
13595   reg = tc_get_register (0);
13596   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
13597   macro_end ();
13598
13599   demand_empty_rest_of_line ();
13600 }
13601
13602 /* Handle the .insn pseudo-op.  This marks instruction labels in
13603    mips16 mode.  This permits the linker to handle them specially,
13604    such as generating jalx instructions when needed.  We also make
13605    them odd for the duration of the assembly, in order to generate the
13606    right sort of code.  We will make them even in the adjust_symtab
13607    routine, while leaving them marked.  This is convenient for the
13608    debugger and the disassembler.  The linker knows to make them odd
13609    again.  */
13610
13611 static void
13612 s_insn (int ignore ATTRIBUTE_UNUSED)
13613 {
13614   mips16_mark_labels ();
13615
13616   demand_empty_rest_of_line ();
13617 }
13618
13619 /* Handle a .stabn directive.  We need these in order to mark a label
13620    as being a mips16 text label correctly.  Sometimes the compiler
13621    will emit a label, followed by a .stabn, and then switch sections.
13622    If the label and .stabn are in mips16 mode, then the label is
13623    really a mips16 text label.  */
13624
13625 static void
13626 s_mips_stab (int type)
13627 {
13628   if (type == 'n')
13629     mips16_mark_labels ();
13630
13631   s_stab (type);
13632 }
13633
13634 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
13635
13636 static void
13637 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
13638 {
13639   char *name;
13640   int c;
13641   symbolS *symbolP;
13642   expressionS exp;
13643
13644   name = input_line_pointer;
13645   c = get_symbol_end ();
13646   symbolP = symbol_find_or_make (name);
13647   S_SET_WEAK (symbolP);
13648   *input_line_pointer = c;
13649
13650   SKIP_WHITESPACE ();
13651
13652   if (! is_end_of_line[(unsigned char) *input_line_pointer])
13653     {
13654       if (S_IS_DEFINED (symbolP))
13655         {
13656           as_bad (_("ignoring attempt to redefine symbol %s"),
13657                   S_GET_NAME (symbolP));
13658           ignore_rest_of_line ();
13659           return;
13660         }
13661
13662       if (*input_line_pointer == ',')
13663         {
13664           ++input_line_pointer;
13665           SKIP_WHITESPACE ();
13666         }
13667
13668       expression (&exp);
13669       if (exp.X_op != O_symbol)
13670         {
13671           as_bad (_("bad .weakext directive"));
13672           ignore_rest_of_line ();
13673           return;
13674         }
13675       symbol_set_value_expression (symbolP, &exp);
13676     }
13677
13678   demand_empty_rest_of_line ();
13679 }
13680
13681 /* Parse a register string into a number.  Called from the ECOFF code
13682    to parse .frame.  The argument is non-zero if this is the frame
13683    register, so that we can record it in mips_frame_reg.  */
13684
13685 int
13686 tc_get_register (int frame)
13687 {
13688   unsigned int reg;
13689
13690   SKIP_WHITESPACE ();
13691   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
13692     reg = 0;
13693   if (frame)
13694     {
13695       mips_frame_reg = reg != 0 ? reg : SP;
13696       mips_frame_reg_valid = 1;
13697       mips_cprestore_valid = 0;
13698     }
13699   return reg;
13700 }
13701
13702 valueT
13703 md_section_align (asection *seg, valueT addr)
13704 {
13705   int align = bfd_get_section_alignment (stdoutput, seg);
13706
13707   if (IS_ELF)
13708     {
13709       /* We don't need to align ELF sections to the full alignment.
13710          However, Irix 5 may prefer that we align them at least to a 16
13711          byte boundary.  We don't bother to align the sections if we
13712          are targeted for an embedded system.  */
13713       if (strncmp (TARGET_OS, "elf", 3) == 0)
13714         return addr;
13715       if (align > 4)
13716         align = 4;
13717     }
13718
13719   return ((addr + (1 << align) - 1) & (-1 << align));
13720 }
13721
13722 /* Utility routine, called from above as well.  If called while the
13723    input file is still being read, it's only an approximation.  (For
13724    example, a symbol may later become defined which appeared to be
13725    undefined earlier.)  */
13726
13727 static int
13728 nopic_need_relax (symbolS *sym, int before_relaxing)
13729 {
13730   if (sym == 0)
13731     return 0;
13732
13733   if (g_switch_value > 0)
13734     {
13735       const char *symname;
13736       int change;
13737
13738       /* Find out whether this symbol can be referenced off the $gp
13739          register.  It can be if it is smaller than the -G size or if
13740          it is in the .sdata or .sbss section.  Certain symbols can
13741          not be referenced off the $gp, although it appears as though
13742          they can.  */
13743       symname = S_GET_NAME (sym);
13744       if (symname != (const char *) NULL
13745           && (strcmp (symname, "eprol") == 0
13746               || strcmp (symname, "etext") == 0
13747               || strcmp (symname, "_gp") == 0
13748               || strcmp (symname, "edata") == 0
13749               || strcmp (symname, "_fbss") == 0
13750               || strcmp (symname, "_fdata") == 0
13751               || strcmp (symname, "_ftext") == 0
13752               || strcmp (symname, "end") == 0
13753               || strcmp (symname, "_gp_disp") == 0))
13754         change = 1;
13755       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
13756                && (0
13757 #ifndef NO_ECOFF_DEBUGGING
13758                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
13759                        && (symbol_get_obj (sym)->ecoff_extern_size
13760                            <= g_switch_value))
13761 #endif
13762                    /* We must defer this decision until after the whole
13763                       file has been read, since there might be a .extern
13764                       after the first use of this symbol.  */
13765                    || (before_relaxing
13766 #ifndef NO_ECOFF_DEBUGGING
13767                        && symbol_get_obj (sym)->ecoff_extern_size == 0
13768 #endif
13769                        && S_GET_VALUE (sym) == 0)
13770                    || (S_GET_VALUE (sym) != 0
13771                        && S_GET_VALUE (sym) <= g_switch_value)))
13772         change = 0;
13773       else
13774         {
13775           const char *segname;
13776
13777           segname = segment_name (S_GET_SEGMENT (sym));
13778           gas_assert (strcmp (segname, ".lit8") != 0
13779                   && strcmp (segname, ".lit4") != 0);
13780           change = (strcmp (segname, ".sdata") != 0
13781                     && strcmp (segname, ".sbss") != 0
13782                     && strncmp (segname, ".sdata.", 7) != 0
13783                     && strncmp (segname, ".sbss.", 6) != 0
13784                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
13785                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
13786         }
13787       return change;
13788     }
13789   else
13790     /* We are not optimizing for the $gp register.  */
13791     return 1;
13792 }
13793
13794
13795 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
13796
13797 static bfd_boolean
13798 pic_need_relax (symbolS *sym, asection *segtype)
13799 {
13800   asection *symsec;
13801
13802   /* Handle the case of a symbol equated to another symbol.  */
13803   while (symbol_equated_reloc_p (sym))
13804     {
13805       symbolS *n;
13806
13807       /* It's possible to get a loop here in a badly written program.  */
13808       n = symbol_get_value_expression (sym)->X_add_symbol;
13809       if (n == sym)
13810         break;
13811       sym = n;
13812     }
13813
13814   if (symbol_section_p (sym))
13815     return TRUE;
13816
13817   symsec = S_GET_SEGMENT (sym);
13818
13819   /* This must duplicate the test in adjust_reloc_syms.  */
13820   return (symsec != &bfd_und_section
13821           && symsec != &bfd_abs_section
13822           && !bfd_is_com_section (symsec)
13823           && !s_is_linkonce (sym, segtype)
13824 #ifdef OBJ_ELF
13825           /* A global or weak symbol is treated as external.  */
13826           && (!IS_ELF || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
13827 #endif
13828           );
13829 }
13830
13831
13832 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
13833    extended opcode.  SEC is the section the frag is in.  */
13834
13835 static int
13836 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
13837 {
13838   int type;
13839   const struct mips16_immed_operand *op;
13840   offsetT val;
13841   int mintiny, maxtiny;
13842   segT symsec;
13843   fragS *sym_frag;
13844
13845   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
13846     return 0;
13847   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
13848     return 1;
13849
13850   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
13851   op = mips16_immed_operands;
13852   while (op->type != type)
13853     {
13854       ++op;
13855       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
13856     }
13857
13858   if (op->unsp)
13859     {
13860       if (type == '<' || type == '>' || type == '[' || type == ']')
13861         {
13862           mintiny = 1;
13863           maxtiny = 1 << op->nbits;
13864         }
13865       else
13866         {
13867           mintiny = 0;
13868           maxtiny = (1 << op->nbits) - 1;
13869         }
13870     }
13871   else
13872     {
13873       mintiny = - (1 << (op->nbits - 1));
13874       maxtiny = (1 << (op->nbits - 1)) - 1;
13875     }
13876
13877   sym_frag = symbol_get_frag (fragp->fr_symbol);
13878   val = S_GET_VALUE (fragp->fr_symbol);
13879   symsec = S_GET_SEGMENT (fragp->fr_symbol);
13880
13881   if (op->pcrel)
13882     {
13883       addressT addr;
13884
13885       /* We won't have the section when we are called from
13886          mips_relax_frag.  However, we will always have been called
13887          from md_estimate_size_before_relax first.  If this is a
13888          branch to a different section, we mark it as such.  If SEC is
13889          NULL, and the frag is not marked, then it must be a branch to
13890          the same section.  */
13891       if (sec == NULL)
13892         {
13893           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
13894             return 1;
13895         }
13896       else
13897         {
13898           /* Must have been called from md_estimate_size_before_relax.  */
13899           if (symsec != sec)
13900             {
13901               fragp->fr_subtype =
13902                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13903
13904               /* FIXME: We should support this, and let the linker
13905                  catch branches and loads that are out of range.  */
13906               as_bad_where (fragp->fr_file, fragp->fr_line,
13907                             _("unsupported PC relative reference to different section"));
13908
13909               return 1;
13910             }
13911           if (fragp != sym_frag && sym_frag->fr_address == 0)
13912             /* Assume non-extended on the first relaxation pass.
13913                The address we have calculated will be bogus if this is
13914                a forward branch to another frag, as the forward frag
13915                will have fr_address == 0.  */
13916             return 0;
13917         }
13918
13919       /* In this case, we know for sure that the symbol fragment is in
13920          the same section.  If the relax_marker of the symbol fragment
13921          differs from the relax_marker of this fragment, we have not
13922          yet adjusted the symbol fragment fr_address.  We want to add
13923          in STRETCH in order to get a better estimate of the address.
13924          This particularly matters because of the shift bits.  */
13925       if (stretch != 0
13926           && sym_frag->relax_marker != fragp->relax_marker)
13927         {
13928           fragS *f;
13929
13930           /* Adjust stretch for any alignment frag.  Note that if have
13931              been expanding the earlier code, the symbol may be
13932              defined in what appears to be an earlier frag.  FIXME:
13933              This doesn't handle the fr_subtype field, which specifies
13934              a maximum number of bytes to skip when doing an
13935              alignment.  */
13936           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
13937             {
13938               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
13939                 {
13940                   if (stretch < 0)
13941                     stretch = - ((- stretch)
13942                                  & ~ ((1 << (int) f->fr_offset) - 1));
13943                   else
13944                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
13945                   if (stretch == 0)
13946                     break;
13947                 }
13948             }
13949           if (f != NULL)
13950             val += stretch;
13951         }
13952
13953       addr = fragp->fr_address + fragp->fr_fix;
13954
13955       /* The base address rules are complicated.  The base address of
13956          a branch is the following instruction.  The base address of a
13957          PC relative load or add is the instruction itself, but if it
13958          is in a delay slot (in which case it can not be extended) use
13959          the address of the instruction whose delay slot it is in.  */
13960       if (type == 'p' || type == 'q')
13961         {
13962           addr += 2;
13963
13964           /* If we are currently assuming that this frag should be
13965              extended, then, the current address is two bytes
13966              higher.  */
13967           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
13968             addr += 2;
13969
13970           /* Ignore the low bit in the target, since it will be set
13971              for a text label.  */
13972           if ((val & 1) != 0)
13973             --val;
13974         }
13975       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
13976         addr -= 4;
13977       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
13978         addr -= 2;
13979
13980       val -= addr & ~ ((1 << op->shift) - 1);
13981
13982       /* Branch offsets have an implicit 0 in the lowest bit.  */
13983       if (type == 'p' || type == 'q')
13984         val /= 2;
13985
13986       /* If any of the shifted bits are set, we must use an extended
13987          opcode.  If the address depends on the size of this
13988          instruction, this can lead to a loop, so we arrange to always
13989          use an extended opcode.  We only check this when we are in
13990          the main relaxation loop, when SEC is NULL.  */
13991       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
13992         {
13993           fragp->fr_subtype =
13994             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
13995           return 1;
13996         }
13997
13998       /* If we are about to mark a frag as extended because the value
13999          is precisely maxtiny + 1, then there is a chance of an
14000          infinite loop as in the following code:
14001              la $4,foo
14002              .skip      1020
14003              .align     2
14004            foo:
14005          In this case when the la is extended, foo is 0x3fc bytes
14006          away, so the la can be shrunk, but then foo is 0x400 away, so
14007          the la must be extended.  To avoid this loop, we mark the
14008          frag as extended if it was small, and is about to become
14009          extended with a value of maxtiny + 1.  */
14010       if (val == ((maxtiny + 1) << op->shift)
14011           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
14012           && sec == NULL)
14013         {
14014           fragp->fr_subtype =
14015             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
14016           return 1;
14017         }
14018     }
14019   else if (symsec != absolute_section && sec != NULL)
14020     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
14021
14022   if ((val & ((1 << op->shift) - 1)) != 0
14023       || val < (mintiny << op->shift)
14024       || val > (maxtiny << op->shift))
14025     return 1;
14026   else
14027     return 0;
14028 }
14029
14030 /* Compute the length of a branch sequence, and adjust the
14031    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
14032    worst-case length is computed, with UPDATE being used to indicate
14033    whether an unconditional (-1), branch-likely (+1) or regular (0)
14034    branch is to be computed.  */
14035 static int
14036 relaxed_branch_length (fragS *fragp, asection *sec, int update)
14037 {
14038   bfd_boolean toofar;
14039   int length;
14040
14041   if (fragp
14042       && S_IS_DEFINED (fragp->fr_symbol)
14043       && sec == S_GET_SEGMENT (fragp->fr_symbol))
14044     {
14045       addressT addr;
14046       offsetT val;
14047
14048       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
14049
14050       addr = fragp->fr_address + fragp->fr_fix + 4;
14051
14052       val -= addr;
14053
14054       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
14055     }
14056   else if (fragp)
14057     /* If the symbol is not defined or it's in a different segment,
14058        assume the user knows what's going on and emit a short
14059        branch.  */
14060     toofar = FALSE;
14061   else
14062     toofar = TRUE;
14063
14064   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
14065     fragp->fr_subtype
14066       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_UNCOND (fragp->fr_subtype),
14067                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
14068                              RELAX_BRANCH_LINK (fragp->fr_subtype),
14069                              toofar);
14070
14071   length = 4;
14072   if (toofar)
14073     {
14074       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
14075         length += 8;
14076
14077       if (mips_pic != NO_PIC)
14078         {
14079           /* Additional space for PIC loading of target address.  */
14080           length += 8;
14081           if (mips_opts.isa == ISA_MIPS1)
14082             /* Additional space for $at-stabilizing nop.  */
14083             length += 4;
14084         }
14085
14086       /* If branch is conditional.  */
14087       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
14088         length += 8;
14089     }
14090
14091   return length;
14092 }
14093
14094 /* Estimate the size of a frag before relaxing.  Unless this is the
14095    mips16, we are not really relaxing here, and the final size is
14096    encoded in the subtype information.  For the mips16, we have to
14097    decide whether we are using an extended opcode or not.  */
14098
14099 int
14100 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
14101 {
14102   int change;
14103
14104   if (RELAX_BRANCH_P (fragp->fr_subtype))
14105     {
14106
14107       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
14108
14109       return fragp->fr_var;
14110     }
14111
14112   if (RELAX_MIPS16_P (fragp->fr_subtype))
14113     /* We don't want to modify the EXTENDED bit here; it might get us
14114        into infinite loops.  We change it only in mips_relax_frag().  */
14115     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
14116
14117   if (mips_pic == NO_PIC)
14118     change = nopic_need_relax (fragp->fr_symbol, 0);
14119   else if (mips_pic == SVR4_PIC)
14120     change = pic_need_relax (fragp->fr_symbol, segtype);
14121   else if (mips_pic == VXWORKS_PIC)
14122     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
14123     change = 0;
14124   else
14125     abort ();
14126
14127   if (change)
14128     {
14129       fragp->fr_subtype |= RELAX_USE_SECOND;
14130       return -RELAX_FIRST (fragp->fr_subtype);
14131     }
14132   else
14133     return -RELAX_SECOND (fragp->fr_subtype);
14134 }
14135
14136 /* This is called to see whether a reloc against a defined symbol
14137    should be converted into a reloc against a section.  */
14138
14139 int
14140 mips_fix_adjustable (fixS *fixp)
14141 {
14142   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14143       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
14144     return 0;
14145
14146   if (fixp->fx_addsy == NULL)
14147     return 1;
14148
14149   /* If symbol SYM is in a mergeable section, relocations of the form
14150      SYM + 0 can usually be made section-relative.  The mergeable data
14151      is then identified by the section offset rather than by the symbol.
14152
14153      However, if we're generating REL LO16 relocations, the offset is split
14154      between the LO16 and parterning high part relocation.  The linker will
14155      need to recalculate the complete offset in order to correctly identify
14156      the merge data.
14157
14158      The linker has traditionally not looked for the parterning high part
14159      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
14160      placed anywhere.  Rather than break backwards compatibility by changing
14161      this, it seems better not to force the issue, and instead keep the
14162      original symbol.  This will work with either linker behavior.  */
14163   if ((lo16_reloc_p (fixp->fx_r_type)
14164        || reloc_needs_lo_p (fixp->fx_r_type))
14165       && HAVE_IN_PLACE_ADDENDS
14166       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
14167     return 0;
14168
14169   /* There is no place to store an in-place offset for JALR relocations.  */
14170   if (fixp->fx_r_type == BFD_RELOC_MIPS_JALR && HAVE_IN_PLACE_ADDENDS)
14171     return 0;
14172
14173 #ifdef OBJ_ELF
14174   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
14175      to a floating-point stub.  The same is true for non-R_MIPS16_26
14176      relocations against MIPS16 functions; in this case, the stub becomes
14177      the function's canonical address.
14178
14179      Floating-point stubs are stored in unique .mips16.call.* or
14180      .mips16.fn.* sections.  If a stub T for function F is in section S,
14181      the first relocation in section S must be against F; this is how the
14182      linker determines the target function.  All relocations that might
14183      resolve to T must also be against F.  We therefore have the following
14184      restrictions, which are given in an intentionally-redundant way:
14185
14186        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
14187           symbols.
14188
14189        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
14190           if that stub might be used.
14191
14192        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
14193           symbols.
14194
14195        4. We cannot reduce a stub's relocations against MIPS16 symbols if
14196           that stub might be used.
14197
14198      There is a further restriction:
14199
14200        5. We cannot reduce R_MIPS16_26 relocations against MIPS16 symbols
14201           on targets with in-place addends; the relocation field cannot
14202           encode the low bit.
14203
14204      For simplicity, we deal with (3)-(5) by not reducing _any_ relocation
14205      against a MIPS16 symbol.
14206
14207      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
14208      relocation against some symbol R, no relocation against R may be
14209      reduced.  (Note that this deals with (2) as well as (1) because
14210      relocations against global symbols will never be reduced on ELF
14211      targets.)  This approach is a little simpler than trying to detect
14212      stub sections, and gives the "all or nothing" per-symbol consistency
14213      that we have for MIPS16 symbols.  */
14214   if (IS_ELF
14215       && fixp->fx_subsy == NULL
14216       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
14217           || *symbol_get_tc (fixp->fx_addsy)))
14218     return 0;
14219 #endif
14220
14221   return 1;
14222 }
14223
14224 /* Translate internal representation of relocation info to BFD target
14225    format.  */
14226
14227 arelent **
14228 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
14229 {
14230   static arelent *retval[4];
14231   arelent *reloc;
14232   bfd_reloc_code_real_type code;
14233
14234   memset (retval, 0, sizeof(retval));
14235   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
14236   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
14237   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
14238   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
14239
14240   if (fixp->fx_pcrel)
14241     {
14242       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2);
14243
14244       /* At this point, fx_addnumber is "symbol offset - pcrel address".
14245          Relocations want only the symbol offset.  */
14246       reloc->addend = fixp->fx_addnumber + reloc->address;
14247       if (!IS_ELF)
14248         {
14249           /* A gruesome hack which is a result of the gruesome gas
14250              reloc handling.  What's worse, for COFF (as opposed to
14251              ECOFF), we might need yet another copy of reloc->address.
14252              See bfd_install_relocation.  */
14253           reloc->addend += reloc->address;
14254         }
14255     }
14256   else
14257     reloc->addend = fixp->fx_addnumber;
14258
14259   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
14260      entry to be used in the relocation's section offset.  */
14261   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
14262     {
14263       reloc->address = reloc->addend;
14264       reloc->addend = 0;
14265     }
14266
14267   code = fixp->fx_r_type;
14268
14269   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
14270   if (reloc->howto == NULL)
14271     {
14272       as_bad_where (fixp->fx_file, fixp->fx_line,
14273                     _("Can not represent %s relocation in this object file format"),
14274                     bfd_get_reloc_code_name (code));
14275       retval[0] = NULL;
14276     }
14277
14278   return retval;
14279 }
14280
14281 /* Relax a machine dependent frag.  This returns the amount by which
14282    the current size of the frag should change.  */
14283
14284 int
14285 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
14286 {
14287   if (RELAX_BRANCH_P (fragp->fr_subtype))
14288     {
14289       offsetT old_var = fragp->fr_var;
14290
14291       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
14292
14293       return fragp->fr_var - old_var;
14294     }
14295
14296   if (! RELAX_MIPS16_P (fragp->fr_subtype))
14297     return 0;
14298
14299   if (mips16_extended_frag (fragp, NULL, stretch))
14300     {
14301       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
14302         return 0;
14303       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
14304       return 2;
14305     }
14306   else
14307     {
14308       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
14309         return 0;
14310       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
14311       return -2;
14312     }
14313
14314   return 0;
14315 }
14316
14317 /* Convert a machine dependent frag.  */
14318
14319 void
14320 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
14321 {
14322   if (RELAX_BRANCH_P (fragp->fr_subtype))
14323     {
14324       bfd_byte *buf;
14325       unsigned long insn;
14326       expressionS exp;
14327       fixS *fixp;
14328
14329       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
14330
14331       if (target_big_endian)
14332         insn = bfd_getb32 (buf);
14333       else
14334         insn = bfd_getl32 (buf);
14335
14336       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
14337         {
14338           /* We generate a fixup instead of applying it right now
14339              because, if there are linker relaxations, we're going to
14340              need the relocations.  */
14341           exp.X_op = O_symbol;
14342           exp.X_add_symbol = fragp->fr_symbol;
14343           exp.X_add_number = fragp->fr_offset;
14344
14345           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
14346                               4, &exp, TRUE, BFD_RELOC_16_PCREL_S2);
14347           fixp->fx_file = fragp->fr_file;
14348           fixp->fx_line = fragp->fr_line;
14349
14350           md_number_to_chars ((char *) buf, insn, 4);
14351           buf += 4;
14352         }
14353       else
14354         {
14355           int i;
14356
14357           as_warn_where (fragp->fr_file, fragp->fr_line,
14358                          _("relaxed out-of-range branch into a jump"));
14359
14360           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
14361             goto uncond;
14362
14363           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
14364             {
14365               /* Reverse the branch.  */
14366               switch ((insn >> 28) & 0xf)
14367                 {
14368                 case 4:
14369                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
14370                      have the condition reversed by tweaking a single
14371                      bit, and their opcodes all have 0x4???????.  */
14372                   gas_assert ((insn & 0xf1000000) == 0x41000000);
14373                   insn ^= 0x00010000;
14374                   break;
14375
14376                 case 0:
14377                   /* bltz       0x04000000      bgez    0x04010000
14378                      bltzal     0x04100000      bgezal  0x04110000  */
14379                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
14380                   insn ^= 0x00010000;
14381                   break;
14382
14383                 case 1:
14384                   /* beq        0x10000000      bne     0x14000000
14385                      blez       0x18000000      bgtz    0x1c000000  */
14386                   insn ^= 0x04000000;
14387                   break;
14388
14389                 default:
14390                   abort ();
14391                 }
14392             }
14393
14394           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
14395             {
14396               /* Clear the and-link bit.  */
14397               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
14398
14399               /* bltzal         0x04100000      bgezal  0x04110000
14400                  bltzall        0x04120000      bgezall 0x04130000  */
14401               insn &= ~0x00100000;
14402             }
14403
14404           /* Branch over the branch (if the branch was likely) or the
14405              full jump (not likely case).  Compute the offset from the
14406              current instruction to branch to.  */
14407           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
14408             i = 16;
14409           else
14410             {
14411               /* How many bytes in instructions we've already emitted?  */
14412               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
14413               /* How many bytes in instructions from here to the end?  */
14414               i = fragp->fr_var - i;
14415             }
14416           /* Convert to instruction count.  */
14417           i >>= 2;
14418           /* Branch counts from the next instruction.  */
14419           i--;
14420           insn |= i;
14421           /* Branch over the jump.  */
14422           md_number_to_chars ((char *) buf, insn, 4);
14423           buf += 4;
14424
14425           /* nop */
14426           md_number_to_chars ((char *) buf, 0, 4);
14427           buf += 4;
14428
14429           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
14430             {
14431               /* beql $0, $0, 2f */
14432               insn = 0x50000000;
14433               /* Compute the PC offset from the current instruction to
14434                  the end of the variable frag.  */
14435               /* How many bytes in instructions we've already emitted?  */
14436               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
14437               /* How many bytes in instructions from here to the end?  */
14438               i = fragp->fr_var - i;
14439               /* Convert to instruction count.  */
14440               i >>= 2;
14441               /* Don't decrement i, because we want to branch over the
14442                  delay slot.  */
14443
14444               insn |= i;
14445               md_number_to_chars ((char *) buf, insn, 4);
14446               buf += 4;
14447
14448               md_number_to_chars ((char *) buf, 0, 4);
14449               buf += 4;
14450             }
14451
14452         uncond:
14453           if (mips_pic == NO_PIC)
14454             {
14455               /* j or jal.  */
14456               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
14457                       ? 0x0c000000 : 0x08000000);
14458               exp.X_op = O_symbol;
14459               exp.X_add_symbol = fragp->fr_symbol;
14460               exp.X_add_number = fragp->fr_offset;
14461
14462               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
14463                                   4, &exp, FALSE, BFD_RELOC_MIPS_JMP);
14464               fixp->fx_file = fragp->fr_file;
14465               fixp->fx_line = fragp->fr_line;
14466
14467               md_number_to_chars ((char *) buf, insn, 4);
14468               buf += 4;
14469             }
14470           else
14471             {
14472               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
14473               insn = HAVE_64BIT_ADDRESSES ? 0xdf810000 : 0x8f810000;
14474               exp.X_op = O_symbol;
14475               exp.X_add_symbol = fragp->fr_symbol;
14476               exp.X_add_number = fragp->fr_offset;
14477
14478               if (fragp->fr_offset)
14479                 {
14480                   exp.X_add_symbol = make_expr_symbol (&exp);
14481                   exp.X_add_number = 0;
14482                 }
14483
14484               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
14485                                   4, &exp, FALSE, BFD_RELOC_MIPS_GOT16);
14486               fixp->fx_file = fragp->fr_file;
14487               fixp->fx_line = fragp->fr_line;
14488
14489               md_number_to_chars ((char *) buf, insn, 4);
14490               buf += 4;
14491
14492               if (mips_opts.isa == ISA_MIPS1)
14493                 {
14494                   /* nop */
14495                   md_number_to_chars ((char *) buf, 0, 4);
14496                   buf += 4;
14497                 }
14498
14499               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
14500               insn = HAVE_64BIT_ADDRESSES ? 0x64210000 : 0x24210000;
14501
14502               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
14503                                   4, &exp, FALSE, BFD_RELOC_LO16);
14504               fixp->fx_file = fragp->fr_file;
14505               fixp->fx_line = fragp->fr_line;
14506
14507               md_number_to_chars ((char *) buf, insn, 4);
14508               buf += 4;
14509
14510               /* j(al)r $at.  */
14511               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
14512                 insn = 0x0020f809;
14513               else
14514                 insn = 0x00200008;
14515
14516               md_number_to_chars ((char *) buf, insn, 4);
14517               buf += 4;
14518             }
14519         }
14520
14521       gas_assert (buf == (bfd_byte *)fragp->fr_literal
14522               + fragp->fr_fix + fragp->fr_var);
14523
14524       fragp->fr_fix += fragp->fr_var;
14525
14526       return;
14527     }
14528
14529   if (RELAX_MIPS16_P (fragp->fr_subtype))
14530     {
14531       int type;
14532       const struct mips16_immed_operand *op;
14533       bfd_boolean small, ext;
14534       offsetT val;
14535       bfd_byte *buf;
14536       unsigned long insn;
14537       bfd_boolean use_extend;
14538       unsigned short extend;
14539
14540       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
14541       op = mips16_immed_operands;
14542       while (op->type != type)
14543         ++op;
14544
14545       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
14546         {
14547           small = FALSE;
14548           ext = TRUE;
14549         }
14550       else
14551         {
14552           small = TRUE;
14553           ext = FALSE;
14554         }
14555
14556       val = resolve_symbol_value (fragp->fr_symbol);
14557       if (op->pcrel)
14558         {
14559           addressT addr;
14560
14561           addr = fragp->fr_address + fragp->fr_fix;
14562
14563           /* The rules for the base address of a PC relative reloc are
14564              complicated; see mips16_extended_frag.  */
14565           if (type == 'p' || type == 'q')
14566             {
14567               addr += 2;
14568               if (ext)
14569                 addr += 2;
14570               /* Ignore the low bit in the target, since it will be
14571                  set for a text label.  */
14572               if ((val & 1) != 0)
14573                 --val;
14574             }
14575           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
14576             addr -= 4;
14577           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
14578             addr -= 2;
14579
14580           addr &= ~ (addressT) ((1 << op->shift) - 1);
14581           val -= addr;
14582
14583           /* Make sure the section winds up with the alignment we have
14584              assumed.  */
14585           if (op->shift > 0)
14586             record_alignment (asec, op->shift);
14587         }
14588
14589       if (ext
14590           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
14591               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
14592         as_warn_where (fragp->fr_file, fragp->fr_line,
14593                        _("extended instruction in delay slot"));
14594
14595       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
14596
14597       if (target_big_endian)
14598         insn = bfd_getb16 (buf);
14599       else
14600         insn = bfd_getl16 (buf);
14601
14602       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
14603                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
14604                     small, ext, &insn, &use_extend, &extend);
14605
14606       if (use_extend)
14607         {
14608           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
14609           fragp->fr_fix += 2;
14610           buf += 2;
14611         }
14612
14613       md_number_to_chars ((char *) buf, insn, 2);
14614       fragp->fr_fix += 2;
14615       buf += 2;
14616     }
14617   else
14618     {
14619       int first, second;
14620       fixS *fixp;
14621
14622       first = RELAX_FIRST (fragp->fr_subtype);
14623       second = RELAX_SECOND (fragp->fr_subtype);
14624       fixp = (fixS *) fragp->fr_opcode;
14625
14626       /* Possibly emit a warning if we've chosen the longer option.  */
14627       if (((fragp->fr_subtype & RELAX_USE_SECOND) != 0)
14628           == ((fragp->fr_subtype & RELAX_SECOND_LONGER) != 0))
14629         {
14630           const char *msg = macro_warning (fragp->fr_subtype);
14631           if (msg != 0)
14632             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
14633         }
14634
14635       /* Go through all the fixups for the first sequence.  Disable them
14636          (by marking them as done) if we're going to use the second
14637          sequence instead.  */
14638       while (fixp
14639              && fixp->fx_frag == fragp
14640              && fixp->fx_where < fragp->fr_fix - second)
14641         {
14642           if (fragp->fr_subtype & RELAX_USE_SECOND)
14643             fixp->fx_done = 1;
14644           fixp = fixp->fx_next;
14645         }
14646
14647       /* Go through the fixups for the second sequence.  Disable them if
14648          we're going to use the first sequence, otherwise adjust their
14649          addresses to account for the relaxation.  */
14650       while (fixp && fixp->fx_frag == fragp)
14651         {
14652           if (fragp->fr_subtype & RELAX_USE_SECOND)
14653             fixp->fx_where -= first;
14654           else
14655             fixp->fx_done = 1;
14656           fixp = fixp->fx_next;
14657         }
14658
14659       /* Now modify the frag contents.  */
14660       if (fragp->fr_subtype & RELAX_USE_SECOND)
14661         {
14662           char *start;
14663
14664           start = fragp->fr_literal + fragp->fr_fix - first - second;
14665           memmove (start, start + first, second);
14666           fragp->fr_fix -= first;
14667         }
14668       else
14669         fragp->fr_fix -= second;
14670     }
14671 }
14672
14673 #ifdef OBJ_ELF
14674
14675 /* This function is called after the relocs have been generated.
14676    We've been storing mips16 text labels as odd.  Here we convert them
14677    back to even for the convenience of the debugger.  */
14678
14679 void
14680 mips_frob_file_after_relocs (void)
14681 {
14682   asymbol **syms;
14683   unsigned int count, i;
14684
14685   if (!IS_ELF)
14686     return;
14687
14688   syms = bfd_get_outsymbols (stdoutput);
14689   count = bfd_get_symcount (stdoutput);
14690   for (i = 0; i < count; i++, syms++)
14691     {
14692       if (ELF_ST_IS_MIPS16 (elf_symbol (*syms)->internal_elf_sym.st_other)
14693           && ((*syms)->value & 1) != 0)
14694         {
14695           (*syms)->value &= ~1;
14696           /* If the symbol has an odd size, it was probably computed
14697              incorrectly, so adjust that as well.  */
14698           if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
14699             ++elf_symbol (*syms)->internal_elf_sym.st_size;
14700         }
14701     }
14702 }
14703
14704 #endif
14705
14706 /* This function is called whenever a label is defined.  It is used
14707    when handling branch delays; if a branch has a label, we assume we
14708    can not move it.  */
14709
14710 void
14711 mips_define_label (symbolS *sym)
14712 {
14713   segment_info_type *si = seg_info (now_seg);
14714   struct insn_label_list *l;
14715
14716   if (free_insn_labels == NULL)
14717     l = (struct insn_label_list *) xmalloc (sizeof *l);
14718   else
14719     {
14720       l = free_insn_labels;
14721       free_insn_labels = l->next;
14722     }
14723
14724   l->label = sym;
14725   l->next = si->label_list;
14726   si->label_list = l;
14727
14728 #ifdef OBJ_ELF
14729   dwarf2_emit_label (sym);
14730 #endif
14731 }
14732 \f
14733 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
14734
14735 /* Some special processing for a MIPS ELF file.  */
14736
14737 void
14738 mips_elf_final_processing (void)
14739 {
14740   /* Write out the register information.  */
14741   if (mips_abi != N64_ABI)
14742     {
14743       Elf32_RegInfo s;
14744
14745       s.ri_gprmask = mips_gprmask;
14746       s.ri_cprmask[0] = mips_cprmask[0];
14747       s.ri_cprmask[1] = mips_cprmask[1];
14748       s.ri_cprmask[2] = mips_cprmask[2];
14749       s.ri_cprmask[3] = mips_cprmask[3];
14750       /* The gp_value field is set by the MIPS ELF backend.  */
14751
14752       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
14753                                        ((Elf32_External_RegInfo *)
14754                                         mips_regmask_frag));
14755     }
14756   else
14757     {
14758       Elf64_Internal_RegInfo s;
14759
14760       s.ri_gprmask = mips_gprmask;
14761       s.ri_pad = 0;
14762       s.ri_cprmask[0] = mips_cprmask[0];
14763       s.ri_cprmask[1] = mips_cprmask[1];
14764       s.ri_cprmask[2] = mips_cprmask[2];
14765       s.ri_cprmask[3] = mips_cprmask[3];
14766       /* The gp_value field is set by the MIPS ELF backend.  */
14767
14768       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
14769                                        ((Elf64_External_RegInfo *)
14770                                         mips_regmask_frag));
14771     }
14772
14773   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
14774      sort of BFD interface for this.  */
14775   if (mips_any_noreorder)
14776     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
14777   if (mips_pic != NO_PIC)
14778     {
14779     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
14780       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
14781     }
14782   if (mips_abicalls)
14783     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
14784
14785   /* Set MIPS ELF flags for ASEs.  */
14786   /* We may need to define a new flag for DSP ASE, and set this flag when
14787      file_ase_dsp is true.  */
14788   /* Same for DSP R2.  */
14789   /* We may need to define a new flag for MT ASE, and set this flag when
14790      file_ase_mt is true.  */
14791   if (file_ase_mips16)
14792     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
14793 #if 0 /* XXX FIXME */
14794   if (file_ase_mips3d)
14795     elf_elfheader (stdoutput)->e_flags |= ???;
14796 #endif
14797   if (file_ase_mdmx)
14798     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
14799
14800   /* Set the MIPS ELF ABI flags.  */
14801   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
14802     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
14803   else if (mips_abi == O64_ABI)
14804     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
14805   else if (mips_abi == EABI_ABI)
14806     {
14807       if (!file_mips_gp32)
14808         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
14809       else
14810         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
14811     }
14812   else if (mips_abi == N32_ABI)
14813     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
14814
14815   /* Nothing to do for N64_ABI.  */
14816
14817   if (mips_32bitmode)
14818     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
14819
14820 #if 0 /* XXX FIXME */
14821   /* 32 bit code with 64 bit FP registers.  */
14822   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
14823     elf_elfheader (stdoutput)->e_flags |= ???;
14824 #endif
14825 }
14826
14827 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
14828 \f
14829 typedef struct proc {
14830   symbolS *func_sym;
14831   symbolS *func_end_sym;
14832   unsigned long reg_mask;
14833   unsigned long reg_offset;
14834   unsigned long fpreg_mask;
14835   unsigned long fpreg_offset;
14836   unsigned long frame_offset;
14837   unsigned long frame_reg;
14838   unsigned long pc_reg;
14839 } procS;
14840
14841 static procS cur_proc;
14842 static procS *cur_proc_ptr;
14843 static int numprocs;
14844
14845 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1" and a normal
14846    nop as "0".  */
14847
14848 char
14849 mips_nop_opcode (void)
14850 {
14851   return seg_info (now_seg)->tc_segment_info_data.mips16;
14852 }
14853
14854 /* Fill in an rs_align_code fragment.  This only needs to do something
14855    for MIPS16 code, where 0 is not a nop.  */
14856
14857 void
14858 mips_handle_align (fragS *fragp)
14859 {
14860   char *p;
14861   int bytes, size, excess;
14862   valueT opcode;
14863
14864   if (fragp->fr_type != rs_align_code)
14865     return;
14866
14867   p = fragp->fr_literal + fragp->fr_fix;
14868   if (*p)
14869     {
14870       opcode = mips16_nop_insn.insn_opcode;
14871       size = 2;
14872     }
14873   else
14874     {
14875       opcode = nop_insn.insn_opcode;
14876       size = 4;
14877     }
14878
14879   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
14880   excess = bytes % size;
14881   if (excess != 0)
14882     {
14883       /* If we're not inserting a whole number of instructions,
14884          pad the end of the fixed part of the frag with zeros.  */
14885       memset (p, 0, excess);
14886       p += excess;
14887       fragp->fr_fix += excess;
14888     }
14889
14890   md_number_to_chars (p, opcode, size);
14891   fragp->fr_var = size;
14892 }
14893
14894 static void
14895 md_obj_begin (void)
14896 {
14897 }
14898
14899 static void
14900 md_obj_end (void)
14901 {
14902   /* Check for premature end, nesting errors, etc.  */
14903   if (cur_proc_ptr)
14904     as_warn (_("missing .end at end of assembly"));
14905 }
14906
14907 static long
14908 get_number (void)
14909 {
14910   int negative = 0;
14911   long val = 0;
14912
14913   if (*input_line_pointer == '-')
14914     {
14915       ++input_line_pointer;
14916       negative = 1;
14917     }
14918   if (!ISDIGIT (*input_line_pointer))
14919     as_bad (_("expected simple number"));
14920   if (input_line_pointer[0] == '0')
14921     {
14922       if (input_line_pointer[1] == 'x')
14923         {
14924           input_line_pointer += 2;
14925           while (ISXDIGIT (*input_line_pointer))
14926             {
14927               val <<= 4;
14928               val |= hex_value (*input_line_pointer++);
14929             }
14930           return negative ? -val : val;
14931         }
14932       else
14933         {
14934           ++input_line_pointer;
14935           while (ISDIGIT (*input_line_pointer))
14936             {
14937               val <<= 3;
14938               val |= *input_line_pointer++ - '0';
14939             }
14940           return negative ? -val : val;
14941         }
14942     }
14943   if (!ISDIGIT (*input_line_pointer))
14944     {
14945       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
14946               *input_line_pointer, *input_line_pointer);
14947       as_warn (_("invalid number"));
14948       return -1;
14949     }
14950   while (ISDIGIT (*input_line_pointer))
14951     {
14952       val *= 10;
14953       val += *input_line_pointer++ - '0';
14954     }
14955   return negative ? -val : val;
14956 }
14957
14958 /* The .file directive; just like the usual .file directive, but there
14959    is an initial number which is the ECOFF file index.  In the non-ECOFF
14960    case .file implies DWARF-2.  */
14961
14962 static void
14963 s_mips_file (int x ATTRIBUTE_UNUSED)
14964 {
14965   static int first_file_directive = 0;
14966
14967   if (ECOFF_DEBUGGING)
14968     {
14969       get_number ();
14970       s_app_file (0);
14971     }
14972   else
14973     {
14974       char *filename;
14975
14976       filename = dwarf2_directive_file (0);
14977
14978       /* Versions of GCC up to 3.1 start files with a ".file"
14979          directive even for stabs output.  Make sure that this
14980          ".file" is handled.  Note that you need a version of GCC
14981          after 3.1 in order to support DWARF-2 on MIPS.  */
14982       if (filename != NULL && ! first_file_directive)
14983         {
14984           (void) new_logical_line (filename, -1);
14985           s_app_file_string (filename, 0);
14986         }
14987       first_file_directive = 1;
14988     }
14989 }
14990
14991 /* The .loc directive, implying DWARF-2.  */
14992
14993 static void
14994 s_mips_loc (int x ATTRIBUTE_UNUSED)
14995 {
14996   if (!ECOFF_DEBUGGING)
14997     dwarf2_directive_loc (0);
14998 }
14999
15000 /* The .end directive.  */
15001
15002 static void
15003 s_mips_end (int x ATTRIBUTE_UNUSED)
15004 {
15005   symbolS *p;
15006
15007   /* Following functions need their own .frame and .cprestore directives.  */
15008   mips_frame_reg_valid = 0;
15009   mips_cprestore_valid = 0;
15010
15011   if (!is_end_of_line[(unsigned char) *input_line_pointer])
15012     {
15013       p = get_symbol ();
15014       demand_empty_rest_of_line ();
15015     }
15016   else
15017     p = NULL;
15018
15019   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
15020     as_warn (_(".end not in text section"));
15021
15022   if (!cur_proc_ptr)
15023     {
15024       as_warn (_(".end directive without a preceding .ent directive."));
15025       demand_empty_rest_of_line ();
15026       return;
15027     }
15028
15029   if (p != NULL)
15030     {
15031       gas_assert (S_GET_NAME (p));
15032       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
15033         as_warn (_(".end symbol does not match .ent symbol."));
15034
15035       if (debug_type == DEBUG_STABS)
15036         stabs_generate_asm_endfunc (S_GET_NAME (p),
15037                                     S_GET_NAME (p));
15038     }
15039   else
15040     as_warn (_(".end directive missing or unknown symbol"));
15041
15042 #ifdef OBJ_ELF
15043   /* Create an expression to calculate the size of the function.  */
15044   if (p && cur_proc_ptr)
15045     {
15046       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
15047       expressionS *exp = xmalloc (sizeof (expressionS));
15048
15049       obj->size = exp;
15050       exp->X_op = O_subtract;
15051       exp->X_add_symbol = symbol_temp_new_now ();
15052       exp->X_op_symbol = p;
15053       exp->X_add_number = 0;
15054
15055       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
15056     }
15057
15058   /* Generate a .pdr section.  */
15059   if (IS_ELF && !ECOFF_DEBUGGING && mips_flag_pdr)
15060     {
15061       segT saved_seg = now_seg;
15062       subsegT saved_subseg = now_subseg;
15063       expressionS exp;
15064       char *fragp;
15065
15066 #ifdef md_flush_pending_output
15067       md_flush_pending_output ();
15068 #endif
15069
15070       gas_assert (pdr_seg);
15071       subseg_set (pdr_seg, 0);
15072
15073       /* Write the symbol.  */
15074       exp.X_op = O_symbol;
15075       exp.X_add_symbol = p;
15076       exp.X_add_number = 0;
15077       emit_expr (&exp, 4);
15078
15079       fragp = frag_more (7 * 4);
15080
15081       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
15082       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
15083       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
15084       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
15085       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
15086       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
15087       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
15088
15089       subseg_set (saved_seg, saved_subseg);
15090     }
15091 #endif /* OBJ_ELF */
15092
15093   cur_proc_ptr = NULL;
15094 }
15095
15096 /* The .aent and .ent directives.  */
15097
15098 static void
15099 s_mips_ent (int aent)
15100 {
15101   symbolS *symbolP;
15102
15103   symbolP = get_symbol ();
15104   if (*input_line_pointer == ',')
15105     ++input_line_pointer;
15106   SKIP_WHITESPACE ();
15107   if (ISDIGIT (*input_line_pointer)
15108       || *input_line_pointer == '-')
15109     get_number ();
15110
15111   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
15112     as_warn (_(".ent or .aent not in text section."));
15113
15114   if (!aent && cur_proc_ptr)
15115     as_warn (_("missing .end"));
15116
15117   if (!aent)
15118     {
15119       /* This function needs its own .frame and .cprestore directives.  */
15120       mips_frame_reg_valid = 0;
15121       mips_cprestore_valid = 0;
15122
15123       cur_proc_ptr = &cur_proc;
15124       memset (cur_proc_ptr, '\0', sizeof (procS));
15125
15126       cur_proc_ptr->func_sym = symbolP;
15127
15128       ++numprocs;
15129
15130       if (debug_type == DEBUG_STABS)
15131         stabs_generate_asm_func (S_GET_NAME (symbolP),
15132                                  S_GET_NAME (symbolP));
15133     }
15134
15135   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
15136
15137   demand_empty_rest_of_line ();
15138 }
15139
15140 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
15141    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
15142    s_mips_frame is used so that we can set the PDR information correctly.
15143    We can't use the ecoff routines because they make reference to the ecoff
15144    symbol table (in the mdebug section).  */
15145
15146 static void
15147 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
15148 {
15149 #ifdef OBJ_ELF
15150   if (IS_ELF && !ECOFF_DEBUGGING)
15151     {
15152       long val;
15153
15154       if (cur_proc_ptr == (procS *) NULL)
15155         {
15156           as_warn (_(".frame outside of .ent"));
15157           demand_empty_rest_of_line ();
15158           return;
15159         }
15160
15161       cur_proc_ptr->frame_reg = tc_get_register (1);
15162
15163       SKIP_WHITESPACE ();
15164       if (*input_line_pointer++ != ','
15165           || get_absolute_expression_and_terminator (&val) != ',')
15166         {
15167           as_warn (_("Bad .frame directive"));
15168           --input_line_pointer;
15169           demand_empty_rest_of_line ();
15170           return;
15171         }
15172
15173       cur_proc_ptr->frame_offset = val;
15174       cur_proc_ptr->pc_reg = tc_get_register (0);
15175
15176       demand_empty_rest_of_line ();
15177     }
15178   else
15179 #endif /* OBJ_ELF */
15180     s_ignore (ignore);
15181 }
15182
15183 /* The .fmask and .mask directives. If the mdebug section is present
15184    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
15185    embedded targets, s_mips_mask is used so that we can set the PDR
15186    information correctly. We can't use the ecoff routines because they
15187    make reference to the ecoff symbol table (in the mdebug section).  */
15188
15189 static void
15190 s_mips_mask (int reg_type)
15191 {
15192 #ifdef OBJ_ELF
15193   if (IS_ELF && !ECOFF_DEBUGGING)
15194     {
15195       long mask, off;
15196
15197       if (cur_proc_ptr == (procS *) NULL)
15198         {
15199           as_warn (_(".mask/.fmask outside of .ent"));
15200           demand_empty_rest_of_line ();
15201           return;
15202         }
15203
15204       if (get_absolute_expression_and_terminator (&mask) != ',')
15205         {
15206           as_warn (_("Bad .mask/.fmask directive"));
15207           --input_line_pointer;
15208           demand_empty_rest_of_line ();
15209           return;
15210         }
15211
15212       off = get_absolute_expression ();
15213
15214       if (reg_type == 'F')
15215         {
15216           cur_proc_ptr->fpreg_mask = mask;
15217           cur_proc_ptr->fpreg_offset = off;
15218         }
15219       else
15220         {
15221           cur_proc_ptr->reg_mask = mask;
15222           cur_proc_ptr->reg_offset = off;
15223         }
15224
15225       demand_empty_rest_of_line ();
15226     }
15227   else
15228 #endif /* OBJ_ELF */
15229     s_ignore (reg_type);
15230 }
15231
15232 /* A table describing all the processors gas knows about.  Names are
15233    matched in the order listed.
15234
15235    To ease comparison, please keep this table in the same order as
15236    gcc's mips_cpu_info_table[].  */
15237 static const struct mips_cpu_info mips_cpu_info_table[] =
15238 {
15239   /* Entries for generic ISAs */
15240   { "mips1",          MIPS_CPU_IS_ISA,          ISA_MIPS1,      CPU_R3000 },
15241   { "mips2",          MIPS_CPU_IS_ISA,          ISA_MIPS2,      CPU_R6000 },
15242   { "mips3",          MIPS_CPU_IS_ISA,          ISA_MIPS3,      CPU_R4000 },
15243   { "mips4",          MIPS_CPU_IS_ISA,          ISA_MIPS4,      CPU_R8000 },
15244   { "mips5",          MIPS_CPU_IS_ISA,          ISA_MIPS5,      CPU_MIPS5 },
15245   { "mips32",         MIPS_CPU_IS_ISA,          ISA_MIPS32,     CPU_MIPS32 },
15246   { "mips32r2",       MIPS_CPU_IS_ISA,          ISA_MIPS32R2,   CPU_MIPS32R2 },
15247   { "mips64",         MIPS_CPU_IS_ISA,          ISA_MIPS64,     CPU_MIPS64 },
15248   { "mips64r2",       MIPS_CPU_IS_ISA,          ISA_MIPS64R2,   CPU_MIPS64R2 },
15249
15250   /* MIPS I */
15251   { "r3000",          0,                        ISA_MIPS1,      CPU_R3000 },
15252   { "r2000",          0,                        ISA_MIPS1,      CPU_R3000 },
15253   { "r3900",          0,                        ISA_MIPS1,      CPU_R3900 },
15254
15255   /* MIPS II */
15256   { "r6000",          0,                        ISA_MIPS2,      CPU_R6000 },
15257
15258   /* MIPS III */
15259   { "r4000",          0,                        ISA_MIPS3,      CPU_R4000 },
15260   { "r4010",          0,                        ISA_MIPS2,      CPU_R4010 },
15261   { "vr4100",         0,                        ISA_MIPS3,      CPU_VR4100 },
15262   { "vr4111",         0,                        ISA_MIPS3,      CPU_R4111 },
15263   { "vr4120",         0,                        ISA_MIPS3,      CPU_VR4120 },
15264   { "vr4130",         0,                        ISA_MIPS3,      CPU_VR4120 },
15265   { "vr4181",         0,                        ISA_MIPS3,      CPU_R4111 },
15266   { "vr4300",         0,                        ISA_MIPS3,      CPU_R4300 },
15267   { "r4400",          0,                        ISA_MIPS3,      CPU_R4400 },
15268   { "r4600",          0,                        ISA_MIPS3,      CPU_R4600 },
15269   { "orion",          0,                        ISA_MIPS3,      CPU_R4600 },
15270   { "r4650",          0,                        ISA_MIPS3,      CPU_R4650 },
15271   /* ST Microelectronics Loongson 2E and 2F cores */
15272   { "loongson2e",     0,                        ISA_MIPS3,   CPU_LOONGSON_2E },
15273   { "loongson2f",     0,                        ISA_MIPS3,   CPU_LOONGSON_2F },
15274
15275   /* MIPS IV */
15276   { "r8000",          0,                        ISA_MIPS4,      CPU_R8000 },
15277   { "r10000",         0,                        ISA_MIPS4,      CPU_R10000 },
15278   { "r12000",         0,                        ISA_MIPS4,      CPU_R12000 },
15279   { "r14000",         0,                        ISA_MIPS4,      CPU_R14000 },
15280   { "r16000",         0,                        ISA_MIPS4,      CPU_R16000 },
15281   { "vr5000",         0,                        ISA_MIPS4,      CPU_R5000 },
15282   { "vr5400",         0,                        ISA_MIPS4,      CPU_VR5400 },
15283   { "vr5500",         0,                        ISA_MIPS4,      CPU_VR5500 },
15284   { "rm5200",         0,                        ISA_MIPS4,      CPU_R5000 },
15285   { "rm5230",         0,                        ISA_MIPS4,      CPU_R5000 },
15286   { "rm5231",         0,                        ISA_MIPS4,      CPU_R5000 },
15287   { "rm5261",         0,                        ISA_MIPS4,      CPU_R5000 },
15288   { "rm5721",         0,                        ISA_MIPS4,      CPU_R5000 },
15289   { "rm7000",         0,                        ISA_MIPS4,      CPU_RM7000 },
15290   { "rm9000",         0,                        ISA_MIPS4,      CPU_RM9000 },
15291
15292   /* MIPS 32 */
15293   { "4kc",            0,                        ISA_MIPS32,     CPU_MIPS32 },
15294   { "4km",            0,                        ISA_MIPS32,     CPU_MIPS32 },
15295   { "4kp",            0,                        ISA_MIPS32,     CPU_MIPS32 },
15296   { "4ksc",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32,     CPU_MIPS32 },
15297
15298   /* MIPS 32 Release 2 */
15299   { "4kec",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15300   { "4kem",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15301   { "4kep",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15302   { "4ksd",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32R2,   CPU_MIPS32R2 },
15303   { "m4k",            0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15304   { "m4kp",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15305   { "24kc",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15306   { "24kf2_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15307   { "24kf",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15308   { "24kf1_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15309   /* Deprecated forms of the above.  */
15310   { "24kfx",          0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15311   { "24kx",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
15312   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
15313   { "24kec",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15314   { "24kef2_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15315   { "24kef",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15316   { "24kef1_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15317   /* Deprecated forms of the above.  */
15318   { "24kefx",         MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15319   { "24kex",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
15320   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
15321   { "34kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15322                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15323   { "34kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15324                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15325   { "34kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15326                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15327   { "34kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15328                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15329   /* Deprecated forms of the above.  */
15330   { "34kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15331                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15332   { "34kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15333                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15334   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
15335   { "74kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15336                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15337   { "74kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15338                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15339   { "74kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15340                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15341   { "74kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15342                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15343   { "74kf3_2",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15344                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15345   /* Deprecated forms of the above.  */
15346   { "74kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15347                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15348   { "74kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
15349                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15350   /* 1004K cores are multiprocessor versions of the 34K.  */
15351   { "1004kc",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15352                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15353   { "1004kf2_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15354                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15355   { "1004kf",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15356                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15357   { "1004kf1_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
15358                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
15359
15360   /* MIPS 64 */
15361   { "5kc",            0,                        ISA_MIPS64,     CPU_MIPS64 },
15362   { "5kf",            0,                        ISA_MIPS64,     CPU_MIPS64 },
15363   { "20kc",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
15364   { "25kf",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
15365
15366   /* Broadcom SB-1 CPU core */
15367   { "sb1",            MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
15368                                                 ISA_MIPS64,     CPU_SB1 },
15369   /* Broadcom SB-1A CPU core */
15370   { "sb1a",           MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
15371                                                 ISA_MIPS64,     CPU_SB1 },
15372   
15373   { "loongson3a",     0,                        ISA_MIPS64,     CPU_LOONGSON_3A },
15374
15375   /* MIPS 64 Release 2 */
15376
15377   /* Cavium Networks Octeon CPU core */
15378   { "octeon",         0,      ISA_MIPS64R2,   CPU_OCTEON },
15379
15380   /* RMI Xlr */
15381   { "xlr",            0,      ISA_MIPS64,     CPU_XLR },
15382
15383   /* End marker */
15384   { NULL, 0, 0, 0 }
15385 };
15386
15387
15388 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
15389    with a final "000" replaced by "k".  Ignore case.
15390
15391    Note: this function is shared between GCC and GAS.  */
15392
15393 static bfd_boolean
15394 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
15395 {
15396   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
15397     given++, canonical++;
15398
15399   return ((*given == 0 && *canonical == 0)
15400           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
15401 }
15402
15403
15404 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
15405    CPU name.  We've traditionally allowed a lot of variation here.
15406
15407    Note: this function is shared between GCC and GAS.  */
15408
15409 static bfd_boolean
15410 mips_matching_cpu_name_p (const char *canonical, const char *given)
15411 {
15412   /* First see if the name matches exactly, or with a final "000"
15413      turned into "k".  */
15414   if (mips_strict_matching_cpu_name_p (canonical, given))
15415     return TRUE;
15416
15417   /* If not, try comparing based on numerical designation alone.
15418      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
15419   if (TOLOWER (*given) == 'r')
15420     given++;
15421   if (!ISDIGIT (*given))
15422     return FALSE;
15423
15424   /* Skip over some well-known prefixes in the canonical name,
15425      hoping to find a number there too.  */
15426   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
15427     canonical += 2;
15428   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
15429     canonical += 2;
15430   else if (TOLOWER (canonical[0]) == 'r')
15431     canonical += 1;
15432
15433   return mips_strict_matching_cpu_name_p (canonical, given);
15434 }
15435
15436
15437 /* Parse an option that takes the name of a processor as its argument.
15438    OPTION is the name of the option and CPU_STRING is the argument.
15439    Return the corresponding processor enumeration if the CPU_STRING is
15440    recognized, otherwise report an error and return null.
15441
15442    A similar function exists in GCC.  */
15443
15444 static const struct mips_cpu_info *
15445 mips_parse_cpu (const char *option, const char *cpu_string)
15446 {
15447   const struct mips_cpu_info *p;
15448
15449   /* 'from-abi' selects the most compatible architecture for the given
15450      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
15451      EABIs, we have to decide whether we're using the 32-bit or 64-bit
15452      version.  Look first at the -mgp options, if given, otherwise base
15453      the choice on MIPS_DEFAULT_64BIT.
15454
15455      Treat NO_ABI like the EABIs.  One reason to do this is that the
15456      plain 'mips' and 'mips64' configs have 'from-abi' as their default
15457      architecture.  This code picks MIPS I for 'mips' and MIPS III for
15458      'mips64', just as we did in the days before 'from-abi'.  */
15459   if (strcasecmp (cpu_string, "from-abi") == 0)
15460     {
15461       if (ABI_NEEDS_32BIT_REGS (mips_abi))
15462         return mips_cpu_info_from_isa (ISA_MIPS1);
15463
15464       if (ABI_NEEDS_64BIT_REGS (mips_abi))
15465         return mips_cpu_info_from_isa (ISA_MIPS3);
15466
15467       if (file_mips_gp32 >= 0)
15468         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
15469
15470       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
15471                                      ? ISA_MIPS3
15472                                      : ISA_MIPS1);
15473     }
15474
15475   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
15476   if (strcasecmp (cpu_string, "default") == 0)
15477     return 0;
15478
15479   for (p = mips_cpu_info_table; p->name != 0; p++)
15480     if (mips_matching_cpu_name_p (p->name, cpu_string))
15481       return p;
15482
15483   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
15484   return 0;
15485 }
15486
15487 /* Return the canonical processor information for ISA (a member of the
15488    ISA_MIPS* enumeration).  */
15489
15490 static const struct mips_cpu_info *
15491 mips_cpu_info_from_isa (int isa)
15492 {
15493   int i;
15494
15495   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
15496     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
15497         && isa == mips_cpu_info_table[i].isa)
15498       return (&mips_cpu_info_table[i]);
15499
15500   return NULL;
15501 }
15502
15503 static const struct mips_cpu_info *
15504 mips_cpu_info_from_arch (int arch)
15505 {
15506   int i;
15507
15508   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
15509     if (arch == mips_cpu_info_table[i].cpu)
15510       return (&mips_cpu_info_table[i]);
15511
15512   return NULL;
15513 }
15514 \f
15515 static void
15516 show (FILE *stream, const char *string, int *col_p, int *first_p)
15517 {
15518   if (*first_p)
15519     {
15520       fprintf (stream, "%24s", "");
15521       *col_p = 24;
15522     }
15523   else
15524     {
15525       fprintf (stream, ", ");
15526       *col_p += 2;
15527     }
15528
15529   if (*col_p + strlen (string) > 72)
15530     {
15531       fprintf (stream, "\n%24s", "");
15532       *col_p = 24;
15533     }
15534
15535   fprintf (stream, "%s", string);
15536   *col_p += strlen (string);
15537
15538   *first_p = 0;
15539 }
15540
15541 void
15542 md_show_usage (FILE *stream)
15543 {
15544   int column, first;
15545   size_t i;
15546
15547   fprintf (stream, _("\
15548 MIPS options:\n\
15549 -EB                     generate big endian output\n\
15550 -EL                     generate little endian output\n\
15551 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
15552 -G NUM                  allow referencing objects up to NUM bytes\n\
15553                         implicitly with the gp register [default 8]\n"));
15554   fprintf (stream, _("\
15555 -mips1                  generate MIPS ISA I instructions\n\
15556 -mips2                  generate MIPS ISA II instructions\n\
15557 -mips3                  generate MIPS ISA III instructions\n\
15558 -mips4                  generate MIPS ISA IV instructions\n\
15559 -mips5                  generate MIPS ISA V instructions\n\
15560 -mips32                 generate MIPS32 ISA instructions\n\
15561 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
15562 -mips64                 generate MIPS64 ISA instructions\n\
15563 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
15564 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
15565
15566   first = 1;
15567
15568   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
15569     show (stream, mips_cpu_info_table[i].name, &column, &first);
15570   show (stream, "from-abi", &column, &first);
15571   fputc ('\n', stream);
15572
15573   fprintf (stream, _("\
15574 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
15575 -no-mCPU                don't generate code specific to CPU.\n\
15576                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
15577
15578   first = 1;
15579
15580   show (stream, "3900", &column, &first);
15581   show (stream, "4010", &column, &first);
15582   show (stream, "4100", &column, &first);
15583   show (stream, "4650", &column, &first);
15584   fputc ('\n', stream);
15585
15586   fprintf (stream, _("\
15587 -mips16                 generate mips16 instructions\n\
15588 -no-mips16              do not generate mips16 instructions\n"));
15589   fprintf (stream, _("\
15590 -msmartmips             generate smartmips instructions\n\
15591 -mno-smartmips          do not generate smartmips instructions\n"));  
15592   fprintf (stream, _("\
15593 -mdsp                   generate DSP instructions\n\
15594 -mno-dsp                do not generate DSP instructions\n"));
15595   fprintf (stream, _("\
15596 -mdspr2                 generate DSP R2 instructions\n\
15597 -mno-dspr2              do not generate DSP R2 instructions\n"));
15598   fprintf (stream, _("\
15599 -mmt                    generate MT instructions\n\
15600 -mno-mt                 do not generate MT instructions\n"));
15601   fprintf (stream, _("\
15602 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
15603 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
15604 -mfix-vr4120            work around certain VR4120 errata\n\
15605 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
15606 -mfix-24k               insert a nop after ERET and DERET instructions\n\
15607 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
15608 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
15609 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
15610 -msym32                 assume all symbols have 32-bit values\n\
15611 -O0                     remove unneeded NOPs, do not swap branches\n\
15612 -O                      remove unneeded NOPs and swap branches\n\
15613 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
15614 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
15615   fprintf (stream, _("\
15616 -mhard-float            allow floating-point instructions\n\
15617 -msoft-float            do not allow floating-point instructions\n\
15618 -msingle-float          only allow 32-bit floating-point operations\n\
15619 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
15620 --[no-]construct-floats [dis]allow floating point values to be constructed\n"
15621                      ));
15622 #ifdef OBJ_ELF
15623   fprintf (stream, _("\
15624 -KPIC, -call_shared     generate SVR4 position independent code\n\
15625 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
15626 -mvxworks-pic           generate VxWorks position independent code\n\
15627 -non_shared             do not generate code that can operate with DSOs\n\
15628 -xgot                   assume a 32 bit GOT\n\
15629 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
15630 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
15631                         position dependent (non shared) code\n\
15632 -mabi=ABI               create ABI conformant object file for:\n"));
15633
15634   first = 1;
15635
15636   show (stream, "32", &column, &first);
15637   show (stream, "o64", &column, &first);
15638   show (stream, "n32", &column, &first);
15639   show (stream, "64", &column, &first);
15640   show (stream, "eabi", &column, &first);
15641
15642   fputc ('\n', stream);
15643
15644   fprintf (stream, _("\
15645 -32                     create o32 ABI object file (default)\n\
15646 -n32                    create n32 ABI object file\n\
15647 -64                     create 64 ABI object file\n"));
15648 #endif
15649 }
15650
15651 #ifdef TE_IRIX
15652 enum dwarf2_format
15653 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
15654 {
15655   if (HAVE_64BIT_SYMBOLS)
15656     return dwarf2_format_64bit_irix;
15657   else
15658     return dwarf2_format_32bit;
15659 }
15660 #endif
15661
15662 int
15663 mips_dwarf2_addr_size (void)
15664 {
15665   if (HAVE_64BIT_OBJECTS)
15666     return 8;
15667   else
15668     return 4;
15669 }
15670
15671 /* Standard calling conventions leave the CFA at SP on entry.  */
15672 void
15673 mips_cfi_frame_initial_instructions (void)
15674 {
15675   cfi_add_CFA_def_cfa_register (SP);
15676 }
15677
15678 int
15679 tc_mips_regname_to_dw2regnum (char *regname)
15680 {
15681   unsigned int regnum = -1;
15682   unsigned int reg;
15683
15684   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
15685     regnum = reg;
15686
15687   return regnum;
15688 }