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 S0  16
95 #define S7  23
96 #define TREG 24
97 #define PIC_CALL_REG 25
98 #define KT0 26
99 #define KT1 27
100 #define GP  28
101 #define SP  29
102 #define FP  30
103 #define RA  31
104
105 #define ILLEGAL_REG (32)
106
107 #define AT  mips_opts.at
108
109 /* Allow override of standard little-endian ECOFF format.  */
110
111 #ifndef ECOFF_LITTLE_FORMAT
112 #define ECOFF_LITTLE_FORMAT "ecoff-littlemips"
113 #endif
114
115 extern int target_big_endian;
116
117 /* The name of the readonly data section.  */
118 #define RDATA_SECTION_NAME (OUTPUT_FLAVOR == bfd_target_ecoff_flavour \
119                             ? ".rdata" \
120                             : OUTPUT_FLAVOR == bfd_target_coff_flavour \
121                             ? ".rdata" \
122                             : OUTPUT_FLAVOR == bfd_target_elf_flavour \
123                             ? ".rodata" \
124                             : (abort (), ""))
125
126 /* Ways in which an instruction can be "appended" to the output.  */
127 enum append_method {
128   /* Just add it normally.  */
129   APPEND_ADD,
130
131   /* Add it normally and then add a nop.  */
132   APPEND_ADD_WITH_NOP,
133
134   /* Turn an instruction with a delay slot into a "compact" version.  */
135   APPEND_ADD_COMPACT,
136
137   /* Insert the instruction before the last one.  */
138   APPEND_SWAP
139 };
140
141 /* Information about an instruction, including its format, operands
142    and fixups.  */
143 struct mips_cl_insn
144 {
145   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
146   const struct mips_opcode *insn_mo;
147
148   /* True if this is a mips16 instruction and if we want the extended
149      form of INSN_MO.  */
150   bfd_boolean use_extend;
151
152   /* The 16-bit extension instruction to use when USE_EXTEND is true.  */
153   unsigned short extend;
154
155   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
156      a copy of INSN_MO->match with the operands filled in.  */
157   unsigned long insn_opcode;
158
159   /* The frag that contains the instruction.  */
160   struct frag *frag;
161
162   /* The offset into FRAG of the first instruction byte.  */
163   long where;
164
165   /* The relocs associated with the instruction, if any.  */
166   fixS *fixp[3];
167
168   /* True if this entry cannot be moved from its current position.  */
169   unsigned int fixed_p : 1;
170
171   /* True if this instruction occurred in a .set noreorder block.  */
172   unsigned int noreorder_p : 1;
173
174   /* True for mips16 instructions that jump to an absolute address.  */
175   unsigned int mips16_absolute_jump_p : 1;
176
177   /* True if this instruction is complete.  */
178   unsigned int complete_p : 1;
179 };
180
181 /* The ABI to use.  */
182 enum mips_abi_level
183 {
184   NO_ABI = 0,
185   O32_ABI,
186   O64_ABI,
187   N32_ABI,
188   N64_ABI,
189   EABI_ABI
190 };
191
192 /* MIPS ABI we are using for this output file.  */
193 static enum mips_abi_level mips_abi = NO_ABI;
194
195 /* Whether or not we have code that can call pic code.  */
196 int mips_abicalls = FALSE;
197
198 /* Whether or not we have code which can be put into a shared
199    library.  */
200 static bfd_boolean mips_in_shared = TRUE;
201
202 /* This is the set of options which may be modified by the .set
203    pseudo-op.  We use a struct so that .set push and .set pop are more
204    reliable.  */
205
206 struct mips_set_options
207 {
208   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
209      if it has not been initialized.  Changed by `.set mipsN', and the
210      -mipsN command line option, and the default CPU.  */
211   int isa;
212   /* Enabled Application Specific Extensions (ASEs).  These are set to -1
213      if they have not been initialized.  Changed by `.set <asename>', by
214      command line options, and based on the default architecture.  */
215   int ase_mips3d;
216   int ase_mdmx;
217   int ase_smartmips;
218   int ase_dsp;
219   int ase_dspr2;
220   int ase_mt;
221   /* Whether we are assembling for the mips16 processor.  0 if we are
222      not, 1 if we are, and -1 if the value has not been initialized.
223      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
224      -nomips16 command line options, and the default CPU.  */
225   int mips16;
226   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
227      1 if we are, and -1 if the value has not been initialized.  Changed
228      by `.set micromips' and `.set nomicromips', and the -mmicromips
229      and -mno-micromips command line options, and the default CPU.  */
230   int micromips;
231   /* Non-zero if we should not reorder instructions.  Changed by `.set
232      reorder' and `.set noreorder'.  */
233   int noreorder;
234   /* Non-zero if we should not permit the register designated "assembler
235      temporary" to be used in instructions.  The value is the register
236      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
237      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
238   unsigned int at;
239   /* Non-zero if we should warn when a macro instruction expands into
240      more than one machine instruction.  Changed by `.set nomacro' and
241      `.set macro'.  */
242   int warn_about_macros;
243   /* Non-zero if we should not move instructions.  Changed by `.set
244      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
245   int nomove;
246   /* Non-zero if we should not optimize branches by moving the target
247      of the branch into the delay slot.  Actually, we don't perform
248      this optimization anyhow.  Changed by `.set bopt' and `.set
249      nobopt'.  */
250   int nobopt;
251   /* Non-zero if we should not autoextend mips16 instructions.
252      Changed by `.set autoextend' and `.set noautoextend'.  */
253   int noautoextend;
254   /* Restrict general purpose registers and floating point registers
255      to 32 bit.  This is initially determined when -mgp32 or -mfp32
256      is passed but can changed if the assembler code uses .set mipsN.  */
257   int gp32;
258   int fp32;
259   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
260      command line option, and the default CPU.  */
261   int arch;
262   /* True if ".set sym32" is in effect.  */
263   bfd_boolean sym32;
264   /* True if floating-point operations are not allowed.  Changed by .set
265      softfloat or .set hardfloat, by command line options -msoft-float or
266      -mhard-float.  The default is false.  */
267   bfd_boolean soft_float;
268
269   /* True if only single-precision floating-point operations are allowed.
270      Changed by .set singlefloat or .set doublefloat, command-line options
271      -msingle-float or -mdouble-float.  The default is false.  */
272   bfd_boolean single_float;
273 };
274
275 /* This is the struct we use to hold the current set of options.  Note
276    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
277    -1 to indicate that they have not been initialized.  */
278
279 /* True if -mgp32 was passed.  */
280 static int file_mips_gp32 = -1;
281
282 /* True if -mfp32 was passed.  */
283 static int file_mips_fp32 = -1;
284
285 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
286 static int file_mips_soft_float = 0;
287
288 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
289 static int file_mips_single_float = 0;
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase_mips3d */ -1, /* ase_mdmx */ -1,
294   /* ase_smartmips */ 0, /* ase_dsp */ -1, /* ase_dspr2 */ -1, /* ase_mt */ -1,
295   /* mips16 */ -1, /* micromips */ -1, /* noreorder */ 0, /* at */ ATREG,
296   /* warn_about_macros */ 0, /* nomove */ 0, /* nobopt */ 0,
297   /* noautoextend */ 0, /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN,
298   /* sym32 */ FALSE, /* soft_float */ FALSE, /* single_float */ FALSE
299 };
300
301 /* These variables are filled in with the masks of registers used.
302    The object format code reads them and puts them in the appropriate
303    place.  */
304 unsigned long mips_gprmask;
305 unsigned long mips_cprmask[4];
306
307 /* MIPS ISA we are using for this output file.  */
308 static int file_mips_isa = ISA_UNKNOWN;
309
310 /* True if any MIPS16 code was produced.  */
311 static int file_ase_mips16;
312
313 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
314                               || mips_opts.isa == ISA_MIPS32R2          \
315                               || mips_opts.isa == ISA_MIPS64            \
316                               || mips_opts.isa == ISA_MIPS64R2)
317
318 /* True if any microMIPS code was produced.  */
319 static int file_ase_micromips;
320
321 /* True if we want to create R_MIPS_JALR for jalr $25.  */
322 #ifdef TE_IRIX
323 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
324 #else
325 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
326    because there's no place for any addend, the only acceptable
327    expression is a bare symbol.  */
328 #define MIPS_JALR_HINT_P(EXPR) \
329   (!HAVE_IN_PLACE_ADDENDS \
330    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
331 #endif
332
333 /* True if -mips3d was passed or implied by arguments passed on the
334    command line (e.g., by -march).  */
335 static int file_ase_mips3d;
336
337 /* True if -mdmx was passed or implied by arguments passed on the
338    command line (e.g., by -march).  */
339 static int file_ase_mdmx;
340
341 /* True if -msmartmips was passed or implied by arguments passed on the
342    command line (e.g., by -march).  */
343 static int file_ase_smartmips;
344
345 #define ISA_SUPPORTS_SMARTMIPS (mips_opts.isa == ISA_MIPS32             \
346                                 || mips_opts.isa == ISA_MIPS32R2)
347
348 /* True if -mdsp was passed or implied by arguments passed on the
349    command line (e.g., by -march).  */
350 static int file_ase_dsp;
351
352 #define ISA_SUPPORTS_DSP_ASE (mips_opts.isa == ISA_MIPS32R2             \
353                               || mips_opts.isa == ISA_MIPS64R2)
354
355 #define ISA_SUPPORTS_DSP64_ASE (mips_opts.isa == ISA_MIPS64R2)
356
357 /* True if -mdspr2 was passed or implied by arguments passed on the
358    command line (e.g., by -march).  */
359 static int file_ase_dspr2;
360
361 #define ISA_SUPPORTS_DSPR2_ASE (mips_opts.isa == ISA_MIPS32R2           \
362                                 || mips_opts.isa == ISA_MIPS64R2)
363
364 /* True if -mmt was passed or implied by arguments passed on the
365    command line (e.g., by -march).  */
366 static int file_ase_mt;
367
368 #define ISA_SUPPORTS_MT_ASE (mips_opts.isa == ISA_MIPS32R2              \
369                              || mips_opts.isa == ISA_MIPS64R2)
370
371 /* The argument of the -march= flag.  The architecture we are assembling.  */
372 static int file_mips_arch = CPU_UNKNOWN;
373 static const char *mips_arch_string;
374
375 /* The argument of the -mtune= flag.  The architecture for which we
376    are optimizing.  */
377 static int mips_tune = CPU_UNKNOWN;
378 static const char *mips_tune_string;
379
380 /* True when generating 32-bit code for a 64-bit processor.  */
381 static int mips_32bitmode = 0;
382
383 /* True if the given ABI requires 32-bit registers.  */
384 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
385
386 /* Likewise 64-bit registers.  */
387 #define ABI_NEEDS_64BIT_REGS(ABI)       \
388   ((ABI) == N32_ABI                     \
389    || (ABI) == N64_ABI                  \
390    || (ABI) == O64_ABI)
391
392 /*  Return true if ISA supports 64 bit wide gp registers.  */
393 #define ISA_HAS_64BIT_REGS(ISA)         \
394   ((ISA) == ISA_MIPS3                   \
395    || (ISA) == ISA_MIPS4                \
396    || (ISA) == ISA_MIPS5                \
397    || (ISA) == ISA_MIPS64               \
398    || (ISA) == ISA_MIPS64R2)
399
400 /*  Return true if ISA supports 64 bit wide float registers.  */
401 #define ISA_HAS_64BIT_FPRS(ISA)         \
402   ((ISA) == ISA_MIPS3                   \
403    || (ISA) == ISA_MIPS4                \
404    || (ISA) == ISA_MIPS5                \
405    || (ISA) == ISA_MIPS32R2             \
406    || (ISA) == ISA_MIPS64               \
407    || (ISA) == ISA_MIPS64R2)
408
409 /* Return true if ISA supports 64-bit right rotate (dror et al.)
410    instructions.  */
411 #define ISA_HAS_DROR(ISA)               \
412   ((ISA) == ISA_MIPS64R2                \
413    || (mips_opts.micromips              \
414        && ISA_HAS_64BIT_REGS (ISA))     \
415    )
416
417 /* Return true if ISA supports 32-bit right rotate (ror et al.)
418    instructions.  */
419 #define ISA_HAS_ROR(ISA)                \
420   ((ISA) == ISA_MIPS32R2                \
421    || (ISA) == ISA_MIPS64R2             \
422    || mips_opts.ase_smartmips           \
423    || mips_opts.micromips               \
424    )
425
426 /* Return true if ISA supports single-precision floats in odd registers.  */
427 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
428   ((ISA) == ISA_MIPS32                  \
429    || (ISA) == ISA_MIPS32R2             \
430    || (ISA) == ISA_MIPS64               \
431    || (ISA) == ISA_MIPS64R2)
432
433 /* Return true if ISA supports move to/from high part of a 64-bit
434    floating-point register. */
435 #define ISA_HAS_MXHC1(ISA)              \
436   ((ISA) == ISA_MIPS32R2                \
437    || (ISA) == ISA_MIPS64R2)
438
439 #define HAVE_32BIT_GPRS                            \
440     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
441
442 #define HAVE_32BIT_FPRS                            \
443     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
444
445 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
446 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
447
448 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
449
450 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
451
452 /* True if relocations are stored in-place.  */
453 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
454
455 /* The ABI-derived address size.  */
456 #define HAVE_64BIT_ADDRESSES \
457   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
458 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
459
460 /* The size of symbolic constants (i.e., expressions of the form
461    "SYMBOL" or "SYMBOL + OFFSET").  */
462 #define HAVE_32BIT_SYMBOLS \
463   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
464 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
465
466 /* Addresses are loaded in different ways, depending on the address size
467    in use.  The n32 ABI Documentation also mandates the use of additions
468    with overflow checking, but existing implementations don't follow it.  */
469 #define ADDRESS_ADD_INSN                                                \
470    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
471
472 #define ADDRESS_ADDI_INSN                                               \
473    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
474
475 #define ADDRESS_LOAD_INSN                                               \
476    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
477
478 #define ADDRESS_STORE_INSN                                              \
479    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
480
481 /* Return true if the given CPU supports the MIPS16 ASE.  */
482 #define CPU_HAS_MIPS16(cpu)                                             \
483    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
484     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
485
486 /* Return true if the given CPU supports the microMIPS ASE.  */
487 #define CPU_HAS_MICROMIPS(cpu)  0
488
489 /* True if CPU has a dror instruction.  */
490 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
491
492 /* True if CPU has a ror instruction.  */
493 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
494
495 /* True if CPU has seq/sne and seqi/snei instructions.  */
496 #define CPU_HAS_SEQ(CPU)        ((CPU) == CPU_OCTEON)
497
498 /* True if CPU does not implement the all the coprocessor insns.  For these
499    CPUs only those COP insns are accepted that are explicitly marked to be
500    available on the CPU.  ISA membership for COP insns is ignored.  */
501 #define NO_ISA_COP(CPU)         ((CPU) == CPU_OCTEON)
502
503 /* True if mflo and mfhi can be immediately followed by instructions
504    which write to the HI and LO registers.
505
506    According to MIPS specifications, MIPS ISAs I, II, and III need
507    (at least) two instructions between the reads of HI/LO and
508    instructions which write them, and later ISAs do not.  Contradicting
509    the MIPS specifications, some MIPS IV processor user manuals (e.g.
510    the UM for the NEC Vr5000) document needing the instructions between
511    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
512    MIPS64 and later ISAs to have the interlocks, plus any specific
513    earlier-ISA CPUs for which CPU documentation declares that the
514    instructions are really interlocked.  */
515 #define hilo_interlocks \
516   (mips_opts.isa == ISA_MIPS32                        \
517    || mips_opts.isa == ISA_MIPS32R2                   \
518    || mips_opts.isa == ISA_MIPS64                     \
519    || mips_opts.isa == ISA_MIPS64R2                   \
520    || mips_opts.arch == CPU_R4010                     \
521    || mips_opts.arch == CPU_R10000                    \
522    || mips_opts.arch == CPU_R12000                    \
523    || mips_opts.arch == CPU_R14000                    \
524    || mips_opts.arch == CPU_R16000                    \
525    || mips_opts.arch == CPU_RM7000                    \
526    || mips_opts.arch == CPU_VR5500                    \
527    || mips_opts.micromips                             \
528    )
529
530 /* Whether the processor uses hardware interlocks to protect reads
531    from the GPRs after they are loaded from memory, and thus does not
532    require nops to be inserted.  This applies to instructions marked
533    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
534    level I and microMIPS mode instructions are always interlocked.  */
535 #define gpr_interlocks                                \
536   (mips_opts.isa != ISA_MIPS1                         \
537    || mips_opts.arch == CPU_R3900                     \
538    || mips_opts.micromips                             \
539    )
540
541 /* Whether the processor uses hardware interlocks to avoid delays
542    required by coprocessor instructions, and thus does not require
543    nops to be inserted.  This applies to instructions marked
544    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
545    between instructions marked INSN_WRITE_COND_CODE and ones marked
546    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
547    levels I, II, and III and microMIPS mode instructions are always
548    interlocked.  */
549 /* Itbl support may require additional care here.  */
550 #define cop_interlocks                                \
551   ((mips_opts.isa != ISA_MIPS1                        \
552     && mips_opts.isa != ISA_MIPS2                     \
553     && mips_opts.isa != ISA_MIPS3)                    \
554    || mips_opts.arch == CPU_R4300                     \
555    || mips_opts.micromips                             \
556    )
557
558 /* Whether the processor uses hardware interlocks to protect reads
559    from coprocessor registers after they are loaded from memory, and
560    thus does not require nops to be inserted.  This applies to
561    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
562    requires at MIPS ISA level I and microMIPS mode instructions are
563    always interlocked.  */
564 #define cop_mem_interlocks                            \
565   (mips_opts.isa != ISA_MIPS1                         \
566    || mips_opts.micromips                             \
567    )
568
569 /* Is this a mfhi or mflo instruction?  */
570 #define MF_HILO_INSN(PINFO) \
571   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
572
573 /* Returns true for a (non floating-point) coprocessor instruction.  Reading
574    or writing the condition code is only possible on the coprocessors and
575    these insns are not marked with INSN_COP.  Thus for these insns use the
576    condition-code flags.  */
577 #define COP_INSN(PINFO)                                                 \
578   (PINFO != INSN_MACRO                                                  \
579    && ((PINFO) & (FP_S | FP_D)) == 0                                    \
580    && ((PINFO) & (INSN_COP | INSN_READ_COND_CODE | INSN_WRITE_COND_CODE)))
581
582 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
583    has been selected.  This implies, in particular, that addresses of text
584    labels have their LSB set.  */
585 #define HAVE_CODE_COMPRESSION                                           \
586   ((mips_opts.mips16 | mips_opts.micromips) != 0)
587
588 /* MIPS PIC level.  */
589
590 enum mips_pic_level mips_pic;
591
592 /* 1 if we should generate 32 bit offsets from the $gp register in
593    SVR4_PIC mode.  Currently has no meaning in other modes.  */
594 static int mips_big_got = 0;
595
596 /* 1 if trap instructions should used for overflow rather than break
597    instructions.  */
598 static int mips_trap = 0;
599
600 /* 1 if double width floating point constants should not be constructed
601    by assembling two single width halves into two single width floating
602    point registers which just happen to alias the double width destination
603    register.  On some architectures this aliasing can be disabled by a bit
604    in the status register, and the setting of this bit cannot be determined
605    automatically at assemble time.  */
606 static int mips_disable_float_construction;
607
608 /* Non-zero if any .set noreorder directives were used.  */
609
610 static int mips_any_noreorder;
611
612 /* Non-zero if nops should be inserted when the register referenced in
613    an mfhi/mflo instruction is read in the next two instructions.  */
614 static int mips_7000_hilo_fix;
615
616 /* The size of objects in the small data section.  */
617 static unsigned int g_switch_value = 8;
618 /* Whether the -G option was used.  */
619 static int g_switch_seen = 0;
620
621 #define N_RMASK 0xc4
622 #define N_VFP   0xd4
623
624 /* If we can determine in advance that GP optimization won't be
625    possible, we can skip the relaxation stuff that tries to produce
626    GP-relative references.  This makes delay slot optimization work
627    better.
628
629    This function can only provide a guess, but it seems to work for
630    gcc output.  It needs to guess right for gcc, otherwise gcc
631    will put what it thinks is a GP-relative instruction in a branch
632    delay slot.
633
634    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
635    fixed it for the non-PIC mode.  KR 95/04/07  */
636 static int nopic_need_relax (symbolS *, int);
637
638 /* handle of the OPCODE hash table */
639 static struct hash_control *op_hash = NULL;
640
641 /* The opcode hash table we use for the mips16.  */
642 static struct hash_control *mips16_op_hash = NULL;
643
644 /* The opcode hash table we use for the microMIPS ASE.  */
645 static struct hash_control *micromips_op_hash = NULL;
646
647 /* This array holds the chars that always start a comment.  If the
648     pre-processor is disabled, these aren't very useful */
649 const char comment_chars[] = "#";
650
651 /* This array holds the chars that only start a comment at the beginning of
652    a line.  If the line seems to have the form '# 123 filename'
653    .line and .file directives will appear in the pre-processed output */
654 /* Note that input_file.c hand checks for '#' at the beginning of the
655    first line of the input file.  This is because the compiler outputs
656    #NO_APP at the beginning of its output.  */
657 /* Also note that C style comments are always supported.  */
658 const char line_comment_chars[] = "#";
659
660 /* This array holds machine specific line separator characters.  */
661 const char line_separator_chars[] = ";";
662
663 /* Chars that can be used to separate mant from exp in floating point nums */
664 const char EXP_CHARS[] = "eE";
665
666 /* Chars that mean this number is a floating point constant */
667 /* As in 0f12.456 */
668 /* or    0d1.2345e12 */
669 const char FLT_CHARS[] = "rRsSfFdDxXpP";
670
671 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
672    changed in read.c .  Ideally it shouldn't have to know about it at all,
673    but nothing is ideal around here.
674  */
675
676 static char *insn_error;
677
678 static int auto_align = 1;
679
680 /* When outputting SVR4 PIC code, the assembler needs to know the
681    offset in the stack frame from which to restore the $gp register.
682    This is set by the .cprestore pseudo-op, and saved in this
683    variable.  */
684 static offsetT mips_cprestore_offset = -1;
685
686 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
687    more optimizations, it can use a register value instead of a memory-saved
688    offset and even an other register than $gp as global pointer.  */
689 static offsetT mips_cpreturn_offset = -1;
690 static int mips_cpreturn_register = -1;
691 static int mips_gp_register = GP;
692 static int mips_gprel_offset = 0;
693
694 /* Whether mips_cprestore_offset has been set in the current function
695    (or whether it has already been warned about, if not).  */
696 static int mips_cprestore_valid = 0;
697
698 /* This is the register which holds the stack frame, as set by the
699    .frame pseudo-op.  This is needed to implement .cprestore.  */
700 static int mips_frame_reg = SP;
701
702 /* Whether mips_frame_reg has been set in the current function
703    (or whether it has already been warned about, if not).  */
704 static int mips_frame_reg_valid = 0;
705
706 /* To output NOP instructions correctly, we need to keep information
707    about the previous two instructions.  */
708
709 /* Whether we are optimizing.  The default value of 2 means to remove
710    unneeded NOPs and swap branch instructions when possible.  A value
711    of 1 means to not swap branches.  A value of 0 means to always
712    insert NOPs.  */
713 static int mips_optimize = 2;
714
715 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
716    equivalent to seeing no -g option at all.  */
717 static int mips_debug = 0;
718
719 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
720 #define MAX_VR4130_NOPS 4
721
722 /* The maximum number of NOPs needed to fill delay slots.  */
723 #define MAX_DELAY_NOPS 2
724
725 /* The maximum number of NOPs needed for any purpose.  */
726 #define MAX_NOPS 4
727
728 /* A list of previous instructions, with index 0 being the most recent.
729    We need to look back MAX_NOPS instructions when filling delay slots
730    or working around processor errata.  We need to look back one
731    instruction further if we're thinking about using history[0] to
732    fill a branch delay slot.  */
733 static struct mips_cl_insn history[1 + MAX_NOPS];
734
735 /* Nop instructions used by emit_nop.  */
736 static struct mips_cl_insn nop_insn;
737 static struct mips_cl_insn mips16_nop_insn;
738 static struct mips_cl_insn micromips_nop16_insn;
739 static struct mips_cl_insn micromips_nop32_insn;
740
741 /* The appropriate nop for the current mode.  */
742 #define NOP_INSN (mips_opts.mips16 ? &mips16_nop_insn \
743                   : (mips_opts.micromips ? &micromips_nop16_insn : &nop_insn))
744
745 /* The size of NOP_INSN in bytes.  */
746 #define NOP_INSN_SIZE (HAVE_CODE_COMPRESSION ? 2 : 4)
747
748 /* If this is set, it points to a frag holding nop instructions which
749    were inserted before the start of a noreorder section.  If those
750    nops turn out to be unnecessary, the size of the frag can be
751    decreased.  */
752 static fragS *prev_nop_frag;
753
754 /* The number of nop instructions we created in prev_nop_frag.  */
755 static int prev_nop_frag_holds;
756
757 /* The number of nop instructions that we know we need in
758    prev_nop_frag.  */
759 static int prev_nop_frag_required;
760
761 /* The number of instructions we've seen since prev_nop_frag.  */
762 static int prev_nop_frag_since;
763
764 /* For ECOFF and ELF, relocations against symbols are done in two
765    parts, with a HI relocation and a LO relocation.  Each relocation
766    has only 16 bits of space to store an addend.  This means that in
767    order for the linker to handle carries correctly, it must be able
768    to locate both the HI and the LO relocation.  This means that the
769    relocations must appear in order in the relocation table.
770
771    In order to implement this, we keep track of each unmatched HI
772    relocation.  We then sort them so that they immediately precede the
773    corresponding LO relocation.  */
774
775 struct mips_hi_fixup
776 {
777   /* Next HI fixup.  */
778   struct mips_hi_fixup *next;
779   /* This fixup.  */
780   fixS *fixp;
781   /* The section this fixup is in.  */
782   segT seg;
783 };
784
785 /* The list of unmatched HI relocs.  */
786
787 static struct mips_hi_fixup *mips_hi_fixup_list;
788
789 /* The frag containing the last explicit relocation operator.
790    Null if explicit relocations have not been used.  */
791
792 static fragS *prev_reloc_op_frag;
793
794 /* Map normal MIPS register numbers to mips16 register numbers.  */
795
796 #define X ILLEGAL_REG
797 static const int mips32_to_16_reg_map[] =
798 {
799   X, X, 2, 3, 4, 5, 6, 7,
800   X, X, X, X, X, X, X, X,
801   0, 1, X, X, X, X, X, X,
802   X, X, X, X, X, X, X, X
803 };
804 #undef X
805
806 /* Map mips16 register numbers to normal MIPS register numbers.  */
807
808 static const unsigned int mips16_to_32_reg_map[] =
809 {
810   16, 17, 2, 3, 4, 5, 6, 7
811 };
812
813 /* Map normal MIPS register numbers to microMIPS register numbers.  */
814
815 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
816 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
817 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
818 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
819 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
820 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
821 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
822
823 #define X ILLEGAL_REG
824 /* reg type h: 4, 5, 6.  */
825 static const int mips32_to_micromips_reg_h_map[] =
826 {
827   X, X, X, X, 4, 5, 6, X,
828   X, X, X, X, X, X, X, X,
829   X, X, X, X, X, X, X, X,
830   X, X, X, X, X, X, X, X
831 };
832
833 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
834 static const int mips32_to_micromips_reg_m_map[] =
835 {
836   0, X, 2, 3, X, X, X, X,
837   X, X, X, X, X, X, X, X,
838   4, 1, 5, 6, 7, X, X, X,
839   X, X, X, X, X, X, X, X
840 };
841
842 /* reg type q: 0, 2-7. 17.  */
843 static const int mips32_to_micromips_reg_q_map[] =
844 {
845   0, X, 2, 3, 4, 5, 6, 7,
846   X, X, X, X, X, X, X, X,
847   X, 1, X, X, X, X, X, X,
848   X, X, X, X, X, X, X, X
849 };
850
851 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
852 #undef X
853
854 /* Map microMIPS register numbers to normal MIPS register numbers.  */
855
856 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
857 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
858 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
859 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
860 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
861 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
862
863 /* The microMIPS registers with type h.  */
864 static const unsigned int micromips_to_32_reg_h_map[] =
865 {
866   5, 5, 6, 4, 4, 4, 4, 4
867 };
868
869 /* The microMIPS registers with type i.  */
870 static const unsigned int micromips_to_32_reg_i_map[] =
871 {
872   6, 7, 7, 21, 22, 5, 6, 7
873 };
874
875 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
876
877 /* The microMIPS registers with type m.  */
878 static const unsigned int micromips_to_32_reg_m_map[] =
879 {
880   0, 17, 2, 3, 16, 18, 19, 20
881 };
882
883 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
884
885 /* The microMIPS registers with type q.  */
886 static const unsigned int micromips_to_32_reg_q_map[] =
887 {
888   0, 17, 2, 3, 4, 5, 6, 7
889 };
890
891 /* microMIPS imm type B.  */
892 static const int micromips_imm_b_map[] =
893 {
894   1, 4, 8, 12, 16, 20, 24, -1
895 };
896
897 /* microMIPS imm type C.  */
898 static const int micromips_imm_c_map[] =
899 {
900   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
901 };
902
903 /* Classifies the kind of instructions we're interested in when
904    implementing -mfix-vr4120.  */
905 enum fix_vr4120_class
906 {
907   FIX_VR4120_MACC,
908   FIX_VR4120_DMACC,
909   FIX_VR4120_MULT,
910   FIX_VR4120_DMULT,
911   FIX_VR4120_DIV,
912   FIX_VR4120_MTHILO,
913   NUM_FIX_VR4120_CLASSES
914 };
915
916 /* ...likewise -mfix-loongson2f-jump.  */
917 static bfd_boolean mips_fix_loongson2f_jump;
918
919 /* ...likewise -mfix-loongson2f-nop.  */
920 static bfd_boolean mips_fix_loongson2f_nop;
921
922 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
923 static bfd_boolean mips_fix_loongson2f;
924
925 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
926    there must be at least one other instruction between an instruction
927    of type X and an instruction of type Y.  */
928 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
929
930 /* True if -mfix-vr4120 is in force.  */
931 static int mips_fix_vr4120;
932
933 /* ...likewise -mfix-vr4130.  */
934 static int mips_fix_vr4130;
935
936 /* ...likewise -mfix-24k.  */
937 static int mips_fix_24k;
938
939 /* ...likewise -mfix-cn63xxp1 */
940 static bfd_boolean mips_fix_cn63xxp1;
941
942 /* We don't relax branches by default, since this causes us to expand
943    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
944    fail to compute the offset before expanding the macro to the most
945    efficient expansion.  */
946
947 static int mips_relax_branch;
948 \f
949 /* The expansion of many macros depends on the type of symbol that
950    they refer to.  For example, when generating position-dependent code,
951    a macro that refers to a symbol may have two different expansions,
952    one which uses GP-relative addresses and one which uses absolute
953    addresses.  When generating SVR4-style PIC, a macro may have
954    different expansions for local and global symbols.
955
956    We handle these situations by generating both sequences and putting
957    them in variant frags.  In position-dependent code, the first sequence
958    will be the GP-relative one and the second sequence will be the
959    absolute one.  In SVR4 PIC, the first sequence will be for global
960    symbols and the second will be for local symbols.
961
962    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
963    SECOND are the lengths of the two sequences in bytes.  These fields
964    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
965    the subtype has the following flags:
966
967    RELAX_USE_SECOND
968         Set if it has been decided that we should use the second
969         sequence instead of the first.
970
971    RELAX_SECOND_LONGER
972         Set in the first variant frag if the macro's second implementation
973         is longer than its first.  This refers to the macro as a whole,
974         not an individual relaxation.
975
976    RELAX_NOMACRO
977         Set in the first variant frag if the macro appeared in a .set nomacro
978         block and if one alternative requires a warning but the other does not.
979
980    RELAX_DELAY_SLOT
981         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
982         delay slot.
983
984    RELAX_DELAY_SLOT_16BIT
985         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
986         16-bit instruction.
987
988    RELAX_DELAY_SLOT_SIZE_FIRST
989         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
990         the macro is of the wrong size for the branch delay slot.
991
992    RELAX_DELAY_SLOT_SIZE_SECOND
993         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
994         the macro is of the wrong size for the branch delay slot.
995
996    The frag's "opcode" points to the first fixup for relaxable code.
997
998    Relaxable macros are generated using a sequence such as:
999
1000       relax_start (SYMBOL);
1001       ... generate first expansion ...
1002       relax_switch ();
1003       ... generate second expansion ...
1004       relax_end ();
1005
1006    The code and fixups for the unwanted alternative are discarded
1007    by md_convert_frag.  */
1008 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
1009
1010 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1011 #define RELAX_SECOND(X) ((X) & 0xff)
1012 #define RELAX_USE_SECOND 0x10000
1013 #define RELAX_SECOND_LONGER 0x20000
1014 #define RELAX_NOMACRO 0x40000
1015 #define RELAX_DELAY_SLOT 0x80000
1016 #define RELAX_DELAY_SLOT_16BIT 0x100000
1017 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
1018 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
1019
1020 /* Branch without likely bit.  If label is out of range, we turn:
1021
1022         beq reg1, reg2, label
1023         delay slot
1024
1025    into
1026
1027         bne reg1, reg2, 0f
1028         nop
1029         j label
1030      0: delay slot
1031
1032    with the following opcode replacements:
1033
1034         beq <-> bne
1035         blez <-> bgtz
1036         bltz <-> bgez
1037         bc1f <-> bc1t
1038
1039         bltzal <-> bgezal  (with jal label instead of j label)
1040
1041    Even though keeping the delay slot instruction in the delay slot of
1042    the branch would be more efficient, it would be very tricky to do
1043    correctly, because we'd have to introduce a variable frag *after*
1044    the delay slot instruction, and expand that instead.  Let's do it
1045    the easy way for now, even if the branch-not-taken case now costs
1046    one additional instruction.  Out-of-range branches are not supposed
1047    to be common, anyway.
1048
1049    Branch likely.  If label is out of range, we turn:
1050
1051         beql reg1, reg2, label
1052         delay slot (annulled if branch not taken)
1053
1054    into
1055
1056         beql reg1, reg2, 1f
1057         nop
1058         beql $0, $0, 2f
1059         nop
1060      1: j[al] label
1061         delay slot (executed only if branch taken)
1062      2:
1063
1064    It would be possible to generate a shorter sequence by losing the
1065    likely bit, generating something like:
1066
1067         bne reg1, reg2, 0f
1068         nop
1069         j[al] label
1070         delay slot (executed only if branch taken)
1071      0:
1072
1073         beql -> bne
1074         bnel -> beq
1075         blezl -> bgtz
1076         bgtzl -> blez
1077         bltzl -> bgez
1078         bgezl -> bltz
1079         bc1fl -> bc1t
1080         bc1tl -> bc1f
1081
1082         bltzall -> bgezal  (with jal label instead of j label)
1083         bgezall -> bltzal  (ditto)
1084
1085
1086    but it's not clear that it would actually improve performance.  */
1087 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1088   ((relax_substateT)                                            \
1089    (0xc0000000                                                  \
1090     | ((at) & 0x1f)                                             \
1091     | ((toofar) ? 0x20 : 0)                                     \
1092     | ((link) ? 0x40 : 0)                                       \
1093     | ((likely) ? 0x80 : 0)                                     \
1094     | ((uncond) ? 0x100 : 0)))
1095 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1096 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1097 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1098 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1099 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1100 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1101
1102 /* For mips16 code, we use an entirely different form of relaxation.
1103    mips16 supports two versions of most instructions which take
1104    immediate values: a small one which takes some small value, and a
1105    larger one which takes a 16 bit value.  Since branches also follow
1106    this pattern, relaxing these values is required.
1107
1108    We can assemble both mips16 and normal MIPS code in a single
1109    object.  Therefore, we need to support this type of relaxation at
1110    the same time that we support the relaxation described above.  We
1111    use the high bit of the subtype field to distinguish these cases.
1112
1113    The information we store for this type of relaxation is the
1114    argument code found in the opcode file for this relocation, whether
1115    the user explicitly requested a small or extended form, and whether
1116    the relocation is in a jump or jal delay slot.  That tells us the
1117    size of the value, and how it should be stored.  We also store
1118    whether the fragment is considered to be extended or not.  We also
1119    store whether this is known to be a branch to a different section,
1120    whether we have tried to relax this frag yet, and whether we have
1121    ever extended a PC relative fragment because of a shift count.  */
1122 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1123   (0x80000000                                                   \
1124    | ((type) & 0xff)                                            \
1125    | ((small) ? 0x100 : 0)                                      \
1126    | ((ext) ? 0x200 : 0)                                        \
1127    | ((dslot) ? 0x400 : 0)                                      \
1128    | ((jal_dslot) ? 0x800 : 0))
1129 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1130 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1131 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1132 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1133 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1134 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1135 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1136 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1137 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1138 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1139 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1140 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1141
1142 /* For microMIPS code, we use relaxation similar to one we use for
1143    MIPS16 code.  Some instructions that take immediate values support
1144    two encodings: a small one which takes some small value, and a
1145    larger one which takes a 16 bit value.  As some branches also follow
1146    this pattern, relaxing these values is required.
1147
1148    We can assemble both microMIPS and normal MIPS code in a single
1149    object.  Therefore, we need to support this type of relaxation at
1150    the same time that we support the relaxation described above.  We
1151    use one of the high bits of the subtype field to distinguish these
1152    cases.
1153
1154    The information we store for this type of relaxation is the argument
1155    code found in the opcode file for this relocation, the register
1156    selected as the assembler temporary, whether the user explicitly
1157    requested a 16-bit form, whether the branch is unconditional, whether
1158    it is compact, whether it stores the link address implicitly in $ra,
1159    whether relaxation of out-of-range 32-bit branches to a sequence of
1160    instructions is enabled, and whether the displacement of a branch is
1161    too large to fit as an immediate argument of a 16-bit and a 32-bit
1162    branch, respectively.  */
1163 #define RELAX_MICROMIPS_ENCODE(type, at, u16bit, uncond, compact, link, \
1164                                relax32, toofar16, toofar32)             \
1165   (0x40000000                                                           \
1166    | ((type) & 0xff)                                                    \
1167    | (((at) & 0x1f) << 8)                                               \
1168    | ((u16bit) ? 0x2000 : 0)                                            \
1169    | ((uncond) ? 0x4000 : 0)                                            \
1170    | ((compact) ? 0x8000 : 0)                                           \
1171    | ((link) ? 0x10000 : 0)                                             \
1172    | ((relax32) ? 0x20000 : 0)                                          \
1173    | ((toofar16) ? 0x40000 : 0)                                         \
1174    | ((toofar32) ? 0x80000 : 0))
1175 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1176 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1177 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1178 #define RELAX_MICROMIPS_U16BIT(i) (((i) & 0x2000) != 0)
1179 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x4000) != 0)
1180 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x8000) != 0)
1181 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x10000) != 0)
1182 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x20000) != 0)
1183
1184 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x40000) != 0)
1185 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x40000)
1186 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x40000)
1187 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x80000) != 0)
1188 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x80000)
1189 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x80000)
1190
1191 /* Is the given value a sign-extended 32-bit value?  */
1192 #define IS_SEXT_32BIT_NUM(x)                                            \
1193   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1194    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1195
1196 /* Is the given value a sign-extended 16-bit value?  */
1197 #define IS_SEXT_16BIT_NUM(x)                                            \
1198   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1199    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1200
1201 /* Is the given value a sign-extended 12-bit value?  */
1202 #define IS_SEXT_12BIT_NUM(x)                                            \
1203   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1204
1205 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1206 #define IS_ZEXT_32BIT_NUM(x)                                            \
1207   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1208    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1209
1210 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1211    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1212 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1213   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1214               | (((VALUE) & (MASK)) << (SHIFT)))
1215
1216 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1217    SHIFT places.  */
1218 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1219   (((STRUCT) >> (SHIFT)) & (MASK))
1220
1221 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1222    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1223
1224    include/opcode/mips.h specifies operand fields using the macros
1225    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1226    with "MIPS16OP" instead of "OP".  */
1227 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1228   do \
1229     if (!(MICROMIPS)) \
1230       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1231                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1232     else \
1233       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1234                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1235   while (0)
1236 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1237   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1238                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1239
1240 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1241 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1242   (!(MICROMIPS) \
1243    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1244    : EXTRACT_BITS ((INSN).insn_opcode, \
1245                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1246 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1247   EXTRACT_BITS ((INSN).insn_opcode, \
1248                 MIPS16OP_MASK_##FIELD, \
1249                 MIPS16OP_SH_##FIELD)
1250 \f
1251 /* Whether or not we are emitting a branch-likely macro.  */
1252 static bfd_boolean emit_branch_likely_macro = FALSE;
1253
1254 /* Global variables used when generating relaxable macros.  See the
1255    comment above RELAX_ENCODE for more details about how relaxation
1256    is used.  */
1257 static struct {
1258   /* 0 if we're not emitting a relaxable macro.
1259      1 if we're emitting the first of the two relaxation alternatives.
1260      2 if we're emitting the second alternative.  */
1261   int sequence;
1262
1263   /* The first relaxable fixup in the current frag.  (In other words,
1264      the first fixup that refers to relaxable code.)  */
1265   fixS *first_fixup;
1266
1267   /* sizes[0] says how many bytes of the first alternative are stored in
1268      the current frag.  Likewise sizes[1] for the second alternative.  */
1269   unsigned int sizes[2];
1270
1271   /* The symbol on which the choice of sequence depends.  */
1272   symbolS *symbol;
1273 } mips_relax;
1274 \f
1275 /* Global variables used to decide whether a macro needs a warning.  */
1276 static struct {
1277   /* True if the macro is in a branch delay slot.  */
1278   bfd_boolean delay_slot_p;
1279
1280   /* Set to the length in bytes required if the macro is in a delay slot
1281      that requires a specific length of instruction, otherwise zero.  */
1282   unsigned int delay_slot_length;
1283
1284   /* For relaxable macros, sizes[0] is the length of the first alternative
1285      in bytes and sizes[1] is the length of the second alternative.
1286      For non-relaxable macros, both elements give the length of the
1287      macro in bytes.  */
1288   unsigned int sizes[2];
1289
1290   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1291      instruction of the first alternative in bytes and first_insn_sizes[1]
1292      is the length of the first instruction of the second alternative.
1293      For non-relaxable macros, both elements give the length of the first
1294      instruction in bytes.
1295
1296      Set to zero if we haven't yet seen the first instruction.  */
1297   unsigned int first_insn_sizes[2];
1298
1299   /* For relaxable macros, insns[0] is the number of instructions for the
1300      first alternative and insns[1] is the number of instructions for the
1301      second alternative.
1302
1303      For non-relaxable macros, both elements give the number of
1304      instructions for the macro.  */
1305   unsigned int insns[2];
1306
1307   /* The first variant frag for this macro.  */
1308   fragS *first_frag;
1309 } mips_macro_warning;
1310 \f
1311 /* Prototypes for static functions.  */
1312
1313 #define internalError()                                                 \
1314     as_fatal (_("internal Error, line %d, %s"), __LINE__, __FILE__)
1315
1316 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1317
1318 static void append_insn
1319   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1320    bfd_boolean expansionp);
1321 static void mips_no_prev_insn (void);
1322 static void macro_build (expressionS *, const char *, const char *, ...);
1323 static void mips16_macro_build
1324   (expressionS *, const char *, const char *, va_list *);
1325 static void load_register (int, expressionS *, int);
1326 static void macro_start (void);
1327 static void macro_end (void);
1328 static void macro (struct mips_cl_insn * ip);
1329 static void mips16_macro (struct mips_cl_insn * ip);
1330 static void mips_ip (char *str, struct mips_cl_insn * ip);
1331 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1332 static void mips16_immed
1333   (char *, unsigned int, int, offsetT, bfd_boolean, bfd_boolean, bfd_boolean,
1334    unsigned long *, bfd_boolean *, unsigned short *);
1335 static size_t my_getSmallExpression
1336   (expressionS *, bfd_reloc_code_real_type *, char *);
1337 static void my_getExpression (expressionS *, char *);
1338 static void s_align (int);
1339 static void s_change_sec (int);
1340 static void s_change_section (int);
1341 static void s_cons (int);
1342 static void s_float_cons (int);
1343 static void s_mips_globl (int);
1344 static void s_option (int);
1345 static void s_mipsset (int);
1346 static void s_abicalls (int);
1347 static void s_cpload (int);
1348 static void s_cpsetup (int);
1349 static void s_cplocal (int);
1350 static void s_cprestore (int);
1351 static void s_cpreturn (int);
1352 static void s_dtprelword (int);
1353 static void s_dtpreldword (int);
1354 static void s_gpvalue (int);
1355 static void s_gpword (int);
1356 static void s_gpdword (int);
1357 static void s_cpadd (int);
1358 static void s_insn (int);
1359 static void md_obj_begin (void);
1360 static void md_obj_end (void);
1361 static void s_mips_ent (int);
1362 static void s_mips_end (int);
1363 static void s_mips_frame (int);
1364 static void s_mips_mask (int reg_type);
1365 static void s_mips_stab (int);
1366 static void s_mips_weakext (int);
1367 static void s_mips_file (int);
1368 static void s_mips_loc (int);
1369 static bfd_boolean pic_need_relax (symbolS *, asection *);
1370 static int relaxed_branch_length (fragS *, asection *, int);
1371 static int validate_mips_insn (const struct mips_opcode *);
1372 static int validate_micromips_insn (const struct mips_opcode *);
1373 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1374 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1375
1376 /* Table and functions used to map between CPU/ISA names, and
1377    ISA levels, and CPU numbers.  */
1378
1379 struct mips_cpu_info
1380 {
1381   const char *name;           /* CPU or ISA name.  */
1382   int flags;                  /* ASEs available, or ISA flag.  */
1383   int isa;                    /* ISA level.  */
1384   int cpu;                    /* CPU number (default CPU if ISA).  */
1385 };
1386
1387 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1388 #define MIPS_CPU_ASE_SMARTMIPS  0x0002  /* CPU implements SmartMIPS ASE */
1389 #define MIPS_CPU_ASE_DSP        0x0004  /* CPU implements DSP ASE */
1390 #define MIPS_CPU_ASE_MT         0x0008  /* CPU implements MT ASE */
1391 #define MIPS_CPU_ASE_MIPS3D     0x0010  /* CPU implements MIPS-3D ASE */
1392 #define MIPS_CPU_ASE_MDMX       0x0020  /* CPU implements MDMX ASE */
1393 #define MIPS_CPU_ASE_DSPR2      0x0040  /* CPU implements DSP R2 ASE */
1394
1395 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1396 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1397 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1398 \f
1399 /* Pseudo-op table.
1400
1401    The following pseudo-ops from the Kane and Heinrich MIPS book
1402    should be defined here, but are currently unsupported: .alias,
1403    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1404
1405    The following pseudo-ops from the Kane and Heinrich MIPS book are
1406    specific to the type of debugging information being generated, and
1407    should be defined by the object format: .aent, .begin, .bend,
1408    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1409    .vreg.
1410
1411    The following pseudo-ops from the Kane and Heinrich MIPS book are
1412    not MIPS CPU specific, but are also not specific to the object file
1413    format.  This file is probably the best place to define them, but
1414    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1415
1416 static const pseudo_typeS mips_pseudo_table[] =
1417 {
1418   /* MIPS specific pseudo-ops.  */
1419   {"option", s_option, 0},
1420   {"set", s_mipsset, 0},
1421   {"rdata", s_change_sec, 'r'},
1422   {"sdata", s_change_sec, 's'},
1423   {"livereg", s_ignore, 0},
1424   {"abicalls", s_abicalls, 0},
1425   {"cpload", s_cpload, 0},
1426   {"cpsetup", s_cpsetup, 0},
1427   {"cplocal", s_cplocal, 0},
1428   {"cprestore", s_cprestore, 0},
1429   {"cpreturn", s_cpreturn, 0},
1430   {"dtprelword", s_dtprelword, 0},
1431   {"dtpreldword", s_dtpreldword, 0},
1432   {"gpvalue", s_gpvalue, 0},
1433   {"gpword", s_gpword, 0},
1434   {"gpdword", s_gpdword, 0},
1435   {"cpadd", s_cpadd, 0},
1436   {"insn", s_insn, 0},
1437
1438   /* Relatively generic pseudo-ops that happen to be used on MIPS
1439      chips.  */
1440   {"asciiz", stringer, 8 + 1},
1441   {"bss", s_change_sec, 'b'},
1442   {"err", s_err, 0},
1443   {"half", s_cons, 1},
1444   {"dword", s_cons, 3},
1445   {"weakext", s_mips_weakext, 0},
1446   {"origin", s_org, 0},
1447   {"repeat", s_rept, 0},
1448
1449   /* For MIPS this is non-standard, but we define it for consistency.  */
1450   {"sbss", s_change_sec, 'B'},
1451
1452   /* These pseudo-ops are defined in read.c, but must be overridden
1453      here for one reason or another.  */
1454   {"align", s_align, 0},
1455   {"byte", s_cons, 0},
1456   {"data", s_change_sec, 'd'},
1457   {"double", s_float_cons, 'd'},
1458   {"float", s_float_cons, 'f'},
1459   {"globl", s_mips_globl, 0},
1460   {"global", s_mips_globl, 0},
1461   {"hword", s_cons, 1},
1462   {"int", s_cons, 2},
1463   {"long", s_cons, 2},
1464   {"octa", s_cons, 4},
1465   {"quad", s_cons, 3},
1466   {"section", s_change_section, 0},
1467   {"short", s_cons, 1},
1468   {"single", s_float_cons, 'f'},
1469   {"stabn", s_mips_stab, 'n'},
1470   {"text", s_change_sec, 't'},
1471   {"word", s_cons, 2},
1472
1473   { "extern", ecoff_directive_extern, 0},
1474
1475   { NULL, NULL, 0 },
1476 };
1477
1478 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1479 {
1480   /* These pseudo-ops should be defined by the object file format.
1481      However, a.out doesn't support them, so we have versions here.  */
1482   {"aent", s_mips_ent, 1},
1483   {"bgnb", s_ignore, 0},
1484   {"end", s_mips_end, 0},
1485   {"endb", s_ignore, 0},
1486   {"ent", s_mips_ent, 0},
1487   {"file", s_mips_file, 0},
1488   {"fmask", s_mips_mask, 'F'},
1489   {"frame", s_mips_frame, 0},
1490   {"loc", s_mips_loc, 0},
1491   {"mask", s_mips_mask, 'R'},
1492   {"verstamp", s_ignore, 0},
1493   { NULL, NULL, 0 },
1494 };
1495
1496 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1497    purpose of the `.dc.a' internal pseudo-op.  */
1498
1499 int
1500 mips_address_bytes (void)
1501 {
1502   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1503 }
1504
1505 extern void pop_insert (const pseudo_typeS *);
1506
1507 void
1508 mips_pop_insert (void)
1509 {
1510   pop_insert (mips_pseudo_table);
1511   if (! ECOFF_DEBUGGING)
1512     pop_insert (mips_nonecoff_pseudo_table);
1513 }
1514 \f
1515 /* Symbols labelling the current insn.  */
1516
1517 struct insn_label_list
1518 {
1519   struct insn_label_list *next;
1520   symbolS *label;
1521 };
1522
1523 static struct insn_label_list *free_insn_labels;
1524 #define label_list tc_segment_info_data.labels
1525
1526 static void mips_clear_insn_labels (void);
1527 static void mips_mark_labels (void);
1528 static void mips_compressed_mark_labels (void);
1529
1530 static inline void
1531 mips_clear_insn_labels (void)
1532 {
1533   register struct insn_label_list **pl;
1534   segment_info_type *si;
1535
1536   if (now_seg)
1537     {
1538       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1539         ;
1540       
1541       si = seg_info (now_seg);
1542       *pl = si->label_list;
1543       si->label_list = NULL;
1544     }
1545 }
1546
1547 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1548
1549 static inline void
1550 mips_mark_labels (void)
1551 {
1552   if (HAVE_CODE_COMPRESSION)
1553     mips_compressed_mark_labels ();
1554 }
1555 \f
1556 static char *expr_end;
1557
1558 /* Expressions which appear in instructions.  These are set by
1559    mips_ip.  */
1560
1561 static expressionS imm_expr;
1562 static expressionS imm2_expr;
1563 static expressionS offset_expr;
1564
1565 /* Relocs associated with imm_expr and offset_expr.  */
1566
1567 static bfd_reloc_code_real_type imm_reloc[3]
1568   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1569 static bfd_reloc_code_real_type offset_reloc[3]
1570   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1571
1572 /* This is set to the resulting size of the instruction to be produced
1573    by mips16_ip if an explicit extension is used or by mips_ip if an
1574    explicit size is supplied.  */
1575
1576 static unsigned int forced_insn_length;
1577
1578 #ifdef OBJ_ELF
1579 /* The pdr segment for per procedure frame/regmask info.  Not used for
1580    ECOFF debugging.  */
1581
1582 static segT pdr_seg;
1583 #endif
1584
1585 /* The default target format to use.  */
1586
1587 #if defined (TE_FreeBSD)
1588 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1589 #elif defined (TE_TMIPS)
1590 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1591 #else
1592 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1593 #endif
1594
1595 const char *
1596 mips_target_format (void)
1597 {
1598   switch (OUTPUT_FLAVOR)
1599     {
1600     case bfd_target_ecoff_flavour:
1601       return target_big_endian ? "ecoff-bigmips" : ECOFF_LITTLE_FORMAT;
1602     case bfd_target_coff_flavour:
1603       return "pe-mips";
1604     case bfd_target_elf_flavour:
1605 #ifdef TE_VXWORKS
1606       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1607         return (target_big_endian
1608                 ? "elf32-bigmips-vxworks"
1609                 : "elf32-littlemips-vxworks");
1610 #endif
1611       return (target_big_endian
1612               ? (HAVE_64BIT_OBJECTS
1613                  ? ELF_TARGET ("elf64-", "big")
1614                  : (HAVE_NEWABI
1615                     ? ELF_TARGET ("elf32-n", "big")
1616                     : ELF_TARGET ("elf32-", "big")))
1617               : (HAVE_64BIT_OBJECTS
1618                  ? ELF_TARGET ("elf64-", "little")
1619                  : (HAVE_NEWABI
1620                     ? ELF_TARGET ("elf32-n", "little")
1621                     : ELF_TARGET ("elf32-", "little"))));
1622     default:
1623       abort ();
1624       return NULL;
1625     }
1626 }
1627
1628 /* Return the length of a microMIPS instruction in bytes.  If bits of
1629    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1630    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1631    major opcode) will require further modifications to the opcode
1632    table.  */
1633
1634 static inline unsigned int
1635 micromips_insn_length (const struct mips_opcode *mo)
1636 {
1637   return (mo->mask >> 16) == 0 ? 2 : 4;
1638 }
1639
1640 /* Return the length of instruction INSN.  */
1641
1642 static inline unsigned int
1643 insn_length (const struct mips_cl_insn *insn)
1644 {
1645   if (mips_opts.micromips)
1646     return micromips_insn_length (insn->insn_mo);
1647   else if (mips_opts.mips16)
1648     return insn->mips16_absolute_jump_p || insn->use_extend ? 4 : 2;
1649   else
1650     return 4;
1651 }
1652
1653 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1654
1655 static void
1656 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1657 {
1658   size_t i;
1659
1660   insn->insn_mo = mo;
1661   insn->use_extend = FALSE;
1662   insn->extend = 0;
1663   insn->insn_opcode = mo->match;
1664   insn->frag = NULL;
1665   insn->where = 0;
1666   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1667     insn->fixp[i] = NULL;
1668   insn->fixed_p = (mips_opts.noreorder > 0);
1669   insn->noreorder_p = (mips_opts.noreorder > 0);
1670   insn->mips16_absolute_jump_p = 0;
1671   insn->complete_p = 0;
1672 }
1673
1674 /* Record the current MIPS16/microMIPS mode in now_seg.  */
1675
1676 static void
1677 mips_record_compressed_mode (void)
1678 {
1679   segment_info_type *si;
1680
1681   si = seg_info (now_seg);
1682   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
1683     si->tc_segment_info_data.mips16 = mips_opts.mips16;
1684   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
1685     si->tc_segment_info_data.micromips = mips_opts.micromips;
1686 }
1687
1688 /* Install INSN at the location specified by its "frag" and "where" fields.  */
1689
1690 static void
1691 install_insn (const struct mips_cl_insn *insn)
1692 {
1693   char *f = insn->frag->fr_literal + insn->where;
1694   if (!HAVE_CODE_COMPRESSION)
1695     md_number_to_chars (f, insn->insn_opcode, 4);
1696   else if (mips_opts.micromips)
1697     {
1698       unsigned int length = insn_length (insn);
1699       if (length == 2)
1700         md_number_to_chars (f, insn->insn_opcode, 2);
1701       else if (length == 4)
1702         {
1703           md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1704           f += 2;
1705           md_number_to_chars (f, insn->insn_opcode & 0xffff, 2);
1706         }
1707       else
1708         as_bad (_("48-bit microMIPS instructions are not supported"));
1709     }
1710   else if (insn->mips16_absolute_jump_p)
1711     {
1712       md_number_to_chars (f, insn->insn_opcode >> 16, 2);
1713       md_number_to_chars (f + 2, insn->insn_opcode & 0xffff, 2);
1714     }
1715   else
1716     {
1717       if (insn->use_extend)
1718         {
1719           md_number_to_chars (f, 0xf000 | insn->extend, 2);
1720           f += 2;
1721         }
1722       md_number_to_chars (f, insn->insn_opcode, 2);
1723     }
1724   mips_record_compressed_mode ();
1725 }
1726
1727 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
1728    and install the opcode in the new location.  */
1729
1730 static void
1731 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
1732 {
1733   size_t i;
1734
1735   insn->frag = frag;
1736   insn->where = where;
1737   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1738     if (insn->fixp[i] != NULL)
1739       {
1740         insn->fixp[i]->fx_frag = frag;
1741         insn->fixp[i]->fx_where = where;
1742       }
1743   install_insn (insn);
1744 }
1745
1746 /* Add INSN to the end of the output.  */
1747
1748 static void
1749 add_fixed_insn (struct mips_cl_insn *insn)
1750 {
1751   char *f = frag_more (insn_length (insn));
1752   move_insn (insn, frag_now, f - frag_now->fr_literal);
1753 }
1754
1755 /* Start a variant frag and move INSN to the start of the variant part,
1756    marking it as fixed.  The other arguments are as for frag_var.  */
1757
1758 static void
1759 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
1760                   relax_substateT subtype, symbolS *symbol, offsetT offset)
1761 {
1762   frag_grow (max_chars);
1763   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
1764   insn->fixed_p = 1;
1765   frag_var (rs_machine_dependent, max_chars, var,
1766             subtype, symbol, offset, NULL);
1767 }
1768
1769 /* Insert N copies of INSN into the history buffer, starting at
1770    position FIRST.  Neither FIRST nor N need to be clipped.  */
1771
1772 static void
1773 insert_into_history (unsigned int first, unsigned int n,
1774                      const struct mips_cl_insn *insn)
1775 {
1776   if (mips_relax.sequence != 2)
1777     {
1778       unsigned int i;
1779
1780       for (i = ARRAY_SIZE (history); i-- > first;)
1781         if (i >= first + n)
1782           history[i] = history[i - n];
1783         else
1784           history[i] = *insn;
1785     }
1786 }
1787
1788 /* Emit a nop instruction, recording it in the history buffer.  */
1789
1790 static void
1791 emit_nop (void)
1792 {
1793   add_fixed_insn (NOP_INSN);
1794   insert_into_history (0, 1, NOP_INSN);
1795 }
1796
1797 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
1798    the idea is to make it obvious at a glance that each errata is
1799    included.  */
1800
1801 static void
1802 init_vr4120_conflicts (void)
1803 {
1804 #define CONFLICT(FIRST, SECOND) \
1805     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
1806
1807   /* Errata 21 - [D]DIV[U] after [D]MACC */
1808   CONFLICT (MACC, DIV);
1809   CONFLICT (DMACC, DIV);
1810
1811   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
1812   CONFLICT (DMULT, DMULT);
1813   CONFLICT (DMULT, DMACC);
1814   CONFLICT (DMACC, DMULT);
1815   CONFLICT (DMACC, DMACC);
1816
1817   /* Errata 24 - MT{LO,HI} after [D]MACC */
1818   CONFLICT (MACC, MTHILO);
1819   CONFLICT (DMACC, MTHILO);
1820
1821   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
1822      instruction is executed immediately after a MACC or DMACC
1823      instruction, the result of [either instruction] is incorrect."  */
1824   CONFLICT (MACC, MULT);
1825   CONFLICT (MACC, DMULT);
1826   CONFLICT (DMACC, MULT);
1827   CONFLICT (DMACC, DMULT);
1828
1829   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
1830      executed immediately after a DMULT, DMULTU, DIV, DIVU,
1831      DDIV or DDIVU instruction, the result of the MACC or
1832      DMACC instruction is incorrect.".  */
1833   CONFLICT (DMULT, MACC);
1834   CONFLICT (DMULT, DMACC);
1835   CONFLICT (DIV, MACC);
1836   CONFLICT (DIV, DMACC);
1837
1838 #undef CONFLICT
1839 }
1840
1841 struct regname {
1842   const char *name;
1843   unsigned int num;
1844 };
1845
1846 #define RTYPE_MASK      0x1ff00
1847 #define RTYPE_NUM       0x00100
1848 #define RTYPE_FPU       0x00200
1849 #define RTYPE_FCC       0x00400
1850 #define RTYPE_VEC       0x00800
1851 #define RTYPE_GP        0x01000
1852 #define RTYPE_CP0       0x02000
1853 #define RTYPE_PC        0x04000
1854 #define RTYPE_ACC       0x08000
1855 #define RTYPE_CCC       0x10000
1856 #define RNUM_MASK       0x000ff
1857 #define RWARN           0x80000
1858
1859 #define GENERIC_REGISTER_NUMBERS \
1860     {"$0",      RTYPE_NUM | 0},  \
1861     {"$1",      RTYPE_NUM | 1},  \
1862     {"$2",      RTYPE_NUM | 2},  \
1863     {"$3",      RTYPE_NUM | 3},  \
1864     {"$4",      RTYPE_NUM | 4},  \
1865     {"$5",      RTYPE_NUM | 5},  \
1866     {"$6",      RTYPE_NUM | 6},  \
1867     {"$7",      RTYPE_NUM | 7},  \
1868     {"$8",      RTYPE_NUM | 8},  \
1869     {"$9",      RTYPE_NUM | 9},  \
1870     {"$10",     RTYPE_NUM | 10}, \
1871     {"$11",     RTYPE_NUM | 11}, \
1872     {"$12",     RTYPE_NUM | 12}, \
1873     {"$13",     RTYPE_NUM | 13}, \
1874     {"$14",     RTYPE_NUM | 14}, \
1875     {"$15",     RTYPE_NUM | 15}, \
1876     {"$16",     RTYPE_NUM | 16}, \
1877     {"$17",     RTYPE_NUM | 17}, \
1878     {"$18",     RTYPE_NUM | 18}, \
1879     {"$19",     RTYPE_NUM | 19}, \
1880     {"$20",     RTYPE_NUM | 20}, \
1881     {"$21",     RTYPE_NUM | 21}, \
1882     {"$22",     RTYPE_NUM | 22}, \
1883     {"$23",     RTYPE_NUM | 23}, \
1884     {"$24",     RTYPE_NUM | 24}, \
1885     {"$25",     RTYPE_NUM | 25}, \
1886     {"$26",     RTYPE_NUM | 26}, \
1887     {"$27",     RTYPE_NUM | 27}, \
1888     {"$28",     RTYPE_NUM | 28}, \
1889     {"$29",     RTYPE_NUM | 29}, \
1890     {"$30",     RTYPE_NUM | 30}, \
1891     {"$31",     RTYPE_NUM | 31} 
1892
1893 #define FPU_REGISTER_NAMES       \
1894     {"$f0",     RTYPE_FPU | 0},  \
1895     {"$f1",     RTYPE_FPU | 1},  \
1896     {"$f2",     RTYPE_FPU | 2},  \
1897     {"$f3",     RTYPE_FPU | 3},  \
1898     {"$f4",     RTYPE_FPU | 4},  \
1899     {"$f5",     RTYPE_FPU | 5},  \
1900     {"$f6",     RTYPE_FPU | 6},  \
1901     {"$f7",     RTYPE_FPU | 7},  \
1902     {"$f8",     RTYPE_FPU | 8},  \
1903     {"$f9",     RTYPE_FPU | 9},  \
1904     {"$f10",    RTYPE_FPU | 10}, \
1905     {"$f11",    RTYPE_FPU | 11}, \
1906     {"$f12",    RTYPE_FPU | 12}, \
1907     {"$f13",    RTYPE_FPU | 13}, \
1908     {"$f14",    RTYPE_FPU | 14}, \
1909     {"$f15",    RTYPE_FPU | 15}, \
1910     {"$f16",    RTYPE_FPU | 16}, \
1911     {"$f17",    RTYPE_FPU | 17}, \
1912     {"$f18",    RTYPE_FPU | 18}, \
1913     {"$f19",    RTYPE_FPU | 19}, \
1914     {"$f20",    RTYPE_FPU | 20}, \
1915     {"$f21",    RTYPE_FPU | 21}, \
1916     {"$f22",    RTYPE_FPU | 22}, \
1917     {"$f23",    RTYPE_FPU | 23}, \
1918     {"$f24",    RTYPE_FPU | 24}, \
1919     {"$f25",    RTYPE_FPU | 25}, \
1920     {"$f26",    RTYPE_FPU | 26}, \
1921     {"$f27",    RTYPE_FPU | 27}, \
1922     {"$f28",    RTYPE_FPU | 28}, \
1923     {"$f29",    RTYPE_FPU | 29}, \
1924     {"$f30",    RTYPE_FPU | 30}, \
1925     {"$f31",    RTYPE_FPU | 31}
1926
1927 #define FPU_CONDITION_CODE_NAMES \
1928     {"$fcc0",   RTYPE_FCC | 0},  \
1929     {"$fcc1",   RTYPE_FCC | 1},  \
1930     {"$fcc2",   RTYPE_FCC | 2},  \
1931     {"$fcc3",   RTYPE_FCC | 3},  \
1932     {"$fcc4",   RTYPE_FCC | 4},  \
1933     {"$fcc5",   RTYPE_FCC | 5},  \
1934     {"$fcc6",   RTYPE_FCC | 6},  \
1935     {"$fcc7",   RTYPE_FCC | 7}
1936
1937 #define COPROC_CONDITION_CODE_NAMES         \
1938     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
1939     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
1940     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
1941     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
1942     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
1943     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
1944     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
1945     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
1946
1947 #define N32N64_SYMBOLIC_REGISTER_NAMES \
1948     {"$a4",     RTYPE_GP | 8},  \
1949     {"$a5",     RTYPE_GP | 9},  \
1950     {"$a6",     RTYPE_GP | 10}, \
1951     {"$a7",     RTYPE_GP | 11}, \
1952     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
1953     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
1954     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
1955     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
1956     {"$t0",     RTYPE_GP | 12}, \
1957     {"$t1",     RTYPE_GP | 13}, \
1958     {"$t2",     RTYPE_GP | 14}, \
1959     {"$t3",     RTYPE_GP | 15}
1960
1961 #define O32_SYMBOLIC_REGISTER_NAMES \
1962     {"$t0",     RTYPE_GP | 8},  \
1963     {"$t1",     RTYPE_GP | 9},  \
1964     {"$t2",     RTYPE_GP | 10}, \
1965     {"$t3",     RTYPE_GP | 11}, \
1966     {"$t4",     RTYPE_GP | 12}, \
1967     {"$t5",     RTYPE_GP | 13}, \
1968     {"$t6",     RTYPE_GP | 14}, \
1969     {"$t7",     RTYPE_GP | 15}, \
1970     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
1971     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
1972     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
1973     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
1974
1975 /* Remaining symbolic register names */
1976 #define SYMBOLIC_REGISTER_NAMES \
1977     {"$zero",   RTYPE_GP | 0},  \
1978     {"$at",     RTYPE_GP | 1},  \
1979     {"$AT",     RTYPE_GP | 1},  \
1980     {"$v0",     RTYPE_GP | 2},  \
1981     {"$v1",     RTYPE_GP | 3},  \
1982     {"$a0",     RTYPE_GP | 4},  \
1983     {"$a1",     RTYPE_GP | 5},  \
1984     {"$a2",     RTYPE_GP | 6},  \
1985     {"$a3",     RTYPE_GP | 7},  \
1986     {"$s0",     RTYPE_GP | 16}, \
1987     {"$s1",     RTYPE_GP | 17}, \
1988     {"$s2",     RTYPE_GP | 18}, \
1989     {"$s3",     RTYPE_GP | 19}, \
1990     {"$s4",     RTYPE_GP | 20}, \
1991     {"$s5",     RTYPE_GP | 21}, \
1992     {"$s6",     RTYPE_GP | 22}, \
1993     {"$s7",     RTYPE_GP | 23}, \
1994     {"$t8",     RTYPE_GP | 24}, \
1995     {"$t9",     RTYPE_GP | 25}, \
1996     {"$k0",     RTYPE_GP | 26}, \
1997     {"$kt0",    RTYPE_GP | 26}, \
1998     {"$k1",     RTYPE_GP | 27}, \
1999     {"$kt1",    RTYPE_GP | 27}, \
2000     {"$gp",     RTYPE_GP | 28}, \
2001     {"$sp",     RTYPE_GP | 29}, \
2002     {"$s8",     RTYPE_GP | 30}, \
2003     {"$fp",     RTYPE_GP | 30}, \
2004     {"$ra",     RTYPE_GP | 31}
2005
2006 #define MIPS16_SPECIAL_REGISTER_NAMES \
2007     {"$pc",     RTYPE_PC | 0}
2008
2009 #define MDMX_VECTOR_REGISTER_NAMES \
2010     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2011     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2012     {"$v2",     RTYPE_VEC | 2},  \
2013     {"$v3",     RTYPE_VEC | 3},  \
2014     {"$v4",     RTYPE_VEC | 4},  \
2015     {"$v5",     RTYPE_VEC | 5},  \
2016     {"$v6",     RTYPE_VEC | 6},  \
2017     {"$v7",     RTYPE_VEC | 7},  \
2018     {"$v8",     RTYPE_VEC | 8},  \
2019     {"$v9",     RTYPE_VEC | 9},  \
2020     {"$v10",    RTYPE_VEC | 10}, \
2021     {"$v11",    RTYPE_VEC | 11}, \
2022     {"$v12",    RTYPE_VEC | 12}, \
2023     {"$v13",    RTYPE_VEC | 13}, \
2024     {"$v14",    RTYPE_VEC | 14}, \
2025     {"$v15",    RTYPE_VEC | 15}, \
2026     {"$v16",    RTYPE_VEC | 16}, \
2027     {"$v17",    RTYPE_VEC | 17}, \
2028     {"$v18",    RTYPE_VEC | 18}, \
2029     {"$v19",    RTYPE_VEC | 19}, \
2030     {"$v20",    RTYPE_VEC | 20}, \
2031     {"$v21",    RTYPE_VEC | 21}, \
2032     {"$v22",    RTYPE_VEC | 22}, \
2033     {"$v23",    RTYPE_VEC | 23}, \
2034     {"$v24",    RTYPE_VEC | 24}, \
2035     {"$v25",    RTYPE_VEC | 25}, \
2036     {"$v26",    RTYPE_VEC | 26}, \
2037     {"$v27",    RTYPE_VEC | 27}, \
2038     {"$v28",    RTYPE_VEC | 28}, \
2039     {"$v29",    RTYPE_VEC | 29}, \
2040     {"$v30",    RTYPE_VEC | 30}, \
2041     {"$v31",    RTYPE_VEC | 31}
2042
2043 #define MIPS_DSP_ACCUMULATOR_NAMES \
2044     {"$ac0",    RTYPE_ACC | 0}, \
2045     {"$ac1",    RTYPE_ACC | 1}, \
2046     {"$ac2",    RTYPE_ACC | 2}, \
2047     {"$ac3",    RTYPE_ACC | 3}
2048
2049 static const struct regname reg_names[] = {
2050   GENERIC_REGISTER_NUMBERS,
2051   FPU_REGISTER_NAMES,
2052   FPU_CONDITION_CODE_NAMES,
2053   COPROC_CONDITION_CODE_NAMES,
2054
2055   /* The $txx registers depends on the abi,
2056      these will be added later into the symbol table from
2057      one of the tables below once mips_abi is set after 
2058      parsing of arguments from the command line. */
2059   SYMBOLIC_REGISTER_NAMES,
2060
2061   MIPS16_SPECIAL_REGISTER_NAMES,
2062   MDMX_VECTOR_REGISTER_NAMES,
2063   MIPS_DSP_ACCUMULATOR_NAMES,
2064   {0, 0}
2065 };
2066
2067 static const struct regname reg_names_o32[] = {
2068   O32_SYMBOLIC_REGISTER_NAMES,
2069   {0, 0}
2070 };
2071
2072 static const struct regname reg_names_n32n64[] = {
2073   N32N64_SYMBOLIC_REGISTER_NAMES,
2074   {0, 0}
2075 };
2076
2077 /* Check if S points at a valid register specifier according to TYPES.
2078    If so, then return 1, advance S to consume the specifier and store
2079    the register's number in REGNOP, otherwise return 0.  */
2080
2081 static int
2082 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2083 {
2084   symbolS *symbolP;
2085   char *e;
2086   char save_c;
2087   int reg = -1;
2088
2089   /* Find end of name.  */
2090   e = *s;
2091   if (is_name_beginner (*e))
2092     ++e;
2093   while (is_part_of_name (*e))
2094     ++e;
2095
2096   /* Terminate name.  */
2097   save_c = *e;
2098   *e = '\0';
2099
2100   /* Look for a register symbol.  */
2101   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2102     {
2103       int r = S_GET_VALUE (symbolP);
2104       if (r & types)
2105         reg = r & RNUM_MASK;
2106       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2107         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2108         reg = (r & RNUM_MASK) - 2;
2109     }
2110   /* Else see if this is a register defined in an itbl entry.  */
2111   else if ((types & RTYPE_GP) && itbl_have_entries)
2112     {
2113       char *n = *s;
2114       unsigned long r;
2115
2116       if (*n == '$')
2117         ++n;
2118       if (itbl_get_reg_val (n, &r))
2119         reg = r & RNUM_MASK;
2120     }
2121
2122   /* Advance to next token if a register was recognised.  */
2123   if (reg >= 0)
2124     *s = e;
2125   else if (types & RWARN)
2126     as_warn (_("Unrecognized register name `%s'"), *s);
2127
2128   *e = save_c;
2129   if (regnop)
2130     *regnop = reg;
2131   return reg >= 0;
2132 }
2133
2134 /* Check if S points at a valid register list according to TYPES.
2135    If so, then return 1, advance S to consume the list and store
2136    the registers present on the list as a bitmask of ones in REGLISTP,
2137    otherwise return 0.  A valid list comprises a comma-separated
2138    enumeration of valid single registers and/or dash-separated
2139    contiguous register ranges as determined by their numbers.
2140
2141    As a special exception if one of s0-s7 registers is specified as
2142    the range's lower delimiter and s8 (fp) is its upper one, then no
2143    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2144    are selected; they have to be listed separately if needed.  */
2145
2146 static int
2147 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2148 {
2149   unsigned int reglist = 0;
2150   unsigned int lastregno;
2151   bfd_boolean ok = TRUE;
2152   unsigned int regmask;
2153   char *s_endlist = *s;
2154   char *s_reset = *s;
2155   unsigned int regno;
2156
2157   while (reg_lookup (s, types, &regno))
2158     {
2159       lastregno = regno;
2160       if (**s == '-')
2161         {
2162           (*s)++;
2163           ok = reg_lookup (s, types, &lastregno);
2164           if (ok && lastregno < regno)
2165             ok = FALSE;
2166           if (!ok)
2167             break;
2168         }
2169
2170       if (lastregno == FP && regno >= S0 && regno <= S7)
2171         {
2172           lastregno = S7;
2173           reglist |= 1 << FP;
2174         }
2175       regmask = 1 << lastregno;
2176       regmask = (regmask << 1) - 1;
2177       regmask ^= (1 << regno) - 1;
2178       reglist |= regmask;
2179
2180       s_endlist = *s;
2181       if (**s != ',')
2182         break;
2183       (*s)++;
2184     }
2185
2186   if (ok)
2187     *s = s_endlist;
2188   else
2189     *s = s_reset;
2190   if (reglistp)
2191     *reglistp = reglist;
2192   return ok && reglist != 0;
2193 }
2194
2195 /* Return TRUE if opcode MO is valid on the currently selected ISA and
2196    architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2197
2198 static bfd_boolean
2199 is_opcode_valid (const struct mips_opcode *mo)
2200 {
2201   int isa = mips_opts.isa;
2202   int fp_s, fp_d;
2203
2204   if (mips_opts.ase_mdmx)
2205     isa |= INSN_MDMX;
2206   if (mips_opts.ase_dsp)
2207     isa |= INSN_DSP;
2208   if (mips_opts.ase_dsp && ISA_SUPPORTS_DSP64_ASE)
2209     isa |= INSN_DSP64;
2210   if (mips_opts.ase_dspr2)
2211     isa |= INSN_DSPR2;
2212   if (mips_opts.ase_mt)
2213     isa |= INSN_MT;
2214   if (mips_opts.ase_mips3d)
2215     isa |= INSN_MIPS3D;
2216   if (mips_opts.ase_smartmips)
2217     isa |= INSN_SMARTMIPS;
2218
2219   /* Don't accept instructions based on the ISA if the CPU does not implement
2220      all the coprocessor insns. */
2221   if (NO_ISA_COP (mips_opts.arch)
2222       && COP_INSN (mo->pinfo))
2223     isa = 0;
2224
2225   if (!OPCODE_IS_MEMBER (mo, isa, mips_opts.arch))
2226     return FALSE;
2227
2228   /* Check whether the instruction or macro requires single-precision or
2229      double-precision floating-point support.  Note that this information is
2230      stored differently in the opcode table for insns and macros.  */
2231   if (mo->pinfo == INSN_MACRO)
2232     {
2233       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2234       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2235     }
2236   else
2237     {
2238       fp_s = mo->pinfo & FP_S;
2239       fp_d = mo->pinfo & FP_D;
2240     }
2241
2242   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2243     return FALSE;
2244
2245   if (fp_s && mips_opts.soft_float)
2246     return FALSE;
2247
2248   return TRUE;
2249 }
2250
2251 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2252    selected ISA and architecture.  */
2253
2254 static bfd_boolean
2255 is_opcode_valid_16 (const struct mips_opcode *mo)
2256 {
2257   return OPCODE_IS_MEMBER (mo, mips_opts.isa, mips_opts.arch) ? TRUE : FALSE;
2258 }
2259
2260 /* Return TRUE if the size of the microMIPS opcode MO matches one
2261    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2262
2263 static bfd_boolean
2264 is_size_valid (const struct mips_opcode *mo)
2265 {
2266   if (!mips_opts.micromips)
2267     return TRUE;
2268
2269   if (!forced_insn_length)
2270     return TRUE;
2271   if (mo->pinfo == INSN_MACRO)
2272     return FALSE;
2273   return forced_insn_length == micromips_insn_length (mo);
2274 }
2275
2276 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2277    of the preceding instruction.  Always TRUE in the standard MIPS mode.  */
2278
2279 static bfd_boolean
2280 is_delay_slot_valid (const struct mips_opcode *mo)
2281 {
2282   if (!mips_opts.micromips)
2283     return TRUE;
2284
2285   if (mo->pinfo == INSN_MACRO)
2286     return TRUE;
2287   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2288       && micromips_insn_length (mo) != 4)
2289     return FALSE;
2290   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2291       && micromips_insn_length (mo) != 2)
2292     return FALSE;
2293
2294   return TRUE;
2295 }
2296
2297 /* This function is called once, at assembler startup time.  It should set up
2298    all the tables, etc. that the MD part of the assembler will need.  */
2299
2300 void
2301 md_begin (void)
2302 {
2303   const char *retval = NULL;
2304   int i = 0;
2305   int broken = 0;
2306
2307   if (mips_pic != NO_PIC)
2308     {
2309       if (g_switch_seen && g_switch_value != 0)
2310         as_bad (_("-G may not be used in position-independent code"));
2311       g_switch_value = 0;
2312     }
2313
2314   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2315     as_warn (_("Could not set architecture and machine"));
2316
2317   op_hash = hash_new ();
2318
2319   for (i = 0; i < NUMOPCODES;)
2320     {
2321       const char *name = mips_opcodes[i].name;
2322
2323       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2324       if (retval != NULL)
2325         {
2326           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2327                    mips_opcodes[i].name, retval);
2328           /* Probably a memory allocation problem?  Give up now.  */
2329           as_fatal (_("Broken assembler.  No assembly attempted."));
2330         }
2331       do
2332         {
2333           if (mips_opcodes[i].pinfo != INSN_MACRO)
2334             {
2335               if (!validate_mips_insn (&mips_opcodes[i]))
2336                 broken = 1;
2337               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2338                 {
2339                   create_insn (&nop_insn, mips_opcodes + i);
2340                   if (mips_fix_loongson2f_nop)
2341                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2342                   nop_insn.fixed_p = 1;
2343                 }
2344             }
2345           ++i;
2346         }
2347       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2348     }
2349
2350   mips16_op_hash = hash_new ();
2351
2352   i = 0;
2353   while (i < bfd_mips16_num_opcodes)
2354     {
2355       const char *name = mips16_opcodes[i].name;
2356
2357       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2358       if (retval != NULL)
2359         as_fatal (_("internal: can't hash `%s': %s"),
2360                   mips16_opcodes[i].name, retval);
2361       do
2362         {
2363           if (mips16_opcodes[i].pinfo != INSN_MACRO
2364               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2365                   != mips16_opcodes[i].match))
2366             {
2367               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2368                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2369               broken = 1;
2370             }
2371           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2372             {
2373               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2374               mips16_nop_insn.fixed_p = 1;
2375             }
2376           ++i;
2377         }
2378       while (i < bfd_mips16_num_opcodes
2379              && strcmp (mips16_opcodes[i].name, name) == 0);
2380     }
2381
2382   micromips_op_hash = hash_new ();
2383
2384   i = 0;
2385   while (i < bfd_micromips_num_opcodes)
2386     {
2387       const char *name = micromips_opcodes[i].name;
2388
2389       retval = hash_insert (micromips_op_hash, name,
2390                             (void *) &micromips_opcodes[i]);
2391       if (retval != NULL)
2392         as_fatal (_("internal: can't hash `%s': %s"),
2393                   micromips_opcodes[i].name, retval);
2394       do
2395         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2396           {
2397             struct mips_cl_insn *micromips_nop_insn;
2398
2399             if (!validate_micromips_insn (&micromips_opcodes[i]))
2400               broken = 1;
2401
2402             if (micromips_insn_length (micromips_opcodes + i) == 2)
2403               micromips_nop_insn = &micromips_nop16_insn;
2404             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2405               micromips_nop_insn = &micromips_nop32_insn;
2406             else
2407               continue;
2408
2409             if (micromips_nop_insn->insn_mo == NULL
2410                 && strcmp (name, "nop") == 0)
2411               {
2412                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2413                 micromips_nop_insn->fixed_p = 1;
2414               }
2415           }
2416       while (++i < bfd_micromips_num_opcodes
2417              && strcmp (micromips_opcodes[i].name, name) == 0);
2418     }
2419
2420   if (broken)
2421     as_fatal (_("Broken assembler.  No assembly attempted."));
2422
2423   /* We add all the general register names to the symbol table.  This
2424      helps us detect invalid uses of them.  */
2425   for (i = 0; reg_names[i].name; i++) 
2426     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2427                                      reg_names[i].num, /* & RNUM_MASK, */
2428                                      &zero_address_frag));
2429   if (HAVE_NEWABI)
2430     for (i = 0; reg_names_n32n64[i].name; i++) 
2431       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2432                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2433                                        &zero_address_frag));
2434   else
2435     for (i = 0; reg_names_o32[i].name; i++) 
2436       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2437                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2438                                        &zero_address_frag));
2439
2440   mips_no_prev_insn ();
2441
2442   mips_gprmask = 0;
2443   mips_cprmask[0] = 0;
2444   mips_cprmask[1] = 0;
2445   mips_cprmask[2] = 0;
2446   mips_cprmask[3] = 0;
2447
2448   /* set the default alignment for the text section (2**2) */
2449   record_alignment (text_section, 2);
2450
2451   bfd_set_gp_size (stdoutput, g_switch_value);
2452
2453 #ifdef OBJ_ELF
2454   if (IS_ELF)
2455     {
2456       /* On a native system other than VxWorks, sections must be aligned
2457          to 16 byte boundaries.  When configured for an embedded ELF
2458          target, we don't bother.  */
2459       if (strncmp (TARGET_OS, "elf", 3) != 0
2460           && strncmp (TARGET_OS, "vxworks", 7) != 0)
2461         {
2462           (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2463           (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2464           (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2465         }
2466
2467       /* Create a .reginfo section for register masks and a .mdebug
2468          section for debugging information.  */
2469       {
2470         segT seg;
2471         subsegT subseg;
2472         flagword flags;
2473         segT sec;
2474
2475         seg = now_seg;
2476         subseg = now_subseg;
2477
2478         /* The ABI says this section should be loaded so that the
2479            running program can access it.  However, we don't load it
2480            if we are configured for an embedded target */
2481         flags = SEC_READONLY | SEC_DATA;
2482         if (strncmp (TARGET_OS, "elf", 3) != 0)
2483           flags |= SEC_ALLOC | SEC_LOAD;
2484
2485         if (mips_abi != N64_ABI)
2486           {
2487             sec = subseg_new (".reginfo", (subsegT) 0);
2488
2489             bfd_set_section_flags (stdoutput, sec, flags);
2490             bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
2491
2492             mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
2493           }
2494         else
2495           {
2496             /* The 64-bit ABI uses a .MIPS.options section rather than
2497                .reginfo section.  */
2498             sec = subseg_new (".MIPS.options", (subsegT) 0);
2499             bfd_set_section_flags (stdoutput, sec, flags);
2500             bfd_set_section_alignment (stdoutput, sec, 3);
2501
2502             /* Set up the option header.  */
2503             {
2504               Elf_Internal_Options opthdr;
2505               char *f;
2506
2507               opthdr.kind = ODK_REGINFO;
2508               opthdr.size = (sizeof (Elf_External_Options)
2509                              + sizeof (Elf64_External_RegInfo));
2510               opthdr.section = 0;
2511               opthdr.info = 0;
2512               f = frag_more (sizeof (Elf_External_Options));
2513               bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
2514                                              (Elf_External_Options *) f);
2515
2516               mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
2517             }
2518           }
2519
2520         if (ECOFF_DEBUGGING)
2521           {
2522             sec = subseg_new (".mdebug", (subsegT) 0);
2523             (void) bfd_set_section_flags (stdoutput, sec,
2524                                           SEC_HAS_CONTENTS | SEC_READONLY);
2525             (void) bfd_set_section_alignment (stdoutput, sec, 2);
2526           }
2527         else if (mips_flag_pdr)
2528           {
2529             pdr_seg = subseg_new (".pdr", (subsegT) 0);
2530             (void) bfd_set_section_flags (stdoutput, pdr_seg,
2531                                           SEC_READONLY | SEC_RELOC
2532                                           | SEC_DEBUGGING);
2533             (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
2534           }
2535
2536         subseg_set (seg, subseg);
2537       }
2538     }
2539 #endif /* OBJ_ELF */
2540
2541   if (! ECOFF_DEBUGGING)
2542     md_obj_begin ();
2543
2544   if (mips_fix_vr4120)
2545     init_vr4120_conflicts ();
2546 }
2547
2548 void
2549 md_mips_end (void)
2550 {
2551   mips_emit_delays ();
2552   if (! ECOFF_DEBUGGING)
2553     md_obj_end ();
2554 }
2555
2556 void
2557 md_assemble (char *str)
2558 {
2559   struct mips_cl_insn insn;
2560   bfd_reloc_code_real_type unused_reloc[3]
2561     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
2562
2563   imm_expr.X_op = O_absent;
2564   imm2_expr.X_op = O_absent;
2565   offset_expr.X_op = O_absent;
2566   imm_reloc[0] = BFD_RELOC_UNUSED;
2567   imm_reloc[1] = BFD_RELOC_UNUSED;
2568   imm_reloc[2] = BFD_RELOC_UNUSED;
2569   offset_reloc[0] = BFD_RELOC_UNUSED;
2570   offset_reloc[1] = BFD_RELOC_UNUSED;
2571   offset_reloc[2] = BFD_RELOC_UNUSED;
2572
2573   if (mips_opts.mips16)
2574     mips16_ip (str, &insn);
2575   else
2576     {
2577       mips_ip (str, &insn);
2578       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
2579             str, insn.insn_opcode));
2580     }
2581
2582   if (insn_error)
2583     {
2584       as_bad ("%s `%s'", insn_error, str);
2585       return;
2586     }
2587
2588   if (insn.insn_mo->pinfo == INSN_MACRO)
2589     {
2590       macro_start ();
2591       if (mips_opts.mips16)
2592         mips16_macro (&insn);
2593       else
2594         macro (&insn);
2595       macro_end ();
2596     }
2597   else
2598     {
2599       if (imm_expr.X_op != O_absent)
2600         append_insn (&insn, &imm_expr, imm_reloc, FALSE);
2601       else if (offset_expr.X_op != O_absent)
2602         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
2603       else
2604         append_insn (&insn, NULL, unused_reloc, FALSE);
2605     }
2606 }
2607
2608 /* Convenience functions for abstracting away the differences between
2609    MIPS16 and non-MIPS16 relocations.  */
2610
2611 static inline bfd_boolean
2612 mips16_reloc_p (bfd_reloc_code_real_type reloc)
2613 {
2614   switch (reloc)
2615     {
2616     case BFD_RELOC_MIPS16_JMP:
2617     case BFD_RELOC_MIPS16_GPREL:
2618     case BFD_RELOC_MIPS16_GOT16:
2619     case BFD_RELOC_MIPS16_CALL16:
2620     case BFD_RELOC_MIPS16_HI16_S:
2621     case BFD_RELOC_MIPS16_HI16:
2622     case BFD_RELOC_MIPS16_LO16:
2623       return TRUE;
2624
2625     default:
2626       return FALSE;
2627     }
2628 }
2629
2630 static inline bfd_boolean
2631 micromips_reloc_p (bfd_reloc_code_real_type reloc)
2632 {
2633   switch (reloc)
2634     {
2635     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
2636     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
2637     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
2638     case BFD_RELOC_MICROMIPS_GPREL16:
2639     case BFD_RELOC_MICROMIPS_JMP:
2640     case BFD_RELOC_MICROMIPS_HI16:
2641     case BFD_RELOC_MICROMIPS_HI16_S:
2642     case BFD_RELOC_MICROMIPS_LO16:
2643     case BFD_RELOC_MICROMIPS_LITERAL:
2644     case BFD_RELOC_MICROMIPS_GOT16:
2645     case BFD_RELOC_MICROMIPS_CALL16:
2646     case BFD_RELOC_MICROMIPS_GOT_HI16:
2647     case BFD_RELOC_MICROMIPS_GOT_LO16:
2648     case BFD_RELOC_MICROMIPS_CALL_HI16:
2649     case BFD_RELOC_MICROMIPS_CALL_LO16:
2650     case BFD_RELOC_MICROMIPS_SUB:
2651     case BFD_RELOC_MICROMIPS_GOT_PAGE:
2652     case BFD_RELOC_MICROMIPS_GOT_OFST:
2653     case BFD_RELOC_MICROMIPS_GOT_DISP:
2654     case BFD_RELOC_MICROMIPS_HIGHEST:
2655     case BFD_RELOC_MICROMIPS_HIGHER:
2656     case BFD_RELOC_MICROMIPS_SCN_DISP:
2657     case BFD_RELOC_MICROMIPS_JALR:
2658       return TRUE;
2659
2660     default:
2661       return FALSE;
2662     }
2663 }
2664
2665 static inline bfd_boolean
2666 jmp_reloc_p (bfd_reloc_code_real_type reloc)
2667 {
2668   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
2669 }
2670
2671 static inline bfd_boolean
2672 got16_reloc_p (bfd_reloc_code_real_type reloc)
2673 {
2674   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
2675           || reloc == BFD_RELOC_MICROMIPS_GOT16);
2676 }
2677
2678 static inline bfd_boolean
2679 hi16_reloc_p (bfd_reloc_code_real_type reloc)
2680 {
2681   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
2682           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
2683 }
2684
2685 static inline bfd_boolean
2686 lo16_reloc_p (bfd_reloc_code_real_type reloc)
2687 {
2688   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
2689           || reloc == BFD_RELOC_MICROMIPS_LO16);
2690 }
2691
2692 static inline bfd_boolean
2693 jalr_reloc_p (bfd_reloc_code_real_type reloc)
2694 {
2695   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
2696 }
2697
2698 /* Return true if the given relocation might need a matching %lo().
2699    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
2700    need a matching %lo() when applied to local symbols.  */
2701
2702 static inline bfd_boolean
2703 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
2704 {
2705   return (HAVE_IN_PLACE_ADDENDS
2706           && (hi16_reloc_p (reloc)
2707               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
2708                  all GOT16 relocations evaluate to "G".  */
2709               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
2710 }
2711
2712 /* Return the type of %lo() reloc needed by RELOC, given that
2713    reloc_needs_lo_p.  */
2714
2715 static inline bfd_reloc_code_real_type
2716 matching_lo_reloc (bfd_reloc_code_real_type reloc)
2717 {
2718   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
2719           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
2720              : BFD_RELOC_LO16));
2721 }
2722
2723 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
2724    relocation.  */
2725
2726 static inline bfd_boolean
2727 fixup_has_matching_lo_p (fixS *fixp)
2728 {
2729   return (fixp->fx_next != NULL
2730           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
2731           && fixp->fx_addsy == fixp->fx_next->fx_addsy
2732           && fixp->fx_offset == fixp->fx_next->fx_offset);
2733 }
2734
2735 /* This function returns true if modifying a register requires a
2736    delay.  */
2737
2738 static int
2739 reg_needs_delay (unsigned int reg)
2740 {
2741   unsigned long prev_pinfo;
2742
2743   prev_pinfo = history[0].insn_mo->pinfo;
2744   if (! mips_opts.noreorder
2745       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
2746            && ! gpr_interlocks)
2747           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
2748               && ! cop_interlocks)))
2749     {
2750       /* A load from a coprocessor or from memory.  All load delays
2751          delay the use of general register rt for one instruction.  */
2752       /* Itbl support may require additional care here.  */
2753       know (prev_pinfo & INSN_WRITE_GPR_T);
2754       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
2755         return 1;
2756     }
2757
2758   return 0;
2759 }
2760
2761 /* Move all labels in insn_labels to the current insertion point.  */
2762
2763 static void
2764 mips_move_labels (void)
2765 {
2766   segment_info_type *si = seg_info (now_seg);
2767   struct insn_label_list *l;
2768   valueT val;
2769
2770   for (l = si->label_list; l != NULL; l = l->next)
2771     {
2772       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
2773       symbol_set_frag (l->label, frag_now);
2774       val = (valueT) frag_now_fix ();
2775       /* MIPS16/microMIPS text labels are stored as odd.  */
2776       if (HAVE_CODE_COMPRESSION)
2777         ++val;
2778       S_SET_VALUE (l->label, val);
2779     }
2780 }
2781
2782 static bfd_boolean
2783 s_is_linkonce (symbolS *sym, segT from_seg)
2784 {
2785   bfd_boolean linkonce = FALSE;
2786   segT symseg = S_GET_SEGMENT (sym);
2787
2788   if (symseg != from_seg && !S_IS_LOCAL (sym))
2789     {
2790       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
2791         linkonce = TRUE;
2792 #ifdef OBJ_ELF
2793       /* The GNU toolchain uses an extension for ELF: a section
2794          beginning with the magic string .gnu.linkonce is a
2795          linkonce section.  */
2796       if (strncmp (segment_name (symseg), ".gnu.linkonce",
2797                    sizeof ".gnu.linkonce" - 1) == 0)
2798         linkonce = TRUE;
2799 #endif
2800     }
2801   return linkonce;
2802 }
2803
2804 /* Mark instruction labels in MIPS16/microMIPS mode.  This permits the
2805    linker to handle them specially, such as generating jalx instructions
2806    when needed.  We also make them odd for the duration of the assembly,
2807    in order to generate the right sort of code.  We will make them even
2808    in the adjust_symtab routine, while leaving them marked.  This is
2809    convenient for the debugger and the disassembler.  The linker knows
2810    to make them odd again.  */
2811
2812 static void
2813 mips_compressed_mark_labels (void)
2814 {
2815   segment_info_type *si = seg_info (now_seg);
2816   struct insn_label_list *l;
2817
2818   gas_assert (HAVE_CODE_COMPRESSION);
2819
2820   for (l = si->label_list; l != NULL; l = l->next)
2821    {
2822       symbolS *label = l->label;
2823
2824 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
2825       if (IS_ELF)
2826         {
2827           if (mips_opts.mips16)
2828             S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
2829           else
2830             S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
2831         }
2832 #endif
2833       if ((S_GET_VALUE (label) & 1) == 0
2834         /* Don't adjust the address if the label is global or weak, or
2835            in a link-once section, since we'll be emitting symbol reloc
2836            references to it which will be patched up by the linker, and
2837            the final value of the symbol may or may not be MIPS16/microMIPS.  */
2838           && ! S_IS_WEAK (label)
2839           && ! S_IS_EXTERNAL (label)
2840           && ! s_is_linkonce (label, now_seg))
2841         S_SET_VALUE (label, S_GET_VALUE (label) | 1);
2842     }
2843 }
2844
2845 /* End the current frag.  Make it a variant frag and record the
2846    relaxation info.  */
2847
2848 static void
2849 relax_close_frag (void)
2850 {
2851   mips_macro_warning.first_frag = frag_now;
2852   frag_var (rs_machine_dependent, 0, 0,
2853             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
2854             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
2855
2856   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
2857   mips_relax.first_fixup = 0;
2858 }
2859
2860 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
2861    See the comment above RELAX_ENCODE for more details.  */
2862
2863 static void
2864 relax_start (symbolS *symbol)
2865 {
2866   gas_assert (mips_relax.sequence == 0);
2867   mips_relax.sequence = 1;
2868   mips_relax.symbol = symbol;
2869 }
2870
2871 /* Start generating the second version of a relaxable sequence.
2872    See the comment above RELAX_ENCODE for more details.  */
2873
2874 static void
2875 relax_switch (void)
2876 {
2877   gas_assert (mips_relax.sequence == 1);
2878   mips_relax.sequence = 2;
2879 }
2880
2881 /* End the current relaxable sequence.  */
2882
2883 static void
2884 relax_end (void)
2885 {
2886   gas_assert (mips_relax.sequence == 2);
2887   relax_close_frag ();
2888   mips_relax.sequence = 0;
2889 }
2890
2891 /* Return true if IP is a delayed branch or jump.  */
2892
2893 static inline bfd_boolean
2894 delayed_branch_p (const struct mips_cl_insn *ip)
2895 {
2896   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
2897                                 | INSN_COND_BRANCH_DELAY
2898                                 | INSN_COND_BRANCH_LIKELY)) != 0;
2899 }
2900
2901 /* Return true if IP is a compact branch or jump.  */
2902
2903 static inline bfd_boolean
2904 compact_branch_p (const struct mips_cl_insn *ip)
2905 {
2906   if (mips_opts.mips16)
2907     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
2908                                   | MIPS16_INSN_COND_BRANCH)) != 0;
2909   else
2910     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
2911                                    | INSN2_COND_BRANCH)) != 0;
2912 }
2913
2914 /* Return true if IP is an unconditional branch or jump.  */
2915
2916 static inline bfd_boolean
2917 uncond_branch_p (const struct mips_cl_insn *ip)
2918 {
2919   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
2920           || (mips_opts.mips16
2921               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
2922               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
2923 }
2924
2925 /* Return true if IP is a branch-likely instruction.  */
2926
2927 static inline bfd_boolean
2928 branch_likely_p (const struct mips_cl_insn *ip)
2929 {
2930   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
2931 }
2932
2933 /* Return the mask of core registers that IP reads or writes.  */
2934
2935 static unsigned int
2936 gpr_mod_mask (const struct mips_cl_insn *ip)
2937 {
2938   unsigned long pinfo2;
2939   unsigned int mask;
2940
2941   mask = 0;
2942   pinfo2 = ip->insn_mo->pinfo2;
2943   if (mips_opts.micromips)
2944     {
2945       if (pinfo2 & INSN2_MOD_GPR_MB)
2946         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
2947       if (pinfo2 & INSN2_MOD_GPR_MC)
2948         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
2949       if (pinfo2 & INSN2_MOD_GPR_MD)
2950         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
2951       if (pinfo2 & INSN2_MOD_GPR_ME)
2952         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
2953       if (pinfo2 & INSN2_MOD_GPR_MF)
2954         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
2955       if (pinfo2 & INSN2_MOD_GPR_MG)
2956         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
2957       if (pinfo2 & INSN2_MOD_GPR_MHI)
2958         {
2959           mask |= 1 << micromips_to_32_reg_h_map[EXTRACT_OPERAND (1, MH, *ip)];
2960           mask |= 1 << micromips_to_32_reg_i_map[EXTRACT_OPERAND (1, MI, *ip)];
2961         }
2962       if (pinfo2 & INSN2_MOD_GPR_MJ)
2963         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
2964       if (pinfo2 & INSN2_MOD_GPR_MM)
2965         mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
2966       if (pinfo2 & INSN2_MOD_GPR_MN)
2967         mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
2968       if (pinfo2 & INSN2_MOD_GPR_MP)
2969         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
2970       if (pinfo2 & INSN2_MOD_GPR_MQ)
2971         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
2972       if (pinfo2 & INSN2_MOD_SP)
2973         mask |= 1 << SP;
2974     }
2975   return mask;
2976 }
2977
2978 /* Return the mask of core registers that IP reads.  */
2979
2980 static unsigned int
2981 gpr_read_mask (const struct mips_cl_insn *ip)
2982 {
2983   unsigned long pinfo, pinfo2;
2984   unsigned int mask;
2985
2986   mask = gpr_mod_mask (ip);
2987   pinfo = ip->insn_mo->pinfo;
2988   pinfo2 = ip->insn_mo->pinfo2;
2989   if (mips_opts.mips16)
2990     {
2991       if (pinfo & MIPS16_INSN_READ_X)
2992         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
2993       if (pinfo & MIPS16_INSN_READ_Y)
2994         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
2995       if (pinfo & MIPS16_INSN_READ_T)
2996         mask |= 1 << TREG;
2997       if (pinfo & MIPS16_INSN_READ_SP)
2998         mask |= 1 << SP;
2999       if (pinfo & MIPS16_INSN_READ_31)
3000         mask |= 1 << RA;
3001       if (pinfo & MIPS16_INSN_READ_Z)
3002         mask |= 1 << (mips16_to_32_reg_map
3003                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3004       if (pinfo & MIPS16_INSN_READ_GPR_X)
3005         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3006     }
3007   else
3008     {
3009       if (pinfo2 & INSN2_READ_GPR_D)
3010         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3011       if (pinfo & INSN_READ_GPR_T)
3012         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3013       if (pinfo & INSN_READ_GPR_S)
3014         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3015       if (pinfo2 & INSN2_READ_GP)
3016         mask |= 1 << GP;
3017       if (pinfo2 & INSN2_READ_GPR_31)
3018         mask |= 1 << RA;
3019       if (pinfo2 & INSN2_READ_GPR_Z)
3020         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3021     }
3022   /* Don't include register 0.  */
3023   return mask & ~1;
3024 }
3025
3026 /* Return the mask of core registers that IP writes.  */
3027
3028 static unsigned int
3029 gpr_write_mask (const struct mips_cl_insn *ip)
3030 {
3031   unsigned long pinfo, pinfo2;
3032   unsigned int mask;
3033
3034   mask = gpr_mod_mask (ip);
3035   pinfo = ip->insn_mo->pinfo;
3036   pinfo2 = ip->insn_mo->pinfo2;
3037   if (mips_opts.mips16)
3038     {
3039       if (pinfo & MIPS16_INSN_WRITE_X)
3040         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3041       if (pinfo & MIPS16_INSN_WRITE_Y)
3042         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3043       if (pinfo & MIPS16_INSN_WRITE_Z)
3044         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3045       if (pinfo & MIPS16_INSN_WRITE_T)
3046         mask |= 1 << TREG;
3047       if (pinfo & MIPS16_INSN_WRITE_SP)
3048         mask |= 1 << SP;
3049       if (pinfo & MIPS16_INSN_WRITE_31)
3050         mask |= 1 << RA;
3051       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3052         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3053     }
3054   else
3055     {
3056       if (pinfo & INSN_WRITE_GPR_D)
3057         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3058       if (pinfo & INSN_WRITE_GPR_T)
3059         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3060       if (pinfo2 & INSN2_WRITE_GPR_S)
3061         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3062       if (pinfo & INSN_WRITE_GPR_31)
3063         mask |= 1 << RA;
3064       if (pinfo2 & INSN2_WRITE_GPR_Z)
3065         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3066     }
3067   /* Don't include register 0.  */
3068   return mask & ~1;
3069 }
3070
3071 /* Return the mask of floating-point registers that IP reads.  */
3072
3073 static unsigned int
3074 fpr_read_mask (const struct mips_cl_insn *ip)
3075 {
3076   unsigned long pinfo, pinfo2;
3077   unsigned int mask;
3078
3079   mask = 0;
3080   pinfo = ip->insn_mo->pinfo;
3081   pinfo2 = ip->insn_mo->pinfo2;
3082   if (!mips_opts.mips16)
3083     {
3084       if (pinfo2 & INSN2_READ_FPR_D)
3085         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3086       if (pinfo & INSN_READ_FPR_S)
3087         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3088       if (pinfo & INSN_READ_FPR_T)
3089         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3090       if (pinfo & INSN_READ_FPR_R)
3091         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3092       if (pinfo2 & INSN2_READ_FPR_Z)
3093         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3094     }
3095   /* Conservatively treat all operands to an FP_D instruction are doubles.
3096      (This is overly pessimistic for things like cvt.d.s.)  */
3097   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3098     mask |= mask << 1;
3099   return mask;
3100 }
3101
3102 /* Return the mask of floating-point registers that IP writes.  */
3103
3104 static unsigned int
3105 fpr_write_mask (const struct mips_cl_insn *ip)
3106 {
3107   unsigned long pinfo, pinfo2;
3108   unsigned int mask;
3109
3110   mask = 0;
3111   pinfo = ip->insn_mo->pinfo;
3112   pinfo2 = ip->insn_mo->pinfo2;
3113   if (!mips_opts.mips16)
3114     {
3115       if (pinfo & INSN_WRITE_FPR_D)
3116         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3117       if (pinfo & INSN_WRITE_FPR_S)
3118         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3119       if (pinfo & INSN_WRITE_FPR_T)
3120         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3121       if (pinfo2 & INSN2_WRITE_FPR_Z)
3122         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3123     }
3124   /* Conservatively treat all operands to an FP_D instruction are doubles.
3125      (This is overly pessimistic for things like cvt.s.d.)  */
3126   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3127     mask |= mask << 1;
3128   return mask;
3129 }
3130
3131 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3132    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3133    by VR4120 errata.  */
3134
3135 static unsigned int
3136 classify_vr4120_insn (const char *name)
3137 {
3138   if (strncmp (name, "macc", 4) == 0)
3139     return FIX_VR4120_MACC;
3140   if (strncmp (name, "dmacc", 5) == 0)
3141     return FIX_VR4120_DMACC;
3142   if (strncmp (name, "mult", 4) == 0)
3143     return FIX_VR4120_MULT;
3144   if (strncmp (name, "dmult", 5) == 0)
3145     return FIX_VR4120_DMULT;
3146   if (strstr (name, "div"))
3147     return FIX_VR4120_DIV;
3148   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3149     return FIX_VR4120_MTHILO;
3150   return NUM_FIX_VR4120_CLASSES;
3151 }
3152
3153 #define INSN_ERET  0x42000018
3154 #define INSN_DERET 0x4200001f
3155
3156 /* Return the number of instructions that must separate INSN1 and INSN2,
3157    where INSN1 is the earlier instruction.  Return the worst-case value
3158    for any INSN2 if INSN2 is null.  */
3159
3160 static unsigned int
3161 insns_between (const struct mips_cl_insn *insn1,
3162                const struct mips_cl_insn *insn2)
3163 {
3164   unsigned long pinfo1, pinfo2;
3165   unsigned int mask;
3166
3167   /* This function needs to know which pinfo flags are set for INSN2
3168      and which registers INSN2 uses.  The former is stored in PINFO2 and
3169      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3170      will have every flag set and INSN2_USES_GPR will always return true.  */
3171   pinfo1 = insn1->insn_mo->pinfo;
3172   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3173
3174 #define INSN2_USES_GPR(REG) \
3175   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3176
3177   /* For most targets, write-after-read dependencies on the HI and LO
3178      registers must be separated by at least two instructions.  */
3179   if (!hilo_interlocks)
3180     {
3181       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3182         return 2;
3183       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3184         return 2;
3185     }
3186
3187   /* If we're working around r7000 errata, there must be two instructions
3188      between an mfhi or mflo and any instruction that uses the result.  */
3189   if (mips_7000_hilo_fix
3190       && !mips_opts.micromips
3191       && MF_HILO_INSN (pinfo1)
3192       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3193     return 2;
3194
3195   /* If we're working around 24K errata, one instruction is required
3196      if an ERET or DERET is followed by a branch instruction.  */
3197   if (mips_fix_24k && !mips_opts.micromips)
3198     {
3199       if (insn1->insn_opcode == INSN_ERET
3200           || insn1->insn_opcode == INSN_DERET)
3201         {
3202           if (insn2 == NULL
3203               || insn2->insn_opcode == INSN_ERET
3204               || insn2->insn_opcode == INSN_DERET
3205               || delayed_branch_p (insn2))
3206             return 1;
3207         }
3208     }
3209
3210   /* If working around VR4120 errata, check for combinations that need
3211      a single intervening instruction.  */
3212   if (mips_fix_vr4120 && !mips_opts.micromips)
3213     {
3214       unsigned int class1, class2;
3215
3216       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3217       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3218         {
3219           if (insn2 == NULL)
3220             return 1;
3221           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3222           if (vr4120_conflicts[class1] & (1 << class2))
3223             return 1;
3224         }
3225     }
3226
3227   if (!HAVE_CODE_COMPRESSION)
3228     {
3229       /* Check for GPR or coprocessor load delays.  All such delays
3230          are on the RT register.  */
3231       /* Itbl support may require additional care here.  */
3232       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3233           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3234         {
3235           know (pinfo1 & INSN_WRITE_GPR_T);
3236           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3237             return 1;
3238         }
3239
3240       /* Check for generic coprocessor hazards.
3241
3242          This case is not handled very well.  There is no special
3243          knowledge of CP0 handling, and the coprocessors other than
3244          the floating point unit are not distinguished at all.  */
3245       /* Itbl support may require additional care here. FIXME!
3246          Need to modify this to include knowledge about
3247          user specified delays!  */
3248       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3249                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3250         {
3251           /* Handle cases where INSN1 writes to a known general coprocessor
3252              register.  There must be a one instruction delay before INSN2
3253              if INSN2 reads that register, otherwise no delay is needed.  */
3254           mask = fpr_write_mask (insn1);
3255           if (mask != 0)
3256             {
3257               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3258                 return 1;
3259             }
3260           else
3261             {
3262               /* Read-after-write dependencies on the control registers
3263                  require a two-instruction gap.  */
3264               if ((pinfo1 & INSN_WRITE_COND_CODE)
3265                   && (pinfo2 & INSN_READ_COND_CODE))
3266                 return 2;
3267
3268               /* We don't know exactly what INSN1 does.  If INSN2 is
3269                  also a coprocessor instruction, assume there must be
3270                  a one instruction gap.  */
3271               if (pinfo2 & INSN_COP)
3272                 return 1;
3273             }
3274         }
3275
3276       /* Check for read-after-write dependencies on the coprocessor
3277          control registers in cases where INSN1 does not need a general
3278          coprocessor delay.  This means that INSN1 is a floating point
3279          comparison instruction.  */
3280       /* Itbl support may require additional care here.  */
3281       else if (!cop_interlocks
3282                && (pinfo1 & INSN_WRITE_COND_CODE)
3283                && (pinfo2 & INSN_READ_COND_CODE))
3284         return 1;
3285     }
3286
3287 #undef INSN2_USES_GPR
3288
3289   return 0;
3290 }
3291
3292 /* Return the number of nops that would be needed to work around the
3293    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3294    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3295    that are contained within the first IGNORE instructions of HIST.  */
3296
3297 static int
3298 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3299                  const struct mips_cl_insn *insn)
3300 {
3301   int i, j;
3302   unsigned int mask;
3303
3304   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3305      are not affected by the errata.  */
3306   if (insn != 0
3307       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3308           || strcmp (insn->insn_mo->name, "mtlo") == 0
3309           || strcmp (insn->insn_mo->name, "mthi") == 0))
3310     return 0;
3311
3312   /* Search for the first MFLO or MFHI.  */
3313   for (i = 0; i < MAX_VR4130_NOPS; i++)
3314     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3315       {
3316         /* Extract the destination register.  */
3317         mask = gpr_write_mask (&hist[i]);
3318
3319         /* No nops are needed if INSN reads that register.  */
3320         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3321           return 0;
3322
3323         /* ...or if any of the intervening instructions do.  */
3324         for (j = 0; j < i; j++)
3325           if (gpr_read_mask (&hist[j]) & mask)
3326             return 0;
3327
3328         if (i >= ignore)
3329           return MAX_VR4130_NOPS - i;
3330       }
3331   return 0;
3332 }
3333
3334 #define BASE_REG_EQ(INSN1, INSN2)       \
3335   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3336       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3337
3338 /* Return the minimum alignment for this store instruction.  */
3339
3340 static int
3341 fix_24k_align_to (const struct mips_opcode *mo)
3342 {
3343   if (strcmp (mo->name, "sh") == 0)
3344     return 2;
3345
3346   if (strcmp (mo->name, "swc1") == 0
3347       || strcmp (mo->name, "swc2") == 0
3348       || strcmp (mo->name, "sw") == 0
3349       || strcmp (mo->name, "sc") == 0
3350       || strcmp (mo->name, "s.s") == 0)
3351     return 4;
3352
3353   if (strcmp (mo->name, "sdc1") == 0
3354       || strcmp (mo->name, "sdc2") == 0
3355       || strcmp (mo->name, "s.d") == 0)
3356     return 8;
3357
3358   /* sb, swl, swr */
3359   return 1;
3360 }
3361
3362 struct fix_24k_store_info
3363   {
3364     /* Immediate offset, if any, for this store instruction.  */
3365     short off;
3366     /* Alignment required by this store instruction.  */
3367     int align_to;
3368     /* True for register offsets.  */
3369     int register_offset;
3370   };
3371
3372 /* Comparison function used by qsort.  */
3373
3374 static int
3375 fix_24k_sort (const void *a, const void *b)
3376 {
3377   const struct fix_24k_store_info *pos1 = a;
3378   const struct fix_24k_store_info *pos2 = b;
3379
3380   return (pos1->off - pos2->off);
3381 }
3382
3383 /* INSN is a store instruction.  Try to record the store information
3384    in STINFO.  Return false if the information isn't known.  */
3385
3386 static bfd_boolean
3387 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3388                            const struct mips_cl_insn *insn)
3389 {
3390   /* The instruction must have a known offset.  */
3391   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3392     return FALSE;
3393
3394   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3395   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3396   return TRUE;
3397 }
3398
3399 /* Return the number of nops that would be needed to work around the 24k
3400    "lost data on stores during refill" errata if instruction INSN
3401    immediately followed the 2 instructions described by HIST.
3402    Ignore hazards that are contained within the first IGNORE
3403    instructions of HIST.
3404
3405    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3406    for the data cache refills and store data. The following describes
3407    the scenario where the store data could be lost.
3408
3409    * A data cache miss, due to either a load or a store, causing fill
3410      data to be supplied by the memory subsystem
3411    * The first three doublewords of fill data are returned and written
3412      into the cache
3413    * A sequence of four stores occurs in consecutive cycles around the
3414      final doubleword of the fill:
3415    * Store A
3416    * Store B
3417    * Store C
3418    * Zero, One or more instructions
3419    * Store D
3420
3421    The four stores A-D must be to different doublewords of the line that
3422    is being filled. The fourth instruction in the sequence above permits
3423    the fill of the final doubleword to be transferred from the FSB into
3424    the cache. In the sequence above, the stores may be either integer
3425    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
3426    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
3427    different doublewords on the line. If the floating point unit is
3428    running in 1:2 mode, it is not possible to create the sequence above
3429    using only floating point store instructions.
3430
3431    In this case, the cache line being filled is incorrectly marked
3432    invalid, thereby losing the data from any store to the line that
3433    occurs between the original miss and the completion of the five
3434    cycle sequence shown above.
3435
3436    The workarounds are:
3437
3438    * Run the data cache in write-through mode.
3439    * Insert a non-store instruction between
3440      Store A and Store B or Store B and Store C.  */
3441   
3442 static int
3443 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
3444               const struct mips_cl_insn *insn)
3445 {
3446   struct fix_24k_store_info pos[3];
3447   int align, i, base_offset;
3448
3449   if (ignore >= 2)
3450     return 0;
3451
3452   /* If the previous instruction wasn't a store, there's nothing to
3453      worry about.  */
3454   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3455     return 0;
3456
3457   /* If the instructions after the previous one are unknown, we have
3458      to assume the worst.  */
3459   if (!insn)
3460     return 1;
3461
3462   /* Check whether we are dealing with three consecutive stores.  */
3463   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
3464       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
3465     return 0;
3466
3467   /* If we don't know the relationship between the store addresses,
3468      assume the worst.  */
3469   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
3470       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
3471     return 1;
3472
3473   if (!fix_24k_record_store_info (&pos[0], insn)
3474       || !fix_24k_record_store_info (&pos[1], &hist[0])
3475       || !fix_24k_record_store_info (&pos[2], &hist[1]))
3476     return 1;
3477
3478   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
3479
3480   /* Pick a value of ALIGN and X such that all offsets are adjusted by
3481      X bytes and such that the base register + X is known to be aligned
3482      to align bytes.  */
3483
3484   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
3485     align = 8;
3486   else
3487     {
3488       align = pos[0].align_to;
3489       base_offset = pos[0].off;
3490       for (i = 1; i < 3; i++)
3491         if (align < pos[i].align_to)
3492           {
3493             align = pos[i].align_to;
3494             base_offset = pos[i].off;
3495           }
3496       for (i = 0; i < 3; i++)
3497         pos[i].off -= base_offset;
3498     }
3499
3500   pos[0].off &= ~align + 1;
3501   pos[1].off &= ~align + 1;
3502   pos[2].off &= ~align + 1;
3503
3504   /* If any two stores write to the same chunk, they also write to the
3505      same doubleword.  The offsets are still sorted at this point.  */
3506   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
3507     return 0;
3508
3509   /* A range of at least 9 bytes is needed for the stores to be in
3510      non-overlapping doublewords.  */
3511   if (pos[2].off - pos[0].off <= 8)
3512     return 0;
3513
3514   if (pos[2].off - pos[1].off >= 24
3515       || pos[1].off - pos[0].off >= 24
3516       || pos[2].off - pos[0].off >= 32)
3517     return 0;
3518
3519   return 1;
3520 }
3521
3522 /* Return the number of nops that would be needed if instruction INSN
3523    immediately followed the MAX_NOPS instructions given by HIST,
3524    where HIST[0] is the most recent instruction.  Ignore hazards
3525    between INSN and the first IGNORE instructions in HIST.
3526
3527    If INSN is null, return the worse-case number of nops for any
3528    instruction.  */
3529
3530 static int
3531 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
3532                const struct mips_cl_insn *insn)
3533 {
3534   int i, nops, tmp_nops;
3535
3536   nops = 0;
3537   for (i = ignore; i < MAX_DELAY_NOPS; i++)
3538     {
3539       tmp_nops = insns_between (hist + i, insn) - i;
3540       if (tmp_nops > nops)
3541         nops = tmp_nops;
3542     }
3543
3544   if (mips_fix_vr4130 && !mips_opts.micromips)
3545     {
3546       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
3547       if (tmp_nops > nops)
3548         nops = tmp_nops;
3549     }
3550
3551   if (mips_fix_24k && !mips_opts.micromips)
3552     {
3553       tmp_nops = nops_for_24k (ignore, hist, insn);
3554       if (tmp_nops > nops)
3555         nops = tmp_nops;
3556     }
3557
3558   return nops;
3559 }
3560
3561 /* The variable arguments provide NUM_INSNS extra instructions that
3562    might be added to HIST.  Return the largest number of nops that
3563    would be needed after the extended sequence, ignoring hazards
3564    in the first IGNORE instructions.  */
3565
3566 static int
3567 nops_for_sequence (int num_insns, int ignore,
3568                    const struct mips_cl_insn *hist, ...)
3569 {
3570   va_list args;
3571   struct mips_cl_insn buffer[MAX_NOPS];
3572   struct mips_cl_insn *cursor;
3573   int nops;
3574
3575   va_start (args, hist);
3576   cursor = buffer + num_insns;
3577   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
3578   while (cursor > buffer)
3579     *--cursor = *va_arg (args, const struct mips_cl_insn *);
3580
3581   nops = nops_for_insn (ignore, buffer, NULL);
3582   va_end (args);
3583   return nops;
3584 }
3585
3586 /* Like nops_for_insn, but if INSN is a branch, take into account the
3587    worst-case delay for the branch target.  */
3588
3589 static int
3590 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
3591                          const struct mips_cl_insn *insn)
3592 {
3593   int nops, tmp_nops;
3594
3595   nops = nops_for_insn (ignore, hist, insn);
3596   if (delayed_branch_p (insn))
3597     {
3598       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
3599                                     hist, insn, NOP_INSN);
3600       if (tmp_nops > nops)
3601         nops = tmp_nops;
3602     }
3603   else if (compact_branch_p (insn))
3604     {
3605       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
3606       if (tmp_nops > nops)
3607         nops = tmp_nops;
3608     }
3609   return nops;
3610 }
3611
3612 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
3613
3614 static void
3615 fix_loongson2f_nop (struct mips_cl_insn * ip)
3616 {
3617   gas_assert (!HAVE_CODE_COMPRESSION);
3618   if (strcmp (ip->insn_mo->name, "nop") == 0)
3619     ip->insn_opcode = LOONGSON2F_NOP_INSN;
3620 }
3621
3622 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
3623                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
3624
3625 static void
3626 fix_loongson2f_jump (struct mips_cl_insn * ip)
3627 {
3628   gas_assert (!HAVE_CODE_COMPRESSION);
3629   if (strcmp (ip->insn_mo->name, "j") == 0
3630       || strcmp (ip->insn_mo->name, "jr") == 0
3631       || strcmp (ip->insn_mo->name, "jalr") == 0)
3632     {
3633       int sreg;
3634       expressionS ep;
3635
3636       if (! mips_opts.at)
3637         return;
3638
3639       sreg = EXTRACT_OPERAND (0, RS, *ip);
3640       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
3641         return;
3642
3643       ep.X_op = O_constant;
3644       ep.X_add_number = 0xcfff0000;
3645       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
3646       ep.X_add_number = 0xffff;
3647       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
3648       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
3649     }
3650 }
3651
3652 static void
3653 fix_loongson2f (struct mips_cl_insn * ip)
3654 {
3655   if (mips_fix_loongson2f_nop)
3656     fix_loongson2f_nop (ip);
3657
3658   if (mips_fix_loongson2f_jump)
3659     fix_loongson2f_jump (ip);
3660 }
3661
3662 /* IP is a branch that has a delay slot, and we need to fill it
3663    automatically.   Return true if we can do that by swapping IP
3664    with the previous instruction.  */
3665
3666 static bfd_boolean
3667 can_swap_branch_p (struct mips_cl_insn *ip)
3668 {
3669   unsigned long pinfo, pinfo2, prev_pinfo;
3670   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
3671
3672   /* For microMIPS, disable reordering.  */
3673   if (mips_opts.micromips)
3674     return FALSE;
3675
3676   /* -O2 and above is required for this optimization.  */
3677   if (mips_optimize < 2)
3678     return FALSE;
3679
3680   /* If we have seen .set volatile or .set nomove, don't optimize.  */
3681   if (mips_opts.nomove)
3682     return FALSE;
3683
3684   /* We can't swap if the previous instruction's position is fixed.  */
3685   if (history[0].fixed_p)
3686     return FALSE;
3687
3688   /* If the previous previous insn was in a .set noreorder, we can't
3689      swap.  Actually, the MIPS assembler will swap in this situation.
3690      However, gcc configured -with-gnu-as will generate code like
3691
3692         .set    noreorder
3693         lw      $4,XXX
3694         .set    reorder
3695         INSN
3696         bne     $4,$0,foo
3697
3698      in which we can not swap the bne and INSN.  If gcc is not configured
3699      -with-gnu-as, it does not output the .set pseudo-ops.  */
3700   if (history[1].noreorder_p)
3701     return FALSE;
3702
3703   /* If the previous instruction had a fixup in mips16 mode, we can not
3704      swap.  This normally means that the previous instruction was a 4
3705      byte branch anyhow.  */
3706   if (mips_opts.mips16 && history[0].fixp[0])
3707     return FALSE;
3708
3709   /* If the branch is itself the target of a branch, we can not swap.
3710      We cheat on this; all we check for is whether there is a label on
3711      this instruction.  If there are any branches to anything other than
3712      a label, users must use .set noreorder.  */
3713   if (seg_info (now_seg)->label_list)
3714     return FALSE;
3715
3716   /* If the previous instruction is in a variant frag other than this
3717      branch's one, we cannot do the swap.  This does not apply to
3718      MIPS16/microMIPS code, which uses variant frags for different
3719      purposes.  */
3720   if (!HAVE_CODE_COMPRESSION
3721       && history[0].frag
3722       && history[0].frag->fr_type == rs_machine_dependent)
3723     return FALSE;
3724
3725   /* We do not swap with instructions that cannot architecturally
3726      be placed in a branch delay slot, such as SYNC or ERET.  We
3727      also refrain from swapping with a trap instruction, since it
3728      complicates trap handlers to have the trap instruction be in
3729      a delay slot.  */
3730   prev_pinfo = history[0].insn_mo->pinfo;
3731   if (prev_pinfo & INSN_NO_DELAY_SLOT)
3732     return FALSE;
3733
3734   /* Check for conflicts between the branch and the instructions
3735      before the candidate delay slot.  */
3736   if (nops_for_insn (0, history + 1, ip) > 0)
3737     return FALSE;
3738
3739   /* Check for conflicts between the swapped sequence and the
3740      target of the branch.  */
3741   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
3742     return FALSE;
3743
3744   /* If the branch reads a register that the previous
3745      instruction sets, we can not swap.  */
3746   gpr_read = gpr_read_mask (ip);
3747   prev_gpr_write = gpr_write_mask (&history[0]);
3748   if (gpr_read & prev_gpr_write)
3749     return FALSE;
3750
3751   /* If the branch writes a register that the previous
3752      instruction sets, we can not swap.  */
3753   gpr_write = gpr_write_mask (ip);
3754   if (gpr_write & prev_gpr_write)
3755     return FALSE;
3756
3757   /* If the branch writes a register that the previous
3758      instruction reads, we can not swap.  */
3759   prev_gpr_read = gpr_read_mask (&history[0]);
3760   if (gpr_write & prev_gpr_read)
3761     return FALSE;
3762
3763   /* If one instruction sets a condition code and the
3764      other one uses a condition code, we can not swap.  */
3765   pinfo = ip->insn_mo->pinfo;
3766   if ((pinfo & INSN_READ_COND_CODE)
3767       && (prev_pinfo & INSN_WRITE_COND_CODE))
3768     return FALSE;
3769   if ((pinfo & INSN_WRITE_COND_CODE)
3770       && (prev_pinfo & INSN_READ_COND_CODE))
3771     return FALSE;
3772
3773   /* If the previous instruction uses the PC, we can not swap.  */
3774   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
3775     return FALSE;
3776
3777   /* If the previous instruction has an incorrect size for a fixed
3778      branch delay slot in microMIPS mode, we cannot swap.  */
3779   pinfo2 = ip->insn_mo->pinfo2;
3780   if (mips_opts.micromips
3781       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
3782       && insn_length (history) != 2)
3783     return FALSE;
3784   if (mips_opts.micromips
3785       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
3786       && insn_length (history) != 4)
3787     return FALSE;
3788
3789   return TRUE;
3790 }
3791
3792 /* Decide how we should add IP to the instruction stream.  */
3793
3794 static enum append_method
3795 get_append_method (struct mips_cl_insn *ip)
3796 {
3797   unsigned long pinfo;
3798
3799   /* The relaxed version of a macro sequence must be inherently
3800      hazard-free.  */
3801   if (mips_relax.sequence == 2)
3802     return APPEND_ADD;
3803
3804   /* We must not dabble with instructions in a ".set norerorder" block.  */
3805   if (mips_opts.noreorder)
3806     return APPEND_ADD;
3807
3808   /* Otherwise, it's our responsibility to fill branch delay slots.  */
3809   if (delayed_branch_p (ip))
3810     {
3811       if (!branch_likely_p (ip) && can_swap_branch_p (ip))
3812         return APPEND_SWAP;
3813
3814       pinfo = ip->insn_mo->pinfo;
3815       if (mips_opts.mips16
3816           && ISA_SUPPORTS_MIPS16E
3817           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
3818         return APPEND_ADD_COMPACT;
3819
3820       return APPEND_ADD_WITH_NOP;
3821     }
3822
3823   return APPEND_ADD;
3824 }
3825
3826 /* IP is a MIPS16 instruction whose opcode we have just changed.
3827    Point IP->insn_mo to the new opcode's definition.  */
3828
3829 static void
3830 find_altered_mips16_opcode (struct mips_cl_insn *ip)
3831 {
3832   const struct mips_opcode *mo, *end;
3833
3834   end = &mips16_opcodes[bfd_mips16_num_opcodes];
3835   for (mo = ip->insn_mo; mo < end; mo++)
3836     if ((ip->insn_opcode & mo->mask) == mo->match)
3837       {
3838         ip->insn_mo = mo;
3839         return;
3840       }
3841   abort ();
3842 }
3843
3844 /* For microMIPS macros, we need to generate a local number label
3845    as the target of branches.  */
3846 #define MICROMIPS_LABEL_CHAR            '\037'
3847 static unsigned long micromips_target_label;
3848 static char micromips_target_name[32];
3849
3850 static char *
3851 micromips_label_name (void)
3852 {
3853   char *p = micromips_target_name;
3854   char symbol_name_temporary[24];
3855   unsigned long l;
3856   int i;
3857
3858   if (*p)
3859     return p;
3860
3861   i = 0;
3862   l = micromips_target_label;
3863 #ifdef LOCAL_LABEL_PREFIX
3864   *p++ = LOCAL_LABEL_PREFIX;
3865 #endif
3866   *p++ = 'L';
3867   *p++ = MICROMIPS_LABEL_CHAR;
3868   do
3869     {
3870       symbol_name_temporary[i++] = l % 10 + '0';
3871       l /= 10;
3872     }
3873   while (l != 0);
3874   while (i > 0)
3875     *p++ = symbol_name_temporary[--i];
3876   *p = '\0';
3877
3878   return micromips_target_name;
3879 }
3880
3881 static void
3882 micromips_label_expr (expressionS *label_expr)
3883 {
3884   label_expr->X_op = O_symbol;
3885   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
3886   label_expr->X_add_number = 0;
3887 }
3888
3889 static void
3890 micromips_label_inc (void)
3891 {
3892   micromips_target_label++;
3893   *micromips_target_name = '\0';
3894 }
3895
3896 static void
3897 micromips_add_label (void)
3898 {
3899   symbolS *s;
3900
3901   s = colon (micromips_label_name ());
3902   micromips_label_inc ();
3903 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
3904   if (IS_ELF)
3905     S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
3906 #endif
3907 }
3908
3909 /* If assembling microMIPS code, then return the microMIPS reloc
3910    corresponding to the requested one if any.  Otherwise return
3911    the reloc unchanged.  */
3912
3913 static bfd_reloc_code_real_type
3914 micromips_map_reloc (bfd_reloc_code_real_type reloc)
3915 {
3916   static const bfd_reloc_code_real_type relocs[][2] =
3917     {
3918       /* Keep sorted incrementally by the left-hand key.  */
3919       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
3920       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
3921       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
3922       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
3923       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
3924       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
3925       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
3926       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
3927       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
3928       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
3929       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
3930       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
3931       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
3932       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
3933       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
3934       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
3935       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
3936       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
3937       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
3938       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
3939       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
3940       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
3941       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
3942       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
3943       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
3944       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
3945       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
3946     };
3947   bfd_reloc_code_real_type r;
3948   size_t i;
3949
3950   if (!mips_opts.micromips)
3951     return reloc;
3952   for (i = 0; i < ARRAY_SIZE (relocs); i++)
3953     {
3954       r = relocs[i][0];
3955       if (r > reloc)
3956         return reloc;
3957       if (r == reloc)
3958         return relocs[i][1];
3959     }
3960   return reloc;
3961 }
3962
3963 /* Output an instruction.  IP is the instruction information.
3964    ADDRESS_EXPR is an operand of the instruction to be used with
3965    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
3966    a macro expansion.  */
3967
3968 static void
3969 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
3970              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
3971 {
3972   unsigned long prev_pinfo2, pinfo, pinfo2;
3973   bfd_boolean relaxed_branch = FALSE;
3974   enum append_method method;
3975   bfd_boolean relax32;
3976
3977   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
3978     fix_loongson2f (ip);
3979
3980   mips_mark_labels ();
3981
3982   file_ase_mips16 |= mips_opts.mips16;
3983   file_ase_micromips |= mips_opts.micromips;
3984
3985   prev_pinfo2 = history[0].insn_mo->pinfo2;
3986   pinfo = ip->insn_mo->pinfo;
3987   pinfo2 = ip->insn_mo->pinfo2;
3988
3989   if (mips_opts.micromips
3990       && !expansionp
3991       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3992            && micromips_insn_length (ip->insn_mo) != 2)
3993           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3994               && micromips_insn_length (ip->insn_mo) != 4)))
3995     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
3996              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
3997
3998   if (address_expr == NULL)
3999     ip->complete_p = 1;
4000   else if (*reloc_type <= BFD_RELOC_UNUSED
4001            && address_expr->X_op == O_constant)
4002     {
4003       unsigned int tmp;
4004
4005       ip->complete_p = 1;
4006       switch (*reloc_type)
4007         {
4008         case BFD_RELOC_32:
4009           ip->insn_opcode |= address_expr->X_add_number;
4010           break;
4011
4012         case BFD_RELOC_MIPS_HIGHEST:
4013           tmp = (address_expr->X_add_number + 0x800080008000ull) >> 48;
4014           ip->insn_opcode |= tmp & 0xffff;
4015           break;
4016
4017         case BFD_RELOC_MIPS_HIGHER:
4018           tmp = (address_expr->X_add_number + 0x80008000ull) >> 32;
4019           ip->insn_opcode |= tmp & 0xffff;
4020           break;
4021
4022         case BFD_RELOC_HI16_S:
4023           tmp = (address_expr->X_add_number + 0x8000) >> 16;
4024           ip->insn_opcode |= tmp & 0xffff;
4025           break;
4026
4027         case BFD_RELOC_HI16:
4028           ip->insn_opcode |= (address_expr->X_add_number >> 16) & 0xffff;
4029           break;
4030
4031         case BFD_RELOC_UNUSED:
4032         case BFD_RELOC_LO16:
4033         case BFD_RELOC_MIPS_GOT_DISP:
4034           ip->insn_opcode |= address_expr->X_add_number & 0xffff;
4035           break;
4036
4037         case BFD_RELOC_MIPS_JMP:
4038           {
4039             int shift;
4040
4041             shift = mips_opts.micromips ? 1 : 2;
4042             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4043               as_bad (_("jump to misaligned address (0x%lx)"),
4044                       (unsigned long) address_expr->X_add_number);
4045             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4046                                 & 0x3ffffff);
4047             ip->complete_p = 0;
4048           }
4049           break;
4050
4051         case BFD_RELOC_MIPS16_JMP:
4052           if ((address_expr->X_add_number & 3) != 0)
4053             as_bad (_("jump to misaligned address (0x%lx)"),
4054                     (unsigned long) address_expr->X_add_number);
4055           ip->insn_opcode |=
4056             (((address_expr->X_add_number & 0x7c0000) << 3)
4057                | ((address_expr->X_add_number & 0xf800000) >> 7)
4058                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4059           ip->complete_p = 0;
4060           break;
4061
4062         case BFD_RELOC_16_PCREL_S2:
4063           {
4064             int shift;
4065
4066             shift = mips_opts.micromips ? 1 : 2;
4067             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4068               as_bad (_("branch to misaligned address (0x%lx)"),
4069                       (unsigned long) address_expr->X_add_number);
4070             if (!mips_relax_branch)
4071               {
4072                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4073                     & ~((1 << (shift + 16)) - 1))
4074                   as_bad (_("branch address range overflow (0x%lx)"),
4075                           (unsigned long) address_expr->X_add_number);
4076                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4077                                     & 0xffff);
4078               }
4079             ip->complete_p = 0;
4080           }
4081           break;
4082
4083         default:
4084           internalError ();
4085         }       
4086     }
4087
4088   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4089     {
4090       /* There are a lot of optimizations we could do that we don't.
4091          In particular, we do not, in general, reorder instructions.
4092          If you use gcc with optimization, it will reorder
4093          instructions and generally do much more optimization then we
4094          do here; repeating all that work in the assembler would only
4095          benefit hand written assembly code, and does not seem worth
4096          it.  */
4097       int nops = (mips_optimize == 0
4098                   ? nops_for_insn (0, history, NULL)
4099                   : nops_for_insn_or_target (0, history, ip));
4100       if (nops > 0)
4101         {
4102           fragS *old_frag;
4103           unsigned long old_frag_offset;
4104           int i;
4105
4106           old_frag = frag_now;
4107           old_frag_offset = frag_now_fix ();
4108
4109           for (i = 0; i < nops; i++)
4110             emit_nop ();
4111
4112           if (listing)
4113             {
4114               listing_prev_line ();
4115               /* We may be at the start of a variant frag.  In case we
4116                  are, make sure there is enough space for the frag
4117                  after the frags created by listing_prev_line.  The
4118                  argument to frag_grow here must be at least as large
4119                  as the argument to all other calls to frag_grow in
4120                  this file.  We don't have to worry about being in the
4121                  middle of a variant frag, because the variants insert
4122                  all needed nop instructions themselves.  */
4123               frag_grow (40);
4124             }
4125
4126           mips_move_labels ();
4127
4128 #ifndef NO_ECOFF_DEBUGGING
4129           if (ECOFF_DEBUGGING)
4130             ecoff_fix_loc (old_frag, old_frag_offset);
4131 #endif
4132         }
4133     }
4134   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4135     {
4136       int nops;
4137
4138       /* Work out how many nops in prev_nop_frag are needed by IP,
4139          ignoring hazards generated by the first prev_nop_frag_since
4140          instructions.  */
4141       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4142       gas_assert (nops <= prev_nop_frag_holds);
4143
4144       /* Enforce NOPS as a minimum.  */
4145       if (nops > prev_nop_frag_required)
4146         prev_nop_frag_required = nops;
4147
4148       if (prev_nop_frag_holds == prev_nop_frag_required)
4149         {
4150           /* Settle for the current number of nops.  Update the history
4151              accordingly (for the benefit of any future .set reorder code).  */
4152           prev_nop_frag = NULL;
4153           insert_into_history (prev_nop_frag_since,
4154                                prev_nop_frag_holds, NOP_INSN);
4155         }
4156       else
4157         {
4158           /* Allow this instruction to replace one of the nops that was
4159              tentatively added to prev_nop_frag.  */
4160           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4161           prev_nop_frag_holds--;
4162           prev_nop_frag_since++;
4163         }
4164     }
4165
4166   method = get_append_method (ip);
4167
4168 #ifdef OBJ_ELF
4169   /* The value passed to dwarf2_emit_insn is the distance between
4170      the beginning of the current instruction and the address that
4171      should be recorded in the debug tables.  This is normally the
4172      current address.
4173
4174      For MIPS16/microMIPS debug info we want to use ISA-encoded
4175      addresses, so we use -1 for an address higher by one than the
4176      current one.
4177
4178      If the instruction produced is a branch that we will swap with
4179      the preceding instruction, then we add the displacement by which
4180      the branch will be moved backwards.  This is more appropriate
4181      and for MIPS16/microMIPS code also prevents a debugger from
4182      placing a breakpoint in the middle of the branch (and corrupting
4183      code if software breakpoints are used).  */
4184   dwarf2_emit_insn ((HAVE_CODE_COMPRESSION ? -1 : 0)
4185                     + (method == APPEND_SWAP ? insn_length (history) : 0));
4186 #endif
4187
4188   relax32 = (mips_relax_branch
4189              /* Don't try branch relaxation within .set nomacro, or within
4190                 .set noat if we use $at for PIC computations.  If it turns
4191                 out that the branch was out-of-range, we'll get an error.  */
4192              && !mips_opts.warn_about_macros
4193              && (mips_opts.at || mips_pic == NO_PIC)
4194              /* Don't relax BPOSGE32/64 as they have no complementing
4195                 branches.  */
4196              && !(ip->insn_mo->membership & (INSN_DSP64 | INSN_DSP))
4197              /* Don't try 32-bit branch relaxation when users specify
4198                 16-bit/32-bit instructions.  */
4199              && !forced_insn_length);
4200
4201   if (!HAVE_CODE_COMPRESSION
4202       && address_expr
4203       && relax32
4204       && *reloc_type == BFD_RELOC_16_PCREL_S2
4205       && delayed_branch_p (ip))
4206     {
4207       relaxed_branch = TRUE;
4208       add_relaxed_insn (ip, (relaxed_branch_length
4209                              (NULL, NULL,
4210                               uncond_branch_p (ip) ? -1
4211                               : branch_likely_p (ip) ? 1
4212                               : 0)), 4,
4213                         RELAX_BRANCH_ENCODE
4214                         (AT,
4215                          uncond_branch_p (ip),
4216                          branch_likely_p (ip),
4217                          pinfo & INSN_WRITE_GPR_31,
4218                          0),
4219                         address_expr->X_add_symbol,
4220                         address_expr->X_add_number);
4221       *reloc_type = BFD_RELOC_UNUSED;
4222     }
4223   else if (mips_opts.micromips
4224            && address_expr
4225            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4226                || *reloc_type > BFD_RELOC_UNUSED)
4227            && (delayed_branch_p (ip) || compact_branch_p (ip)))
4228     {
4229       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4230       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4231       int uncond = uncond_branch_p (ip) ? -1 : 0;
4232       int compact = compact_branch_p (ip);
4233       int al = pinfo & INSN_WRITE_GPR_31;
4234       int length32;
4235
4236       gas_assert (address_expr != NULL);
4237       gas_assert (!mips_relax.sequence);
4238
4239       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4240       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4241                         RELAX_MICROMIPS_ENCODE (type, AT,
4242                                                 forced_insn_length == 2,
4243                                                 uncond, compact, al, relax32,
4244                                                 0, 0),
4245                         address_expr->X_add_symbol,
4246                         address_expr->X_add_number);
4247       *reloc_type = BFD_RELOC_UNUSED;
4248     }
4249   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4250     {
4251       /* We need to set up a variant frag.  */
4252       gas_assert (address_expr != NULL);
4253       add_relaxed_insn (ip, 4, 0,
4254                         RELAX_MIPS16_ENCODE
4255                         (*reloc_type - BFD_RELOC_UNUSED,
4256                          forced_insn_length == 2, forced_insn_length == 4,
4257                          delayed_branch_p (&history[0]),
4258                          history[0].mips16_absolute_jump_p),
4259                         make_expr_symbol (address_expr), 0);
4260     }
4261   else if (mips_opts.mips16
4262            && ! ip->use_extend
4263            && *reloc_type != BFD_RELOC_MIPS16_JMP)
4264     {
4265       if (!delayed_branch_p (ip))
4266         /* Make sure there is enough room to swap this instruction with
4267            a following jump instruction.  */
4268         frag_grow (6);
4269       add_fixed_insn (ip);
4270     }
4271   else
4272     {
4273       if (mips_opts.mips16
4274           && mips_opts.noreorder
4275           && delayed_branch_p (&history[0]))
4276         as_warn (_("extended instruction in delay slot"));
4277
4278       if (mips_relax.sequence)
4279         {
4280           /* If we've reached the end of this frag, turn it into a variant
4281              frag and record the information for the instructions we've
4282              written so far.  */
4283           if (frag_room () < 4)
4284             relax_close_frag ();
4285           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4286         }
4287
4288       if (mips_relax.sequence != 2)
4289         {
4290           if (mips_macro_warning.first_insn_sizes[0] == 0)
4291             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4292           mips_macro_warning.sizes[0] += insn_length (ip);
4293           mips_macro_warning.insns[0]++;
4294         }
4295       if (mips_relax.sequence != 1)
4296         {
4297           if (mips_macro_warning.first_insn_sizes[1] == 0)
4298             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4299           mips_macro_warning.sizes[1] += insn_length (ip);
4300           mips_macro_warning.insns[1]++;
4301         }
4302
4303       if (mips_opts.mips16)
4304         {
4305           ip->fixed_p = 1;
4306           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4307         }
4308       add_fixed_insn (ip);
4309     }
4310
4311   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4312     {
4313       bfd_reloc_code_real_type final_type[3];
4314       reloc_howto_type *howto0;
4315       reloc_howto_type *howto;
4316       int i;
4317
4318       /* Perform any necessary conversion to microMIPS relocations
4319          and find out how many relocations there actually are.  */
4320       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4321         final_type[i] = micromips_map_reloc (reloc_type[i]);
4322
4323       /* In a compound relocation, it is the final (outermost)
4324          operator that determines the relocated field.  */
4325       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4326
4327       if (howto == NULL)
4328         {
4329           /* To reproduce this failure try assembling gas/testsuites/
4330              gas/mips/mips16-intermix.s with a mips-ecoff targeted
4331              assembler.  */
4332           as_bad (_("Unsupported MIPS relocation number %d"),
4333                   final_type[i - 1]);
4334           howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16);
4335         }
4336
4337       if (i > 1)
4338         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4339       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4340                                  bfd_get_reloc_size (howto),
4341                                  address_expr,
4342                                  howto0 && howto0->pc_relative,
4343                                  final_type[0]);
4344
4345       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4346       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
4347         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4348
4349       /* These relocations can have an addend that won't fit in
4350          4 octets for 64bit assembly.  */
4351       if (HAVE_64BIT_GPRS
4352           && ! howto->partial_inplace
4353           && (reloc_type[0] == BFD_RELOC_16
4354               || reloc_type[0] == BFD_RELOC_32
4355               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4356               || reloc_type[0] == BFD_RELOC_GPREL16
4357               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4358               || reloc_type[0] == BFD_RELOC_GPREL32
4359               || reloc_type[0] == BFD_RELOC_64
4360               || reloc_type[0] == BFD_RELOC_CTOR
4361               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4362               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4363               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4364               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4365               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4366               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4367               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4368               || hi16_reloc_p (reloc_type[0])
4369               || lo16_reloc_p (reloc_type[0])))
4370         ip->fixp[0]->fx_no_overflow = 1;
4371
4372       if (mips_relax.sequence)
4373         {
4374           if (mips_relax.first_fixup == 0)
4375             mips_relax.first_fixup = ip->fixp[0];
4376         }
4377       else if (reloc_needs_lo_p (*reloc_type))
4378         {
4379           struct mips_hi_fixup *hi_fixup;
4380
4381           /* Reuse the last entry if it already has a matching %lo.  */
4382           hi_fixup = mips_hi_fixup_list;
4383           if (hi_fixup == 0
4384               || !fixup_has_matching_lo_p (hi_fixup->fixp))
4385             {
4386               hi_fixup = ((struct mips_hi_fixup *)
4387                           xmalloc (sizeof (struct mips_hi_fixup)));
4388               hi_fixup->next = mips_hi_fixup_list;
4389               mips_hi_fixup_list = hi_fixup;
4390             }
4391           hi_fixup->fixp = ip->fixp[0];
4392           hi_fixup->seg = now_seg;
4393         }
4394
4395       /* Add fixups for the second and third relocations, if given.
4396          Note that the ABI allows the second relocation to be
4397          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
4398          moment we only use RSS_UNDEF, but we could add support
4399          for the others if it ever becomes necessary.  */
4400       for (i = 1; i < 3; i++)
4401         if (reloc_type[i] != BFD_RELOC_UNUSED)
4402           {
4403             ip->fixp[i] = fix_new (ip->frag, ip->where,
4404                                    ip->fixp[0]->fx_size, NULL, 0,
4405                                    FALSE, final_type[i]);
4406
4407             /* Use fx_tcbit to mark compound relocs.  */
4408             ip->fixp[0]->fx_tcbit = 1;
4409             ip->fixp[i]->fx_tcbit = 1;
4410           }
4411     }
4412   install_insn (ip);
4413
4414   /* Update the register mask information.  */
4415   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
4416   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
4417
4418   switch (method)
4419     {
4420     case APPEND_ADD:
4421       insert_into_history (0, 1, ip);
4422       break;
4423
4424     case APPEND_ADD_WITH_NOP:
4425       insert_into_history (0, 1, ip);
4426       if (mips_opts.micromips
4427           && (pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4428         {
4429           add_fixed_insn (&micromips_nop32_insn);
4430           insert_into_history (0, 1, &micromips_nop32_insn);
4431           if (mips_relax.sequence)
4432             mips_relax.sizes[mips_relax.sequence - 1] += 4;
4433         }
4434       else
4435         {
4436           emit_nop ();
4437           if (mips_relax.sequence)
4438             mips_relax.sizes[mips_relax.sequence - 1] += NOP_INSN_SIZE;
4439         }
4440       break;
4441
4442     case APPEND_ADD_COMPACT:
4443       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
4444       gas_assert (mips_opts.mips16);
4445       ip->insn_opcode |= 0x0080;
4446       find_altered_mips16_opcode (ip);
4447       install_insn (ip);
4448       insert_into_history (0, 1, ip);
4449       break;
4450
4451     case APPEND_SWAP:
4452       {
4453         struct mips_cl_insn delay = history[0];
4454         if (mips_opts.mips16)
4455           {
4456             know (delay.frag == ip->frag);
4457             move_insn (ip, delay.frag, delay.where);
4458             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
4459           }
4460         else if (mips_opts.micromips)
4461           {
4462             /* We don't reorder for micromips.  */
4463             abort ();
4464           }
4465         else if (relaxed_branch)
4466           {
4467             /* Add the delay slot instruction to the end of the
4468                current frag and shrink the fixed part of the
4469                original frag.  If the branch occupies the tail of
4470                the latter, move it backwards to cover the gap.  */
4471             delay.frag->fr_fix -= 4;
4472             if (delay.frag == ip->frag)
4473               move_insn (ip, ip->frag, ip->where - 4);
4474             add_fixed_insn (&delay);
4475           }
4476         else
4477           {
4478             move_insn (&delay, ip->frag, ip->where);
4479             move_insn (ip, history[0].frag, history[0].where);
4480           }
4481         history[0] = *ip;
4482         delay.fixed_p = 1;
4483         insert_into_history (0, 1, &delay);
4484       }
4485       break;
4486     }
4487
4488   /* If we have just completed an unconditional branch, clear the history.  */
4489   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
4490       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
4491     mips_no_prev_insn ();
4492
4493   /* We need to emit a label at the end of branch-likely macros.  */
4494   if (emit_branch_likely_macro)
4495     {
4496       emit_branch_likely_macro = FALSE;
4497       micromips_add_label ();
4498     }
4499
4500   /* We just output an insn, so the next one doesn't have a label.  */
4501   mips_clear_insn_labels ();
4502 }
4503
4504 /* Forget that there was any previous instruction or label.  */
4505
4506 static void
4507 mips_no_prev_insn (void)
4508 {
4509   prev_nop_frag = NULL;
4510   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
4511   mips_clear_insn_labels ();
4512 }
4513
4514 /* This function must be called before we emit something other than
4515    instructions.  It is like mips_no_prev_insn except that it inserts
4516    any NOPS that might be needed by previous instructions.  */
4517
4518 void
4519 mips_emit_delays (void)
4520 {
4521   if (! mips_opts.noreorder)
4522     {
4523       int nops = nops_for_insn (0, history, NULL);
4524       if (nops > 0)
4525         {
4526           while (nops-- > 0)
4527             add_fixed_insn (NOP_INSN);
4528           mips_move_labels ();
4529         }
4530     }
4531   mips_no_prev_insn ();
4532 }
4533
4534 /* Start a (possibly nested) noreorder block.  */
4535
4536 static void
4537 start_noreorder (void)
4538 {
4539   if (mips_opts.noreorder == 0)
4540     {
4541       unsigned int i;
4542       int nops;
4543
4544       /* None of the instructions before the .set noreorder can be moved.  */
4545       for (i = 0; i < ARRAY_SIZE (history); i++)
4546         history[i].fixed_p = 1;
4547
4548       /* Insert any nops that might be needed between the .set noreorder
4549          block and the previous instructions.  We will later remove any
4550          nops that turn out not to be needed.  */
4551       nops = nops_for_insn (0, history, NULL);
4552       if (nops > 0)
4553         {
4554           if (mips_optimize != 0)
4555             {
4556               /* Record the frag which holds the nop instructions, so
4557                  that we can remove them if we don't need them.  */
4558               frag_grow (nops * NOP_INSN_SIZE);
4559               prev_nop_frag = frag_now;
4560               prev_nop_frag_holds = nops;
4561               prev_nop_frag_required = 0;
4562               prev_nop_frag_since = 0;
4563             }
4564
4565           for (; nops > 0; --nops)
4566             add_fixed_insn (NOP_INSN);
4567
4568           /* Move on to a new frag, so that it is safe to simply
4569              decrease the size of prev_nop_frag.  */
4570           frag_wane (frag_now);
4571           frag_new (0);
4572           mips_move_labels ();
4573         }
4574       mips_mark_labels ();
4575       mips_clear_insn_labels ();
4576     }
4577   mips_opts.noreorder++;
4578   mips_any_noreorder = 1;
4579 }
4580
4581 /* End a nested noreorder block.  */
4582
4583 static void
4584 end_noreorder (void)
4585 {
4586
4587   mips_opts.noreorder--;
4588   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
4589     {
4590       /* Commit to inserting prev_nop_frag_required nops and go back to
4591          handling nop insertion the .set reorder way.  */
4592       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
4593                                 * NOP_INSN_SIZE);
4594       insert_into_history (prev_nop_frag_since,
4595                            prev_nop_frag_required, NOP_INSN);
4596       prev_nop_frag = NULL;
4597     }
4598 }
4599
4600 /* Set up global variables for the start of a new macro.  */
4601
4602 static void
4603 macro_start (void)
4604 {
4605   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
4606   memset (&mips_macro_warning.first_insn_sizes, 0,
4607           sizeof (mips_macro_warning.first_insn_sizes));
4608   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
4609   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
4610                                      && delayed_branch_p (&history[0]));
4611   switch (history[0].insn_mo->pinfo2
4612           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
4613     {
4614     case INSN2_BRANCH_DELAY_32BIT:
4615       mips_macro_warning.delay_slot_length = 4;
4616       break;
4617     case INSN2_BRANCH_DELAY_16BIT:
4618       mips_macro_warning.delay_slot_length = 2;
4619       break;
4620     default:
4621       mips_macro_warning.delay_slot_length = 0;
4622       break;
4623     }
4624   mips_macro_warning.first_frag = NULL;
4625 }
4626
4627 /* Given that a macro is longer than one instruction or of the wrong size,
4628    return the appropriate warning for it.  Return null if no warning is
4629    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
4630    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
4631    and RELAX_NOMACRO.  */
4632
4633 static const char *
4634 macro_warning (relax_substateT subtype)
4635 {
4636   if (subtype & RELAX_DELAY_SLOT)
4637     return _("Macro instruction expanded into multiple instructions"
4638              " in a branch delay slot");
4639   else if (subtype & RELAX_NOMACRO)
4640     return _("Macro instruction expanded into multiple instructions");
4641   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
4642                       | RELAX_DELAY_SLOT_SIZE_SECOND))
4643     return ((subtype & RELAX_DELAY_SLOT_16BIT)
4644             ? _("Macro instruction expanded into a wrong size instruction"
4645                 " in a 16-bit branch delay slot")
4646             : _("Macro instruction expanded into a wrong size instruction"
4647                 " in a 32-bit branch delay slot"));
4648   else
4649     return 0;
4650 }
4651
4652 /* Finish up a macro.  Emit warnings as appropriate.  */
4653
4654 static void
4655 macro_end (void)
4656 {
4657   /* Relaxation warning flags.  */
4658   relax_substateT subtype = 0;
4659
4660   /* Check delay slot size requirements.  */
4661   if (mips_macro_warning.delay_slot_length == 2)
4662     subtype |= RELAX_DELAY_SLOT_16BIT;
4663   if (mips_macro_warning.delay_slot_length != 0)
4664     {
4665       if (mips_macro_warning.delay_slot_length
4666           != mips_macro_warning.first_insn_sizes[0])
4667         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
4668       if (mips_macro_warning.delay_slot_length
4669           != mips_macro_warning.first_insn_sizes[1])
4670         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
4671     }
4672
4673   /* Check instruction count requirements.  */
4674   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
4675     {
4676       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
4677         subtype |= RELAX_SECOND_LONGER;
4678       if (mips_opts.warn_about_macros)
4679         subtype |= RELAX_NOMACRO;
4680       if (mips_macro_warning.delay_slot_p)
4681         subtype |= RELAX_DELAY_SLOT;
4682     }
4683
4684   /* If both alternatives fail to fill a delay slot correctly,
4685      emit the warning now.  */
4686   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
4687       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
4688     {
4689       relax_substateT s;
4690       const char *msg;
4691
4692       s = subtype & (RELAX_DELAY_SLOT_16BIT
4693                      | RELAX_DELAY_SLOT_SIZE_FIRST
4694                      | RELAX_DELAY_SLOT_SIZE_SECOND);
4695       msg = macro_warning (s);
4696       if (msg != NULL)
4697         as_warn ("%s", msg);
4698       subtype &= ~s;
4699     }
4700
4701   /* If both implementations are longer than 1 instruction, then emit the
4702      warning now.  */
4703   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
4704     {
4705       relax_substateT s;
4706       const char *msg;
4707
4708       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
4709       msg = macro_warning (s);
4710       if (msg != NULL)
4711         as_warn ("%s", msg);
4712       subtype &= ~s;
4713     }
4714
4715   /* If any flags still set, then one implementation might need a warning
4716      and the other either will need one of a different kind or none at all.
4717      Pass any remaining flags over to relaxation.  */
4718   if (mips_macro_warning.first_frag != NULL)
4719     mips_macro_warning.first_frag->fr_subtype |= subtype;
4720 }
4721
4722 /* Instruction operand formats used in macros that vary between
4723    standard MIPS and microMIPS code.  */
4724
4725 static const char * const brk_fmt[2] = { "c", "mF" };
4726 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
4727 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
4728 static const char * const lui_fmt[2] = { "t,u", "s,u" };
4729 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
4730 static const char * const mfhl_fmt[2] = { "d", "mj" };
4731 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
4732 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
4733
4734 #define BRK_FMT (brk_fmt[mips_opts.micromips])
4735 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
4736 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
4737 #define LUI_FMT (lui_fmt[mips_opts.micromips])
4738 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
4739 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips])
4740 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
4741 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
4742
4743 /* Read a macro's relocation codes from *ARGS and store them in *R.
4744    The first argument in *ARGS will be either the code for a single
4745    relocation or -1 followed by the three codes that make up a
4746    composite relocation.  */
4747
4748 static void
4749 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
4750 {
4751   int i, next;
4752
4753   next = va_arg (*args, int);
4754   if (next >= 0)
4755     r[0] = (bfd_reloc_code_real_type) next;
4756   else
4757     for (i = 0; i < 3; i++)
4758       r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
4759 }
4760
4761 /* Build an instruction created by a macro expansion.  This is passed
4762    a pointer to the count of instructions created so far, an
4763    expression, the name of the instruction to build, an operand format
4764    string, and corresponding arguments.  */
4765
4766 static void
4767 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
4768 {
4769   const struct mips_opcode *mo = NULL;
4770   bfd_reloc_code_real_type r[3];
4771   const struct mips_opcode *amo;
4772   struct hash_control *hash;
4773   struct mips_cl_insn insn;
4774   va_list args;
4775
4776   va_start (args, fmt);
4777
4778   if (mips_opts.mips16)
4779     {
4780       mips16_macro_build (ep, name, fmt, &args);
4781       va_end (args);
4782       return;
4783     }
4784
4785   r[0] = BFD_RELOC_UNUSED;
4786   r[1] = BFD_RELOC_UNUSED;
4787   r[2] = BFD_RELOC_UNUSED;
4788   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
4789   amo = (struct mips_opcode *) hash_find (hash, name);
4790   gas_assert (amo);
4791   gas_assert (strcmp (name, amo->name) == 0);
4792
4793   do
4794     {
4795       /* Search until we get a match for NAME.  It is assumed here that
4796          macros will never generate MDMX, MIPS-3D, or MT instructions.
4797          We try to match an instruction that fulfils the branch delay
4798          slot instruction length requirement (if any) of the previous
4799          instruction.  While doing this we record the first instruction
4800          seen that matches all the other conditions and use it anyway
4801          if the requirement cannot be met; we will issue an appropriate
4802          warning later on.  */
4803       if (strcmp (fmt, amo->args) == 0
4804           && amo->pinfo != INSN_MACRO
4805           && is_opcode_valid (amo)
4806           && is_size_valid (amo))
4807         {
4808           if (is_delay_slot_valid (amo))
4809             {
4810               mo = amo;
4811               break;
4812             }
4813           else if (!mo)
4814             mo = amo;
4815         }
4816
4817       ++amo;
4818       gas_assert (amo->name);
4819     }
4820   while (strcmp (name, amo->name) == 0);
4821
4822   gas_assert (mo);
4823   create_insn (&insn, mo);
4824   for (;;)
4825     {
4826       switch (*fmt++)
4827         {
4828         case '\0':
4829           break;
4830
4831         case ',':
4832         case '(':
4833         case ')':
4834           continue;
4835
4836         case '+':
4837           switch (*fmt++)
4838             {
4839             case 'A':
4840             case 'E':
4841               INSERT_OPERAND (mips_opts.micromips,
4842                               EXTLSB, insn, va_arg (args, int));
4843               continue;
4844
4845             case 'B':
4846             case 'F':
4847               /* Note that in the macro case, these arguments are already
4848                  in MSB form.  (When handling the instruction in the
4849                  non-macro case, these arguments are sizes from which
4850                  MSB values must be calculated.)  */
4851               INSERT_OPERAND (mips_opts.micromips,
4852                               INSMSB, insn, va_arg (args, int));
4853               continue;
4854
4855             case 'C':
4856             case 'G':
4857             case 'H':
4858               /* Note that in the macro case, these arguments are already
4859                  in MSBD form.  (When handling the instruction in the
4860                  non-macro case, these arguments are sizes from which
4861                  MSBD values must be calculated.)  */
4862               INSERT_OPERAND (mips_opts.micromips,
4863                               EXTMSBD, insn, va_arg (args, int));
4864               continue;
4865
4866             case 'Q':
4867               gas_assert (!mips_opts.micromips);
4868               INSERT_OPERAND (0, SEQI, insn, va_arg (args, int));
4869               continue;
4870
4871             default:
4872               internalError ();
4873             }
4874           continue;
4875
4876         case '2':
4877           gas_assert (!mips_opts.micromips);
4878           INSERT_OPERAND (0, BP, insn, va_arg (args, int));
4879           continue;
4880
4881         case 'n':
4882           gas_assert (mips_opts.micromips);
4883         case 't':
4884         case 'w':
4885         case 'E':
4886           INSERT_OPERAND (mips_opts.micromips, RT, insn, va_arg (args, int));
4887           continue;
4888
4889         case 'c':
4890           gas_assert (!mips_opts.micromips);
4891           INSERT_OPERAND (0, CODE, insn, va_arg (args, int));
4892           continue;
4893
4894         case 'W':
4895           gas_assert (!mips_opts.micromips);
4896         case 'T':
4897           INSERT_OPERAND (mips_opts.micromips, FT, insn, va_arg (args, int));
4898           continue;
4899
4900         case 'G':
4901           if (mips_opts.micromips)
4902             INSERT_OPERAND (1, RS, insn, va_arg (args, int));
4903           else
4904             INSERT_OPERAND (0, RD, insn, va_arg (args, int));
4905           continue;
4906
4907         case 'K':
4908           gas_assert (!mips_opts.micromips);
4909         case 'd':
4910           INSERT_OPERAND (mips_opts.micromips, RD, insn, va_arg (args, int));
4911           continue;
4912
4913         case 'U':
4914           gas_assert (!mips_opts.micromips);
4915           {
4916             int tmp = va_arg (args, int);
4917
4918             INSERT_OPERAND (0, RT, insn, tmp);
4919             INSERT_OPERAND (0, RD, insn, tmp);
4920           }
4921           continue;
4922
4923         case 'V':
4924         case 'S':
4925           gas_assert (!mips_opts.micromips);
4926           INSERT_OPERAND (0, FS, insn, va_arg (args, int));
4927           continue;
4928
4929         case 'z':
4930           continue;
4931
4932         case '<':
4933           INSERT_OPERAND (mips_opts.micromips,
4934                           SHAMT, insn, va_arg (args, int));
4935           continue;
4936
4937         case 'D':
4938           gas_assert (!mips_opts.micromips);
4939           INSERT_OPERAND (0, FD, insn, va_arg (args, int));
4940           continue;
4941
4942         case 'B':
4943           gas_assert (!mips_opts.micromips);
4944           INSERT_OPERAND (0, CODE20, insn, va_arg (args, int));
4945           continue;
4946
4947         case 'J':
4948           gas_assert (!mips_opts.micromips);
4949           INSERT_OPERAND (0, CODE19, insn, va_arg (args, int));
4950           continue;
4951
4952         case 'q':
4953           gas_assert (!mips_opts.micromips);
4954           INSERT_OPERAND (0, CODE2, insn, va_arg (args, int));
4955           continue;
4956
4957         case 'b':
4958         case 's':
4959         case 'r':
4960         case 'v':
4961           INSERT_OPERAND (mips_opts.micromips, RS, insn, va_arg (args, int));
4962           continue;
4963
4964         case 'i':
4965         case 'j':
4966           macro_read_relocs (&args, r);
4967           gas_assert (*r == BFD_RELOC_GPREL16
4968                       || *r == BFD_RELOC_MIPS_HIGHER
4969                       || *r == BFD_RELOC_HI16_S
4970                       || *r == BFD_RELOC_LO16
4971                       || *r == BFD_RELOC_MIPS_GOT_OFST);
4972           continue;
4973
4974         case 'o':
4975           macro_read_relocs (&args, r);
4976           continue;
4977
4978         case 'u':
4979           macro_read_relocs (&args, r);
4980           gas_assert (ep != NULL
4981                       && (ep->X_op == O_constant
4982                           || (ep->X_op == O_symbol
4983                               && (*r == BFD_RELOC_MIPS_HIGHEST
4984                                   || *r == BFD_RELOC_HI16_S
4985                                   || *r == BFD_RELOC_HI16
4986                                   || *r == BFD_RELOC_GPREL16
4987                                   || *r == BFD_RELOC_MIPS_GOT_HI16
4988                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
4989           continue;
4990
4991         case 'p':
4992           gas_assert (ep != NULL);
4993
4994           /*
4995            * This allows macro() to pass an immediate expression for
4996            * creating short branches without creating a symbol.
4997            *
4998            * We don't allow branch relaxation for these branches, as
4999            * they should only appear in ".set nomacro" anyway.
5000            */
5001           if (ep->X_op == O_constant)
5002             {
5003               /* For microMIPS we always use relocations for branches.
5004                  So we should not resolve immediate values.  */
5005               gas_assert (!mips_opts.micromips);
5006
5007               if ((ep->X_add_number & 3) != 0)
5008                 as_bad (_("branch to misaligned address (0x%lx)"),
5009                         (unsigned long) ep->X_add_number);
5010               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5011                 as_bad (_("branch address range overflow (0x%lx)"),
5012                         (unsigned long) ep->X_add_number);
5013               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5014               ep = NULL;
5015             }
5016           else
5017             *r = BFD_RELOC_16_PCREL_S2;
5018           continue;
5019
5020         case 'a':
5021           gas_assert (ep != NULL);
5022           *r = BFD_RELOC_MIPS_JMP;
5023           continue;
5024
5025         case 'C':
5026           gas_assert (!mips_opts.micromips);
5027           INSERT_OPERAND (0, COPZ, insn, va_arg (args, unsigned long));
5028           continue;
5029
5030         case 'k':
5031           INSERT_OPERAND (mips_opts.micromips,
5032                           CACHE, insn, va_arg (args, unsigned long));
5033           continue;
5034
5035         case '|':
5036           gas_assert (mips_opts.micromips);
5037           INSERT_OPERAND (1, TRAP, insn, va_arg (args, int));
5038           continue;
5039
5040         case '.':
5041           gas_assert (mips_opts.micromips);
5042           INSERT_OPERAND (1, OFFSET10, insn, va_arg (args, int));
5043           continue;
5044
5045         case '~':
5046           gas_assert (mips_opts.micromips);
5047           INSERT_OPERAND (1, OFFSET12, insn, va_arg (args, unsigned long));
5048           continue;
5049
5050         case 'N':
5051           gas_assert (mips_opts.micromips);
5052           INSERT_OPERAND (1, BCC, insn, va_arg (args, int));
5053           continue;
5054
5055         case 'm':       /* Opcode extension character.  */
5056           gas_assert (mips_opts.micromips);
5057           switch (*fmt++)
5058             {
5059             case 'j':
5060               INSERT_OPERAND (1, MJ, insn, va_arg (args, int));
5061               break;
5062
5063             case 'p':
5064               INSERT_OPERAND (1, MP, insn, va_arg (args, int));
5065               break;
5066
5067             case 'F':
5068               INSERT_OPERAND (1, IMMF, insn, va_arg (args, int));
5069               break;
5070
5071             default:
5072               internalError ();
5073             }
5074           continue;
5075
5076         default:
5077           internalError ();
5078         }
5079       break;
5080     }
5081   va_end (args);
5082   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5083
5084   append_insn (&insn, ep, r, TRUE);
5085 }
5086
5087 static void
5088 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5089                     va_list *args)
5090 {
5091   struct mips_opcode *mo;
5092   struct mips_cl_insn insn;
5093   bfd_reloc_code_real_type r[3]
5094     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5095
5096   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5097   gas_assert (mo);
5098   gas_assert (strcmp (name, mo->name) == 0);
5099
5100   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5101     {
5102       ++mo;
5103       gas_assert (mo->name);
5104       gas_assert (strcmp (name, mo->name) == 0);
5105     }
5106
5107   create_insn (&insn, mo);
5108   for (;;)
5109     {
5110       int c;
5111
5112       c = *fmt++;
5113       switch (c)
5114         {
5115         case '\0':
5116           break;
5117
5118         case ',':
5119         case '(':
5120         case ')':
5121           continue;
5122
5123         case 'y':
5124         case 'w':
5125           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
5126           continue;
5127
5128         case 'x':
5129         case 'v':
5130           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
5131           continue;
5132
5133         case 'z':
5134           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
5135           continue;
5136
5137         case 'Z':
5138           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
5139           continue;
5140
5141         case '0':
5142         case 'S':
5143         case 'P':
5144         case 'R':
5145           continue;
5146
5147         case 'X':
5148           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
5149           continue;
5150
5151         case 'Y':
5152           {
5153             int regno;
5154
5155             regno = va_arg (*args, int);
5156             regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
5157             MIPS16_INSERT_OPERAND (REG32R, insn, regno);
5158           }
5159           continue;
5160
5161         case '<':
5162         case '>':
5163         case '4':
5164         case '5':
5165         case 'H':
5166         case 'W':
5167         case 'D':
5168         case 'j':
5169         case '8':
5170         case 'V':
5171         case 'C':
5172         case 'U':
5173         case 'k':
5174         case 'K':
5175         case 'p':
5176         case 'q':
5177           {
5178             gas_assert (ep != NULL);
5179
5180             if (ep->X_op != O_constant)
5181               *r = (int) BFD_RELOC_UNUSED + c;
5182             else
5183               {
5184                 mips16_immed (NULL, 0, c, ep->X_add_number, FALSE, FALSE,
5185                               FALSE, &insn.insn_opcode, &insn.use_extend,
5186                               &insn.extend);
5187                 ep = NULL;
5188                 *r = BFD_RELOC_UNUSED;
5189               }
5190           }
5191           continue;
5192
5193         case '6':
5194           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
5195           continue;
5196         }
5197
5198       break;
5199     }
5200
5201   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5202
5203   append_insn (&insn, ep, r, TRUE);
5204 }
5205
5206 /*
5207  * Sign-extend 32-bit mode constants that have bit 31 set and all
5208  * higher bits unset.
5209  */
5210 static void
5211 normalize_constant_expr (expressionS *ex)
5212 {
5213   if (ex->X_op == O_constant
5214       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5215     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5216                         - 0x80000000);
5217 }
5218
5219 /*
5220  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5221  * all higher bits unset.
5222  */
5223 static void
5224 normalize_address_expr (expressionS *ex)
5225 {
5226   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5227         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5228       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5229     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5230                         - 0x80000000);
5231 }
5232
5233 /*
5234  * Generate a "jalr" instruction with a relocation hint to the called
5235  * function.  This occurs in NewABI PIC code.
5236  */
5237 static void
5238 macro_build_jalr (expressionS *ep, int cprestore)
5239 {
5240   static const bfd_reloc_code_real_type jalr_relocs[2]
5241     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5242   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5243   const char *jalr;
5244   char *f = NULL;
5245
5246   if (MIPS_JALR_HINT_P (ep))
5247     {
5248       frag_grow (8);
5249       f = frag_more (0);
5250     }
5251   if (!mips_opts.micromips)
5252     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5253   else
5254     {
5255       jalr = mips_opts.noreorder && !cprestore ? "jalr" : "jalrs";
5256       if (MIPS_JALR_HINT_P (ep))
5257         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5258       else
5259         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5260     }
5261   if (MIPS_JALR_HINT_P (ep))
5262     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5263 }
5264
5265 /*
5266  * Generate a "lui" instruction.
5267  */
5268 static void
5269 macro_build_lui (expressionS *ep, int regnum)
5270 {
5271   gas_assert (! mips_opts.mips16);
5272
5273   if (ep->X_op != O_constant)
5274     {
5275       gas_assert (ep->X_op == O_symbol);
5276       /* _gp_disp is a special case, used from s_cpload.
5277          __gnu_local_gp is used if mips_no_shared.  */
5278       gas_assert (mips_pic == NO_PIC
5279               || (! HAVE_NEWABI
5280                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5281               || (! mips_in_shared
5282                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5283                              "__gnu_local_gp") == 0));
5284     }
5285
5286   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5287 }
5288
5289 /* Generate a sequence of instructions to do a load or store from a constant
5290    offset off of a base register (breg) into/from a target register (treg),
5291    using AT if necessary.  */
5292 static void
5293 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5294                               int treg, int breg, int dbl)
5295 {
5296   gas_assert (ep->X_op == O_constant);
5297
5298   /* Sign-extending 32-bit constants makes their handling easier.  */
5299   if (!dbl)
5300     normalize_constant_expr (ep);
5301
5302   /* Right now, this routine can only handle signed 32-bit constants.  */
5303   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5304     as_warn (_("operand overflow"));
5305
5306   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5307     {
5308       /* Signed 16-bit offset will fit in the op.  Easy!  */
5309       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5310     }
5311   else
5312     {
5313       /* 32-bit offset, need multiple instructions and AT, like:
5314            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5315            addu     $tempreg,$tempreg,$breg
5316            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5317          to handle the complete offset.  */
5318       macro_build_lui (ep, AT);
5319       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5320       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5321
5322       if (!mips_opts.at)
5323         as_bad (_("Macro used $at after \".set noat\""));
5324     }
5325 }
5326
5327 /*                      set_at()
5328  * Generates code to set the $at register to true (one)
5329  * if reg is less than the immediate expression.
5330  */
5331 static void
5332 set_at (int reg, int unsignedp)
5333 {
5334   if (imm_expr.X_op == O_constant
5335       && imm_expr.X_add_number >= -0x8000
5336       && imm_expr.X_add_number < 0x8000)
5337     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5338                  AT, reg, BFD_RELOC_LO16);
5339   else
5340     {
5341       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5342       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5343     }
5344 }
5345
5346 /* Warn if an expression is not a constant.  */
5347
5348 static void
5349 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5350 {
5351   if (ex->X_op == O_big)
5352     as_bad (_("unsupported large constant"));
5353   else if (ex->X_op != O_constant)
5354     as_bad (_("Instruction %s requires absolute expression"),
5355             ip->insn_mo->name);
5356
5357   if (HAVE_32BIT_GPRS)
5358     normalize_constant_expr (ex);
5359 }
5360
5361 /* Count the leading zeroes by performing a binary chop. This is a
5362    bulky bit of source, but performance is a LOT better for the
5363    majority of values than a simple loop to count the bits:
5364        for (lcnt = 0; (lcnt < 32); lcnt++)
5365          if ((v) & (1 << (31 - lcnt)))
5366            break;
5367   However it is not code size friendly, and the gain will drop a bit
5368   on certain cached systems.
5369 */
5370 #define COUNT_TOP_ZEROES(v)             \
5371   (((v) & ~0xffff) == 0                 \
5372    ? ((v) & ~0xff) == 0                 \
5373      ? ((v) & ~0xf) == 0                \
5374        ? ((v) & ~0x3) == 0              \
5375          ? ((v) & ~0x1) == 0            \
5376            ? !(v)                       \
5377              ? 32                       \
5378              : 31                       \
5379            : 30                         \
5380          : ((v) & ~0x7) == 0            \
5381            ? 29                         \
5382            : 28                         \
5383        : ((v) & ~0x3f) == 0             \
5384          ? ((v) & ~0x1f) == 0           \
5385            ? 27                         \
5386            : 26                         \
5387          : ((v) & ~0x7f) == 0           \
5388            ? 25                         \
5389            : 24                         \
5390      : ((v) & ~0xfff) == 0              \
5391        ? ((v) & ~0x3ff) == 0            \
5392          ? ((v) & ~0x1ff) == 0          \
5393            ? 23                         \
5394            : 22                         \
5395          : ((v) & ~0x7ff) == 0          \
5396            ? 21                         \
5397            : 20                         \
5398        : ((v) & ~0x3fff) == 0           \
5399          ? ((v) & ~0x1fff) == 0         \
5400            ? 19                         \
5401            : 18                         \
5402          : ((v) & ~0x7fff) == 0         \
5403            ? 17                         \
5404            : 16                         \
5405    : ((v) & ~0xffffff) == 0             \
5406      ? ((v) & ~0xfffff) == 0            \
5407        ? ((v) & ~0x3ffff) == 0          \
5408          ? ((v) & ~0x1ffff) == 0        \
5409            ? 15                         \
5410            : 14                         \
5411          : ((v) & ~0x7ffff) == 0        \
5412            ? 13                         \
5413            : 12                         \
5414        : ((v) & ~0x3fffff) == 0         \
5415          ? ((v) & ~0x1fffff) == 0       \
5416            ? 11                         \
5417            : 10                         \
5418          : ((v) & ~0x7fffff) == 0       \
5419            ? 9                          \
5420            : 8                          \
5421      : ((v) & ~0xfffffff) == 0          \
5422        ? ((v) & ~0x3ffffff) == 0        \
5423          ? ((v) & ~0x1ffffff) == 0      \
5424            ? 7                          \
5425            : 6                          \
5426          : ((v) & ~0x7ffffff) == 0      \
5427            ? 5                          \
5428            : 4                          \
5429        : ((v) & ~0x3fffffff) == 0       \
5430          ? ((v) & ~0x1fffffff) == 0     \
5431            ? 3                          \
5432            : 2                          \
5433          : ((v) & ~0x7fffffff) == 0     \
5434            ? 1                          \
5435            : 0)
5436
5437 /*                      load_register()
5438  *  This routine generates the least number of instructions necessary to load
5439  *  an absolute expression value into a register.
5440  */
5441 static void
5442 load_register (int reg, expressionS *ep, int dbl)
5443 {
5444   int freg;
5445   expressionS hi32, lo32;
5446
5447   if (ep->X_op != O_big)
5448     {
5449       gas_assert (ep->X_op == O_constant);
5450
5451       /* Sign-extending 32-bit constants makes their handling easier.  */
5452       if (!dbl)
5453         normalize_constant_expr (ep);
5454
5455       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
5456         {
5457           /* We can handle 16 bit signed values with an addiu to
5458              $zero.  No need to ever use daddiu here, since $zero and
5459              the result are always correct in 32 bit mode.  */
5460           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5461           return;
5462         }
5463       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
5464         {
5465           /* We can handle 16 bit unsigned values with an ori to
5466              $zero.  */
5467           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5468           return;
5469         }
5470       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
5471         {
5472           /* 32 bit values require an lui.  */
5473           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5474           if ((ep->X_add_number & 0xffff) != 0)
5475             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5476           return;
5477         }
5478     }
5479
5480   /* The value is larger than 32 bits.  */
5481
5482   if (!dbl || HAVE_32BIT_GPRS)
5483     {
5484       char value[32];
5485
5486       sprintf_vma (value, ep->X_add_number);
5487       as_bad (_("Number (0x%s) larger than 32 bits"), value);
5488       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5489       return;
5490     }
5491
5492   if (ep->X_op != O_big)
5493     {
5494       hi32 = *ep;
5495       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5496       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
5497       hi32.X_add_number &= 0xffffffff;
5498       lo32 = *ep;
5499       lo32.X_add_number &= 0xffffffff;
5500     }
5501   else
5502     {
5503       gas_assert (ep->X_add_number > 2);
5504       if (ep->X_add_number == 3)
5505         generic_bignum[3] = 0;
5506       else if (ep->X_add_number > 4)
5507         as_bad (_("Number larger than 64 bits"));
5508       lo32.X_op = O_constant;
5509       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
5510       hi32.X_op = O_constant;
5511       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
5512     }
5513
5514   if (hi32.X_add_number == 0)
5515     freg = 0;
5516   else
5517     {
5518       int shift, bit;
5519       unsigned long hi, lo;
5520
5521       if (hi32.X_add_number == (offsetT) 0xffffffff)
5522         {
5523           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
5524             {
5525               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5526               return;
5527             }
5528           if (lo32.X_add_number & 0x80000000)
5529             {
5530               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5531               if (lo32.X_add_number & 0xffff)
5532                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
5533               return;
5534             }
5535         }
5536
5537       /* Check for 16bit shifted constant.  We know that hi32 is
5538          non-zero, so start the mask on the first bit of the hi32
5539          value.  */
5540       shift = 17;
5541       do
5542         {
5543           unsigned long himask, lomask;
5544
5545           if (shift < 32)
5546             {
5547               himask = 0xffff >> (32 - shift);
5548               lomask = (0xffff << shift) & 0xffffffff;
5549             }
5550           else
5551             {
5552               himask = 0xffff << (shift - 32);
5553               lomask = 0;
5554             }
5555           if ((hi32.X_add_number & ~(offsetT) himask) == 0
5556               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
5557             {
5558               expressionS tmp;
5559
5560               tmp.X_op = O_constant;
5561               if (shift < 32)
5562                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
5563                                     | (lo32.X_add_number >> shift));
5564               else
5565                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
5566               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
5567               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5568                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5569               return;
5570             }
5571           ++shift;
5572         }
5573       while (shift <= (64 - 16));
5574
5575       /* Find the bit number of the lowest one bit, and store the
5576          shifted value in hi/lo.  */
5577       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
5578       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
5579       if (lo != 0)
5580         {
5581           bit = 0;
5582           while ((lo & 1) == 0)
5583             {
5584               lo >>= 1;
5585               ++bit;
5586             }
5587           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
5588           hi >>= bit;
5589         }
5590       else
5591         {
5592           bit = 32;
5593           while ((hi & 1) == 0)
5594             {
5595               hi >>= 1;
5596               ++bit;
5597             }
5598           lo = hi;
5599           hi = 0;
5600         }
5601
5602       /* Optimize if the shifted value is a (power of 2) - 1.  */
5603       if ((hi == 0 && ((lo + 1) & lo) == 0)
5604           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
5605         {
5606           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
5607           if (shift != 0)
5608             {
5609               expressionS tmp;
5610
5611               /* This instruction will set the register to be all
5612                  ones.  */
5613               tmp.X_op = O_constant;
5614               tmp.X_add_number = (offsetT) -1;
5615               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
5616               if (bit != 0)
5617                 {
5618                   bit += shift;
5619                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
5620                                reg, reg, (bit >= 32) ? bit - 32 : bit);
5621                 }
5622               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
5623                            reg, reg, (shift >= 32) ? shift - 32 : shift);
5624               return;
5625             }
5626         }
5627
5628       /* Sign extend hi32 before calling load_register, because we can
5629          generally get better code when we load a sign extended value.  */
5630       if ((hi32.X_add_number & 0x80000000) != 0)
5631         hi32.X_add_number |= ~(offsetT) 0xffffffff;
5632       load_register (reg, &hi32, 0);
5633       freg = reg;
5634     }
5635   if ((lo32.X_add_number & 0xffff0000) == 0)
5636     {
5637       if (freg != 0)
5638         {
5639           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
5640           freg = reg;
5641         }
5642     }
5643   else
5644     {
5645       expressionS mid16;
5646
5647       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
5648         {
5649           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
5650           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
5651           return;
5652         }
5653
5654       if (freg != 0)
5655         {
5656           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
5657           freg = reg;
5658         }
5659       mid16 = lo32;
5660       mid16.X_add_number >>= 16;
5661       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5662       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5663       freg = reg;
5664     }
5665   if ((lo32.X_add_number & 0xffff) != 0)
5666     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
5667 }
5668
5669 static inline void
5670 load_delay_nop (void)
5671 {
5672   if (!gpr_interlocks)
5673     macro_build (NULL, "nop", "");
5674 }
5675
5676 /* Load an address into a register.  */
5677
5678 static void
5679 load_address (int reg, expressionS *ep, int *used_at)
5680 {
5681   if (ep->X_op != O_constant
5682       && ep->X_op != O_symbol)
5683     {
5684       as_bad (_("expression too complex"));
5685       ep->X_op = O_constant;
5686     }
5687
5688   if (ep->X_op == O_constant)
5689     {
5690       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
5691       return;
5692     }
5693
5694   if (mips_pic == NO_PIC)
5695     {
5696       /* If this is a reference to a GP relative symbol, we want
5697            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
5698          Otherwise we want
5699            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
5700            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5701          If we have an addend, we always use the latter form.
5702
5703          With 64bit address space and a usable $at we want
5704            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5705            lui          $at,<sym>               (BFD_RELOC_HI16_S)
5706            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5707            daddiu       $at,<sym>               (BFD_RELOC_LO16)
5708            dsll32       $reg,0
5709            daddu        $reg,$reg,$at
5710
5711          If $at is already in use, we use a path which is suboptimal
5712          on superscalar processors.
5713            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
5714            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
5715            dsll         $reg,16
5716            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
5717            dsll         $reg,16
5718            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
5719
5720          For GP relative symbols in 64bit address space we can use
5721          the same sequence as in 32bit address space.  */
5722       if (HAVE_64BIT_SYMBOLS)
5723         {
5724           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5725               && !nopic_need_relax (ep->X_add_symbol, 1))
5726             {
5727               relax_start (ep->X_add_symbol);
5728               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5729                            mips_gp_register, BFD_RELOC_GPREL16);
5730               relax_switch ();
5731             }
5732
5733           if (*used_at == 0 && mips_opts.at)
5734             {
5735               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5736               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
5737               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5738                            BFD_RELOC_MIPS_HIGHER);
5739               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
5740               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
5741               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
5742               *used_at = 1;
5743             }
5744           else
5745             {
5746               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
5747               macro_build (ep, "daddiu", "t,r,j", reg, reg,
5748                            BFD_RELOC_MIPS_HIGHER);
5749               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5750               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
5751               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
5752               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
5753             }
5754
5755           if (mips_relax.sequence)
5756             relax_end ();
5757         }
5758       else
5759         {
5760           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
5761               && !nopic_need_relax (ep->X_add_symbol, 1))
5762             {
5763               relax_start (ep->X_add_symbol);
5764               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
5765                            mips_gp_register, BFD_RELOC_GPREL16);
5766               relax_switch ();
5767             }
5768           macro_build_lui (ep, reg);
5769           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
5770                        reg, reg, BFD_RELOC_LO16);
5771           if (mips_relax.sequence)
5772             relax_end ();
5773         }
5774     }
5775   else if (!mips_big_got)
5776     {
5777       expressionS ex;
5778
5779       /* If this is a reference to an external symbol, we want
5780            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5781          Otherwise we want
5782            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5783            nop
5784            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5785          If there is a constant, it must be added in after.
5786
5787          If we have NewABI, we want
5788            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
5789          unless we're referencing a global symbol with a non-zero
5790          offset, in which case cst must be added separately.  */
5791       if (HAVE_NEWABI)
5792         {
5793           if (ep->X_add_number)
5794             {
5795               ex.X_add_number = ep->X_add_number;
5796               ep->X_add_number = 0;
5797               relax_start (ep->X_add_symbol);
5798               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5799                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5800               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5801                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5802               ex.X_op = O_constant;
5803               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5804                            reg, reg, BFD_RELOC_LO16);
5805               ep->X_add_number = ex.X_add_number;
5806               relax_switch ();
5807             }
5808           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5809                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
5810           if (mips_relax.sequence)
5811             relax_end ();
5812         }
5813       else
5814         {
5815           ex.X_add_number = ep->X_add_number;
5816           ep->X_add_number = 0;
5817           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5818                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5819           load_delay_nop ();
5820           relax_start (ep->X_add_symbol);
5821           relax_switch ();
5822           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5823                        BFD_RELOC_LO16);
5824           relax_end ();
5825
5826           if (ex.X_add_number != 0)
5827             {
5828               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5829                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5830               ex.X_op = O_constant;
5831               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
5832                            reg, reg, BFD_RELOC_LO16);
5833             }
5834         }
5835     }
5836   else if (mips_big_got)
5837     {
5838       expressionS ex;
5839
5840       /* This is the large GOT case.  If this is a reference to an
5841          external symbol, we want
5842            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
5843            addu         $reg,$reg,$gp
5844            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
5845
5846          Otherwise, for a reference to a local symbol in old ABI, we want
5847            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
5848            nop
5849            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
5850          If there is a constant, it must be added in after.
5851
5852          In the NewABI, for local symbols, with or without offsets, we want:
5853            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
5854            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
5855       */
5856       if (HAVE_NEWABI)
5857         {
5858           ex.X_add_number = ep->X_add_number;
5859           ep->X_add_number = 0;
5860           relax_start (ep->X_add_symbol);
5861           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5862           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5863                        reg, reg, mips_gp_register);
5864           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5865                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5866           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5867             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5868           else if (ex.X_add_number)
5869             {
5870               ex.X_op = O_constant;
5871               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5872                            BFD_RELOC_LO16);
5873             }
5874
5875           ep->X_add_number = ex.X_add_number;
5876           relax_switch ();
5877           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5878                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
5879           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5880                        BFD_RELOC_MIPS_GOT_OFST);
5881           relax_end ();
5882         }
5883       else
5884         {
5885           ex.X_add_number = ep->X_add_number;
5886           ep->X_add_number = 0;
5887           relax_start (ep->X_add_symbol);
5888           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
5889           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
5890                        reg, reg, mips_gp_register);
5891           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
5892                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
5893           relax_switch ();
5894           if (reg_needs_delay (mips_gp_register))
5895             {
5896               /* We need a nop before loading from $gp.  This special
5897                  check is required because the lui which starts the main
5898                  instruction stream does not refer to $gp, and so will not
5899                  insert the nop which may be required.  */
5900               macro_build (NULL, "nop", "");
5901             }
5902           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
5903                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
5904           load_delay_nop ();
5905           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5906                        BFD_RELOC_LO16);
5907           relax_end ();
5908
5909           if (ex.X_add_number != 0)
5910             {
5911               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
5912                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
5913               ex.X_op = O_constant;
5914               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
5915                            BFD_RELOC_LO16);
5916             }
5917         }
5918     }
5919   else
5920     abort ();
5921
5922   if (!mips_opts.at && *used_at == 1)
5923     as_bad (_("Macro used $at after \".set noat\""));
5924 }
5925
5926 /* Move the contents of register SOURCE into register DEST.  */
5927
5928 static void
5929 move_register (int dest, int source)
5930 {
5931   /* Prefer to use a 16-bit microMIPS instruction unless the previous
5932      instruction specifically requires a 32-bit one.  */
5933   if (mips_opts.micromips
5934       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5935     macro_build (NULL, "move", "mp,mj", dest, source );
5936   else
5937     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
5938                  dest, source, 0);
5939 }
5940
5941 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
5942    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
5943    The two alternatives are:
5944
5945    Global symbol                Local sybmol
5946    -------------                ------------
5947    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
5948    ...                          ...
5949    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
5950
5951    load_got_offset emits the first instruction and add_got_offset
5952    emits the second for a 16-bit offset or add_got_offset_hilo emits
5953    a sequence to add a 32-bit offset using a scratch register.  */
5954
5955 static void
5956 load_got_offset (int dest, expressionS *local)
5957 {
5958   expressionS global;
5959
5960   global = *local;
5961   global.X_add_number = 0;
5962
5963   relax_start (local->X_add_symbol);
5964   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5965                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5966   relax_switch ();
5967   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
5968                BFD_RELOC_MIPS_GOT16, mips_gp_register);
5969   relax_end ();
5970 }
5971
5972 static void
5973 add_got_offset (int dest, expressionS *local)
5974 {
5975   expressionS global;
5976
5977   global.X_op = O_constant;
5978   global.X_op_symbol = NULL;
5979   global.X_add_symbol = NULL;
5980   global.X_add_number = local->X_add_number;
5981
5982   relax_start (local->X_add_symbol);
5983   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
5984                dest, dest, BFD_RELOC_LO16);
5985   relax_switch ();
5986   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
5987   relax_end ();
5988 }
5989
5990 static void
5991 add_got_offset_hilo (int dest, expressionS *local, int tmp)
5992 {
5993   expressionS global;
5994   int hold_mips_optimize;
5995
5996   global.X_op = O_constant;
5997   global.X_op_symbol = NULL;
5998   global.X_add_symbol = NULL;
5999   global.X_add_number = local->X_add_number;
6000
6001   relax_start (local->X_add_symbol);
6002   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6003   relax_switch ();
6004   /* Set mips_optimize around the lui instruction to avoid
6005      inserting an unnecessary nop after the lw.  */
6006   hold_mips_optimize = mips_optimize;
6007   mips_optimize = 2;
6008   macro_build_lui (&global, tmp);
6009   mips_optimize = hold_mips_optimize;
6010   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6011   relax_end ();
6012
6013   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6014 }
6015
6016 /* Emit a sequence of instructions to emulate a branch likely operation.
6017    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6018    is its complementing branch with the original condition negated.
6019    CALL is set if the original branch specified the link operation.
6020    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6021
6022    Code like this is produced in the noreorder mode:
6023
6024         BRNEG   <args>, 1f
6025          nop
6026         b       <sym>
6027          delay slot (executed only if branch taken)
6028     1:
6029
6030    or, if CALL is set:
6031
6032         BRNEG   <args>, 1f
6033          nop
6034         bal     <sym>
6035          delay slot (executed only if branch taken)
6036     1:
6037
6038    In the reorder mode the delay slot would be filled with a nop anyway,
6039    so code produced is simply:
6040
6041         BR      <args>, <sym>
6042          nop
6043
6044    This function is used when producing code for the microMIPS ASE that
6045    does not implement branch likely instructions in hardware.  */
6046
6047 static void
6048 macro_build_branch_likely (const char *br, const char *brneg,
6049                            int call, expressionS *ep, const char *fmt,
6050                            unsigned int sreg, unsigned int treg)
6051 {
6052   int noreorder = mips_opts.noreorder;
6053   expressionS expr1;
6054
6055   gas_assert (mips_opts.micromips);
6056   start_noreorder ();
6057   if (noreorder)
6058     {
6059       micromips_label_expr (&expr1);
6060       macro_build (&expr1, brneg, fmt, sreg, treg);
6061       macro_build (NULL, "nop", "");
6062       macro_build (ep, call ? "bal" : "b", "p");
6063
6064       /* Set to true so that append_insn adds a label.  */
6065       emit_branch_likely_macro = TRUE;
6066     }
6067   else
6068     {
6069       macro_build (ep, br, fmt, sreg, treg);
6070       macro_build (NULL, "nop", "");
6071     }
6072   end_noreorder ();
6073 }
6074
6075 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6076    the condition code tested.  EP specifies the branch target.  */
6077
6078 static void
6079 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6080 {
6081   const int call = 0;
6082   const char *brneg;
6083   const char *br;
6084
6085   switch (type)
6086     {
6087     case M_BC1FL:
6088       br = "bc1f";
6089       brneg = "bc1t";
6090       break;
6091     case M_BC1TL:
6092       br = "bc1t";
6093       brneg = "bc1f";
6094       break;
6095     case M_BC2FL:
6096       br = "bc2f";
6097       brneg = "bc2t";
6098       break;
6099     case M_BC2TL:
6100       br = "bc2t";
6101       brneg = "bc2f";
6102       break;
6103     default:
6104       abort ();
6105     }
6106   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6107 }
6108
6109 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6110    the register tested.  EP specifies the branch target.  */
6111
6112 static void
6113 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6114 {
6115   const char *brneg = NULL;
6116   const char *br;
6117   int call = 0;
6118
6119   switch (type)
6120     {
6121     case M_BGEZ:
6122       br = "bgez";
6123       break;
6124     case M_BGEZL:
6125       br = mips_opts.micromips ? "bgez" : "bgezl";
6126       brneg = "bltz";
6127       break;
6128     case M_BGEZALL:
6129       gas_assert (mips_opts.micromips);
6130       br = "bgezals";
6131       brneg = "bltz";
6132       call = 1;
6133       break;
6134     case M_BGTZ:
6135       br = "bgtz";
6136       break;
6137     case M_BGTZL:
6138       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6139       brneg = "blez";
6140       break;
6141     case M_BLEZ:
6142       br = "blez";
6143       break;
6144     case M_BLEZL:
6145       br = mips_opts.micromips ? "blez" : "blezl";
6146       brneg = "bgtz";
6147       break;
6148     case M_BLTZ:
6149       br = "bltz";
6150       break;
6151     case M_BLTZL:
6152       br = mips_opts.micromips ? "bltz" : "bltzl";
6153       brneg = "bgez";
6154       break;
6155     case M_BLTZALL:
6156       gas_assert (mips_opts.micromips);
6157       br = "bltzals";
6158       brneg = "bgez";
6159       call = 1;
6160       break;
6161     default:
6162       abort ();
6163     }
6164   if (mips_opts.micromips && brneg)
6165     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6166   else
6167     macro_build (ep, br, "s,p", sreg);
6168 }
6169
6170 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6171    TREG as the registers tested.  EP specifies the branch target.  */
6172
6173 static void
6174 macro_build_branch_rsrt (int type, expressionS *ep,
6175                          unsigned int sreg, unsigned int treg)
6176 {
6177   const char *brneg = NULL;
6178   const int call = 0;
6179   const char *br;
6180
6181   switch (type)
6182     {
6183     case M_BEQ:
6184     case M_BEQ_I:
6185       br = "beq";
6186       break;
6187     case M_BEQL:
6188     case M_BEQL_I:
6189       br = mips_opts.micromips ? "beq" : "beql";
6190       brneg = "bne";
6191       break;
6192     case M_BNE:
6193     case M_BNE_I:
6194       br = "bne";
6195       break;
6196     case M_BNEL:
6197     case M_BNEL_I:
6198       br = mips_opts.micromips ? "bne" : "bnel";
6199       brneg = "beq";
6200       break;
6201     default:
6202       abort ();
6203     }
6204   if (mips_opts.micromips && brneg)
6205     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6206   else
6207     macro_build (ep, br, "s,t,p", sreg, treg);
6208 }
6209
6210 /*
6211  *                      Build macros
6212  *   This routine implements the seemingly endless macro or synthesized
6213  * instructions and addressing modes in the mips assembly language. Many
6214  * of these macros are simple and are similar to each other. These could
6215  * probably be handled by some kind of table or grammar approach instead of
6216  * this verbose method. Others are not simple macros but are more like
6217  * optimizing code generation.
6218  *   One interesting optimization is when several store macros appear
6219  * consecutively that would load AT with the upper half of the same address.
6220  * The ensuing load upper instructions are ommited. This implies some kind
6221  * of global optimization. We currently only optimize within a single macro.
6222  *   For many of the load and store macros if the address is specified as a
6223  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6224  * first load register 'at' with zero and use it as the base register. The
6225  * mips assembler simply uses register $zero. Just one tiny optimization
6226  * we're missing.
6227  */
6228 static void
6229 macro (struct mips_cl_insn *ip)
6230 {
6231   unsigned int treg, sreg, dreg, breg;
6232   unsigned int tempreg;
6233   int mask;
6234   int used_at = 0;
6235   expressionS label_expr;
6236   expressionS expr1;
6237   expressionS *ep;
6238   const char *s;
6239   const char *s2;
6240   const char *fmt;
6241   int likely = 0;
6242   int coproc = 0;
6243   int off12 = 0;
6244   int call = 0;
6245   int jals = 0;
6246   int dbl = 0;
6247   int imm = 0;
6248   int ust = 0;
6249   int lp = 0;
6250   int ab = 0;
6251   int off;
6252   offsetT maxnum;
6253   bfd_reloc_code_real_type r;
6254   int hold_mips_optimize;
6255
6256   gas_assert (! mips_opts.mips16);
6257
6258   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6259   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6260   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6261   mask = ip->insn_mo->mask;
6262
6263   label_expr.X_op = O_constant;
6264   label_expr.X_op_symbol = NULL;
6265   label_expr.X_add_symbol = NULL;
6266   label_expr.X_add_number = 0;
6267
6268   expr1.X_op = O_constant;
6269   expr1.X_op_symbol = NULL;
6270   expr1.X_add_symbol = NULL;
6271   expr1.X_add_number = 1;
6272
6273   switch (mask)
6274     {
6275     case M_DABS:
6276       dbl = 1;
6277     case M_ABS:
6278       /*    bgez    $a0,1f
6279             move    v0,$a0
6280             sub     v0,$zero,$a0
6281          1:
6282        */
6283
6284       start_noreorder ();
6285
6286       if (mips_opts.micromips)
6287         micromips_label_expr (&label_expr);
6288       else
6289         label_expr.X_add_number = 8;
6290       macro_build (&label_expr, "bgez", "s,p", sreg);
6291       if (dreg == sreg)
6292         macro_build (NULL, "nop", "");
6293       else
6294         move_register (dreg, sreg);
6295       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6296       if (mips_opts.micromips)
6297         micromips_add_label ();
6298
6299       end_noreorder ();
6300       break;
6301
6302     case M_ADD_I:
6303       s = "addi";
6304       s2 = "add";
6305       goto do_addi;
6306     case M_ADDU_I:
6307       s = "addiu";
6308       s2 = "addu";
6309       goto do_addi;
6310     case M_DADD_I:
6311       dbl = 1;
6312       s = "daddi";
6313       s2 = "dadd";
6314       if (!mips_opts.micromips)
6315         goto do_addi;
6316       if (imm_expr.X_op == O_constant
6317           && imm_expr.X_add_number >= -0x200
6318           && imm_expr.X_add_number < 0x200)
6319         {
6320           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
6321           break;
6322         }
6323       goto do_addi_i;
6324     case M_DADDU_I:
6325       dbl = 1;
6326       s = "daddiu";
6327       s2 = "daddu";
6328     do_addi:
6329       if (imm_expr.X_op == O_constant
6330           && imm_expr.X_add_number >= -0x8000
6331           && imm_expr.X_add_number < 0x8000)
6332         {
6333           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
6334           break;
6335         }
6336     do_addi_i:
6337       used_at = 1;
6338       load_register (AT, &imm_expr, dbl);
6339       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6340       break;
6341
6342     case M_AND_I:
6343       s = "andi";
6344       s2 = "and";
6345       goto do_bit;
6346     case M_OR_I:
6347       s = "ori";
6348       s2 = "or";
6349       goto do_bit;
6350     case M_NOR_I:
6351       s = "";
6352       s2 = "nor";
6353       goto do_bit;
6354     case M_XOR_I:
6355       s = "xori";
6356       s2 = "xor";
6357     do_bit:
6358       if (imm_expr.X_op == O_constant
6359           && imm_expr.X_add_number >= 0
6360           && imm_expr.X_add_number < 0x10000)
6361         {
6362           if (mask != M_NOR_I)
6363             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
6364           else
6365             {
6366               macro_build (&imm_expr, "ori", "t,r,i",
6367                            treg, sreg, BFD_RELOC_LO16);
6368               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
6369             }
6370           break;
6371         }
6372
6373       used_at = 1;
6374       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6375       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
6376       break;
6377
6378     case M_BALIGN:
6379       switch (imm_expr.X_add_number)
6380         {
6381         case 0:
6382           macro_build (NULL, "nop", "");
6383           break;
6384         case 2:
6385           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
6386           break;
6387         default:
6388           macro_build (NULL, "balign", "t,s,2", treg, sreg,
6389                        (int) imm_expr.X_add_number);
6390           break;
6391         }
6392       break;
6393
6394     case M_BC1FL:
6395     case M_BC1TL:
6396     case M_BC2FL:
6397     case M_BC2TL:
6398       gas_assert (mips_opts.micromips);
6399       macro_build_branch_ccl (mask, &offset_expr,
6400                               EXTRACT_OPERAND (1, BCC, *ip));
6401       break;
6402
6403     case M_BEQ_I:
6404     case M_BEQL_I:
6405     case M_BNE_I:
6406     case M_BNEL_I:
6407       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6408         treg = 0;
6409       else
6410         {
6411           treg = AT;
6412           used_at = 1;
6413           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
6414         }
6415       /* Fall through.  */
6416     case M_BEQL:
6417     case M_BNEL:
6418       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
6419       break;
6420
6421     case M_BGEL:
6422       likely = 1;
6423     case M_BGE:
6424       if (treg == 0)
6425         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
6426       else if (sreg == 0)
6427         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
6428       else
6429         {
6430           used_at = 1;
6431           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6432           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6433                                    &offset_expr, AT, ZERO);
6434         }
6435       break;
6436
6437     case M_BGEZL:
6438     case M_BGEZALL:
6439     case M_BGTZL:
6440     case M_BLEZL:
6441     case M_BLTZL:
6442     case M_BLTZALL:
6443       macro_build_branch_rs (mask, &offset_expr, sreg);
6444       break;
6445
6446     case M_BGTL_I:
6447       likely = 1;
6448     case M_BGT_I:
6449       /* Check for > max integer.  */
6450       maxnum = 0x7fffffff;
6451       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6452         {
6453           maxnum <<= 16;
6454           maxnum |= 0xffff;
6455           maxnum <<= 16;
6456           maxnum |= 0xffff;
6457         }
6458       if (imm_expr.X_op == O_constant
6459           && imm_expr.X_add_number >= maxnum
6460           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6461         {
6462         do_false:
6463           /* Result is always false.  */
6464           if (! likely)
6465             macro_build (NULL, "nop", "");
6466           else
6467             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
6468           break;
6469         }
6470       if (imm_expr.X_op != O_constant)
6471         as_bad (_("Unsupported large constant"));
6472       ++imm_expr.X_add_number;
6473       /* FALLTHROUGH */
6474     case M_BGE_I:
6475     case M_BGEL_I:
6476       if (mask == M_BGEL_I)
6477         likely = 1;
6478       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6479         {
6480           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
6481                                  &offset_expr, sreg);
6482           break;
6483         }
6484       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6485         {
6486           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
6487                                  &offset_expr, sreg);
6488           break;
6489         }
6490       maxnum = 0x7fffffff;
6491       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6492         {
6493           maxnum <<= 16;
6494           maxnum |= 0xffff;
6495           maxnum <<= 16;
6496           maxnum |= 0xffff;
6497         }
6498       maxnum = - maxnum - 1;
6499       if (imm_expr.X_op == O_constant
6500           && imm_expr.X_add_number <= maxnum
6501           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6502         {
6503         do_true:
6504           /* result is always true */
6505           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
6506           macro_build (&offset_expr, "b", "p");
6507           break;
6508         }
6509       used_at = 1;
6510       set_at (sreg, 0);
6511       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6512                                &offset_expr, AT, ZERO);
6513       break;
6514
6515     case M_BGEUL:
6516       likely = 1;
6517     case M_BGEU:
6518       if (treg == 0)
6519         goto do_true;
6520       else if (sreg == 0)
6521         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6522                                  &offset_expr, ZERO, treg);
6523       else
6524         {
6525           used_at = 1;
6526           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6527           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6528                                    &offset_expr, AT, ZERO);
6529         }
6530       break;
6531
6532     case M_BGTUL_I:
6533       likely = 1;
6534     case M_BGTU_I:
6535       if (sreg == 0
6536           || (HAVE_32BIT_GPRS
6537               && imm_expr.X_op == O_constant
6538               && imm_expr.X_add_number == -1))
6539         goto do_false;
6540       if (imm_expr.X_op != O_constant)
6541         as_bad (_("Unsupported large constant"));
6542       ++imm_expr.X_add_number;
6543       /* FALLTHROUGH */
6544     case M_BGEU_I:
6545     case M_BGEUL_I:
6546       if (mask == M_BGEUL_I)
6547         likely = 1;
6548       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6549         goto do_true;
6550       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6551         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6552                                  &offset_expr, sreg, ZERO);
6553       else
6554         {
6555           used_at = 1;
6556           set_at (sreg, 1);
6557           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6558                                    &offset_expr, AT, ZERO);
6559         }
6560       break;
6561
6562     case M_BGTL:
6563       likely = 1;
6564     case M_BGT:
6565       if (treg == 0)
6566         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
6567       else if (sreg == 0)
6568         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
6569       else
6570         {
6571           used_at = 1;
6572           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6573           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6574                                    &offset_expr, AT, ZERO);
6575         }
6576       break;
6577
6578     case M_BGTUL:
6579       likely = 1;
6580     case M_BGTU:
6581       if (treg == 0)
6582         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6583                                  &offset_expr, sreg, ZERO);
6584       else if (sreg == 0)
6585         goto do_false;
6586       else
6587         {
6588           used_at = 1;
6589           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6590           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6591                                    &offset_expr, AT, ZERO);
6592         }
6593       break;
6594
6595     case M_BLEL:
6596       likely = 1;
6597     case M_BLE:
6598       if (treg == 0)
6599         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6600       else if (sreg == 0)
6601         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
6602       else
6603         {
6604           used_at = 1;
6605           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
6606           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6607                                    &offset_expr, AT, ZERO);
6608         }
6609       break;
6610
6611     case M_BLEL_I:
6612       likely = 1;
6613     case M_BLE_I:
6614       maxnum = 0x7fffffff;
6615       if (HAVE_64BIT_GPRS && sizeof (maxnum) > 4)
6616         {
6617           maxnum <<= 16;
6618           maxnum |= 0xffff;
6619           maxnum <<= 16;
6620           maxnum |= 0xffff;
6621         }
6622       if (imm_expr.X_op == O_constant
6623           && imm_expr.X_add_number >= maxnum
6624           && (HAVE_32BIT_GPRS || sizeof (maxnum) > 4))
6625         goto do_true;
6626       if (imm_expr.X_op != O_constant)
6627         as_bad (_("Unsupported large constant"));
6628       ++imm_expr.X_add_number;
6629       /* FALLTHROUGH */
6630     case M_BLT_I:
6631     case M_BLTL_I:
6632       if (mask == M_BLTL_I)
6633         likely = 1;
6634       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6635         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6636       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6637         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
6638       else
6639         {
6640           used_at = 1;
6641           set_at (sreg, 0);
6642           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6643                                    &offset_expr, AT, ZERO);
6644         }
6645       break;
6646
6647     case M_BLEUL:
6648       likely = 1;
6649     case M_BLEU:
6650       if (treg == 0)
6651         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6652                                  &offset_expr, sreg, ZERO);
6653       else if (sreg == 0)
6654         goto do_true;
6655       else
6656         {
6657           used_at = 1;
6658           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
6659           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6660                                    &offset_expr, AT, ZERO);
6661         }
6662       break;
6663
6664     case M_BLEUL_I:
6665       likely = 1;
6666     case M_BLEU_I:
6667       if (sreg == 0
6668           || (HAVE_32BIT_GPRS
6669               && imm_expr.X_op == O_constant
6670               && imm_expr.X_add_number == -1))
6671         goto do_true;
6672       if (imm_expr.X_op != O_constant)
6673         as_bad (_("Unsupported large constant"));
6674       ++imm_expr.X_add_number;
6675       /* FALLTHROUGH */
6676     case M_BLTU_I:
6677     case M_BLTUL_I:
6678       if (mask == M_BLTUL_I)
6679         likely = 1;
6680       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6681         goto do_false;
6682       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6683         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
6684                                  &offset_expr, sreg, ZERO);
6685       else
6686         {
6687           used_at = 1;
6688           set_at (sreg, 1);
6689           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6690                                    &offset_expr, AT, ZERO);
6691         }
6692       break;
6693
6694     case M_BLTL:
6695       likely = 1;
6696     case M_BLT:
6697       if (treg == 0)
6698         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
6699       else if (sreg == 0)
6700         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
6701       else
6702         {
6703           used_at = 1;
6704           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
6705           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6706                                    &offset_expr, AT, ZERO);
6707         }
6708       break;
6709
6710     case M_BLTUL:
6711       likely = 1;
6712     case M_BLTU:
6713       if (treg == 0)
6714         goto do_false;
6715       else if (sreg == 0)
6716         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6717                                  &offset_expr, ZERO, treg);
6718       else
6719         {
6720           used_at = 1;
6721           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
6722           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
6723                                    &offset_expr, AT, ZERO);
6724         }
6725       break;
6726
6727     case M_DEXT:
6728       {
6729         /* Use unsigned arithmetic.  */
6730         addressT pos;
6731         addressT size;
6732
6733         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6734           {
6735             as_bad (_("Unsupported large constant"));
6736             pos = size = 1;
6737           }
6738         else
6739           {
6740             pos = imm_expr.X_add_number;
6741             size = imm2_expr.X_add_number;
6742           }
6743
6744         if (pos > 63)
6745           {
6746             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6747             pos = 1;
6748           }
6749         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6750           {
6751             as_bad (_("Improper extract size (%lu, position %lu)"),
6752                     (unsigned long) size, (unsigned long) pos);
6753             size = 1;
6754           }
6755
6756         if (size <= 32 && pos < 32)
6757           {
6758             s = "dext";
6759             fmt = "t,r,+A,+C";
6760           }
6761         else if (size <= 32)
6762           {
6763             s = "dextu";
6764             fmt = "t,r,+E,+H";
6765           }
6766         else
6767           {
6768             s = "dextm";
6769             fmt = "t,r,+A,+G";
6770           }
6771         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6772                      (int) (size - 1));
6773       }
6774       break;
6775
6776     case M_DINS:
6777       {
6778         /* Use unsigned arithmetic.  */
6779         addressT pos;
6780         addressT size;
6781
6782         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
6783           {
6784             as_bad (_("Unsupported large constant"));
6785             pos = size = 1;
6786           }
6787         else
6788           {
6789             pos = imm_expr.X_add_number;
6790             size = imm2_expr.X_add_number;
6791           }
6792
6793         if (pos > 63)
6794           {
6795             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
6796             pos = 1;
6797           }
6798         if (size == 0 || size > 64 || (pos + size - 1) > 63)
6799           {
6800             as_bad (_("Improper insert size (%lu, position %lu)"),
6801                     (unsigned long) size, (unsigned long) pos);
6802             size = 1;
6803           }
6804
6805         if (pos < 32 && (pos + size - 1) < 32)
6806           {
6807             s = "dins";
6808             fmt = "t,r,+A,+B";
6809           }
6810         else if (pos >= 32)
6811           {
6812             s = "dinsu";
6813             fmt = "t,r,+E,+F";
6814           }
6815         else
6816           {
6817             s = "dinsm";
6818             fmt = "t,r,+A,+F";
6819           }
6820         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
6821                      (int) (pos + size - 1));
6822       }
6823       break;
6824
6825     case M_DDIV_3:
6826       dbl = 1;
6827     case M_DIV_3:
6828       s = "mflo";
6829       goto do_div3;
6830     case M_DREM_3:
6831       dbl = 1;
6832     case M_REM_3:
6833       s = "mfhi";
6834     do_div3:
6835       if (treg == 0)
6836         {
6837           as_warn (_("Divide by zero."));
6838           if (mips_trap)
6839             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6840           else
6841             macro_build (NULL, "break", BRK_FMT, 7);
6842           break;
6843         }
6844
6845       start_noreorder ();
6846       if (mips_trap)
6847         {
6848           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
6849           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6850         }
6851       else
6852         {
6853           if (mips_opts.micromips)
6854             micromips_label_expr (&label_expr);
6855           else
6856             label_expr.X_add_number = 8;
6857           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
6858           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
6859           macro_build (NULL, "break", BRK_FMT, 7);
6860           if (mips_opts.micromips)
6861             micromips_add_label ();
6862         }
6863       expr1.X_add_number = -1;
6864       used_at = 1;
6865       load_register (AT, &expr1, dbl);
6866       if (mips_opts.micromips)
6867         micromips_label_expr (&label_expr);
6868       else
6869         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
6870       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
6871       if (dbl)
6872         {
6873           expr1.X_add_number = 1;
6874           load_register (AT, &expr1, dbl);
6875           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
6876         }
6877       else
6878         {
6879           expr1.X_add_number = 0x80000000;
6880           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
6881         }
6882       if (mips_trap)
6883         {
6884           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
6885           /* We want to close the noreorder block as soon as possible, so
6886              that later insns are available for delay slot filling.  */
6887           end_noreorder ();
6888         }
6889       else
6890         {
6891           if (mips_opts.micromips)
6892             micromips_label_expr (&label_expr);
6893           else
6894             label_expr.X_add_number = 8;
6895           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
6896           macro_build (NULL, "nop", "");
6897
6898           /* We want to close the noreorder block as soon as possible, so
6899              that later insns are available for delay slot filling.  */
6900           end_noreorder ();
6901
6902           macro_build (NULL, "break", BRK_FMT, 6);
6903         }
6904       if (mips_opts.micromips)
6905         micromips_add_label ();
6906       macro_build (NULL, s, MFHL_FMT, dreg);
6907       break;
6908
6909     case M_DIV_3I:
6910       s = "div";
6911       s2 = "mflo";
6912       goto do_divi;
6913     case M_DIVU_3I:
6914       s = "divu";
6915       s2 = "mflo";
6916       goto do_divi;
6917     case M_REM_3I:
6918       s = "div";
6919       s2 = "mfhi";
6920       goto do_divi;
6921     case M_REMU_3I:
6922       s = "divu";
6923       s2 = "mfhi";
6924       goto do_divi;
6925     case M_DDIV_3I:
6926       dbl = 1;
6927       s = "ddiv";
6928       s2 = "mflo";
6929       goto do_divi;
6930     case M_DDIVU_3I:
6931       dbl = 1;
6932       s = "ddivu";
6933       s2 = "mflo";
6934       goto do_divi;
6935     case M_DREM_3I:
6936       dbl = 1;
6937       s = "ddiv";
6938       s2 = "mfhi";
6939       goto do_divi;
6940     case M_DREMU_3I:
6941       dbl = 1;
6942       s = "ddivu";
6943       s2 = "mfhi";
6944     do_divi:
6945       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
6946         {
6947           as_warn (_("Divide by zero."));
6948           if (mips_trap)
6949             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
6950           else
6951             macro_build (NULL, "break", BRK_FMT, 7);
6952           break;
6953         }
6954       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
6955         {
6956           if (strcmp (s2, "mflo") == 0)
6957             move_register (dreg, sreg);
6958           else
6959             move_register (dreg, ZERO);
6960           break;
6961         }
6962       if (imm_expr.X_op == O_constant
6963           && imm_expr.X_add_number == -1
6964           && s[strlen (s) - 1] != 'u')
6965         {
6966           if (strcmp (s2, "mflo") == 0)
6967             {
6968               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
6969             }
6970           else
6971             move_register (dreg, ZERO);
6972           break;
6973         }
6974
6975       used_at = 1;
6976       load_register (AT, &imm_expr, dbl);
6977       macro_build (NULL, s, "z,s,t", sreg, AT);
6978       macro_build (NULL, s2, MFHL_FMT, dreg);
6979       break;
6980
6981     case M_DIVU_3:
6982       s = "divu";
6983       s2 = "mflo";
6984       goto do_divu3;
6985     case M_REMU_3:
6986       s = "divu";
6987       s2 = "mfhi";
6988       goto do_divu3;
6989     case M_DDIVU_3:
6990       s = "ddivu";
6991       s2 = "mflo";
6992       goto do_divu3;
6993     case M_DREMU_3:
6994       s = "ddivu";
6995       s2 = "mfhi";
6996     do_divu3:
6997       start_noreorder ();
6998       if (mips_trap)
6999         {
7000           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7001           macro_build (NULL, s, "z,s,t", sreg, treg);
7002           /* We want to close the noreorder block as soon as possible, so
7003              that later insns are available for delay slot filling.  */
7004           end_noreorder ();
7005         }
7006       else
7007         {
7008           if (mips_opts.micromips)
7009             micromips_label_expr (&label_expr);
7010           else
7011             label_expr.X_add_number = 8;
7012           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7013           macro_build (NULL, s, "z,s,t", sreg, treg);
7014
7015           /* We want to close the noreorder block as soon as possible, so
7016              that later insns are available for delay slot filling.  */
7017           end_noreorder ();
7018           macro_build (NULL, "break", BRK_FMT, 7);
7019           if (mips_opts.micromips)
7020             micromips_add_label ();
7021         }
7022       macro_build (NULL, s2, MFHL_FMT, dreg);
7023       break;
7024
7025     case M_DLCA_AB:
7026       dbl = 1;
7027     case M_LCA_AB:
7028       call = 1;
7029       goto do_la;
7030     case M_DLA_AB:
7031       dbl = 1;
7032     case M_LA_AB:
7033     do_la:
7034       /* Load the address of a symbol into a register.  If breg is not
7035          zero, we then add a base register to it.  */
7036
7037       if (dbl && HAVE_32BIT_GPRS)
7038         as_warn (_("dla used to load 32-bit register"));
7039
7040       if (!dbl && HAVE_64BIT_OBJECTS)
7041         as_warn (_("la used to load 64-bit address"));
7042
7043       if (offset_expr.X_op == O_constant
7044           && offset_expr.X_add_number >= -0x8000
7045           && offset_expr.X_add_number < 0x8000)
7046         {
7047           macro_build (&offset_expr, ADDRESS_ADDI_INSN,
7048                        "t,r,j", treg, sreg, BFD_RELOC_LO16);
7049           break;
7050         }
7051
7052       if (mips_opts.at && (treg == breg))
7053         {
7054           tempreg = AT;
7055           used_at = 1;
7056         }
7057       else
7058         {
7059           tempreg = treg;
7060         }
7061
7062       if (offset_expr.X_op != O_symbol
7063           && offset_expr.X_op != O_constant)
7064         {
7065           as_bad (_("Expression too complex"));
7066           offset_expr.X_op = O_constant;
7067         }
7068
7069       if (offset_expr.X_op == O_constant)
7070         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7071       else if (mips_pic == NO_PIC)
7072         {
7073           /* If this is a reference to a GP relative symbol, we want
7074                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7075              Otherwise we want
7076                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7077                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7078              If we have a constant, we need two instructions anyhow,
7079              so we may as well always use the latter form.
7080
7081              With 64bit address space and a usable $at we want
7082                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7083                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7084                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7085                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7086                dsll32   $tempreg,0
7087                daddu    $tempreg,$tempreg,$at
7088
7089              If $at is already in use, we use a path which is suboptimal
7090              on superscalar processors.
7091                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7092                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7093                dsll     $tempreg,16
7094                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7095                dsll     $tempreg,16
7096                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7097
7098              For GP relative symbols in 64bit address space we can use
7099              the same sequence as in 32bit address space.  */
7100           if (HAVE_64BIT_SYMBOLS)
7101             {
7102               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7103                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7104                 {
7105                   relax_start (offset_expr.X_add_symbol);
7106                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7107                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7108                   relax_switch ();
7109                 }
7110
7111               if (used_at == 0 && mips_opts.at)
7112                 {
7113                   macro_build (&offset_expr, "lui", LUI_FMT,
7114                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7115                   macro_build (&offset_expr, "lui", LUI_FMT,
7116                                AT, BFD_RELOC_HI16_S);
7117                   macro_build (&offset_expr, "daddiu", "t,r,j",
7118                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7119                   macro_build (&offset_expr, "daddiu", "t,r,j",
7120                                AT, AT, BFD_RELOC_LO16);
7121                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7122                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7123                   used_at = 1;
7124                 }
7125               else
7126                 {
7127                   macro_build (&offset_expr, "lui", LUI_FMT,
7128                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7129                   macro_build (&offset_expr, "daddiu", "t,r,j",
7130                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7131                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7132                   macro_build (&offset_expr, "daddiu", "t,r,j",
7133                                tempreg, tempreg, BFD_RELOC_HI16_S);
7134                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7135                   macro_build (&offset_expr, "daddiu", "t,r,j",
7136                                tempreg, tempreg, BFD_RELOC_LO16);
7137                 }
7138
7139               if (mips_relax.sequence)
7140                 relax_end ();
7141             }
7142           else
7143             {
7144               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7145                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7146                 {
7147                   relax_start (offset_expr.X_add_symbol);
7148                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7149                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7150                   relax_switch ();
7151                 }
7152               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7153                 as_bad (_("Offset too large"));
7154               macro_build_lui (&offset_expr, tempreg);
7155               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7156                            tempreg, tempreg, BFD_RELOC_LO16);
7157               if (mips_relax.sequence)
7158                 relax_end ();
7159             }
7160         }
7161       else if (!mips_big_got && !HAVE_NEWABI)
7162         {
7163           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7164
7165           /* If this is a reference to an external symbol, and there
7166              is no constant, we want
7167                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7168              or for lca or if tempreg is PIC_CALL_REG
7169                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7170              For a local symbol, we want
7171                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7172                nop
7173                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7174
7175              If we have a small constant, and this is a reference to
7176              an external symbol, we want
7177                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7178                nop
7179                addiu    $tempreg,$tempreg,<constant>
7180              For a local symbol, we want the same instruction
7181              sequence, but we output a BFD_RELOC_LO16 reloc on the
7182              addiu instruction.
7183
7184              If we have a large constant, and this is a reference to
7185              an external symbol, we want
7186                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7187                lui      $at,<hiconstant>
7188                addiu    $at,$at,<loconstant>
7189                addu     $tempreg,$tempreg,$at
7190              For a local symbol, we want the same instruction
7191              sequence, but we output a BFD_RELOC_LO16 reloc on the
7192              addiu instruction.
7193            */
7194
7195           if (offset_expr.X_add_number == 0)
7196             {
7197               if (mips_pic == SVR4_PIC
7198                   && breg == 0
7199                   && (call || tempreg == PIC_CALL_REG))
7200                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7201
7202               relax_start (offset_expr.X_add_symbol);
7203               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7204                            lw_reloc_type, mips_gp_register);
7205               if (breg != 0)
7206                 {
7207                   /* We're going to put in an addu instruction using
7208                      tempreg, so we may as well insert the nop right
7209                      now.  */
7210                   load_delay_nop ();
7211                 }
7212               relax_switch ();
7213               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7214                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7215               load_delay_nop ();
7216               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7217                            tempreg, tempreg, BFD_RELOC_LO16);
7218               relax_end ();
7219               /* FIXME: If breg == 0, and the next instruction uses
7220                  $tempreg, then if this variant case is used an extra
7221                  nop will be generated.  */
7222             }
7223           else if (offset_expr.X_add_number >= -0x8000
7224                    && offset_expr.X_add_number < 0x8000)
7225             {
7226               load_got_offset (tempreg, &offset_expr);
7227               load_delay_nop ();
7228               add_got_offset (tempreg, &offset_expr);
7229             }
7230           else
7231             {
7232               expr1.X_add_number = offset_expr.X_add_number;
7233               offset_expr.X_add_number =
7234                 ((offset_expr.X_add_number + 0x8000) & 0xffff) - 0x8000;
7235               load_got_offset (tempreg, &offset_expr);
7236               offset_expr.X_add_number = expr1.X_add_number;
7237               /* If we are going to add in a base register, and the
7238                  target register and the base register are the same,
7239                  then we are using AT as a temporary register.  Since
7240                  we want to load the constant into AT, we add our
7241                  current AT (from the global offset table) and the
7242                  register into the register now, and pretend we were
7243                  not using a base register.  */
7244               if (breg == treg)
7245                 {
7246                   load_delay_nop ();
7247                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7248                                treg, AT, breg);
7249                   breg = 0;
7250                   tempreg = treg;
7251                 }
7252               add_got_offset_hilo (tempreg, &offset_expr, AT);
7253               used_at = 1;
7254             }
7255         }
7256       else if (!mips_big_got && HAVE_NEWABI)
7257         {
7258           int add_breg_early = 0;
7259
7260           /* If this is a reference to an external, and there is no
7261              constant, or local symbol (*), with or without a
7262              constant, we want
7263                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7264              or for lca or if tempreg is PIC_CALL_REG
7265                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7266
7267              If we have a small constant, and this is a reference to
7268              an external symbol, we want
7269                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7270                addiu    $tempreg,$tempreg,<constant>
7271
7272              If we have a large constant, and this is a reference to
7273              an external symbol, we want
7274                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7275                lui      $at,<hiconstant>
7276                addiu    $at,$at,<loconstant>
7277                addu     $tempreg,$tempreg,$at
7278
7279              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7280              local symbols, even though it introduces an additional
7281              instruction.  */
7282
7283           if (offset_expr.X_add_number)
7284             {
7285               expr1.X_add_number = offset_expr.X_add_number;
7286               offset_expr.X_add_number = 0;
7287
7288               relax_start (offset_expr.X_add_symbol);
7289               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7290                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7291
7292               if (expr1.X_add_number >= -0x8000
7293                   && expr1.X_add_number < 0x8000)
7294                 {
7295                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7296                                tempreg, tempreg, BFD_RELOC_LO16);
7297                 }
7298               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7299                 {
7300                   /* If we are going to add in a base register, and the
7301                      target register and the base register are the same,
7302                      then we are using AT as a temporary register.  Since
7303                      we want to load the constant into AT, we add our
7304                      current AT (from the global offset table) and the
7305                      register into the register now, and pretend we were
7306                      not using a base register.  */
7307                   if (breg != treg)
7308                     dreg = tempreg;
7309                   else
7310                     {
7311                       gas_assert (tempreg == AT);
7312                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7313                                    treg, AT, breg);
7314                       dreg = treg;
7315                       add_breg_early = 1;
7316                     }
7317
7318                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7319                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7320                                dreg, dreg, AT);
7321
7322                   used_at = 1;
7323                 }
7324               else
7325                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7326
7327               relax_switch ();
7328               offset_expr.X_add_number = expr1.X_add_number;
7329
7330               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7331                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7332               if (add_breg_early)
7333                 {
7334                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7335                                treg, tempreg, breg);
7336                   breg = 0;
7337                   tempreg = treg;
7338                 }
7339               relax_end ();
7340             }
7341           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7342             {
7343               relax_start (offset_expr.X_add_symbol);
7344               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7345                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7346               relax_switch ();
7347               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7348                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7349               relax_end ();
7350             }
7351           else
7352             {
7353               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7354                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7355             }
7356         }
7357       else if (mips_big_got && !HAVE_NEWABI)
7358         {
7359           int gpdelay;
7360           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7361           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7362           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7363
7364           /* This is the large GOT case.  If this is a reference to an
7365              external symbol, and there is no constant, we want
7366                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7367                addu     $tempreg,$tempreg,$gp
7368                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7369              or for lca or if tempreg is PIC_CALL_REG
7370                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7371                addu     $tempreg,$tempreg,$gp
7372                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7373              For a local symbol, we want
7374                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7375                nop
7376                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7377
7378              If we have a small constant, and this is a reference to
7379              an external symbol, we want
7380                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7381                addu     $tempreg,$tempreg,$gp
7382                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7383                nop
7384                addiu    $tempreg,$tempreg,<constant>
7385              For a local symbol, we want
7386                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7387                nop
7388                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
7389
7390              If we have a large constant, and this is a reference to
7391              an external symbol, we want
7392                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7393                addu     $tempreg,$tempreg,$gp
7394                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7395                lui      $at,<hiconstant>
7396                addiu    $at,$at,<loconstant>
7397                addu     $tempreg,$tempreg,$at
7398              For a local symbol, we want
7399                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7400                lui      $at,<hiconstant>
7401                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
7402                addu     $tempreg,$tempreg,$at
7403           */
7404
7405           expr1.X_add_number = offset_expr.X_add_number;
7406           offset_expr.X_add_number = 0;
7407           relax_start (offset_expr.X_add_symbol);
7408           gpdelay = reg_needs_delay (mips_gp_register);
7409           if (expr1.X_add_number == 0 && breg == 0
7410               && (call || tempreg == PIC_CALL_REG))
7411             {
7412               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7413               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7414             }
7415           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7416           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7417                        tempreg, tempreg, mips_gp_register);
7418           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7419                        tempreg, lw_reloc_type, tempreg);
7420           if (expr1.X_add_number == 0)
7421             {
7422               if (breg != 0)
7423                 {
7424                   /* We're going to put in an addu instruction using
7425                      tempreg, so we may as well insert the nop right
7426                      now.  */
7427                   load_delay_nop ();
7428                 }
7429             }
7430           else if (expr1.X_add_number >= -0x8000
7431                    && expr1.X_add_number < 0x8000)
7432             {
7433               load_delay_nop ();
7434               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7435                            tempreg, tempreg, BFD_RELOC_LO16);
7436             }
7437           else
7438             {
7439               /* If we are going to add in a base register, and the
7440                  target register and the base register are the same,
7441                  then we are using AT as a temporary register.  Since
7442                  we want to load the constant into AT, we add our
7443                  current AT (from the global offset table) and the
7444                  register into the register now, and pretend we were
7445                  not using a base register.  */
7446               if (breg != treg)
7447                 dreg = tempreg;
7448               else
7449                 {
7450                   gas_assert (tempreg == AT);
7451                   load_delay_nop ();
7452                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7453                                treg, AT, breg);
7454                   dreg = treg;
7455                 }
7456
7457               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7458               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7459
7460               used_at = 1;
7461             }
7462           offset_expr.X_add_number =
7463             ((expr1.X_add_number + 0x8000) & 0xffff) - 0x8000;
7464           relax_switch ();
7465
7466           if (gpdelay)
7467             {
7468               /* This is needed because this instruction uses $gp, but
7469                  the first instruction on the main stream does not.  */
7470               macro_build (NULL, "nop", "");
7471             }
7472
7473           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7474                        local_reloc_type, mips_gp_register);
7475           if (expr1.X_add_number >= -0x8000
7476               && expr1.X_add_number < 0x8000)
7477             {
7478               load_delay_nop ();
7479               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7480                            tempreg, tempreg, BFD_RELOC_LO16);
7481               /* FIXME: If add_number is 0, and there was no base
7482                  register, the external symbol case ended with a load,
7483                  so if the symbol turns out to not be external, and
7484                  the next instruction uses tempreg, an unnecessary nop
7485                  will be inserted.  */
7486             }
7487           else
7488             {
7489               if (breg == treg)
7490                 {
7491                   /* We must add in the base register now, as in the
7492                      external symbol case.  */
7493                   gas_assert (tempreg == AT);
7494                   load_delay_nop ();
7495                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7496                                treg, AT, breg);
7497                   tempreg = treg;
7498                   /* We set breg to 0 because we have arranged to add
7499                      it in in both cases.  */
7500                   breg = 0;
7501                 }
7502
7503               macro_build_lui (&expr1, AT);
7504               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7505                            AT, AT, BFD_RELOC_LO16);
7506               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7507                            tempreg, tempreg, AT);
7508               used_at = 1;
7509             }
7510           relax_end ();
7511         }
7512       else if (mips_big_got && HAVE_NEWABI)
7513         {
7514           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
7515           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
7516           int add_breg_early = 0;
7517
7518           /* This is the large GOT case.  If this is a reference to an
7519              external symbol, and there is no constant, we want
7520                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7521                add      $tempreg,$tempreg,$gp
7522                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7523              or for lca or if tempreg is PIC_CALL_REG
7524                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
7525                add      $tempreg,$tempreg,$gp
7526                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
7527
7528              If we have a small constant, and this is a reference to
7529              an external symbol, we want
7530                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7531                add      $tempreg,$tempreg,$gp
7532                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7533                addi     $tempreg,$tempreg,<constant>
7534
7535              If we have a large constant, and this is a reference to
7536              an external symbol, we want
7537                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
7538                addu     $tempreg,$tempreg,$gp
7539                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
7540                lui      $at,<hiconstant>
7541                addi     $at,$at,<loconstant>
7542                add      $tempreg,$tempreg,$at
7543
7544              If we have NewABI, and we know it's a local symbol, we want
7545                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7546                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7547              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
7548
7549           relax_start (offset_expr.X_add_symbol);
7550
7551           expr1.X_add_number = offset_expr.X_add_number;
7552           offset_expr.X_add_number = 0;
7553
7554           if (expr1.X_add_number == 0 && breg == 0
7555               && (call || tempreg == PIC_CALL_REG))
7556             {
7557               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
7558               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
7559             }
7560           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
7561           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7562                        tempreg, tempreg, mips_gp_register);
7563           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7564                        tempreg, lw_reloc_type, tempreg);
7565
7566           if (expr1.X_add_number == 0)
7567             ;
7568           else if (expr1.X_add_number >= -0x8000
7569                    && expr1.X_add_number < 0x8000)
7570             {
7571               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7572                            tempreg, tempreg, BFD_RELOC_LO16);
7573             }
7574           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7575             {
7576               /* If we are going to add in a base register, and the
7577                  target register and the base register are the same,
7578                  then we are using AT as a temporary register.  Since
7579                  we want to load the constant into AT, we add our
7580                  current AT (from the global offset table) and the
7581                  register into the register now, and pretend we were
7582                  not using a base register.  */
7583               if (breg != treg)
7584                 dreg = tempreg;
7585               else
7586                 {
7587                   gas_assert (tempreg == AT);
7588                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7589                                treg, AT, breg);
7590                   dreg = treg;
7591                   add_breg_early = 1;
7592                 }
7593
7594               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7595               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
7596
7597               used_at = 1;
7598             }
7599           else
7600             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7601
7602           relax_switch ();
7603           offset_expr.X_add_number = expr1.X_add_number;
7604           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7605                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7606           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
7607                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
7608           if (add_breg_early)
7609             {
7610               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7611                            treg, tempreg, breg);
7612               breg = 0;
7613               tempreg = treg;
7614             }
7615           relax_end ();
7616         }
7617       else
7618         abort ();
7619
7620       if (breg != 0)
7621         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
7622       break;
7623
7624     case M_MSGSND:
7625       gas_assert (!mips_opts.micromips);
7626       {
7627         unsigned long temp = (treg << 16) | (0x01);
7628         macro_build (NULL, "c2", "C", temp);
7629       }
7630       break;
7631
7632     case M_MSGLD:
7633       gas_assert (!mips_opts.micromips);
7634       {
7635         unsigned long temp = (0x02);
7636         macro_build (NULL, "c2", "C", temp);
7637       }
7638       break;
7639
7640     case M_MSGLD_T:
7641       gas_assert (!mips_opts.micromips);
7642       {
7643         unsigned long temp = (treg << 16) | (0x02);
7644         macro_build (NULL, "c2", "C", temp);
7645       }
7646       break;
7647
7648     case M_MSGWAIT:
7649       gas_assert (!mips_opts.micromips);
7650       macro_build (NULL, "c2", "C", 3);
7651       break;
7652
7653     case M_MSGWAIT_T:
7654       gas_assert (!mips_opts.micromips);
7655       {
7656         unsigned long temp = (treg << 16) | 0x03;
7657         macro_build (NULL, "c2", "C", temp);
7658       }
7659       break;
7660
7661     case M_J_A:
7662       /* The j instruction may not be used in PIC code, since it
7663          requires an absolute address.  We convert it to a b
7664          instruction.  */
7665       if (mips_pic == NO_PIC)
7666         macro_build (&offset_expr, "j", "a");
7667       else
7668         macro_build (&offset_expr, "b", "p");
7669       break;
7670
7671       /* The jal instructions must be handled as macros because when
7672          generating PIC code they expand to multi-instruction
7673          sequences.  Normally they are simple instructions.  */
7674     case M_JALS_1:
7675       dreg = RA;
7676       /* Fall through.  */
7677     case M_JALS_2:
7678       gas_assert (mips_opts.micromips);
7679       jals = 1;
7680       goto jal;
7681     case M_JAL_1:
7682       dreg = RA;
7683       /* Fall through.  */
7684     case M_JAL_2:
7685     jal:
7686       if (mips_pic == NO_PIC)
7687         {
7688           s = jals ? "jalrs" : "jalr";
7689           if (mips_opts.micromips && dreg == RA)
7690             macro_build (NULL, s, "mj", sreg);
7691           else
7692             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7693         }
7694       else
7695         {
7696           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
7697                            && mips_cprestore_offset >= 0);
7698
7699           if (sreg != PIC_CALL_REG)
7700             as_warn (_("MIPS PIC call to register other than $25"));
7701
7702           s = (mips_opts.micromips && (!mips_opts.noreorder || cprestore)
7703                ? "jalrs" : "jalr");
7704           if (mips_opts.micromips && dreg == RA)
7705             macro_build (NULL, s, "mj", sreg);
7706           else
7707             macro_build (NULL, s, JALR_FMT, dreg, sreg);
7708           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
7709             {
7710               if (mips_cprestore_offset < 0)
7711                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7712               else
7713                 {
7714                   if (!mips_frame_reg_valid)
7715                     {
7716                       as_warn (_("No .frame pseudo-op used in PIC code"));
7717                       /* Quiet this warning.  */
7718                       mips_frame_reg_valid = 1;
7719                     }
7720                   if (!mips_cprestore_valid)
7721                     {
7722                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7723                       /* Quiet this warning.  */
7724                       mips_cprestore_valid = 1;
7725                     }
7726                   if (mips_opts.noreorder)
7727                     macro_build (NULL, "nop", "");
7728                   expr1.X_add_number = mips_cprestore_offset;
7729                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7730                                                 mips_gp_register,
7731                                                 mips_frame_reg,
7732                                                 HAVE_64BIT_ADDRESSES);
7733                 }
7734             }
7735         }
7736
7737       break;
7738
7739     case M_JALS_A:
7740       gas_assert (mips_opts.micromips);
7741       jals = 1;
7742       /* Fall through.  */
7743     case M_JAL_A:
7744       if (mips_pic == NO_PIC)
7745         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
7746       else if (mips_pic == SVR4_PIC)
7747         {
7748           /* If this is a reference to an external symbol, and we are
7749              using a small GOT, we want
7750                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
7751                nop
7752                jalr     $ra,$25
7753                nop
7754                lw       $gp,cprestore($sp)
7755              The cprestore value is set using the .cprestore
7756              pseudo-op.  If we are using a big GOT, we want
7757                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
7758                addu     $25,$25,$gp
7759                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
7760                nop
7761                jalr     $ra,$25
7762                nop
7763                lw       $gp,cprestore($sp)
7764              If the symbol is not external, we want
7765                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
7766                nop
7767                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
7768                jalr     $ra,$25
7769                nop
7770                lw $gp,cprestore($sp)
7771
7772              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
7773              sequences above, minus nops, unless the symbol is local,
7774              which enables us to use GOT_PAGE/GOT_OFST (big got) or
7775              GOT_DISP.  */
7776           if (HAVE_NEWABI)
7777             {
7778               if (!mips_big_got)
7779                 {
7780                   relax_start (offset_expr.X_add_symbol);
7781                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7782                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7783                                mips_gp_register);
7784                   relax_switch ();
7785                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7786                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
7787                                mips_gp_register);
7788                   relax_end ();
7789                 }
7790               else
7791                 {
7792                   relax_start (offset_expr.X_add_symbol);
7793                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7794                                BFD_RELOC_MIPS_CALL_HI16);
7795                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7796                                PIC_CALL_REG, mips_gp_register);
7797                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7798                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7799                                PIC_CALL_REG);
7800                   relax_switch ();
7801                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7802                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
7803                                mips_gp_register);
7804                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7805                                PIC_CALL_REG, PIC_CALL_REG,
7806                                BFD_RELOC_MIPS_GOT_OFST);
7807                   relax_end ();
7808                 }
7809
7810               macro_build_jalr (&offset_expr, 0);
7811             }
7812           else
7813             {
7814               relax_start (offset_expr.X_add_symbol);
7815               if (!mips_big_got)
7816                 {
7817                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7818                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
7819                                mips_gp_register);
7820                   load_delay_nop ();
7821                   relax_switch ();
7822                 }
7823               else
7824                 {
7825                   int gpdelay;
7826
7827                   gpdelay = reg_needs_delay (mips_gp_register);
7828                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
7829                                BFD_RELOC_MIPS_CALL_HI16);
7830                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
7831                                PIC_CALL_REG, mips_gp_register);
7832                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7833                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
7834                                PIC_CALL_REG);
7835                   load_delay_nop ();
7836                   relax_switch ();
7837                   if (gpdelay)
7838                     macro_build (NULL, "nop", "");
7839                 }
7840               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7841                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
7842                            mips_gp_register);
7843               load_delay_nop ();
7844               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7845                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
7846               relax_end ();
7847               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
7848
7849               if (mips_cprestore_offset < 0)
7850                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
7851               else
7852                 {
7853                   if (!mips_frame_reg_valid)
7854                     {
7855                       as_warn (_("No .frame pseudo-op used in PIC code"));
7856                       /* Quiet this warning.  */
7857                       mips_frame_reg_valid = 1;
7858                     }
7859                   if (!mips_cprestore_valid)
7860                     {
7861                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
7862                       /* Quiet this warning.  */
7863                       mips_cprestore_valid = 1;
7864                     }
7865                   if (mips_opts.noreorder)
7866                     macro_build (NULL, "nop", "");
7867                   expr1.X_add_number = mips_cprestore_offset;
7868                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
7869                                                 mips_gp_register,
7870                                                 mips_frame_reg,
7871                                                 HAVE_64BIT_ADDRESSES);
7872                 }
7873             }
7874         }
7875       else if (mips_pic == VXWORKS_PIC)
7876         as_bad (_("Non-PIC jump used in PIC library"));
7877       else
7878         abort ();
7879
7880       break;
7881
7882     case M_LB_AB:
7883       ab = 1;
7884       s = "lb";
7885       fmt = "t,o(b)";
7886       goto ld;
7887     case M_LBU_AB:
7888       ab = 1;
7889       s = "lbu";
7890       fmt = "t,o(b)";
7891       goto ld;
7892     case M_LH_AB:
7893       ab = 1;
7894       s = "lh";
7895       fmt = "t,o(b)";
7896       goto ld;
7897     case M_LHU_AB:
7898       ab = 1;
7899       s = "lhu";
7900       fmt = "t,o(b)";
7901       goto ld;
7902     case M_LW_AB:
7903       ab = 1;
7904       s = "lw";
7905       fmt = "t,o(b)";
7906       goto ld;
7907     case M_LWC0_AB:
7908       ab = 1;
7909       gas_assert (!mips_opts.micromips);
7910       s = "lwc0";
7911       fmt = "E,o(b)";
7912       /* Itbl support may require additional care here.  */
7913       coproc = 1;
7914       goto ld_st;
7915     case M_LWC1_AB:
7916       ab = 1;
7917       s = "lwc1";
7918       fmt = "T,o(b)";
7919       /* Itbl support may require additional care here.  */
7920       coproc = 1;
7921       goto ld_st;
7922     case M_LWC2_AB:
7923       ab = 1;
7924     case M_LWC2_OB:
7925       s = "lwc2";
7926       fmt = COP12_FMT;
7927       off12 = mips_opts.micromips;
7928       /* Itbl support may require additional care here.  */
7929       coproc = 1;
7930       goto ld_st;
7931     case M_LWC3_AB:
7932       ab = 1;
7933       gas_assert (!mips_opts.micromips);
7934       s = "lwc3";
7935       fmt = "E,o(b)";
7936       /* Itbl support may require additional care here.  */
7937       coproc = 1;
7938       goto ld_st;
7939     case M_LWL_AB:
7940       ab = 1;
7941     case M_LWL_OB:
7942       s = "lwl";
7943       fmt = MEM12_FMT;
7944       off12 = mips_opts.micromips;
7945       goto ld_st;
7946     case M_LWR_AB:
7947       ab = 1;
7948     case M_LWR_OB:
7949       s = "lwr";
7950       fmt = MEM12_FMT;
7951       off12 = mips_opts.micromips;
7952       goto ld_st;
7953     case M_LDC1_AB:
7954       ab = 1;
7955       s = "ldc1";
7956       fmt = "T,o(b)";
7957       /* Itbl support may require additional care here.  */
7958       coproc = 1;
7959       goto ld_st;
7960     case M_LDC2_AB:
7961       ab = 1;
7962     case M_LDC2_OB:
7963       s = "ldc2";
7964       fmt = COP12_FMT;
7965       off12 = mips_opts.micromips;
7966       /* Itbl support may require additional care here.  */
7967       coproc = 1;
7968       goto ld_st;
7969     case M_LDC3_AB:
7970       ab = 1;
7971       s = "ldc3";
7972       fmt = "E,o(b)";
7973       /* Itbl support may require additional care here.  */
7974       coproc = 1;
7975       goto ld_st;
7976     case M_LDL_AB:
7977       ab = 1;
7978     case M_LDL_OB:
7979       s = "ldl";
7980       fmt = MEM12_FMT;
7981       off12 = mips_opts.micromips;
7982       goto ld_st;
7983     case M_LDR_AB:
7984       ab = 1;
7985     case M_LDR_OB:
7986       s = "ldr";
7987       fmt = MEM12_FMT;
7988       off12 = mips_opts.micromips;
7989       goto ld_st;
7990     case M_LL_AB:
7991       ab = 1;
7992     case M_LL_OB:
7993       s = "ll";
7994       fmt = MEM12_FMT;
7995       off12 = mips_opts.micromips;
7996       goto ld;
7997     case M_LLD_AB:
7998       ab = 1;
7999     case M_LLD_OB:
8000       s = "lld";
8001       fmt = MEM12_FMT;
8002       off12 = mips_opts.micromips;
8003       goto ld;
8004     case M_LWU_AB:
8005       ab = 1;
8006     case M_LWU_OB:
8007       s = "lwu";
8008       fmt = MEM12_FMT;
8009       off12 = mips_opts.micromips;
8010       goto ld;
8011     case M_LWP_AB:
8012       ab = 1;
8013     case M_LWP_OB:
8014       gas_assert (mips_opts.micromips);
8015       s = "lwp";
8016       fmt = "t,~(b)";
8017       off12 = 1;
8018       lp = 1;
8019       goto ld;
8020     case M_LDP_AB:
8021       ab = 1;
8022     case M_LDP_OB:
8023       gas_assert (mips_opts.micromips);
8024       s = "ldp";
8025       fmt = "t,~(b)";
8026       off12 = 1;
8027       lp = 1;
8028       goto ld;
8029     case M_LWM_AB:
8030       ab = 1;
8031     case M_LWM_OB:
8032       gas_assert (mips_opts.micromips);
8033       s = "lwm";
8034       fmt = "n,~(b)";
8035       off12 = 1;
8036       goto ld_st;
8037     case M_LDM_AB:
8038       ab = 1;
8039     case M_LDM_OB:
8040       gas_assert (mips_opts.micromips);
8041       s = "ldm";
8042       fmt = "n,~(b)";
8043       off12 = 1;
8044       goto ld_st;
8045
8046     ld:
8047       if (breg == treg + lp)
8048         goto ld_st;
8049       else
8050         tempreg = treg + lp;
8051       goto ld_noat;
8052
8053     case M_SB_AB:
8054       ab = 1;
8055       s = "sb";
8056       fmt = "t,o(b)";
8057       goto ld_st;
8058     case M_SH_AB:
8059       ab = 1;
8060       s = "sh";
8061       fmt = "t,o(b)";
8062       goto ld_st;
8063     case M_SW_AB:
8064       ab = 1;
8065       s = "sw";
8066       fmt = "t,o(b)";
8067       goto ld_st;
8068     case M_SWC0_AB:
8069       ab = 1;
8070       gas_assert (!mips_opts.micromips);
8071       s = "swc0";
8072       fmt = "E,o(b)";
8073       /* Itbl support may require additional care here.  */
8074       coproc = 1;
8075       goto ld_st;
8076     case M_SWC1_AB:
8077       ab = 1;
8078       s = "swc1";
8079       fmt = "T,o(b)";
8080       /* Itbl support may require additional care here.  */
8081       coproc = 1;
8082       goto ld_st;
8083     case M_SWC2_AB:
8084       ab = 1;
8085     case M_SWC2_OB:
8086       s = "swc2";
8087       fmt = COP12_FMT;
8088       off12 = mips_opts.micromips;
8089       /* Itbl support may require additional care here.  */
8090       coproc = 1;
8091       goto ld_st;
8092     case M_SWC3_AB:
8093       ab = 1;
8094       gas_assert (!mips_opts.micromips);
8095       s = "swc3";
8096       fmt = "E,o(b)";
8097       /* Itbl support may require additional care here.  */
8098       coproc = 1;
8099       goto ld_st;
8100     case M_SWL_AB:
8101       ab = 1;
8102     case M_SWL_OB:
8103       s = "swl";
8104       fmt = MEM12_FMT;
8105       off12 = mips_opts.micromips;
8106       goto ld_st;
8107     case M_SWR_AB:
8108       ab = 1;
8109     case M_SWR_OB:
8110       s = "swr";
8111       fmt = MEM12_FMT;
8112       off12 = mips_opts.micromips;
8113       goto ld_st;
8114     case M_SC_AB:
8115       ab = 1;
8116     case M_SC_OB:
8117       s = "sc";
8118       fmt = MEM12_FMT;
8119       off12 = mips_opts.micromips;
8120       goto ld_st;
8121     case M_SCD_AB:
8122       ab = 1;
8123     case M_SCD_OB:
8124       s = "scd";
8125       fmt = MEM12_FMT;
8126       off12 = mips_opts.micromips;
8127       goto ld_st;
8128     case M_CACHE_AB:
8129       ab = 1;
8130     case M_CACHE_OB:
8131       s = "cache";
8132       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8133       off12 = mips_opts.micromips;
8134       goto ld_st;
8135     case M_PREF_AB:
8136       ab = 1;
8137     case M_PREF_OB:
8138       s = "pref";
8139       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8140       off12 = mips_opts.micromips;
8141       goto ld_st;
8142     case M_SDC1_AB:
8143       ab = 1;
8144       s = "sdc1";
8145       fmt = "T,o(b)";
8146       coproc = 1;
8147       /* Itbl support may require additional care here.  */
8148       goto ld_st;
8149     case M_SDC2_AB:
8150       ab = 1;
8151     case M_SDC2_OB:
8152       s = "sdc2";
8153       fmt = COP12_FMT;
8154       off12 = mips_opts.micromips;
8155       /* Itbl support may require additional care here.  */
8156       coproc = 1;
8157       goto ld_st;
8158     case M_SDC3_AB:
8159       ab = 1;
8160       gas_assert (!mips_opts.micromips);
8161       s = "sdc3";
8162       fmt = "E,o(b)";
8163       /* Itbl support may require additional care here.  */
8164       coproc = 1;
8165       goto ld_st;
8166     case M_SDL_AB:
8167       ab = 1;
8168     case M_SDL_OB:
8169       s = "sdl";
8170       fmt = MEM12_FMT;
8171       off12 = mips_opts.micromips;
8172       goto ld_st;
8173     case M_SDR_AB:
8174       ab = 1;
8175     case M_SDR_OB:
8176       s = "sdr";
8177       fmt = MEM12_FMT;
8178       off12 = mips_opts.micromips;
8179       goto ld_st;
8180     case M_SWP_AB:
8181       ab = 1;
8182     case M_SWP_OB:
8183       gas_assert (mips_opts.micromips);
8184       s = "swp";
8185       fmt = "t,~(b)";
8186       off12 = 1;
8187       goto ld_st;
8188     case M_SDP_AB:
8189       ab = 1;
8190     case M_SDP_OB:
8191       gas_assert (mips_opts.micromips);
8192       s = "sdp";
8193       fmt = "t,~(b)";
8194       off12 = 1;
8195       goto ld_st;
8196     case M_SWM_AB:
8197       ab = 1;
8198     case M_SWM_OB:
8199       gas_assert (mips_opts.micromips);
8200       s = "swm";
8201       fmt = "n,~(b)";
8202       off12 = 1;
8203       goto ld_st;
8204     case M_SDM_AB:
8205       ab = 1;
8206     case M_SDM_OB:
8207       gas_assert (mips_opts.micromips);
8208       s = "sdm";
8209       fmt = "n,~(b)";
8210       off12 = 1;
8211
8212     ld_st:
8213       tempreg = AT;
8214       used_at = 1;
8215     ld_noat:
8216       if (coproc
8217           && NO_ISA_COP (mips_opts.arch)
8218           && (ip->insn_mo->pinfo2 & (INSN2_M_FP_S | INSN2_M_FP_D)) == 0)
8219         {
8220           as_bad (_("Opcode not supported on this processor: %s"),
8221                   mips_cpu_info_from_arch (mips_opts.arch)->name);
8222           break;
8223         }
8224
8225       if (offset_expr.X_op != O_constant
8226           && offset_expr.X_op != O_symbol)
8227         {
8228           as_bad (_("Expression too complex"));
8229           offset_expr.X_op = O_constant;
8230         }
8231
8232       if (HAVE_32BIT_ADDRESSES
8233           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8234         {
8235           char value [32];
8236
8237           sprintf_vma (value, offset_expr.X_add_number);
8238           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8239         }
8240
8241       /* A constant expression in PIC code can be handled just as it
8242          is in non PIC code.  */
8243       if (offset_expr.X_op == O_constant)
8244         {
8245           int hipart = 0;
8246
8247           expr1.X_add_number = offset_expr.X_add_number;
8248           normalize_address_expr (&expr1);
8249           if (!off12 && !IS_SEXT_16BIT_NUM (expr1.X_add_number))
8250             {
8251               expr1.X_add_number = ((expr1.X_add_number + 0x8000)
8252                                     & ~(bfd_vma) 0xffff);
8253               hipart = 1;
8254             }
8255           else if (off12 && !IS_SEXT_12BIT_NUM (expr1.X_add_number))
8256             {
8257               expr1.X_add_number = ((expr1.X_add_number + 0x800)
8258                                     & ~(bfd_vma) 0xfff);
8259               hipart = 1;
8260             }
8261           if (hipart)
8262             {
8263               load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8264               if (breg != 0)
8265                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8266                              tempreg, tempreg, breg);
8267               breg = tempreg;
8268             }
8269           if (!off12)
8270             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, breg);
8271           else
8272             macro_build (NULL, s, fmt,
8273                          treg, (unsigned long) offset_expr.X_add_number, breg);
8274         }
8275       else if (off12)
8276         {
8277           /* A 12-bit offset field is too narrow to be used for a low-part
8278              relocation, so load the whole address into the auxillary
8279              register.  In the case of "A(b)" addresses, we first load
8280              absolute address "A" into the register and then add base
8281              register "b".  In the case of "o(b)" addresses, we simply
8282              need to add 16-bit offset "o" to base register "b", and
8283              offset_reloc already contains the relocations associated
8284              with "o".  */
8285           if (ab)
8286             {
8287               load_address (tempreg, &offset_expr, &used_at);
8288               if (breg != 0)
8289                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8290                              tempreg, tempreg, breg);
8291             }
8292           else
8293             macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8294                          tempreg, breg, -1,
8295                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8296           expr1.X_add_number = 0;
8297           macro_build (NULL, s, fmt,
8298                        treg, (unsigned long) expr1.X_add_number, tempreg);
8299         }
8300       else if (mips_pic == NO_PIC)
8301         {
8302           /* If this is a reference to a GP relative symbol, and there
8303              is no base register, we want
8304                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8305              Otherwise, if there is no base register, we want
8306                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8307                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8308              If we have a constant, we need two instructions anyhow,
8309              so we always use the latter form.
8310
8311              If we have a base register, and this is a reference to a
8312              GP relative symbol, we want
8313                addu     $tempreg,$breg,$gp
8314                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
8315              Otherwise we want
8316                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8317                addu     $tempreg,$tempreg,$breg
8318                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8319              With a constant we always use the latter case.
8320
8321              With 64bit address space and no base register and $at usable,
8322              we want
8323                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8324                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8325                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8326                dsll32   $tempreg,0
8327                daddu    $tempreg,$at
8328                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8329              If we have a base register, we want
8330                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8331                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8332                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8333                daddu    $at,$breg
8334                dsll32   $tempreg,0
8335                daddu    $tempreg,$at
8336                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8337
8338              Without $at we can't generate the optimal path for superscalar
8339              processors here since this would require two temporary registers.
8340                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8341                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8342                dsll     $tempreg,16
8343                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8344                dsll     $tempreg,16
8345                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8346              If we have a base register, we want
8347                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8348                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8349                dsll     $tempreg,16
8350                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8351                dsll     $tempreg,16
8352                daddu    $tempreg,$tempreg,$breg
8353                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
8354
8355              For GP relative symbols in 64bit address space we can use
8356              the same sequence as in 32bit address space.  */
8357           if (HAVE_64BIT_SYMBOLS)
8358             {
8359               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8360                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8361                 {
8362                   relax_start (offset_expr.X_add_symbol);
8363                   if (breg == 0)
8364                     {
8365                       macro_build (&offset_expr, s, fmt, treg,
8366                                    BFD_RELOC_GPREL16, mips_gp_register);
8367                     }
8368                   else
8369                     {
8370                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8371                                    tempreg, breg, mips_gp_register);
8372                       macro_build (&offset_expr, s, fmt, treg,
8373                                    BFD_RELOC_GPREL16, tempreg);
8374                     }
8375                   relax_switch ();
8376                 }
8377
8378               if (used_at == 0 && mips_opts.at)
8379                 {
8380                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8381                                BFD_RELOC_MIPS_HIGHEST);
8382                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
8383                                BFD_RELOC_HI16_S);
8384                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8385                                tempreg, BFD_RELOC_MIPS_HIGHER);
8386                   if (breg != 0)
8387                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
8388                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8389                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8390                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
8391                                tempreg);
8392                   used_at = 1;
8393                 }
8394               else
8395                 {
8396                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8397                                BFD_RELOC_MIPS_HIGHEST);
8398                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8399                                tempreg, BFD_RELOC_MIPS_HIGHER);
8400                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8401                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
8402                                tempreg, BFD_RELOC_HI16_S);
8403                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8404                   if (breg != 0)
8405                     macro_build (NULL, "daddu", "d,v,t",
8406                                  tempreg, tempreg, breg);
8407                   macro_build (&offset_expr, s, fmt, treg,
8408                                BFD_RELOC_LO16, tempreg);
8409                 }
8410
8411               if (mips_relax.sequence)
8412                 relax_end ();
8413               break;
8414             }
8415
8416           if (breg == 0)
8417             {
8418               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8419                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8420                 {
8421                   relax_start (offset_expr.X_add_symbol);
8422                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
8423                                mips_gp_register);
8424                   relax_switch ();
8425                 }
8426               macro_build_lui (&offset_expr, tempreg);
8427               macro_build (&offset_expr, s, fmt, treg,
8428                            BFD_RELOC_LO16, tempreg);
8429               if (mips_relax.sequence)
8430                 relax_end ();
8431             }
8432           else
8433             {
8434               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8435                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8436                 {
8437                   relax_start (offset_expr.X_add_symbol);
8438                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8439                                tempreg, breg, mips_gp_register);
8440                   macro_build (&offset_expr, s, fmt, treg,
8441                                BFD_RELOC_GPREL16, tempreg);
8442                   relax_switch ();
8443                 }
8444               macro_build_lui (&offset_expr, tempreg);
8445               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8446                            tempreg, tempreg, breg);
8447               macro_build (&offset_expr, s, fmt, treg,
8448                            BFD_RELOC_LO16, tempreg);
8449               if (mips_relax.sequence)
8450                 relax_end ();
8451             }
8452         }
8453       else if (!mips_big_got)
8454         {
8455           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8456
8457           /* If this is a reference to an external symbol, we want
8458                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8459                nop
8460                <op>     $treg,0($tempreg)
8461              Otherwise we want
8462                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8463                nop
8464                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8465                <op>     $treg,0($tempreg)
8466
8467              For NewABI, we want
8468                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8469                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
8470
8471              If there is a base register, we add it to $tempreg before
8472              the <op>.  If there is a constant, we stick it in the
8473              <op> instruction.  We don't handle constants larger than
8474              16 bits, because we have no way to load the upper 16 bits
8475              (actually, we could handle them for the subset of cases
8476              in which we are not using $at).  */
8477           gas_assert (offset_expr.X_op == O_symbol);
8478           if (HAVE_NEWABI)
8479             {
8480               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8481                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8482               if (breg != 0)
8483                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8484                              tempreg, tempreg, breg);
8485               macro_build (&offset_expr, s, fmt, treg,
8486                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
8487               break;
8488             }
8489           expr1.X_add_number = offset_expr.X_add_number;
8490           offset_expr.X_add_number = 0;
8491           if (expr1.X_add_number < -0x8000
8492               || expr1.X_add_number >= 0x8000)
8493             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8494           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8495                        lw_reloc_type, mips_gp_register);
8496           load_delay_nop ();
8497           relax_start (offset_expr.X_add_symbol);
8498           relax_switch ();
8499           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8500                        tempreg, BFD_RELOC_LO16);
8501           relax_end ();
8502           if (breg != 0)
8503             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8504                          tempreg, tempreg, breg);
8505           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8506         }
8507       else if (mips_big_got && !HAVE_NEWABI)
8508         {
8509           int gpdelay;
8510
8511           /* If this is a reference to an external symbol, we want
8512                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8513                addu     $tempreg,$tempreg,$gp
8514                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8515                <op>     $treg,0($tempreg)
8516              Otherwise we want
8517                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8518                nop
8519                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8520                <op>     $treg,0($tempreg)
8521              If there is a base register, we add it to $tempreg before
8522              the <op>.  If there is a constant, we stick it in the
8523              <op> instruction.  We don't handle constants larger than
8524              16 bits, because we have no way to load the upper 16 bits
8525              (actually, we could handle them for the subset of cases
8526              in which we are not using $at).  */
8527           gas_assert (offset_expr.X_op == O_symbol);
8528           expr1.X_add_number = offset_expr.X_add_number;
8529           offset_expr.X_add_number = 0;
8530           if (expr1.X_add_number < -0x8000
8531               || expr1.X_add_number >= 0x8000)
8532             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8533           gpdelay = reg_needs_delay (mips_gp_register);
8534           relax_start (offset_expr.X_add_symbol);
8535           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8536                        BFD_RELOC_MIPS_GOT_HI16);
8537           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
8538                        mips_gp_register);
8539           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8540                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
8541           relax_switch ();
8542           if (gpdelay)
8543             macro_build (NULL, "nop", "");
8544           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8545                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8546           load_delay_nop ();
8547           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8548                        tempreg, BFD_RELOC_LO16);
8549           relax_end ();
8550
8551           if (breg != 0)
8552             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8553                          tempreg, tempreg, breg);
8554           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8555         }
8556       else if (mips_big_got && HAVE_NEWABI)
8557         {
8558           /* If this is a reference to an external symbol, we want
8559                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8560                add      $tempreg,$tempreg,$gp
8561                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8562                <op>     $treg,<ofst>($tempreg)
8563              Otherwise, for local symbols, we want:
8564                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
8565                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
8566           gas_assert (offset_expr.X_op == O_symbol);
8567           expr1.X_add_number = offset_expr.X_add_number;
8568           offset_expr.X_add_number = 0;
8569           if (expr1.X_add_number < -0x8000
8570               || expr1.X_add_number >= 0x8000)
8571             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8572           relax_start (offset_expr.X_add_symbol);
8573           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
8574                        BFD_RELOC_MIPS_GOT_HI16);
8575           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
8576                        mips_gp_register);
8577           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8578                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
8579           if (breg != 0)
8580             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8581                          tempreg, tempreg, breg);
8582           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8583
8584           relax_switch ();
8585           offset_expr.X_add_number = expr1.X_add_number;
8586           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8587                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8588           if (breg != 0)
8589             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8590                          tempreg, tempreg, breg);
8591           macro_build (&offset_expr, s, fmt, treg,
8592                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
8593           relax_end ();
8594         }
8595       else
8596         abort ();
8597
8598       break;
8599
8600     case M_LI:
8601     case M_LI_S:
8602       load_register (treg, &imm_expr, 0);
8603       break;
8604
8605     case M_DLI:
8606       load_register (treg, &imm_expr, 1);
8607       break;
8608
8609     case M_LI_SS:
8610       if (imm_expr.X_op == O_constant)
8611         {
8612           used_at = 1;
8613           load_register (AT, &imm_expr, 0);
8614           macro_build (NULL, "mtc1", "t,G", AT, treg);
8615           break;
8616         }
8617       else
8618         {
8619           gas_assert (offset_expr.X_op == O_symbol
8620                       && strcmp (segment_name (S_GET_SEGMENT
8621                                                (offset_expr.X_add_symbol)),
8622                                  ".lit4") == 0
8623                       && offset_expr.X_add_number == 0);
8624           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
8625                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8626           break;
8627         }
8628
8629     case M_LI_D:
8630       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
8631          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
8632          order 32 bits of the value and the low order 32 bits are either
8633          zero or in OFFSET_EXPR.  */
8634       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8635         {
8636           if (HAVE_64BIT_GPRS)
8637             load_register (treg, &imm_expr, 1);
8638           else
8639             {
8640               int hreg, lreg;
8641
8642               if (target_big_endian)
8643                 {
8644                   hreg = treg;
8645                   lreg = treg + 1;
8646                 }
8647               else
8648                 {
8649                   hreg = treg + 1;
8650                   lreg = treg;
8651                 }
8652
8653               if (hreg <= 31)
8654                 load_register (hreg, &imm_expr, 0);
8655               if (lreg <= 31)
8656                 {
8657                   if (offset_expr.X_op == O_absent)
8658                     move_register (lreg, 0);
8659                   else
8660                     {
8661                       gas_assert (offset_expr.X_op == O_constant);
8662                       load_register (lreg, &offset_expr, 0);
8663                     }
8664                 }
8665             }
8666           break;
8667         }
8668
8669       /* We know that sym is in the .rdata section.  First we get the
8670          upper 16 bits of the address.  */
8671       if (mips_pic == NO_PIC)
8672         {
8673           macro_build_lui (&offset_expr, AT);
8674           used_at = 1;
8675         }
8676       else
8677         {
8678           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8679                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8680           used_at = 1;
8681         }
8682
8683       /* Now we load the register(s).  */
8684       if (HAVE_64BIT_GPRS)
8685         {
8686           used_at = 1;
8687           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8688         }
8689       else
8690         {
8691           used_at = 1;
8692           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
8693           if (treg != RA)
8694             {
8695               /* FIXME: How in the world do we deal with the possible
8696                  overflow here?  */
8697               offset_expr.X_add_number += 4;
8698               macro_build (&offset_expr, "lw", "t,o(b)",
8699                            treg + 1, BFD_RELOC_LO16, AT);
8700             }
8701         }
8702       break;
8703
8704     case M_LI_DD:
8705       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
8706          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
8707          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
8708          the value and the low order 32 bits are either zero or in
8709          OFFSET_EXPR.  */
8710       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
8711         {
8712           used_at = 1;
8713           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
8714           if (HAVE_64BIT_FPRS)
8715             {
8716               gas_assert (HAVE_64BIT_GPRS);
8717               macro_build (NULL, "dmtc1", "t,S", AT, treg);
8718             }
8719           else
8720             {
8721               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
8722               if (offset_expr.X_op == O_absent)
8723                 macro_build (NULL, "mtc1", "t,G", 0, treg);
8724               else
8725                 {
8726                   gas_assert (offset_expr.X_op == O_constant);
8727                   load_register (AT, &offset_expr, 0);
8728                   macro_build (NULL, "mtc1", "t,G", AT, treg);
8729                 }
8730             }
8731           break;
8732         }
8733
8734       gas_assert (offset_expr.X_op == O_symbol
8735                   && offset_expr.X_add_number == 0);
8736       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
8737       if (strcmp (s, ".lit8") == 0)
8738         {
8739           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8740             {
8741               macro_build (&offset_expr, "ldc1", "T,o(b)", treg,
8742                            BFD_RELOC_MIPS_LITERAL, mips_gp_register);
8743               break;
8744             }
8745           breg = mips_gp_register;
8746           r = BFD_RELOC_MIPS_LITERAL;
8747           goto dob;
8748         }
8749       else
8750         {
8751           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
8752           used_at = 1;
8753           if (mips_pic != NO_PIC)
8754             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
8755                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
8756           else
8757             {
8758               /* FIXME: This won't work for a 64 bit address.  */
8759               macro_build_lui (&offset_expr, AT);
8760             }
8761
8762           if (mips_opts.isa != ISA_MIPS1 || mips_opts.micromips)
8763             {
8764               macro_build (&offset_expr, "ldc1", "T,o(b)",
8765                            treg, BFD_RELOC_LO16, AT);
8766               break;
8767             }
8768           breg = AT;
8769           r = BFD_RELOC_LO16;
8770           goto dob;
8771         }
8772
8773     case M_L_DOB:
8774       /* Even on a big endian machine $fn comes before $fn+1.  We have
8775          to adjust when loading from memory.  */
8776       r = BFD_RELOC_LO16;
8777     dob:
8778       gas_assert (!mips_opts.micromips);
8779       gas_assert (mips_opts.isa == ISA_MIPS1);
8780       macro_build (&offset_expr, "lwc1", "T,o(b)",
8781                    target_big_endian ? treg + 1 : treg, r, breg);
8782       /* FIXME: A possible overflow which I don't know how to deal
8783          with.  */
8784       offset_expr.X_add_number += 4;
8785       macro_build (&offset_expr, "lwc1", "T,o(b)",
8786                    target_big_endian ? treg : treg + 1, r, breg);
8787       break;
8788
8789     case M_S_DOB:
8790       gas_assert (!mips_opts.micromips);
8791       gas_assert (mips_opts.isa == ISA_MIPS1);
8792       /* Even on a big endian machine $fn comes before $fn+1.  We have
8793          to adjust when storing to memory.  */
8794       macro_build (&offset_expr, "swc1", "T,o(b)",
8795                    target_big_endian ? treg + 1 : treg, BFD_RELOC_LO16, breg);
8796       offset_expr.X_add_number += 4;
8797       macro_build (&offset_expr, "swc1", "T,o(b)",
8798                    target_big_endian ? treg : treg + 1, BFD_RELOC_LO16, breg);
8799       break;
8800
8801     case M_L_DAB:
8802       gas_assert (!mips_opts.micromips);
8803       /*
8804        * The MIPS assembler seems to check for X_add_number not
8805        * being double aligned and generating:
8806        *        lui     at,%hi(foo+1)
8807        *        addu    at,at,v1
8808        *        addiu   at,at,%lo(foo+1)
8809        *        lwc1    f2,0(at)
8810        *        lwc1    f3,4(at)
8811        * But, the resulting address is the same after relocation so why
8812        * generate the extra instruction?
8813        */
8814       /* Itbl support may require additional care here.  */
8815       coproc = 1;
8816       fmt = "T,o(b)";
8817       if (mips_opts.isa != ISA_MIPS1)
8818         {
8819           s = "ldc1";
8820           goto ld_st;
8821         }
8822       s = "lwc1";
8823       goto ldd_std;
8824
8825     case M_S_DAB:
8826       gas_assert (!mips_opts.micromips);
8827       /* Itbl support may require additional care here.  */
8828       coproc = 1;
8829       fmt = "T,o(b)";
8830       if (mips_opts.isa != ISA_MIPS1)
8831         {
8832           s = "sdc1";
8833           goto ld_st;
8834         }
8835       s = "swc1";
8836       goto ldd_std;
8837
8838     case M_LD_AB:
8839       fmt = "t,o(b)";
8840       if (HAVE_64BIT_GPRS)
8841         {
8842           s = "ld";
8843           goto ld;
8844         }
8845       s = "lw";
8846       goto ldd_std;
8847
8848     case M_SD_AB:
8849       fmt = "t,o(b)";
8850       if (HAVE_64BIT_GPRS)
8851         {
8852           s = "sd";
8853           goto ld_st;
8854         }
8855       s = "sw";
8856
8857     ldd_std:
8858       if (offset_expr.X_op != O_symbol
8859           && offset_expr.X_op != O_constant)
8860         {
8861           as_bad (_("Expression too complex"));
8862           offset_expr.X_op = O_constant;
8863         }
8864
8865       if (HAVE_32BIT_ADDRESSES
8866           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8867         {
8868           char value [32];
8869
8870           sprintf_vma (value, offset_expr.X_add_number);
8871           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8872         }
8873
8874       /* Even on a big endian machine $fn comes before $fn+1.  We have
8875          to adjust when loading from memory.  We set coproc if we must
8876          load $fn+1 first.  */
8877       /* Itbl support may require additional care here.  */
8878       if (!target_big_endian)
8879         coproc = 0;
8880
8881       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
8882         {
8883           /* If this is a reference to a GP relative symbol, we want
8884                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8885                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
8886              If we have a base register, we use this
8887                addu     $at,$breg,$gp
8888                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
8889                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
8890              If this is not a GP relative symbol, we want
8891                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8892                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
8893                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
8894              If there is a base register, we add it to $at after the
8895              lui instruction.  If there is a constant, we always use
8896              the last case.  */
8897           if (offset_expr.X_op == O_symbol
8898               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8899               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8900             {
8901               relax_start (offset_expr.X_add_symbol);
8902               if (breg == 0)
8903                 {
8904                   tempreg = mips_gp_register;
8905                 }
8906               else
8907                 {
8908                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8909                                AT, breg, mips_gp_register);
8910                   tempreg = AT;
8911                   used_at = 1;
8912                 }
8913
8914               /* Itbl support may require additional care here.  */
8915               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8916                            BFD_RELOC_GPREL16, tempreg);
8917               offset_expr.X_add_number += 4;
8918
8919               /* Set mips_optimize to 2 to avoid inserting an
8920                  undesired nop.  */
8921               hold_mips_optimize = mips_optimize;
8922               mips_optimize = 2;
8923               /* Itbl support may require additional care here.  */
8924               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8925                            BFD_RELOC_GPREL16, tempreg);
8926               mips_optimize = hold_mips_optimize;
8927
8928               relax_switch ();
8929
8930               offset_expr.X_add_number -= 4;
8931             }
8932           used_at = 1;
8933           macro_build_lui (&offset_expr, AT);
8934           if (breg != 0)
8935             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
8936           /* Itbl support may require additional care here.  */
8937           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8938                        BFD_RELOC_LO16, AT);
8939           /* FIXME: How do we handle overflow here?  */
8940           offset_expr.X_add_number += 4;
8941           /* Itbl support may require additional care here.  */
8942           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8943                        BFD_RELOC_LO16, AT);
8944           if (mips_relax.sequence)
8945             relax_end ();
8946         }
8947       else if (!mips_big_got)
8948         {
8949           /* If this is a reference to an external symbol, we want
8950                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8951                nop
8952                <op>     $treg,0($at)
8953                <op>     $treg+1,4($at)
8954              Otherwise we want
8955                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8956                nop
8957                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
8958                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
8959              If there is a base register we add it to $at before the
8960              lwc1 instructions.  If there is a constant we include it
8961              in the lwc1 instructions.  */
8962           used_at = 1;
8963           expr1.X_add_number = offset_expr.X_add_number;
8964           if (expr1.X_add_number < -0x8000
8965               || expr1.X_add_number >= 0x8000 - 4)
8966             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8967           load_got_offset (AT, &offset_expr);
8968           load_delay_nop ();
8969           if (breg != 0)
8970             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
8971
8972           /* Set mips_optimize to 2 to avoid inserting an undesired
8973              nop.  */
8974           hold_mips_optimize = mips_optimize;
8975           mips_optimize = 2;
8976
8977           /* Itbl support may require additional care here.  */
8978           relax_start (offset_expr.X_add_symbol);
8979           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
8980                        BFD_RELOC_LO16, AT);
8981           expr1.X_add_number += 4;
8982           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
8983                        BFD_RELOC_LO16, AT);
8984           relax_switch ();
8985           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
8986                        BFD_RELOC_LO16, AT);
8987           offset_expr.X_add_number += 4;
8988           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
8989                        BFD_RELOC_LO16, AT);
8990           relax_end ();
8991
8992           mips_optimize = hold_mips_optimize;
8993         }
8994       else if (mips_big_got)
8995         {
8996           int gpdelay;
8997
8998           /* If this is a reference to an external symbol, we want
8999                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9000                addu     $at,$at,$gp
9001                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9002                nop
9003                <op>     $treg,0($at)
9004                <op>     $treg+1,4($at)
9005              Otherwise we want
9006                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9007                nop
9008                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9009                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9010              If there is a base register we add it to $at before the
9011              lwc1 instructions.  If there is a constant we include it
9012              in the lwc1 instructions.  */
9013           used_at = 1;
9014           expr1.X_add_number = offset_expr.X_add_number;
9015           offset_expr.X_add_number = 0;
9016           if (expr1.X_add_number < -0x8000
9017               || expr1.X_add_number >= 0x8000 - 4)
9018             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9019           gpdelay = reg_needs_delay (mips_gp_register);
9020           relax_start (offset_expr.X_add_symbol);
9021           macro_build (&offset_expr, "lui", LUI_FMT,
9022                        AT, BFD_RELOC_MIPS_GOT_HI16);
9023           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9024                        AT, AT, mips_gp_register);
9025           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9026                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9027           load_delay_nop ();
9028           if (breg != 0)
9029             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9030           /* Itbl support may require additional care here.  */
9031           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9032                        BFD_RELOC_LO16, AT);
9033           expr1.X_add_number += 4;
9034
9035           /* Set mips_optimize to 2 to avoid inserting an undesired
9036              nop.  */
9037           hold_mips_optimize = mips_optimize;
9038           mips_optimize = 2;
9039           /* Itbl support may require additional care here.  */
9040           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9041                        BFD_RELOC_LO16, AT);
9042           mips_optimize = hold_mips_optimize;
9043           expr1.X_add_number -= 4;
9044
9045           relax_switch ();
9046           offset_expr.X_add_number = expr1.X_add_number;
9047           if (gpdelay)
9048             macro_build (NULL, "nop", "");
9049           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9050                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9051           load_delay_nop ();
9052           if (breg != 0)
9053             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9054           /* Itbl support may require additional care here.  */
9055           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9056                        BFD_RELOC_LO16, AT);
9057           offset_expr.X_add_number += 4;
9058
9059           /* Set mips_optimize to 2 to avoid inserting an undesired
9060              nop.  */
9061           hold_mips_optimize = mips_optimize;
9062           mips_optimize = 2;
9063           /* Itbl support may require additional care here.  */
9064           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9065                        BFD_RELOC_LO16, AT);
9066           mips_optimize = hold_mips_optimize;
9067           relax_end ();
9068         }
9069       else
9070         abort ();
9071
9072       break;
9073
9074     case M_LD_OB:
9075       s = HAVE_64BIT_GPRS ? "ld" : "lw";
9076       goto sd_ob;
9077     case M_SD_OB:
9078       s = HAVE_64BIT_GPRS ? "sd" : "sw";
9079     sd_ob:
9080       macro_build (&offset_expr, s, "t,o(b)", treg,
9081                    -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9082                    breg);
9083       if (!HAVE_64BIT_GPRS)
9084         {
9085           offset_expr.X_add_number += 4;
9086           macro_build (&offset_expr, s, "t,o(b)", treg + 1,
9087                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2],
9088                        breg);
9089         }
9090       break;
9091
9092    /* New code added to support COPZ instructions.
9093       This code builds table entries out of the macros in mip_opcodes.
9094       R4000 uses interlocks to handle coproc delays.
9095       Other chips (like the R3000) require nops to be inserted for delays.
9096
9097       FIXME: Currently, we require that the user handle delays.
9098       In order to fill delay slots for non-interlocked chips,
9099       we must have a way to specify delays based on the coprocessor.
9100       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9101       What are the side-effects of the cop instruction?
9102       What cache support might we have and what are its effects?
9103       Both coprocessor & memory require delays. how long???
9104       What registers are read/set/modified?
9105
9106       If an itbl is provided to interpret cop instructions,
9107       this knowledge can be encoded in the itbl spec.  */
9108
9109     case M_COP0:
9110       s = "c0";
9111       goto copz;
9112     case M_COP1:
9113       s = "c1";
9114       goto copz;
9115     case M_COP2:
9116       s = "c2";
9117       goto copz;
9118     case M_COP3:
9119       s = "c3";
9120     copz:
9121       gas_assert (!mips_opts.micromips);
9122       if (NO_ISA_COP (mips_opts.arch)
9123           && (ip->insn_mo->pinfo2 & INSN2_M_FP_S) == 0)
9124         {
9125           as_bad (_("opcode not supported on this processor: %s"),
9126                   mips_cpu_info_from_arch (mips_opts.arch)->name);
9127           break;
9128         }
9129
9130       /* For now we just do C (same as Cz).  The parameter will be
9131          stored in insn_opcode by mips_ip.  */
9132       macro_build (NULL, s, "C", ip->insn_opcode);
9133       break;
9134
9135     case M_MOVE:
9136       move_register (dreg, sreg);
9137       break;
9138
9139     case M_DMUL:
9140       dbl = 1;
9141     case M_MUL:
9142       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9143       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9144       break;
9145
9146     case M_DMUL_I:
9147       dbl = 1;
9148     case M_MUL_I:
9149       /* The MIPS assembler some times generates shifts and adds.  I'm
9150          not trying to be that fancy. GCC should do this for us
9151          anyway.  */
9152       used_at = 1;
9153       load_register (AT, &imm_expr, dbl);
9154       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9155       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9156       break;
9157
9158     case M_DMULO_I:
9159       dbl = 1;
9160     case M_MULO_I:
9161       imm = 1;
9162       goto do_mulo;
9163
9164     case M_DMULO:
9165       dbl = 1;
9166     case M_MULO:
9167     do_mulo:
9168       start_noreorder ();
9169       used_at = 1;
9170       if (imm)
9171         load_register (AT, &imm_expr, dbl);
9172       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9173       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9174       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9175       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9176       if (mips_trap)
9177         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9178       else
9179         {
9180           if (mips_opts.micromips)
9181             micromips_label_expr (&label_expr);
9182           else
9183             label_expr.X_add_number = 8;
9184           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9185           macro_build (NULL, "nop", "");
9186           macro_build (NULL, "break", BRK_FMT, 6);
9187           if (mips_opts.micromips)
9188             micromips_add_label ();
9189         }
9190       end_noreorder ();
9191       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9192       break;
9193
9194     case M_DMULOU_I:
9195       dbl = 1;
9196     case M_MULOU_I:
9197       imm = 1;
9198       goto do_mulou;
9199
9200     case M_DMULOU:
9201       dbl = 1;
9202     case M_MULOU:
9203     do_mulou:
9204       start_noreorder ();
9205       used_at = 1;
9206       if (imm)
9207         load_register (AT, &imm_expr, dbl);
9208       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9209                    sreg, imm ? AT : treg);
9210       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9211       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9212       if (mips_trap)
9213         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9214       else
9215         {
9216           if (mips_opts.micromips)
9217             micromips_label_expr (&label_expr);
9218           else
9219             label_expr.X_add_number = 8;
9220           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9221           macro_build (NULL, "nop", "");
9222           macro_build (NULL, "break", BRK_FMT, 6);
9223           if (mips_opts.micromips)
9224             micromips_add_label ();
9225         }
9226       end_noreorder ();
9227       break;
9228
9229     case M_DROL:
9230       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9231         {
9232           if (dreg == sreg)
9233             {
9234               tempreg = AT;
9235               used_at = 1;
9236             }
9237           else
9238             {
9239               tempreg = dreg;
9240             }
9241           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9242           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9243           break;
9244         }
9245       used_at = 1;
9246       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9247       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9248       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9249       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9250       break;
9251
9252     case M_ROL:
9253       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9254         {
9255           if (dreg == sreg)
9256             {
9257               tempreg = AT;
9258               used_at = 1;
9259             }
9260           else
9261             {
9262               tempreg = dreg;
9263             }
9264           macro_build (NULL, "negu", "d,w", tempreg, treg);
9265           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
9266           break;
9267         }
9268       used_at = 1;
9269       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9270       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
9271       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
9272       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9273       break;
9274
9275     case M_DROL_I:
9276       {
9277         unsigned int rot;
9278         char *l;
9279         char *rr;
9280
9281         if (imm_expr.X_op != O_constant)
9282           as_bad (_("Improper rotate count"));
9283         rot = imm_expr.X_add_number & 0x3f;
9284         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9285           {
9286             rot = (64 - rot) & 0x3f;
9287             if (rot >= 32)
9288               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9289             else
9290               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9291             break;
9292           }
9293         if (rot == 0)
9294           {
9295             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9296             break;
9297           }
9298         l = (rot < 0x20) ? "dsll" : "dsll32";
9299         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
9300         rot &= 0x1f;
9301         used_at = 1;
9302         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
9303         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9304         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9305       }
9306       break;
9307
9308     case M_ROL_I:
9309       {
9310         unsigned int rot;
9311
9312         if (imm_expr.X_op != O_constant)
9313           as_bad (_("Improper rotate count"));
9314         rot = imm_expr.X_add_number & 0x1f;
9315         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9316           {
9317             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
9318             break;
9319           }
9320         if (rot == 0)
9321           {
9322             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9323             break;
9324           }
9325         used_at = 1;
9326         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
9327         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9328         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9329       }
9330       break;
9331
9332     case M_DROR:
9333       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9334         {
9335           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
9336           break;
9337         }
9338       used_at = 1;
9339       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9340       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
9341       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
9342       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9343       break;
9344
9345     case M_ROR:
9346       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9347         {
9348           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
9349           break;
9350         }
9351       used_at = 1;
9352       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
9353       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
9354       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
9355       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9356       break;
9357
9358     case M_DROR_I:
9359       {
9360         unsigned int rot;
9361         char *l;
9362         char *rr;
9363
9364         if (imm_expr.X_op != O_constant)
9365           as_bad (_("Improper rotate count"));
9366         rot = imm_expr.X_add_number & 0x3f;
9367         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9368           {
9369             if (rot >= 32)
9370               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
9371             else
9372               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
9373             break;
9374           }
9375         if (rot == 0)
9376           {
9377             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
9378             break;
9379           }
9380         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
9381         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
9382         rot &= 0x1f;
9383         used_at = 1;
9384         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
9385         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9386         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9387       }
9388       break;
9389
9390     case M_ROR_I:
9391       {
9392         unsigned int rot;
9393
9394         if (imm_expr.X_op != O_constant)
9395           as_bad (_("Improper rotate count"));
9396         rot = imm_expr.X_add_number & 0x1f;
9397         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9398           {
9399             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
9400             break;
9401           }
9402         if (rot == 0)
9403           {
9404             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
9405             break;
9406           }
9407         used_at = 1;
9408         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
9409         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
9410         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9411       }
9412       break;
9413
9414     case M_SEQ:
9415       if (sreg == 0)
9416         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
9417       else if (treg == 0)
9418         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9419       else
9420         {
9421           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9422           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9423         }
9424       break;
9425
9426     case M_SEQ_I:
9427       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9428         {
9429           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9430           break;
9431         }
9432       if (sreg == 0)
9433         {
9434           as_warn (_("Instruction %s: result is always false"),
9435                    ip->insn_mo->name);
9436           move_register (dreg, 0);
9437           break;
9438         }
9439       if (CPU_HAS_SEQ (mips_opts.arch)
9440           && -512 <= imm_expr.X_add_number
9441           && imm_expr.X_add_number < 512)
9442         {
9443           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
9444                        (int) imm_expr.X_add_number);
9445           break;
9446         }
9447       if (imm_expr.X_op == O_constant
9448           && imm_expr.X_add_number >= 0
9449           && imm_expr.X_add_number < 0x10000)
9450         {
9451           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9452         }
9453       else if (imm_expr.X_op == O_constant
9454                && imm_expr.X_add_number > -0x8000
9455                && imm_expr.X_add_number < 0)
9456         {
9457           imm_expr.X_add_number = -imm_expr.X_add_number;
9458           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9459                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9460         }
9461       else if (CPU_HAS_SEQ (mips_opts.arch))
9462         {
9463           used_at = 1;
9464           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9465           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
9466           break;
9467         }
9468       else
9469         {
9470           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9471           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9472           used_at = 1;
9473         }
9474       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
9475       break;
9476
9477     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
9478       s = "slt";
9479       goto sge;
9480     case M_SGEU:
9481       s = "sltu";
9482     sge:
9483       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
9484       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9485       break;
9486
9487     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
9488     case M_SGEU_I:
9489       if (imm_expr.X_op == O_constant
9490           && imm_expr.X_add_number >= -0x8000
9491           && imm_expr.X_add_number < 0x8000)
9492         {
9493           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
9494                        dreg, sreg, BFD_RELOC_LO16);
9495         }
9496       else
9497         {
9498           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9499           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
9500                        dreg, sreg, AT);
9501           used_at = 1;
9502         }
9503       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9504       break;
9505
9506     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
9507       s = "slt";
9508       goto sgt;
9509     case M_SGTU:
9510       s = "sltu";
9511     sgt:
9512       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9513       break;
9514
9515     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
9516       s = "slt";
9517       goto sgti;
9518     case M_SGTU_I:
9519       s = "sltu";
9520     sgti:
9521       used_at = 1;
9522       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9523       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9524       break;
9525
9526     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
9527       s = "slt";
9528       goto sle;
9529     case M_SLEU:
9530       s = "sltu";
9531     sle:
9532       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
9533       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9534       break;
9535
9536     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
9537       s = "slt";
9538       goto slei;
9539     case M_SLEU_I:
9540       s = "sltu";
9541     slei:
9542       used_at = 1;
9543       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9544       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
9545       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
9546       break;
9547
9548     case M_SLT_I:
9549       if (imm_expr.X_op == O_constant
9550           && imm_expr.X_add_number >= -0x8000
9551           && imm_expr.X_add_number < 0x8000)
9552         {
9553           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9554           break;
9555         }
9556       used_at = 1;
9557       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9558       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
9559       break;
9560
9561     case M_SLTU_I:
9562       if (imm_expr.X_op == O_constant
9563           && imm_expr.X_add_number >= -0x8000
9564           && imm_expr.X_add_number < 0x8000)
9565         {
9566           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
9567                        BFD_RELOC_LO16);
9568           break;
9569         }
9570       used_at = 1;
9571       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9572       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
9573       break;
9574
9575     case M_SNE:
9576       if (sreg == 0)
9577         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
9578       else if (treg == 0)
9579         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9580       else
9581         {
9582           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
9583           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9584         }
9585       break;
9586
9587     case M_SNE_I:
9588       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
9589         {
9590           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
9591           break;
9592         }
9593       if (sreg == 0)
9594         {
9595           as_warn (_("Instruction %s: result is always true"),
9596                    ip->insn_mo->name);
9597           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
9598                        dreg, 0, BFD_RELOC_LO16);
9599           break;
9600         }
9601       if (CPU_HAS_SEQ (mips_opts.arch)
9602           && -512 <= imm_expr.X_add_number
9603           && imm_expr.X_add_number < 512)
9604         {
9605           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
9606                        (int) imm_expr.X_add_number);
9607           break;
9608         }
9609       if (imm_expr.X_op == O_constant
9610           && imm_expr.X_add_number >= 0
9611           && imm_expr.X_add_number < 0x10000)
9612         {
9613           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
9614         }
9615       else if (imm_expr.X_op == O_constant
9616                && imm_expr.X_add_number > -0x8000
9617                && imm_expr.X_add_number < 0)
9618         {
9619           imm_expr.X_add_number = -imm_expr.X_add_number;
9620           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
9621                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9622         }
9623       else if (CPU_HAS_SEQ (mips_opts.arch))
9624         {
9625           used_at = 1;
9626           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9627           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
9628           break;
9629         }
9630       else
9631         {
9632           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9633           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
9634           used_at = 1;
9635         }
9636       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
9637       break;
9638
9639     case M_SUB_I:
9640       s = "addi";
9641       s2 = "sub";
9642       goto do_subi;
9643     case M_SUBU_I:
9644       s = "addiu";
9645       s2 = "subu";
9646       goto do_subi;
9647     case M_DSUB_I:
9648       dbl = 1;
9649       s = "daddi";
9650       s2 = "dsub";
9651       if (!mips_opts.micromips)
9652         goto do_subi;
9653       if (imm_expr.X_op == O_constant
9654           && imm_expr.X_add_number > -0x200
9655           && imm_expr.X_add_number <= 0x200)
9656         {
9657           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
9658           break;
9659         }
9660       goto do_subi_i;
9661     case M_DSUBU_I:
9662       dbl = 1;
9663       s = "daddiu";
9664       s2 = "dsubu";
9665     do_subi:
9666       if (imm_expr.X_op == O_constant
9667           && imm_expr.X_add_number > -0x8000
9668           && imm_expr.X_add_number <= 0x8000)
9669         {
9670           imm_expr.X_add_number = -imm_expr.X_add_number;
9671           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
9672           break;
9673         }
9674     do_subi_i:
9675       used_at = 1;
9676       load_register (AT, &imm_expr, dbl);
9677       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
9678       break;
9679
9680     case M_TEQ_I:
9681       s = "teq";
9682       goto trap;
9683     case M_TGE_I:
9684       s = "tge";
9685       goto trap;
9686     case M_TGEU_I:
9687       s = "tgeu";
9688       goto trap;
9689     case M_TLT_I:
9690       s = "tlt";
9691       goto trap;
9692     case M_TLTU_I:
9693       s = "tltu";
9694       goto trap;
9695     case M_TNE_I:
9696       s = "tne";
9697     trap:
9698       used_at = 1;
9699       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9700       macro_build (NULL, s, "s,t", sreg, AT);
9701       break;
9702
9703     case M_TRUNCWS:
9704     case M_TRUNCWD:
9705       gas_assert (!mips_opts.micromips);
9706       gas_assert (mips_opts.isa == ISA_MIPS1);
9707       used_at = 1;
9708       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
9709       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
9710
9711       /*
9712        * Is the double cfc1 instruction a bug in the mips assembler;
9713        * or is there a reason for it?
9714        */
9715       start_noreorder ();
9716       macro_build (NULL, "cfc1", "t,G", treg, RA);
9717       macro_build (NULL, "cfc1", "t,G", treg, RA);
9718       macro_build (NULL, "nop", "");
9719       expr1.X_add_number = 3;
9720       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
9721       expr1.X_add_number = 2;
9722       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
9723       macro_build (NULL, "ctc1", "t,G", AT, RA);
9724       macro_build (NULL, "nop", "");
9725       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
9726                    dreg, sreg);
9727       macro_build (NULL, "ctc1", "t,G", treg, RA);
9728       macro_build (NULL, "nop", "");
9729       end_noreorder ();
9730       break;
9731
9732     case M_ULH_A:
9733       ab = 1;
9734     case M_ULH:
9735       s = "lb";
9736       s2 = "lbu";
9737       off = 1;
9738       goto uld_st;
9739     case M_ULHU_A:
9740       ab = 1;
9741     case M_ULHU:
9742       s = "lbu";
9743       s2 = "lbu";
9744       off = 1;
9745       goto uld_st;
9746     case M_ULW_A:
9747       ab = 1;
9748     case M_ULW:
9749       s = "lwl";
9750       s2 = "lwr";
9751       off12 = mips_opts.micromips;
9752       off = 3;
9753       goto uld_st;
9754     case M_ULD_A:
9755       ab = 1;
9756     case M_ULD:
9757       s = "ldl";
9758       s2 = "ldr";
9759       off12 = mips_opts.micromips;
9760       off = 7;
9761       goto uld_st;
9762     case M_USH_A:
9763       ab = 1;
9764     case M_USH:
9765       s = "sb";
9766       s2 = "sb";
9767       off = 1;
9768       ust = 1;
9769       goto uld_st;
9770     case M_USW_A:
9771       ab = 1;
9772     case M_USW:
9773       s = "swl";
9774       s2 = "swr";
9775       off12 = mips_opts.micromips;
9776       off = 3;
9777       ust = 1;
9778       goto uld_st;
9779     case M_USD_A:
9780       ab = 1;
9781     case M_USD:
9782       s = "sdl";
9783       s2 = "sdr";
9784       off12 = mips_opts.micromips;
9785       off = 7;
9786       ust = 1;
9787
9788     uld_st:
9789       if (!ab && offset_expr.X_add_number >= 0x8000 - off)
9790         as_bad (_("Operand overflow"));
9791
9792       ep = &offset_expr;
9793       expr1.X_add_number = 0;
9794       if (ab)
9795         {
9796           used_at = 1;
9797           tempreg = AT;
9798           load_address (tempreg, ep, &used_at);
9799           if (breg != 0)
9800             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9801                          tempreg, tempreg, breg);
9802           breg = tempreg;
9803           tempreg = treg;
9804           ep = &expr1;
9805         }
9806       else if (off12
9807                && (offset_expr.X_op != O_constant
9808                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number)
9809                    || !IS_SEXT_12BIT_NUM (offset_expr.X_add_number + off)))
9810         {
9811           used_at = 1;
9812           tempreg = AT;
9813           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg,
9814                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9815           breg = tempreg;
9816           tempreg = treg;
9817           ep = &expr1;
9818         }
9819       else if (!ust && treg == breg)
9820         {
9821           used_at = 1;
9822           tempreg = AT;
9823         }
9824       else
9825         tempreg = treg;
9826
9827       if (off == 1)
9828         goto ulh_sh;
9829
9830       if (!target_big_endian)
9831         ep->X_add_number += off;
9832       if (!off12)
9833         macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9834       else
9835         macro_build (NULL, s, "t,~(b)",
9836                      tempreg, (unsigned long) ep->X_add_number, breg);
9837
9838       if (!target_big_endian)
9839         ep->X_add_number -= off;
9840       else
9841         ep->X_add_number += off;
9842       if (!off12)
9843         macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9844       else
9845         macro_build (NULL, s2, "t,~(b)",
9846                      tempreg, (unsigned long) ep->X_add_number, breg);
9847
9848       /* If necessary, move the result in tempreg to the final destination.  */
9849       if (!ust && treg != tempreg)
9850         {
9851           /* Protect second load's delay slot.  */
9852           load_delay_nop ();
9853           move_register (treg, tempreg);
9854         }
9855       break;
9856
9857     ulh_sh:
9858       used_at = 1;
9859       if (target_big_endian == ust)
9860         ep->X_add_number += off;
9861       tempreg = ust || ab ? treg : AT;
9862       macro_build (ep, s, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9863
9864       /* For halfword transfers we need a temporary register to shuffle
9865          bytes.  Unfortunately for M_USH_A we have none available before
9866          the next store as AT holds the base address.  We deal with this
9867          case by clobbering TREG and then restoring it as with ULH.  */
9868       tempreg = ust == ab ? treg : AT;
9869       if (ust)
9870         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
9871
9872       if (target_big_endian == ust)
9873         ep->X_add_number -= off;
9874       else
9875         ep->X_add_number += off;
9876       macro_build (ep, s2, "t,o(b)", tempreg, BFD_RELOC_LO16, breg);
9877
9878       /* For M_USH_A re-retrieve the LSB.  */
9879       if (ust && ab)
9880         {
9881           if (target_big_endian)
9882             ep->X_add_number += off;
9883           else
9884             ep->X_add_number -= off;
9885           macro_build (&expr1, "lbu", "t,o(b)", AT, BFD_RELOC_LO16, AT);
9886         }
9887       /* For ULH and M_USH_A OR the LSB in.  */
9888       if (!ust || ab)
9889         {
9890           tempreg = !ab ? AT : treg;
9891           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
9892           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
9893         }
9894       break;
9895
9896     default:
9897       /* FIXME: Check if this is one of the itbl macros, since they
9898          are added dynamically.  */
9899       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
9900       break;
9901     }
9902   if (!mips_opts.at && used_at)
9903     as_bad (_("Macro used $at after \".set noat\""));
9904 }
9905
9906 /* Implement macros in mips16 mode.  */
9907
9908 static void
9909 mips16_macro (struct mips_cl_insn *ip)
9910 {
9911   int mask;
9912   int xreg, yreg, zreg, tmp;
9913   expressionS expr1;
9914   int dbl;
9915   const char *s, *s2, *s3;
9916
9917   mask = ip->insn_mo->mask;
9918
9919   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
9920   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
9921   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
9922
9923   expr1.X_op = O_constant;
9924   expr1.X_op_symbol = NULL;
9925   expr1.X_add_symbol = NULL;
9926   expr1.X_add_number = 1;
9927
9928   dbl = 0;
9929
9930   switch (mask)
9931     {
9932     default:
9933       internalError ();
9934
9935     case M_DDIV_3:
9936       dbl = 1;
9937     case M_DIV_3:
9938       s = "mflo";
9939       goto do_div3;
9940     case M_DREM_3:
9941       dbl = 1;
9942     case M_REM_3:
9943       s = "mfhi";
9944     do_div3:
9945       start_noreorder ();
9946       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
9947       expr1.X_add_number = 2;
9948       macro_build (&expr1, "bnez", "x,p", yreg);
9949       macro_build (NULL, "break", "6", 7);
9950
9951       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
9952          since that causes an overflow.  We should do that as well,
9953          but I don't see how to do the comparisons without a temporary
9954          register.  */
9955       end_noreorder ();
9956       macro_build (NULL, s, "x", zreg);
9957       break;
9958
9959     case M_DIVU_3:
9960       s = "divu";
9961       s2 = "mflo";
9962       goto do_divu3;
9963     case M_REMU_3:
9964       s = "divu";
9965       s2 = "mfhi";
9966       goto do_divu3;
9967     case M_DDIVU_3:
9968       s = "ddivu";
9969       s2 = "mflo";
9970       goto do_divu3;
9971     case M_DREMU_3:
9972       s = "ddivu";
9973       s2 = "mfhi";
9974     do_divu3:
9975       start_noreorder ();
9976       macro_build (NULL, s, "0,x,y", xreg, yreg);
9977       expr1.X_add_number = 2;
9978       macro_build (&expr1, "bnez", "x,p", yreg);
9979       macro_build (NULL, "break", "6", 7);
9980       end_noreorder ();
9981       macro_build (NULL, s2, "x", zreg);
9982       break;
9983
9984     case M_DMUL:
9985       dbl = 1;
9986     case M_MUL:
9987       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
9988       macro_build (NULL, "mflo", "x", zreg);
9989       break;
9990
9991     case M_DSUBU_I:
9992       dbl = 1;
9993       goto do_subu;
9994     case M_SUBU_I:
9995     do_subu:
9996       if (imm_expr.X_op != O_constant)
9997         as_bad (_("Unsupported large constant"));
9998       imm_expr.X_add_number = -imm_expr.X_add_number;
9999       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10000       break;
10001
10002     case M_SUBU_I_2:
10003       if (imm_expr.X_op != O_constant)
10004         as_bad (_("Unsupported large constant"));
10005       imm_expr.X_add_number = -imm_expr.X_add_number;
10006       macro_build (&imm_expr, "addiu", "x,k", xreg);
10007       break;
10008
10009     case M_DSUBU_I_2:
10010       if (imm_expr.X_op != O_constant)
10011         as_bad (_("Unsupported large constant"));
10012       imm_expr.X_add_number = -imm_expr.X_add_number;
10013       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10014       break;
10015
10016     case M_BEQ:
10017       s = "cmp";
10018       s2 = "bteqz";
10019       goto do_branch;
10020     case M_BNE:
10021       s = "cmp";
10022       s2 = "btnez";
10023       goto do_branch;
10024     case M_BLT:
10025       s = "slt";
10026       s2 = "btnez";
10027       goto do_branch;
10028     case M_BLTU:
10029       s = "sltu";
10030       s2 = "btnez";
10031       goto do_branch;
10032     case M_BLE:
10033       s = "slt";
10034       s2 = "bteqz";
10035       goto do_reverse_branch;
10036     case M_BLEU:
10037       s = "sltu";
10038       s2 = "bteqz";
10039       goto do_reverse_branch;
10040     case M_BGE:
10041       s = "slt";
10042       s2 = "bteqz";
10043       goto do_branch;
10044     case M_BGEU:
10045       s = "sltu";
10046       s2 = "bteqz";
10047       goto do_branch;
10048     case M_BGT:
10049       s = "slt";
10050       s2 = "btnez";
10051       goto do_reverse_branch;
10052     case M_BGTU:
10053       s = "sltu";
10054       s2 = "btnez";
10055
10056     do_reverse_branch:
10057       tmp = xreg;
10058       xreg = yreg;
10059       yreg = tmp;
10060
10061     do_branch:
10062       macro_build (NULL, s, "x,y", xreg, yreg);
10063       macro_build (&offset_expr, s2, "p");
10064       break;
10065
10066     case M_BEQ_I:
10067       s = "cmpi";
10068       s2 = "bteqz";
10069       s3 = "x,U";
10070       goto do_branch_i;
10071     case M_BNE_I:
10072       s = "cmpi";
10073       s2 = "btnez";
10074       s3 = "x,U";
10075       goto do_branch_i;
10076     case M_BLT_I:
10077       s = "slti";
10078       s2 = "btnez";
10079       s3 = "x,8";
10080       goto do_branch_i;
10081     case M_BLTU_I:
10082       s = "sltiu";
10083       s2 = "btnez";
10084       s3 = "x,8";
10085       goto do_branch_i;
10086     case M_BLE_I:
10087       s = "slti";
10088       s2 = "btnez";
10089       s3 = "x,8";
10090       goto do_addone_branch_i;
10091     case M_BLEU_I:
10092       s = "sltiu";
10093       s2 = "btnez";
10094       s3 = "x,8";
10095       goto do_addone_branch_i;
10096     case M_BGE_I:
10097       s = "slti";
10098       s2 = "bteqz";
10099       s3 = "x,8";
10100       goto do_branch_i;
10101     case M_BGEU_I:
10102       s = "sltiu";
10103       s2 = "bteqz";
10104       s3 = "x,8";
10105       goto do_branch_i;
10106     case M_BGT_I:
10107       s = "slti";
10108       s2 = "bteqz";
10109       s3 = "x,8";
10110       goto do_addone_branch_i;
10111     case M_BGTU_I:
10112       s = "sltiu";
10113       s2 = "bteqz";
10114       s3 = "x,8";
10115
10116     do_addone_branch_i:
10117       if (imm_expr.X_op != O_constant)
10118         as_bad (_("Unsupported large constant"));
10119       ++imm_expr.X_add_number;
10120
10121     do_branch_i:
10122       macro_build (&imm_expr, s, s3, xreg);
10123       macro_build (&offset_expr, s2, "p");
10124       break;
10125
10126     case M_ABS:
10127       expr1.X_add_number = 0;
10128       macro_build (&expr1, "slti", "x,8", yreg);
10129       if (xreg != yreg)
10130         move_register (xreg, yreg);
10131       expr1.X_add_number = 2;
10132       macro_build (&expr1, "bteqz", "p");
10133       macro_build (NULL, "neg", "x,w", xreg, xreg);
10134     }
10135 }
10136
10137 /* For consistency checking, verify that all bits are specified either
10138    by the match/mask part of the instruction definition, or by the
10139    operand list.  */
10140 static int
10141 validate_mips_insn (const struct mips_opcode *opc)
10142 {
10143   const char *p = opc->args;
10144   char c;
10145   unsigned long used_bits = opc->mask;
10146
10147   if ((used_bits & opc->match) != opc->match)
10148     {
10149       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
10150               opc->name, opc->args);
10151       return 0;
10152     }
10153 #define USE_BITS(mask,shift)    (used_bits |= ((mask) << (shift)))
10154   while (*p)
10155     switch (c = *p++)
10156       {
10157       case ',': break;
10158       case '(': break;
10159       case ')': break;
10160       case '+':
10161         switch (c = *p++)
10162           {
10163           case '1': USE_BITS (OP_MASK_UDI1,     OP_SH_UDI1);    break;
10164           case '2': USE_BITS (OP_MASK_UDI2,     OP_SH_UDI2);    break;
10165           case '3': USE_BITS (OP_MASK_UDI3,     OP_SH_UDI3);    break;
10166           case '4': USE_BITS (OP_MASK_UDI4,     OP_SH_UDI4);    break;
10167           case 'A': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10168           case 'B': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10169           case 'C': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10170           case 'D': USE_BITS (OP_MASK_RD,       OP_SH_RD);
10171                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10172           case 'E': USE_BITS (OP_MASK_SHAMT,    OP_SH_SHAMT);   break;
10173           case 'F': USE_BITS (OP_MASK_INSMSB,   OP_SH_INSMSB);  break;
10174           case 'G': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10175           case 'H': USE_BITS (OP_MASK_EXTMSBD,  OP_SH_EXTMSBD); break;
10176           case 'I': break;
10177           case 't': USE_BITS (OP_MASK_RT,       OP_SH_RT);      break;
10178           case 'T': USE_BITS (OP_MASK_RT,       OP_SH_RT);
10179                     USE_BITS (OP_MASK_SEL,      OP_SH_SEL);     break;
10180           case 'x': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10181           case 'X': USE_BITS (OP_MASK_BBITIND,  OP_SH_BBITIND); break;
10182           case 'p': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10183           case 'P': USE_BITS (OP_MASK_CINSPOS,  OP_SH_CINSPOS); break;
10184           case 'Q': USE_BITS (OP_MASK_SEQI,     OP_SH_SEQI);    break;
10185           case 's': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10186           case 'S': USE_BITS (OP_MASK_CINSLM1,  OP_SH_CINSLM1); break;
10187           case 'z': USE_BITS (OP_MASK_RZ,       OP_SH_RZ);      break;
10188           case 'Z': USE_BITS (OP_MASK_FZ,       OP_SH_FZ);      break;
10189           case 'a': USE_BITS (OP_MASK_OFFSET_A, OP_SH_OFFSET_A); break;
10190           case 'b': USE_BITS (OP_MASK_OFFSET_B, OP_SH_OFFSET_B); break;
10191           case 'c': USE_BITS (OP_MASK_OFFSET_C, OP_SH_OFFSET_C); break;
10192
10193           default:
10194             as_bad (_("internal: bad mips opcode (unknown extension operand type `+%c'): %s %s"),
10195                     c, opc->name, opc->args);
10196             return 0;
10197           }
10198         break;
10199       case '<': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10200       case '>': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10201       case 'A': break;
10202       case 'B': USE_BITS (OP_MASK_CODE20,       OP_SH_CODE20);  break;
10203       case 'C': USE_BITS (OP_MASK_COPZ,         OP_SH_COPZ);    break;
10204       case 'D': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10205       case 'E': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10206       case 'F': break;
10207       case 'G': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10208       case 'H': USE_BITS (OP_MASK_SEL,          OP_SH_SEL);     break;
10209       case 'I': break;
10210       case 'J': USE_BITS (OP_MASK_CODE19,       OP_SH_CODE19);  break;
10211       case 'K': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10212       case 'L': break;
10213       case 'M': USE_BITS (OP_MASK_CCC,          OP_SH_CCC);     break;
10214       case 'N': USE_BITS (OP_MASK_BCC,          OP_SH_BCC);     break;
10215       case 'O': USE_BITS (OP_MASK_ALN,          OP_SH_ALN);     break;
10216       case 'Q': USE_BITS (OP_MASK_VSEL,         OP_SH_VSEL);
10217                 USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10218       case 'R': USE_BITS (OP_MASK_FR,           OP_SH_FR);      break;
10219       case 'S': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10220       case 'T': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10221       case 'V': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10222       case 'W': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10223       case 'X': USE_BITS (OP_MASK_FD,           OP_SH_FD);      break;
10224       case 'Y': USE_BITS (OP_MASK_FS,           OP_SH_FS);      break;
10225       case 'Z': USE_BITS (OP_MASK_FT,           OP_SH_FT);      break;
10226       case 'a': USE_BITS (OP_MASK_TARGET,       OP_SH_TARGET);  break;
10227       case 'b': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10228       case 'c': USE_BITS (OP_MASK_CODE,         OP_SH_CODE);    break;
10229       case 'd': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10230       case 'f': break;
10231       case 'h': USE_BITS (OP_MASK_PREFX,        OP_SH_PREFX);   break;
10232       case 'i': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10233       case 'j': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10234       case 'k': USE_BITS (OP_MASK_CACHE,        OP_SH_CACHE);   break;
10235       case 'l': break;
10236       case 'o': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10237       case 'p': USE_BITS (OP_MASK_DELTA,        OP_SH_DELTA);   break;
10238       case 'q': USE_BITS (OP_MASK_CODE2,        OP_SH_CODE2);   break;
10239       case 'r': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10240       case 's': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10241       case 't': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10242       case 'u': USE_BITS (OP_MASK_IMMEDIATE,    OP_SH_IMMEDIATE); break;
10243       case 'v': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10244       case 'w': USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10245       case 'x': break;
10246       case 'z': break;
10247       case 'P': USE_BITS (OP_MASK_PERFREG,      OP_SH_PERFREG); break;
10248       case 'U': USE_BITS (OP_MASK_RD,           OP_SH_RD);
10249                 USE_BITS (OP_MASK_RT,           OP_SH_RT);      break;
10250       case 'e': USE_BITS (OP_MASK_VECBYTE,      OP_SH_VECBYTE); break;
10251       case '%': USE_BITS (OP_MASK_VECALIGN,     OP_SH_VECALIGN); break;
10252       case '[': break;
10253       case ']': break;
10254       case '1': USE_BITS (OP_MASK_SHAMT,        OP_SH_SHAMT);   break;
10255       case '2': USE_BITS (OP_MASK_BP,           OP_SH_BP);      break;
10256       case '3': USE_BITS (OP_MASK_SA3,          OP_SH_SA3);     break;
10257       case '4': USE_BITS (OP_MASK_SA4,          OP_SH_SA4);     break;
10258       case '5': USE_BITS (OP_MASK_IMM8,         OP_SH_IMM8);    break;
10259       case '6': USE_BITS (OP_MASK_RS,           OP_SH_RS);      break;
10260       case '7': USE_BITS (OP_MASK_DSPACC,       OP_SH_DSPACC);  break;
10261       case '8': USE_BITS (OP_MASK_WRDSP,        OP_SH_WRDSP);   break;
10262       case '9': USE_BITS (OP_MASK_DSPACC_S,     OP_SH_DSPACC_S);break;
10263       case '0': USE_BITS (OP_MASK_DSPSFT,       OP_SH_DSPSFT);  break;
10264       case '\'': USE_BITS (OP_MASK_RDDSP,       OP_SH_RDDSP);   break;
10265       case ':': USE_BITS (OP_MASK_DSPSFT_7,     OP_SH_DSPSFT_7);break;
10266       case '@': USE_BITS (OP_MASK_IMM10,        OP_SH_IMM10);   break;
10267       case '!': USE_BITS (OP_MASK_MT_U,         OP_SH_MT_U);    break;
10268       case '$': USE_BITS (OP_MASK_MT_H,         OP_SH_MT_H);    break;
10269       case '*': USE_BITS (OP_MASK_MTACC_T,      OP_SH_MTACC_T); break;
10270       case '&': USE_BITS (OP_MASK_MTACC_D,      OP_SH_MTACC_D); break;
10271       case 'g': USE_BITS (OP_MASK_RD,           OP_SH_RD);      break;
10272       default:
10273         as_bad (_("internal: bad mips opcode (unknown operand type `%c'): %s %s"),
10274                 c, opc->name, opc->args);
10275         return 0;
10276       }
10277 #undef USE_BITS
10278   if (used_bits != 0xffffffff)
10279     {
10280       as_bad (_("internal: bad mips opcode (bits 0x%lx undefined): %s %s"),
10281               ~used_bits & 0xffffffff, opc->name, opc->args);
10282       return 0;
10283     }
10284   return 1;
10285 }
10286
10287 /* For consistency checking, verify that the length implied matches the
10288    major opcode and that all bits are specified either by the match/mask
10289    part of the instruction definition, or by the operand list.  */
10290
10291 static int
10292 validate_micromips_insn (const struct mips_opcode *opc)
10293 {
10294   unsigned long match = opc->match;
10295   unsigned long mask = opc->mask;
10296   const char *p = opc->args;
10297   unsigned long insn_bits;
10298   unsigned long used_bits;
10299   unsigned long major;
10300   unsigned int length;
10301   char e;
10302   char c;
10303
10304   if ((mask & match) != match)
10305     {
10306       as_bad (_("Internal error: bad microMIPS opcode (mask error): %s %s"),
10307               opc->name, opc->args);
10308       return 0;
10309     }
10310   length = micromips_insn_length (opc);
10311   if (length != 2 && length != 4)
10312     {
10313       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
10314                 "%s %s"), length, opc->name, opc->args);
10315       return 0;
10316     }
10317   major = match >> (10 + 8 * (length - 2));
10318   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
10319       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
10320     {
10321       as_bad (_("Internal error: bad microMIPS opcode "
10322                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
10323       return 0;
10324     }
10325
10326   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
10327   insn_bits = 1 << 4 * length;
10328   insn_bits <<= 4 * length;
10329   insn_bits -= 1;
10330   used_bits = mask;
10331 #define USE_BITS(field) \
10332   (used_bits |= MICROMIPSOP_MASK_##field << MICROMIPSOP_SH_##field)
10333   while (*p)
10334     switch (c = *p++)
10335       {
10336       case ',': break;
10337       case '(': break;
10338       case ')': break;
10339       case '+':
10340         e = c;
10341         switch (c = *p++)
10342           {
10343           case 'A': USE_BITS (EXTLSB);  break;
10344           case 'B': USE_BITS (INSMSB);  break;
10345           case 'C': USE_BITS (EXTMSBD); break;
10346           case 'D': USE_BITS (RS);      USE_BITS (SEL); break;
10347           case 'E': USE_BITS (EXTLSB);  break;
10348           case 'F': USE_BITS (INSMSB);  break;
10349           case 'G': USE_BITS (EXTMSBD); break;
10350           case 'H': USE_BITS (EXTMSBD); break;
10351           default:
10352             as_bad (_("Internal error: bad mips opcode "
10353                       "(unknown extension operand type `%c%c'): %s %s"),
10354                     e, c, opc->name, opc->args);
10355             return 0;
10356           }
10357         break;
10358       case 'm':
10359         e = c;
10360         switch (c = *p++)
10361           {
10362           case 'A': USE_BITS (IMMA);    break;
10363           case 'B': USE_BITS (IMMB);    break;
10364           case 'C': USE_BITS (IMMC);    break;
10365           case 'D': USE_BITS (IMMD);    break;
10366           case 'E': USE_BITS (IMME);    break;
10367           case 'F': USE_BITS (IMMF);    break;
10368           case 'G': USE_BITS (IMMG);    break;
10369           case 'H': USE_BITS (IMMH);    break;
10370           case 'I': USE_BITS (IMMI);    break;
10371           case 'J': USE_BITS (IMMJ);    break;
10372           case 'L': USE_BITS (IMML);    break;
10373           case 'M': USE_BITS (IMMM);    break;
10374           case 'N': USE_BITS (IMMN);    break;
10375           case 'O': USE_BITS (IMMO);    break;
10376           case 'P': USE_BITS (IMMP);    break;
10377           case 'Q': USE_BITS (IMMQ);    break;
10378           case 'U': USE_BITS (IMMU);    break;
10379           case 'W': USE_BITS (IMMW);    break;
10380           case 'X': USE_BITS (IMMX);    break;
10381           case 'Y': USE_BITS (IMMY);    break;
10382           case 'Z': break;
10383           case 'a': break;
10384           case 'b': USE_BITS (MB);      break;
10385           case 'c': USE_BITS (MC);      break;
10386           case 'd': USE_BITS (MD);      break;
10387           case 'e': USE_BITS (ME);      break;
10388           case 'f': USE_BITS (MF);      break;
10389           case 'g': USE_BITS (MG);      break;
10390           case 'h': USE_BITS (MH);      break;
10391           case 'i': USE_BITS (MI);      break;
10392           case 'j': USE_BITS (MJ);      break;
10393           case 'l': USE_BITS (ML);      break;
10394           case 'm': USE_BITS (MM);      break;
10395           case 'n': USE_BITS (MN);      break;
10396           case 'p': USE_BITS (MP);      break;
10397           case 'q': USE_BITS (MQ);      break;
10398           case 'r': break;
10399           case 's': break;
10400           case 't': break;
10401           case 'x': break;
10402           case 'y': break;
10403           case 'z': break;
10404           default:
10405             as_bad (_("Internal error: bad mips opcode "
10406                       "(unknown extension operand type `%c%c'): %s %s"),
10407                     e, c, opc->name, opc->args);
10408             return 0;
10409           }
10410         break;
10411       case '.': USE_BITS (OFFSET10);    break;
10412       case '1': USE_BITS (STYPE);       break;
10413       case '<': USE_BITS (SHAMT);       break;
10414       case '>': USE_BITS (SHAMT);       break;
10415       case 'B': USE_BITS (CODE10);      break;
10416       case 'C': USE_BITS (COPZ);        break;
10417       case 'D': USE_BITS (FD);          break;
10418       case 'E': USE_BITS (RT);          break;
10419       case 'G': USE_BITS (RS);          break;
10420       case 'H': USE_BITS (SEL); break;
10421       case 'K': USE_BITS (RS);          break;
10422       case 'M': USE_BITS (CCC);         break;
10423       case 'N': USE_BITS (BCC);         break;
10424       case 'R': USE_BITS (FR);          break;
10425       case 'S': USE_BITS (FS);          break;
10426       case 'T': USE_BITS (FT);          break;
10427       case 'V': USE_BITS (FS);          break;
10428       case 'a': USE_BITS (TARGET);      break;
10429       case 'b': USE_BITS (RS);          break;
10430       case 'c': USE_BITS (CODE);        break;
10431       case 'd': USE_BITS (RD);          break;
10432       case 'h': USE_BITS (PREFX);       break;
10433       case 'i': USE_BITS (IMMEDIATE);   break;
10434       case 'j': USE_BITS (DELTA);       break;
10435       case 'k': USE_BITS (CACHE);       break;
10436       case 'n': USE_BITS (RT);          break;
10437       case 'o': USE_BITS (DELTA);       break;
10438       case 'p': USE_BITS (DELTA);       break;
10439       case 'q': USE_BITS (CODE2);       break;
10440       case 'r': USE_BITS (RS);          break;
10441       case 's': USE_BITS (RS);          break;
10442       case 't': USE_BITS (RT);          break;
10443       case 'u': USE_BITS (IMMEDIATE);   break;
10444       case 'v': USE_BITS (RS);          break;
10445       case 'w': USE_BITS (RT);          break;
10446       case 'y': USE_BITS (RS3);         break;
10447       case 'z': break;
10448       case '|': USE_BITS (TRAP);        break;
10449       case '~': USE_BITS (OFFSET12);    break;
10450       default:
10451         as_bad (_("Internal error: bad microMIPS opcode "
10452                   "(unknown operand type `%c'): %s %s"),
10453                 c, opc->name, opc->args);
10454         return 0;
10455       }
10456 #undef USE_BITS
10457   if (used_bits != insn_bits)
10458     {
10459       if (~used_bits & insn_bits)
10460         as_bad (_("Internal error: bad microMIPS opcode "
10461                   "(bits 0x%lx undefined): %s %s"),
10462                 ~used_bits & insn_bits, opc->name, opc->args);
10463       if (used_bits & ~insn_bits)
10464         as_bad (_("Internal error: bad microMIPS opcode "
10465                   "(bits 0x%lx defined): %s %s"),
10466                 used_bits & ~insn_bits, opc->name, opc->args);
10467       return 0;
10468     }
10469   return 1;
10470 }
10471
10472 /* UDI immediates.  */
10473 struct mips_immed {
10474   char          type;
10475   unsigned int  shift;
10476   unsigned long mask;
10477   const char *  desc;
10478 };
10479
10480 static const struct mips_immed mips_immed[] = {
10481   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
10482   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
10483   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
10484   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
10485   { 0,0,0,0 }
10486 };
10487
10488 /* Check whether an odd floating-point register is allowed.  */
10489 static int
10490 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
10491 {
10492   const char *s = insn->name;
10493
10494   if (insn->pinfo == INSN_MACRO)
10495     /* Let a macro pass, we'll catch it later when it is expanded.  */
10496     return 1;
10497
10498   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa))
10499     {
10500       /* Allow odd registers for single-precision ops.  */
10501       switch (insn->pinfo & (FP_S | FP_D))
10502         {
10503         case FP_S:
10504         case 0:
10505           return 1;     /* both single precision - ok */
10506         case FP_D:
10507           return 0;     /* both double precision - fail */
10508         default:
10509           break;
10510         }
10511
10512       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
10513       s = strchr (insn->name, '.');
10514       if (argnum == 2)
10515         s = s != NULL ? strchr (s + 1, '.') : NULL;
10516       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
10517     } 
10518
10519   /* Single-precision coprocessor loads and moves are OK too.  */
10520   if ((insn->pinfo & FP_S)
10521       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
10522                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
10523     return 1;
10524
10525   return 0;
10526 }
10527
10528 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
10529    taking bits from BIT up.  */
10530 static int
10531 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
10532 {
10533   return (ep->X_op == O_constant
10534           && (ep->X_add_number & ((1 << bit) - 1)) == 0
10535           && ep->X_add_number >= min << bit
10536           && ep->X_add_number < max << bit);
10537 }
10538
10539 /* This routine assembles an instruction into its binary format.  As a
10540    side effect, it sets one of the global variables imm_reloc or
10541    offset_reloc to the type of relocation to do if one of the operands
10542    is an address expression.  */
10543
10544 static void
10545 mips_ip (char *str, struct mips_cl_insn *ip)
10546 {
10547   bfd_boolean wrong_delay_slot_insns = FALSE;
10548   bfd_boolean need_delay_slot_ok = TRUE;
10549   struct mips_opcode *firstinsn = NULL;
10550   const struct mips_opcode *past;
10551   struct hash_control *hash;
10552   char *s;
10553   const char *args;
10554   char c = 0;
10555   struct mips_opcode *insn;
10556   char *argsStart;
10557   unsigned int regno;
10558   unsigned int lastregno;
10559   unsigned int destregno = 0;
10560   unsigned int lastpos = 0;
10561   unsigned int limlo, limhi;
10562   char *s_reset;
10563   offsetT min_range, max_range;
10564   long opend;
10565   char *name;
10566   int argnum;
10567   unsigned int rtype;
10568   char *dot;
10569   long end;
10570
10571   insn_error = NULL;
10572
10573   if (mips_opts.micromips)
10574     {
10575       hash = micromips_op_hash;
10576       past = &micromips_opcodes[bfd_micromips_num_opcodes];
10577     }
10578   else
10579     {
10580       hash = op_hash;
10581       past = &mips_opcodes[NUMOPCODES];
10582     }
10583   forced_insn_length = 0;
10584   insn = NULL;
10585
10586   /* We first try to match an instruction up to a space or to the end.  */
10587   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
10588     continue;
10589
10590   /* Make a copy of the instruction so that we can fiddle with it.  */
10591   name = alloca (end + 1);
10592   memcpy (name, str, end);
10593   name[end] = '\0';
10594
10595   for (;;)
10596     {
10597       insn = (struct mips_opcode *) hash_find (hash, name);
10598
10599       if (insn != NULL || !mips_opts.micromips)
10600         break;
10601       if (forced_insn_length)
10602         break;
10603
10604       /* See if there's an instruction size override suffix,
10605          either `16' or `32', at the end of the mnemonic proper,
10606          that defines the operation, i.e. before the first `.'
10607          character if any.  Strip it and retry.  */
10608       dot = strchr (name, '.');
10609       opend = dot != NULL ? dot - name : end;
10610       if (opend < 3)
10611         break;
10612       if (name[opend - 2] == '1' && name[opend - 1] == '6')
10613         forced_insn_length = 2;
10614       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
10615         forced_insn_length = 4;
10616       else
10617         break;
10618       memcpy (name + opend - 2, name + opend, end - opend + 1);
10619     }
10620   if (insn == NULL)
10621     {
10622       insn_error = _("Unrecognized opcode");
10623       return;
10624     }
10625
10626   /* For microMIPS instructions placed in a fixed-length branch delay slot
10627      we make up to two passes over the relevant fragment of the opcode
10628      table.  First we try instructions that meet the delay slot's length
10629      requirement.  If none matched, then we retry with the remaining ones
10630      and if one matches, then we use it and then issue an appropriate
10631      warning later on.  */
10632   argsStart = s = str + end;
10633   for (;;)
10634     {
10635       bfd_boolean delay_slot_ok;
10636       bfd_boolean size_ok;
10637       bfd_boolean ok;
10638
10639       gas_assert (strcmp (insn->name, name) == 0);
10640
10641       ok = is_opcode_valid (insn);
10642       size_ok = is_size_valid (insn);
10643       delay_slot_ok = is_delay_slot_valid (insn);
10644       if (!delay_slot_ok && !wrong_delay_slot_insns)
10645         {
10646           firstinsn = insn;
10647           wrong_delay_slot_insns = TRUE;
10648         }
10649       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
10650         {
10651           static char buf[256];
10652
10653           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
10654             {
10655               ++insn;
10656               continue;
10657             }
10658           if (wrong_delay_slot_insns && need_delay_slot_ok)
10659             {
10660               gas_assert (firstinsn);
10661               need_delay_slot_ok = FALSE;
10662               past = insn + 1;
10663               insn = firstinsn;
10664               continue;
10665             }
10666
10667           if (insn_error)
10668             return;
10669
10670           if (!ok)
10671             sprintf (buf, _("opcode not supported on this processor: %s (%s)"),
10672                      mips_cpu_info_from_arch (mips_opts.arch)->name,
10673                      mips_cpu_info_from_isa (mips_opts.isa)->name);
10674           else
10675             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
10676                      8 * forced_insn_length);
10677           insn_error = buf;
10678
10679           return;
10680         }
10681
10682       create_insn (ip, insn);
10683       insn_error = NULL;
10684       argnum = 1;
10685       lastregno = 0xffffffff;
10686       for (args = insn->args;; ++args)
10687         {
10688           int is_mdmx;
10689
10690           s += strspn (s, " \t");
10691           is_mdmx = 0;
10692           switch (*args)
10693             {
10694             case '\0':          /* end of args */
10695               if (*s == '\0')
10696                 return;
10697               break;
10698
10699             case '2': /* DSP 2-bit unsigned immediate in bit 11.  */
10700               gas_assert (!mips_opts.micromips);
10701               my_getExpression (&imm_expr, s);
10702               check_absolute_expr (ip, &imm_expr);
10703               if ((unsigned long) imm_expr.X_add_number != 1
10704                   && (unsigned long) imm_expr.X_add_number != 3)
10705                 {
10706                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
10707                           (unsigned long) imm_expr.X_add_number);
10708                 }
10709               INSERT_OPERAND (0, BP, *ip, imm_expr.X_add_number);
10710               imm_expr.X_op = O_absent;
10711               s = expr_end;
10712               continue;
10713
10714             case '3': /* DSP 3-bit unsigned immediate in bit 21.  */
10715               gas_assert (!mips_opts.micromips);
10716               my_getExpression (&imm_expr, s);
10717               check_absolute_expr (ip, &imm_expr);
10718               if (imm_expr.X_add_number & ~OP_MASK_SA3)
10719                 {
10720                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10721                           OP_MASK_SA3, (unsigned long) imm_expr.X_add_number);
10722                 }
10723               INSERT_OPERAND (0, SA3, *ip, imm_expr.X_add_number);
10724               imm_expr.X_op = O_absent;
10725               s = expr_end;
10726               continue;
10727
10728             case '4': /* DSP 4-bit unsigned immediate in bit 21.  */
10729               gas_assert (!mips_opts.micromips);
10730               my_getExpression (&imm_expr, s);
10731               check_absolute_expr (ip, &imm_expr);
10732               if (imm_expr.X_add_number & ~OP_MASK_SA4)
10733                 {
10734                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10735                           OP_MASK_SA4, (unsigned long) imm_expr.X_add_number);
10736                 }
10737               INSERT_OPERAND (0, SA4, *ip, imm_expr.X_add_number);
10738               imm_expr.X_op = O_absent;
10739               s = expr_end;
10740               continue;
10741
10742             case '5': /* DSP 8-bit unsigned immediate in bit 16.  */
10743               gas_assert (!mips_opts.micromips);
10744               my_getExpression (&imm_expr, s);
10745               check_absolute_expr (ip, &imm_expr);
10746               if (imm_expr.X_add_number & ~OP_MASK_IMM8)
10747                 {
10748                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10749                           OP_MASK_IMM8, (unsigned long) imm_expr.X_add_number);
10750                 }
10751               INSERT_OPERAND (0, IMM8, *ip, imm_expr.X_add_number);
10752               imm_expr.X_op = O_absent;
10753               s = expr_end;
10754               continue;
10755
10756             case '6': /* DSP 5-bit unsigned immediate in bit 21.  */
10757               gas_assert (!mips_opts.micromips);
10758               my_getExpression (&imm_expr, s);
10759               check_absolute_expr (ip, &imm_expr);
10760               if (imm_expr.X_add_number & ~OP_MASK_RS)
10761                 {
10762                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10763                           OP_MASK_RS, (unsigned long) imm_expr.X_add_number);
10764                 }
10765               INSERT_OPERAND (0, RS, *ip, imm_expr.X_add_number);
10766               imm_expr.X_op = O_absent;
10767               s = expr_end;
10768               continue;
10769
10770             case '7': /* Four DSP accumulators in bits 11,12.  */
10771               gas_assert (!mips_opts.micromips);
10772               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10773                   s[3] >= '0' && s[3] <= '3')
10774                 {
10775                   regno = s[3] - '0';
10776                   s += 4;
10777                   INSERT_OPERAND (0, DSPACC, *ip, regno);
10778                   continue;
10779                 }
10780               else
10781                 as_bad (_("Invalid dsp acc register"));
10782               break;
10783
10784             case '8': /* DSP 6-bit unsigned immediate in bit 11.  */
10785               gas_assert (!mips_opts.micromips);
10786               my_getExpression (&imm_expr, s);
10787               check_absolute_expr (ip, &imm_expr);
10788               if (imm_expr.X_add_number & ~OP_MASK_WRDSP)
10789                 {
10790                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10791                           OP_MASK_WRDSP,
10792                           (unsigned long) imm_expr.X_add_number);
10793                 }
10794               INSERT_OPERAND (0, WRDSP, *ip, imm_expr.X_add_number);
10795               imm_expr.X_op = O_absent;
10796               s = expr_end;
10797               continue;
10798
10799             case '9': /* Four DSP accumulators in bits 21,22.  */
10800               gas_assert (!mips_opts.micromips);
10801               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10802                   s[3] >= '0' && s[3] <= '3')
10803                 {
10804                   regno = s[3] - '0';
10805                   s += 4;
10806                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
10807                   continue;
10808                 }
10809               else
10810                 as_bad (_("Invalid dsp acc register"));
10811               break;
10812
10813             case '0': /* DSP 6-bit signed immediate in bit 20.  */
10814               gas_assert (!mips_opts.micromips);
10815               my_getExpression (&imm_expr, s);
10816               check_absolute_expr (ip, &imm_expr);
10817               min_range = -((OP_MASK_DSPSFT + 1) >> 1);
10818               max_range = ((OP_MASK_DSPSFT + 1) >> 1) - 1;
10819               if (imm_expr.X_add_number < min_range ||
10820                   imm_expr.X_add_number > max_range)
10821                 {
10822                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10823                           (long) min_range, (long) max_range,
10824                           (long) imm_expr.X_add_number);
10825                 }
10826               INSERT_OPERAND (0, DSPSFT, *ip, imm_expr.X_add_number);
10827               imm_expr.X_op = O_absent;
10828               s = expr_end;
10829               continue;
10830
10831             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
10832               gas_assert (!mips_opts.micromips);
10833               my_getExpression (&imm_expr, s);
10834               check_absolute_expr (ip, &imm_expr);
10835               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
10836                 {
10837                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
10838                           OP_MASK_RDDSP,
10839                           (unsigned long) imm_expr.X_add_number);
10840                 }
10841               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
10842               imm_expr.X_op = O_absent;
10843               s = expr_end;
10844               continue;
10845
10846             case ':': /* DSP 7-bit signed immediate in bit 19.  */
10847               gas_assert (!mips_opts.micromips);
10848               my_getExpression (&imm_expr, s);
10849               check_absolute_expr (ip, &imm_expr);
10850               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
10851               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
10852               if (imm_expr.X_add_number < min_range ||
10853                   imm_expr.X_add_number > max_range)
10854                 {
10855                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10856                           (long) min_range, (long) max_range,
10857                           (long) imm_expr.X_add_number);
10858                 }
10859               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
10860               imm_expr.X_op = O_absent;
10861               s = expr_end;
10862               continue;
10863
10864             case '@': /* DSP 10-bit signed immediate in bit 16.  */
10865               gas_assert (!mips_opts.micromips);
10866               my_getExpression (&imm_expr, s);
10867               check_absolute_expr (ip, &imm_expr);
10868               min_range = -((OP_MASK_IMM10 + 1) >> 1);
10869               max_range = ((OP_MASK_IMM10 + 1) >> 1) - 1;
10870               if (imm_expr.X_add_number < min_range ||
10871                   imm_expr.X_add_number > max_range)
10872                 {
10873                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
10874                           (long) min_range, (long) max_range,
10875                           (long) imm_expr.X_add_number);
10876                 }
10877               INSERT_OPERAND (0, IMM10, *ip, imm_expr.X_add_number);
10878               imm_expr.X_op = O_absent;
10879               s = expr_end;
10880               continue;
10881
10882             case '!': /* MT usermode flag bit.  */
10883               gas_assert (!mips_opts.micromips);
10884               my_getExpression (&imm_expr, s);
10885               check_absolute_expr (ip, &imm_expr);
10886               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
10887                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
10888                         (unsigned long) imm_expr.X_add_number);
10889               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
10890               imm_expr.X_op = O_absent;
10891               s = expr_end;
10892               continue;
10893
10894             case '$': /* MT load high flag bit.  */
10895               gas_assert (!mips_opts.micromips);
10896               my_getExpression (&imm_expr, s);
10897               check_absolute_expr (ip, &imm_expr);
10898               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
10899                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
10900                         (unsigned long) imm_expr.X_add_number);
10901               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
10902               imm_expr.X_op = O_absent;
10903               s = expr_end;
10904               continue;
10905
10906             case '*': /* Four DSP accumulators in bits 18,19.  */
10907               gas_assert (!mips_opts.micromips);
10908               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10909                   s[3] >= '0' && s[3] <= '3')
10910                 {
10911                   regno = s[3] - '0';
10912                   s += 4;
10913                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
10914                   continue;
10915                 }
10916               else
10917                 as_bad (_("Invalid dsp/smartmips acc register"));
10918               break;
10919
10920             case '&': /* Four DSP accumulators in bits 13,14.  */
10921               gas_assert (!mips_opts.micromips);
10922               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
10923                   s[3] >= '0' && s[3] <= '3')
10924                 {
10925                   regno = s[3] - '0';
10926                   s += 4;
10927                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
10928                   continue;
10929                 }
10930               else
10931                 as_bad (_("Invalid dsp/smartmips acc register"));
10932               break;
10933
10934             case ',':
10935               ++argnum;
10936               if (*s++ == *args)
10937                 continue;
10938               s--;
10939               switch (*++args)
10940                 {
10941                 case 'r':
10942                 case 'v':
10943                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
10944                   continue;
10945
10946                 case 'w':
10947                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
10948                   continue;
10949
10950                 case 'W':
10951                   gas_assert (!mips_opts.micromips);
10952                   INSERT_OPERAND (0, FT, *ip, lastregno);
10953                   continue;
10954
10955                 case 'V':
10956                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
10957                   continue;
10958                 }
10959               break;
10960
10961             case '(':
10962               /* Handle optional base register.
10963                  Either the base register is omitted or
10964                  we must have a left paren.  */
10965               /* This is dependent on the next operand specifier
10966                  is a base register specification.  */
10967               gas_assert (args[1] == 'b'
10968                           || (mips_opts.micromips
10969                               && args[1] == 'm'
10970                               && (args[2] == 'l' || args[2] == 'n'
10971                                   || args[2] == 's' || args[2] == 'a')));
10972               if (*s == '\0' && args[1] == 'b')
10973                 return;
10974               /* Fall through.  */
10975
10976             case ')':           /* These must match exactly.  */
10977               if (*s++ == *args)
10978                 continue;
10979               break;
10980
10981             case '[':           /* These must match exactly.  */
10982             case ']':
10983               gas_assert (!mips_opts.micromips);
10984               if (*s++ == *args)
10985                 continue;
10986               break;
10987
10988             case '+':           /* Opcode extension character.  */
10989               switch (*++args)
10990                 {
10991                 case '1':       /* UDI immediates.  */
10992                 case '2':
10993                 case '3':
10994                 case '4':
10995                   gas_assert (!mips_opts.micromips);
10996                   {
10997                     const struct mips_immed *imm = mips_immed;
10998
10999                     while (imm->type && imm->type != *args)
11000                       ++imm;
11001                     if (! imm->type)
11002                       internalError ();
11003                     my_getExpression (&imm_expr, s);
11004                     check_absolute_expr (ip, &imm_expr);
11005                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11006                       {
11007                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11008                                  imm->desc ? imm->desc : ip->insn_mo->name,
11009                                  (unsigned long) imm_expr.X_add_number,
11010                                  (unsigned long) imm_expr.X_add_number);
11011                         imm_expr.X_add_number &= imm->mask;
11012                       }
11013                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11014                                         << imm->shift);
11015                     imm_expr.X_op = O_absent;
11016                     s = expr_end;
11017                   }
11018                   continue;
11019
11020                 case 'A':               /* ins/ext position, becomes LSB.  */
11021                   limlo = 0;
11022                   limhi = 31;
11023                   goto do_lsb;
11024                 case 'E':
11025                   limlo = 32;
11026                   limhi = 63;
11027                   goto do_lsb;
11028                 do_lsb:
11029                   my_getExpression (&imm_expr, s);
11030                   check_absolute_expr (ip, &imm_expr);
11031                   if ((unsigned long) imm_expr.X_add_number < limlo
11032                       || (unsigned long) imm_expr.X_add_number > limhi)
11033                     {
11034                       as_bad (_("Improper position (%lu)"),
11035                               (unsigned long) imm_expr.X_add_number);
11036                       imm_expr.X_add_number = limlo;
11037                     }
11038                   lastpos = imm_expr.X_add_number;
11039                   INSERT_OPERAND (mips_opts.micromips,
11040                                   EXTLSB, *ip, imm_expr.X_add_number);
11041                   imm_expr.X_op = O_absent;
11042                   s = expr_end;
11043                   continue;
11044
11045                 case 'B':               /* ins size, becomes MSB.  */
11046                   limlo = 1;
11047                   limhi = 32;
11048                   goto do_msb;
11049                 case 'F':
11050                   limlo = 33;
11051                   limhi = 64;
11052                   goto do_msb;
11053                 do_msb:
11054                   my_getExpression (&imm_expr, s);
11055                   check_absolute_expr (ip, &imm_expr);
11056                   /* Check for negative input so that small negative numbers
11057                      will not succeed incorrectly.  The checks against
11058                      (pos+size) transitively check "size" itself,
11059                      assuming that "pos" is reasonable.  */
11060                   if ((long) imm_expr.X_add_number < 0
11061                       || ((unsigned long) imm_expr.X_add_number
11062                           + lastpos) < limlo
11063                       || ((unsigned long) imm_expr.X_add_number
11064                           + lastpos) > limhi)
11065                     {
11066                       as_bad (_("Improper insert size (%lu, position %lu)"),
11067                               (unsigned long) imm_expr.X_add_number,
11068                               (unsigned long) lastpos);
11069                       imm_expr.X_add_number = limlo - lastpos;
11070                     }
11071                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11072                                   lastpos + imm_expr.X_add_number - 1);
11073                   imm_expr.X_op = O_absent;
11074                   s = expr_end;
11075                   continue;
11076
11077                 case 'C':               /* ext size, becomes MSBD.  */
11078                   limlo = 1;
11079                   limhi = 32;
11080                   goto do_msbd;
11081                 case 'G':
11082                   limlo = 33;
11083                   limhi = 64;
11084                   goto do_msbd;
11085                 case 'H':
11086                   limlo = 33;
11087                   limhi = 64;
11088                   goto do_msbd;
11089                 do_msbd:
11090                   my_getExpression (&imm_expr, s);
11091                   check_absolute_expr (ip, &imm_expr);
11092                   /* Check for negative input so that small negative numbers
11093                      will not succeed incorrectly.  The checks against
11094                      (pos+size) transitively check "size" itself,
11095                      assuming that "pos" is reasonable.  */
11096                   if ((long) imm_expr.X_add_number < 0
11097                       || ((unsigned long) imm_expr.X_add_number
11098                           + lastpos) < limlo
11099                       || ((unsigned long) imm_expr.X_add_number
11100                           + lastpos) > limhi)
11101                     {
11102                       as_bad (_("Improper extract size (%lu, position %lu)"),
11103                               (unsigned long) imm_expr.X_add_number,
11104                               (unsigned long) lastpos);
11105                       imm_expr.X_add_number = limlo - lastpos;
11106                     }
11107                   INSERT_OPERAND (mips_opts.micromips,
11108                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11109                   imm_expr.X_op = O_absent;
11110                   s = expr_end;
11111                   continue;
11112
11113                 case 'D':
11114                   /* +D is for disassembly only; never match.  */
11115                   break;
11116
11117                 case 'I':
11118                   /* "+I" is like "I", except that imm2_expr is used.  */
11119                   my_getExpression (&imm2_expr, s);
11120                   if (imm2_expr.X_op != O_big
11121                       && imm2_expr.X_op != O_constant)
11122                   insn_error = _("absolute expression required");
11123                   if (HAVE_32BIT_GPRS)
11124                     normalize_constant_expr (&imm2_expr);
11125                   s = expr_end;
11126                   continue;
11127
11128                 case 'T': /* Coprocessor register.  */
11129                   gas_assert (!mips_opts.micromips);
11130                   /* +T is for disassembly only; never match.  */
11131                   break;
11132
11133                 case 't': /* Coprocessor register number.  */
11134                   gas_assert (!mips_opts.micromips);
11135                   if (s[0] == '$' && ISDIGIT (s[1]))
11136                     {
11137                       ++s;
11138                       regno = 0;
11139                       do
11140                         {
11141                           regno *= 10;
11142                           regno += *s - '0';
11143                           ++s;
11144                         }
11145                       while (ISDIGIT (*s));
11146                       if (regno > 31)
11147                         as_bad (_("Invalid register number (%d)"), regno);
11148                       else
11149                         {
11150                           INSERT_OPERAND (0, RT, *ip, regno);
11151                           continue;
11152                         }
11153                     }
11154                   else
11155                     as_bad (_("Invalid coprocessor 0 register number"));
11156                   break;
11157
11158                 case 'x':
11159                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11160                      is not in the valid range.  */
11161                   gas_assert (!mips_opts.micromips);
11162                   my_getExpression (&imm_expr, s);
11163                   check_absolute_expr (ip, &imm_expr);
11164                   if ((unsigned) imm_expr.X_add_number > 31)
11165                     {
11166                       as_bad (_("Improper bit index (%lu)"),
11167                               (unsigned long) imm_expr.X_add_number);
11168                       imm_expr.X_add_number = 0;
11169                     }
11170                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11171                   imm_expr.X_op = O_absent;
11172                   s = expr_end;
11173                   continue;
11174
11175                 case 'X':
11176                   /* bbit[01] bit index when bbit is used but we generate
11177                      bbit[01]32 because the index is over 32.  Move to the
11178                      next candidate if index is not in the valid range.  */
11179                   gas_assert (!mips_opts.micromips);
11180                   my_getExpression (&imm_expr, s);
11181                   check_absolute_expr (ip, &imm_expr);
11182                   if ((unsigned) imm_expr.X_add_number < 32
11183                       || (unsigned) imm_expr.X_add_number > 63)
11184                     break;
11185                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11186                   imm_expr.X_op = O_absent;
11187                   s = expr_end;
11188                   continue;
11189
11190                 case 'p':
11191                   /* cins, cins32, exts and exts32 position field.  Give error
11192                      if it's not in the valid range.  */
11193                   gas_assert (!mips_opts.micromips);
11194                   my_getExpression (&imm_expr, s);
11195                   check_absolute_expr (ip, &imm_expr);
11196                   if ((unsigned) imm_expr.X_add_number > 31)
11197                     {
11198                       as_bad (_("Improper position (%lu)"),
11199                               (unsigned long) imm_expr.X_add_number);
11200                       imm_expr.X_add_number = 0;
11201                     }
11202                   /* Make the pos explicit to simplify +S.  */
11203                   lastpos = imm_expr.X_add_number + 32;
11204                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
11205                   imm_expr.X_op = O_absent;
11206                   s = expr_end;
11207                   continue;
11208
11209                 case 'P':
11210                   /* cins, cins32, exts and exts32 position field.  Move to
11211                      the next candidate if it's not in the valid range.  */
11212                   gas_assert (!mips_opts.micromips);
11213                   my_getExpression (&imm_expr, s);
11214                   check_absolute_expr (ip, &imm_expr);
11215                   if ((unsigned) imm_expr.X_add_number < 32
11216                       || (unsigned) imm_expr.X_add_number > 63)
11217                     break;
11218                   lastpos = imm_expr.X_add_number;
11219                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
11220                   imm_expr.X_op = O_absent;
11221                   s = expr_end;
11222                   continue;
11223
11224                 case 's':
11225                   /* cins and exts length-minus-one field.  */
11226                   gas_assert (!mips_opts.micromips);
11227                   my_getExpression (&imm_expr, s);
11228                   check_absolute_expr (ip, &imm_expr);
11229                   if ((unsigned long) imm_expr.X_add_number > 31)
11230                     {
11231                       as_bad (_("Improper size (%lu)"),
11232                               (unsigned long) imm_expr.X_add_number);
11233                       imm_expr.X_add_number = 0;
11234                     }
11235                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11236                   imm_expr.X_op = O_absent;
11237                   s = expr_end;
11238                   continue;
11239
11240                 case 'S':
11241                   /* cins32/exts32 and cins/exts aliasing cint32/exts32
11242                      length-minus-one field.  */
11243                   gas_assert (!mips_opts.micromips);
11244                   my_getExpression (&imm_expr, s);
11245                   check_absolute_expr (ip, &imm_expr);
11246                   if ((long) imm_expr.X_add_number < 0
11247                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
11248                     {
11249                       as_bad (_("Improper size (%lu)"),
11250                               (unsigned long) imm_expr.X_add_number);
11251                       imm_expr.X_add_number = 0;
11252                     }
11253                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11254                   imm_expr.X_op = O_absent;
11255                   s = expr_end;
11256                   continue;
11257
11258                 case 'Q':
11259                   /* seqi/snei immediate field.  */
11260                   gas_assert (!mips_opts.micromips);
11261                   my_getExpression (&imm_expr, s);
11262                   check_absolute_expr (ip, &imm_expr);
11263                   if ((long) imm_expr.X_add_number < -512
11264                       || (long) imm_expr.X_add_number >= 512)
11265                     {
11266                       as_bad (_("Improper immediate (%ld)"),
11267                                (long) imm_expr.X_add_number);
11268                       imm_expr.X_add_number = 0;
11269                     }
11270                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
11271                   imm_expr.X_op = O_absent;
11272                   s = expr_end;
11273                   continue;
11274
11275                 case 'a': /* 8-bit signed offset in bit 6 */
11276                   gas_assert (!mips_opts.micromips);
11277                   my_getExpression (&imm_expr, s);
11278                   check_absolute_expr (ip, &imm_expr);
11279                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
11280                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
11281                   if (imm_expr.X_add_number < min_range
11282                       || imm_expr.X_add_number > max_range)
11283                     {
11284                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11285                               (long) min_range, (long) max_range,
11286                               (long) imm_expr.X_add_number);
11287                     }
11288                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
11289                   imm_expr.X_op = O_absent;
11290                   s = expr_end;
11291                   continue;
11292
11293                 case 'b': /* 8-bit signed offset in bit 3 */
11294                   gas_assert (!mips_opts.micromips);
11295                   my_getExpression (&imm_expr, s);
11296                   check_absolute_expr (ip, &imm_expr);
11297                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
11298                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
11299                   if (imm_expr.X_add_number < min_range
11300                       || imm_expr.X_add_number > max_range)
11301                     {
11302                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11303                               (long) min_range, (long) max_range,
11304                               (long) imm_expr.X_add_number);
11305                     }
11306                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
11307                   imm_expr.X_op = O_absent;
11308                   s = expr_end;
11309                   continue;
11310
11311                 case 'c': /* 9-bit signed offset in bit 6 */
11312                   gas_assert (!mips_opts.micromips);
11313                   my_getExpression (&imm_expr, s);
11314                   check_absolute_expr (ip, &imm_expr);
11315                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
11316                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
11317                   /* We check the offset range before adjusted.  */
11318                   min_range <<= 4;
11319                   max_range <<= 4;
11320                   if (imm_expr.X_add_number < min_range
11321                       || imm_expr.X_add_number > max_range)
11322                     {
11323                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11324                               (long) min_range, (long) max_range,
11325                               (long) imm_expr.X_add_number);
11326                     }
11327                   if (imm_expr.X_add_number & 0xf)
11328                     {
11329                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
11330                               (long) imm_expr.X_add_number);
11331                     }
11332                   /* Right shift 4 bits to adjust the offset operand.  */
11333                   INSERT_OPERAND (0, OFFSET_C, *ip,
11334                                   imm_expr.X_add_number >> 4);
11335                   imm_expr.X_op = O_absent;
11336                   s = expr_end;
11337                   continue;
11338
11339                 case 'z':
11340                   gas_assert (!mips_opts.micromips);
11341                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
11342                     break;
11343                   if (regno == AT && mips_opts.at)
11344                     {
11345                       if (mips_opts.at == ATREG)
11346                         as_warn (_("used $at without \".set noat\""));
11347                       else
11348                         as_warn (_("used $%u with \".set at=$%u\""),
11349                                  regno, mips_opts.at);
11350                     }
11351                   INSERT_OPERAND (0, RZ, *ip, regno);
11352                   continue;
11353
11354                 case 'Z':
11355                   gas_assert (!mips_opts.micromips);
11356                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
11357                     break;
11358                   INSERT_OPERAND (0, FZ, *ip, regno);
11359                   continue;
11360
11361                 default:
11362                   as_bad (_("Internal error: bad %s opcode "
11363                             "(unknown extension operand type `+%c'): %s %s"),
11364                           mips_opts.micromips ? "microMIPS" : "MIPS",
11365                           *args, insn->name, insn->args);
11366                   /* Further processing is fruitless.  */
11367                   return;
11368                 }
11369               break;
11370
11371             case '.':           /* 10-bit offset.  */
11372             case '~':           /* 12-bit offset.  */
11373               gas_assert (mips_opts.micromips);
11374               {
11375                 int shift = *args == '.' ? 9 : 11;
11376                 size_t i;
11377
11378                 /* Check whether there is only a single bracketed expression
11379                    left.  If so, it must be the base register and the
11380                    constant must be zero.  */
11381                 if (*s == '(' && strchr (s + 1, '(') == 0)
11382                   continue;
11383
11384                 /* If this value won't fit into the offset, then go find
11385                    a macro that will generate a 16- or 32-bit offset code
11386                    pattern.  */
11387                 i = my_getSmallExpression (&imm_expr, imm_reloc, s);
11388                 if ((i == 0 && (imm_expr.X_op != O_constant
11389                                 || imm_expr.X_add_number >= 1 << shift
11390                                 || imm_expr.X_add_number < -1 << shift))
11391                     || i > 0)
11392                   {
11393                     imm_expr.X_op = O_absent;
11394                     break;
11395                   }
11396                 if (shift == 9)
11397                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
11398                 else
11399                   INSERT_OPERAND (1, OFFSET12, *ip, imm_expr.X_add_number);
11400                 imm_expr.X_op = O_absent;
11401                 s = expr_end;
11402               }
11403               continue;
11404
11405             case '<':           /* must be at least one digit */
11406               /*
11407                * According to the manual, if the shift amount is greater
11408                * than 31 or less than 0, then the shift amount should be
11409                * mod 32.  In reality the mips assembler issues an error.
11410                * We issue a warning and mask out all but the low 5 bits.
11411                */
11412               my_getExpression (&imm_expr, s);
11413               check_absolute_expr (ip, &imm_expr);
11414               if ((unsigned long) imm_expr.X_add_number > 31)
11415                 as_warn (_("Improper shift amount (%lu)"),
11416                          (unsigned long) imm_expr.X_add_number);
11417               INSERT_OPERAND (mips_opts.micromips,
11418                               SHAMT, *ip, imm_expr.X_add_number);
11419               imm_expr.X_op = O_absent;
11420               s = expr_end;
11421               continue;
11422
11423             case '>':           /* shift amount minus 32 */
11424               my_getExpression (&imm_expr, s);
11425               check_absolute_expr (ip, &imm_expr);
11426               if ((unsigned long) imm_expr.X_add_number < 32
11427                   || (unsigned long) imm_expr.X_add_number > 63)
11428                 break;
11429               INSERT_OPERAND (mips_opts.micromips,
11430                               SHAMT, *ip, imm_expr.X_add_number - 32);
11431               imm_expr.X_op = O_absent;
11432               s = expr_end;
11433               continue;
11434
11435             case 'k':           /* CACHE code.  */
11436             case 'h':           /* PREFX code.  */
11437             case '1':           /* SYNC type.  */
11438               my_getExpression (&imm_expr, s);
11439               check_absolute_expr (ip, &imm_expr);
11440               if ((unsigned long) imm_expr.X_add_number > 31)
11441                 as_warn (_("Invalid value for `%s' (%lu)"),
11442                          ip->insn_mo->name,
11443                          (unsigned long) imm_expr.X_add_number);
11444               switch (*args)
11445                 {
11446                 case 'k':
11447                   if (mips_fix_cn63xxp1
11448                       && !mips_opts.micromips
11449                       && strcmp ("pref", insn->name) == 0)
11450                     switch (imm_expr.X_add_number)
11451                       {
11452                       case 5:
11453                       case 25:
11454                       case 26:
11455                       case 27:
11456                       case 28:
11457                       case 29:
11458                       case 30:
11459                       case 31:  /* These are ok.  */
11460                         break;
11461
11462                       default:  /* The rest must be changed to 28.  */
11463                         imm_expr.X_add_number = 28;
11464                         break;
11465                       }
11466                   INSERT_OPERAND (mips_opts.micromips,
11467                                   CACHE, *ip, imm_expr.X_add_number);
11468                   break;
11469                 case 'h':
11470                   INSERT_OPERAND (mips_opts.micromips,
11471                                   PREFX, *ip, imm_expr.X_add_number);
11472                   break;
11473                 case '1':
11474                   INSERT_OPERAND (mips_opts.micromips,
11475                                   STYPE, *ip, imm_expr.X_add_number);
11476                   break;
11477                 }
11478               imm_expr.X_op = O_absent;
11479               s = expr_end;
11480               continue;
11481
11482             case 'c':           /* BREAK code.  */
11483               {
11484                 unsigned long mask = (mips_opts.micromips
11485                                       ? MICROMIPSOP_MASK_CODE
11486                                       : OP_MASK_CODE);
11487
11488                 my_getExpression (&imm_expr, s);
11489                 check_absolute_expr (ip, &imm_expr);
11490                 if ((unsigned long) imm_expr.X_add_number > mask)
11491                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11492                            ip->insn_mo->name,
11493                            mask, (unsigned long) imm_expr.X_add_number);
11494                 INSERT_OPERAND (mips_opts.micromips,
11495                                 CODE, *ip, imm_expr.X_add_number);
11496                 imm_expr.X_op = O_absent;
11497                 s = expr_end;
11498               }
11499               continue;
11500
11501             case 'q':           /* Lower BREAK code.  */
11502               {
11503                 unsigned long mask = (mips_opts.micromips
11504                                       ? MICROMIPSOP_MASK_CODE2
11505                                       : OP_MASK_CODE2);
11506
11507                 my_getExpression (&imm_expr, s);
11508                 check_absolute_expr (ip, &imm_expr);
11509                 if ((unsigned long) imm_expr.X_add_number > mask)
11510                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
11511                            ip->insn_mo->name,
11512                            mask, (unsigned long) imm_expr.X_add_number);
11513                 INSERT_OPERAND (mips_opts.micromips,
11514                                 CODE2, *ip, imm_expr.X_add_number);
11515                 imm_expr.X_op = O_absent;
11516                 s = expr_end;
11517               }
11518               continue;
11519
11520             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
11521               {
11522                 unsigned long mask = (mips_opts.micromips
11523                                       ? MICROMIPSOP_MASK_CODE10
11524                                       : OP_MASK_CODE20);
11525
11526                 my_getExpression (&imm_expr, s);
11527                 check_absolute_expr (ip, &imm_expr);
11528                 if ((unsigned long) imm_expr.X_add_number > mask)
11529                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11530                            ip->insn_mo->name,
11531                            mask, (unsigned long) imm_expr.X_add_number);
11532                 if (mips_opts.micromips)
11533                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
11534                 else
11535                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
11536                 imm_expr.X_op = O_absent;
11537                 s = expr_end;
11538               }
11539               continue;
11540
11541             case 'C':           /* 25- or 23-bit coprocessor code.  */
11542               {
11543                 unsigned long mask = (mips_opts.micromips
11544                                       ? MICROMIPSOP_MASK_COPZ
11545                                       : OP_MASK_COPZ);
11546
11547                 my_getExpression (&imm_expr, s);
11548                 check_absolute_expr (ip, &imm_expr);
11549                 if ((unsigned long) imm_expr.X_add_number > mask)
11550                   as_warn (_("Coproccesor code > %u bits (%lu)"),
11551                            mips_opts.micromips ? 23U : 25U,
11552                            (unsigned long) imm_expr.X_add_number);
11553                 INSERT_OPERAND (mips_opts.micromips,
11554                                 COPZ, *ip, imm_expr.X_add_number);
11555                 imm_expr.X_op = O_absent;
11556                 s = expr_end;
11557               }
11558               continue;
11559
11560             case 'J':           /* 19-bit WAIT code.  */
11561               gas_assert (!mips_opts.micromips);
11562               my_getExpression (&imm_expr, s);
11563               check_absolute_expr (ip, &imm_expr);
11564               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
11565                 {
11566                   as_warn (_("Illegal 19-bit code (%lu)"),
11567                            (unsigned long) imm_expr.X_add_number);
11568                   imm_expr.X_add_number &= OP_MASK_CODE19;
11569                 }
11570               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
11571               imm_expr.X_op = O_absent;
11572               s = expr_end;
11573               continue;
11574
11575             case 'P':           /* Performance register.  */
11576               gas_assert (!mips_opts.micromips);
11577               my_getExpression (&imm_expr, s);
11578               check_absolute_expr (ip, &imm_expr);
11579               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
11580                 as_warn (_("Invalid performance register (%lu)"),
11581                          (unsigned long) imm_expr.X_add_number);
11582               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
11583               imm_expr.X_op = O_absent;
11584               s = expr_end;
11585               continue;
11586
11587             case 'G':           /* Coprocessor destination register.  */
11588               {
11589                 unsigned long opcode = ip->insn_opcode;
11590                 unsigned long mask;
11591                 unsigned int types;
11592                 int cop0;
11593
11594                 if (mips_opts.micromips)
11595                   {
11596                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
11597                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
11598                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
11599                     opcode &= mask;
11600                     switch (opcode)
11601                       {
11602                       case 0x000000fc:                          /* mfc0  */
11603                       case 0x000002fc:                          /* mtc0  */
11604                       case 0x580000fc:                          /* dmfc0 */
11605                       case 0x580002fc:                          /* dmtc0 */
11606                         cop0 = 1;
11607                         break;
11608                       default:
11609                         cop0 = 0;
11610                         break;
11611                       }
11612                   }
11613                 else
11614                   {
11615                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
11616                     cop0 = opcode == OP_OP_COP0;
11617                   }
11618                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
11619                 ok = reg_lookup (&s, types, &regno);
11620                 if (mips_opts.micromips)
11621                   INSERT_OPERAND (1, RS, *ip, regno);
11622                 else
11623                   INSERT_OPERAND (0, RD, *ip, regno);
11624                 if (ok)
11625                   {
11626                     lastregno = regno;
11627                     continue;
11628                   }
11629               }
11630               break;
11631
11632             case 'y':           /* ALNV.PS source register.  */
11633               gas_assert (mips_opts.micromips);
11634               goto do_reg;
11635             case 'x':           /* Ignore register name.  */
11636             case 'U':           /* Destination register (CLO/CLZ).  */
11637             case 'g':           /* Coprocessor destination register.  */
11638               gas_assert (!mips_opts.micromips);
11639             case 'b':           /* Base register.  */
11640             case 'd':           /* Destination register.  */
11641             case 's':           /* Source register.  */
11642             case 't':           /* Target register.  */
11643             case 'r':           /* Both target and source.  */
11644             case 'v':           /* Both dest and source.  */
11645             case 'w':           /* Both dest and target.  */
11646             case 'E':           /* Coprocessor target register.  */
11647             case 'K':           /* RDHWR destination register.  */
11648             case 'z':           /* Must be zero register.  */
11649             do_reg:
11650               s_reset = s;
11651               if (*args == 'E' || *args == 'K')
11652                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
11653               else
11654                 {
11655                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
11656                   if (regno == AT && mips_opts.at)
11657                     {
11658                       if (mips_opts.at == ATREG)
11659                         as_warn (_("Used $at without \".set noat\""));
11660                       else
11661                         as_warn (_("Used $%u with \".set at=$%u\""),
11662                                  regno, mips_opts.at);
11663                     }
11664                 }
11665               if (ok)
11666                 {
11667                   c = *args;
11668                   if (*s == ' ')
11669                     ++s;
11670                   if (args[1] != *s)
11671                     {
11672                       if (c == 'r' || c == 'v' || c == 'w')
11673                         {
11674                           regno = lastregno;
11675                           s = s_reset;
11676                           ++args;
11677                         }
11678                     }
11679                   /* 'z' only matches $0.  */
11680                   if (c == 'z' && regno != 0)
11681                     break;
11682
11683                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
11684                     {
11685                       if (regno == lastregno)
11686                         {
11687                           insn_error
11688                             = _("Source and destination must be different");
11689                           continue;
11690                         }
11691                       if (regno == 31 && lastregno == 0xffffffff)
11692                         {
11693                           insn_error
11694                             = _("A destination register must be supplied");
11695                           continue;
11696                         }
11697                     }
11698                   /* Now that we have assembled one operand, we use the args
11699                      string to figure out where it goes in the instruction.  */
11700                   switch (c)
11701                     {
11702                     case 'r':
11703                     case 's':
11704                     case 'v':
11705                     case 'b':
11706                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
11707                       break;
11708
11709                     case 'K':
11710                       if (mips_opts.micromips)
11711                         INSERT_OPERAND (1, RS, *ip, regno);
11712                       else
11713                         INSERT_OPERAND (0, RD, *ip, regno);
11714                       break;
11715
11716                     case 'd':
11717                     case 'g':
11718                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
11719                       break;
11720
11721                     case 'U':
11722                       gas_assert (!mips_opts.micromips);
11723                       INSERT_OPERAND (0, RD, *ip, regno);
11724                       INSERT_OPERAND (0, RT, *ip, regno);
11725                       break;
11726
11727                     case 'w':
11728                     case 't':
11729                     case 'E':
11730                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
11731                       break;
11732
11733                     case 'y':
11734                       gas_assert (mips_opts.micromips);
11735                       INSERT_OPERAND (1, RS3, *ip, regno);
11736                       break;
11737
11738                     case 'x':
11739                       /* This case exists because on the r3000 trunc
11740                          expands into a macro which requires a gp
11741                          register.  On the r6000 or r4000 it is
11742                          assembled into a single instruction which
11743                          ignores the register.  Thus the insn version
11744                          is MIPS_ISA2 and uses 'x', and the macro
11745                          version is MIPS_ISA1 and uses 't'.  */
11746                       break;
11747
11748                     case 'z':
11749                       /* This case is for the div instruction, which
11750                          acts differently if the destination argument
11751                          is $0.  This only matches $0, and is checked
11752                          outside the switch.  */
11753                       break;
11754                     }
11755                   lastregno = regno;
11756                   continue;
11757                 }
11758               switch (*args++)
11759                 {
11760                 case 'r':
11761                 case 'v':
11762                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11763                   continue;
11764
11765                 case 'w':
11766                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11767                   continue;
11768                 }
11769               break;
11770
11771             case 'O':           /* MDMX alignment immediate constant.  */
11772               gas_assert (!mips_opts.micromips);
11773               my_getExpression (&imm_expr, s);
11774               check_absolute_expr (ip, &imm_expr);
11775               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
11776                 as_warn (_("Improper align amount (%ld), using low bits"),
11777                          (long) imm_expr.X_add_number);
11778               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
11779               imm_expr.X_op = O_absent;
11780               s = expr_end;
11781               continue;
11782
11783             case 'Q':           /* MDMX vector, element sel, or const.  */
11784               if (s[0] != '$')
11785                 {
11786                   /* MDMX Immediate.  */
11787                   gas_assert (!mips_opts.micromips);
11788                   my_getExpression (&imm_expr, s);
11789                   check_absolute_expr (ip, &imm_expr);
11790                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
11791                     as_warn (_("Invalid MDMX Immediate (%ld)"),
11792                              (long) imm_expr.X_add_number);
11793                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
11794                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11795                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
11796                   else
11797                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
11798                   imm_expr.X_op = O_absent;
11799                   s = expr_end;
11800                   continue;
11801                 }
11802               /* Not MDMX Immediate.  Fall through.  */
11803             case 'X':           /* MDMX destination register.  */
11804             case 'Y':           /* MDMX source register.  */
11805             case 'Z':           /* MDMX target register.  */
11806               is_mdmx = 1;
11807             case 'W':
11808               gas_assert (!mips_opts.micromips);
11809             case 'D':           /* Floating point destination register.  */
11810             case 'S':           /* Floating point source register.  */
11811             case 'T':           /* Floating point target register.  */
11812             case 'R':           /* Floating point source register.  */
11813             case 'V':
11814               rtype = RTYPE_FPU;
11815               if (is_mdmx
11816                   || (mips_opts.ase_mdmx
11817                       && (ip->insn_mo->pinfo & FP_D)
11818                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
11819                                                 | INSN_COPROC_MEMORY_DELAY
11820                                                 | INSN_LOAD_COPROC_DELAY
11821                                                 | INSN_LOAD_MEMORY_DELAY
11822                                                 | INSN_STORE_MEMORY))))
11823                 rtype |= RTYPE_VEC;
11824               s_reset = s;
11825               if (reg_lookup (&s, rtype, &regno))
11826                 {
11827                   if ((regno & 1) != 0
11828                       && HAVE_32BIT_FPRS
11829                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
11830                     as_warn (_("Float register should be even, was %d"),
11831                              regno);
11832
11833                   c = *args;
11834                   if (*s == ' ')
11835                     ++s;
11836                   if (args[1] != *s)
11837                     {
11838                       if (c == 'V' || c == 'W')
11839                         {
11840                           regno = lastregno;
11841                           s = s_reset;
11842                           ++args;
11843                         }
11844                     }
11845                   switch (c)
11846                     {
11847                     case 'D':
11848                     case 'X':
11849                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
11850                       break;
11851
11852                     case 'V':
11853                     case 'S':
11854                     case 'Y':
11855                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
11856                       break;
11857
11858                     case 'Q':
11859                       /* This is like 'Z', but also needs to fix the MDMX
11860                          vector/scalar select bits.  Note that the
11861                          scalar immediate case is handled above.  */
11862                       if (*s == '[')
11863                         {
11864                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
11865                           int max_el = (is_qh ? 3 : 7);
11866                           s++;
11867                           my_getExpression(&imm_expr, s);
11868                           check_absolute_expr (ip, &imm_expr);
11869                           s = expr_end;
11870                           if (imm_expr.X_add_number > max_el)
11871                             as_bad (_("Bad element selector %ld"),
11872                                     (long) imm_expr.X_add_number);
11873                           imm_expr.X_add_number &= max_el;
11874                           ip->insn_opcode |= (imm_expr.X_add_number
11875                                               << (OP_SH_VSEL +
11876                                                   (is_qh ? 2 : 1)));
11877                           imm_expr.X_op = O_absent;
11878                           if (*s != ']')
11879                             as_warn (_("Expecting ']' found '%s'"), s);
11880                           else
11881                             s++;
11882                         }
11883                       else
11884                         {
11885                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
11886                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
11887                                                 << OP_SH_VSEL);
11888                           else
11889                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
11890                                                 OP_SH_VSEL);
11891                         }
11892                       /* Fall through.  */
11893                     case 'W':
11894                     case 'T':
11895                     case 'Z':
11896                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
11897                       break;
11898
11899                     case 'R':
11900                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
11901                       break;
11902                     }
11903                   lastregno = regno;
11904                   continue;
11905                 }
11906
11907               switch (*args++)
11908                 {
11909                 case 'V':
11910                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11911                   continue;
11912
11913                 case 'W':
11914                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
11915                   continue;
11916                 }
11917               break;
11918
11919             case 'I':
11920               my_getExpression (&imm_expr, s);
11921               if (imm_expr.X_op != O_big
11922                   && imm_expr.X_op != O_constant)
11923                 insn_error = _("absolute expression required");
11924               if (HAVE_32BIT_GPRS)
11925                 normalize_constant_expr (&imm_expr);
11926               s = expr_end;
11927               continue;
11928
11929             case 'A':
11930               my_getExpression (&offset_expr, s);
11931               normalize_address_expr (&offset_expr);
11932               *imm_reloc = BFD_RELOC_32;
11933               s = expr_end;
11934               continue;
11935
11936             case 'F':
11937             case 'L':
11938             case 'f':
11939             case 'l':
11940               {
11941                 int f64;
11942                 int using_gprs;
11943                 char *save_in;
11944                 char *err;
11945                 unsigned char temp[8];
11946                 int len;
11947                 unsigned int length;
11948                 segT seg;
11949                 subsegT subseg;
11950                 char *p;
11951
11952                 /* These only appear as the last operand in an
11953                    instruction, and every instruction that accepts
11954                    them in any variant accepts them in all variants.
11955                    This means we don't have to worry about backing out
11956                    any changes if the instruction does not match.
11957
11958                    The difference between them is the size of the
11959                    floating point constant and where it goes.  For 'F'
11960                    and 'L' the constant is 64 bits; for 'f' and 'l' it
11961                    is 32 bits.  Where the constant is placed is based
11962                    on how the MIPS assembler does things:
11963                     F -- .rdata
11964                     L -- .lit8
11965                     f -- immediate value
11966                     l -- .lit4
11967
11968                     The .lit4 and .lit8 sections are only used if
11969                     permitted by the -G argument.
11970
11971                     The code below needs to know whether the target register
11972                     is 32 or 64 bits wide.  It relies on the fact 'f' and
11973                     'F' are used with GPR-based instructions and 'l' and
11974                     'L' are used with FPR-based instructions.  */
11975
11976                 f64 = *args == 'F' || *args == 'L';
11977                 using_gprs = *args == 'F' || *args == 'f';
11978
11979                 save_in = input_line_pointer;
11980                 input_line_pointer = s;
11981                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
11982                 length = len;
11983                 s = input_line_pointer;
11984                 input_line_pointer = save_in;
11985                 if (err != NULL && *err != '\0')
11986                   {
11987                     as_bad (_("Bad floating point constant: %s"), err);
11988                     memset (temp, '\0', sizeof temp);
11989                     length = f64 ? 8 : 4;
11990                   }
11991
11992                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
11993
11994                 if (*args == 'f'
11995                     || (*args == 'l'
11996                         && (g_switch_value < 4
11997                             || (temp[0] == 0 && temp[1] == 0)
11998                             || (temp[2] == 0 && temp[3] == 0))))
11999                   {
12000                     imm_expr.X_op = O_constant;
12001                     if (!target_big_endian)
12002                       imm_expr.X_add_number = bfd_getl32 (temp);
12003                     else
12004                       imm_expr.X_add_number = bfd_getb32 (temp);
12005                   }
12006                 else if (length > 4
12007                          && !mips_disable_float_construction
12008                          /* Constants can only be constructed in GPRs and
12009                             copied to FPRs if the GPRs are at least as wide
12010                             as the FPRs.  Force the constant into memory if
12011                             we are using 64-bit FPRs but the GPRs are only
12012                             32 bits wide.  */
12013                          && (using_gprs
12014                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12015                          && ((temp[0] == 0 && temp[1] == 0)
12016                              || (temp[2] == 0 && temp[3] == 0))
12017                          && ((temp[4] == 0 && temp[5] == 0)
12018                              || (temp[6] == 0 && temp[7] == 0)))
12019                   {
12020                     /* The value is simple enough to load with a couple of
12021                        instructions.  If using 32-bit registers, set
12022                        imm_expr to the high order 32 bits and offset_expr to
12023                        the low order 32 bits.  Otherwise, set imm_expr to
12024                        the entire 64 bit constant.  */
12025                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12026                       {
12027                         imm_expr.X_op = O_constant;
12028                         offset_expr.X_op = O_constant;
12029                         if (!target_big_endian)
12030                           {
12031                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12032                             offset_expr.X_add_number = bfd_getl32 (temp);
12033                           }
12034                         else
12035                           {
12036                             imm_expr.X_add_number = bfd_getb32 (temp);
12037                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12038                           }
12039                         if (offset_expr.X_add_number == 0)
12040                           offset_expr.X_op = O_absent;
12041                       }
12042                     else if (sizeof (imm_expr.X_add_number) > 4)
12043                       {
12044                         imm_expr.X_op = O_constant;
12045                         if (!target_big_endian)
12046                           imm_expr.X_add_number = bfd_getl64 (temp);
12047                         else
12048                           imm_expr.X_add_number = bfd_getb64 (temp);
12049                       }
12050                     else
12051                       {
12052                         imm_expr.X_op = O_big;
12053                         imm_expr.X_add_number = 4;
12054                         if (!target_big_endian)
12055                           {
12056                             generic_bignum[0] = bfd_getl16 (temp);
12057                             generic_bignum[1] = bfd_getl16 (temp + 2);
12058                             generic_bignum[2] = bfd_getl16 (temp + 4);
12059                             generic_bignum[3] = bfd_getl16 (temp + 6);
12060                           }
12061                         else
12062                           {
12063                             generic_bignum[0] = bfd_getb16 (temp + 6);
12064                             generic_bignum[1] = bfd_getb16 (temp + 4);
12065                             generic_bignum[2] = bfd_getb16 (temp + 2);
12066                             generic_bignum[3] = bfd_getb16 (temp);
12067                           }
12068                       }
12069                   }
12070                 else
12071                   {
12072                     const char *newname;
12073                     segT new_seg;
12074
12075                     /* Switch to the right section.  */
12076                     seg = now_seg;
12077                     subseg = now_subseg;
12078                     switch (*args)
12079                       {
12080                       default: /* unused default case avoids warnings.  */
12081                       case 'L':
12082                         newname = RDATA_SECTION_NAME;
12083                         if (g_switch_value >= 8)
12084                           newname = ".lit8";
12085                         break;
12086                       case 'F':
12087                         newname = RDATA_SECTION_NAME;
12088                         break;
12089                       case 'l':
12090                         gas_assert (g_switch_value >= 4);
12091                         newname = ".lit4";
12092                         break;
12093                       }
12094                     new_seg = subseg_new (newname, (subsegT) 0);
12095                     if (IS_ELF)
12096                       bfd_set_section_flags (stdoutput, new_seg,
12097                                              (SEC_ALLOC
12098                                               | SEC_LOAD
12099                                               | SEC_READONLY
12100                                               | SEC_DATA));
12101                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12102                     if (IS_ELF && strncmp (TARGET_OS, "elf", 3) != 0)
12103                       record_alignment (new_seg, 4);
12104                     else
12105                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12106                     if (seg == now_seg)
12107                       as_bad (_("Can't use floating point insn in this section"));
12108
12109                     /* Set the argument to the current address in the
12110                        section.  */
12111                     offset_expr.X_op = O_symbol;
12112                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12113                     offset_expr.X_add_number = 0;
12114
12115                     /* Put the floating point number into the section.  */
12116                     p = frag_more ((int) length);
12117                     memcpy (p, temp, length);
12118
12119                     /* Switch back to the original section.  */
12120                     subseg_set (seg, subseg);
12121                   }
12122               }
12123               continue;
12124
12125             case 'i':           /* 16-bit unsigned immediate.  */
12126             case 'j':           /* 16-bit signed immediate.  */
12127               *imm_reloc = BFD_RELOC_LO16;
12128               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0)
12129                 {
12130                   int more;
12131                   offsetT minval, maxval;
12132
12133                   more = (insn + 1 < past
12134                           && strcmp (insn->name, insn[1].name) == 0);
12135
12136                   /* If the expression was written as an unsigned number,
12137                      only treat it as signed if there are no more
12138                      alternatives.  */
12139                   if (more
12140                       && *args == 'j'
12141                       && sizeof (imm_expr.X_add_number) <= 4
12142                       && imm_expr.X_op == O_constant
12143                       && imm_expr.X_add_number < 0
12144                       && imm_expr.X_unsigned
12145                       && HAVE_64BIT_GPRS)
12146                     break;
12147
12148                   /* For compatibility with older assemblers, we accept
12149                      0x8000-0xffff as signed 16-bit numbers when only
12150                      signed numbers are allowed.  */
12151                   if (*args == 'i')
12152                     minval = 0, maxval = 0xffff;
12153                   else if (more)
12154                     minval = -0x8000, maxval = 0x7fff;
12155                   else
12156                     minval = -0x8000, maxval = 0xffff;
12157
12158                   if (imm_expr.X_op != O_constant
12159                       || imm_expr.X_add_number < minval
12160                       || imm_expr.X_add_number > maxval)
12161                     {
12162                       if (more)
12163                         break;
12164                       if (imm_expr.X_op == O_constant
12165                           || imm_expr.X_op == O_big)
12166                         as_bad (_("Expression out of range"));
12167                     }
12168                 }
12169               s = expr_end;
12170               continue;
12171
12172             case 'o':           /* 16-bit offset.  */
12173               offset_reloc[0] = BFD_RELOC_LO16;
12174               offset_reloc[1] = BFD_RELOC_UNUSED;
12175               offset_reloc[2] = BFD_RELOC_UNUSED;
12176
12177               /* Check whether there is only a single bracketed expression
12178                  left.  If so, it must be the base register and the
12179                  constant must be zero.  */
12180               if (*s == '(' && strchr (s + 1, '(') == 0)
12181                 {
12182                   offset_expr.X_op = O_constant;
12183                   offset_expr.X_add_number = 0;
12184                   continue;
12185                 }
12186
12187               /* If this value won't fit into a 16 bit offset, then go
12188                  find a macro that will generate the 32 bit offset
12189                  code pattern.  */
12190               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12191                   && (offset_expr.X_op != O_constant
12192                       || offset_expr.X_add_number >= 0x8000
12193                       || offset_expr.X_add_number < -0x8000))
12194                 break;
12195
12196               s = expr_end;
12197               continue;
12198
12199             case 'p':           /* PC-relative offset.  */
12200               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12201               my_getExpression (&offset_expr, s);
12202               s = expr_end;
12203               continue;
12204
12205             case 'u':           /* Upper 16 bits.  */
12206               if (my_getSmallExpression (&imm_expr, imm_reloc, s) == 0
12207                   && imm_expr.X_op == O_constant
12208                   && (imm_expr.X_add_number < 0
12209                       || imm_expr.X_add_number >= 0x10000))
12210                 as_bad (_("lui expression (%lu) not in range 0..65535"),
12211                         (unsigned long) imm_expr.X_add_number);
12212               s = expr_end;
12213               continue;
12214
12215             case 'a':           /* 26-bit address.  */
12216               *offset_reloc = BFD_RELOC_MIPS_JMP;
12217               my_getExpression (&offset_expr, s);
12218               s = expr_end;
12219               continue;
12220
12221             case 'N':           /* 3-bit branch condition code.  */
12222             case 'M':           /* 3-bit compare condition code.  */
12223               rtype = RTYPE_CCC;
12224               if (ip->insn_mo->pinfo & (FP_D | FP_S))
12225                 rtype |= RTYPE_FCC;
12226               if (!reg_lookup (&s, rtype, &regno))
12227                 break;
12228               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
12229                    || strcmp (str + strlen (str) - 5, "any2f") == 0
12230                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
12231                   && (regno & 1) != 0)
12232                 as_warn (_("Condition code register should be even for %s, "
12233                            "was %d"),
12234                          str, regno);
12235               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
12236                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
12237                   && (regno & 3) != 0)
12238                 as_warn (_("Condition code register should be 0 or 4 for %s, "
12239                            "was %d"),
12240                          str, regno);
12241               if (*args == 'N')
12242                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
12243               else
12244                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
12245               continue;
12246
12247             case 'H':
12248               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
12249                 s += 2;
12250               if (ISDIGIT (*s))
12251                 {
12252                   c = 0;
12253                   do
12254                     {
12255                       c *= 10;
12256                       c += *s - '0';
12257                       ++s;
12258                     }
12259                   while (ISDIGIT (*s));
12260                 }
12261               else
12262                 c = 8; /* Invalid sel value.  */
12263
12264               if (c > 7)
12265                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
12266               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
12267               continue;
12268
12269             case 'e':
12270               gas_assert (!mips_opts.micromips);
12271               /* Must be at least one digit.  */
12272               my_getExpression (&imm_expr, s);
12273               check_absolute_expr (ip, &imm_expr);
12274
12275               if ((unsigned long) imm_expr.X_add_number
12276                   > (unsigned long) OP_MASK_VECBYTE)
12277                 {
12278                   as_bad (_("bad byte vector index (%ld)"),
12279                            (long) imm_expr.X_add_number);
12280                   imm_expr.X_add_number = 0;
12281                 }
12282
12283               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
12284               imm_expr.X_op = O_absent;
12285               s = expr_end;
12286               continue;
12287
12288             case '%':
12289               gas_assert (!mips_opts.micromips);
12290               my_getExpression (&imm_expr, s);
12291               check_absolute_expr (ip, &imm_expr);
12292
12293               if ((unsigned long) imm_expr.X_add_number
12294                   > (unsigned long) OP_MASK_VECALIGN)
12295                 {
12296                   as_bad (_("bad byte vector index (%ld)"),
12297                            (long) imm_expr.X_add_number);
12298                   imm_expr.X_add_number = 0;
12299                 }
12300
12301               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
12302               imm_expr.X_op = O_absent;
12303               s = expr_end;
12304               continue;
12305
12306             case 'm':           /* Opcode extension character.  */
12307               gas_assert (mips_opts.micromips);
12308               c = *++args;
12309               switch (c)
12310                 {
12311                 case 'r':
12312                   if (strncmp (s, "$pc", 3) == 0)
12313                     {
12314                       s += 3;
12315                       continue;
12316                     }
12317                   break;
12318
12319                 case 'a':
12320                 case 'b':
12321                 case 'c':
12322                 case 'd':
12323                 case 'e':
12324                 case 'f':
12325                 case 'g':
12326                 case 'h':
12327                 case 'i':
12328                 case 'j':
12329                 case 'l':
12330                 case 'm':
12331                 case 'n':
12332                 case 'p':
12333                 case 'q':
12334                 case 's':
12335                 case 't':
12336                 case 'x':
12337                 case 'y':
12338                 case 'z':
12339                   s_reset = s;
12340                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12341                   if (regno == AT && mips_opts.at)
12342                     {
12343                       if (mips_opts.at == ATREG)
12344                         as_warn (_("Used $at without \".set noat\""));
12345                       else
12346                         as_warn (_("Used $%u with \".set at=$%u\""),
12347                                  regno, mips_opts.at);
12348                     }
12349                   if (!ok)
12350                     {
12351                       if (c == 'c')
12352                         {
12353                           gas_assert (args[1] == ',');
12354                           regno = lastregno;
12355                           ++args;
12356                         }
12357                       else if (c == 't')
12358                         {
12359                           gas_assert (args[1] == ',');
12360                           ++args;
12361                           continue;                     /* Nothing to do.  */
12362                         }
12363                       else
12364                         break;
12365                     }
12366
12367                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
12368                     {
12369                       if (regno == lastregno)
12370                         {
12371                           insn_error
12372                             = _("Source and destination must be different");
12373                           continue;
12374                         }
12375                       if (regno == 31 && lastregno == 0xffffffff)
12376                         {
12377                           insn_error
12378                             = _("A destination register must be supplied");
12379                           continue;
12380                         }
12381                     }
12382
12383                   if (*s == ' ')
12384                     ++s;
12385                   if (args[1] != *s)
12386                     {
12387                       if (c == 'e')
12388                         {
12389                           gas_assert (args[1] == ',');
12390                           regno = lastregno;
12391                           s = s_reset;
12392                           ++args;
12393                         }
12394                       else if (c == 't')
12395                         {
12396                           gas_assert (args[1] == ',');
12397                           s = s_reset;
12398                           ++args;
12399                           continue;                     /* Nothing to do.  */
12400                         }
12401                     }
12402
12403                   /* Make sure regno is the same as lastregno.  */
12404                   if (c == 't' && regno != lastregno)
12405                     break;
12406
12407                   /* Make sure regno is the same as destregno.  */
12408                   if (c == 'x' && regno != destregno)
12409                     break;
12410
12411                   /* We need to save regno, before regno maps to the
12412                      microMIPS register encoding.  */
12413                   lastregno = regno;
12414
12415                   if (c == 'f')
12416                     destregno = regno;
12417
12418                   switch (c)
12419                     {
12420                       case 'a':
12421                         if (regno != GP)
12422                           regno = ILLEGAL_REG;
12423                         break;
12424
12425                       case 'b':
12426                         regno = mips32_to_micromips_reg_b_map[regno];
12427                         break;
12428
12429                       case 'c':
12430                         regno = mips32_to_micromips_reg_c_map[regno];
12431                         break;
12432
12433                       case 'd':
12434                         regno = mips32_to_micromips_reg_d_map[regno];
12435                         break;
12436
12437                       case 'e':
12438                         regno = mips32_to_micromips_reg_e_map[regno];
12439                         break;
12440
12441                       case 'f':
12442                         regno = mips32_to_micromips_reg_f_map[regno];
12443                         break;
12444
12445                       case 'g':
12446                         regno = mips32_to_micromips_reg_g_map[regno];
12447                         break;
12448
12449                       case 'h':
12450                         regno = mips32_to_micromips_reg_h_map[regno];
12451                         break;
12452
12453                       case 'i':
12454                         switch (EXTRACT_OPERAND (1, MI, *ip))
12455                           {
12456                             case 4:
12457                               if (regno == 21)
12458                                 regno = 3;
12459                               else if (regno == 22)
12460                                 regno = 4;
12461                               else if (regno == 5)
12462                                 regno = 5;
12463                               else if (regno == 6)
12464                                 regno = 6;
12465                               else if (regno == 7)
12466                                 regno = 7;
12467                               else
12468                                 regno = ILLEGAL_REG;
12469                               break;
12470
12471                             case 5:
12472                               if (regno == 6)
12473                                 regno = 0;
12474                               else if (regno == 7)
12475                                 regno = 1;
12476                               else
12477                                 regno = ILLEGAL_REG;
12478                               break;
12479
12480                             case 6:
12481                               if (regno == 7)
12482                                 regno = 2;
12483                               else
12484                                 regno = ILLEGAL_REG;
12485                               break;
12486
12487                             default:
12488                               regno = ILLEGAL_REG;
12489                               break;
12490                           }
12491                         break;
12492
12493                       case 'l':
12494                         regno = mips32_to_micromips_reg_l_map[regno];
12495                         break;
12496
12497                       case 'm':
12498                         regno = mips32_to_micromips_reg_m_map[regno];
12499                         break;
12500
12501                       case 'n':
12502                         regno = mips32_to_micromips_reg_n_map[regno];
12503                         break;
12504
12505                       case 'q':
12506                         regno = mips32_to_micromips_reg_q_map[regno];
12507                         break;
12508
12509                       case 's':
12510                         if (regno != SP)
12511                           regno = ILLEGAL_REG;
12512                         break;
12513
12514                       case 'y':
12515                         if (regno != 31)
12516                           regno = ILLEGAL_REG;
12517                         break;
12518
12519                       case 'z':
12520                         if (regno != ZERO)
12521                           regno = ILLEGAL_REG;
12522                         break;
12523
12524                       case 'j': /* Do nothing.  */
12525                       case 'p':
12526                       case 't':
12527                       case 'x':
12528                         break;
12529
12530                       default:
12531                         internalError ();
12532                     }
12533
12534                   if (regno == ILLEGAL_REG)
12535                     break;
12536
12537                   switch (c)
12538                     {
12539                       case 'b':
12540                         INSERT_OPERAND (1, MB, *ip, regno);
12541                         break;
12542
12543                       case 'c':
12544                         INSERT_OPERAND (1, MC, *ip, regno);
12545                         break;
12546
12547                       case 'd':
12548                         INSERT_OPERAND (1, MD, *ip, regno);
12549                         break;
12550
12551                       case 'e':
12552                         INSERT_OPERAND (1, ME, *ip, regno);
12553                         break;
12554
12555                       case 'f':
12556                         INSERT_OPERAND (1, MF, *ip, regno);
12557                         break;
12558
12559                       case 'g':
12560                         INSERT_OPERAND (1, MG, *ip, regno);
12561                         break;
12562
12563                       case 'h':
12564                         INSERT_OPERAND (1, MH, *ip, regno);
12565                         break;
12566
12567                       case 'i':
12568                         INSERT_OPERAND (1, MI, *ip, regno);
12569                         break;
12570
12571                       case 'j':
12572                         INSERT_OPERAND (1, MJ, *ip, regno);
12573                         break;
12574
12575                       case 'l':
12576                         INSERT_OPERAND (1, ML, *ip, regno);
12577                         break;
12578
12579                       case 'm':
12580                         INSERT_OPERAND (1, MM, *ip, regno);
12581                         break;
12582
12583                       case 'n':
12584                         INSERT_OPERAND (1, MN, *ip, regno);
12585                         break;
12586
12587                       case 'p':
12588                         INSERT_OPERAND (1, MP, *ip, regno);
12589                         break;
12590
12591                       case 'q':
12592                         INSERT_OPERAND (1, MQ, *ip, regno);
12593                         break;
12594
12595                       case 'a': /* Do nothing.  */
12596                       case 's': /* Do nothing.  */
12597                       case 't': /* Do nothing.  */
12598                       case 'x': /* Do nothing.  */
12599                       case 'y': /* Do nothing.  */
12600                       case 'z': /* Do nothing.  */
12601                         break;
12602
12603                       default:
12604                         internalError ();
12605                     }
12606                   continue;
12607
12608                 case 'A':
12609                   {
12610                     bfd_reloc_code_real_type r[3];
12611                     expressionS ep;
12612                     int imm;
12613
12614                     /* Check whether there is only a single bracketed
12615                        expression left.  If so, it must be the base register
12616                        and the constant must be zero.  */
12617                     if (*s == '(' && strchr (s + 1, '(') == 0)
12618                       {
12619                         INSERT_OPERAND (1, IMMA, *ip, 0);
12620                         continue;
12621                       }
12622
12623                     if (my_getSmallExpression (&ep, r, s) > 0
12624                         || !expr_const_in_range (&ep, -64, 64, 2))
12625                       break;
12626
12627                     imm = ep.X_add_number >> 2;
12628                     INSERT_OPERAND (1, IMMA, *ip, imm);
12629                   }
12630                   s = expr_end;
12631                   continue;
12632
12633                 case 'B':
12634                   {
12635                     bfd_reloc_code_real_type r[3];
12636                     expressionS ep;
12637                     int imm;
12638
12639                     if (my_getSmallExpression (&ep, r, s) > 0
12640                         || ep.X_op != O_constant)
12641                       break;
12642
12643                     for (imm = 0; imm < 8; imm++)
12644                       if (micromips_imm_b_map[imm] == ep.X_add_number)
12645                         break;
12646                     if (imm >= 8)
12647                       break;
12648
12649                     INSERT_OPERAND (1, IMMB, *ip, imm);
12650                   }
12651                   s = expr_end;
12652                   continue;
12653
12654                 case 'C':
12655                   {
12656                     bfd_reloc_code_real_type r[3];
12657                     expressionS ep;
12658                     int imm;
12659
12660                     if (my_getSmallExpression (&ep, r, s) > 0
12661                         || ep.X_op != O_constant)
12662                       break;
12663
12664                     for (imm = 0; imm < 16; imm++)
12665                       if (micromips_imm_c_map[imm] == ep.X_add_number)
12666                         break;
12667                     if (imm >= 16)
12668                       break;
12669
12670                     INSERT_OPERAND (1, IMMC, *ip, imm);
12671                   }
12672                   s = expr_end;
12673                   continue;
12674
12675                 case 'D':       /* pc relative offset */
12676                 case 'E':       /* pc relative offset */
12677                   my_getExpression (&offset_expr, s);
12678                   if (offset_expr.X_op == O_register)
12679                     break;
12680
12681                   *offset_reloc = (int) BFD_RELOC_UNUSED + c;
12682                   s = expr_end;
12683                   continue;
12684
12685                 case 'F':
12686                   {
12687                     bfd_reloc_code_real_type r[3];
12688                     expressionS ep;
12689                     int imm;
12690
12691                     if (my_getSmallExpression (&ep, r, s) > 0
12692                         || !expr_const_in_range (&ep, 0, 16, 0))
12693                       break;
12694
12695                     imm = ep.X_add_number;
12696                     INSERT_OPERAND (1, IMMF, *ip, imm);
12697                   }
12698                   s = expr_end;
12699                   continue;
12700
12701                 case 'G':
12702                   {
12703                     bfd_reloc_code_real_type r[3];
12704                     expressionS ep;
12705                     int imm;
12706
12707                     /* Check whether there is only a single bracketed
12708                        expression left.  If so, it must be the base register
12709                        and the constant must be zero.  */
12710                     if (*s == '(' && strchr (s + 1, '(') == 0)
12711                       {
12712                         INSERT_OPERAND (1, IMMG, *ip, 0);
12713                         continue;
12714                       }
12715
12716                     if (my_getSmallExpression (&ep, r, s) > 0
12717                         || !expr_const_in_range (&ep, -1, 15, 0))
12718                       break;
12719
12720                     imm = ep.X_add_number & 15;
12721                     INSERT_OPERAND (1, IMMG, *ip, imm);
12722                   }
12723                   s = expr_end;
12724                   continue;
12725
12726                 case 'H':
12727                   {
12728                     bfd_reloc_code_real_type r[3];
12729                     expressionS ep;
12730                     int imm;
12731
12732                     /* Check whether there is only a single bracketed
12733                        expression left.  If so, it must be the base register
12734                        and the constant must be zero.  */
12735                     if (*s == '(' && strchr (s + 1, '(') == 0)
12736                       {
12737                         INSERT_OPERAND (1, IMMH, *ip, 0);
12738                         continue;
12739                       }
12740
12741                     if (my_getSmallExpression (&ep, r, s) > 0
12742                         || !expr_const_in_range (&ep, 0, 16, 1))
12743                       break;
12744
12745                     imm = ep.X_add_number >> 1;
12746                     INSERT_OPERAND (1, IMMH, *ip, imm);
12747                   }
12748                   s = expr_end;
12749                   continue;
12750
12751                 case 'I':
12752                   {
12753                     bfd_reloc_code_real_type r[3];
12754                     expressionS ep;
12755                     int imm;
12756
12757                     if (my_getSmallExpression (&ep, r, s) > 0
12758                         || !expr_const_in_range (&ep, -1, 127, 0))
12759                       break;
12760
12761                     imm = ep.X_add_number & 127;
12762                     INSERT_OPERAND (1, IMMI, *ip, imm);
12763                   }
12764                   s = expr_end;
12765                   continue;
12766
12767                 case 'J':
12768                   {
12769                     bfd_reloc_code_real_type r[3];
12770                     expressionS ep;
12771                     int imm;
12772
12773                     /* Check whether there is only a single bracketed
12774                        expression left.  If so, it must be the base register
12775                        and the constant must be zero.  */
12776                     if (*s == '(' && strchr (s + 1, '(') == 0)
12777                       {
12778                         INSERT_OPERAND (1, IMMJ, *ip, 0);
12779                         continue;
12780                       }
12781
12782                     if (my_getSmallExpression (&ep, r, s) > 0
12783                         || !expr_const_in_range (&ep, 0, 16, 2))
12784                       break;
12785
12786                     imm = ep.X_add_number >> 2;
12787                     INSERT_OPERAND (1, IMMJ, *ip, imm);
12788                   }
12789                   s = expr_end;
12790                   continue;
12791
12792                 case 'L':
12793                   {
12794                     bfd_reloc_code_real_type r[3];
12795                     expressionS ep;
12796                     int imm;
12797
12798                     /* Check whether there is only a single bracketed
12799                        expression left.  If so, it must be the base register
12800                        and the constant must be zero.  */
12801                     if (*s == '(' && strchr (s + 1, '(') == 0)
12802                       {
12803                         INSERT_OPERAND (1, IMML, *ip, 0);
12804                         continue;
12805                       }
12806
12807                     if (my_getSmallExpression (&ep, r, s) > 0
12808                         || !expr_const_in_range (&ep, 0, 16, 0))
12809                       break;
12810
12811                     imm = ep.X_add_number;
12812                     INSERT_OPERAND (1, IMML, *ip, imm);
12813                   }
12814                   s = expr_end;
12815                   continue;
12816
12817                 case 'M':
12818                   {
12819                     bfd_reloc_code_real_type r[3];
12820                     expressionS ep;
12821                     int imm;
12822
12823                     if (my_getSmallExpression (&ep, r, s) > 0
12824                         || !expr_const_in_range (&ep, 1, 9, 0))
12825                       break;
12826
12827                     imm = ep.X_add_number & 7;
12828                     INSERT_OPERAND (1, IMMM, *ip, imm);
12829                   }
12830                   s = expr_end;
12831                   continue;
12832
12833                 case 'N':       /* Register list for lwm and swm.  */
12834                   {
12835                     /* A comma-separated list of registers and/or
12836                        dash-separated contiguous ranges including
12837                        both ra and a set of one or more registers
12838                        starting at s0 up to s3 which have to be
12839                        consecutive, e.g.:
12840
12841                        s0, ra
12842                        s0, s1, ra, s2, s3
12843                        s0-s2, ra
12844
12845                        and any permutations of these.  */
12846                     unsigned int reglist;
12847                     int imm;
12848
12849                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
12850                       break;
12851
12852                     if ((reglist & 0xfff1ffff) != 0x80010000)
12853                       break;
12854
12855                     reglist = (reglist >> 17) & 7;
12856                     reglist += 1;
12857                     if ((reglist & -reglist) != reglist)
12858                       break;
12859
12860                     imm = ffs (reglist) - 1;
12861                     INSERT_OPERAND (1, IMMN, *ip, imm);
12862                   }
12863                   continue;
12864
12865                 case 'O':       /* sdbbp 4-bit code.  */
12866                   {
12867                     bfd_reloc_code_real_type r[3];
12868                     expressionS ep;
12869                     int imm;
12870
12871                     if (my_getSmallExpression (&ep, r, s) > 0
12872                         || !expr_const_in_range (&ep, 0, 16, 0))
12873                       break;
12874
12875                     imm = ep.X_add_number;
12876                     INSERT_OPERAND (1, IMMO, *ip, imm);
12877                   }
12878                   s = expr_end;
12879                   continue;
12880
12881                 case 'P':
12882                   {
12883                     bfd_reloc_code_real_type r[3];
12884                     expressionS ep;
12885                     int imm;
12886
12887                     if (my_getSmallExpression (&ep, r, s) > 0
12888                         || !expr_const_in_range (&ep, 0, 32, 2))
12889                       break;
12890
12891                     imm = ep.X_add_number >> 2;
12892                     INSERT_OPERAND (1, IMMP, *ip, imm);
12893                   }
12894                   s = expr_end;
12895                   continue;
12896
12897                 case 'Q':
12898                   {
12899                     bfd_reloc_code_real_type r[3];
12900                     expressionS ep;
12901                     int imm;
12902
12903                     if (my_getSmallExpression (&ep, r, s) > 0
12904                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
12905                       break;
12906
12907                     imm = ep.X_add_number >> 2;
12908                     INSERT_OPERAND (1, IMMQ, *ip, imm);
12909                   }
12910                   s = expr_end;
12911                   continue;
12912
12913                 case 'U':
12914                   {
12915                     bfd_reloc_code_real_type r[3];
12916                     expressionS ep;
12917                     int imm;
12918
12919                     /* Check whether there is only a single bracketed
12920                        expression left.  If so, it must be the base register
12921                        and the constant must be zero.  */
12922                     if (*s == '(' && strchr (s + 1, '(') == 0)
12923                       {
12924                         INSERT_OPERAND (1, IMMU, *ip, 0);
12925                         continue;
12926                       }
12927
12928                     if (my_getSmallExpression (&ep, r, s) > 0
12929                         || !expr_const_in_range (&ep, 0, 32, 2))
12930                       break;
12931
12932                     imm = ep.X_add_number >> 2;
12933                     INSERT_OPERAND (1, IMMU, *ip, imm);
12934                   }
12935                   s = expr_end;
12936                   continue;
12937
12938                 case 'W':
12939                   {
12940                     bfd_reloc_code_real_type r[3];
12941                     expressionS ep;
12942                     int imm;
12943
12944                     if (my_getSmallExpression (&ep, r, s) > 0
12945                         || !expr_const_in_range (&ep, 0, 64, 2))
12946                       break;
12947
12948                     imm = ep.X_add_number >> 2;
12949                     INSERT_OPERAND (1, IMMW, *ip, imm);
12950                   }
12951                   s = expr_end;
12952                   continue;
12953
12954                 case 'X':
12955                   {
12956                     bfd_reloc_code_real_type r[3];
12957                     expressionS ep;
12958                     int imm;
12959
12960                     if (my_getSmallExpression (&ep, r, s) > 0
12961                         || !expr_const_in_range (&ep, -8, 8, 0))
12962                       break;
12963
12964                     imm = ep.X_add_number;
12965                     INSERT_OPERAND (1, IMMX, *ip, imm);
12966                   }
12967                   s = expr_end;
12968                   continue;
12969
12970                 case 'Y':
12971                   {
12972                     bfd_reloc_code_real_type r[3];
12973                     expressionS ep;
12974                     int imm;
12975
12976                     if (my_getSmallExpression (&ep, r, s) > 0
12977                         || expr_const_in_range (&ep, -2, 2, 2)
12978                         || !expr_const_in_range (&ep, -258, 258, 2))
12979                       break;
12980
12981                     imm = ep.X_add_number >> 2;
12982                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
12983                     INSERT_OPERAND (1, IMMY, *ip, imm);
12984                   }
12985                   s = expr_end;
12986                   continue;
12987
12988                 case 'Z':
12989                   {
12990                     bfd_reloc_code_real_type r[3];
12991                     expressionS ep;
12992
12993                     if (my_getSmallExpression (&ep, r, s) > 0
12994                         || !expr_const_in_range (&ep, 0, 1, 0))
12995                       break;
12996                   }
12997                   s = expr_end;
12998                   continue;
12999
13000                 default:
13001                   as_bad (_("Internal error: bad microMIPS opcode "
13002                             "(unknown extension operand type `m%c'): %s %s"),
13003                           *args, insn->name, insn->args);
13004                   /* Further processing is fruitless.  */
13005                   return;
13006                 }
13007               break;
13008
13009             case 'n':           /* Register list for 32-bit lwm and swm.  */
13010               gas_assert (mips_opts.micromips);
13011               {
13012                 /* A comma-separated list of registers and/or
13013                    dash-separated contiguous ranges including
13014                    at least one of ra and a set of one or more
13015                    registers starting at s0 up to s7 and then
13016                    s8 which have to be consecutive, e.g.:
13017
13018                    ra
13019                    s0
13020                    ra, s0, s1, s2
13021                    s0-s8
13022                    s0-s5, ra
13023
13024                    and any permutations of these.  */
13025                 unsigned int reglist;
13026                 int imm;
13027                 int ra;
13028
13029                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13030                   break;
13031
13032                 if ((reglist & 0x3f00ffff) != 0)
13033                   break;
13034
13035                 ra = (reglist >> 27) & 0x10;
13036                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13037                 reglist += 1;
13038                 if ((reglist & -reglist) != reglist)
13039                   break;
13040
13041                 imm = (ffs (reglist) - 1) | ra;
13042                 INSERT_OPERAND (1, RT, *ip, imm);
13043                 imm_expr.X_op = O_absent;
13044               }
13045               continue;
13046
13047             case '|':           /* 4-bit trap code.  */
13048               gas_assert (mips_opts.micromips);
13049               my_getExpression (&imm_expr, s);
13050               check_absolute_expr (ip, &imm_expr);
13051               if ((unsigned long) imm_expr.X_add_number
13052                   > MICROMIPSOP_MASK_TRAP)
13053                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13054                         (unsigned long) imm_expr.X_add_number,
13055                         ip->insn_mo->name);
13056               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13057               imm_expr.X_op = O_absent;
13058               s = expr_end;
13059               continue;
13060
13061             default:
13062               as_bad (_("Bad char = '%c'\n"), *args);
13063               internalError ();
13064             }
13065           break;
13066         }
13067       /* Args don't match.  */
13068       s = argsStart;
13069       insn_error = _("Illegal operands");
13070       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13071         {
13072           ++insn;
13073           continue;
13074         }
13075       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13076         {
13077           gas_assert (firstinsn);
13078           need_delay_slot_ok = FALSE;
13079           past = insn + 1;
13080           insn = firstinsn;
13081           continue;
13082         }
13083       return;
13084     }
13085 }
13086
13087 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13088
13089 /* This routine assembles an instruction into its binary format when
13090    assembling for the mips16.  As a side effect, it sets one of the
13091    global variables imm_reloc or offset_reloc to the type of relocation
13092    to do if one of the operands is an address expression.  It also sets
13093    forced_insn_length to the resulting instruction size in bytes if the
13094    user explicitly requested a small or extended instruction.  */
13095
13096 static void
13097 mips16_ip (char *str, struct mips_cl_insn *ip)
13098 {
13099   char *s;
13100   const char *args;
13101   struct mips_opcode *insn;
13102   char *argsstart;
13103   unsigned int regno;
13104   unsigned int lastregno = 0;
13105   char *s_reset;
13106   size_t i;
13107
13108   insn_error = NULL;
13109
13110   forced_insn_length = 0;
13111
13112   for (s = str; ISLOWER (*s); ++s)
13113     ;
13114   switch (*s)
13115     {
13116     case '\0':
13117       break;
13118
13119     case ' ':
13120       *s++ = '\0';
13121       break;
13122
13123     case '.':
13124       if (s[1] == 't' && s[2] == ' ')
13125         {
13126           *s = '\0';
13127           forced_insn_length = 2;
13128           s += 3;
13129           break;
13130         }
13131       else if (s[1] == 'e' && s[2] == ' ')
13132         {
13133           *s = '\0';
13134           forced_insn_length = 4;
13135           s += 3;
13136           break;
13137         }
13138       /* Fall through.  */
13139     default:
13140       insn_error = _("unknown opcode");
13141       return;
13142     }
13143
13144   if (mips_opts.noautoextend && !forced_insn_length)
13145     forced_insn_length = 2;
13146
13147   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
13148     {
13149       insn_error = _("unrecognized opcode");
13150       return;
13151     }
13152
13153   argsstart = s;
13154   for (;;)
13155     {
13156       bfd_boolean ok;
13157
13158       gas_assert (strcmp (insn->name, str) == 0);
13159
13160       ok = is_opcode_valid_16 (insn);
13161       if (! ok)
13162         {
13163           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13164               && strcmp (insn->name, insn[1].name) == 0)
13165             {
13166               ++insn;
13167               continue;
13168             }
13169           else
13170             {
13171               if (!insn_error)
13172                 {
13173                   static char buf[100];
13174                   sprintf (buf,
13175                            _("opcode not supported on this processor: %s (%s)"),
13176                            mips_cpu_info_from_arch (mips_opts.arch)->name,
13177                            mips_cpu_info_from_isa (mips_opts.isa)->name);
13178                   insn_error = buf;
13179                 }
13180               return;
13181             }
13182         }
13183
13184       create_insn (ip, insn);
13185       imm_expr.X_op = O_absent;
13186       imm_reloc[0] = BFD_RELOC_UNUSED;
13187       imm_reloc[1] = BFD_RELOC_UNUSED;
13188       imm_reloc[2] = BFD_RELOC_UNUSED;
13189       imm2_expr.X_op = O_absent;
13190       offset_expr.X_op = O_absent;
13191       offset_reloc[0] = BFD_RELOC_UNUSED;
13192       offset_reloc[1] = BFD_RELOC_UNUSED;
13193       offset_reloc[2] = BFD_RELOC_UNUSED;
13194       for (args = insn->args; 1; ++args)
13195         {
13196           int c;
13197
13198           if (*s == ' ')
13199             ++s;
13200
13201           /* In this switch statement we call break if we did not find
13202              a match, continue if we did find a match, or return if we
13203              are done.  */
13204
13205           c = *args;
13206           switch (c)
13207             {
13208             case '\0':
13209               if (*s == '\0')
13210                 {
13211                   /* Stuff the immediate value in now, if we can.  */
13212                   if (imm_expr.X_op == O_constant
13213                       && *imm_reloc > BFD_RELOC_UNUSED
13214                       && *imm_reloc != BFD_RELOC_MIPS16_GOT16
13215                       && *imm_reloc != BFD_RELOC_MIPS16_CALL16
13216                       && insn->pinfo != INSN_MACRO)
13217                     {
13218                       valueT tmp;
13219
13220                       switch (*offset_reloc)
13221                         {
13222                           case BFD_RELOC_MIPS16_HI16_S:
13223                             tmp = (imm_expr.X_add_number + 0x8000) >> 16;
13224                             break;
13225
13226                           case BFD_RELOC_MIPS16_HI16:
13227                             tmp = imm_expr.X_add_number >> 16;
13228                             break;
13229
13230                           case BFD_RELOC_MIPS16_LO16:
13231                             tmp = ((imm_expr.X_add_number + 0x8000) & 0xffff)
13232                                   - 0x8000;
13233                             break;
13234
13235                           case BFD_RELOC_UNUSED:
13236                             tmp = imm_expr.X_add_number;
13237                             break;
13238
13239                           default:
13240                             internalError ();
13241                         }
13242                       *offset_reloc = BFD_RELOC_UNUSED;
13243
13244                       mips16_immed (NULL, 0, *imm_reloc - BFD_RELOC_UNUSED,
13245                                     tmp, TRUE, forced_insn_length == 2,
13246                                     forced_insn_length == 4, &ip->insn_opcode,
13247                                     &ip->use_extend, &ip->extend);
13248                       imm_expr.X_op = O_absent;
13249                       *imm_reloc = BFD_RELOC_UNUSED;
13250                     }
13251
13252                   return;
13253                 }
13254               break;
13255
13256             case ',':
13257               if (*s++ == c)
13258                 continue;
13259               s--;
13260               switch (*++args)
13261                 {
13262                 case 'v':
13263                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13264                   continue;
13265                 case 'w':
13266                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13267                   continue;
13268                 }
13269               break;
13270
13271             case '(':
13272             case ')':
13273               if (*s++ == c)
13274                 continue;
13275               break;
13276
13277             case 'v':
13278             case 'w':
13279               if (s[0] != '$')
13280                 {
13281                   if (c == 'v')
13282                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13283                   else
13284                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13285                   ++args;
13286                   continue;
13287                 }
13288               /* Fall through.  */
13289             case 'x':
13290             case 'y':
13291             case 'z':
13292             case 'Z':
13293             case '0':
13294             case 'S':
13295             case 'R':
13296             case 'X':
13297             case 'Y':
13298               s_reset = s;
13299               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
13300                 {
13301                   if (c == 'v' || c == 'w')
13302                     {
13303                       if (c == 'v')
13304                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13305                       else
13306                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13307                       ++args;
13308                       continue;
13309                     }
13310                   break;
13311                 }
13312
13313               if (*s == ' ')
13314                 ++s;
13315               if (args[1] != *s)
13316                 {
13317                   if (c == 'v' || c == 'w')
13318                     {
13319                       regno = mips16_to_32_reg_map[lastregno];
13320                       s = s_reset;
13321                       ++args;
13322                     }
13323                 }
13324
13325               switch (c)
13326                 {
13327                 case 'x':
13328                 case 'y':
13329                 case 'z':
13330                 case 'v':
13331                 case 'w':
13332                 case 'Z':
13333                   regno = mips32_to_16_reg_map[regno];
13334                   break;
13335
13336                 case '0':
13337                   if (regno != 0)
13338                     regno = ILLEGAL_REG;
13339                   break;
13340
13341                 case 'S':
13342                   if (regno != SP)
13343                     regno = ILLEGAL_REG;
13344                   break;
13345
13346                 case 'R':
13347                   if (regno != RA)
13348                     regno = ILLEGAL_REG;
13349                   break;
13350
13351                 case 'X':
13352                 case 'Y':
13353                   if (regno == AT && mips_opts.at)
13354                     {
13355                       if (mips_opts.at == ATREG)
13356                         as_warn (_("used $at without \".set noat\""));
13357                       else
13358                         as_warn (_("used $%u with \".set at=$%u\""),
13359                                  regno, mips_opts.at);
13360                     }
13361                   break;
13362
13363                 default:
13364                   internalError ();
13365                 }
13366
13367               if (regno == ILLEGAL_REG)
13368                 break;
13369
13370               switch (c)
13371                 {
13372                 case 'x':
13373                 case 'v':
13374                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
13375                   break;
13376                 case 'y':
13377                 case 'w':
13378                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
13379                   break;
13380                 case 'z':
13381                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
13382                   break;
13383                 case 'Z':
13384                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
13385                 case '0':
13386                 case 'S':
13387                 case 'R':
13388                   break;
13389                 case 'X':
13390                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
13391                   break;
13392                 case 'Y':
13393                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
13394                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
13395                   break;
13396                 default:
13397                   internalError ();
13398                 }
13399
13400               lastregno = regno;
13401               continue;
13402
13403             case 'P':
13404               if (strncmp (s, "$pc", 3) == 0)
13405                 {
13406                   s += 3;
13407                   continue;
13408                 }
13409               break;
13410
13411             case '5':
13412             case 'H':
13413             case 'W':
13414             case 'D':
13415             case 'j':
13416             case 'V':
13417             case 'C':
13418             case 'U':
13419             case 'k':
13420             case 'K':
13421               i = my_getSmallExpression (&imm_expr, imm_reloc, s);
13422               if (i > 0)
13423                 {
13424                   if (imm_expr.X_op != O_constant)
13425                     {
13426                       forced_insn_length = 4;
13427                       ip->use_extend = TRUE;
13428                       ip->extend = 0;
13429                     }
13430                   else
13431                     {
13432                       /* We need to relax this instruction.  */
13433                       *offset_reloc = *imm_reloc;
13434                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13435                     }
13436                   s = expr_end;
13437                   continue;
13438                 }
13439               *imm_reloc = BFD_RELOC_UNUSED;
13440               /* Fall through.  */
13441             case '<':
13442             case '>':
13443             case '[':
13444             case ']':
13445             case '4':
13446             case '8':
13447               my_getExpression (&imm_expr, s);
13448               if (imm_expr.X_op == O_register)
13449                 {
13450                   /* What we thought was an expression turned out to
13451                      be a register.  */
13452
13453                   if (s[0] == '(' && args[1] == '(')
13454                     {
13455                       /* It looks like the expression was omitted
13456                          before a register indirection, which means
13457                          that the expression is implicitly zero.  We
13458                          still set up imm_expr, so that we handle
13459                          explicit extensions correctly.  */
13460                       imm_expr.X_op = O_constant;
13461                       imm_expr.X_add_number = 0;
13462                       *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13463                       continue;
13464                     }
13465
13466                   break;
13467                 }
13468
13469               /* We need to relax this instruction.  */
13470               *imm_reloc = (int) BFD_RELOC_UNUSED + c;
13471               s = expr_end;
13472               continue;
13473
13474             case 'p':
13475             case 'q':
13476             case 'A':
13477             case 'B':
13478             case 'E':
13479               /* We use offset_reloc rather than imm_reloc for the PC
13480                  relative operands.  This lets macros with both
13481                  immediate and address operands work correctly.  */
13482               my_getExpression (&offset_expr, s);
13483
13484               if (offset_expr.X_op == O_register)
13485                 break;
13486
13487               /* We need to relax this instruction.  */
13488               *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13489               s = expr_end;
13490               continue;
13491
13492             case '6':           /* break code */
13493               my_getExpression (&imm_expr, s);
13494               check_absolute_expr (ip, &imm_expr);
13495               if ((unsigned long) imm_expr.X_add_number > 63)
13496                 as_warn (_("Invalid value for `%s' (%lu)"),
13497                          ip->insn_mo->name,
13498                          (unsigned long) imm_expr.X_add_number);
13499               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
13500               imm_expr.X_op = O_absent;
13501               s = expr_end;
13502               continue;
13503
13504             case 'a':           /* 26 bit address */
13505               my_getExpression (&offset_expr, s);
13506               s = expr_end;
13507               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13508               ip->insn_opcode <<= 16;
13509               continue;
13510
13511             case 'l':           /* register list for entry macro */
13512             case 'L':           /* register list for exit macro */
13513               {
13514                 int mask;
13515
13516                 if (c == 'l')
13517                   mask = 0;
13518                 else
13519                   mask = 7 << 3;
13520                 while (*s != '\0')
13521                   {
13522                     unsigned int freg, reg1, reg2;
13523
13524                     while (*s == ' ' || *s == ',')
13525                       ++s;
13526                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13527                       freg = 0;
13528                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
13529                       freg = 1;
13530                     else
13531                       {
13532                         as_bad (_("can't parse register list"));
13533                         break;
13534                       }
13535                     if (*s == ' ')
13536                       ++s;
13537                     if (*s != '-')
13538                       reg2 = reg1;
13539                     else
13540                       {
13541                         ++s;
13542                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
13543                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
13544                           {
13545                             as_bad (_("invalid register list"));
13546                             break;
13547                           }
13548                       }
13549                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
13550                       {
13551                         mask &= ~ (7 << 3);
13552                         mask |= 5 << 3;
13553                       }
13554                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
13555                       {
13556                         mask &= ~ (7 << 3);
13557                         mask |= 6 << 3;
13558                       }
13559                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
13560                       mask |= (reg2 - 3) << 3;
13561                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
13562                       mask |= (reg2 - 15) << 1;
13563                     else if (reg1 == RA && reg2 == RA)
13564                       mask |= 1;
13565                     else
13566                       {
13567                         as_bad (_("invalid register list"));
13568                         break;
13569                       }
13570                   }
13571                 /* The mask is filled in in the opcode table for the
13572                    benefit of the disassembler.  We remove it before
13573                    applying the actual mask.  */
13574                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
13575                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
13576               }
13577             continue;
13578
13579             case 'm':           /* Register list for save insn.  */
13580             case 'M':           /* Register list for restore insn.  */
13581               {
13582                 int opcode = 0;
13583                 int framesz = 0, seen_framesz = 0;
13584                 int nargs = 0, statics = 0, sregs = 0;
13585
13586                 while (*s != '\0')
13587                   {
13588                     unsigned int reg1, reg2;
13589
13590                     SKIP_SPACE_TABS (s);
13591                     while (*s == ',')
13592                       ++s;
13593                     SKIP_SPACE_TABS (s);
13594
13595                     my_getExpression (&imm_expr, s);
13596                     if (imm_expr.X_op == O_constant)
13597                       {
13598                         /* Handle the frame size.  */
13599                         if (seen_framesz)
13600                           {
13601                             as_bad (_("more than one frame size in list"));
13602                             break;
13603                           }
13604                         seen_framesz = 1;
13605                         framesz = imm_expr.X_add_number;
13606                         imm_expr.X_op = O_absent;
13607                         s = expr_end;
13608                         continue;
13609                       }
13610
13611                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13612                       {
13613                         as_bad (_("can't parse register list"));
13614                         break;
13615                       }
13616
13617                     while (*s == ' ')
13618                       ++s;
13619
13620                     if (*s != '-')
13621                       reg2 = reg1;
13622                     else
13623                       {
13624                         ++s;
13625                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
13626                             || reg2 < reg1)
13627                           {
13628                             as_bad (_("can't parse register list"));
13629                             break;
13630                           }
13631                       }
13632
13633                     while (reg1 <= reg2)
13634                       {
13635                         if (reg1 >= 4 && reg1 <= 7)
13636                           {
13637                             if (!seen_framesz)
13638                                 /* args $a0-$a3 */
13639                                 nargs |= 1 << (reg1 - 4);
13640                             else
13641                                 /* statics $a0-$a3 */
13642                                 statics |= 1 << (reg1 - 4);
13643                           }
13644                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
13645                           {
13646                             /* $s0-$s8 */
13647                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
13648                           }
13649                         else if (reg1 == 31)
13650                           {
13651                             /* Add $ra to insn.  */
13652                             opcode |= 0x40;
13653                           }
13654                         else
13655                           {
13656                             as_bad (_("unexpected register in list"));
13657                             break;
13658                           }
13659                         if (++reg1 == 24)
13660                           reg1 = 30;
13661                       }
13662                   }
13663
13664                 /* Encode args/statics combination.  */
13665                 if (nargs & statics)
13666                   as_bad (_("arg/static registers overlap"));
13667                 else if (nargs == 0xf)
13668                   /* All $a0-$a3 are args.  */
13669                   opcode |= MIPS16_ALL_ARGS << 16;
13670                 else if (statics == 0xf)
13671                   /* All $a0-$a3 are statics.  */
13672                   opcode |= MIPS16_ALL_STATICS << 16;
13673                 else 
13674                   {
13675                     int narg = 0, nstat = 0;
13676
13677                     /* Count arg registers.  */
13678                     while (nargs & 0x1)
13679                       {
13680                         nargs >>= 1;
13681                         narg++;
13682                       }
13683                     if (nargs != 0)
13684                       as_bad (_("invalid arg register list"));
13685
13686                     /* Count static registers.  */
13687                     while (statics & 0x8)
13688                       {
13689                         statics = (statics << 1) & 0xf;
13690                         nstat++;
13691                       }
13692                     if (statics != 0) 
13693                       as_bad (_("invalid static register list"));
13694
13695                     /* Encode args/statics.  */
13696                     opcode |= ((narg << 2) | nstat) << 16;
13697                   }
13698
13699                 /* Encode $s0/$s1.  */
13700                 if (sregs & (1 << 0))           /* $s0 */
13701                   opcode |= 0x20;
13702                 if (sregs & (1 << 1))           /* $s1 */
13703                   opcode |= 0x10;
13704                 sregs >>= 2;
13705
13706                 if (sregs != 0)
13707                   {
13708                     /* Count regs $s2-$s8.  */
13709                     int nsreg = 0;
13710                     while (sregs & 1)
13711                       {
13712                         sregs >>= 1;
13713                         nsreg++;
13714                       }
13715                     if (sregs != 0)
13716                       as_bad (_("invalid static register list"));
13717                     /* Encode $s2-$s8. */
13718                     opcode |= nsreg << 24;
13719                   }
13720
13721                 /* Encode frame size.  */
13722                 if (!seen_framesz)
13723                   as_bad (_("missing frame size"));
13724                 else if ((framesz & 7) != 0 || framesz < 0
13725                          || framesz > 0xff * 8)
13726                   as_bad (_("invalid frame size"));
13727                 else if (framesz != 128 || (opcode >> 16) != 0)
13728                   {
13729                     framesz /= 8;
13730                     opcode |= (((framesz & 0xf0) << 16)
13731                              | (framesz & 0x0f));
13732                   }
13733
13734                 /* Finally build the instruction.  */
13735                 if ((opcode >> 16) != 0 || framesz == 0)
13736                   {
13737                     ip->use_extend = TRUE;
13738                     ip->extend = opcode >> 16;
13739                   }
13740                 ip->insn_opcode |= opcode & 0x7f;
13741               }
13742             continue;
13743
13744             case 'e':           /* extend code */
13745               my_getExpression (&imm_expr, s);
13746               check_absolute_expr (ip, &imm_expr);
13747               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
13748                 {
13749                   as_warn (_("Invalid value for `%s' (%lu)"),
13750                            ip->insn_mo->name,
13751                            (unsigned long) imm_expr.X_add_number);
13752                   imm_expr.X_add_number &= 0x7ff;
13753                 }
13754               ip->insn_opcode |= imm_expr.X_add_number;
13755               imm_expr.X_op = O_absent;
13756               s = expr_end;
13757               continue;
13758
13759             default:
13760               internalError ();
13761             }
13762           break;
13763         }
13764
13765       /* Args don't match.  */
13766       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
13767           strcmp (insn->name, insn[1].name) == 0)
13768         {
13769           ++insn;
13770           s = argsstart;
13771           continue;
13772         }
13773
13774       insn_error = _("illegal operands");
13775
13776       return;
13777     }
13778 }
13779
13780 /* This structure holds information we know about a mips16 immediate
13781    argument type.  */
13782
13783 struct mips16_immed_operand
13784 {
13785   /* The type code used in the argument string in the opcode table.  */
13786   int type;
13787   /* The number of bits in the short form of the opcode.  */
13788   int nbits;
13789   /* The number of bits in the extended form of the opcode.  */
13790   int extbits;
13791   /* The amount by which the short form is shifted when it is used;
13792      for example, the sw instruction has a shift count of 2.  */
13793   int shift;
13794   /* The amount by which the short form is shifted when it is stored
13795      into the instruction code.  */
13796   int op_shift;
13797   /* Non-zero if the short form is unsigned.  */
13798   int unsp;
13799   /* Non-zero if the extended form is unsigned.  */
13800   int extu;
13801   /* Non-zero if the value is PC relative.  */
13802   int pcrel;
13803 };
13804
13805 /* The mips16 immediate operand types.  */
13806
13807 static const struct mips16_immed_operand mips16_immed_operands[] =
13808 {
13809   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13810   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13811   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
13812   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
13813   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
13814   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
13815   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
13816   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
13817   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
13818   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
13819   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
13820   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
13821   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
13822   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
13823   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
13824   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
13825   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13826   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
13827   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
13828   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
13829   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
13830 };
13831
13832 #define MIPS16_NUM_IMMED \
13833   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
13834
13835 /* Handle a mips16 instruction with an immediate value.  This or's the
13836    small immediate value into *INSN.  It sets *USE_EXTEND to indicate
13837    whether an extended value is needed; if one is needed, it sets
13838    *EXTEND to the value.  The argument type is TYPE.  The value is VAL.
13839    If SMALL is true, an unextended opcode was explicitly requested.
13840    If EXT is true, an extended opcode was explicitly requested.  If
13841    WARN is true, warn if EXT does not match reality.  */
13842
13843 static void
13844 mips16_immed (char *file, unsigned int line, int type, offsetT val,
13845               bfd_boolean warn, bfd_boolean small, bfd_boolean ext,
13846               unsigned long *insn, bfd_boolean *use_extend,
13847               unsigned short *extend)
13848 {
13849   const struct mips16_immed_operand *op;
13850   int mintiny, maxtiny;
13851   bfd_boolean needext;
13852
13853   op = mips16_immed_operands;
13854   while (op->type != type)
13855     {
13856       ++op;
13857       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
13858     }
13859
13860   if (op->unsp)
13861     {
13862       if (type == '<' || type == '>' || type == '[' || type == ']')
13863         {
13864           mintiny = 1;
13865           maxtiny = 1 << op->nbits;
13866         }
13867       else
13868         {
13869           mintiny = 0;
13870           maxtiny = (1 << op->nbits) - 1;
13871         }
13872     }
13873   else
13874     {
13875       mintiny = - (1 << (op->nbits - 1));
13876       maxtiny = (1 << (op->nbits - 1)) - 1;
13877     }
13878
13879   /* Branch offsets have an implicit 0 in the lowest bit.  */
13880   if (type == 'p' || type == 'q')
13881     val /= 2;
13882
13883   if ((val & ((1 << op->shift) - 1)) != 0
13884       || val < (mintiny << op->shift)
13885       || val > (maxtiny << op->shift))
13886     needext = TRUE;
13887   else
13888     needext = FALSE;
13889
13890   if (warn && ext && ! needext)
13891     as_warn_where (file, line,
13892                    _("extended operand requested but not required"));
13893   if (small && needext)
13894     as_bad_where (file, line, _("invalid unextended operand value"));
13895
13896   if (small || (! ext && ! needext))
13897     {
13898       int insnval;
13899
13900       *use_extend = FALSE;
13901       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
13902       insnval <<= op->op_shift;
13903       *insn |= insnval;
13904     }
13905   else
13906     {
13907       long minext, maxext;
13908       int extval;
13909
13910       if (op->extu)
13911         {
13912           minext = 0;
13913           maxext = (1 << op->extbits) - 1;
13914         }
13915       else
13916         {
13917           minext = - (1 << (op->extbits - 1));
13918           maxext = (1 << (op->extbits - 1)) - 1;
13919         }
13920       if (val < minext || val > maxext)
13921         as_bad_where (file, line,
13922                       _("operand value out of range for instruction"));
13923
13924       *use_extend = TRUE;
13925       if (op->extbits == 16)
13926         {
13927           extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13928           val &= 0x1f;
13929         }
13930       else if (op->extbits == 15)
13931         {
13932           extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13933           val &= 0xf;
13934         }
13935       else
13936         {
13937           extval = ((val & 0x1f) << 6) | (val & 0x20);
13938           val = 0;
13939         }
13940
13941       *extend = (unsigned short) extval;
13942       *insn |= val;
13943     }
13944 }
13945 \f
13946 struct percent_op_match
13947 {
13948   const char *str;
13949   bfd_reloc_code_real_type reloc;
13950 };
13951
13952 static const struct percent_op_match mips_percent_op[] =
13953 {
13954   {"%lo", BFD_RELOC_LO16},
13955 #ifdef OBJ_ELF
13956   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13957   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13958   {"%call16", BFD_RELOC_MIPS_CALL16},
13959   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13960   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13961   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13962   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13963   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13964   {"%got", BFD_RELOC_MIPS_GOT16},
13965   {"%gp_rel", BFD_RELOC_GPREL16},
13966   {"%half", BFD_RELOC_16},
13967   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13968   {"%higher", BFD_RELOC_MIPS_HIGHER},
13969   {"%neg", BFD_RELOC_MIPS_SUB},
13970   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13971   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13972   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13973   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13974   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13975   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13976   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13977 #endif
13978   {"%hi", BFD_RELOC_HI16_S}
13979 };
13980
13981 static const struct percent_op_match mips16_percent_op[] =
13982 {
13983   {"%lo", BFD_RELOC_MIPS16_LO16},
13984   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13985   {"%got", BFD_RELOC_MIPS16_GOT16},
13986   {"%call16", BFD_RELOC_MIPS16_CALL16},
13987   {"%hi", BFD_RELOC_MIPS16_HI16_S}
13988 };
13989
13990
13991 /* Return true if *STR points to a relocation operator.  When returning true,
13992    move *STR over the operator and store its relocation code in *RELOC.
13993    Leave both *STR and *RELOC alone when returning false.  */
13994
13995 static bfd_boolean
13996 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13997 {
13998   const struct percent_op_match *percent_op;
13999   size_t limit, i;
14000
14001   if (mips_opts.mips16)
14002     {
14003       percent_op = mips16_percent_op;
14004       limit = ARRAY_SIZE (mips16_percent_op);
14005     }
14006   else
14007     {
14008       percent_op = mips_percent_op;
14009       limit = ARRAY_SIZE (mips_percent_op);
14010     }
14011
14012   for (i = 0; i < limit; i++)
14013     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14014       {
14015         int len = strlen (percent_op[i].str);
14016
14017         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14018           continue;
14019
14020         *str += strlen (percent_op[i].str);
14021         *reloc = percent_op[i].reloc;
14022
14023         /* Check whether the output BFD supports this relocation.
14024            If not, issue an error and fall back on something safe.  */
14025         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14026           {
14027             as_bad (_("relocation %s isn't supported by the current ABI"),
14028                     percent_op[i].str);
14029             *reloc = BFD_RELOC_UNUSED;
14030           }
14031         return TRUE;
14032       }
14033   return FALSE;
14034 }
14035
14036
14037 /* Parse string STR as a 16-bit relocatable operand.  Store the
14038    expression in *EP and the relocations in the array starting
14039    at RELOC.  Return the number of relocation operators used.
14040
14041    On exit, EXPR_END points to the first character after the expression.  */
14042
14043 static size_t
14044 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14045                        char *str)
14046 {
14047   bfd_reloc_code_real_type reversed_reloc[3];
14048   size_t reloc_index, i;
14049   int crux_depth, str_depth;
14050   char *crux;
14051
14052   /* Search for the start of the main expression, recoding relocations
14053      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14054      of the main expression and with CRUX_DEPTH containing the number
14055      of open brackets at that point.  */
14056   reloc_index = -1;
14057   str_depth = 0;
14058   do
14059     {
14060       reloc_index++;
14061       crux = str;
14062       crux_depth = str_depth;
14063
14064       /* Skip over whitespace and brackets, keeping count of the number
14065          of brackets.  */
14066       while (*str == ' ' || *str == '\t' || *str == '(')
14067         if (*str++ == '(')
14068           str_depth++;
14069     }
14070   while (*str == '%'
14071          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14072          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14073
14074   my_getExpression (ep, crux);
14075   str = expr_end;
14076
14077   /* Match every open bracket.  */
14078   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14079     if (*str++ == ')')
14080       crux_depth--;
14081
14082   if (crux_depth > 0)
14083     as_bad (_("unclosed '('"));
14084
14085   expr_end = str;
14086
14087   if (reloc_index != 0)
14088     {
14089       prev_reloc_op_frag = frag_now;
14090       for (i = 0; i < reloc_index; i++)
14091         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14092     }
14093
14094   return reloc_index;
14095 }
14096
14097 static void
14098 my_getExpression (expressionS *ep, char *str)
14099 {
14100   char *save_in;
14101
14102   save_in = input_line_pointer;
14103   input_line_pointer = str;
14104   expression (ep);
14105   expr_end = input_line_pointer;
14106   input_line_pointer = save_in;
14107 }
14108
14109 char *
14110 md_atof (int type, char *litP, int *sizeP)
14111 {
14112   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14113 }
14114
14115 void
14116 md_number_to_chars (char *buf, valueT val, int n)
14117 {
14118   if (target_big_endian)
14119     number_to_chars_bigendian (buf, val, n);
14120   else
14121     number_to_chars_littleendian (buf, val, n);
14122 }
14123 \f
14124 #ifdef OBJ_ELF
14125 static int support_64bit_objects(void)
14126 {
14127   const char **list, **l;
14128   int yes;
14129
14130   list = bfd_target_list ();
14131   for (l = list; *l != NULL; l++)
14132     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14133         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14134       break;
14135   yes = (*l != NULL);
14136   free (list);
14137   return yes;
14138 }
14139 #endif /* OBJ_ELF */
14140
14141 const char *md_shortopts = "O::g::G:";
14142
14143 enum options
14144   {
14145     OPTION_MARCH = OPTION_MD_BASE,
14146     OPTION_MTUNE,
14147     OPTION_MIPS1,
14148     OPTION_MIPS2,
14149     OPTION_MIPS3,
14150     OPTION_MIPS4,
14151     OPTION_MIPS5,
14152     OPTION_MIPS32,
14153     OPTION_MIPS64,
14154     OPTION_MIPS32R2,
14155     OPTION_MIPS64R2,
14156     OPTION_MIPS16,
14157     OPTION_NO_MIPS16,
14158     OPTION_MIPS3D,
14159     OPTION_NO_MIPS3D,
14160     OPTION_MDMX,
14161     OPTION_NO_MDMX,
14162     OPTION_DSP,
14163     OPTION_NO_DSP,
14164     OPTION_MT,
14165     OPTION_NO_MT,
14166     OPTION_SMARTMIPS,
14167     OPTION_NO_SMARTMIPS,
14168     OPTION_DSPR2,
14169     OPTION_NO_DSPR2,
14170     OPTION_MICROMIPS,
14171     OPTION_NO_MICROMIPS,
14172     OPTION_COMPAT_ARCH_BASE,
14173     OPTION_M4650,
14174     OPTION_NO_M4650,
14175     OPTION_M4010,
14176     OPTION_NO_M4010,
14177     OPTION_M4100,
14178     OPTION_NO_M4100,
14179     OPTION_M3900,
14180     OPTION_NO_M3900,
14181     OPTION_M7000_HILO_FIX,
14182     OPTION_MNO_7000_HILO_FIX, 
14183     OPTION_FIX_24K,
14184     OPTION_NO_FIX_24K,
14185     OPTION_FIX_LOONGSON2F_JUMP,
14186     OPTION_NO_FIX_LOONGSON2F_JUMP,
14187     OPTION_FIX_LOONGSON2F_NOP,
14188     OPTION_NO_FIX_LOONGSON2F_NOP,
14189     OPTION_FIX_VR4120,
14190     OPTION_NO_FIX_VR4120,
14191     OPTION_FIX_VR4130,
14192     OPTION_NO_FIX_VR4130,
14193     OPTION_FIX_CN63XXP1,
14194     OPTION_NO_FIX_CN63XXP1,
14195     OPTION_TRAP,
14196     OPTION_BREAK,
14197     OPTION_EB,
14198     OPTION_EL,
14199     OPTION_FP32,
14200     OPTION_GP32,
14201     OPTION_CONSTRUCT_FLOATS,
14202     OPTION_NO_CONSTRUCT_FLOATS,
14203     OPTION_FP64,
14204     OPTION_GP64,
14205     OPTION_RELAX_BRANCH,
14206     OPTION_NO_RELAX_BRANCH,
14207     OPTION_MSHARED,
14208     OPTION_MNO_SHARED,
14209     OPTION_MSYM32,
14210     OPTION_MNO_SYM32,
14211     OPTION_SOFT_FLOAT,
14212     OPTION_HARD_FLOAT,
14213     OPTION_SINGLE_FLOAT,
14214     OPTION_DOUBLE_FLOAT,
14215     OPTION_32,
14216 #ifdef OBJ_ELF
14217     OPTION_CALL_SHARED,
14218     OPTION_CALL_NONPIC,
14219     OPTION_NON_SHARED,
14220     OPTION_XGOT,
14221     OPTION_MABI,
14222     OPTION_N32,
14223     OPTION_64,
14224     OPTION_MDEBUG,
14225     OPTION_NO_MDEBUG,
14226     OPTION_PDR,
14227     OPTION_NO_PDR,
14228     OPTION_MVXWORKS_PIC,
14229 #endif /* OBJ_ELF */
14230     OPTION_END_OF_ENUM    
14231   };
14232   
14233 struct option md_longopts[] =
14234 {
14235   /* Options which specify architecture.  */
14236   {"march", required_argument, NULL, OPTION_MARCH},
14237   {"mtune", required_argument, NULL, OPTION_MTUNE},
14238   {"mips0", no_argument, NULL, OPTION_MIPS1},
14239   {"mips1", no_argument, NULL, OPTION_MIPS1},
14240   {"mips2", no_argument, NULL, OPTION_MIPS2},
14241   {"mips3", no_argument, NULL, OPTION_MIPS3},
14242   {"mips4", no_argument, NULL, OPTION_MIPS4},
14243   {"mips5", no_argument, NULL, OPTION_MIPS5},
14244   {"mips32", no_argument, NULL, OPTION_MIPS32},
14245   {"mips64", no_argument, NULL, OPTION_MIPS64},
14246   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
14247   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
14248
14249   /* Options which specify Application Specific Extensions (ASEs).  */
14250   {"mips16", no_argument, NULL, OPTION_MIPS16},
14251   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
14252   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
14253   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
14254   {"mdmx", no_argument, NULL, OPTION_MDMX},
14255   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
14256   {"mdsp", no_argument, NULL, OPTION_DSP},
14257   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
14258   {"mmt", no_argument, NULL, OPTION_MT},
14259   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
14260   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
14261   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
14262   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
14263   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
14264   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
14265   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
14266
14267   /* Old-style architecture options.  Don't add more of these.  */
14268   {"m4650", no_argument, NULL, OPTION_M4650},
14269   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
14270   {"m4010", no_argument, NULL, OPTION_M4010},
14271   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
14272   {"m4100", no_argument, NULL, OPTION_M4100},
14273   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
14274   {"m3900", no_argument, NULL, OPTION_M3900},
14275   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
14276
14277   /* Options which enable bug fixes.  */
14278   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
14279   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14280   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
14281   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
14282   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
14283   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
14284   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
14285   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
14286   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
14287   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
14288   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
14289   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
14290   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
14291   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
14292   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
14293
14294   /* Miscellaneous options.  */
14295   {"trap", no_argument, NULL, OPTION_TRAP},
14296   {"no-break", no_argument, NULL, OPTION_TRAP},
14297   {"break", no_argument, NULL, OPTION_BREAK},
14298   {"no-trap", no_argument, NULL, OPTION_BREAK},
14299   {"EB", no_argument, NULL, OPTION_EB},
14300   {"EL", no_argument, NULL, OPTION_EL},
14301   {"mfp32", no_argument, NULL, OPTION_FP32},
14302   {"mgp32", no_argument, NULL, OPTION_GP32},
14303   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
14304   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
14305   {"mfp64", no_argument, NULL, OPTION_FP64},
14306   {"mgp64", no_argument, NULL, OPTION_GP64},
14307   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
14308   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
14309   {"mshared", no_argument, NULL, OPTION_MSHARED},
14310   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
14311   {"msym32", no_argument, NULL, OPTION_MSYM32},
14312   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
14313   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
14314   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
14315   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
14316   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
14317
14318   /* Strictly speaking this next option is ELF specific,
14319      but we allow it for other ports as well in order to
14320      make testing easier.  */
14321   {"32",          no_argument, NULL, OPTION_32},
14322   
14323   /* ELF-specific options.  */
14324 #ifdef OBJ_ELF
14325   {"KPIC",        no_argument, NULL, OPTION_CALL_SHARED},
14326   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
14327   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
14328   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
14329   {"xgot",        no_argument, NULL, OPTION_XGOT},
14330   {"mabi", required_argument, NULL, OPTION_MABI},
14331   {"n32",         no_argument, NULL, OPTION_N32},
14332   {"64",          no_argument, NULL, OPTION_64},
14333   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
14334   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
14335   {"mpdr", no_argument, NULL, OPTION_PDR},
14336   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
14337   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
14338 #endif /* OBJ_ELF */
14339
14340   {NULL, no_argument, NULL, 0}
14341 };
14342 size_t md_longopts_size = sizeof (md_longopts);
14343
14344 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14345    NEW_VALUE.  Warn if another value was already specified.  Note:
14346    we have to defer parsing the -march and -mtune arguments in order
14347    to handle 'from-abi' correctly, since the ABI might be specified
14348    in a later argument.  */
14349
14350 static void
14351 mips_set_option_string (const char **string_ptr, const char *new_value)
14352 {
14353   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14354     as_warn (_("A different %s was already specified, is now %s"),
14355              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14356              new_value);
14357
14358   *string_ptr = new_value;
14359 }
14360
14361 int
14362 md_parse_option (int c, char *arg)
14363 {
14364   switch (c)
14365     {
14366     case OPTION_CONSTRUCT_FLOATS:
14367       mips_disable_float_construction = 0;
14368       break;
14369
14370     case OPTION_NO_CONSTRUCT_FLOATS:
14371       mips_disable_float_construction = 1;
14372       break;
14373
14374     case OPTION_TRAP:
14375       mips_trap = 1;
14376       break;
14377
14378     case OPTION_BREAK:
14379       mips_trap = 0;
14380       break;
14381
14382     case OPTION_EB:
14383       target_big_endian = 1;
14384       break;
14385
14386     case OPTION_EL:
14387       target_big_endian = 0;
14388       break;
14389
14390     case 'O':
14391       if (arg == NULL)
14392         mips_optimize = 1;
14393       else if (arg[0] == '0')
14394         mips_optimize = 0;
14395       else if (arg[0] == '1')
14396         mips_optimize = 1;
14397       else
14398         mips_optimize = 2;
14399       break;
14400
14401     case 'g':
14402       if (arg == NULL)
14403         mips_debug = 2;
14404       else
14405         mips_debug = atoi (arg);
14406       break;
14407
14408     case OPTION_MIPS1:
14409       file_mips_isa = ISA_MIPS1;
14410       break;
14411
14412     case OPTION_MIPS2:
14413       file_mips_isa = ISA_MIPS2;
14414       break;
14415
14416     case OPTION_MIPS3:
14417       file_mips_isa = ISA_MIPS3;
14418       break;
14419
14420     case OPTION_MIPS4:
14421       file_mips_isa = ISA_MIPS4;
14422       break;
14423
14424     case OPTION_MIPS5:
14425       file_mips_isa = ISA_MIPS5;
14426       break;
14427
14428     case OPTION_MIPS32:
14429       file_mips_isa = ISA_MIPS32;
14430       break;
14431
14432     case OPTION_MIPS32R2:
14433       file_mips_isa = ISA_MIPS32R2;
14434       break;
14435
14436     case OPTION_MIPS64R2:
14437       file_mips_isa = ISA_MIPS64R2;
14438       break;
14439
14440     case OPTION_MIPS64:
14441       file_mips_isa = ISA_MIPS64;
14442       break;
14443
14444     case OPTION_MTUNE:
14445       mips_set_option_string (&mips_tune_string, arg);
14446       break;
14447
14448     case OPTION_MARCH:
14449       mips_set_option_string (&mips_arch_string, arg);
14450       break;
14451
14452     case OPTION_M4650:
14453       mips_set_option_string (&mips_arch_string, "4650");
14454       mips_set_option_string (&mips_tune_string, "4650");
14455       break;
14456
14457     case OPTION_NO_M4650:
14458       break;
14459
14460     case OPTION_M4010:
14461       mips_set_option_string (&mips_arch_string, "4010");
14462       mips_set_option_string (&mips_tune_string, "4010");
14463       break;
14464
14465     case OPTION_NO_M4010:
14466       break;
14467
14468     case OPTION_M4100:
14469       mips_set_option_string (&mips_arch_string, "4100");
14470       mips_set_option_string (&mips_tune_string, "4100");
14471       break;
14472
14473     case OPTION_NO_M4100:
14474       break;
14475
14476     case OPTION_M3900:
14477       mips_set_option_string (&mips_arch_string, "3900");
14478       mips_set_option_string (&mips_tune_string, "3900");
14479       break;
14480
14481     case OPTION_NO_M3900:
14482       break;
14483
14484     case OPTION_MDMX:
14485       mips_opts.ase_mdmx = 1;
14486       break;
14487
14488     case OPTION_NO_MDMX:
14489       mips_opts.ase_mdmx = 0;
14490       break;
14491
14492     case OPTION_DSP:
14493       mips_opts.ase_dsp = 1;
14494       mips_opts.ase_dspr2 = 0;
14495       break;
14496
14497     case OPTION_NO_DSP:
14498       mips_opts.ase_dsp = 0;
14499       mips_opts.ase_dspr2 = 0;
14500       break;
14501
14502     case OPTION_DSPR2:
14503       mips_opts.ase_dspr2 = 1;
14504       mips_opts.ase_dsp = 1;
14505       break;
14506
14507     case OPTION_NO_DSPR2:
14508       mips_opts.ase_dspr2 = 0;
14509       mips_opts.ase_dsp = 0;
14510       break;
14511
14512     case OPTION_MT:
14513       mips_opts.ase_mt = 1;
14514       break;
14515
14516     case OPTION_NO_MT:
14517       mips_opts.ase_mt = 0;
14518       break;
14519
14520     case OPTION_MICROMIPS:
14521       if (mips_opts.mips16 == 1)
14522         {
14523           as_bad (_("-mmicromips cannot be used with -mips16"));
14524           return 0;
14525         }
14526       mips_opts.micromips = 1;
14527       mips_no_prev_insn ();
14528       break;
14529
14530     case OPTION_NO_MICROMIPS:
14531       mips_opts.micromips = 0;
14532       mips_no_prev_insn ();
14533       break;
14534
14535     case OPTION_MIPS16:
14536       if (mips_opts.micromips == 1)
14537         {
14538           as_bad (_("-mips16 cannot be used with -micromips"));
14539           return 0;
14540         }
14541       mips_opts.mips16 = 1;
14542       mips_no_prev_insn ();
14543       break;
14544
14545     case OPTION_NO_MIPS16:
14546       mips_opts.mips16 = 0;
14547       mips_no_prev_insn ();
14548       break;
14549
14550     case OPTION_MIPS3D:
14551       mips_opts.ase_mips3d = 1;
14552       break;
14553
14554     case OPTION_NO_MIPS3D:
14555       mips_opts.ase_mips3d = 0;
14556       break;
14557
14558     case OPTION_SMARTMIPS:
14559       mips_opts.ase_smartmips = 1;
14560       break;
14561
14562     case OPTION_NO_SMARTMIPS:
14563       mips_opts.ase_smartmips = 0;
14564       break;
14565
14566     case OPTION_FIX_24K:
14567       mips_fix_24k = 1;
14568       break;
14569
14570     case OPTION_NO_FIX_24K:
14571       mips_fix_24k = 0;
14572       break;
14573
14574     case OPTION_FIX_LOONGSON2F_JUMP:
14575       mips_fix_loongson2f_jump = TRUE;
14576       break;
14577
14578     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14579       mips_fix_loongson2f_jump = FALSE;
14580       break;
14581
14582     case OPTION_FIX_LOONGSON2F_NOP:
14583       mips_fix_loongson2f_nop = TRUE;
14584       break;
14585
14586     case OPTION_NO_FIX_LOONGSON2F_NOP:
14587       mips_fix_loongson2f_nop = FALSE;
14588       break;
14589
14590     case OPTION_FIX_VR4120:
14591       mips_fix_vr4120 = 1;
14592       break;
14593
14594     case OPTION_NO_FIX_VR4120:
14595       mips_fix_vr4120 = 0;
14596       break;
14597
14598     case OPTION_FIX_VR4130:
14599       mips_fix_vr4130 = 1;
14600       break;
14601
14602     case OPTION_NO_FIX_VR4130:
14603       mips_fix_vr4130 = 0;
14604       break;
14605
14606     case OPTION_FIX_CN63XXP1:
14607       mips_fix_cn63xxp1 = TRUE;
14608       break;
14609
14610     case OPTION_NO_FIX_CN63XXP1:
14611       mips_fix_cn63xxp1 = FALSE;
14612       break;
14613
14614     case OPTION_RELAX_BRANCH:
14615       mips_relax_branch = 1;
14616       break;
14617
14618     case OPTION_NO_RELAX_BRANCH:
14619       mips_relax_branch = 0;
14620       break;
14621
14622     case OPTION_MSHARED:
14623       mips_in_shared = TRUE;
14624       break;
14625
14626     case OPTION_MNO_SHARED:
14627       mips_in_shared = FALSE;
14628       break;
14629
14630     case OPTION_MSYM32:
14631       mips_opts.sym32 = TRUE;
14632       break;
14633
14634     case OPTION_MNO_SYM32:
14635       mips_opts.sym32 = FALSE;
14636       break;
14637
14638 #ifdef OBJ_ELF
14639       /* When generating ELF code, we permit -KPIC and -call_shared to
14640          select SVR4_PIC, and -non_shared to select no PIC.  This is
14641          intended to be compatible with Irix 5.  */
14642     case OPTION_CALL_SHARED:
14643       if (!IS_ELF)
14644         {
14645           as_bad (_("-call_shared is supported only for ELF format"));
14646           return 0;
14647         }
14648       mips_pic = SVR4_PIC;
14649       mips_abicalls = TRUE;
14650       break;
14651
14652     case OPTION_CALL_NONPIC:
14653       if (!IS_ELF)
14654         {
14655           as_bad (_("-call_nonpic is supported only for ELF format"));
14656           return 0;
14657         }
14658       mips_pic = NO_PIC;
14659       mips_abicalls = TRUE;
14660       break;
14661
14662     case OPTION_NON_SHARED:
14663       if (!IS_ELF)
14664         {
14665           as_bad (_("-non_shared is supported only for ELF format"));
14666           return 0;
14667         }
14668       mips_pic = NO_PIC;
14669       mips_abicalls = FALSE;
14670       break;
14671
14672       /* The -xgot option tells the assembler to use 32 bit offsets
14673          when accessing the got in SVR4_PIC mode.  It is for Irix
14674          compatibility.  */
14675     case OPTION_XGOT:
14676       mips_big_got = 1;
14677       break;
14678 #endif /* OBJ_ELF */
14679
14680     case 'G':
14681       g_switch_value = atoi (arg);
14682       g_switch_seen = 1;
14683       break;
14684
14685       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14686          and -mabi=64.  */
14687     case OPTION_32:
14688       if (IS_ELF)
14689         mips_abi = O32_ABI;
14690       /* We silently ignore -32 for non-ELF targets.  This greatly
14691          simplifies the construction of the MIPS GAS test cases.  */
14692       break;
14693
14694 #ifdef OBJ_ELF
14695     case OPTION_N32:
14696       if (!IS_ELF)
14697         {
14698           as_bad (_("-n32 is supported for ELF format only"));
14699           return 0;
14700         }
14701       mips_abi = N32_ABI;
14702       break;
14703
14704     case OPTION_64:
14705       if (!IS_ELF)
14706         {
14707           as_bad (_("-64 is supported for ELF format only"));
14708           return 0;
14709         }
14710       mips_abi = N64_ABI;
14711       if (!support_64bit_objects())
14712         as_fatal (_("No compiled in support for 64 bit object file format"));
14713       break;
14714 #endif /* OBJ_ELF */
14715
14716     case OPTION_GP32:
14717       file_mips_gp32 = 1;
14718       break;
14719
14720     case OPTION_GP64:
14721       file_mips_gp32 = 0;
14722       break;
14723
14724     case OPTION_FP32:
14725       file_mips_fp32 = 1;
14726       break;
14727
14728     case OPTION_FP64:
14729       file_mips_fp32 = 0;
14730       break;
14731
14732     case OPTION_SINGLE_FLOAT:
14733       file_mips_single_float = 1;
14734       break;
14735
14736     case OPTION_DOUBLE_FLOAT:
14737       file_mips_single_float = 0;
14738       break;
14739
14740     case OPTION_SOFT_FLOAT:
14741       file_mips_soft_float = 1;
14742       break;
14743
14744     case OPTION_HARD_FLOAT:
14745       file_mips_soft_float = 0;
14746       break;
14747
14748 #ifdef OBJ_ELF
14749     case OPTION_MABI:
14750       if (!IS_ELF)
14751         {
14752           as_bad (_("-mabi is supported for ELF format only"));
14753           return 0;
14754         }
14755       if (strcmp (arg, "32") == 0)
14756         mips_abi = O32_ABI;
14757       else if (strcmp (arg, "o64") == 0)
14758         mips_abi = O64_ABI;
14759       else if (strcmp (arg, "n32") == 0)
14760         mips_abi = N32_ABI;
14761       else if (strcmp (arg, "64") == 0)
14762         {
14763           mips_abi = N64_ABI;
14764           if (! support_64bit_objects())
14765             as_fatal (_("No compiled in support for 64 bit object file "
14766                         "format"));
14767         }
14768       else if (strcmp (arg, "eabi") == 0)
14769         mips_abi = EABI_ABI;
14770       else
14771         {
14772           as_fatal (_("invalid abi -mabi=%s"), arg);
14773           return 0;
14774         }
14775       break;
14776 #endif /* OBJ_ELF */
14777
14778     case OPTION_M7000_HILO_FIX:
14779       mips_7000_hilo_fix = TRUE;
14780       break;
14781
14782     case OPTION_MNO_7000_HILO_FIX:
14783       mips_7000_hilo_fix = FALSE;
14784       break;
14785
14786 #ifdef OBJ_ELF
14787     case OPTION_MDEBUG:
14788       mips_flag_mdebug = TRUE;
14789       break;
14790
14791     case OPTION_NO_MDEBUG:
14792       mips_flag_mdebug = FALSE;
14793       break;
14794
14795     case OPTION_PDR:
14796       mips_flag_pdr = TRUE;
14797       break;
14798
14799     case OPTION_NO_PDR:
14800       mips_flag_pdr = FALSE;
14801       break;
14802
14803     case OPTION_MVXWORKS_PIC:
14804       mips_pic = VXWORKS_PIC;
14805       break;
14806 #endif /* OBJ_ELF */
14807
14808     default:
14809       return 0;
14810     }
14811
14812     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14813
14814   return 1;
14815 }
14816 \f
14817 /* Set up globals to generate code for the ISA or processor
14818    described by INFO.  */
14819
14820 static void
14821 mips_set_architecture (const struct mips_cpu_info *info)
14822 {
14823   if (info != 0)
14824     {
14825       file_mips_arch = info->cpu;
14826       mips_opts.arch = info->cpu;
14827       mips_opts.isa = info->isa;
14828     }
14829 }
14830
14831
14832 /* Likewise for tuning.  */
14833
14834 static void
14835 mips_set_tune (const struct mips_cpu_info *info)
14836 {
14837   if (info != 0)
14838     mips_tune = info->cpu;
14839 }
14840
14841
14842 void
14843 mips_after_parse_args (void)
14844 {
14845   const struct mips_cpu_info *arch_info = 0;
14846   const struct mips_cpu_info *tune_info = 0;
14847
14848   /* GP relative stuff not working for PE */
14849   if (strncmp (TARGET_OS, "pe", 2) == 0)
14850     {
14851       if (g_switch_seen && g_switch_value != 0)
14852         as_bad (_("-G not supported in this configuration."));
14853       g_switch_value = 0;
14854     }
14855
14856   if (mips_abi == NO_ABI)
14857     mips_abi = MIPS_DEFAULT_ABI;
14858
14859   /* The following code determines the architecture and register size.
14860      Similar code was added to GCC 3.3 (see override_options() in
14861      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14862      as much as possible.  */
14863
14864   if (mips_arch_string != 0)
14865     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14866
14867   if (file_mips_isa != ISA_UNKNOWN)
14868     {
14869       /* Handle -mipsN.  At this point, file_mips_isa contains the
14870          ISA level specified by -mipsN, while arch_info->isa contains
14871          the -march selection (if any).  */
14872       if (arch_info != 0)
14873         {
14874           /* -march takes precedence over -mipsN, since it is more descriptive.
14875              There's no harm in specifying both as long as the ISA levels
14876              are the same.  */
14877           if (file_mips_isa != arch_info->isa)
14878             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
14879                     mips_cpu_info_from_isa (file_mips_isa)->name,
14880                     mips_cpu_info_from_isa (arch_info->isa)->name);
14881         }
14882       else
14883         arch_info = mips_cpu_info_from_isa (file_mips_isa);
14884     }
14885
14886   if (arch_info == 0)
14887     arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14888
14889   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14890     as_bad (_("-march=%s is not compatible with the selected ABI"),
14891             arch_info->name);
14892
14893   mips_set_architecture (arch_info);
14894
14895   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
14896   if (mips_tune_string != 0)
14897     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14898
14899   if (tune_info == 0)
14900     mips_set_tune (arch_info);
14901   else
14902     mips_set_tune (tune_info);
14903
14904   if (file_mips_gp32 >= 0)
14905     {
14906       /* The user specified the size of the integer registers.  Make sure
14907          it agrees with the ABI and ISA.  */
14908       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
14909         as_bad (_("-mgp64 used with a 32-bit processor"));
14910       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
14911         as_bad (_("-mgp32 used with a 64-bit ABI"));
14912       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
14913         as_bad (_("-mgp64 used with a 32-bit ABI"));
14914     }
14915   else
14916     {
14917       /* Infer the integer register size from the ABI and processor.
14918          Restrict ourselves to 32-bit registers if that's all the
14919          processor has, or if the ABI cannot handle 64-bit registers.  */
14920       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
14921                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
14922     }
14923
14924   switch (file_mips_fp32)
14925     {
14926     default:
14927     case -1:
14928       /* No user specified float register size.
14929          ??? GAS treats single-float processors as though they had 64-bit
14930          float registers (although it complains when double-precision
14931          instructions are used).  As things stand, saying they have 32-bit
14932          registers would lead to spurious "register must be even" messages.
14933          So here we assume float registers are never smaller than the
14934          integer ones.  */
14935       if (file_mips_gp32 == 0)
14936         /* 64-bit integer registers implies 64-bit float registers.  */
14937         file_mips_fp32 = 0;
14938       else if ((mips_opts.ase_mips3d > 0 || mips_opts.ase_mdmx > 0)
14939                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
14940         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
14941         file_mips_fp32 = 0;
14942       else
14943         /* 32-bit float registers.  */
14944         file_mips_fp32 = 1;
14945       break;
14946
14947     /* The user specified the size of the float registers.  Check if it
14948        agrees with the ABI and ISA.  */
14949     case 0:
14950       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14951         as_bad (_("-mfp64 used with a 32-bit fpu"));
14952       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
14953                && !ISA_HAS_MXHC1 (mips_opts.isa))
14954         as_warn (_("-mfp64 used with a 32-bit ABI"));
14955       break;
14956     case 1:
14957       if (ABI_NEEDS_64BIT_REGS (mips_abi))
14958         as_warn (_("-mfp32 used with a 64-bit ABI"));
14959       break;
14960     }
14961
14962   /* End of GCC-shared inference code.  */
14963
14964   /* This flag is set when we have a 64-bit capable CPU but use only
14965      32-bit wide registers.  Note that EABI does not use it.  */
14966   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14967       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14968           || mips_abi == O32_ABI))
14969     mips_32bitmode = 1;
14970
14971   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14972     as_bad (_("trap exception not supported at ISA 1"));
14973
14974   /* If the selected architecture includes support for ASEs, enable
14975      generation of code for them.  */
14976   if (mips_opts.mips16 == -1)
14977     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14978   if (mips_opts.micromips == -1)
14979     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14980   if (mips_opts.ase_mips3d == -1)
14981     mips_opts.ase_mips3d = ((arch_info->flags & MIPS_CPU_ASE_MIPS3D)
14982                             && file_mips_fp32 == 0) ? 1 : 0;
14983   if (mips_opts.ase_mips3d && file_mips_fp32 == 1)
14984     as_bad (_("-mfp32 used with -mips3d"));
14985
14986   if (mips_opts.ase_mdmx == -1)
14987     mips_opts.ase_mdmx = ((arch_info->flags & MIPS_CPU_ASE_MDMX)
14988                           && file_mips_fp32 == 0) ? 1 : 0;
14989   if (mips_opts.ase_mdmx && file_mips_fp32 == 1)
14990     as_bad (_("-mfp32 used with -mdmx"));
14991
14992   if (mips_opts.ase_smartmips == -1)
14993     mips_opts.ase_smartmips = (arch_info->flags & MIPS_CPU_ASE_SMARTMIPS) ? 1 : 0;
14994   if (mips_opts.ase_smartmips && !ISA_SUPPORTS_SMARTMIPS)
14995     as_warn (_("%s ISA does not support SmartMIPS"), 
14996              mips_cpu_info_from_isa (mips_opts.isa)->name);
14997
14998   if (mips_opts.ase_dsp == -1)
14999     mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15000   if (mips_opts.ase_dsp && !ISA_SUPPORTS_DSP_ASE)
15001     as_warn (_("%s ISA does not support DSP ASE"), 
15002              mips_cpu_info_from_isa (mips_opts.isa)->name);
15003
15004   if (mips_opts.ase_dspr2 == -1)
15005     {
15006       mips_opts.ase_dspr2 = (arch_info->flags & MIPS_CPU_ASE_DSPR2) ? 1 : 0;
15007       mips_opts.ase_dsp = (arch_info->flags & MIPS_CPU_ASE_DSP) ? 1 : 0;
15008     }
15009   if (mips_opts.ase_dspr2 && !ISA_SUPPORTS_DSPR2_ASE)
15010     as_warn (_("%s ISA does not support DSP R2 ASE"),
15011              mips_cpu_info_from_isa (mips_opts.isa)->name);
15012
15013   if (mips_opts.ase_mt == -1)
15014     mips_opts.ase_mt = (arch_info->flags & MIPS_CPU_ASE_MT) ? 1 : 0;
15015   if (mips_opts.ase_mt && !ISA_SUPPORTS_MT_ASE)
15016     as_warn (_("%s ISA does not support MT ASE"),
15017              mips_cpu_info_from_isa (mips_opts.isa)->name);
15018
15019   file_mips_isa = mips_opts.isa;
15020   file_ase_mips3d = mips_opts.ase_mips3d;
15021   file_ase_mdmx = mips_opts.ase_mdmx;
15022   file_ase_smartmips = mips_opts.ase_smartmips;
15023   file_ase_dsp = mips_opts.ase_dsp;
15024   file_ase_dspr2 = mips_opts.ase_dspr2;
15025   file_ase_mt = mips_opts.ase_mt;
15026   mips_opts.gp32 = file_mips_gp32;
15027   mips_opts.fp32 = file_mips_fp32;
15028   mips_opts.soft_float = file_mips_soft_float;
15029   mips_opts.single_float = file_mips_single_float;
15030
15031   if (mips_flag_mdebug < 0)
15032     {
15033 #ifdef OBJ_MAYBE_ECOFF
15034       if (OUTPUT_FLAVOR == bfd_target_ecoff_flavour)
15035         mips_flag_mdebug = 1;
15036       else
15037 #endif /* OBJ_MAYBE_ECOFF */
15038         mips_flag_mdebug = 0;
15039     }
15040 }
15041 \f
15042 void
15043 mips_init_after_args (void)
15044 {
15045   /* initialize opcodes */
15046   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15047   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15048 }
15049
15050 long
15051 md_pcrel_from (fixS *fixP)
15052 {
15053   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15054   switch (fixP->fx_r_type)
15055     {
15056     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15057     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15058       /* Return the address of the delay slot.  */
15059       return addr + 2;
15060
15061     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15062     case BFD_RELOC_MICROMIPS_JMP:
15063     case BFD_RELOC_16_PCREL_S2:
15064     case BFD_RELOC_MIPS_JMP:
15065       /* Return the address of the delay slot.  */
15066       return addr + 4;
15067
15068     default:
15069       /* We have no relocation type for PC relative MIPS16 instructions.  */
15070       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15071         as_bad_where (fixP->fx_file, fixP->fx_line,
15072                       _("PC relative MIPS16 instruction references a different section"));
15073       return addr;
15074     }
15075 }
15076
15077 /* This is called before the symbol table is processed.  In order to
15078    work with gcc when using mips-tfile, we must keep all local labels.
15079    However, in other cases, we want to discard them.  If we were
15080    called with -g, but we didn't see any debugging information, it may
15081    mean that gcc is smuggling debugging information through to
15082    mips-tfile, in which case we must generate all local labels.  */
15083
15084 void
15085 mips_frob_file_before_adjust (void)
15086 {
15087 #ifndef NO_ECOFF_DEBUGGING
15088   if (ECOFF_DEBUGGING
15089       && mips_debug != 0
15090       && ! ecoff_debugging_seen)
15091     flag_keep_locals = 1;
15092 #endif
15093 }
15094
15095 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15096    the corresponding LO16 reloc.  This is called before md_apply_fix and
15097    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15098    relocation operators.
15099
15100    For our purposes, a %lo() expression matches a %got() or %hi()
15101    expression if:
15102
15103       (a) it refers to the same symbol; and
15104       (b) the offset applied in the %lo() expression is no lower than
15105           the offset applied in the %got() or %hi().
15106
15107    (b) allows us to cope with code like:
15108
15109         lui     $4,%hi(foo)
15110         lh      $4,%lo(foo+2)($4)
15111
15112    ...which is legal on RELA targets, and has a well-defined behaviour
15113    if the user knows that adding 2 to "foo" will not induce a carry to
15114    the high 16 bits.
15115
15116    When several %lo()s match a particular %got() or %hi(), we use the
15117    following rules to distinguish them:
15118
15119      (1) %lo()s with smaller offsets are a better match than %lo()s with
15120          higher offsets.
15121
15122      (2) %lo()s with no matching %got() or %hi() are better than those
15123          that already have a matching %got() or %hi().
15124
15125      (3) later %lo()s are better than earlier %lo()s.
15126
15127    These rules are applied in order.
15128
15129    (1) means, among other things, that %lo()s with identical offsets are
15130    chosen if they exist.
15131
15132    (2) means that we won't associate several high-part relocations with
15133    the same low-part relocation unless there's no alternative.  Having
15134    several high parts for the same low part is a GNU extension; this rule
15135    allows careful users to avoid it.
15136
15137    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15138    with the last high-part relocation being at the front of the list.
15139    It therefore makes sense to choose the last matching low-part
15140    relocation, all other things being equal.  It's also easier
15141    to code that way.  */
15142
15143 void
15144 mips_frob_file (void)
15145 {
15146   struct mips_hi_fixup *l;
15147   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15148
15149   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15150     {
15151       segment_info_type *seginfo;
15152       bfd_boolean matched_lo_p;
15153       fixS **hi_pos, **lo_pos, **pos;
15154
15155       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15156
15157       /* If a GOT16 relocation turns out to be against a global symbol,
15158          there isn't supposed to be a matching LO.  */
15159       if (got16_reloc_p (l->fixp->fx_r_type)
15160           && !pic_need_relax (l->fixp->fx_addsy, l->seg))
15161         continue;
15162
15163       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15164       if (fixup_has_matching_lo_p (l->fixp))
15165         continue;
15166
15167       seginfo = seg_info (l->seg);
15168
15169       /* Set HI_POS to the position of this relocation in the chain.
15170          Set LO_POS to the position of the chosen low-part relocation.
15171          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15172          relocation that matches an immediately-preceding high-part
15173          relocation.  */
15174       hi_pos = NULL;
15175       lo_pos = NULL;
15176       matched_lo_p = FALSE;
15177       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15178
15179       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15180         {
15181           if (*pos == l->fixp)
15182             hi_pos = pos;
15183
15184           if ((*pos)->fx_r_type == looking_for_rtype
15185               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15186               && (*pos)->fx_offset >= l->fixp->fx_offset
15187               && (lo_pos == NULL
15188                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15189                   || (!matched_lo_p
15190                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15191             lo_pos = pos;
15192
15193           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15194                           && fixup_has_matching_lo_p (*pos));
15195         }
15196
15197       /* If we found a match, remove the high-part relocation from its
15198          current position and insert it before the low-part relocation.
15199          Make the offsets match so that fixup_has_matching_lo_p()
15200          will return true.
15201
15202          We don't warn about unmatched high-part relocations since some
15203          versions of gcc have been known to emit dead "lui ...%hi(...)"
15204          instructions.  */
15205       if (lo_pos != NULL)
15206         {
15207           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15208           if (l->fixp->fx_next != *lo_pos)
15209             {
15210               *hi_pos = l->fixp->fx_next;
15211               l->fixp->fx_next = *lo_pos;
15212               *lo_pos = l->fixp;
15213             }
15214         }
15215     }
15216 }
15217
15218 /* We may have combined relocations without symbols in the N32/N64 ABI.
15219    We have to prevent gas from dropping them.  */
15220
15221 int
15222 mips_force_relocation (fixS *fixp)
15223 {
15224   if (generic_force_reloc (fixp))
15225     return 1;
15226
15227   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15228      so that the linker relaxation can update targets.  */
15229   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15230       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15231       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15232     return 1;
15233
15234   if (HAVE_NEWABI
15235       && S_GET_SEGMENT (fixp->fx_addsy) == bfd_abs_section_ptr
15236       && (fixp->fx_r_type == BFD_RELOC_MIPS_SUB
15237           || hi16_reloc_p (fixp->fx_r_type)
15238           || lo16_reloc_p (fixp->fx_r_type)))
15239     return 1;
15240
15241   return 0;
15242 }
15243
15244 /* Apply a fixup to the object file.  */
15245
15246 void
15247 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15248 {
15249   bfd_byte *buf;
15250   long insn;
15251   reloc_howto_type *howto;
15252
15253   /* We ignore generic BFD relocations we don't know about.  */
15254   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15255   if (! howto)
15256     return;
15257
15258   gas_assert (fixP->fx_size == 2
15259               || fixP->fx_size == 4
15260               || fixP->fx_r_type == BFD_RELOC_16
15261               || fixP->fx_r_type == BFD_RELOC_64
15262               || fixP->fx_r_type == BFD_RELOC_CTOR
15263               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15264               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15265               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15266               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15267               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15268
15269   buf = (bfd_byte *) (fixP->fx_frag->fr_literal + fixP->fx_where);
15270
15271   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15272               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15273               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15274               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
15275
15276   /* Don't treat parts of a composite relocation as done.  There are two
15277      reasons for this:
15278
15279      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15280          should nevertheless be emitted if the first part is.
15281
15282      (2) In normal usage, composite relocations are never assembly-time
15283          constants.  The easiest way of dealing with the pathological
15284          exceptions is to generate a relocation against STN_UNDEF and
15285          leave everything up to the linker.  */
15286   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15287     fixP->fx_done = 1;
15288
15289   switch (fixP->fx_r_type)
15290     {
15291     case BFD_RELOC_MIPS_TLS_GD:
15292     case BFD_RELOC_MIPS_TLS_LDM:
15293     case BFD_RELOC_MIPS_TLS_DTPREL32:
15294     case BFD_RELOC_MIPS_TLS_DTPREL64:
15295     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15296     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15297     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15298     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15299     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15300     case BFD_RELOC_MICROMIPS_TLS_GD:
15301     case BFD_RELOC_MICROMIPS_TLS_LDM:
15302     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15303     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15304     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15305     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15306     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15307       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15308       /* fall through */
15309
15310     case BFD_RELOC_MIPS_JMP:
15311     case BFD_RELOC_MIPS_SHIFT5:
15312     case BFD_RELOC_MIPS_SHIFT6:
15313     case BFD_RELOC_MIPS_GOT_DISP:
15314     case BFD_RELOC_MIPS_GOT_PAGE:
15315     case BFD_RELOC_MIPS_GOT_OFST:
15316     case BFD_RELOC_MIPS_SUB:
15317     case BFD_RELOC_MIPS_INSERT_A:
15318     case BFD_RELOC_MIPS_INSERT_B:
15319     case BFD_RELOC_MIPS_DELETE:
15320     case BFD_RELOC_MIPS_HIGHEST:
15321     case BFD_RELOC_MIPS_HIGHER:
15322     case BFD_RELOC_MIPS_SCN_DISP:
15323     case BFD_RELOC_MIPS_REL16:
15324     case BFD_RELOC_MIPS_RELGOT:
15325     case BFD_RELOC_MIPS_JALR:
15326     case BFD_RELOC_HI16:
15327     case BFD_RELOC_HI16_S:
15328     case BFD_RELOC_GPREL16:
15329     case BFD_RELOC_MIPS_LITERAL:
15330     case BFD_RELOC_MIPS_CALL16:
15331     case BFD_RELOC_MIPS_GOT16:
15332     case BFD_RELOC_GPREL32:
15333     case BFD_RELOC_MIPS_GOT_HI16:
15334     case BFD_RELOC_MIPS_GOT_LO16:
15335     case BFD_RELOC_MIPS_CALL_HI16:
15336     case BFD_RELOC_MIPS_CALL_LO16:
15337     case BFD_RELOC_MIPS16_GPREL:
15338     case BFD_RELOC_MIPS16_GOT16:
15339     case BFD_RELOC_MIPS16_CALL16:
15340     case BFD_RELOC_MIPS16_HI16:
15341     case BFD_RELOC_MIPS16_HI16_S:
15342     case BFD_RELOC_MIPS16_JMP:
15343     case BFD_RELOC_MICROMIPS_JMP:
15344     case BFD_RELOC_MICROMIPS_GOT_DISP:
15345     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15346     case BFD_RELOC_MICROMIPS_GOT_OFST:
15347     case BFD_RELOC_MICROMIPS_SUB:
15348     case BFD_RELOC_MICROMIPS_HIGHEST:
15349     case BFD_RELOC_MICROMIPS_HIGHER:
15350     case BFD_RELOC_MICROMIPS_SCN_DISP:
15351     case BFD_RELOC_MICROMIPS_JALR:
15352     case BFD_RELOC_MICROMIPS_HI16:
15353     case BFD_RELOC_MICROMIPS_HI16_S:
15354     case BFD_RELOC_MICROMIPS_GPREL16:
15355     case BFD_RELOC_MICROMIPS_LITERAL:
15356     case BFD_RELOC_MICROMIPS_CALL16:
15357     case BFD_RELOC_MICROMIPS_GOT16:
15358     case BFD_RELOC_MICROMIPS_GOT_HI16:
15359     case BFD_RELOC_MICROMIPS_GOT_LO16:
15360     case BFD_RELOC_MICROMIPS_CALL_HI16:
15361     case BFD_RELOC_MICROMIPS_CALL_LO16:
15362       /* Nothing needed to do.  The value comes from the reloc entry.  */
15363       break;
15364
15365     case BFD_RELOC_64:
15366       /* This is handled like BFD_RELOC_32, but we output a sign
15367          extended value if we are only 32 bits.  */
15368       if (fixP->fx_done)
15369         {
15370           if (8 <= sizeof (valueT))
15371             md_number_to_chars ((char *) buf, *valP, 8);
15372           else
15373             {
15374               valueT hiv;
15375
15376               if ((*valP & 0x80000000) != 0)
15377                 hiv = 0xffffffff;
15378               else
15379                 hiv = 0;
15380               md_number_to_chars ((char *)(buf + (target_big_endian ? 4 : 0)),
15381                                   *valP, 4);
15382               md_number_to_chars ((char *)(buf + (target_big_endian ? 0 : 4)),
15383                                   hiv, 4);
15384             }
15385         }
15386       break;
15387
15388     case BFD_RELOC_RVA:
15389     case BFD_RELOC_32:
15390     case BFD_RELOC_16:
15391       /* If we are deleting this reloc entry, we must fill in the
15392          value now.  This can happen if we have a .word which is not
15393          resolved when it appears but is later defined.  */
15394       if (fixP->fx_done)
15395         md_number_to_chars ((char *) buf, *valP, fixP->fx_size);
15396       break;
15397
15398     case BFD_RELOC_LO16:
15399     case BFD_RELOC_MIPS16_LO16:
15400     case BFD_RELOC_MICROMIPS_LO16:
15401       /* FIXME: Now that embedded-PIC is gone, some of this code/comment
15402          may be safe to remove, but if so it's not obvious.  */
15403       /* When handling an embedded PIC switch statement, we can wind
15404          up deleting a LO16 reloc.  See the 'o' case in mips_ip.  */
15405       if (fixP->fx_done)
15406         {
15407           if (*valP + 0x8000 > 0xffff)
15408             as_bad_where (fixP->fx_file, fixP->fx_line,
15409                           _("relocation overflow"));
15410           /* 32-bit microMIPS instructions are divided into two halfwords.
15411              Relocations always refer to the second halfword, regardless
15412              of endianness.  */
15413           if (target_big_endian || fixP->fx_r_type == BFD_RELOC_MICROMIPS_LO16)
15414             buf += 2;
15415           md_number_to_chars ((char *) buf, *valP, 2);
15416         }
15417       break;
15418
15419     case BFD_RELOC_16_PCREL_S2:
15420       if ((*valP & 0x3) != 0)
15421         as_bad_where (fixP->fx_file, fixP->fx_line,
15422                       _("Branch to misaligned address (%lx)"), (long) *valP);
15423
15424       /* We need to save the bits in the instruction since fixup_segment()
15425          might be deleting the relocation entry (i.e., a branch within
15426          the current segment).  */
15427       if (! fixP->fx_done)
15428         break;
15429
15430       /* Update old instruction data.  */
15431       if (target_big_endian)
15432         insn = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
15433       else
15434         insn = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
15435
15436       if (*valP + 0x20000 <= 0x3ffff)
15437         {
15438           insn |= (*valP >> 2) & 0xffff;
15439           md_number_to_chars ((char *) buf, insn, 4);
15440         }
15441       else if (mips_pic == NO_PIC
15442                && fixP->fx_done
15443                && fixP->fx_frag->fr_address >= text_section->vma
15444                && (fixP->fx_frag->fr_address
15445                    < text_section->vma + bfd_get_section_size (text_section))
15446                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15447                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15448                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15449         {
15450           /* The branch offset is too large.  If this is an
15451              unconditional branch, and we are not generating PIC code,
15452              we can convert it to an absolute jump instruction.  */
15453           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15454             insn = 0x0c000000;  /* jal */
15455           else
15456             insn = 0x08000000;  /* j */
15457           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15458           fixP->fx_done = 0;
15459           fixP->fx_addsy = section_symbol (text_section);
15460           *valP += md_pcrel_from (fixP);
15461           md_number_to_chars ((char *) buf, insn, 4);
15462         }
15463       else
15464         {
15465           /* If we got here, we have branch-relaxation disabled,
15466              and there's nothing we can do to fix this instruction
15467              without turning it into a longer sequence.  */
15468           as_bad_where (fixP->fx_file, fixP->fx_line,
15469                         _("Branch out of range"));
15470         }
15471       break;
15472
15473     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15474     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15475     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15476       /* We adjust the offset back to even.  */
15477       if ((*valP & 0x1) != 0)
15478         --(*valP);
15479
15480       if (! fixP->fx_done)
15481         break;
15482
15483       /* Should never visit here, because we keep the relocation.  */
15484       abort ();
15485       break;
15486
15487     case BFD_RELOC_VTABLE_INHERIT:
15488       fixP->fx_done = 0;
15489       if (fixP->fx_addsy
15490           && !S_IS_DEFINED (fixP->fx_addsy)
15491           && !S_IS_WEAK (fixP->fx_addsy))
15492         S_SET_WEAK (fixP->fx_addsy);
15493       break;
15494
15495     case BFD_RELOC_VTABLE_ENTRY:
15496       fixP->fx_done = 0;
15497       break;
15498
15499     default:
15500       internalError ();
15501     }
15502
15503   /* Remember value for tc_gen_reloc.  */
15504   fixP->fx_addnumber = *valP;
15505 }
15506
15507 static symbolS *
15508 get_symbol (void)
15509 {
15510   int c;
15511   char *name;
15512   symbolS *p;
15513
15514   name = input_line_pointer;
15515   c = get_symbol_end ();
15516   p = (symbolS *) symbol_find_or_make (name);
15517   *input_line_pointer = c;
15518   return p;
15519 }
15520
15521 /* Align the current frag to a given power of two.  If a particular
15522    fill byte should be used, FILL points to an integer that contains
15523    that byte, otherwise FILL is null.
15524
15525    The MIPS assembler also automatically adjusts any preceding
15526    label.  */
15527
15528 static void
15529 mips_align (int to, int *fill, symbolS *label)
15530 {
15531   mips_emit_delays ();
15532   mips_record_compressed_mode ();
15533   if (fill == NULL && subseg_text_p (now_seg))
15534     frag_align_code (to, 0);
15535   else
15536     frag_align (to, fill ? *fill : 0, 0);
15537   record_alignment (now_seg, to);
15538   if (label != NULL)
15539     {
15540       gas_assert (S_GET_SEGMENT (label) == now_seg);
15541       symbol_set_frag (label, frag_now);
15542       S_SET_VALUE (label, (valueT) frag_now_fix ());
15543     }
15544 }
15545
15546 /* Align to a given power of two.  .align 0 turns off the automatic
15547    alignment used by the data creating pseudo-ops.  */
15548
15549 static void
15550 s_align (int x ATTRIBUTE_UNUSED)
15551 {
15552   int temp, fill_value, *fill_ptr;
15553   long max_alignment = 28;
15554
15555   /* o Note that the assembler pulls down any immediately preceding label
15556        to the aligned address.
15557      o It's not documented but auto alignment is reinstated by
15558        a .align pseudo instruction.
15559      o Note also that after auto alignment is turned off the mips assembler
15560        issues an error on attempt to assemble an improperly aligned data item.
15561        We don't.  */
15562
15563   temp = get_absolute_expression ();
15564   if (temp > max_alignment)
15565     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
15566   else if (temp < 0)
15567     {
15568       as_warn (_("Alignment negative: 0 assumed."));
15569       temp = 0;
15570     }
15571   if (*input_line_pointer == ',')
15572     {
15573       ++input_line_pointer;
15574       fill_value = get_absolute_expression ();
15575       fill_ptr = &fill_value;
15576     }
15577   else
15578     fill_ptr = 0;
15579   if (temp)
15580     {
15581       segment_info_type *si = seg_info (now_seg);
15582       struct insn_label_list *l = si->label_list;
15583       /* Auto alignment should be switched on by next section change.  */
15584       auto_align = 1;
15585       mips_align (temp, fill_ptr, l != NULL ? l->label : NULL);
15586     }
15587   else
15588     {
15589       auto_align = 0;
15590     }
15591
15592   demand_empty_rest_of_line ();
15593 }
15594
15595 static void
15596 s_change_sec (int sec)
15597 {
15598   segT seg;
15599
15600 #ifdef OBJ_ELF
15601   /* The ELF backend needs to know that we are changing sections, so
15602      that .previous works correctly.  We could do something like check
15603      for an obj_section_change_hook macro, but that might be confusing
15604      as it would not be appropriate to use it in the section changing
15605      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15606      This should be cleaner, somehow.  */
15607   if (IS_ELF)
15608     obj_elf_section_change_hook ();
15609 #endif
15610
15611   mips_emit_delays ();
15612
15613   switch (sec)
15614     {
15615     case 't':
15616       s_text (0);
15617       break;
15618     case 'd':
15619       s_data (0);
15620       break;
15621     case 'b':
15622       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15623       demand_empty_rest_of_line ();
15624       break;
15625
15626     case 'r':
15627       seg = subseg_new (RDATA_SECTION_NAME,
15628                         (subsegT) get_absolute_expression ());
15629       if (IS_ELF)
15630         {
15631           bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15632                                                   | SEC_READONLY | SEC_RELOC
15633                                                   | SEC_DATA));
15634           if (strncmp (TARGET_OS, "elf", 3) != 0)
15635             record_alignment (seg, 4);
15636         }
15637       demand_empty_rest_of_line ();
15638       break;
15639
15640     case 's':
15641       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15642       if (IS_ELF)
15643         {
15644           bfd_set_section_flags (stdoutput, seg,
15645                                  SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15646           if (strncmp (TARGET_OS, "elf", 3) != 0)
15647             record_alignment (seg, 4);
15648         }
15649       demand_empty_rest_of_line ();
15650       break;
15651
15652     case 'B':
15653       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15654       if (IS_ELF)
15655         {
15656           bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15657           if (strncmp (TARGET_OS, "elf", 3) != 0)
15658             record_alignment (seg, 4);
15659         }
15660       demand_empty_rest_of_line ();
15661       break;
15662     }
15663
15664   auto_align = 1;
15665 }
15666
15667 void
15668 s_change_section (int ignore ATTRIBUTE_UNUSED)
15669 {
15670 #ifdef OBJ_ELF
15671   char *section_name;
15672   char c;
15673   char next_c = 0;
15674   int section_type;
15675   int section_flag;
15676   int section_entry_size;
15677   int section_alignment;
15678
15679   if (!IS_ELF)
15680     return;
15681
15682   section_name = input_line_pointer;
15683   c = get_symbol_end ();
15684   if (c)
15685     next_c = *(input_line_pointer + 1);
15686
15687   /* Do we have .section Name<,"flags">?  */
15688   if (c != ',' || (c == ',' && next_c == '"'))
15689     {
15690       /* just after name is now '\0'.  */
15691       *input_line_pointer = c;
15692       input_line_pointer = section_name;
15693       obj_elf_section (ignore);
15694       return;
15695     }
15696   input_line_pointer++;
15697
15698   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15699   if (c == ',')
15700     section_type = get_absolute_expression ();
15701   else
15702     section_type = 0;
15703   if (*input_line_pointer++ == ',')
15704     section_flag = get_absolute_expression ();
15705   else
15706     section_flag = 0;
15707   if (*input_line_pointer++ == ',')
15708     section_entry_size = get_absolute_expression ();
15709   else
15710     section_entry_size = 0;
15711   if (*input_line_pointer++ == ',')
15712     section_alignment = get_absolute_expression ();
15713   else
15714     section_alignment = 0;
15715   /* FIXME: really ignore?  */
15716   (void) section_alignment;
15717
15718   section_name = xstrdup (section_name);
15719
15720   /* When using the generic form of .section (as implemented by obj-elf.c),
15721      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15722      traditionally had to fall back on the more common @progbits instead.
15723
15724      There's nothing really harmful in this, since bfd will correct
15725      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15726      means that, for backwards compatibility, the special_section entries
15727      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15728
15729      Even so, we shouldn't force users of the MIPS .section syntax to
15730      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15731      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15732      generic type-checking code.  */
15733   if (section_type == SHT_MIPS_DWARF)
15734     section_type = SHT_PROGBITS;
15735
15736   obj_elf_change_section (section_name, section_type, section_flag,
15737                           section_entry_size, 0, 0, 0);
15738
15739   if (now_seg->name != section_name)
15740     free (section_name);
15741 #endif /* OBJ_ELF */
15742 }
15743
15744 void
15745 mips_enable_auto_align (void)
15746 {
15747   auto_align = 1;
15748 }
15749
15750 static void
15751 s_cons (int log_size)
15752 {
15753   segment_info_type *si = seg_info (now_seg);
15754   struct insn_label_list *l = si->label_list;
15755   symbolS *label;
15756
15757   label = l != NULL ? l->label : NULL;
15758   mips_emit_delays ();
15759   if (log_size > 0 && auto_align)
15760     mips_align (log_size, 0, label);
15761   cons (1 << log_size);
15762   mips_clear_insn_labels ();
15763 }
15764
15765 static void
15766 s_float_cons (int type)
15767 {
15768   segment_info_type *si = seg_info (now_seg);
15769   struct insn_label_list *l = si->label_list;
15770   symbolS *label;
15771
15772   label = l != NULL ? l->label : NULL;
15773
15774   mips_emit_delays ();
15775
15776   if (auto_align)
15777     {
15778       if (type == 'd')
15779         mips_align (3, 0, label);
15780       else
15781         mips_align (2, 0, label);
15782     }
15783
15784   float_cons (type);
15785   mips_clear_insn_labels ();
15786 }
15787
15788 /* Handle .globl.  We need to override it because on Irix 5 you are
15789    permitted to say
15790        .globl foo .text
15791    where foo is an undefined symbol, to mean that foo should be
15792    considered to be the address of a function.  */
15793
15794 static void
15795 s_mips_globl (int x ATTRIBUTE_UNUSED)
15796 {
15797   char *name;
15798   int c;
15799   symbolS *symbolP;
15800   flagword flag;
15801
15802   do
15803     {
15804       name = input_line_pointer;
15805       c = get_symbol_end ();
15806       symbolP = symbol_find_or_make (name);
15807       S_SET_EXTERNAL (symbolP);
15808
15809       *input_line_pointer = c;
15810       SKIP_WHITESPACE ();
15811
15812       /* On Irix 5, every global symbol that is not explicitly labelled as
15813          being a function is apparently labelled as being an object.  */
15814       flag = BSF_OBJECT;
15815
15816       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15817           && (*input_line_pointer != ','))
15818         {
15819           char *secname;
15820           asection *sec;
15821
15822           secname = input_line_pointer;
15823           c = get_symbol_end ();
15824           sec = bfd_get_section_by_name (stdoutput, secname);
15825           if (sec == NULL)
15826             as_bad (_("%s: no such section"), secname);
15827           *input_line_pointer = c;
15828
15829           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15830             flag = BSF_FUNCTION;
15831         }
15832
15833       symbol_get_bfdsym (symbolP)->flags |= flag;
15834
15835       c = *input_line_pointer;
15836       if (c == ',')
15837         {
15838           input_line_pointer++;
15839           SKIP_WHITESPACE ();
15840           if (is_end_of_line[(unsigned char) *input_line_pointer])
15841             c = '\n';
15842         }
15843     }
15844   while (c == ',');
15845
15846   demand_empty_rest_of_line ();
15847 }
15848
15849 static void
15850 s_option (int x ATTRIBUTE_UNUSED)
15851 {
15852   char *opt;
15853   char c;
15854
15855   opt = input_line_pointer;
15856   c = get_symbol_end ();
15857
15858   if (*opt == 'O')
15859     {
15860       /* FIXME: What does this mean?  */
15861     }
15862   else if (strncmp (opt, "pic", 3) == 0)
15863     {
15864       int i;
15865
15866       i = atoi (opt + 3);
15867       if (i == 0)
15868         mips_pic = NO_PIC;
15869       else if (i == 2)
15870         {
15871         mips_pic = SVR4_PIC;
15872           mips_abicalls = TRUE;
15873         }
15874       else
15875         as_bad (_(".option pic%d not supported"), i);
15876
15877       if (mips_pic == SVR4_PIC)
15878         {
15879           if (g_switch_seen && g_switch_value != 0)
15880             as_warn (_("-G may not be used with SVR4 PIC code"));
15881           g_switch_value = 0;
15882           bfd_set_gp_size (stdoutput, 0);
15883         }
15884     }
15885   else
15886     as_warn (_("Unrecognized option \"%s\""), opt);
15887
15888   *input_line_pointer = c;
15889   demand_empty_rest_of_line ();
15890 }
15891
15892 /* This structure is used to hold a stack of .set values.  */
15893
15894 struct mips_option_stack
15895 {
15896   struct mips_option_stack *next;
15897   struct mips_set_options options;
15898 };
15899
15900 static struct mips_option_stack *mips_opts_stack;
15901
15902 /* Handle the .set pseudo-op.  */
15903
15904 static void
15905 s_mipsset (int x ATTRIBUTE_UNUSED)
15906 {
15907   char *name = input_line_pointer, ch;
15908
15909   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15910     ++input_line_pointer;
15911   ch = *input_line_pointer;
15912   *input_line_pointer = '\0';
15913
15914   if (strcmp (name, "reorder") == 0)
15915     {
15916       if (mips_opts.noreorder)
15917         end_noreorder ();
15918     }
15919   else if (strcmp (name, "noreorder") == 0)
15920     {
15921       if (!mips_opts.noreorder)
15922         start_noreorder ();
15923     }
15924   else if (strncmp (name, "at=", 3) == 0)
15925     {
15926       char *s = name + 3;
15927
15928       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15929         as_bad (_("Unrecognized register name `%s'"), s);
15930     }
15931   else if (strcmp (name, "at") == 0)
15932     {
15933       mips_opts.at = ATREG;
15934     }
15935   else if (strcmp (name, "noat") == 0)
15936     {
15937       mips_opts.at = ZERO;
15938     }
15939   else if (strcmp (name, "macro") == 0)
15940     {
15941       mips_opts.warn_about_macros = 0;
15942     }
15943   else if (strcmp (name, "nomacro") == 0)
15944     {
15945       if (mips_opts.noreorder == 0)
15946         as_bad (_("`noreorder' must be set before `nomacro'"));
15947       mips_opts.warn_about_macros = 1;
15948     }
15949   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15950     {
15951       mips_opts.nomove = 0;
15952     }
15953   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15954     {
15955       mips_opts.nomove = 1;
15956     }
15957   else if (strcmp (name, "bopt") == 0)
15958     {
15959       mips_opts.nobopt = 0;
15960     }
15961   else if (strcmp (name, "nobopt") == 0)
15962     {
15963       mips_opts.nobopt = 1;
15964     }
15965   else if (strcmp (name, "gp=default") == 0)
15966     mips_opts.gp32 = file_mips_gp32;
15967   else if (strcmp (name, "gp=32") == 0)
15968     mips_opts.gp32 = 1;
15969   else if (strcmp (name, "gp=64") == 0)
15970     {
15971       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
15972         as_warn (_("%s isa does not support 64-bit registers"),
15973                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15974       mips_opts.gp32 = 0;
15975     }
15976   else if (strcmp (name, "fp=default") == 0)
15977     mips_opts.fp32 = file_mips_fp32;
15978   else if (strcmp (name, "fp=32") == 0)
15979     mips_opts.fp32 = 1;
15980   else if (strcmp (name, "fp=64") == 0)
15981     {
15982       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15983         as_warn (_("%s isa does not support 64-bit floating point registers"),
15984                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15985       mips_opts.fp32 = 0;
15986     }
15987   else if (strcmp (name, "softfloat") == 0)
15988     mips_opts.soft_float = 1;
15989   else if (strcmp (name, "hardfloat") == 0)
15990     mips_opts.soft_float = 0;
15991   else if (strcmp (name, "singlefloat") == 0)
15992     mips_opts.single_float = 1;
15993   else if (strcmp (name, "doublefloat") == 0)
15994     mips_opts.single_float = 0;
15995   else if (strcmp (name, "mips16") == 0
15996            || strcmp (name, "MIPS-16") == 0)
15997     {
15998       if (mips_opts.micromips == 1)
15999         as_fatal (_("`mips16' cannot be used with `micromips'"));
16000       mips_opts.mips16 = 1;
16001     }
16002   else if (strcmp (name, "nomips16") == 0
16003            || strcmp (name, "noMIPS-16") == 0)
16004     mips_opts.mips16 = 0;
16005   else if (strcmp (name, "micromips") == 0)
16006     {
16007       if (mips_opts.mips16 == 1)
16008         as_fatal (_("`micromips' cannot be used with `mips16'"));
16009       mips_opts.micromips = 1;
16010     }
16011   else if (strcmp (name, "nomicromips") == 0)
16012     mips_opts.micromips = 0;
16013   else if (strcmp (name, "smartmips") == 0)
16014     {
16015       if (!ISA_SUPPORTS_SMARTMIPS)
16016         as_warn (_("%s ISA does not support SmartMIPS ASE"), 
16017                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16018       mips_opts.ase_smartmips = 1;
16019     }
16020   else if (strcmp (name, "nosmartmips") == 0)
16021     mips_opts.ase_smartmips = 0;
16022   else if (strcmp (name, "mips3d") == 0)
16023     mips_opts.ase_mips3d = 1;
16024   else if (strcmp (name, "nomips3d") == 0)
16025     mips_opts.ase_mips3d = 0;
16026   else if (strcmp (name, "mdmx") == 0)
16027     mips_opts.ase_mdmx = 1;
16028   else if (strcmp (name, "nomdmx") == 0)
16029     mips_opts.ase_mdmx = 0;
16030   else if (strcmp (name, "dsp") == 0)
16031     {
16032       if (!ISA_SUPPORTS_DSP_ASE)
16033         as_warn (_("%s ISA does not support DSP ASE"), 
16034                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16035       mips_opts.ase_dsp = 1;
16036       mips_opts.ase_dspr2 = 0;
16037     }
16038   else if (strcmp (name, "nodsp") == 0)
16039     {
16040       mips_opts.ase_dsp = 0;
16041       mips_opts.ase_dspr2 = 0;
16042     }
16043   else if (strcmp (name, "dspr2") == 0)
16044     {
16045       if (!ISA_SUPPORTS_DSPR2_ASE)
16046         as_warn (_("%s ISA does not support DSP R2 ASE"),
16047                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16048       mips_opts.ase_dspr2 = 1;
16049       mips_opts.ase_dsp = 1;
16050     }
16051   else if (strcmp (name, "nodspr2") == 0)
16052     {
16053       mips_opts.ase_dspr2 = 0;
16054       mips_opts.ase_dsp = 0;
16055     }
16056   else if (strcmp (name, "mt") == 0)
16057     {
16058       if (!ISA_SUPPORTS_MT_ASE)
16059         as_warn (_("%s ISA does not support MT ASE"), 
16060                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16061       mips_opts.ase_mt = 1;
16062     }
16063   else if (strcmp (name, "nomt") == 0)
16064     mips_opts.ase_mt = 0;
16065   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16066     {
16067       int reset = 0;
16068
16069       /* Permit the user to change the ISA and architecture on the fly.
16070          Needless to say, misuse can cause serious problems.  */
16071       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16072         {
16073           reset = 1;
16074           mips_opts.isa = file_mips_isa;
16075           mips_opts.arch = file_mips_arch;
16076         }
16077       else if (strncmp (name, "arch=", 5) == 0)
16078         {
16079           const struct mips_cpu_info *p;
16080
16081           p = mips_parse_cpu("internal use", name + 5);
16082           if (!p)
16083             as_bad (_("unknown architecture %s"), name + 5);
16084           else
16085             {
16086               mips_opts.arch = p->cpu;
16087               mips_opts.isa = p->isa;
16088             }
16089         }
16090       else if (strncmp (name, "mips", 4) == 0)
16091         {
16092           const struct mips_cpu_info *p;
16093
16094           p = mips_parse_cpu("internal use", name);
16095           if (!p)
16096             as_bad (_("unknown ISA level %s"), name + 4);
16097           else
16098             {
16099               mips_opts.arch = p->cpu;
16100               mips_opts.isa = p->isa;
16101             }
16102         }
16103       else
16104         as_bad (_("unknown ISA or architecture %s"), name);
16105
16106       switch (mips_opts.isa)
16107         {
16108         case  0:
16109           break;
16110         case ISA_MIPS1:
16111         case ISA_MIPS2:
16112         case ISA_MIPS32:
16113         case ISA_MIPS32R2:
16114           mips_opts.gp32 = 1;
16115           mips_opts.fp32 = 1;
16116           break;
16117         case ISA_MIPS3:
16118         case ISA_MIPS4:
16119         case ISA_MIPS5:
16120         case ISA_MIPS64:
16121         case ISA_MIPS64R2:
16122           mips_opts.gp32 = 0;
16123           mips_opts.fp32 = 0;
16124           break;
16125         default:
16126           as_bad (_("unknown ISA level %s"), name + 4);
16127           break;
16128         }
16129       if (reset)
16130         {
16131           mips_opts.gp32 = file_mips_gp32;
16132           mips_opts.fp32 = file_mips_fp32;
16133         }
16134     }
16135   else if (strcmp (name, "autoextend") == 0)
16136     mips_opts.noautoextend = 0;
16137   else if (strcmp (name, "noautoextend") == 0)
16138     mips_opts.noautoextend = 1;
16139   else if (strcmp (name, "push") == 0)
16140     {
16141       struct mips_option_stack *s;
16142
16143       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16144       s->next = mips_opts_stack;
16145       s->options = mips_opts;
16146       mips_opts_stack = s;
16147     }
16148   else if (strcmp (name, "pop") == 0)
16149     {
16150       struct mips_option_stack *s;
16151
16152       s = mips_opts_stack;
16153       if (s == NULL)
16154         as_bad (_(".set pop with no .set push"));
16155       else
16156         {
16157           /* If we're changing the reorder mode we need to handle
16158              delay slots correctly.  */
16159           if (s->options.noreorder && ! mips_opts.noreorder)
16160             start_noreorder ();
16161           else if (! s->options.noreorder && mips_opts.noreorder)
16162             end_noreorder ();
16163
16164           mips_opts = s->options;
16165           mips_opts_stack = s->next;
16166           free (s);
16167         }
16168     }
16169   else if (strcmp (name, "sym32") == 0)
16170     mips_opts.sym32 = TRUE;
16171   else if (strcmp (name, "nosym32") == 0)
16172     mips_opts.sym32 = FALSE;
16173   else if (strchr (name, ','))
16174     {
16175       /* Generic ".set" directive; use the generic handler.  */
16176       *input_line_pointer = ch;
16177       input_line_pointer = name;
16178       s_set (0);
16179       return;
16180     }
16181   else
16182     {
16183       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16184     }
16185   *input_line_pointer = ch;
16186   demand_empty_rest_of_line ();
16187 }
16188
16189 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16190    .option pic2.  It means to generate SVR4 PIC calls.  */
16191
16192 static void
16193 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16194 {
16195   mips_pic = SVR4_PIC;
16196   mips_abicalls = TRUE;
16197
16198   if (g_switch_seen && g_switch_value != 0)
16199     as_warn (_("-G may not be used with SVR4 PIC code"));
16200   g_switch_value = 0;
16201
16202   bfd_set_gp_size (stdoutput, 0);
16203   demand_empty_rest_of_line ();
16204 }
16205
16206 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16207    PIC code.  It sets the $gp register for the function based on the
16208    function address, which is in the register named in the argument.
16209    This uses a relocation against _gp_disp, which is handled specially
16210    by the linker.  The result is:
16211         lui     $gp,%hi(_gp_disp)
16212         addiu   $gp,$gp,%lo(_gp_disp)
16213         addu    $gp,$gp,.cpload argument
16214    The .cpload argument is normally $25 == $t9.
16215
16216    The -mno-shared option changes this to:
16217         lui     $gp,%hi(__gnu_local_gp)
16218         addiu   $gp,$gp,%lo(__gnu_local_gp)
16219    and the argument is ignored.  This saves an instruction, but the
16220    resulting code is not position independent; it uses an absolute
16221    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16222    can go into an ordinary executable, but not into a shared library.  */
16223
16224 static void
16225 s_cpload (int ignore ATTRIBUTE_UNUSED)
16226 {
16227   expressionS ex;
16228   int reg;
16229   int in_shared;
16230
16231   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16232      .cpload is ignored.  */
16233   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16234     {
16235       s_ignore (0);
16236       return;
16237     }
16238
16239   /* .cpload should be in a .set noreorder section.  */
16240   if (mips_opts.noreorder == 0)
16241     as_warn (_(".cpload not in noreorder section"));
16242
16243   reg = tc_get_register (0);
16244
16245   /* If we need to produce a 64-bit address, we are better off using
16246      the default instruction sequence.  */
16247   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16248
16249   ex.X_op = O_symbol;
16250   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16251                                          "__gnu_local_gp");
16252   ex.X_op_symbol = NULL;
16253   ex.X_add_number = 0;
16254
16255   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16256   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16257
16258   macro_start ();
16259   macro_build_lui (&ex, mips_gp_register);
16260   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16261                mips_gp_register, BFD_RELOC_LO16);
16262   if (in_shared)
16263     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16264                  mips_gp_register, reg);
16265   macro_end ();
16266
16267   demand_empty_rest_of_line ();
16268 }
16269
16270 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16271      .cpsetup $reg1, offset|$reg2, label
16272
16273    If offset is given, this results in:
16274      sd         $gp, offset($sp)
16275      lui        $gp, %hi(%neg(%gp_rel(label)))
16276      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16277      daddu      $gp, $gp, $reg1
16278
16279    If $reg2 is given, this results in:
16280      daddu      $reg2, $gp, $0
16281      lui        $gp, %hi(%neg(%gp_rel(label)))
16282      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16283      daddu      $gp, $gp, $reg1
16284    $reg1 is normally $25 == $t9.
16285
16286    The -mno-shared option replaces the last three instructions with
16287         lui     $gp,%hi(_gp)
16288         addiu   $gp,$gp,%lo(_gp)  */
16289
16290 static void
16291 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16292 {
16293   expressionS ex_off;
16294   expressionS ex_sym;
16295   int reg1;
16296
16297   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16298      We also need NewABI support.  */
16299   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16300     {
16301       s_ignore (0);
16302       return;
16303     }
16304
16305   reg1 = tc_get_register (0);
16306   SKIP_WHITESPACE ();
16307   if (*input_line_pointer != ',')
16308     {
16309       as_bad (_("missing argument separator ',' for .cpsetup"));
16310       return;
16311     }
16312   else
16313     ++input_line_pointer;
16314   SKIP_WHITESPACE ();
16315   if (*input_line_pointer == '$')
16316     {
16317       mips_cpreturn_register = tc_get_register (0);
16318       mips_cpreturn_offset = -1;
16319     }
16320   else
16321     {
16322       mips_cpreturn_offset = get_absolute_expression ();
16323       mips_cpreturn_register = -1;
16324     }
16325   SKIP_WHITESPACE ();
16326   if (*input_line_pointer != ',')
16327     {
16328       as_bad (_("missing argument separator ',' for .cpsetup"));
16329       return;
16330     }
16331   else
16332     ++input_line_pointer;
16333   SKIP_WHITESPACE ();
16334   expression (&ex_sym);
16335
16336   macro_start ();
16337   if (mips_cpreturn_register == -1)
16338     {
16339       ex_off.X_op = O_constant;
16340       ex_off.X_add_symbol = NULL;
16341       ex_off.X_op_symbol = NULL;
16342       ex_off.X_add_number = mips_cpreturn_offset;
16343
16344       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16345                    BFD_RELOC_LO16, SP);
16346     }
16347   else
16348     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16349                  mips_gp_register, 0);
16350
16351   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16352     {
16353       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16354                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16355                    BFD_RELOC_HI16_S);
16356
16357       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16358                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16359                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16360
16361       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16362                    mips_gp_register, reg1);
16363     }
16364   else
16365     {
16366       expressionS ex;
16367
16368       ex.X_op = O_symbol;
16369       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16370       ex.X_op_symbol = NULL;
16371       ex.X_add_number = 0;
16372
16373       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16374       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16375
16376       macro_build_lui (&ex, mips_gp_register);
16377       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16378                    mips_gp_register, BFD_RELOC_LO16);
16379     }
16380
16381   macro_end ();
16382
16383   demand_empty_rest_of_line ();
16384 }
16385
16386 static void
16387 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16388 {
16389   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16390      .cplocal is ignored.  */
16391   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16392     {
16393       s_ignore (0);
16394       return;
16395     }
16396
16397   mips_gp_register = tc_get_register (0);
16398   demand_empty_rest_of_line ();
16399 }
16400
16401 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16402    offset from $sp.  The offset is remembered, and after making a PIC
16403    call $gp is restored from that location.  */
16404
16405 static void
16406 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16407 {
16408   expressionS ex;
16409
16410   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16411      .cprestore is ignored.  */
16412   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16413     {
16414       s_ignore (0);
16415       return;
16416     }
16417
16418   mips_cprestore_offset = get_absolute_expression ();
16419   mips_cprestore_valid = 1;
16420
16421   ex.X_op = O_constant;
16422   ex.X_add_symbol = NULL;
16423   ex.X_op_symbol = NULL;
16424   ex.X_add_number = mips_cprestore_offset;
16425
16426   macro_start ();
16427   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16428                                 SP, HAVE_64BIT_ADDRESSES);
16429   macro_end ();
16430
16431   demand_empty_rest_of_line ();
16432 }
16433
16434 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16435    was given in the preceding .cpsetup, it results in:
16436      ld         $gp, offset($sp)
16437
16438    If a register $reg2 was given there, it results in:
16439      daddu      $gp, $reg2, $0  */
16440
16441 static void
16442 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16443 {
16444   expressionS ex;
16445
16446   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16447      We also need NewABI support.  */
16448   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16449     {
16450       s_ignore (0);
16451       return;
16452     }
16453
16454   macro_start ();
16455   if (mips_cpreturn_register == -1)
16456     {
16457       ex.X_op = O_constant;
16458       ex.X_add_symbol = NULL;
16459       ex.X_op_symbol = NULL;
16460       ex.X_add_number = mips_cpreturn_offset;
16461
16462       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16463     }
16464   else
16465     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
16466                  mips_cpreturn_register, 0);
16467   macro_end ();
16468
16469   demand_empty_rest_of_line ();
16470 }
16471
16472 /* Handle the .dtprelword and .dtpreldword pseudo-ops.  They generate
16473    a 32-bit or 64-bit DTP-relative relocation (BYTES says which) for
16474    use in DWARF debug information.  */
16475
16476 static void
16477 s_dtprel_internal (size_t bytes)
16478 {
16479   expressionS ex;
16480   char *p;
16481
16482   expression (&ex);
16483
16484   if (ex.X_op != O_symbol)
16485     {
16486       as_bad (_("Unsupported use of %s"), (bytes == 8
16487                                            ? ".dtpreldword"
16488                                            : ".dtprelword"));
16489       ignore_rest_of_line ();
16490     }
16491
16492   p = frag_more (bytes);
16493   md_number_to_chars (p, 0, bytes);
16494   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE,
16495                (bytes == 8
16496                 ? BFD_RELOC_MIPS_TLS_DTPREL64
16497                 : BFD_RELOC_MIPS_TLS_DTPREL32));
16498
16499   demand_empty_rest_of_line ();
16500 }
16501
16502 /* Handle .dtprelword.  */
16503
16504 static void
16505 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16506 {
16507   s_dtprel_internal (4);
16508 }
16509
16510 /* Handle .dtpreldword.  */
16511
16512 static void
16513 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16514 {
16515   s_dtprel_internal (8);
16516 }
16517
16518 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16519    code.  It sets the offset to use in gp_rel relocations.  */
16520
16521 static void
16522 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16523 {
16524   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16525      We also need NewABI support.  */
16526   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16527     {
16528       s_ignore (0);
16529       return;
16530     }
16531
16532   mips_gprel_offset = get_absolute_expression ();
16533
16534   demand_empty_rest_of_line ();
16535 }
16536
16537 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16538    code.  It generates a 32 bit GP relative reloc.  */
16539
16540 static void
16541 s_gpword (int ignore ATTRIBUTE_UNUSED)
16542 {
16543   segment_info_type *si;
16544   struct insn_label_list *l;
16545   symbolS *label;
16546   expressionS ex;
16547   char *p;
16548
16549   /* When not generating PIC code, this is treated as .word.  */
16550   if (mips_pic != SVR4_PIC)
16551     {
16552       s_cons (2);
16553       return;
16554     }
16555
16556   si = seg_info (now_seg);
16557   l = si->label_list;
16558   label = l != NULL ? l->label : NULL;
16559   mips_emit_delays ();
16560   if (auto_align)
16561     mips_align (2, 0, label);
16562
16563   expression (&ex);
16564   mips_clear_insn_labels ();
16565
16566   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16567     {
16568       as_bad (_("Unsupported use of .gpword"));
16569       ignore_rest_of_line ();
16570     }
16571
16572   p = frag_more (4);
16573   md_number_to_chars (p, 0, 4);
16574   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16575                BFD_RELOC_GPREL32);
16576
16577   demand_empty_rest_of_line ();
16578 }
16579
16580 static void
16581 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16582 {
16583   segment_info_type *si;
16584   struct insn_label_list *l;
16585   symbolS *label;
16586   expressionS ex;
16587   char *p;
16588
16589   /* When not generating PIC code, this is treated as .dword.  */
16590   if (mips_pic != SVR4_PIC)
16591     {
16592       s_cons (3);
16593       return;
16594     }
16595
16596   si = seg_info (now_seg);
16597   l = si->label_list;
16598   label = l != NULL ? l->label : NULL;
16599   mips_emit_delays ();
16600   if (auto_align)
16601     mips_align (3, 0, label);
16602
16603   expression (&ex);
16604   mips_clear_insn_labels ();
16605
16606   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16607     {
16608       as_bad (_("Unsupported use of .gpdword"));
16609       ignore_rest_of_line ();
16610     }
16611
16612   p = frag_more (8);
16613   md_number_to_chars (p, 0, 8);
16614   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16615                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16616
16617   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16618   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16619            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16620
16621   demand_empty_rest_of_line ();
16622 }
16623
16624 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16625    tables in SVR4 PIC code.  */
16626
16627 static void
16628 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16629 {
16630   int reg;
16631
16632   /* This is ignored when not generating SVR4 PIC code.  */
16633   if (mips_pic != SVR4_PIC)
16634     {
16635       s_ignore (0);
16636       return;
16637     }
16638
16639   /* Add $gp to the register named as an argument.  */
16640   macro_start ();
16641   reg = tc_get_register (0);
16642   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16643   macro_end ();
16644
16645   demand_empty_rest_of_line ();
16646 }
16647
16648 /* Handle the .insn pseudo-op.  This marks instruction labels in
16649    mips16/micromips mode.  This permits the linker to handle them specially,
16650    such as generating jalx instructions when needed.  We also make
16651    them odd for the duration of the assembly, in order to generate the
16652    right sort of code.  We will make them even in the adjust_symtab
16653    routine, while leaving them marked.  This is convenient for the
16654    debugger and the disassembler.  The linker knows to make them odd
16655    again.  */
16656
16657 static void
16658 s_insn (int ignore ATTRIBUTE_UNUSED)
16659 {
16660   mips_mark_labels ();
16661
16662   demand_empty_rest_of_line ();
16663 }
16664
16665 /* Handle a .stabn directive.  We need these in order to mark a label
16666    as being a mips16 text label correctly.  Sometimes the compiler
16667    will emit a label, followed by a .stabn, and then switch sections.
16668    If the label and .stabn are in mips16 mode, then the label is
16669    really a mips16 text label.  */
16670
16671 static void
16672 s_mips_stab (int type)
16673 {
16674   if (type == 'n')
16675     mips_mark_labels ();
16676
16677   s_stab (type);
16678 }
16679
16680 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16681
16682 static void
16683 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16684 {
16685   char *name;
16686   int c;
16687   symbolS *symbolP;
16688   expressionS exp;
16689
16690   name = input_line_pointer;
16691   c = get_symbol_end ();
16692   symbolP = symbol_find_or_make (name);
16693   S_SET_WEAK (symbolP);
16694   *input_line_pointer = c;
16695
16696   SKIP_WHITESPACE ();
16697
16698   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16699     {
16700       if (S_IS_DEFINED (symbolP))
16701         {
16702           as_bad (_("ignoring attempt to redefine symbol %s"),
16703                   S_GET_NAME (symbolP));
16704           ignore_rest_of_line ();
16705           return;
16706         }
16707
16708       if (*input_line_pointer == ',')
16709         {
16710           ++input_line_pointer;
16711           SKIP_WHITESPACE ();
16712         }
16713
16714       expression (&exp);
16715       if (exp.X_op != O_symbol)
16716         {
16717           as_bad (_("bad .weakext directive"));
16718           ignore_rest_of_line ();
16719           return;
16720         }
16721       symbol_set_value_expression (symbolP, &exp);
16722     }
16723
16724   demand_empty_rest_of_line ();
16725 }
16726
16727 /* Parse a register string into a number.  Called from the ECOFF code
16728    to parse .frame.  The argument is non-zero if this is the frame
16729    register, so that we can record it in mips_frame_reg.  */
16730
16731 int
16732 tc_get_register (int frame)
16733 {
16734   unsigned int reg;
16735
16736   SKIP_WHITESPACE ();
16737   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16738     reg = 0;
16739   if (frame)
16740     {
16741       mips_frame_reg = reg != 0 ? reg : SP;
16742       mips_frame_reg_valid = 1;
16743       mips_cprestore_valid = 0;
16744     }
16745   return reg;
16746 }
16747
16748 valueT
16749 md_section_align (asection *seg, valueT addr)
16750 {
16751   int align = bfd_get_section_alignment (stdoutput, seg);
16752
16753   if (IS_ELF)
16754     {
16755       /* We don't need to align ELF sections to the full alignment.
16756          However, Irix 5 may prefer that we align them at least to a 16
16757          byte boundary.  We don't bother to align the sections if we
16758          are targeted for an embedded system.  */
16759       if (strncmp (TARGET_OS, "elf", 3) == 0)
16760         return addr;
16761       if (align > 4)
16762         align = 4;
16763     }
16764
16765   return ((addr + (1 << align) - 1) & (-1 << align));
16766 }
16767
16768 /* Utility routine, called from above as well.  If called while the
16769    input file is still being read, it's only an approximation.  (For
16770    example, a symbol may later become defined which appeared to be
16771    undefined earlier.)  */
16772
16773 static int
16774 nopic_need_relax (symbolS *sym, int before_relaxing)
16775 {
16776   if (sym == 0)
16777     return 0;
16778
16779   if (g_switch_value > 0)
16780     {
16781       const char *symname;
16782       int change;
16783
16784       /* Find out whether this symbol can be referenced off the $gp
16785          register.  It can be if it is smaller than the -G size or if
16786          it is in the .sdata or .sbss section.  Certain symbols can
16787          not be referenced off the $gp, although it appears as though
16788          they can.  */
16789       symname = S_GET_NAME (sym);
16790       if (symname != (const char *) NULL
16791           && (strcmp (symname, "eprol") == 0
16792               || strcmp (symname, "etext") == 0
16793               || strcmp (symname, "_gp") == 0
16794               || strcmp (symname, "edata") == 0
16795               || strcmp (symname, "_fbss") == 0
16796               || strcmp (symname, "_fdata") == 0
16797               || strcmp (symname, "_ftext") == 0
16798               || strcmp (symname, "end") == 0
16799               || strcmp (symname, "_gp_disp") == 0))
16800         change = 1;
16801       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16802                && (0
16803 #ifndef NO_ECOFF_DEBUGGING
16804                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16805                        && (symbol_get_obj (sym)->ecoff_extern_size
16806                            <= g_switch_value))
16807 #endif
16808                    /* We must defer this decision until after the whole
16809                       file has been read, since there might be a .extern
16810                       after the first use of this symbol.  */
16811                    || (before_relaxing
16812 #ifndef NO_ECOFF_DEBUGGING
16813                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16814 #endif
16815                        && S_GET_VALUE (sym) == 0)
16816                    || (S_GET_VALUE (sym) != 0
16817                        && S_GET_VALUE (sym) <= g_switch_value)))
16818         change = 0;
16819       else
16820         {
16821           const char *segname;
16822
16823           segname = segment_name (S_GET_SEGMENT (sym));
16824           gas_assert (strcmp (segname, ".lit8") != 0
16825                   && strcmp (segname, ".lit4") != 0);
16826           change = (strcmp (segname, ".sdata") != 0
16827                     && strcmp (segname, ".sbss") != 0
16828                     && strncmp (segname, ".sdata.", 7) != 0
16829                     && strncmp (segname, ".sbss.", 6) != 0
16830                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16831                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16832         }
16833       return change;
16834     }
16835   else
16836     /* We are not optimizing for the $gp register.  */
16837     return 1;
16838 }
16839
16840
16841 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16842
16843 static bfd_boolean
16844 pic_need_relax (symbolS *sym, asection *segtype)
16845 {
16846   asection *symsec;
16847
16848   /* Handle the case of a symbol equated to another symbol.  */
16849   while (symbol_equated_reloc_p (sym))
16850     {
16851       symbolS *n;
16852
16853       /* It's possible to get a loop here in a badly written program.  */
16854       n = symbol_get_value_expression (sym)->X_add_symbol;
16855       if (n == sym)
16856         break;
16857       sym = n;
16858     }
16859
16860   if (symbol_section_p (sym))
16861     return TRUE;
16862
16863   symsec = S_GET_SEGMENT (sym);
16864
16865   /* This must duplicate the test in adjust_reloc_syms.  */
16866   return (symsec != &bfd_und_section
16867           && symsec != &bfd_abs_section
16868           && !bfd_is_com_section (symsec)
16869           && !s_is_linkonce (sym, segtype)
16870 #ifdef OBJ_ELF
16871           /* A global or weak symbol is treated as external.  */
16872           && (!IS_ELF || (! S_IS_WEAK (sym) && ! S_IS_EXTERNAL (sym)))
16873 #endif
16874           );
16875 }
16876
16877
16878 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16879    extended opcode.  SEC is the section the frag is in.  */
16880
16881 static int
16882 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16883 {
16884   int type;
16885   const struct mips16_immed_operand *op;
16886   offsetT val;
16887   int mintiny, maxtiny;
16888   segT symsec;
16889   fragS *sym_frag;
16890
16891   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16892     return 0;
16893   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16894     return 1;
16895
16896   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16897   op = mips16_immed_operands;
16898   while (op->type != type)
16899     {
16900       ++op;
16901       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
16902     }
16903
16904   if (op->unsp)
16905     {
16906       if (type == '<' || type == '>' || type == '[' || type == ']')
16907         {
16908           mintiny = 1;
16909           maxtiny = 1 << op->nbits;
16910         }
16911       else
16912         {
16913           mintiny = 0;
16914           maxtiny = (1 << op->nbits) - 1;
16915         }
16916     }
16917   else
16918     {
16919       mintiny = - (1 << (op->nbits - 1));
16920       maxtiny = (1 << (op->nbits - 1)) - 1;
16921     }
16922
16923   sym_frag = symbol_get_frag (fragp->fr_symbol);
16924   val = S_GET_VALUE (fragp->fr_symbol);
16925   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16926
16927   if (op->pcrel)
16928     {
16929       addressT addr;
16930
16931       /* We won't have the section when we are called from
16932          mips_relax_frag.  However, we will always have been called
16933          from md_estimate_size_before_relax first.  If this is a
16934          branch to a different section, we mark it as such.  If SEC is
16935          NULL, and the frag is not marked, then it must be a branch to
16936          the same section.  */
16937       if (sec == NULL)
16938         {
16939           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16940             return 1;
16941         }
16942       else
16943         {
16944           /* Must have been called from md_estimate_size_before_relax.  */
16945           if (symsec != sec)
16946             {
16947               fragp->fr_subtype =
16948                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16949
16950               /* FIXME: We should support this, and let the linker
16951                  catch branches and loads that are out of range.  */
16952               as_bad_where (fragp->fr_file, fragp->fr_line,
16953                             _("unsupported PC relative reference to different section"));
16954
16955               return 1;
16956             }
16957           if (fragp != sym_frag && sym_frag->fr_address == 0)
16958             /* Assume non-extended on the first relaxation pass.
16959                The address we have calculated will be bogus if this is
16960                a forward branch to another frag, as the forward frag
16961                will have fr_address == 0.  */
16962             return 0;
16963         }
16964
16965       /* In this case, we know for sure that the symbol fragment is in
16966          the same section.  If the relax_marker of the symbol fragment
16967          differs from the relax_marker of this fragment, we have not
16968          yet adjusted the symbol fragment fr_address.  We want to add
16969          in STRETCH in order to get a better estimate of the address.
16970          This particularly matters because of the shift bits.  */
16971       if (stretch != 0
16972           && sym_frag->relax_marker != fragp->relax_marker)
16973         {
16974           fragS *f;
16975
16976           /* Adjust stretch for any alignment frag.  Note that if have
16977              been expanding the earlier code, the symbol may be
16978              defined in what appears to be an earlier frag.  FIXME:
16979              This doesn't handle the fr_subtype field, which specifies
16980              a maximum number of bytes to skip when doing an
16981              alignment.  */
16982           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16983             {
16984               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16985                 {
16986                   if (stretch < 0)
16987                     stretch = - ((- stretch)
16988                                  & ~ ((1 << (int) f->fr_offset) - 1));
16989                   else
16990                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16991                   if (stretch == 0)
16992                     break;
16993                 }
16994             }
16995           if (f != NULL)
16996             val += stretch;
16997         }
16998
16999       addr = fragp->fr_address + fragp->fr_fix;
17000
17001       /* The base address rules are complicated.  The base address of
17002          a branch is the following instruction.  The base address of a
17003          PC relative load or add is the instruction itself, but if it
17004          is in a delay slot (in which case it can not be extended) use
17005          the address of the instruction whose delay slot it is in.  */
17006       if (type == 'p' || type == 'q')
17007         {
17008           addr += 2;
17009
17010           /* If we are currently assuming that this frag should be
17011              extended, then, the current address is two bytes
17012              higher.  */
17013           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17014             addr += 2;
17015
17016           /* Ignore the low bit in the target, since it will be set
17017              for a text label.  */
17018           if ((val & 1) != 0)
17019             --val;
17020         }
17021       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17022         addr -= 4;
17023       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17024         addr -= 2;
17025
17026       val -= addr & ~ ((1 << op->shift) - 1);
17027
17028       /* Branch offsets have an implicit 0 in the lowest bit.  */
17029       if (type == 'p' || type == 'q')
17030         val /= 2;
17031
17032       /* If any of the shifted bits are set, we must use an extended
17033          opcode.  If the address depends on the size of this
17034          instruction, this can lead to a loop, so we arrange to always
17035          use an extended opcode.  We only check this when we are in
17036          the main relaxation loop, when SEC is NULL.  */
17037       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17038         {
17039           fragp->fr_subtype =
17040             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17041           return 1;
17042         }
17043
17044       /* If we are about to mark a frag as extended because the value
17045          is precisely maxtiny + 1, then there is a chance of an
17046          infinite loop as in the following code:
17047              la $4,foo
17048              .skip      1020
17049              .align     2
17050            foo:
17051          In this case when the la is extended, foo is 0x3fc bytes
17052          away, so the la can be shrunk, but then foo is 0x400 away, so
17053          the la must be extended.  To avoid this loop, we mark the
17054          frag as extended if it was small, and is about to become
17055          extended with a value of maxtiny + 1.  */
17056       if (val == ((maxtiny + 1) << op->shift)
17057           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17058           && sec == NULL)
17059         {
17060           fragp->fr_subtype =
17061             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17062           return 1;
17063         }
17064     }
17065   else if (symsec != absolute_section && sec != NULL)
17066     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17067
17068   if ((val & ((1 << op->shift) - 1)) != 0
17069       || val < (mintiny << op->shift)
17070       || val > (maxtiny << op->shift))
17071     return 1;
17072   else
17073     return 0;
17074 }
17075
17076 /* Compute the length of a branch sequence, and adjust the
17077    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17078    worst-case length is computed, with UPDATE being used to indicate
17079    whether an unconditional (-1), branch-likely (+1) or regular (0)
17080    branch is to be computed.  */
17081 static int
17082 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17083 {
17084   bfd_boolean toofar;
17085   int length;
17086
17087   if (fragp
17088       && S_IS_DEFINED (fragp->fr_symbol)
17089       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17090     {
17091       addressT addr;
17092       offsetT val;
17093
17094       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17095
17096       addr = fragp->fr_address + fragp->fr_fix + 4;
17097
17098       val -= addr;
17099
17100       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17101     }
17102   else if (fragp)
17103     /* If the symbol is not defined or it's in a different segment,
17104        assume the user knows what's going on and emit a short
17105        branch.  */
17106     toofar = FALSE;
17107   else
17108     toofar = TRUE;
17109
17110   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17111     fragp->fr_subtype
17112       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17113                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17114                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17115                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17116                              toofar);
17117
17118   length = 4;
17119   if (toofar)
17120     {
17121       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17122         length += 8;
17123
17124       if (mips_pic != NO_PIC)
17125         {
17126           /* Additional space for PIC loading of target address.  */
17127           length += 8;
17128           if (mips_opts.isa == ISA_MIPS1)
17129             /* Additional space for $at-stabilizing nop.  */
17130             length += 4;
17131         }
17132
17133       /* If branch is conditional.  */
17134       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17135         length += 8;
17136     }
17137
17138   return length;
17139 }
17140
17141 /* Compute the length of a branch sequence, and adjust the
17142    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17143    worst-case length is computed, with UPDATE being used to indicate
17144    whether an unconditional (-1), or regular (0) branch is to be
17145    computed.  */
17146
17147 static int
17148 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17149 {
17150   bfd_boolean toofar;
17151   int length;
17152
17153   if (fragp
17154       && S_IS_DEFINED (fragp->fr_symbol)
17155       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17156     {
17157       addressT addr;
17158       offsetT val;
17159
17160       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17161       /* Ignore the low bit in the target, since it will be set
17162          for a text label.  */
17163       if ((val & 1) != 0)
17164         --val;
17165
17166       addr = fragp->fr_address + fragp->fr_fix + 4;
17167
17168       val -= addr;
17169
17170       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17171     }
17172   else if (fragp)
17173     /* If the symbol is not defined or it's in a different segment,
17174        assume the user knows what's going on and emit a short
17175        branch.  */
17176     toofar = FALSE;
17177   else
17178     toofar = TRUE;
17179
17180   if (fragp && update
17181       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17182     fragp->fr_subtype = (toofar
17183                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17184                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17185
17186   length = 4;
17187   if (toofar)
17188     {
17189       bfd_boolean compact_known = fragp != NULL;
17190       bfd_boolean compact = FALSE;
17191       bfd_boolean uncond;
17192
17193       if (compact_known)
17194         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17195       if (fragp)
17196         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17197       else
17198         uncond = update < 0;
17199
17200       /* If label is out of range, we turn branch <br>:
17201
17202                 <br>    label                   # 4 bytes
17203             0:
17204
17205          into:
17206
17207                 j       label                   # 4 bytes
17208                 nop                             # 2 bytes if compact && !PIC
17209             0:
17210        */
17211       if (mips_pic == NO_PIC && (!compact_known || compact))
17212         length += 2;
17213
17214       /* If assembling PIC code, we further turn:
17215
17216                         j       label                   # 4 bytes
17217
17218          into:
17219
17220                         lw/ld   at, %got(label)(gp)     # 4 bytes
17221                         d/addiu at, %lo(label)          # 4 bytes
17222                         jr/c    at                      # 2 bytes
17223        */
17224       if (mips_pic != NO_PIC)
17225         length += 6;
17226
17227       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17228
17229                         <brneg> 0f                      # 4 bytes
17230                         nop                             # 2 bytes if !compact
17231        */
17232       if (!uncond)
17233         length += (compact_known && compact) ? 4 : 6;
17234     }
17235
17236   return length;
17237 }
17238
17239 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17240    bit accordingly.  */
17241
17242 static int
17243 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17244 {
17245   bfd_boolean toofar;
17246
17247   if (RELAX_MICROMIPS_U16BIT (fragp->fr_subtype))
17248     return 2;
17249
17250   if (fragp
17251       && S_IS_DEFINED (fragp->fr_symbol)
17252       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17253     {
17254       addressT addr;
17255       offsetT val;
17256       int type;
17257
17258       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17259       /* Ignore the low bit in the target, since it will be set
17260          for a text label.  */
17261       if ((val & 1) != 0)
17262         --val;
17263
17264       /* Assume this is a 2-byte branch.  */
17265       addr = fragp->fr_address + fragp->fr_fix + 2;
17266
17267       /* We try to avoid the infinite loop by not adding 2 more bytes for
17268          long branches.  */
17269
17270       val -= addr;
17271
17272       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17273       if (type == 'D')
17274         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17275       else if (type == 'E')
17276         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17277       else
17278         abort ();
17279     }
17280   else
17281     /* If the symbol is not defined or it's in a different segment,
17282        we emit a normal 32-bit branch.  */
17283     toofar = TRUE;
17284
17285   if (fragp && update
17286       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17287     fragp->fr_subtype
17288       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17289                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17290
17291   if (toofar)
17292     return 4;
17293
17294   return 2;
17295 }
17296
17297 /* Estimate the size of a frag before relaxing.  Unless this is the
17298    mips16, we are not really relaxing here, and the final size is
17299    encoded in the subtype information.  For the mips16, we have to
17300    decide whether we are using an extended opcode or not.  */
17301
17302 int
17303 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17304 {
17305   int change;
17306
17307   if (RELAX_BRANCH_P (fragp->fr_subtype))
17308     {
17309
17310       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17311
17312       return fragp->fr_var;
17313     }
17314
17315   if (RELAX_MIPS16_P (fragp->fr_subtype))
17316     /* We don't want to modify the EXTENDED bit here; it might get us
17317        into infinite loops.  We change it only in mips_relax_frag().  */
17318     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17319
17320   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17321     {
17322       int length = 4;
17323
17324       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17325         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17326       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17327         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17328       fragp->fr_var = length;
17329
17330       return length;
17331     }
17332
17333   if (mips_pic == NO_PIC)
17334     change = nopic_need_relax (fragp->fr_symbol, 0);
17335   else if (mips_pic == SVR4_PIC)
17336     change = pic_need_relax (fragp->fr_symbol, segtype);
17337   else if (mips_pic == VXWORKS_PIC)
17338     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17339     change = 0;
17340   else
17341     abort ();
17342
17343   if (change)
17344     {
17345       fragp->fr_subtype |= RELAX_USE_SECOND;
17346       return -RELAX_FIRST (fragp->fr_subtype);
17347     }
17348   else
17349     return -RELAX_SECOND (fragp->fr_subtype);
17350 }
17351
17352 /* This is called to see whether a reloc against a defined symbol
17353    should be converted into a reloc against a section.  */
17354
17355 int
17356 mips_fix_adjustable (fixS *fixp)
17357 {
17358   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17359       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17360     return 0;
17361
17362   if (fixp->fx_addsy == NULL)
17363     return 1;
17364
17365   /* If symbol SYM is in a mergeable section, relocations of the form
17366      SYM + 0 can usually be made section-relative.  The mergeable data
17367      is then identified by the section offset rather than by the symbol.
17368
17369      However, if we're generating REL LO16 relocations, the offset is split
17370      between the LO16 and parterning high part relocation.  The linker will
17371      need to recalculate the complete offset in order to correctly identify
17372      the merge data.
17373
17374      The linker has traditionally not looked for the parterning high part
17375      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17376      placed anywhere.  Rather than break backwards compatibility by changing
17377      this, it seems better not to force the issue, and instead keep the
17378      original symbol.  This will work with either linker behavior.  */
17379   if ((lo16_reloc_p (fixp->fx_r_type)
17380        || reloc_needs_lo_p (fixp->fx_r_type))
17381       && HAVE_IN_PLACE_ADDENDS
17382       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17383     return 0;
17384
17385   /* There is no place to store an in-place offset for JALR relocations.
17386      Likewise an in-range offset of PC-relative relocations may overflow
17387      the in-place relocatable field if recalculated against the start
17388      address of the symbol's containing section.  */
17389   if (HAVE_IN_PLACE_ADDENDS
17390       && (fixp->fx_pcrel || jalr_reloc_p (fixp->fx_r_type)))
17391     return 0;
17392
17393 #ifdef OBJ_ELF
17394   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17395      to a floating-point stub.  The same is true for non-R_MIPS16_26
17396      relocations against MIPS16 functions; in this case, the stub becomes
17397      the function's canonical address.
17398
17399      Floating-point stubs are stored in unique .mips16.call.* or
17400      .mips16.fn.* sections.  If a stub T for function F is in section S,
17401      the first relocation in section S must be against F; this is how the
17402      linker determines the target function.  All relocations that might
17403      resolve to T must also be against F.  We therefore have the following
17404      restrictions, which are given in an intentionally-redundant way:
17405
17406        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17407           symbols.
17408
17409        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17410           if that stub might be used.
17411
17412        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17413           symbols.
17414
17415        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17416           that stub might be used.
17417
17418      There is a further restriction:
17419
17420        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17421           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
17422           targets with in-place addends; the relocation field cannot
17423           encode the low bit.
17424
17425      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17426      against a MIPS16 symbol.  We deal with (5) by by not reducing any
17427      such relocations on REL targets.
17428
17429      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17430      relocation against some symbol R, no relocation against R may be
17431      reduced.  (Note that this deals with (2) as well as (1) because
17432      relocations against global symbols will never be reduced on ELF
17433      targets.)  This approach is a little simpler than trying to detect
17434      stub sections, and gives the "all or nothing" per-symbol consistency
17435      that we have for MIPS16 symbols.  */
17436   if (IS_ELF
17437       && fixp->fx_subsy == NULL
17438       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17439           || *symbol_get_tc (fixp->fx_addsy)
17440           || (HAVE_IN_PLACE_ADDENDS
17441               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17442               && jmp_reloc_p (fixp->fx_r_type))))
17443     return 0;
17444 #endif
17445
17446   return 1;
17447 }
17448
17449 /* Translate internal representation of relocation info to BFD target
17450    format.  */
17451
17452 arelent **
17453 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17454 {
17455   static arelent *retval[4];
17456   arelent *reloc;
17457   bfd_reloc_code_real_type code;
17458
17459   memset (retval, 0, sizeof(retval));
17460   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
17461   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
17462   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17463   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17464
17465   if (fixp->fx_pcrel)
17466     {
17467       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17468                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17469                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17470                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1);
17471
17472       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17473          Relocations want only the symbol offset.  */
17474       reloc->addend = fixp->fx_addnumber + reloc->address;
17475       if (!IS_ELF)
17476         {
17477           /* A gruesome hack which is a result of the gruesome gas
17478              reloc handling.  What's worse, for COFF (as opposed to
17479              ECOFF), we might need yet another copy of reloc->address.
17480              See bfd_install_relocation.  */
17481           reloc->addend += reloc->address;
17482         }
17483     }
17484   else
17485     reloc->addend = fixp->fx_addnumber;
17486
17487   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17488      entry to be used in the relocation's section offset.  */
17489   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17490     {
17491       reloc->address = reloc->addend;
17492       reloc->addend = 0;
17493     }
17494
17495   code = fixp->fx_r_type;
17496
17497   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17498   if (reloc->howto == NULL)
17499     {
17500       as_bad_where (fixp->fx_file, fixp->fx_line,
17501                     _("Can not represent %s relocation in this object file format"),
17502                     bfd_get_reloc_code_name (code));
17503       retval[0] = NULL;
17504     }
17505
17506   return retval;
17507 }
17508
17509 /* Relax a machine dependent frag.  This returns the amount by which
17510    the current size of the frag should change.  */
17511
17512 int
17513 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17514 {
17515   if (RELAX_BRANCH_P (fragp->fr_subtype))
17516     {
17517       offsetT old_var = fragp->fr_var;
17518
17519       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17520
17521       return fragp->fr_var - old_var;
17522     }
17523
17524   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17525     {
17526       offsetT old_var = fragp->fr_var;
17527       offsetT new_var = 4;
17528
17529       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17530         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17531       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17532         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17533       fragp->fr_var = new_var;
17534
17535       return new_var - old_var;
17536     }
17537
17538   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17539     return 0;
17540
17541   if (mips16_extended_frag (fragp, NULL, stretch))
17542     {
17543       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17544         return 0;
17545       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17546       return 2;
17547     }
17548   else
17549     {
17550       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17551         return 0;
17552       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17553       return -2;
17554     }
17555
17556   return 0;
17557 }
17558
17559 /* Convert a machine dependent frag.  */
17560
17561 void
17562 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17563 {
17564   if (RELAX_BRANCH_P (fragp->fr_subtype))
17565     {
17566       bfd_byte *buf;
17567       unsigned long insn;
17568       expressionS exp;
17569       fixS *fixp;
17570
17571       buf = (bfd_byte *)fragp->fr_literal + fragp->fr_fix;
17572
17573       if (target_big_endian)
17574         insn = bfd_getb32 (buf);
17575       else
17576         insn = bfd_getl32 (buf);
17577
17578       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17579         {
17580           /* We generate a fixup instead of applying it right now
17581              because, if there are linker relaxations, we're going to
17582              need the relocations.  */
17583           exp.X_op = O_symbol;
17584           exp.X_add_symbol = fragp->fr_symbol;
17585           exp.X_add_number = fragp->fr_offset;
17586
17587           fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17588                               4, &exp, TRUE, BFD_RELOC_16_PCREL_S2);
17589           fixp->fx_file = fragp->fr_file;
17590           fixp->fx_line = fragp->fr_line;
17591
17592           md_number_to_chars ((char *) buf, insn, 4);
17593           buf += 4;
17594         }
17595       else
17596         {
17597           int i;
17598
17599           as_warn_where (fragp->fr_file, fragp->fr_line,
17600                          _("Relaxed out-of-range branch into a jump"));
17601
17602           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17603             goto uncond;
17604
17605           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17606             {
17607               /* Reverse the branch.  */
17608               switch ((insn >> 28) & 0xf)
17609                 {
17610                 case 4:
17611                   /* bc[0-3][tf]l? and bc1any[24][ft] instructions can
17612                      have the condition reversed by tweaking a single
17613                      bit, and their opcodes all have 0x4???????.  */
17614                   gas_assert ((insn & 0xf1000000) == 0x41000000);
17615                   insn ^= 0x00010000;
17616                   break;
17617
17618                 case 0:
17619                   /* bltz       0x04000000      bgez    0x04010000
17620                      bltzal     0x04100000      bgezal  0x04110000  */
17621                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17622                   insn ^= 0x00010000;
17623                   break;
17624
17625                 case 1:
17626                   /* beq        0x10000000      bne     0x14000000
17627                      blez       0x18000000      bgtz    0x1c000000  */
17628                   insn ^= 0x04000000;
17629                   break;
17630
17631                 default:
17632                   abort ();
17633                 }
17634             }
17635
17636           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17637             {
17638               /* Clear the and-link bit.  */
17639               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17640
17641               /* bltzal         0x04100000      bgezal  0x04110000
17642                  bltzall        0x04120000      bgezall 0x04130000  */
17643               insn &= ~0x00100000;
17644             }
17645
17646           /* Branch over the branch (if the branch was likely) or the
17647              full jump (not likely case).  Compute the offset from the
17648              current instruction to branch to.  */
17649           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17650             i = 16;
17651           else
17652             {
17653               /* How many bytes in instructions we've already emitted?  */
17654               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17655               /* How many bytes in instructions from here to the end?  */
17656               i = fragp->fr_var - i;
17657             }
17658           /* Convert to instruction count.  */
17659           i >>= 2;
17660           /* Branch counts from the next instruction.  */
17661           i--;
17662           insn |= i;
17663           /* Branch over the jump.  */
17664           md_number_to_chars ((char *) buf, insn, 4);
17665           buf += 4;
17666
17667           /* nop */
17668           md_number_to_chars ((char *) buf, 0, 4);
17669           buf += 4;
17670
17671           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17672             {
17673               /* beql $0, $0, 2f */
17674               insn = 0x50000000;
17675               /* Compute the PC offset from the current instruction to
17676                  the end of the variable frag.  */
17677               /* How many bytes in instructions we've already emitted?  */
17678               i = buf - (bfd_byte *)fragp->fr_literal - fragp->fr_fix;
17679               /* How many bytes in instructions from here to the end?  */
17680               i = fragp->fr_var - i;
17681               /* Convert to instruction count.  */
17682               i >>= 2;
17683               /* Don't decrement i, because we want to branch over the
17684                  delay slot.  */
17685
17686               insn |= i;
17687               md_number_to_chars ((char *) buf, insn, 4);
17688               buf += 4;
17689
17690               md_number_to_chars ((char *) buf, 0, 4);
17691               buf += 4;
17692             }
17693
17694         uncond:
17695           if (mips_pic == NO_PIC)
17696             {
17697               /* j or jal.  */
17698               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17699                       ? 0x0c000000 : 0x08000000);
17700               exp.X_op = O_symbol;
17701               exp.X_add_symbol = fragp->fr_symbol;
17702               exp.X_add_number = fragp->fr_offset;
17703
17704               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17705                                   4, &exp, FALSE, BFD_RELOC_MIPS_JMP);
17706               fixp->fx_file = fragp->fr_file;
17707               fixp->fx_line = fragp->fr_line;
17708
17709               md_number_to_chars ((char *) buf, insn, 4);
17710               buf += 4;
17711             }
17712           else
17713             {
17714               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17715
17716               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17717               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17718               insn |= at << OP_SH_RT;
17719               exp.X_op = O_symbol;
17720               exp.X_add_symbol = fragp->fr_symbol;
17721               exp.X_add_number = fragp->fr_offset;
17722
17723               if (fragp->fr_offset)
17724                 {
17725                   exp.X_add_symbol = make_expr_symbol (&exp);
17726                   exp.X_add_number = 0;
17727                 }
17728
17729               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17730                                   4, &exp, FALSE, BFD_RELOC_MIPS_GOT16);
17731               fixp->fx_file = fragp->fr_file;
17732               fixp->fx_line = fragp->fr_line;
17733
17734               md_number_to_chars ((char *) buf, insn, 4);
17735               buf += 4;
17736
17737               if (mips_opts.isa == ISA_MIPS1)
17738                 {
17739                   /* nop */
17740                   md_number_to_chars ((char *) buf, 0, 4);
17741                   buf += 4;
17742                 }
17743
17744               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17745               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17746               insn |= at << OP_SH_RS | at << OP_SH_RT;
17747
17748               fixp = fix_new_exp (fragp, buf - (bfd_byte *)fragp->fr_literal,
17749                                   4, &exp, FALSE, BFD_RELOC_LO16);
17750               fixp->fx_file = fragp->fr_file;
17751               fixp->fx_line = fragp->fr_line;
17752
17753               md_number_to_chars ((char *) buf, insn, 4);
17754               buf += 4;
17755
17756               /* j(al)r $at.  */
17757               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17758                 insn = 0x0000f809;
17759               else
17760                 insn = 0x00000008;
17761               insn |= at << OP_SH_RS;
17762
17763               md_number_to_chars ((char *) buf, insn, 4);
17764               buf += 4;
17765             }
17766         }
17767
17768       gas_assert (buf == (bfd_byte *)fragp->fr_literal
17769               + fragp->fr_fix + fragp->fr_var);
17770
17771       fragp->fr_fix += fragp->fr_var;
17772
17773       return;
17774     }
17775
17776   /* Relax microMIPS branches.  */
17777   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17778     {
17779       bfd_byte *buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
17780       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17781       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17782       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17783       bfd_boolean short_ds;
17784       unsigned long insn;
17785       expressionS exp;
17786       fixS *fixp;
17787
17788       exp.X_op = O_symbol;
17789       exp.X_add_symbol = fragp->fr_symbol;
17790       exp.X_add_number = fragp->fr_offset;
17791
17792       fragp->fr_fix += fragp->fr_var;
17793
17794       /* Handle 16-bit branches that fit or are forced to fit.  */
17795       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17796         {
17797           /* We generate a fixup instead of applying it right now,
17798              because if there is linker relaxation, we're going to
17799              need the relocations.  */
17800           if (type == 'D')
17801             fixp = fix_new_exp (fragp,
17802                                 buf - (bfd_byte *) fragp->fr_literal,
17803                                 2, &exp, TRUE,
17804                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17805           else if (type == 'E')
17806             fixp = fix_new_exp (fragp,
17807                                 buf - (bfd_byte *) fragp->fr_literal,
17808                                 2, &exp, TRUE,
17809                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17810           else
17811             abort ();
17812
17813           fixp->fx_file = fragp->fr_file;
17814           fixp->fx_line = fragp->fr_line;
17815
17816           /* These relocations can have an addend that won't fit in
17817              2 octets.  */
17818           fixp->fx_no_overflow = 1;
17819
17820           return;
17821         }
17822
17823       /* Handle 32-bit branches that fit or are forced to fit.  */
17824       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17825           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17826         {
17827           /* We generate a fixup instead of applying it right now,
17828              because if there is linker relaxation, we're going to
17829              need the relocations.  */
17830           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
17831                               4, &exp, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
17832           fixp->fx_file = fragp->fr_file;
17833           fixp->fx_line = fragp->fr_line;
17834
17835           if (type == 0)
17836             return;
17837         }
17838
17839       /* Relax 16-bit branches to 32-bit branches.  */
17840       if (type != 0)
17841         {
17842           if (target_big_endian)
17843             insn = bfd_getb16 (buf);
17844           else
17845             insn = bfd_getl16 (buf);
17846
17847           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17848             insn = 0x94000000;                          /* beq  */
17849           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17850             {
17851               unsigned long regno;
17852
17853               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17854               regno = micromips_to_32_reg_d_map [regno];
17855               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17856               insn |= regno << MICROMIPSOP_SH_RS;
17857             }
17858           else
17859             abort ();
17860
17861           /* Nothing else to do, just write it out.  */
17862           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17863               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17864             {
17865               md_number_to_chars ((char *) buf, insn >> 16, 2);
17866               buf += 2;
17867               md_number_to_chars ((char *) buf, insn & 0xffff, 2);
17868               buf += 2;
17869
17870               gas_assert (buf == ((bfd_byte *) fragp->fr_literal
17871                                   + fragp->fr_fix));
17872               return;
17873             }
17874         }
17875       else
17876         {
17877           unsigned long next;
17878
17879           if (target_big_endian)
17880             {
17881               insn = bfd_getb16 (buf);
17882               next = bfd_getb16 (buf + 2);
17883             }
17884           else
17885             {
17886               insn = bfd_getl16 (buf);
17887               next = bfd_getl16 (buf + 2);
17888             }
17889           insn = (insn << 16) | next;
17890         }
17891
17892       /* Relax 32-bit branches to a sequence of instructions.  */
17893       as_warn_where (fragp->fr_file, fragp->fr_line,
17894                      _("Relaxed out-of-range branch into a jump"));
17895
17896       /* Set the short-delay-slot bit.  */
17897       short_ds = al && (insn & 0x02000000) != 0;
17898
17899       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17900         {
17901           symbolS *l;
17902
17903           /* Reverse the branch.  */
17904           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17905               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17906             insn ^= 0x20000000;
17907           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17908                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17909                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17910                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17911                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17912                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17913                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17914                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17915                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17916                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17917             insn ^= 0x00400000;
17918           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17919                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17920                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17921                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17922             insn ^= 0x00200000;
17923           else
17924             abort ();
17925
17926           if (al)
17927             {
17928               /* Clear the and-link and short-delay-slot bits.  */
17929               gas_assert ((insn & 0xfda00000) == 0x40200000);
17930
17931               /* bltzal  0x40200000     bgezal  0x40600000  */
17932               /* bltzals 0x42200000     bgezals 0x42600000  */
17933               insn &= ~0x02200000;
17934             }
17935
17936           /* Make a label at the end for use with the branch.  */
17937           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17938           micromips_label_inc ();
17939 #if defined(OBJ_ELF) || defined(OBJ_MAYBE_ELF)
17940           if (IS_ELF)
17941             S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17942 #endif
17943
17944           /* Refer to it.  */
17945           fixp = fix_new (fragp, buf - (bfd_byte *) fragp->fr_literal,
17946                           4, l, 0, TRUE, BFD_RELOC_MICROMIPS_16_PCREL_S1);
17947           fixp->fx_file = fragp->fr_file;
17948           fixp->fx_line = fragp->fr_line;
17949
17950           /* Branch over the jump.  */
17951           md_number_to_chars ((char *) buf, insn >> 16, 2);
17952           buf += 2;
17953           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
17954           buf += 2;
17955
17956           if (!compact)
17957             {
17958               /* nop  */
17959               insn = 0x0c00;
17960               md_number_to_chars ((char *) buf, insn, 2);
17961               buf += 2;
17962             }
17963         }
17964
17965       if (mips_pic == NO_PIC)
17966         {
17967           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17968
17969           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17970           insn = al ? jal : 0xd4000000;
17971
17972           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
17973                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_JMP);
17974           fixp->fx_file = fragp->fr_file;
17975           fixp->fx_line = fragp->fr_line;
17976
17977           md_number_to_chars ((char *) buf, insn >> 16, 2);
17978           buf += 2;
17979           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
17980           buf += 2;
17981
17982           if (compact)
17983             {
17984               /* nop  */
17985               insn = 0x0c00;
17986               md_number_to_chars ((char *) buf, insn, 2);
17987               buf += 2;
17988             }
17989         }
17990       else
17991         {
17992           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17993           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17994           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17995
17996           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17997           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17998           insn |= at << MICROMIPSOP_SH_RT;
17999
18000           if (exp.X_add_number)
18001             {
18002               exp.X_add_symbol = make_expr_symbol (&exp);
18003               exp.X_add_number = 0;
18004             }
18005
18006           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18007                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_GOT16);
18008           fixp->fx_file = fragp->fr_file;
18009           fixp->fx_line = fragp->fr_line;
18010
18011           md_number_to_chars ((char *) buf, insn >> 16, 2);
18012           buf += 2;
18013           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18014           buf += 2;
18015
18016           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18017           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18018           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18019
18020           fixp = fix_new_exp (fragp, buf - (bfd_byte *) fragp->fr_literal,
18021                               4, &exp, FALSE, BFD_RELOC_MICROMIPS_LO16);
18022           fixp->fx_file = fragp->fr_file;
18023           fixp->fx_line = fragp->fr_line;
18024
18025           md_number_to_chars ((char *) buf, insn >> 16, 2);
18026           buf += 2;
18027           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18028           buf += 2;
18029
18030           /* jr/jrc/jalr/jalrs $at  */
18031           insn = al ? jalr : jr;
18032           insn |= at << MICROMIPSOP_SH_MJ;
18033
18034           md_number_to_chars ((char *) buf, insn & 0xffff, 2);
18035           buf += 2;
18036         }
18037
18038       gas_assert (buf == (bfd_byte *) fragp->fr_literal + fragp->fr_fix);
18039       return;
18040     }
18041
18042   if (RELAX_MIPS16_P (fragp->fr_subtype))
18043     {
18044       int type;
18045       const struct mips16_immed_operand *op;
18046       bfd_boolean small, ext;
18047       offsetT val;
18048       bfd_byte *buf;
18049       unsigned long insn;
18050       bfd_boolean use_extend;
18051       unsigned short extend;
18052
18053       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18054       op = mips16_immed_operands;
18055       while (op->type != type)
18056         ++op;
18057
18058       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18059         {
18060           small = FALSE;
18061           ext = TRUE;
18062         }
18063       else
18064         {
18065           small = TRUE;
18066           ext = FALSE;
18067         }
18068
18069       val = resolve_symbol_value (fragp->fr_symbol);
18070       if (op->pcrel)
18071         {
18072           addressT addr;
18073
18074           addr = fragp->fr_address + fragp->fr_fix;
18075
18076           /* The rules for the base address of a PC relative reloc are
18077              complicated; see mips16_extended_frag.  */
18078           if (type == 'p' || type == 'q')
18079             {
18080               addr += 2;
18081               if (ext)
18082                 addr += 2;
18083               /* Ignore the low bit in the target, since it will be
18084                  set for a text label.  */
18085               if ((val & 1) != 0)
18086                 --val;
18087             }
18088           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18089             addr -= 4;
18090           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18091             addr -= 2;
18092
18093           addr &= ~ (addressT) ((1 << op->shift) - 1);
18094           val -= addr;
18095
18096           /* Make sure the section winds up with the alignment we have
18097              assumed.  */
18098           if (op->shift > 0)
18099             record_alignment (asec, op->shift);
18100         }
18101
18102       if (ext
18103           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18104               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18105         as_warn_where (fragp->fr_file, fragp->fr_line,
18106                        _("extended instruction in delay slot"));
18107
18108       buf = (bfd_byte *) (fragp->fr_literal + fragp->fr_fix);
18109
18110       if (target_big_endian)
18111         insn = bfd_getb16 (buf);
18112       else
18113         insn = bfd_getl16 (buf);
18114
18115       mips16_immed (fragp->fr_file, fragp->fr_line, type, val,
18116                     RELAX_MIPS16_USER_EXT (fragp->fr_subtype),
18117                     small, ext, &insn, &use_extend, &extend);
18118
18119       if (use_extend)
18120         {
18121           md_number_to_chars ((char *) buf, 0xf000 | extend, 2);
18122           fragp->fr_fix += 2;
18123           buf += 2;
18124         }
18125
18126       md_number_to_chars ((char *) buf, insn, 2);
18127       fragp->fr_fix += 2;
18128       buf += 2;
18129     }
18130   else
18131     {
18132       relax_substateT subtype = fragp->fr_subtype;
18133       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18134       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18135       int first, second;
18136       fixS *fixp;
18137
18138       first = RELAX_FIRST (subtype);
18139       second = RELAX_SECOND (subtype);
18140       fixp = (fixS *) fragp->fr_opcode;
18141
18142       /* If the delay slot chosen does not match the size of the instruction,
18143          then emit a warning.  */
18144       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18145            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18146         {
18147           relax_substateT s;
18148           const char *msg;
18149
18150           s = subtype & (RELAX_DELAY_SLOT_16BIT
18151                          | RELAX_DELAY_SLOT_SIZE_FIRST
18152                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18153           msg = macro_warning (s);
18154           if (msg != NULL)
18155             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
18156           subtype &= ~s;
18157         }
18158
18159       /* Possibly emit a warning if we've chosen the longer option.  */
18160       if (use_second == second_longer)
18161         {
18162           relax_substateT s;
18163           const char *msg;
18164
18165           s = (subtype
18166                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18167           msg = macro_warning (s);
18168           if (msg != NULL)
18169             as_warn_where (fragp->fr_file, fragp->fr_line, msg);
18170           subtype &= ~s;
18171         }
18172
18173       /* Go through all the fixups for the first sequence.  Disable them
18174          (by marking them as done) if we're going to use the second
18175          sequence instead.  */
18176       while (fixp
18177              && fixp->fx_frag == fragp
18178              && fixp->fx_where < fragp->fr_fix - second)
18179         {
18180           if (subtype & RELAX_USE_SECOND)
18181             fixp->fx_done = 1;
18182           fixp = fixp->fx_next;
18183         }
18184
18185       /* Go through the fixups for the second sequence.  Disable them if
18186          we're going to use the first sequence, otherwise adjust their
18187          addresses to account for the relaxation.  */
18188       while (fixp && fixp->fx_frag == fragp)
18189         {
18190           if (subtype & RELAX_USE_SECOND)
18191             fixp->fx_where -= first;
18192           else
18193             fixp->fx_done = 1;
18194           fixp = fixp->fx_next;
18195         }
18196
18197       /* Now modify the frag contents.  */
18198       if (subtype & RELAX_USE_SECOND)
18199         {
18200           char *start;
18201
18202           start = fragp->fr_literal + fragp->fr_fix - first - second;
18203           memmove (start, start + first, second);
18204           fragp->fr_fix -= first;
18205         }
18206       else
18207         fragp->fr_fix -= second;
18208     }
18209 }
18210
18211 #ifdef OBJ_ELF
18212
18213 /* This function is called after the relocs have been generated.
18214    We've been storing mips16 text labels as odd.  Here we convert them
18215    back to even for the convenience of the debugger.  */
18216
18217 void
18218 mips_frob_file_after_relocs (void)
18219 {
18220   asymbol **syms;
18221   unsigned int count, i;
18222
18223   if (!IS_ELF)
18224     return;
18225
18226   syms = bfd_get_outsymbols (stdoutput);
18227   count = bfd_get_symcount (stdoutput);
18228   for (i = 0; i < count; i++, syms++)
18229     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18230         && ((*syms)->value & 1) != 0)
18231       {
18232         (*syms)->value &= ~1;
18233         /* If the symbol has an odd size, it was probably computed
18234            incorrectly, so adjust that as well.  */
18235         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18236           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18237       }
18238 }
18239
18240 #endif
18241
18242 /* This function is called whenever a label is defined, including fake
18243    labels instantiated off the dot special symbol.  It is used when
18244    handling branch delays; if a branch has a label, we assume we cannot
18245    move it.  This also bumps the value of the symbol by 1 in compressed
18246    code.  */
18247
18248 void
18249 mips_record_label (symbolS *sym)
18250 {
18251   segment_info_type *si = seg_info (now_seg);
18252   struct insn_label_list *l;
18253
18254   if (free_insn_labels == NULL)
18255     l = (struct insn_label_list *) xmalloc (sizeof *l);
18256   else
18257     {
18258       l = free_insn_labels;
18259       free_insn_labels = l->next;
18260     }
18261
18262   l->label = sym;
18263   l->next = si->label_list;
18264   si->label_list = l;
18265 }
18266
18267 /* This function is called as tc_frob_label() whenever a label is defined
18268    and adds a DWARF-2 record we only want for true labels.  */
18269
18270 void
18271 mips_define_label (symbolS *sym)
18272 {
18273   mips_record_label (sym);
18274 #ifdef OBJ_ELF
18275   dwarf2_emit_label (sym);
18276 #endif
18277 }
18278 \f
18279 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
18280
18281 /* Some special processing for a MIPS ELF file.  */
18282
18283 void
18284 mips_elf_final_processing (void)
18285 {
18286   /* Write out the register information.  */
18287   if (mips_abi != N64_ABI)
18288     {
18289       Elf32_RegInfo s;
18290
18291       s.ri_gprmask = mips_gprmask;
18292       s.ri_cprmask[0] = mips_cprmask[0];
18293       s.ri_cprmask[1] = mips_cprmask[1];
18294       s.ri_cprmask[2] = mips_cprmask[2];
18295       s.ri_cprmask[3] = mips_cprmask[3];
18296       /* The gp_value field is set by the MIPS ELF backend.  */
18297
18298       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18299                                        ((Elf32_External_RegInfo *)
18300                                         mips_regmask_frag));
18301     }
18302   else
18303     {
18304       Elf64_Internal_RegInfo s;
18305
18306       s.ri_gprmask = mips_gprmask;
18307       s.ri_pad = 0;
18308       s.ri_cprmask[0] = mips_cprmask[0];
18309       s.ri_cprmask[1] = mips_cprmask[1];
18310       s.ri_cprmask[2] = mips_cprmask[2];
18311       s.ri_cprmask[3] = mips_cprmask[3];
18312       /* The gp_value field is set by the MIPS ELF backend.  */
18313
18314       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18315                                        ((Elf64_External_RegInfo *)
18316                                         mips_regmask_frag));
18317     }
18318
18319   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18320      sort of BFD interface for this.  */
18321   if (mips_any_noreorder)
18322     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18323   if (mips_pic != NO_PIC)
18324     {
18325     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18326       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18327     }
18328   if (mips_abicalls)
18329     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18330
18331   /* Set MIPS ELF flags for ASEs.  */
18332   /* We may need to define a new flag for DSP ASE, and set this flag when
18333      file_ase_dsp is true.  */
18334   /* Same for DSP R2.  */
18335   /* We may need to define a new flag for MT ASE, and set this flag when
18336      file_ase_mt is true.  */
18337   if (file_ase_mips16)
18338     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18339   if (file_ase_micromips)
18340     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18341 #if 0 /* XXX FIXME */
18342   if (file_ase_mips3d)
18343     elf_elfheader (stdoutput)->e_flags |= ???;
18344 #endif
18345   if (file_ase_mdmx)
18346     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18347
18348   /* Set the MIPS ELF ABI flags.  */
18349   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18350     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18351   else if (mips_abi == O64_ABI)
18352     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18353   else if (mips_abi == EABI_ABI)
18354     {
18355       if (!file_mips_gp32)
18356         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18357       else
18358         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18359     }
18360   else if (mips_abi == N32_ABI)
18361     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18362
18363   /* Nothing to do for N64_ABI.  */
18364
18365   if (mips_32bitmode)
18366     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18367
18368 #if 0 /* XXX FIXME */
18369   /* 32 bit code with 64 bit FP registers.  */
18370   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18371     elf_elfheader (stdoutput)->e_flags |= ???;
18372 #endif
18373 }
18374
18375 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */
18376 \f
18377 typedef struct proc {
18378   symbolS *func_sym;
18379   symbolS *func_end_sym;
18380   unsigned long reg_mask;
18381   unsigned long reg_offset;
18382   unsigned long fpreg_mask;
18383   unsigned long fpreg_offset;
18384   unsigned long frame_offset;
18385   unsigned long frame_reg;
18386   unsigned long pc_reg;
18387 } procS;
18388
18389 static procS cur_proc;
18390 static procS *cur_proc_ptr;
18391 static int numprocs;
18392
18393 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18394    as "2", and a normal nop as "0".  */
18395
18396 #define NOP_OPCODE_MIPS         0
18397 #define NOP_OPCODE_MIPS16       1
18398 #define NOP_OPCODE_MICROMIPS    2
18399
18400 char
18401 mips_nop_opcode (void)
18402 {
18403   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18404     return NOP_OPCODE_MICROMIPS;
18405   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18406     return NOP_OPCODE_MIPS16;
18407   else
18408     return NOP_OPCODE_MIPS;
18409 }
18410
18411 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18412    32-bit microMIPS NOPs here (if applicable).  */
18413
18414 void
18415 mips_handle_align (fragS *fragp)
18416 {
18417   char nop_opcode;
18418   char *p;
18419   int bytes, size, excess;
18420   valueT opcode;
18421
18422   if (fragp->fr_type != rs_align_code)
18423     return;
18424
18425   p = fragp->fr_literal + fragp->fr_fix;
18426   nop_opcode = *p;
18427   switch (nop_opcode)
18428     {
18429     case NOP_OPCODE_MICROMIPS:
18430       opcode = micromips_nop32_insn.insn_opcode;
18431       size = 4;
18432       break;
18433     case NOP_OPCODE_MIPS16:
18434       opcode = mips16_nop_insn.insn_opcode;
18435       size = 2;
18436       break;
18437     case NOP_OPCODE_MIPS:
18438     default:
18439       opcode = nop_insn.insn_opcode;
18440       size = 4;
18441       break;
18442     }
18443
18444   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18445   excess = bytes % size;
18446
18447   /* Handle the leading part if we're not inserting a whole number of
18448      instructions, and make it the end of the fixed part of the frag.
18449      Try to fit in a short microMIPS NOP if applicable and possible,
18450      and use zeroes otherwise.  */
18451   gas_assert (excess < 4);
18452   fragp->fr_fix += excess;
18453   switch (excess)
18454     {
18455     case 3:
18456       *p++ = '\0';
18457       /* Fall through.  */
18458     case 2:
18459       if (nop_opcode == NOP_OPCODE_MICROMIPS)
18460         {
18461           md_number_to_chars (p, micromips_nop16_insn.insn_opcode, 2);
18462           p += 2;
18463           break;
18464         }
18465       *p++ = '\0';
18466       /* Fall through.  */
18467     case 1:
18468       *p++ = '\0';
18469       /* Fall through.  */
18470     case 0:
18471       break;
18472     }
18473
18474   md_number_to_chars (p, opcode, size);
18475   fragp->fr_var = size;
18476 }
18477
18478 static void
18479 md_obj_begin (void)
18480 {
18481 }
18482
18483 static void
18484 md_obj_end (void)
18485 {
18486   /* Check for premature end, nesting errors, etc.  */
18487   if (cur_proc_ptr)
18488     as_warn (_("missing .end at end of assembly"));
18489 }
18490
18491 static long
18492 get_number (void)
18493 {
18494   int negative = 0;
18495   long val = 0;
18496
18497   if (*input_line_pointer == '-')
18498     {
18499       ++input_line_pointer;
18500       negative = 1;
18501     }
18502   if (!ISDIGIT (*input_line_pointer))
18503     as_bad (_("expected simple number"));
18504   if (input_line_pointer[0] == '0')
18505     {
18506       if (input_line_pointer[1] == 'x')
18507         {
18508           input_line_pointer += 2;
18509           while (ISXDIGIT (*input_line_pointer))
18510             {
18511               val <<= 4;
18512               val |= hex_value (*input_line_pointer++);
18513             }
18514           return negative ? -val : val;
18515         }
18516       else
18517         {
18518           ++input_line_pointer;
18519           while (ISDIGIT (*input_line_pointer))
18520             {
18521               val <<= 3;
18522               val |= *input_line_pointer++ - '0';
18523             }
18524           return negative ? -val : val;
18525         }
18526     }
18527   if (!ISDIGIT (*input_line_pointer))
18528     {
18529       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18530               *input_line_pointer, *input_line_pointer);
18531       as_warn (_("invalid number"));
18532       return -1;
18533     }
18534   while (ISDIGIT (*input_line_pointer))
18535     {
18536       val *= 10;
18537       val += *input_line_pointer++ - '0';
18538     }
18539   return negative ? -val : val;
18540 }
18541
18542 /* The .file directive; just like the usual .file directive, but there
18543    is an initial number which is the ECOFF file index.  In the non-ECOFF
18544    case .file implies DWARF-2.  */
18545
18546 static void
18547 s_mips_file (int x ATTRIBUTE_UNUSED)
18548 {
18549   static int first_file_directive = 0;
18550
18551   if (ECOFF_DEBUGGING)
18552     {
18553       get_number ();
18554       s_app_file (0);
18555     }
18556   else
18557     {
18558       char *filename;
18559
18560       filename = dwarf2_directive_file (0);
18561
18562       /* Versions of GCC up to 3.1 start files with a ".file"
18563          directive even for stabs output.  Make sure that this
18564          ".file" is handled.  Note that you need a version of GCC
18565          after 3.1 in order to support DWARF-2 on MIPS.  */
18566       if (filename != NULL && ! first_file_directive)
18567         {
18568           (void) new_logical_line (filename, -1);
18569           s_app_file_string (filename, 0);
18570         }
18571       first_file_directive = 1;
18572     }
18573 }
18574
18575 /* The .loc directive, implying DWARF-2.  */
18576
18577 static void
18578 s_mips_loc (int x ATTRIBUTE_UNUSED)
18579 {
18580   if (!ECOFF_DEBUGGING)
18581     dwarf2_directive_loc (0);
18582 }
18583
18584 /* The .end directive.  */
18585
18586 static void
18587 s_mips_end (int x ATTRIBUTE_UNUSED)
18588 {
18589   symbolS *p;
18590
18591   /* Following functions need their own .frame and .cprestore directives.  */
18592   mips_frame_reg_valid = 0;
18593   mips_cprestore_valid = 0;
18594
18595   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18596     {
18597       p = get_symbol ();
18598       demand_empty_rest_of_line ();
18599     }
18600   else
18601     p = NULL;
18602
18603   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18604     as_warn (_(".end not in text section"));
18605
18606   if (!cur_proc_ptr)
18607     {
18608       as_warn (_(".end directive without a preceding .ent directive."));
18609       demand_empty_rest_of_line ();
18610       return;
18611     }
18612
18613   if (p != NULL)
18614     {
18615       gas_assert (S_GET_NAME (p));
18616       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18617         as_warn (_(".end symbol does not match .ent symbol."));
18618
18619       if (debug_type == DEBUG_STABS)
18620         stabs_generate_asm_endfunc (S_GET_NAME (p),
18621                                     S_GET_NAME (p));
18622     }
18623   else
18624     as_warn (_(".end directive missing or unknown symbol"));
18625
18626 #ifdef OBJ_ELF
18627   /* Create an expression to calculate the size of the function.  */
18628   if (p && cur_proc_ptr)
18629     {
18630       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18631       expressionS *exp = xmalloc (sizeof (expressionS));
18632
18633       obj->size = exp;
18634       exp->X_op = O_subtract;
18635       exp->X_add_symbol = symbol_temp_new_now ();
18636       exp->X_op_symbol = p;
18637       exp->X_add_number = 0;
18638
18639       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18640     }
18641
18642   /* Generate a .pdr section.  */
18643   if (IS_ELF && !ECOFF_DEBUGGING && mips_flag_pdr)
18644     {
18645       segT saved_seg = now_seg;
18646       subsegT saved_subseg = now_subseg;
18647       expressionS exp;
18648       char *fragp;
18649
18650 #ifdef md_flush_pending_output
18651       md_flush_pending_output ();
18652 #endif
18653
18654       gas_assert (pdr_seg);
18655       subseg_set (pdr_seg, 0);
18656
18657       /* Write the symbol.  */
18658       exp.X_op = O_symbol;
18659       exp.X_add_symbol = p;
18660       exp.X_add_number = 0;
18661       emit_expr (&exp, 4);
18662
18663       fragp = frag_more (7 * 4);
18664
18665       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18666       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18667       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18668       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18669       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18670       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18671       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18672
18673       subseg_set (saved_seg, saved_subseg);
18674     }
18675 #endif /* OBJ_ELF */
18676
18677   cur_proc_ptr = NULL;
18678 }
18679
18680 /* The .aent and .ent directives.  */
18681
18682 static void
18683 s_mips_ent (int aent)
18684 {
18685   symbolS *symbolP;
18686
18687   symbolP = get_symbol ();
18688   if (*input_line_pointer == ',')
18689     ++input_line_pointer;
18690   SKIP_WHITESPACE ();
18691   if (ISDIGIT (*input_line_pointer)
18692       || *input_line_pointer == '-')
18693     get_number ();
18694
18695   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18696     as_warn (_(".ent or .aent not in text section."));
18697
18698   if (!aent && cur_proc_ptr)
18699     as_warn (_("missing .end"));
18700
18701   if (!aent)
18702     {
18703       /* This function needs its own .frame and .cprestore directives.  */
18704       mips_frame_reg_valid = 0;
18705       mips_cprestore_valid = 0;
18706
18707       cur_proc_ptr = &cur_proc;
18708       memset (cur_proc_ptr, '\0', sizeof (procS));
18709
18710       cur_proc_ptr->func_sym = symbolP;
18711
18712       ++numprocs;
18713
18714       if (debug_type == DEBUG_STABS)
18715         stabs_generate_asm_func (S_GET_NAME (symbolP),
18716                                  S_GET_NAME (symbolP));
18717     }
18718
18719   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18720
18721   demand_empty_rest_of_line ();
18722 }
18723
18724 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18725    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18726    s_mips_frame is used so that we can set the PDR information correctly.
18727    We can't use the ecoff routines because they make reference to the ecoff
18728    symbol table (in the mdebug section).  */
18729
18730 static void
18731 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18732 {
18733 #ifdef OBJ_ELF
18734   if (IS_ELF && !ECOFF_DEBUGGING)
18735     {
18736       long val;
18737
18738       if (cur_proc_ptr == (procS *) NULL)
18739         {
18740           as_warn (_(".frame outside of .ent"));
18741           demand_empty_rest_of_line ();
18742           return;
18743         }
18744
18745       cur_proc_ptr->frame_reg = tc_get_register (1);
18746
18747       SKIP_WHITESPACE ();
18748       if (*input_line_pointer++ != ','
18749           || get_absolute_expression_and_terminator (&val) != ',')
18750         {
18751           as_warn (_("Bad .frame directive"));
18752           --input_line_pointer;
18753           demand_empty_rest_of_line ();
18754           return;
18755         }
18756
18757       cur_proc_ptr->frame_offset = val;
18758       cur_proc_ptr->pc_reg = tc_get_register (0);
18759
18760       demand_empty_rest_of_line ();
18761     }
18762   else
18763 #endif /* OBJ_ELF */
18764     s_ignore (ignore);
18765 }
18766
18767 /* The .fmask and .mask directives. If the mdebug section is present
18768    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18769    embedded targets, s_mips_mask is used so that we can set the PDR
18770    information correctly. We can't use the ecoff routines because they
18771    make reference to the ecoff symbol table (in the mdebug section).  */
18772
18773 static void
18774 s_mips_mask (int reg_type)
18775 {
18776 #ifdef OBJ_ELF
18777   if (IS_ELF && !ECOFF_DEBUGGING)
18778     {
18779       long mask, off;
18780
18781       if (cur_proc_ptr == (procS *) NULL)
18782         {
18783           as_warn (_(".mask/.fmask outside of .ent"));
18784           demand_empty_rest_of_line ();
18785           return;
18786         }
18787
18788       if (get_absolute_expression_and_terminator (&mask) != ',')
18789         {
18790           as_warn (_("Bad .mask/.fmask directive"));
18791           --input_line_pointer;
18792           demand_empty_rest_of_line ();
18793           return;
18794         }
18795
18796       off = get_absolute_expression ();
18797
18798       if (reg_type == 'F')
18799         {
18800           cur_proc_ptr->fpreg_mask = mask;
18801           cur_proc_ptr->fpreg_offset = off;
18802         }
18803       else
18804         {
18805           cur_proc_ptr->reg_mask = mask;
18806           cur_proc_ptr->reg_offset = off;
18807         }
18808
18809       demand_empty_rest_of_line ();
18810     }
18811   else
18812 #endif /* OBJ_ELF */
18813     s_ignore (reg_type);
18814 }
18815
18816 /* A table describing all the processors gas knows about.  Names are
18817    matched in the order listed.
18818
18819    To ease comparison, please keep this table in the same order as
18820    gcc's mips_cpu_info_table[].  */
18821 static const struct mips_cpu_info mips_cpu_info_table[] =
18822 {
18823   /* Entries for generic ISAs */
18824   { "mips1",          MIPS_CPU_IS_ISA,          ISA_MIPS1,      CPU_R3000 },
18825   { "mips2",          MIPS_CPU_IS_ISA,          ISA_MIPS2,      CPU_R6000 },
18826   { "mips3",          MIPS_CPU_IS_ISA,          ISA_MIPS3,      CPU_R4000 },
18827   { "mips4",          MIPS_CPU_IS_ISA,          ISA_MIPS4,      CPU_R8000 },
18828   { "mips5",          MIPS_CPU_IS_ISA,          ISA_MIPS5,      CPU_MIPS5 },
18829   { "mips32",         MIPS_CPU_IS_ISA,          ISA_MIPS32,     CPU_MIPS32 },
18830   { "mips32r2",       MIPS_CPU_IS_ISA,          ISA_MIPS32R2,   CPU_MIPS32R2 },
18831   { "mips64",         MIPS_CPU_IS_ISA,          ISA_MIPS64,     CPU_MIPS64 },
18832   { "mips64r2",       MIPS_CPU_IS_ISA,          ISA_MIPS64R2,   CPU_MIPS64R2 },
18833
18834   /* MIPS I */
18835   { "r3000",          0,                        ISA_MIPS1,      CPU_R3000 },
18836   { "r2000",          0,                        ISA_MIPS1,      CPU_R3000 },
18837   { "r3900",          0,                        ISA_MIPS1,      CPU_R3900 },
18838
18839   /* MIPS II */
18840   { "r6000",          0,                        ISA_MIPS2,      CPU_R6000 },
18841
18842   /* MIPS III */
18843   { "r4000",          0,                        ISA_MIPS3,      CPU_R4000 },
18844   { "r4010",          0,                        ISA_MIPS2,      CPU_R4010 },
18845   { "vr4100",         0,                        ISA_MIPS3,      CPU_VR4100 },
18846   { "vr4111",         0,                        ISA_MIPS3,      CPU_R4111 },
18847   { "vr4120",         0,                        ISA_MIPS3,      CPU_VR4120 },
18848   { "vr4130",         0,                        ISA_MIPS3,      CPU_VR4120 },
18849   { "vr4181",         0,                        ISA_MIPS3,      CPU_R4111 },
18850   { "vr4300",         0,                        ISA_MIPS3,      CPU_R4300 },
18851   { "r4400",          0,                        ISA_MIPS3,      CPU_R4400 },
18852   { "r4600",          0,                        ISA_MIPS3,      CPU_R4600 },
18853   { "orion",          0,                        ISA_MIPS3,      CPU_R4600 },
18854   { "r4650",          0,                        ISA_MIPS3,      CPU_R4650 },
18855   /* ST Microelectronics Loongson 2E and 2F cores */
18856   { "loongson2e",     0,                        ISA_MIPS3,   CPU_LOONGSON_2E },
18857   { "loongson2f",     0,                        ISA_MIPS3,   CPU_LOONGSON_2F },
18858
18859   /* MIPS IV */
18860   { "r8000",          0,                        ISA_MIPS4,      CPU_R8000 },
18861   { "r10000",         0,                        ISA_MIPS4,      CPU_R10000 },
18862   { "r12000",         0,                        ISA_MIPS4,      CPU_R12000 },
18863   { "r14000",         0,                        ISA_MIPS4,      CPU_R14000 },
18864   { "r16000",         0,                        ISA_MIPS4,      CPU_R16000 },
18865   { "vr5000",         0,                        ISA_MIPS4,      CPU_R5000 },
18866   { "vr5400",         0,                        ISA_MIPS4,      CPU_VR5400 },
18867   { "vr5500",         0,                        ISA_MIPS4,      CPU_VR5500 },
18868   { "rm5200",         0,                        ISA_MIPS4,      CPU_R5000 },
18869   { "rm5230",         0,                        ISA_MIPS4,      CPU_R5000 },
18870   { "rm5231",         0,                        ISA_MIPS4,      CPU_R5000 },
18871   { "rm5261",         0,                        ISA_MIPS4,      CPU_R5000 },
18872   { "rm5721",         0,                        ISA_MIPS4,      CPU_R5000 },
18873   { "rm7000",         0,                        ISA_MIPS4,      CPU_RM7000 },
18874   { "rm9000",         0,                        ISA_MIPS4,      CPU_RM9000 },
18875
18876   /* MIPS 32 */
18877   { "4kc",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18878   { "4km",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18879   { "4kp",            0,                        ISA_MIPS32,     CPU_MIPS32 },
18880   { "4ksc",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32,     CPU_MIPS32 },
18881
18882   /* MIPS 32 Release 2 */
18883   { "4kec",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18884   { "4kem",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18885   { "4kep",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18886   { "4ksd",           MIPS_CPU_ASE_SMARTMIPS,   ISA_MIPS32R2,   CPU_MIPS32R2 },
18887   { "m4k",            0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18888   { "m4kp",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18889   { "24kc",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18890   { "24kf2_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18891   { "24kf",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18892   { "24kf1_1",        0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18893   /* Deprecated forms of the above.  */
18894   { "24kfx",          0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18895   { "24kx",           0,                        ISA_MIPS32R2,   CPU_MIPS32R2 },
18896   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
18897   { "24kec",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18898   { "24kef2_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18899   { "24kef",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18900   { "24kef1_1",       MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18901   /* Deprecated forms of the above.  */
18902   { "24kefx",         MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18903   { "24kex",          MIPS_CPU_ASE_DSP,         ISA_MIPS32R2,   CPU_MIPS32R2 },
18904   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
18905   { "34kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18906                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18907   { "34kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18908                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18909   { "34kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18910                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18911   { "34kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18912                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18913   /* Deprecated forms of the above.  */
18914   { "34kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18915                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18916   { "34kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18917                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18918   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
18919   { "74kc",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18920                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18921   { "74kf2_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18922                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18923   { "74kf",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18924                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18925   { "74kf1_1",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18926                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18927   { "74kf3_2",        MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18928                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18929   /* Deprecated forms of the above.  */
18930   { "74kfx",          MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18931                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18932   { "74kx",           MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_DSPR2,
18933                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18934   /* 1004K cores are multiprocessor versions of the 34K.  */
18935   { "1004kc",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18936                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18937   { "1004kf2_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18938                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18939   { "1004kf",         MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18940                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18941   { "1004kf1_1",      MIPS_CPU_ASE_DSP | MIPS_CPU_ASE_MT,
18942                                                 ISA_MIPS32R2,   CPU_MIPS32R2 },
18943
18944   /* MIPS 64 */
18945   { "5kc",            0,                        ISA_MIPS64,     CPU_MIPS64 },
18946   { "5kf",            0,                        ISA_MIPS64,     CPU_MIPS64 },
18947   { "20kc",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
18948   { "25kf",           MIPS_CPU_ASE_MIPS3D,      ISA_MIPS64,     CPU_MIPS64 },
18949
18950   /* Broadcom SB-1 CPU core */
18951   { "sb1",            MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
18952                                                 ISA_MIPS64,     CPU_SB1 },
18953   /* Broadcom SB-1A CPU core */
18954   { "sb1a",           MIPS_CPU_ASE_MIPS3D | MIPS_CPU_ASE_MDMX,
18955                                                 ISA_MIPS64,     CPU_SB1 },
18956   
18957   { "loongson3a",     0,                        ISA_MIPS64,     CPU_LOONGSON_3A },
18958
18959   /* MIPS 64 Release 2 */
18960
18961   /* Cavium Networks Octeon CPU core */
18962   { "octeon",         0,      ISA_MIPS64R2,   CPU_OCTEON },
18963
18964   /* RMI Xlr */
18965   { "xlr",            0,      ISA_MIPS64,     CPU_XLR },
18966
18967   /* End marker */
18968   { NULL, 0, 0, 0 }
18969 };
18970
18971
18972 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
18973    with a final "000" replaced by "k".  Ignore case.
18974
18975    Note: this function is shared between GCC and GAS.  */
18976
18977 static bfd_boolean
18978 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
18979 {
18980   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
18981     given++, canonical++;
18982
18983   return ((*given == 0 && *canonical == 0)
18984           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
18985 }
18986
18987
18988 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
18989    CPU name.  We've traditionally allowed a lot of variation here.
18990
18991    Note: this function is shared between GCC and GAS.  */
18992
18993 static bfd_boolean
18994 mips_matching_cpu_name_p (const char *canonical, const char *given)
18995 {
18996   /* First see if the name matches exactly, or with a final "000"
18997      turned into "k".  */
18998   if (mips_strict_matching_cpu_name_p (canonical, given))
18999     return TRUE;
19000
19001   /* If not, try comparing based on numerical designation alone.
19002      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19003   if (TOLOWER (*given) == 'r')
19004     given++;
19005   if (!ISDIGIT (*given))
19006     return FALSE;
19007
19008   /* Skip over some well-known prefixes in the canonical name,
19009      hoping to find a number there too.  */
19010   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19011     canonical += 2;
19012   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19013     canonical += 2;
19014   else if (TOLOWER (canonical[0]) == 'r')
19015     canonical += 1;
19016
19017   return mips_strict_matching_cpu_name_p (canonical, given);
19018 }
19019
19020
19021 /* Parse an option that takes the name of a processor as its argument.
19022    OPTION is the name of the option and CPU_STRING is the argument.
19023    Return the corresponding processor enumeration if the CPU_STRING is
19024    recognized, otherwise report an error and return null.
19025
19026    A similar function exists in GCC.  */
19027
19028 static const struct mips_cpu_info *
19029 mips_parse_cpu (const char *option, const char *cpu_string)
19030 {
19031   const struct mips_cpu_info *p;
19032
19033   /* 'from-abi' selects the most compatible architecture for the given
19034      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19035      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19036      version.  Look first at the -mgp options, if given, otherwise base
19037      the choice on MIPS_DEFAULT_64BIT.
19038
19039      Treat NO_ABI like the EABIs.  One reason to do this is that the
19040      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19041      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19042      'mips64', just as we did in the days before 'from-abi'.  */
19043   if (strcasecmp (cpu_string, "from-abi") == 0)
19044     {
19045       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19046         return mips_cpu_info_from_isa (ISA_MIPS1);
19047
19048       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19049         return mips_cpu_info_from_isa (ISA_MIPS3);
19050
19051       if (file_mips_gp32 >= 0)
19052         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19053
19054       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19055                                      ? ISA_MIPS3
19056                                      : ISA_MIPS1);
19057     }
19058
19059   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19060   if (strcasecmp (cpu_string, "default") == 0)
19061     return 0;
19062
19063   for (p = mips_cpu_info_table; p->name != 0; p++)
19064     if (mips_matching_cpu_name_p (p->name, cpu_string))
19065       return p;
19066
19067   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19068   return 0;
19069 }
19070
19071 /* Return the canonical processor information for ISA (a member of the
19072    ISA_MIPS* enumeration).  */
19073
19074 static const struct mips_cpu_info *
19075 mips_cpu_info_from_isa (int isa)
19076 {
19077   int i;
19078
19079   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19080     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19081         && isa == mips_cpu_info_table[i].isa)
19082       return (&mips_cpu_info_table[i]);
19083
19084   return NULL;
19085 }
19086
19087 static const struct mips_cpu_info *
19088 mips_cpu_info_from_arch (int arch)
19089 {
19090   int i;
19091
19092   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19093     if (arch == mips_cpu_info_table[i].cpu)
19094       return (&mips_cpu_info_table[i]);
19095
19096   return NULL;
19097 }
19098 \f
19099 static void
19100 show (FILE *stream, const char *string, int *col_p, int *first_p)
19101 {
19102   if (*first_p)
19103     {
19104       fprintf (stream, "%24s", "");
19105       *col_p = 24;
19106     }
19107   else
19108     {
19109       fprintf (stream, ", ");
19110       *col_p += 2;
19111     }
19112
19113   if (*col_p + strlen (string) > 72)
19114     {
19115       fprintf (stream, "\n%24s", "");
19116       *col_p = 24;
19117     }
19118
19119   fprintf (stream, "%s", string);
19120   *col_p += strlen (string);
19121
19122   *first_p = 0;
19123 }
19124
19125 void
19126 md_show_usage (FILE *stream)
19127 {
19128   int column, first;
19129   size_t i;
19130
19131   fprintf (stream, _("\
19132 MIPS options:\n\
19133 -EB                     generate big endian output\n\
19134 -EL                     generate little endian output\n\
19135 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19136 -G NUM                  allow referencing objects up to NUM bytes\n\
19137                         implicitly with the gp register [default 8]\n"));
19138   fprintf (stream, _("\
19139 -mips1                  generate MIPS ISA I instructions\n\
19140 -mips2                  generate MIPS ISA II instructions\n\
19141 -mips3                  generate MIPS ISA III instructions\n\
19142 -mips4                  generate MIPS ISA IV instructions\n\
19143 -mips5                  generate MIPS ISA V instructions\n\
19144 -mips32                 generate MIPS32 ISA instructions\n\
19145 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19146 -mips64                 generate MIPS64 ISA instructions\n\
19147 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19148 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19149
19150   first = 1;
19151
19152   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19153     show (stream, mips_cpu_info_table[i].name, &column, &first);
19154   show (stream, "from-abi", &column, &first);
19155   fputc ('\n', stream);
19156
19157   fprintf (stream, _("\
19158 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19159 -no-mCPU                don't generate code specific to CPU.\n\
19160                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19161
19162   first = 1;
19163
19164   show (stream, "3900", &column, &first);
19165   show (stream, "4010", &column, &first);
19166   show (stream, "4100", &column, &first);
19167   show (stream, "4650", &column, &first);
19168   fputc ('\n', stream);
19169
19170   fprintf (stream, _("\
19171 -mips16                 generate mips16 instructions\n\
19172 -no-mips16              do not generate mips16 instructions\n"));
19173   fprintf (stream, _("\
19174 -mmicromips             generate microMIPS instructions\n\
19175 -mno-micromips          do not generate microMIPS instructions\n"));
19176   fprintf (stream, _("\
19177 -msmartmips             generate smartmips instructions\n\
19178 -mno-smartmips          do not generate smartmips instructions\n"));  
19179   fprintf (stream, _("\
19180 -mdsp                   generate DSP instructions\n\
19181 -mno-dsp                do not generate DSP instructions\n"));
19182   fprintf (stream, _("\
19183 -mdspr2                 generate DSP R2 instructions\n\
19184 -mno-dspr2              do not generate DSP R2 instructions\n"));
19185   fprintf (stream, _("\
19186 -mmt                    generate MT instructions\n\
19187 -mno-mt                 do not generate MT instructions\n"));
19188   fprintf (stream, _("\
19189 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19190 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19191 -mfix-vr4120            work around certain VR4120 errata\n\
19192 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19193 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19194 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19195 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19196 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19197 -msym32                 assume all symbols have 32-bit values\n\
19198 -O0                     remove unneeded NOPs, do not swap branches\n\
19199 -O                      remove unneeded NOPs and swap branches\n\
19200 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19201 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19202   fprintf (stream, _("\
19203 -mhard-float            allow floating-point instructions\n\
19204 -msoft-float            do not allow floating-point instructions\n\
19205 -msingle-float          only allow 32-bit floating-point operations\n\
19206 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19207 --[no-]construct-floats [dis]allow floating point values to be constructed\n"
19208                      ));
19209 #ifdef OBJ_ELF
19210   fprintf (stream, _("\
19211 -KPIC, -call_shared     generate SVR4 position independent code\n\
19212 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19213 -mvxworks-pic           generate VxWorks position independent code\n\
19214 -non_shared             do not generate code that can operate with DSOs\n\
19215 -xgot                   assume a 32 bit GOT\n\
19216 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19217 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19218                         position dependent (non shared) code\n\
19219 -mabi=ABI               create ABI conformant object file for:\n"));
19220
19221   first = 1;
19222
19223   show (stream, "32", &column, &first);
19224   show (stream, "o64", &column, &first);
19225   show (stream, "n32", &column, &first);
19226   show (stream, "64", &column, &first);
19227   show (stream, "eabi", &column, &first);
19228
19229   fputc ('\n', stream);
19230
19231   fprintf (stream, _("\
19232 -32                     create o32 ABI object file (default)\n\
19233 -n32                    create n32 ABI object file\n\
19234 -64                     create 64 ABI object file\n"));
19235 #endif
19236 }
19237
19238 #ifdef TE_IRIX
19239 enum dwarf2_format
19240 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19241 {
19242   if (HAVE_64BIT_SYMBOLS)
19243     return dwarf2_format_64bit_irix;
19244   else
19245     return dwarf2_format_32bit;
19246 }
19247 #endif
19248
19249 int
19250 mips_dwarf2_addr_size (void)
19251 {
19252   if (HAVE_64BIT_OBJECTS)
19253     return 8;
19254   else
19255     return 4;
19256 }
19257
19258 /* Standard calling conventions leave the CFA at SP on entry.  */
19259 void
19260 mips_cfi_frame_initial_instructions (void)
19261 {
19262   cfi_add_CFA_def_cfa_register (SP);
19263 }
19264
19265 int
19266 tc_mips_regname_to_dw2regnum (char *regname)
19267 {
19268   unsigned int regnum = -1;
19269   unsigned int reg;
19270
19271   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19272     regnum = reg;
19273
19274   return regnum;
19275 }