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, 2011, 2012, 2013
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 /* Check assumptions made in this file.  */
38 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
39 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
40
41 #ifdef DEBUG
42 #define DBG(x) printf x
43 #else
44 #define DBG(x)
45 #endif
46
47 /* Clean up namespace so we can include obj-elf.h too.  */
48 static int mips_output_flavor (void);
49 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
50 #undef OBJ_PROCESS_STAB
51 #undef OUTPUT_FLAVOR
52 #undef S_GET_ALIGN
53 #undef S_GET_SIZE
54 #undef S_SET_ALIGN
55 #undef S_SET_SIZE
56 #undef obj_frob_file
57 #undef obj_frob_file_after_relocs
58 #undef obj_frob_symbol
59 #undef obj_pop_insert
60 #undef obj_sec_sym_ok_for_reloc
61 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
62
63 #include "obj-elf.h"
64 /* Fix any of them that we actually care about.  */
65 #undef OUTPUT_FLAVOR
66 #define OUTPUT_FLAVOR mips_output_flavor()
67
68 #include "elf/mips.h"
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 static char *mips_regmask_frag;
89
90 #define ZERO 0
91 #define ATREG 1
92 #define S0  16
93 #define S7  23
94 #define TREG 24
95 #define PIC_CALL_REG 25
96 #define KT0 26
97 #define KT1 27
98 #define GP  28
99 #define SP  29
100 #define FP  30
101 #define RA  31
102
103 #define ILLEGAL_REG (32)
104
105 #define AT  mips_opts.at
106
107 extern int target_big_endian;
108
109 /* The name of the readonly data section.  */
110 #define RDATA_SECTION_NAME ".rodata"
111
112 /* Ways in which an instruction can be "appended" to the output.  */
113 enum append_method {
114   /* Just add it normally.  */
115   APPEND_ADD,
116
117   /* Add it normally and then add a nop.  */
118   APPEND_ADD_WITH_NOP,
119
120   /* Turn an instruction with a delay slot into a "compact" version.  */
121   APPEND_ADD_COMPACT,
122
123   /* Insert the instruction before the last one.  */
124   APPEND_SWAP
125 };
126
127 /* Information about an instruction, including its format, operands
128    and fixups.  */
129 struct mips_cl_insn
130 {
131   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
132   const struct mips_opcode *insn_mo;
133
134   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
135      a copy of INSN_MO->match with the operands filled in.  If we have
136      decided to use an extended MIPS16 instruction, this includes the
137      extension.  */
138   unsigned long insn_opcode;
139
140   /* The frag that contains the instruction.  */
141   struct frag *frag;
142
143   /* The offset into FRAG of the first instruction byte.  */
144   long where;
145
146   /* The relocs associated with the instruction, if any.  */
147   fixS *fixp[3];
148
149   /* True if this entry cannot be moved from its current position.  */
150   unsigned int fixed_p : 1;
151
152   /* True if this instruction occurred in a .set noreorder block.  */
153   unsigned int noreorder_p : 1;
154
155   /* True for mips16 instructions that jump to an absolute address.  */
156   unsigned int mips16_absolute_jump_p : 1;
157
158   /* True if this instruction is complete.  */
159   unsigned int complete_p : 1;
160
161   /* True if this instruction is cleared from history by unconditional
162      branch.  */
163   unsigned int cleared_p : 1;
164 };
165
166 /* The ABI to use.  */
167 enum mips_abi_level
168 {
169   NO_ABI = 0,
170   O32_ABI,
171   O64_ABI,
172   N32_ABI,
173   N64_ABI,
174   EABI_ABI
175 };
176
177 /* MIPS ABI we are using for this output file.  */
178 static enum mips_abi_level mips_abi = NO_ABI;
179
180 /* Whether or not we have code that can call pic code.  */
181 int mips_abicalls = FALSE;
182
183 /* Whether or not we have code which can be put into a shared
184    library.  */
185 static bfd_boolean mips_in_shared = TRUE;
186
187 /* This is the set of options which may be modified by the .set
188    pseudo-op.  We use a struct so that .set push and .set pop are more
189    reliable.  */
190
191 struct mips_set_options
192 {
193   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
194      if it has not been initialized.  Changed by `.set mipsN', and the
195      -mipsN command line option, and the default CPU.  */
196   int isa;
197   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
198      <asename>', by command line options, and based on the default
199      architecture.  */
200   int ase;
201   /* Whether we are assembling for the mips16 processor.  0 if we are
202      not, 1 if we are, and -1 if the value has not been initialized.
203      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
204      -nomips16 command line options, and the default CPU.  */
205   int mips16;
206   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
207      1 if we are, and -1 if the value has not been initialized.  Changed
208      by `.set micromips' and `.set nomicromips', and the -mmicromips
209      and -mno-micromips command line options, and the default CPU.  */
210   int micromips;
211   /* Non-zero if we should not reorder instructions.  Changed by `.set
212      reorder' and `.set noreorder'.  */
213   int noreorder;
214   /* Non-zero if we should not permit the register designated "assembler
215      temporary" to be used in instructions.  The value is the register
216      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
217      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
218   unsigned int at;
219   /* Non-zero if we should warn when a macro instruction expands into
220      more than one machine instruction.  Changed by `.set nomacro' and
221      `.set macro'.  */
222   int warn_about_macros;
223   /* Non-zero if we should not move instructions.  Changed by `.set
224      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
225   int nomove;
226   /* Non-zero if we should not optimize branches by moving the target
227      of the branch into the delay slot.  Actually, we don't perform
228      this optimization anyhow.  Changed by `.set bopt' and `.set
229      nobopt'.  */
230   int nobopt;
231   /* Non-zero if we should not autoextend mips16 instructions.
232      Changed by `.set autoextend' and `.set noautoextend'.  */
233   int noautoextend;
234   /* True if we should only emit 32-bit microMIPS instructions.
235      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
236      and -mno-insn32 command line options.  */
237   bfd_boolean insn32;
238   /* Restrict general purpose registers and floating point registers
239      to 32 bit.  This is initially determined when -mgp32 or -mfp32
240      is passed but can changed if the assembler code uses .set mipsN.  */
241   int gp32;
242   int fp32;
243   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
244      command line option, and the default CPU.  */
245   int arch;
246   /* True if ".set sym32" is in effect.  */
247   bfd_boolean sym32;
248   /* True if floating-point operations are not allowed.  Changed by .set
249      softfloat or .set hardfloat, by command line options -msoft-float or
250      -mhard-float.  The default is false.  */
251   bfd_boolean soft_float;
252
253   /* True if only single-precision floating-point operations are allowed.
254      Changed by .set singlefloat or .set doublefloat, command-line options
255      -msingle-float or -mdouble-float.  The default is false.  */
256   bfd_boolean single_float;
257 };
258
259 /* This is the struct we use to hold the current set of options.  Note
260    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
261    -1 to indicate that they have not been initialized.  */
262
263 /* True if -mgp32 was passed.  */
264 static int file_mips_gp32 = -1;
265
266 /* True if -mfp32 was passed.  */
267 static int file_mips_fp32 = -1;
268
269 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
270 static int file_mips_soft_float = 0;
271
272 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
273 static int file_mips_single_float = 0;
274
275 /* True if -mnan=2008, false if -mnan=legacy.  */
276 static bfd_boolean mips_flag_nan2008 = FALSE;
277
278 static struct mips_set_options mips_opts =
279 {
280   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
281   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
282   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
283   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
284   /* soft_float */ FALSE, /* single_float */ FALSE
285 };
286
287 /* The set of ASEs that were selected on the command line, either
288    explicitly via ASE options or implicitly through things like -march.  */
289 static unsigned int file_ase;
290
291 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
292 static unsigned int file_ase_explicit;
293
294 /* These variables are filled in with the masks of registers used.
295    The object format code reads them and puts them in the appropriate
296    place.  */
297 unsigned long mips_gprmask;
298 unsigned long mips_cprmask[4];
299
300 /* MIPS ISA we are using for this output file.  */
301 static int file_mips_isa = ISA_UNKNOWN;
302
303 /* True if any MIPS16 code was produced.  */
304 static int file_ase_mips16;
305
306 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
307                               || mips_opts.isa == ISA_MIPS32R2          \
308                               || mips_opts.isa == ISA_MIPS64            \
309                               || mips_opts.isa == ISA_MIPS64R2)
310
311 /* True if any microMIPS code was produced.  */
312 static int file_ase_micromips;
313
314 /* True if we want to create R_MIPS_JALR for jalr $25.  */
315 #ifdef TE_IRIX
316 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
317 #else
318 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
319    because there's no place for any addend, the only acceptable
320    expression is a bare symbol.  */
321 #define MIPS_JALR_HINT_P(EXPR) \
322   (!HAVE_IN_PLACE_ADDENDS \
323    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
324 #endif
325
326 /* The argument of the -march= flag.  The architecture we are assembling.  */
327 static int file_mips_arch = CPU_UNKNOWN;
328 static const char *mips_arch_string;
329
330 /* The argument of the -mtune= flag.  The architecture for which we
331    are optimizing.  */
332 static int mips_tune = CPU_UNKNOWN;
333 static const char *mips_tune_string;
334
335 /* True when generating 32-bit code for a 64-bit processor.  */
336 static int mips_32bitmode = 0;
337
338 /* True if the given ABI requires 32-bit registers.  */
339 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
340
341 /* Likewise 64-bit registers.  */
342 #define ABI_NEEDS_64BIT_REGS(ABI)       \
343   ((ABI) == N32_ABI                     \
344    || (ABI) == N64_ABI                  \
345    || (ABI) == O64_ABI)
346
347 /*  Return true if ISA supports 64 bit wide gp registers.  */
348 #define ISA_HAS_64BIT_REGS(ISA)         \
349   ((ISA) == ISA_MIPS3                   \
350    || (ISA) == ISA_MIPS4                \
351    || (ISA) == ISA_MIPS5                \
352    || (ISA) == ISA_MIPS64               \
353    || (ISA) == ISA_MIPS64R2)
354
355 /*  Return true if ISA supports 64 bit wide float registers.  */
356 #define ISA_HAS_64BIT_FPRS(ISA)         \
357   ((ISA) == ISA_MIPS3                   \
358    || (ISA) == ISA_MIPS4                \
359    || (ISA) == ISA_MIPS5                \
360    || (ISA) == ISA_MIPS32R2             \
361    || (ISA) == ISA_MIPS64               \
362    || (ISA) == ISA_MIPS64R2)
363
364 /* Return true if ISA supports 64-bit right rotate (dror et al.)
365    instructions.  */
366 #define ISA_HAS_DROR(ISA)               \
367   ((ISA) == ISA_MIPS64R2                \
368    || (mips_opts.micromips              \
369        && ISA_HAS_64BIT_REGS (ISA))     \
370    )
371
372 /* Return true if ISA supports 32-bit right rotate (ror et al.)
373    instructions.  */
374 #define ISA_HAS_ROR(ISA)                \
375   ((ISA) == ISA_MIPS32R2                \
376    || (ISA) == ISA_MIPS64R2             \
377    || (mips_opts.ase & ASE_SMARTMIPS)   \
378    || mips_opts.micromips               \
379    )
380
381 /* Return true if ISA supports single-precision floats in odd registers.  */
382 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
383   ((ISA) == ISA_MIPS32                  \
384    || (ISA) == ISA_MIPS32R2             \
385    || (ISA) == ISA_MIPS64               \
386    || (ISA) == ISA_MIPS64R2)
387
388 /* Return true if ISA supports move to/from high part of a 64-bit
389    floating-point register. */
390 #define ISA_HAS_MXHC1(ISA)              \
391   ((ISA) == ISA_MIPS32R2                \
392    || (ISA) == ISA_MIPS64R2)
393
394 #define HAVE_32BIT_GPRS                            \
395     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
396
397 #define HAVE_32BIT_FPRS                            \
398     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
399
400 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
401 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
402
403 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
404
405 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
406
407 /* True if relocations are stored in-place.  */
408 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
409
410 /* The ABI-derived address size.  */
411 #define HAVE_64BIT_ADDRESSES \
412   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
413 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
414
415 /* The size of symbolic constants (i.e., expressions of the form
416    "SYMBOL" or "SYMBOL + OFFSET").  */
417 #define HAVE_32BIT_SYMBOLS \
418   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
419 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
420
421 /* Addresses are loaded in different ways, depending on the address size
422    in use.  The n32 ABI Documentation also mandates the use of additions
423    with overflow checking, but existing implementations don't follow it.  */
424 #define ADDRESS_ADD_INSN                                                \
425    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
426
427 #define ADDRESS_ADDI_INSN                                               \
428    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
429
430 #define ADDRESS_LOAD_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
432
433 #define ADDRESS_STORE_INSN                                              \
434    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
435
436 /* Return true if the given CPU supports the MIPS16 ASE.  */
437 #define CPU_HAS_MIPS16(cpu)                                             \
438    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
439     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
440
441 /* Return true if the given CPU supports the microMIPS ASE.  */
442 #define CPU_HAS_MICROMIPS(cpu)  0
443
444 /* True if CPU has a dror instruction.  */
445 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
446
447 /* True if CPU has a ror instruction.  */
448 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
449
450 /* True if CPU is in the Octeon family */
451 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
452
453 /* True if CPU has seq/sne and seqi/snei instructions.  */
454 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
455
456 /* True, if CPU has support for ldc1 and sdc1. */
457 #define CPU_HAS_LDC1_SDC1(CPU)  \
458    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
459
460 /* True if mflo and mfhi can be immediately followed by instructions
461    which write to the HI and LO registers.
462
463    According to MIPS specifications, MIPS ISAs I, II, and III need
464    (at least) two instructions between the reads of HI/LO and
465    instructions which write them, and later ISAs do not.  Contradicting
466    the MIPS specifications, some MIPS IV processor user manuals (e.g.
467    the UM for the NEC Vr5000) document needing the instructions between
468    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
469    MIPS64 and later ISAs to have the interlocks, plus any specific
470    earlier-ISA CPUs for which CPU documentation declares that the
471    instructions are really interlocked.  */
472 #define hilo_interlocks \
473   (mips_opts.isa == ISA_MIPS32                        \
474    || mips_opts.isa == ISA_MIPS32R2                   \
475    || mips_opts.isa == ISA_MIPS64                     \
476    || mips_opts.isa == ISA_MIPS64R2                   \
477    || mips_opts.arch == CPU_R4010                     \
478    || mips_opts.arch == CPU_R5900                     \
479    || mips_opts.arch == CPU_R10000                    \
480    || mips_opts.arch == CPU_R12000                    \
481    || mips_opts.arch == CPU_R14000                    \
482    || mips_opts.arch == CPU_R16000                    \
483    || mips_opts.arch == CPU_RM7000                    \
484    || mips_opts.arch == CPU_VR5500                    \
485    || mips_opts.micromips                             \
486    )
487
488 /* Whether the processor uses hardware interlocks to protect reads
489    from the GPRs after they are loaded from memory, and thus does not
490    require nops to be inserted.  This applies to instructions marked
491    INSN_LOAD_MEMORY_DELAY.  These nops are only required at MIPS ISA
492    level I and microMIPS mode instructions are always interlocked.  */
493 #define gpr_interlocks                                \
494   (mips_opts.isa != ISA_MIPS1                         \
495    || mips_opts.arch == CPU_R3900                     \
496    || mips_opts.arch == CPU_R5900                     \
497    || mips_opts.micromips                             \
498    )
499
500 /* Whether the processor uses hardware interlocks to avoid delays
501    required by coprocessor instructions, and thus does not require
502    nops to be inserted.  This applies to instructions marked
503    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
504    between instructions marked INSN_WRITE_COND_CODE and ones marked
505    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
506    levels I, II, and III and microMIPS mode instructions are always
507    interlocked.  */
508 /* Itbl support may require additional care here.  */
509 #define cop_interlocks                                \
510   ((mips_opts.isa != ISA_MIPS1                        \
511     && mips_opts.isa != ISA_MIPS2                     \
512     && mips_opts.isa != ISA_MIPS3)                    \
513    || mips_opts.arch == CPU_R4300                     \
514    || mips_opts.micromips                             \
515    )
516
517 /* Whether the processor uses hardware interlocks to protect reads
518    from coprocessor registers after they are loaded from memory, and
519    thus does not require nops to be inserted.  This applies to
520    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
521    requires at MIPS ISA level I and microMIPS mode instructions are
522    always interlocked.  */
523 #define cop_mem_interlocks                            \
524   (mips_opts.isa != ISA_MIPS1                         \
525    || mips_opts.micromips                             \
526    )
527
528 /* Is this a mfhi or mflo instruction?  */
529 #define MF_HILO_INSN(PINFO) \
530   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
531
532 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
533    has been selected.  This implies, in particular, that addresses of text
534    labels have their LSB set.  */
535 #define HAVE_CODE_COMPRESSION                                           \
536   ((mips_opts.mips16 | mips_opts.micromips) != 0)
537
538 /* The minimum and maximum signed values that can be stored in a GPR.  */
539 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
540 #define GPR_SMIN (-GPR_SMAX - 1)
541
542 /* MIPS PIC level.  */
543
544 enum mips_pic_level mips_pic;
545
546 /* 1 if we should generate 32 bit offsets from the $gp register in
547    SVR4_PIC mode.  Currently has no meaning in other modes.  */
548 static int mips_big_got = 0;
549
550 /* 1 if trap instructions should used for overflow rather than break
551    instructions.  */
552 static int mips_trap = 0;
553
554 /* 1 if double width floating point constants should not be constructed
555    by assembling two single width halves into two single width floating
556    point registers which just happen to alias the double width destination
557    register.  On some architectures this aliasing can be disabled by a bit
558    in the status register, and the setting of this bit cannot be determined
559    automatically at assemble time.  */
560 static int mips_disable_float_construction;
561
562 /* Non-zero if any .set noreorder directives were used.  */
563
564 static int mips_any_noreorder;
565
566 /* Non-zero if nops should be inserted when the register referenced in
567    an mfhi/mflo instruction is read in the next two instructions.  */
568 static int mips_7000_hilo_fix;
569
570 /* The size of objects in the small data section.  */
571 static unsigned int g_switch_value = 8;
572 /* Whether the -G option was used.  */
573 static int g_switch_seen = 0;
574
575 #define N_RMASK 0xc4
576 #define N_VFP   0xd4
577
578 /* If we can determine in advance that GP optimization won't be
579    possible, we can skip the relaxation stuff that tries to produce
580    GP-relative references.  This makes delay slot optimization work
581    better.
582
583    This function can only provide a guess, but it seems to work for
584    gcc output.  It needs to guess right for gcc, otherwise gcc
585    will put what it thinks is a GP-relative instruction in a branch
586    delay slot.
587
588    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
589    fixed it for the non-PIC mode.  KR 95/04/07  */
590 static int nopic_need_relax (symbolS *, int);
591
592 /* handle of the OPCODE hash table */
593 static struct hash_control *op_hash = NULL;
594
595 /* The opcode hash table we use for the mips16.  */
596 static struct hash_control *mips16_op_hash = NULL;
597
598 /* The opcode hash table we use for the microMIPS ASE.  */
599 static struct hash_control *micromips_op_hash = NULL;
600
601 /* This array holds the chars that always start a comment.  If the
602     pre-processor is disabled, these aren't very useful */
603 const char comment_chars[] = "#";
604
605 /* This array holds the chars that only start a comment at the beginning of
606    a line.  If the line seems to have the form '# 123 filename'
607    .line and .file directives will appear in the pre-processed output */
608 /* Note that input_file.c hand checks for '#' at the beginning of the
609    first line of the input file.  This is because the compiler outputs
610    #NO_APP at the beginning of its output.  */
611 /* Also note that C style comments are always supported.  */
612 const char line_comment_chars[] = "#";
613
614 /* This array holds machine specific line separator characters.  */
615 const char line_separator_chars[] = ";";
616
617 /* Chars that can be used to separate mant from exp in floating point nums */
618 const char EXP_CHARS[] = "eE";
619
620 /* Chars that mean this number is a floating point constant */
621 /* As in 0f12.456 */
622 /* or    0d1.2345e12 */
623 const char FLT_CHARS[] = "rRsSfFdDxXpP";
624
625 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
626    changed in read.c .  Ideally it shouldn't have to know about it at all,
627    but nothing is ideal around here.
628  */
629
630 static char *insn_error;
631
632 static int auto_align = 1;
633
634 /* When outputting SVR4 PIC code, the assembler needs to know the
635    offset in the stack frame from which to restore the $gp register.
636    This is set by the .cprestore pseudo-op, and saved in this
637    variable.  */
638 static offsetT mips_cprestore_offset = -1;
639
640 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
641    more optimizations, it can use a register value instead of a memory-saved
642    offset and even an other register than $gp as global pointer.  */
643 static offsetT mips_cpreturn_offset = -1;
644 static int mips_cpreturn_register = -1;
645 static int mips_gp_register = GP;
646 static int mips_gprel_offset = 0;
647
648 /* Whether mips_cprestore_offset has been set in the current function
649    (or whether it has already been warned about, if not).  */
650 static int mips_cprestore_valid = 0;
651
652 /* This is the register which holds the stack frame, as set by the
653    .frame pseudo-op.  This is needed to implement .cprestore.  */
654 static int mips_frame_reg = SP;
655
656 /* Whether mips_frame_reg has been set in the current function
657    (or whether it has already been warned about, if not).  */
658 static int mips_frame_reg_valid = 0;
659
660 /* To output NOP instructions correctly, we need to keep information
661    about the previous two instructions.  */
662
663 /* Whether we are optimizing.  The default value of 2 means to remove
664    unneeded NOPs and swap branch instructions when possible.  A value
665    of 1 means to not swap branches.  A value of 0 means to always
666    insert NOPs.  */
667 static int mips_optimize = 2;
668
669 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
670    equivalent to seeing no -g option at all.  */
671 static int mips_debug = 0;
672
673 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
674 #define MAX_VR4130_NOPS 4
675
676 /* The maximum number of NOPs needed to fill delay slots.  */
677 #define MAX_DELAY_NOPS 2
678
679 /* The maximum number of NOPs needed for any purpose.  */
680 #define MAX_NOPS 4
681
682 /* A list of previous instructions, with index 0 being the most recent.
683    We need to look back MAX_NOPS instructions when filling delay slots
684    or working around processor errata.  We need to look back one
685    instruction further if we're thinking about using history[0] to
686    fill a branch delay slot.  */
687 static struct mips_cl_insn history[1 + MAX_NOPS];
688
689 /* Nop instructions used by emit_nop.  */
690 static struct mips_cl_insn nop_insn;
691 static struct mips_cl_insn mips16_nop_insn;
692 static struct mips_cl_insn micromips_nop16_insn;
693 static struct mips_cl_insn micromips_nop32_insn;
694
695 /* The appropriate nop for the current mode.  */
696 #define NOP_INSN (mips_opts.mips16                                      \
697                   ? &mips16_nop_insn                                    \
698                   : (mips_opts.micromips                                \
699                      ? (mips_opts.insn32                                \
700                         ? &micromips_nop32_insn                         \
701                         : &micromips_nop16_insn)                        \
702                      : &nop_insn))
703
704 /* The size of NOP_INSN in bytes.  */
705 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
706                         || (mips_opts.micromips && !mips_opts.insn32))  \
707                        ? 2 : 4)
708
709 /* If this is set, it points to a frag holding nop instructions which
710    were inserted before the start of a noreorder section.  If those
711    nops turn out to be unnecessary, the size of the frag can be
712    decreased.  */
713 static fragS *prev_nop_frag;
714
715 /* The number of nop instructions we created in prev_nop_frag.  */
716 static int prev_nop_frag_holds;
717
718 /* The number of nop instructions that we know we need in
719    prev_nop_frag.  */
720 static int prev_nop_frag_required;
721
722 /* The number of instructions we've seen since prev_nop_frag.  */
723 static int prev_nop_frag_since;
724
725 /* Relocations against symbols are sometimes done in two parts, with a HI
726    relocation and a LO relocation.  Each relocation has only 16 bits of
727    space to store an addend.  This means that in order for the linker to
728    handle carries correctly, it must be able to locate both the HI and
729    the LO relocation.  This means that the relocations must appear in
730    order in the relocation table.
731
732    In order to implement this, we keep track of each unmatched HI
733    relocation.  We then sort them so that they immediately precede the
734    corresponding LO relocation.  */
735
736 struct mips_hi_fixup
737 {
738   /* Next HI fixup.  */
739   struct mips_hi_fixup *next;
740   /* This fixup.  */
741   fixS *fixp;
742   /* The section this fixup is in.  */
743   segT seg;
744 };
745
746 /* The list of unmatched HI relocs.  */
747
748 static struct mips_hi_fixup *mips_hi_fixup_list;
749
750 /* The frag containing the last explicit relocation operator.
751    Null if explicit relocations have not been used.  */
752
753 static fragS *prev_reloc_op_frag;
754
755 /* Map normal MIPS register numbers to mips16 register numbers.  */
756
757 #define X ILLEGAL_REG
758 static const int mips32_to_16_reg_map[] =
759 {
760   X, X, 2, 3, 4, 5, 6, 7,
761   X, X, X, X, X, X, X, X,
762   0, 1, X, X, X, X, X, X,
763   X, X, X, X, X, X, X, X
764 };
765 #undef X
766
767 /* Map mips16 register numbers to normal MIPS register numbers.  */
768
769 static const unsigned int mips16_to_32_reg_map[] =
770 {
771   16, 17, 2, 3, 4, 5, 6, 7
772 };
773
774 /* Map normal MIPS register numbers to microMIPS register numbers.  */
775
776 #define mips32_to_micromips_reg_b_map   mips32_to_16_reg_map
777 #define mips32_to_micromips_reg_c_map   mips32_to_16_reg_map
778 #define mips32_to_micromips_reg_d_map   mips32_to_16_reg_map
779 #define mips32_to_micromips_reg_e_map   mips32_to_16_reg_map
780 #define mips32_to_micromips_reg_f_map   mips32_to_16_reg_map
781 #define mips32_to_micromips_reg_g_map   mips32_to_16_reg_map
782 #define mips32_to_micromips_reg_l_map   mips32_to_16_reg_map
783
784 #define X ILLEGAL_REG
785 /* reg type m: 0, 17, 2, 3, 16, 18, 19, 20.  */
786 static const int mips32_to_micromips_reg_m_map[] =
787 {
788   0, X, 2, 3, X, X, X, X,
789   X, X, X, X, X, X, X, X,
790   4, 1, 5, 6, 7, X, X, X,
791   X, X, X, X, X, X, X, X
792 };
793
794 /* reg type q: 0, 2-7. 17.  */
795 static const int mips32_to_micromips_reg_q_map[] =
796 {
797   0, X, 2, 3, 4, 5, 6, 7,
798   X, X, X, X, X, X, X, X,
799   X, 1, X, X, X, X, X, X,
800   X, X, X, X, X, X, X, X
801 };
802
803 #define mips32_to_micromips_reg_n_map  mips32_to_micromips_reg_m_map
804 #undef X
805
806 /* Map microMIPS register numbers to normal MIPS register numbers.  */
807
808 #define micromips_to_32_reg_b_map       mips16_to_32_reg_map
809 #define micromips_to_32_reg_c_map       mips16_to_32_reg_map
810 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
811 #define micromips_to_32_reg_e_map       mips16_to_32_reg_map
812 #define micromips_to_32_reg_f_map       mips16_to_32_reg_map
813 #define micromips_to_32_reg_g_map       mips16_to_32_reg_map
814
815 /* The microMIPS registers with type h.  */
816 static const unsigned int micromips_to_32_reg_h_map1[] =
817 {
818   5, 5, 6, 4, 4, 4, 4, 4
819 };
820 static const unsigned int micromips_to_32_reg_h_map2[] =
821 {
822   6, 7, 7, 21, 22, 5, 6, 7
823 };
824
825 #define micromips_to_32_reg_l_map       mips16_to_32_reg_map
826
827 /* The microMIPS registers with type m.  */
828 static const unsigned int micromips_to_32_reg_m_map[] =
829 {
830   0, 17, 2, 3, 16, 18, 19, 20
831 };
832
833 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
834
835 /* The microMIPS registers with type q.  */
836 static const unsigned int micromips_to_32_reg_q_map[] =
837 {
838   0, 17, 2, 3, 4, 5, 6, 7
839 };
840
841 /* microMIPS imm type B.  */
842 static const int micromips_imm_b_map[] =
843 {
844   1, 4, 8, 12, 16, 20, 24, -1
845 };
846
847 /* microMIPS imm type C.  */
848 static const int micromips_imm_c_map[] =
849 {
850   128, 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 255, 32768, 65535
851 };
852
853 /* Classifies the kind of instructions we're interested in when
854    implementing -mfix-vr4120.  */
855 enum fix_vr4120_class
856 {
857   FIX_VR4120_MACC,
858   FIX_VR4120_DMACC,
859   FIX_VR4120_MULT,
860   FIX_VR4120_DMULT,
861   FIX_VR4120_DIV,
862   FIX_VR4120_MTHILO,
863   NUM_FIX_VR4120_CLASSES
864 };
865
866 /* ...likewise -mfix-loongson2f-jump.  */
867 static bfd_boolean mips_fix_loongson2f_jump;
868
869 /* ...likewise -mfix-loongson2f-nop.  */
870 static bfd_boolean mips_fix_loongson2f_nop;
871
872 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
873 static bfd_boolean mips_fix_loongson2f;
874
875 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
876    there must be at least one other instruction between an instruction
877    of type X and an instruction of type Y.  */
878 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
879
880 /* True if -mfix-vr4120 is in force.  */
881 static int mips_fix_vr4120;
882
883 /* ...likewise -mfix-vr4130.  */
884 static int mips_fix_vr4130;
885
886 /* ...likewise -mfix-24k.  */
887 static int mips_fix_24k;
888
889 /* ...likewise -mfix-cn63xxp1 */
890 static bfd_boolean mips_fix_cn63xxp1;
891
892 /* We don't relax branches by default, since this causes us to expand
893    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
894    fail to compute the offset before expanding the macro to the most
895    efficient expansion.  */
896
897 static int mips_relax_branch;
898 \f
899 /* The expansion of many macros depends on the type of symbol that
900    they refer to.  For example, when generating position-dependent code,
901    a macro that refers to a symbol may have two different expansions,
902    one which uses GP-relative addresses and one which uses absolute
903    addresses.  When generating SVR4-style PIC, a macro may have
904    different expansions for local and global symbols.
905
906    We handle these situations by generating both sequences and putting
907    them in variant frags.  In position-dependent code, the first sequence
908    will be the GP-relative one and the second sequence will be the
909    absolute one.  In SVR4 PIC, the first sequence will be for global
910    symbols and the second will be for local symbols.
911
912    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
913    SECOND are the lengths of the two sequences in bytes.  These fields
914    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
915    the subtype has the following flags:
916
917    RELAX_USE_SECOND
918         Set if it has been decided that we should use the second
919         sequence instead of the first.
920
921    RELAX_SECOND_LONGER
922         Set in the first variant frag if the macro's second implementation
923         is longer than its first.  This refers to the macro as a whole,
924         not an individual relaxation.
925
926    RELAX_NOMACRO
927         Set in the first variant frag if the macro appeared in a .set nomacro
928         block and if one alternative requires a warning but the other does not.
929
930    RELAX_DELAY_SLOT
931         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
932         delay slot.
933
934    RELAX_DELAY_SLOT_16BIT
935         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
936         16-bit instruction.
937
938    RELAX_DELAY_SLOT_SIZE_FIRST
939         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
940         the macro is of the wrong size for the branch delay slot.
941
942    RELAX_DELAY_SLOT_SIZE_SECOND
943         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
944         the macro is of the wrong size for the branch delay slot.
945
946    The frag's "opcode" points to the first fixup for relaxable code.
947
948    Relaxable macros are generated using a sequence such as:
949
950       relax_start (SYMBOL);
951       ... generate first expansion ...
952       relax_switch ();
953       ... generate second expansion ...
954       relax_end ();
955
956    The code and fixups for the unwanted alternative are discarded
957    by md_convert_frag.  */
958 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
959
960 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
961 #define RELAX_SECOND(X) ((X) & 0xff)
962 #define RELAX_USE_SECOND 0x10000
963 #define RELAX_SECOND_LONGER 0x20000
964 #define RELAX_NOMACRO 0x40000
965 #define RELAX_DELAY_SLOT 0x80000
966 #define RELAX_DELAY_SLOT_16BIT 0x100000
967 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
968 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
969
970 /* Branch without likely bit.  If label is out of range, we turn:
971
972         beq reg1, reg2, label
973         delay slot
974
975    into
976
977         bne reg1, reg2, 0f
978         nop
979         j label
980      0: delay slot
981
982    with the following opcode replacements:
983
984         beq <-> bne
985         blez <-> bgtz
986         bltz <-> bgez
987         bc1f <-> bc1t
988
989         bltzal <-> bgezal  (with jal label instead of j label)
990
991    Even though keeping the delay slot instruction in the delay slot of
992    the branch would be more efficient, it would be very tricky to do
993    correctly, because we'd have to introduce a variable frag *after*
994    the delay slot instruction, and expand that instead.  Let's do it
995    the easy way for now, even if the branch-not-taken case now costs
996    one additional instruction.  Out-of-range branches are not supposed
997    to be common, anyway.
998
999    Branch likely.  If label is out of range, we turn:
1000
1001         beql reg1, reg2, label
1002         delay slot (annulled if branch not taken)
1003
1004    into
1005
1006         beql reg1, reg2, 1f
1007         nop
1008         beql $0, $0, 2f
1009         nop
1010      1: j[al] label
1011         delay slot (executed only if branch taken)
1012      2:
1013
1014    It would be possible to generate a shorter sequence by losing the
1015    likely bit, generating something like:
1016
1017         bne reg1, reg2, 0f
1018         nop
1019         j[al] label
1020         delay slot (executed only if branch taken)
1021      0:
1022
1023         beql -> bne
1024         bnel -> beq
1025         blezl -> bgtz
1026         bgtzl -> blez
1027         bltzl -> bgez
1028         bgezl -> bltz
1029         bc1fl -> bc1t
1030         bc1tl -> bc1f
1031
1032         bltzall -> bgezal  (with jal label instead of j label)
1033         bgezall -> bltzal  (ditto)
1034
1035
1036    but it's not clear that it would actually improve performance.  */
1037 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1038   ((relax_substateT)                                            \
1039    (0xc0000000                                                  \
1040     | ((at) & 0x1f)                                             \
1041     | ((toofar) ? 0x20 : 0)                                     \
1042     | ((link) ? 0x40 : 0)                                       \
1043     | ((likely) ? 0x80 : 0)                                     \
1044     | ((uncond) ? 0x100 : 0)))
1045 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1046 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1047 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1048 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1049 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1050 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1051
1052 /* For mips16 code, we use an entirely different form of relaxation.
1053    mips16 supports two versions of most instructions which take
1054    immediate values: a small one which takes some small value, and a
1055    larger one which takes a 16 bit value.  Since branches also follow
1056    this pattern, relaxing these values is required.
1057
1058    We can assemble both mips16 and normal MIPS code in a single
1059    object.  Therefore, we need to support this type of relaxation at
1060    the same time that we support the relaxation described above.  We
1061    use the high bit of the subtype field to distinguish these cases.
1062
1063    The information we store for this type of relaxation is the
1064    argument code found in the opcode file for this relocation, whether
1065    the user explicitly requested a small or extended form, and whether
1066    the relocation is in a jump or jal delay slot.  That tells us the
1067    size of the value, and how it should be stored.  We also store
1068    whether the fragment is considered to be extended or not.  We also
1069    store whether this is known to be a branch to a different section,
1070    whether we have tried to relax this frag yet, and whether we have
1071    ever extended a PC relative fragment because of a shift count.  */
1072 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1073   (0x80000000                                                   \
1074    | ((type) & 0xff)                                            \
1075    | ((small) ? 0x100 : 0)                                      \
1076    | ((ext) ? 0x200 : 0)                                        \
1077    | ((dslot) ? 0x400 : 0)                                      \
1078    | ((jal_dslot) ? 0x800 : 0))
1079 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1080 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1081 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1082 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1083 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1084 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1085 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1086 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1087 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1088 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1089 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1090 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1091
1092 /* For microMIPS code, we use relaxation similar to one we use for
1093    MIPS16 code.  Some instructions that take immediate values support
1094    two encodings: a small one which takes some small value, and a
1095    larger one which takes a 16 bit value.  As some branches also follow
1096    this pattern, relaxing these values is required.
1097
1098    We can assemble both microMIPS and normal MIPS code in a single
1099    object.  Therefore, we need to support this type of relaxation at
1100    the same time that we support the relaxation described above.  We
1101    use one of the high bits of the subtype field to distinguish these
1102    cases.
1103
1104    The information we store for this type of relaxation is the argument
1105    code found in the opcode file for this relocation, the register
1106    selected as the assembler temporary, whether the branch is
1107    unconditional, whether it is compact, whether it stores the link
1108    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1109    branches to a sequence of instructions is enabled, and whether the
1110    displacement of a branch is too large to fit as an immediate argument
1111    of a 16-bit and a 32-bit branch, respectively.  */
1112 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1113                                relax32, toofar16, toofar32)     \
1114   (0x40000000                                                   \
1115    | ((type) & 0xff)                                            \
1116    | (((at) & 0x1f) << 8)                                       \
1117    | ((uncond) ? 0x2000 : 0)                                    \
1118    | ((compact) ? 0x4000 : 0)                                   \
1119    | ((link) ? 0x8000 : 0)                                      \
1120    | ((relax32) ? 0x10000 : 0)                                  \
1121    | ((toofar16) ? 0x20000 : 0)                                 \
1122    | ((toofar32) ? 0x40000 : 0))
1123 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1124 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1125 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1126 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1127 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1128 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1129 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1130
1131 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1132 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1133 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1134 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1135 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1136 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1137
1138 /* Sign-extend 16-bit value X.  */
1139 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1140
1141 /* Is the given value a sign-extended 32-bit value?  */
1142 #define IS_SEXT_32BIT_NUM(x)                                            \
1143   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1144    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1145
1146 /* Is the given value a sign-extended 16-bit value?  */
1147 #define IS_SEXT_16BIT_NUM(x)                                            \
1148   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1149    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1150
1151 /* Is the given value a sign-extended 12-bit value?  */
1152 #define IS_SEXT_12BIT_NUM(x)                                            \
1153   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1154
1155 /* Is the given value a sign-extended 9-bit value?  */
1156 #define IS_SEXT_9BIT_NUM(x)                                             \
1157   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1158
1159 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1160 #define IS_ZEXT_32BIT_NUM(x)                                            \
1161   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1162    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1163
1164 /* Replace bits MASK << SHIFT of STRUCT with the equivalent bits in
1165    VALUE << SHIFT.  VALUE is evaluated exactly once.  */
1166 #define INSERT_BITS(STRUCT, VALUE, MASK, SHIFT) \
1167   (STRUCT) = (((STRUCT) & ~((MASK) << (SHIFT))) \
1168               | (((VALUE) & (MASK)) << (SHIFT)))
1169
1170 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1171    SHIFT places.  */
1172 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1173   (((STRUCT) >> (SHIFT)) & (MASK))
1174
1175 /* Change INSN's opcode so that the operand given by FIELD has value VALUE.
1176    INSN is a mips_cl_insn structure and VALUE is evaluated exactly once.
1177
1178    include/opcode/mips.h specifies operand fields using the macros
1179    OP_MASK_<FIELD> and OP_SH_<FIELD>.  The MIPS16 equivalents start
1180    with "MIPS16OP" instead of "OP".  */
1181 #define INSERT_OPERAND(MICROMIPS, FIELD, INSN, VALUE) \
1182   do \
1183     if (!(MICROMIPS)) \
1184       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1185                    OP_MASK_##FIELD, OP_SH_##FIELD); \
1186     else \
1187       INSERT_BITS ((INSN).insn_opcode, VALUE, \
1188                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD); \
1189   while (0)
1190 #define MIPS16_INSERT_OPERAND(FIELD, INSN, VALUE) \
1191   INSERT_BITS ((INSN).insn_opcode, VALUE, \
1192                 MIPS16OP_MASK_##FIELD, MIPS16OP_SH_##FIELD)
1193
1194 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1195 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1196   (!(MICROMIPS) \
1197    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1198    : EXTRACT_BITS ((INSN).insn_opcode, \
1199                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1200 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1201   EXTRACT_BITS ((INSN).insn_opcode, \
1202                 MIPS16OP_MASK_##FIELD, \
1203                 MIPS16OP_SH_##FIELD)
1204
1205 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1206 #define MIPS16_EXTEND (0xf000U << 16)
1207 \f
1208 /* Whether or not we are emitting a branch-likely macro.  */
1209 static bfd_boolean emit_branch_likely_macro = FALSE;
1210
1211 /* Global variables used when generating relaxable macros.  See the
1212    comment above RELAX_ENCODE for more details about how relaxation
1213    is used.  */
1214 static struct {
1215   /* 0 if we're not emitting a relaxable macro.
1216      1 if we're emitting the first of the two relaxation alternatives.
1217      2 if we're emitting the second alternative.  */
1218   int sequence;
1219
1220   /* The first relaxable fixup in the current frag.  (In other words,
1221      the first fixup that refers to relaxable code.)  */
1222   fixS *first_fixup;
1223
1224   /* sizes[0] says how many bytes of the first alternative are stored in
1225      the current frag.  Likewise sizes[1] for the second alternative.  */
1226   unsigned int sizes[2];
1227
1228   /* The symbol on which the choice of sequence depends.  */
1229   symbolS *symbol;
1230 } mips_relax;
1231 \f
1232 /* Global variables used to decide whether a macro needs a warning.  */
1233 static struct {
1234   /* True if the macro is in a branch delay slot.  */
1235   bfd_boolean delay_slot_p;
1236
1237   /* Set to the length in bytes required if the macro is in a delay slot
1238      that requires a specific length of instruction, otherwise zero.  */
1239   unsigned int delay_slot_length;
1240
1241   /* For relaxable macros, sizes[0] is the length of the first alternative
1242      in bytes and sizes[1] is the length of the second alternative.
1243      For non-relaxable macros, both elements give the length of the
1244      macro in bytes.  */
1245   unsigned int sizes[2];
1246
1247   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1248      instruction of the first alternative in bytes and first_insn_sizes[1]
1249      is the length of the first instruction of the second alternative.
1250      For non-relaxable macros, both elements give the length of the first
1251      instruction in bytes.
1252
1253      Set to zero if we haven't yet seen the first instruction.  */
1254   unsigned int first_insn_sizes[2];
1255
1256   /* For relaxable macros, insns[0] is the number of instructions for the
1257      first alternative and insns[1] is the number of instructions for the
1258      second alternative.
1259
1260      For non-relaxable macros, both elements give the number of
1261      instructions for the macro.  */
1262   unsigned int insns[2];
1263
1264   /* The first variant frag for this macro.  */
1265   fragS *first_frag;
1266 } mips_macro_warning;
1267 \f
1268 /* Prototypes for static functions.  */
1269
1270 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1271
1272 static void append_insn
1273   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1274    bfd_boolean expansionp);
1275 static void mips_no_prev_insn (void);
1276 static void macro_build (expressionS *, const char *, const char *, ...);
1277 static void mips16_macro_build
1278   (expressionS *, const char *, const char *, va_list *);
1279 static void load_register (int, expressionS *, int);
1280 static void macro_start (void);
1281 static void macro_end (void);
1282 static void macro (struct mips_cl_insn *ip, char *str);
1283 static void mips16_macro (struct mips_cl_insn * ip);
1284 static void mips_ip (char *str, struct mips_cl_insn * ip);
1285 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1286 static void mips16_immed
1287   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1288    unsigned int, unsigned long *);
1289 static size_t my_getSmallExpression
1290   (expressionS *, bfd_reloc_code_real_type *, char *);
1291 static void my_getExpression (expressionS *, char *);
1292 static void s_align (int);
1293 static void s_change_sec (int);
1294 static void s_change_section (int);
1295 static void s_cons (int);
1296 static void s_float_cons (int);
1297 static void s_mips_globl (int);
1298 static void s_option (int);
1299 static void s_mipsset (int);
1300 static void s_abicalls (int);
1301 static void s_cpload (int);
1302 static void s_cpsetup (int);
1303 static void s_cplocal (int);
1304 static void s_cprestore (int);
1305 static void s_cpreturn (int);
1306 static void s_dtprelword (int);
1307 static void s_dtpreldword (int);
1308 static void s_tprelword (int);
1309 static void s_tpreldword (int);
1310 static void s_gpvalue (int);
1311 static void s_gpword (int);
1312 static void s_gpdword (int);
1313 static void s_ehword (int);
1314 static void s_cpadd (int);
1315 static void s_insn (int);
1316 static void s_nan (int);
1317 static void md_obj_begin (void);
1318 static void md_obj_end (void);
1319 static void s_mips_ent (int);
1320 static void s_mips_end (int);
1321 static void s_mips_frame (int);
1322 static void s_mips_mask (int reg_type);
1323 static void s_mips_stab (int);
1324 static void s_mips_weakext (int);
1325 static void s_mips_file (int);
1326 static void s_mips_loc (int);
1327 static bfd_boolean pic_need_relax (symbolS *, asection *);
1328 static int relaxed_branch_length (fragS *, asection *, int);
1329 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1330 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1331
1332 /* Table and functions used to map between CPU/ISA names, and
1333    ISA levels, and CPU numbers.  */
1334
1335 struct mips_cpu_info
1336 {
1337   const char *name;           /* CPU or ISA name.  */
1338   int flags;                  /* MIPS_CPU_* flags.  */
1339   int ase;                    /* Set of ASEs implemented by the CPU.  */
1340   int isa;                    /* ISA level.  */
1341   int cpu;                    /* CPU number (default CPU if ISA).  */
1342 };
1343
1344 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1345
1346 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1347 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1348 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1349 \f
1350 /* Command-line options.  */
1351 const char *md_shortopts = "O::g::G:";
1352
1353 enum options
1354   {
1355     OPTION_MARCH = OPTION_MD_BASE,
1356     OPTION_MTUNE,
1357     OPTION_MIPS1,
1358     OPTION_MIPS2,
1359     OPTION_MIPS3,
1360     OPTION_MIPS4,
1361     OPTION_MIPS5,
1362     OPTION_MIPS32,
1363     OPTION_MIPS64,
1364     OPTION_MIPS32R2,
1365     OPTION_MIPS64R2,
1366     OPTION_MIPS16,
1367     OPTION_NO_MIPS16,
1368     OPTION_MIPS3D,
1369     OPTION_NO_MIPS3D,
1370     OPTION_MDMX,
1371     OPTION_NO_MDMX,
1372     OPTION_DSP,
1373     OPTION_NO_DSP,
1374     OPTION_MT,
1375     OPTION_NO_MT,
1376     OPTION_VIRT,
1377     OPTION_NO_VIRT,
1378     OPTION_SMARTMIPS,
1379     OPTION_NO_SMARTMIPS,
1380     OPTION_DSPR2,
1381     OPTION_NO_DSPR2,
1382     OPTION_EVA,
1383     OPTION_NO_EVA,
1384     OPTION_MICROMIPS,
1385     OPTION_NO_MICROMIPS,
1386     OPTION_MCU,
1387     OPTION_NO_MCU,
1388     OPTION_COMPAT_ARCH_BASE,
1389     OPTION_M4650,
1390     OPTION_NO_M4650,
1391     OPTION_M4010,
1392     OPTION_NO_M4010,
1393     OPTION_M4100,
1394     OPTION_NO_M4100,
1395     OPTION_M3900,
1396     OPTION_NO_M3900,
1397     OPTION_M7000_HILO_FIX,
1398     OPTION_MNO_7000_HILO_FIX,
1399     OPTION_FIX_24K,
1400     OPTION_NO_FIX_24K,
1401     OPTION_FIX_LOONGSON2F_JUMP,
1402     OPTION_NO_FIX_LOONGSON2F_JUMP,
1403     OPTION_FIX_LOONGSON2F_NOP,
1404     OPTION_NO_FIX_LOONGSON2F_NOP,
1405     OPTION_FIX_VR4120,
1406     OPTION_NO_FIX_VR4120,
1407     OPTION_FIX_VR4130,
1408     OPTION_NO_FIX_VR4130,
1409     OPTION_FIX_CN63XXP1,
1410     OPTION_NO_FIX_CN63XXP1,
1411     OPTION_TRAP,
1412     OPTION_BREAK,
1413     OPTION_EB,
1414     OPTION_EL,
1415     OPTION_FP32,
1416     OPTION_GP32,
1417     OPTION_CONSTRUCT_FLOATS,
1418     OPTION_NO_CONSTRUCT_FLOATS,
1419     OPTION_FP64,
1420     OPTION_GP64,
1421     OPTION_RELAX_BRANCH,
1422     OPTION_NO_RELAX_BRANCH,
1423     OPTION_INSN32,
1424     OPTION_NO_INSN32,
1425     OPTION_MSHARED,
1426     OPTION_MNO_SHARED,
1427     OPTION_MSYM32,
1428     OPTION_MNO_SYM32,
1429     OPTION_SOFT_FLOAT,
1430     OPTION_HARD_FLOAT,
1431     OPTION_SINGLE_FLOAT,
1432     OPTION_DOUBLE_FLOAT,
1433     OPTION_32,
1434     OPTION_CALL_SHARED,
1435     OPTION_CALL_NONPIC,
1436     OPTION_NON_SHARED,
1437     OPTION_XGOT,
1438     OPTION_MABI,
1439     OPTION_N32,
1440     OPTION_64,
1441     OPTION_MDEBUG,
1442     OPTION_NO_MDEBUG,
1443     OPTION_PDR,
1444     OPTION_NO_PDR,
1445     OPTION_MVXWORKS_PIC,
1446     OPTION_NAN,
1447     OPTION_END_OF_ENUM
1448   };
1449
1450 struct option md_longopts[] =
1451 {
1452   /* Options which specify architecture.  */
1453   {"march", required_argument, NULL, OPTION_MARCH},
1454   {"mtune", required_argument, NULL, OPTION_MTUNE},
1455   {"mips0", no_argument, NULL, OPTION_MIPS1},
1456   {"mips1", no_argument, NULL, OPTION_MIPS1},
1457   {"mips2", no_argument, NULL, OPTION_MIPS2},
1458   {"mips3", no_argument, NULL, OPTION_MIPS3},
1459   {"mips4", no_argument, NULL, OPTION_MIPS4},
1460   {"mips5", no_argument, NULL, OPTION_MIPS5},
1461   {"mips32", no_argument, NULL, OPTION_MIPS32},
1462   {"mips64", no_argument, NULL, OPTION_MIPS64},
1463   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1464   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1465
1466   /* Options which specify Application Specific Extensions (ASEs).  */
1467   {"mips16", no_argument, NULL, OPTION_MIPS16},
1468   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1469   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1470   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1471   {"mdmx", no_argument, NULL, OPTION_MDMX},
1472   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1473   {"mdsp", no_argument, NULL, OPTION_DSP},
1474   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1475   {"mmt", no_argument, NULL, OPTION_MT},
1476   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1477   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1478   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1479   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1480   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1481   {"meva", no_argument, NULL, OPTION_EVA},
1482   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1483   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1484   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1485   {"mmcu", no_argument, NULL, OPTION_MCU},
1486   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1487   {"mvirt", no_argument, NULL, OPTION_VIRT},
1488   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1489
1490   /* Old-style architecture options.  Don't add more of these.  */
1491   {"m4650", no_argument, NULL, OPTION_M4650},
1492   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1493   {"m4010", no_argument, NULL, OPTION_M4010},
1494   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1495   {"m4100", no_argument, NULL, OPTION_M4100},
1496   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1497   {"m3900", no_argument, NULL, OPTION_M3900},
1498   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1499
1500   /* Options which enable bug fixes.  */
1501   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1502   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1503   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1504   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1505   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1506   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1507   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1508   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1509   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1510   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1511   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1512   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1513   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1514   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1515   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1516
1517   /* Miscellaneous options.  */
1518   {"trap", no_argument, NULL, OPTION_TRAP},
1519   {"no-break", no_argument, NULL, OPTION_TRAP},
1520   {"break", no_argument, NULL, OPTION_BREAK},
1521   {"no-trap", no_argument, NULL, OPTION_BREAK},
1522   {"EB", no_argument, NULL, OPTION_EB},
1523   {"EL", no_argument, NULL, OPTION_EL},
1524   {"mfp32", no_argument, NULL, OPTION_FP32},
1525   {"mgp32", no_argument, NULL, OPTION_GP32},
1526   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1527   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1528   {"mfp64", no_argument, NULL, OPTION_FP64},
1529   {"mgp64", no_argument, NULL, OPTION_GP64},
1530   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1531   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1532   {"minsn32", no_argument, NULL, OPTION_INSN32},
1533   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1534   {"mshared", no_argument, NULL, OPTION_MSHARED},
1535   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1536   {"msym32", no_argument, NULL, OPTION_MSYM32},
1537   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1538   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1539   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1540   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1541   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1542
1543   /* Strictly speaking this next option is ELF specific,
1544      but we allow it for other ports as well in order to
1545      make testing easier.  */
1546   {"32", no_argument, NULL, OPTION_32},
1547
1548   /* ELF-specific options.  */
1549   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1550   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1551   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1552   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1553   {"xgot", no_argument, NULL, OPTION_XGOT},
1554   {"mabi", required_argument, NULL, OPTION_MABI},
1555   {"n32", no_argument, NULL, OPTION_N32},
1556   {"64", no_argument, NULL, OPTION_64},
1557   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1558   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1559   {"mpdr", no_argument, NULL, OPTION_PDR},
1560   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1561   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1562   {"mnan", required_argument, NULL, OPTION_NAN},
1563
1564   {NULL, no_argument, NULL, 0}
1565 };
1566 size_t md_longopts_size = sizeof (md_longopts);
1567 \f
1568 /* Information about either an Application Specific Extension or an
1569    optional architecture feature that, for simplicity, we treat in the
1570    same way as an ASE.  */
1571 struct mips_ase
1572 {
1573   /* The name of the ASE, used in both the command-line and .set options.  */
1574   const char *name;
1575
1576   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1577      and 64-bit architectures, the flags here refer to the subset that
1578      is available on both.  */
1579   unsigned int flags;
1580
1581   /* The ASE_* flag used for instructions that are available on 64-bit
1582      architectures but that are not included in FLAGS.  */
1583   unsigned int flags64;
1584
1585   /* The command-line options that turn the ASE on and off.  */
1586   int option_on;
1587   int option_off;
1588
1589   /* The minimum required architecture revisions for MIPS32, MIPS64,
1590      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1591   int mips32_rev;
1592   int mips64_rev;
1593   int micromips32_rev;
1594   int micromips64_rev;
1595 };
1596
1597 /* A table of all supported ASEs.  */
1598 static const struct mips_ase mips_ases[] = {
1599   { "dsp", ASE_DSP, ASE_DSP64,
1600     OPTION_DSP, OPTION_NO_DSP,
1601     2, 2, 2, 2 },
1602
1603   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1604     OPTION_DSPR2, OPTION_NO_DSPR2,
1605     2, 2, 2, 2 },
1606
1607   { "eva", ASE_EVA, 0,
1608     OPTION_EVA, OPTION_NO_EVA,
1609     2, 2, 2, 2 },
1610
1611   { "mcu", ASE_MCU, 0,
1612     OPTION_MCU, OPTION_NO_MCU,
1613     2, 2, 2, 2 },
1614
1615   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1616   { "mdmx", ASE_MDMX, 0,
1617     OPTION_MDMX, OPTION_NO_MDMX,
1618     -1, 1, -1, -1 },
1619
1620   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1621   { "mips3d", ASE_MIPS3D, 0,
1622     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1623     2, 1, -1, -1 },
1624
1625   { "mt", ASE_MT, 0,
1626     OPTION_MT, OPTION_NO_MT,
1627     2, 2, -1, -1 },
1628
1629   { "smartmips", ASE_SMARTMIPS, 0,
1630     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1631     1, -1, -1, -1 },
1632
1633   { "virt", ASE_VIRT, ASE_VIRT64,
1634     OPTION_VIRT, OPTION_NO_VIRT,
1635     2, 2, 2, 2 }
1636 };
1637
1638 /* The set of ASEs that require -mfp64.  */
1639 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1640
1641 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1642 static const unsigned int mips_ase_groups[] = {
1643   ASE_DSP | ASE_DSPR2
1644 };
1645 \f
1646 /* Pseudo-op table.
1647
1648    The following pseudo-ops from the Kane and Heinrich MIPS book
1649    should be defined here, but are currently unsupported: .alias,
1650    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1651
1652    The following pseudo-ops from the Kane and Heinrich MIPS book are
1653    specific to the type of debugging information being generated, and
1654    should be defined by the object format: .aent, .begin, .bend,
1655    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1656    .vreg.
1657
1658    The following pseudo-ops from the Kane and Heinrich MIPS book are
1659    not MIPS CPU specific, but are also not specific to the object file
1660    format.  This file is probably the best place to define them, but
1661    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1662
1663 static const pseudo_typeS mips_pseudo_table[] =
1664 {
1665   /* MIPS specific pseudo-ops.  */
1666   {"option", s_option, 0},
1667   {"set", s_mipsset, 0},
1668   {"rdata", s_change_sec, 'r'},
1669   {"sdata", s_change_sec, 's'},
1670   {"livereg", s_ignore, 0},
1671   {"abicalls", s_abicalls, 0},
1672   {"cpload", s_cpload, 0},
1673   {"cpsetup", s_cpsetup, 0},
1674   {"cplocal", s_cplocal, 0},
1675   {"cprestore", s_cprestore, 0},
1676   {"cpreturn", s_cpreturn, 0},
1677   {"dtprelword", s_dtprelword, 0},
1678   {"dtpreldword", s_dtpreldword, 0},
1679   {"tprelword", s_tprelword, 0},
1680   {"tpreldword", s_tpreldword, 0},
1681   {"gpvalue", s_gpvalue, 0},
1682   {"gpword", s_gpword, 0},
1683   {"gpdword", s_gpdword, 0},
1684   {"ehword", s_ehword, 0},
1685   {"cpadd", s_cpadd, 0},
1686   {"insn", s_insn, 0},
1687   {"nan", s_nan, 0},
1688
1689   /* Relatively generic pseudo-ops that happen to be used on MIPS
1690      chips.  */
1691   {"asciiz", stringer, 8 + 1},
1692   {"bss", s_change_sec, 'b'},
1693   {"err", s_err, 0},
1694   {"half", s_cons, 1},
1695   {"dword", s_cons, 3},
1696   {"weakext", s_mips_weakext, 0},
1697   {"origin", s_org, 0},
1698   {"repeat", s_rept, 0},
1699
1700   /* For MIPS this is non-standard, but we define it for consistency.  */
1701   {"sbss", s_change_sec, 'B'},
1702
1703   /* These pseudo-ops are defined in read.c, but must be overridden
1704      here for one reason or another.  */
1705   {"align", s_align, 0},
1706   {"byte", s_cons, 0},
1707   {"data", s_change_sec, 'd'},
1708   {"double", s_float_cons, 'd'},
1709   {"float", s_float_cons, 'f'},
1710   {"globl", s_mips_globl, 0},
1711   {"global", s_mips_globl, 0},
1712   {"hword", s_cons, 1},
1713   {"int", s_cons, 2},
1714   {"long", s_cons, 2},
1715   {"octa", s_cons, 4},
1716   {"quad", s_cons, 3},
1717   {"section", s_change_section, 0},
1718   {"short", s_cons, 1},
1719   {"single", s_float_cons, 'f'},
1720   {"stabd", s_mips_stab, 'd'},
1721   {"stabn", s_mips_stab, 'n'},
1722   {"stabs", s_mips_stab, 's'},
1723   {"text", s_change_sec, 't'},
1724   {"word", s_cons, 2},
1725
1726   { "extern", ecoff_directive_extern, 0},
1727
1728   { NULL, NULL, 0 },
1729 };
1730
1731 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1732 {
1733   /* These pseudo-ops should be defined by the object file format.
1734      However, a.out doesn't support them, so we have versions here.  */
1735   {"aent", s_mips_ent, 1},
1736   {"bgnb", s_ignore, 0},
1737   {"end", s_mips_end, 0},
1738   {"endb", s_ignore, 0},
1739   {"ent", s_mips_ent, 0},
1740   {"file", s_mips_file, 0},
1741   {"fmask", s_mips_mask, 'F'},
1742   {"frame", s_mips_frame, 0},
1743   {"loc", s_mips_loc, 0},
1744   {"mask", s_mips_mask, 'R'},
1745   {"verstamp", s_ignore, 0},
1746   { NULL, NULL, 0 },
1747 };
1748
1749 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1750    purpose of the `.dc.a' internal pseudo-op.  */
1751
1752 int
1753 mips_address_bytes (void)
1754 {
1755   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1756 }
1757
1758 extern void pop_insert (const pseudo_typeS *);
1759
1760 void
1761 mips_pop_insert (void)
1762 {
1763   pop_insert (mips_pseudo_table);
1764   if (! ECOFF_DEBUGGING)
1765     pop_insert (mips_nonecoff_pseudo_table);
1766 }
1767 \f
1768 /* Symbols labelling the current insn.  */
1769
1770 struct insn_label_list
1771 {
1772   struct insn_label_list *next;
1773   symbolS *label;
1774 };
1775
1776 static struct insn_label_list *free_insn_labels;
1777 #define label_list tc_segment_info_data.labels
1778
1779 static void mips_clear_insn_labels (void);
1780 static void mips_mark_labels (void);
1781 static void mips_compressed_mark_labels (void);
1782
1783 static inline void
1784 mips_clear_insn_labels (void)
1785 {
1786   register struct insn_label_list **pl;
1787   segment_info_type *si;
1788
1789   if (now_seg)
1790     {
1791       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1792         ;
1793       
1794       si = seg_info (now_seg);
1795       *pl = si->label_list;
1796       si->label_list = NULL;
1797     }
1798 }
1799
1800 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1801
1802 static inline void
1803 mips_mark_labels (void)
1804 {
1805   if (HAVE_CODE_COMPRESSION)
1806     mips_compressed_mark_labels ();
1807 }
1808 \f
1809 static char *expr_end;
1810
1811 /* Expressions which appear in macro instructions.  These are set by
1812    mips_ip and read by macro.  */
1813
1814 static expressionS imm_expr;
1815 static expressionS imm2_expr;
1816
1817 /* The relocatable field in an instruction and the relocs associated
1818    with it.  These variables are used for instructions like LUI and
1819    JAL as well as true offsets.  They are also used for address
1820    operands in macros.  */
1821
1822 static expressionS offset_expr;
1823 static bfd_reloc_code_real_type offset_reloc[3]
1824   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1825
1826 /* This is set to the resulting size of the instruction to be produced
1827    by mips16_ip if an explicit extension is used or by mips_ip if an
1828    explicit size is supplied.  */
1829
1830 static unsigned int forced_insn_length;
1831
1832 /* True if we are assembling an instruction.  All dot symbols defined during
1833    this time should be treated as code labels.  */
1834
1835 static bfd_boolean mips_assembling_insn;
1836
1837 /* The pdr segment for per procedure frame/regmask info.  Not used for
1838    ECOFF debugging.  */
1839
1840 static segT pdr_seg;
1841
1842 /* The default target format to use.  */
1843
1844 #if defined (TE_FreeBSD)
1845 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1846 #elif defined (TE_TMIPS)
1847 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1848 #else
1849 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1850 #endif
1851
1852 const char *
1853 mips_target_format (void)
1854 {
1855   switch (OUTPUT_FLAVOR)
1856     {
1857     case bfd_target_elf_flavour:
1858 #ifdef TE_VXWORKS
1859       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1860         return (target_big_endian
1861                 ? "elf32-bigmips-vxworks"
1862                 : "elf32-littlemips-vxworks");
1863 #endif
1864       return (target_big_endian
1865               ? (HAVE_64BIT_OBJECTS
1866                  ? ELF_TARGET ("elf64-", "big")
1867                  : (HAVE_NEWABI
1868                     ? ELF_TARGET ("elf32-n", "big")
1869                     : ELF_TARGET ("elf32-", "big")))
1870               : (HAVE_64BIT_OBJECTS
1871                  ? ELF_TARGET ("elf64-", "little")
1872                  : (HAVE_NEWABI
1873                     ? ELF_TARGET ("elf32-n", "little")
1874                     : ELF_TARGET ("elf32-", "little"))));
1875     default:
1876       abort ();
1877       return NULL;
1878     }
1879 }
1880
1881 /* Return the ISA revision that is currently in use, or 0 if we are
1882    generating code for MIPS V or below.  */
1883
1884 static int
1885 mips_isa_rev (void)
1886 {
1887   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1888     return 2;
1889
1890   /* microMIPS implies revision 2 or above.  */
1891   if (mips_opts.micromips)
1892     return 2;
1893
1894   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1895     return 1;
1896
1897   return 0;
1898 }
1899
1900 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1901
1902 static unsigned int
1903 mips_ase_mask (unsigned int flags)
1904 {
1905   unsigned int i;
1906
1907   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1908     if (flags & mips_ase_groups[i])
1909       flags |= mips_ase_groups[i];
1910   return flags;
1911 }
1912
1913 /* Check whether the current ISA supports ASE.  Issue a warning if
1914    appropriate.  */
1915
1916 static void
1917 mips_check_isa_supports_ase (const struct mips_ase *ase)
1918 {
1919   const char *base;
1920   int min_rev, size;
1921   static unsigned int warned_isa;
1922   static unsigned int warned_fp32;
1923
1924   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1925     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1926   else
1927     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1928   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1929       && (warned_isa & ase->flags) != ase->flags)
1930     {
1931       warned_isa |= ase->flags;
1932       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1933       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1934       if (min_rev < 0)
1935         as_warn (_("The %d-bit %s architecture does not support the"
1936                    " `%s' extension"), size, base, ase->name);
1937       else
1938         as_warn (_("The `%s' extension requires %s%d revision %d or greater"),
1939                  ase->name, base, size, min_rev);
1940     }
1941   if ((ase->flags & FP64_ASES)
1942       && mips_opts.fp32
1943       && (warned_fp32 & ase->flags) != ase->flags)
1944     {
1945       warned_fp32 |= ase->flags;
1946       as_warn (_("The `%s' extension requires 64-bit FPRs"), ase->name);
1947     }
1948 }
1949
1950 /* Check all enabled ASEs to see whether they are supported by the
1951    chosen architecture.  */
1952
1953 static void
1954 mips_check_isa_supports_ases (void)
1955 {
1956   unsigned int i, mask;
1957
1958   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1959     {
1960       mask = mips_ase_mask (mips_ases[i].flags);
1961       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1962         mips_check_isa_supports_ase (&mips_ases[i]);
1963     }
1964 }
1965
1966 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1967    that were affected.  */
1968
1969 static unsigned int
1970 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1971 {
1972   unsigned int mask;
1973
1974   mask = mips_ase_mask (ase->flags);
1975   mips_opts.ase &= ~mask;
1976   if (enabled_p)
1977     mips_opts.ase |= ase->flags;
1978   return mask;
1979 }
1980
1981 /* Return the ASE called NAME, or null if none.  */
1982
1983 static const struct mips_ase *
1984 mips_lookup_ase (const char *name)
1985 {
1986   unsigned int i;
1987
1988   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1989     if (strcmp (name, mips_ases[i].name) == 0)
1990       return &mips_ases[i];
1991   return NULL;
1992 }
1993
1994 /* Return the length of a microMIPS instruction in bytes.  If bits of
1995    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1996    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1997    major opcode) will require further modifications to the opcode
1998    table.  */
1999
2000 static inline unsigned int
2001 micromips_insn_length (const struct mips_opcode *mo)
2002 {
2003   return (mo->mask >> 16) == 0 ? 2 : 4;
2004 }
2005
2006 /* Return the length of MIPS16 instruction OPCODE.  */
2007
2008 static inline unsigned int
2009 mips16_opcode_length (unsigned long opcode)
2010 {
2011   return (opcode >> 16) == 0 ? 2 : 4;
2012 }
2013
2014 /* Return the length of instruction INSN.  */
2015
2016 static inline unsigned int
2017 insn_length (const struct mips_cl_insn *insn)
2018 {
2019   if (mips_opts.micromips)
2020     return micromips_insn_length (insn->insn_mo);
2021   else if (mips_opts.mips16)
2022     return mips16_opcode_length (insn->insn_opcode);
2023   else
2024     return 4;
2025 }
2026
2027 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2028
2029 static void
2030 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2031 {
2032   size_t i;
2033
2034   insn->insn_mo = mo;
2035   insn->insn_opcode = mo->match;
2036   insn->frag = NULL;
2037   insn->where = 0;
2038   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2039     insn->fixp[i] = NULL;
2040   insn->fixed_p = (mips_opts.noreorder > 0);
2041   insn->noreorder_p = (mips_opts.noreorder > 0);
2042   insn->mips16_absolute_jump_p = 0;
2043   insn->complete_p = 0;
2044   insn->cleared_p = 0;
2045 }
2046
2047 /* Install UVAL as the value of OPERAND in INSN.  */
2048
2049 static inline void
2050 insn_insert_operand (struct mips_cl_insn *insn,
2051                      const struct mips_operand *operand, unsigned int uval)
2052 {
2053   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2054 }
2055
2056 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2057
2058 static void
2059 mips_record_compressed_mode (void)
2060 {
2061   segment_info_type *si;
2062
2063   si = seg_info (now_seg);
2064   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2065     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2066   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2067     si->tc_segment_info_data.micromips = mips_opts.micromips;
2068 }
2069
2070 /* Read a standard MIPS instruction from BUF.  */
2071
2072 static unsigned long
2073 read_insn (char *buf)
2074 {
2075   if (target_big_endian)
2076     return bfd_getb32 ((bfd_byte *) buf);
2077   else
2078     return bfd_getl32 ((bfd_byte *) buf);
2079 }
2080
2081 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2082    the next byte.  */
2083
2084 static char *
2085 write_insn (char *buf, unsigned int insn)
2086 {
2087   md_number_to_chars (buf, insn, 4);
2088   return buf + 4;
2089 }
2090
2091 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2092    has length LENGTH.  */
2093
2094 static unsigned long
2095 read_compressed_insn (char *buf, unsigned int length)
2096 {
2097   unsigned long insn;
2098   unsigned int i;
2099
2100   insn = 0;
2101   for (i = 0; i < length; i += 2)
2102     {
2103       insn <<= 16;
2104       if (target_big_endian)
2105         insn |= bfd_getb16 ((char *) buf);
2106       else
2107         insn |= bfd_getl16 ((char *) buf);
2108       buf += 2;
2109     }
2110   return insn;
2111 }
2112
2113 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2114    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2115
2116 static char *
2117 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2118 {
2119   unsigned int i;
2120
2121   for (i = 0; i < length; i += 2)
2122     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2123   return buf + length;
2124 }
2125
2126 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2127
2128 static void
2129 install_insn (const struct mips_cl_insn *insn)
2130 {
2131   char *f = insn->frag->fr_literal + insn->where;
2132   if (HAVE_CODE_COMPRESSION)
2133     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2134   else
2135     write_insn (f, insn->insn_opcode);
2136   mips_record_compressed_mode ();
2137 }
2138
2139 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2140    and install the opcode in the new location.  */
2141
2142 static void
2143 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2144 {
2145   size_t i;
2146
2147   insn->frag = frag;
2148   insn->where = where;
2149   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2150     if (insn->fixp[i] != NULL)
2151       {
2152         insn->fixp[i]->fx_frag = frag;
2153         insn->fixp[i]->fx_where = where;
2154       }
2155   install_insn (insn);
2156 }
2157
2158 /* Add INSN to the end of the output.  */
2159
2160 static void
2161 add_fixed_insn (struct mips_cl_insn *insn)
2162 {
2163   char *f = frag_more (insn_length (insn));
2164   move_insn (insn, frag_now, f - frag_now->fr_literal);
2165 }
2166
2167 /* Start a variant frag and move INSN to the start of the variant part,
2168    marking it as fixed.  The other arguments are as for frag_var.  */
2169
2170 static void
2171 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2172                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2173 {
2174   frag_grow (max_chars);
2175   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2176   insn->fixed_p = 1;
2177   frag_var (rs_machine_dependent, max_chars, var,
2178             subtype, symbol, offset, NULL);
2179 }
2180
2181 /* Insert N copies of INSN into the history buffer, starting at
2182    position FIRST.  Neither FIRST nor N need to be clipped.  */
2183
2184 static void
2185 insert_into_history (unsigned int first, unsigned int n,
2186                      const struct mips_cl_insn *insn)
2187 {
2188   if (mips_relax.sequence != 2)
2189     {
2190       unsigned int i;
2191
2192       for (i = ARRAY_SIZE (history); i-- > first;)
2193         if (i >= first + n)
2194           history[i] = history[i - n];
2195         else
2196           history[i] = *insn;
2197     }
2198 }
2199
2200 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2201    the idea is to make it obvious at a glance that each errata is
2202    included.  */
2203
2204 static void
2205 init_vr4120_conflicts (void)
2206 {
2207 #define CONFLICT(FIRST, SECOND) \
2208     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2209
2210   /* Errata 21 - [D]DIV[U] after [D]MACC */
2211   CONFLICT (MACC, DIV);
2212   CONFLICT (DMACC, DIV);
2213
2214   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2215   CONFLICT (DMULT, DMULT);
2216   CONFLICT (DMULT, DMACC);
2217   CONFLICT (DMACC, DMULT);
2218   CONFLICT (DMACC, DMACC);
2219
2220   /* Errata 24 - MT{LO,HI} after [D]MACC */
2221   CONFLICT (MACC, MTHILO);
2222   CONFLICT (DMACC, MTHILO);
2223
2224   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2225      instruction is executed immediately after a MACC or DMACC
2226      instruction, the result of [either instruction] is incorrect."  */
2227   CONFLICT (MACC, MULT);
2228   CONFLICT (MACC, DMULT);
2229   CONFLICT (DMACC, MULT);
2230   CONFLICT (DMACC, DMULT);
2231
2232   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2233      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2234      DDIV or DDIVU instruction, the result of the MACC or
2235      DMACC instruction is incorrect.".  */
2236   CONFLICT (DMULT, MACC);
2237   CONFLICT (DMULT, DMACC);
2238   CONFLICT (DIV, MACC);
2239   CONFLICT (DIV, DMACC);
2240
2241 #undef CONFLICT
2242 }
2243
2244 struct regname {
2245   const char *name;
2246   unsigned int num;
2247 };
2248
2249 #define RTYPE_MASK      0x1ff00
2250 #define RTYPE_NUM       0x00100
2251 #define RTYPE_FPU       0x00200
2252 #define RTYPE_FCC       0x00400
2253 #define RTYPE_VEC       0x00800
2254 #define RTYPE_GP        0x01000
2255 #define RTYPE_CP0       0x02000
2256 #define RTYPE_PC        0x04000
2257 #define RTYPE_ACC       0x08000
2258 #define RTYPE_CCC       0x10000
2259 #define RNUM_MASK       0x000ff
2260 #define RWARN           0x80000
2261
2262 #define GENERIC_REGISTER_NUMBERS \
2263     {"$0",      RTYPE_NUM | 0},  \
2264     {"$1",      RTYPE_NUM | 1},  \
2265     {"$2",      RTYPE_NUM | 2},  \
2266     {"$3",      RTYPE_NUM | 3},  \
2267     {"$4",      RTYPE_NUM | 4},  \
2268     {"$5",      RTYPE_NUM | 5},  \
2269     {"$6",      RTYPE_NUM | 6},  \
2270     {"$7",      RTYPE_NUM | 7},  \
2271     {"$8",      RTYPE_NUM | 8},  \
2272     {"$9",      RTYPE_NUM | 9},  \
2273     {"$10",     RTYPE_NUM | 10}, \
2274     {"$11",     RTYPE_NUM | 11}, \
2275     {"$12",     RTYPE_NUM | 12}, \
2276     {"$13",     RTYPE_NUM | 13}, \
2277     {"$14",     RTYPE_NUM | 14}, \
2278     {"$15",     RTYPE_NUM | 15}, \
2279     {"$16",     RTYPE_NUM | 16}, \
2280     {"$17",     RTYPE_NUM | 17}, \
2281     {"$18",     RTYPE_NUM | 18}, \
2282     {"$19",     RTYPE_NUM | 19}, \
2283     {"$20",     RTYPE_NUM | 20}, \
2284     {"$21",     RTYPE_NUM | 21}, \
2285     {"$22",     RTYPE_NUM | 22}, \
2286     {"$23",     RTYPE_NUM | 23}, \
2287     {"$24",     RTYPE_NUM | 24}, \
2288     {"$25",     RTYPE_NUM | 25}, \
2289     {"$26",     RTYPE_NUM | 26}, \
2290     {"$27",     RTYPE_NUM | 27}, \
2291     {"$28",     RTYPE_NUM | 28}, \
2292     {"$29",     RTYPE_NUM | 29}, \
2293     {"$30",     RTYPE_NUM | 30}, \
2294     {"$31",     RTYPE_NUM | 31} 
2295
2296 #define FPU_REGISTER_NAMES       \
2297     {"$f0",     RTYPE_FPU | 0},  \
2298     {"$f1",     RTYPE_FPU | 1},  \
2299     {"$f2",     RTYPE_FPU | 2},  \
2300     {"$f3",     RTYPE_FPU | 3},  \
2301     {"$f4",     RTYPE_FPU | 4},  \
2302     {"$f5",     RTYPE_FPU | 5},  \
2303     {"$f6",     RTYPE_FPU | 6},  \
2304     {"$f7",     RTYPE_FPU | 7},  \
2305     {"$f8",     RTYPE_FPU | 8},  \
2306     {"$f9",     RTYPE_FPU | 9},  \
2307     {"$f10",    RTYPE_FPU | 10}, \
2308     {"$f11",    RTYPE_FPU | 11}, \
2309     {"$f12",    RTYPE_FPU | 12}, \
2310     {"$f13",    RTYPE_FPU | 13}, \
2311     {"$f14",    RTYPE_FPU | 14}, \
2312     {"$f15",    RTYPE_FPU | 15}, \
2313     {"$f16",    RTYPE_FPU | 16}, \
2314     {"$f17",    RTYPE_FPU | 17}, \
2315     {"$f18",    RTYPE_FPU | 18}, \
2316     {"$f19",    RTYPE_FPU | 19}, \
2317     {"$f20",    RTYPE_FPU | 20}, \
2318     {"$f21",    RTYPE_FPU | 21}, \
2319     {"$f22",    RTYPE_FPU | 22}, \
2320     {"$f23",    RTYPE_FPU | 23}, \
2321     {"$f24",    RTYPE_FPU | 24}, \
2322     {"$f25",    RTYPE_FPU | 25}, \
2323     {"$f26",    RTYPE_FPU | 26}, \
2324     {"$f27",    RTYPE_FPU | 27}, \
2325     {"$f28",    RTYPE_FPU | 28}, \
2326     {"$f29",    RTYPE_FPU | 29}, \
2327     {"$f30",    RTYPE_FPU | 30}, \
2328     {"$f31",    RTYPE_FPU | 31}
2329
2330 #define FPU_CONDITION_CODE_NAMES \
2331     {"$fcc0",   RTYPE_FCC | 0},  \
2332     {"$fcc1",   RTYPE_FCC | 1},  \
2333     {"$fcc2",   RTYPE_FCC | 2},  \
2334     {"$fcc3",   RTYPE_FCC | 3},  \
2335     {"$fcc4",   RTYPE_FCC | 4},  \
2336     {"$fcc5",   RTYPE_FCC | 5},  \
2337     {"$fcc6",   RTYPE_FCC | 6},  \
2338     {"$fcc7",   RTYPE_FCC | 7}
2339
2340 #define COPROC_CONDITION_CODE_NAMES         \
2341     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2342     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2343     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2344     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2345     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2346     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2347     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2348     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2349
2350 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2351     {"$a4",     RTYPE_GP | 8},  \
2352     {"$a5",     RTYPE_GP | 9},  \
2353     {"$a6",     RTYPE_GP | 10}, \
2354     {"$a7",     RTYPE_GP | 11}, \
2355     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2356     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2357     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2358     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2359     {"$t0",     RTYPE_GP | 12}, \
2360     {"$t1",     RTYPE_GP | 13}, \
2361     {"$t2",     RTYPE_GP | 14}, \
2362     {"$t3",     RTYPE_GP | 15}
2363
2364 #define O32_SYMBOLIC_REGISTER_NAMES \
2365     {"$t0",     RTYPE_GP | 8},  \
2366     {"$t1",     RTYPE_GP | 9},  \
2367     {"$t2",     RTYPE_GP | 10}, \
2368     {"$t3",     RTYPE_GP | 11}, \
2369     {"$t4",     RTYPE_GP | 12}, \
2370     {"$t5",     RTYPE_GP | 13}, \
2371     {"$t6",     RTYPE_GP | 14}, \
2372     {"$t7",     RTYPE_GP | 15}, \
2373     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2374     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2375     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2376     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2377
2378 /* Remaining symbolic register names */
2379 #define SYMBOLIC_REGISTER_NAMES \
2380     {"$zero",   RTYPE_GP | 0},  \
2381     {"$at",     RTYPE_GP | 1},  \
2382     {"$AT",     RTYPE_GP | 1},  \
2383     {"$v0",     RTYPE_GP | 2},  \
2384     {"$v1",     RTYPE_GP | 3},  \
2385     {"$a0",     RTYPE_GP | 4},  \
2386     {"$a1",     RTYPE_GP | 5},  \
2387     {"$a2",     RTYPE_GP | 6},  \
2388     {"$a3",     RTYPE_GP | 7},  \
2389     {"$s0",     RTYPE_GP | 16}, \
2390     {"$s1",     RTYPE_GP | 17}, \
2391     {"$s2",     RTYPE_GP | 18}, \
2392     {"$s3",     RTYPE_GP | 19}, \
2393     {"$s4",     RTYPE_GP | 20}, \
2394     {"$s5",     RTYPE_GP | 21}, \
2395     {"$s6",     RTYPE_GP | 22}, \
2396     {"$s7",     RTYPE_GP | 23}, \
2397     {"$t8",     RTYPE_GP | 24}, \
2398     {"$t9",     RTYPE_GP | 25}, \
2399     {"$k0",     RTYPE_GP | 26}, \
2400     {"$kt0",    RTYPE_GP | 26}, \
2401     {"$k1",     RTYPE_GP | 27}, \
2402     {"$kt1",    RTYPE_GP | 27}, \
2403     {"$gp",     RTYPE_GP | 28}, \
2404     {"$sp",     RTYPE_GP | 29}, \
2405     {"$s8",     RTYPE_GP | 30}, \
2406     {"$fp",     RTYPE_GP | 30}, \
2407     {"$ra",     RTYPE_GP | 31}
2408
2409 #define MIPS16_SPECIAL_REGISTER_NAMES \
2410     {"$pc",     RTYPE_PC | 0}
2411
2412 #define MDMX_VECTOR_REGISTER_NAMES \
2413     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2414     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2415     {"$v2",     RTYPE_VEC | 2},  \
2416     {"$v3",     RTYPE_VEC | 3},  \
2417     {"$v4",     RTYPE_VEC | 4},  \
2418     {"$v5",     RTYPE_VEC | 5},  \
2419     {"$v6",     RTYPE_VEC | 6},  \
2420     {"$v7",     RTYPE_VEC | 7},  \
2421     {"$v8",     RTYPE_VEC | 8},  \
2422     {"$v9",     RTYPE_VEC | 9},  \
2423     {"$v10",    RTYPE_VEC | 10}, \
2424     {"$v11",    RTYPE_VEC | 11}, \
2425     {"$v12",    RTYPE_VEC | 12}, \
2426     {"$v13",    RTYPE_VEC | 13}, \
2427     {"$v14",    RTYPE_VEC | 14}, \
2428     {"$v15",    RTYPE_VEC | 15}, \
2429     {"$v16",    RTYPE_VEC | 16}, \
2430     {"$v17",    RTYPE_VEC | 17}, \
2431     {"$v18",    RTYPE_VEC | 18}, \
2432     {"$v19",    RTYPE_VEC | 19}, \
2433     {"$v20",    RTYPE_VEC | 20}, \
2434     {"$v21",    RTYPE_VEC | 21}, \
2435     {"$v22",    RTYPE_VEC | 22}, \
2436     {"$v23",    RTYPE_VEC | 23}, \
2437     {"$v24",    RTYPE_VEC | 24}, \
2438     {"$v25",    RTYPE_VEC | 25}, \
2439     {"$v26",    RTYPE_VEC | 26}, \
2440     {"$v27",    RTYPE_VEC | 27}, \
2441     {"$v28",    RTYPE_VEC | 28}, \
2442     {"$v29",    RTYPE_VEC | 29}, \
2443     {"$v30",    RTYPE_VEC | 30}, \
2444     {"$v31",    RTYPE_VEC | 31}
2445
2446 #define MIPS_DSP_ACCUMULATOR_NAMES \
2447     {"$ac0",    RTYPE_ACC | 0}, \
2448     {"$ac1",    RTYPE_ACC | 1}, \
2449     {"$ac2",    RTYPE_ACC | 2}, \
2450     {"$ac3",    RTYPE_ACC | 3}
2451
2452 static const struct regname reg_names[] = {
2453   GENERIC_REGISTER_NUMBERS,
2454   FPU_REGISTER_NAMES,
2455   FPU_CONDITION_CODE_NAMES,
2456   COPROC_CONDITION_CODE_NAMES,
2457
2458   /* The $txx registers depends on the abi,
2459      these will be added later into the symbol table from
2460      one of the tables below once mips_abi is set after 
2461      parsing of arguments from the command line. */
2462   SYMBOLIC_REGISTER_NAMES,
2463
2464   MIPS16_SPECIAL_REGISTER_NAMES,
2465   MDMX_VECTOR_REGISTER_NAMES,
2466   MIPS_DSP_ACCUMULATOR_NAMES,
2467   {0, 0}
2468 };
2469
2470 static const struct regname reg_names_o32[] = {
2471   O32_SYMBOLIC_REGISTER_NAMES,
2472   {0, 0}
2473 };
2474
2475 static const struct regname reg_names_n32n64[] = {
2476   N32N64_SYMBOLIC_REGISTER_NAMES,
2477   {0, 0}
2478 };
2479
2480 /* Check if S points at a valid register specifier according to TYPES.
2481    If so, then return 1, advance S to consume the specifier and store
2482    the register's number in REGNOP, otherwise return 0.  */
2483
2484 static int
2485 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2486 {
2487   symbolS *symbolP;
2488   char *e;
2489   char save_c;
2490   int reg = -1;
2491
2492   /* Find end of name.  */
2493   e = *s;
2494   if (is_name_beginner (*e))
2495     ++e;
2496   while (is_part_of_name (*e))
2497     ++e;
2498
2499   /* Terminate name.  */
2500   save_c = *e;
2501   *e = '\0';
2502
2503   /* Look for a register symbol.  */
2504   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2505     {
2506       int r = S_GET_VALUE (symbolP);
2507       if (r & types)
2508         reg = r & RNUM_MASK;
2509       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2510         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2511         reg = (r & RNUM_MASK) - 2;
2512     }
2513   /* Else see if this is a register defined in an itbl entry.  */
2514   else if ((types & RTYPE_GP) && itbl_have_entries)
2515     {
2516       char *n = *s;
2517       unsigned long r;
2518
2519       if (*n == '$')
2520         ++n;
2521       if (itbl_get_reg_val (n, &r))
2522         reg = r & RNUM_MASK;
2523     }
2524
2525   /* Advance to next token if a register was recognised.  */
2526   if (reg >= 0)
2527     *s = e;
2528   else if (types & RWARN)
2529     as_warn (_("Unrecognized register name `%s'"), *s);
2530
2531   *e = save_c;
2532   if (regnop)
2533     *regnop = reg;
2534   return reg >= 0;
2535 }
2536
2537 /* Check if S points at a valid register list according to TYPES.
2538    If so, then return 1, advance S to consume the list and store
2539    the registers present on the list as a bitmask of ones in REGLISTP,
2540    otherwise return 0.  A valid list comprises a comma-separated
2541    enumeration of valid single registers and/or dash-separated
2542    contiguous register ranges as determined by their numbers.
2543
2544    As a special exception if one of s0-s7 registers is specified as
2545    the range's lower delimiter and s8 (fp) is its upper one, then no
2546    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2547    are selected; they have to be listed separately if needed.  */
2548
2549 static int
2550 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2551 {
2552   unsigned int reglist = 0;
2553   unsigned int lastregno;
2554   bfd_boolean ok = TRUE;
2555   unsigned int regmask;
2556   char *s_endlist = *s;
2557   char *s_reset = *s;
2558   unsigned int regno;
2559
2560   while (reg_lookup (s, types, &regno))
2561     {
2562       lastregno = regno;
2563       if (**s == '-')
2564         {
2565           (*s)++;
2566           ok = reg_lookup (s, types, &lastregno);
2567           if (ok && lastregno < regno)
2568             ok = FALSE;
2569           if (!ok)
2570             break;
2571         }
2572
2573       if (lastregno == FP && regno >= S0 && regno <= S7)
2574         {
2575           lastregno = S7;
2576           reglist |= 1 << FP;
2577         }
2578       regmask = 1 << lastregno;
2579       regmask = (regmask << 1) - 1;
2580       regmask ^= (1 << regno) - 1;
2581       reglist |= regmask;
2582
2583       s_endlist = *s;
2584       if (**s != ',')
2585         break;
2586       (*s)++;
2587     }
2588
2589   if (ok)
2590     *s = s_endlist;
2591   else
2592     *s = s_reset;
2593   if (reglistp)
2594     *reglistp = reglist;
2595   return ok && reglist != 0;
2596 }
2597
2598 static unsigned int
2599 mips_lookup_reg_pair (unsigned int regno1, unsigned int regno2,
2600                       const unsigned int *map1, const unsigned int *map2,
2601                       unsigned int count)
2602 {
2603   unsigned int i;
2604
2605   for (i = 0; i < count; i++)
2606     if (map1[i] == regno1 && map2[i] == regno2)
2607       return i;
2608   return ILLEGAL_REG;
2609 }
2610
2611 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2612    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2613
2614 static bfd_boolean
2615 is_opcode_valid (const struct mips_opcode *mo)
2616 {
2617   int isa = mips_opts.isa;
2618   int ase = mips_opts.ase;
2619   int fp_s, fp_d;
2620   unsigned int i;
2621
2622   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2623     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2624       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2625         ase |= mips_ases[i].flags64;
2626
2627   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2628     return FALSE;
2629
2630   /* Check whether the instruction or macro requires single-precision or
2631      double-precision floating-point support.  Note that this information is
2632      stored differently in the opcode table for insns and macros.  */
2633   if (mo->pinfo == INSN_MACRO)
2634     {
2635       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2636       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2637     }
2638   else
2639     {
2640       fp_s = mo->pinfo & FP_S;
2641       fp_d = mo->pinfo & FP_D;
2642     }
2643
2644   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2645     return FALSE;
2646
2647   if (fp_s && mips_opts.soft_float)
2648     return FALSE;
2649
2650   return TRUE;
2651 }
2652
2653 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2654    selected ISA and architecture.  */
2655
2656 static bfd_boolean
2657 is_opcode_valid_16 (const struct mips_opcode *mo)
2658 {
2659   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2660 }
2661
2662 /* Return TRUE if the size of the microMIPS opcode MO matches one
2663    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2664
2665 static bfd_boolean
2666 is_size_valid (const struct mips_opcode *mo)
2667 {
2668   if (!mips_opts.micromips)
2669     return TRUE;
2670
2671   if (mips_opts.insn32)
2672     {
2673       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2674         return FALSE;
2675       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2676         return FALSE;
2677     }
2678   if (!forced_insn_length)
2679     return TRUE;
2680   if (mo->pinfo == INSN_MACRO)
2681     return FALSE;
2682   return forced_insn_length == micromips_insn_length (mo);
2683 }
2684
2685 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2686    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2687
2688    We don't accept macros in 16-bit delay slots to avoid a case where
2689    a macro expansion fails because it relies on a preceding 32-bit real
2690    instruction to have matched and does not handle the operands correctly.
2691    The only macros that may expand to 16-bit instructions are JAL that
2692    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2693    and BGT (that likewise cannot be placed in a delay slot) that decay to
2694    a NOP.  In all these cases the macros precede any corresponding real
2695    instruction definitions in the opcode table, so they will match in the
2696    second pass where the size of the delay slot is ignored and therefore
2697    produce correct code.  */
2698
2699 static bfd_boolean
2700 is_delay_slot_valid (const struct mips_opcode *mo)
2701 {
2702   if (!mips_opts.micromips)
2703     return TRUE;
2704
2705   if (mo->pinfo == INSN_MACRO)
2706     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2707   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2708       && micromips_insn_length (mo) != 4)
2709     return FALSE;
2710   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2711       && micromips_insn_length (mo) != 2)
2712     return FALSE;
2713
2714   return TRUE;
2715 }
2716
2717 /* For consistency checking, verify that all bits of OPCODE are
2718    specified either by the match/mask part of the instruction
2719    definition, or by the operand list.  INSN_BITS says which
2720    bits of the instruction are significant and DECODE_OPERAND
2721    provides the mips_operand description of each operand.  */
2722
2723 static int
2724 validate_mips_insn (const struct mips_opcode *opcode,
2725                     unsigned long insn_bits,
2726                     const struct mips_operand *(*decode_operand) (const char *))
2727 {
2728   const char *s;
2729   unsigned long used_bits, doubled, undefined;
2730   const struct mips_operand *operand;
2731
2732   if ((opcode->mask & opcode->match) != opcode->match)
2733     {
2734       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
2735               opcode->name, opcode->args);
2736       return 0;
2737     }
2738   used_bits = 0;
2739   for (s = opcode->args; *s; ++s)
2740     switch (*s)
2741       {
2742       case ',':
2743       case '(':
2744       case ')':
2745         break;
2746
2747       default:
2748         operand = decode_operand (s);
2749         if (!operand)
2750           {
2751             as_bad (_("internal: unknown operand type: %s %s"),
2752                     opcode->name, opcode->args);
2753             return 0;
2754           }
2755         used_bits |= ((1 << operand->size) - 1) << operand->lsb;
2756         if (operand->type == OP_MDMX_IMM_REG)
2757           /* Bit 5 is the format selector (OB vs QH).  The opcode table
2758              has separate entries for each format.  */
2759           used_bits &= ~(1 << (operand->lsb + 5));
2760         /* Skip prefix characters.  */
2761         if (*s == '+' || *s == 'm')
2762           ++s;
2763         break;
2764       }
2765   doubled = used_bits & opcode->mask & insn_bits;
2766   if (doubled)
2767     {
2768       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
2769                 " %s %s"), doubled, opcode->name, opcode->args);
2770       return 0;
2771     }
2772   used_bits |= opcode->mask;
2773   undefined = ~used_bits & insn_bits;
2774   if (undefined)
2775     {
2776       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
2777               undefined, opcode->name, opcode->args);
2778       return 0;
2779     }
2780   used_bits &= ~insn_bits;
2781   if (used_bits)
2782     {
2783       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
2784               used_bits, opcode->name, opcode->args);
2785       return 0;
2786     }
2787   return 1;
2788 }
2789
2790 /* The microMIPS version of validate_mips_insn.  */
2791
2792 static int
2793 validate_micromips_insn (const struct mips_opcode *opc)
2794 {
2795   unsigned long insn_bits;
2796   unsigned long major;
2797   unsigned int length;
2798
2799   length = micromips_insn_length (opc);
2800   if (length != 2 && length != 4)
2801     {
2802       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
2803                 "%s %s"), length, opc->name, opc->args);
2804       return 0;
2805     }
2806   major = opc->match >> (10 + 8 * (length - 2));
2807   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
2808       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
2809     {
2810       as_bad (_("Internal error: bad microMIPS opcode "
2811                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
2812       return 0;
2813     }
2814
2815   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
2816   insn_bits = 1 << 4 * length;
2817   insn_bits <<= 4 * length;
2818   insn_bits -= 1;
2819   return validate_mips_insn (opc, insn_bits, decode_micromips_operand);
2820 }
2821
2822 /* This function is called once, at assembler startup time.  It should set up
2823    all the tables, etc. that the MD part of the assembler will need.  */
2824
2825 void
2826 md_begin (void)
2827 {
2828   const char *retval = NULL;
2829   int i = 0;
2830   int broken = 0;
2831
2832   if (mips_pic != NO_PIC)
2833     {
2834       if (g_switch_seen && g_switch_value != 0)
2835         as_bad (_("-G may not be used in position-independent code"));
2836       g_switch_value = 0;
2837     }
2838
2839   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2840     as_warn (_("Could not set architecture and machine"));
2841
2842   op_hash = hash_new ();
2843
2844   for (i = 0; i < NUMOPCODES;)
2845     {
2846       const char *name = mips_opcodes[i].name;
2847
2848       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2849       if (retval != NULL)
2850         {
2851           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2852                    mips_opcodes[i].name, retval);
2853           /* Probably a memory allocation problem?  Give up now.  */
2854           as_fatal (_("Broken assembler.  No assembly attempted."));
2855         }
2856       do
2857         {
2858           if (mips_opcodes[i].pinfo != INSN_MACRO)
2859             {
2860               if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
2861                                        decode_mips_operand))
2862                 broken = 1;
2863               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2864                 {
2865                   create_insn (&nop_insn, mips_opcodes + i);
2866                   if (mips_fix_loongson2f_nop)
2867                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2868                   nop_insn.fixed_p = 1;
2869                 }
2870             }
2871           ++i;
2872         }
2873       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2874     }
2875
2876   mips16_op_hash = hash_new ();
2877
2878   i = 0;
2879   while (i < bfd_mips16_num_opcodes)
2880     {
2881       const char *name = mips16_opcodes[i].name;
2882
2883       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2884       if (retval != NULL)
2885         as_fatal (_("internal: can't hash `%s': %s"),
2886                   mips16_opcodes[i].name, retval);
2887       do
2888         {
2889           if (mips16_opcodes[i].pinfo != INSN_MACRO
2890               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2891                   != mips16_opcodes[i].match))
2892             {
2893               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2894                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2895               broken = 1;
2896             }
2897           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2898             {
2899               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2900               mips16_nop_insn.fixed_p = 1;
2901             }
2902           ++i;
2903         }
2904       while (i < bfd_mips16_num_opcodes
2905              && strcmp (mips16_opcodes[i].name, name) == 0);
2906     }
2907
2908   micromips_op_hash = hash_new ();
2909
2910   i = 0;
2911   while (i < bfd_micromips_num_opcodes)
2912     {
2913       const char *name = micromips_opcodes[i].name;
2914
2915       retval = hash_insert (micromips_op_hash, name,
2916                             (void *) &micromips_opcodes[i]);
2917       if (retval != NULL)
2918         as_fatal (_("internal: can't hash `%s': %s"),
2919                   micromips_opcodes[i].name, retval);
2920       do
2921         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2922           {
2923             struct mips_cl_insn *micromips_nop_insn;
2924
2925             if (!validate_micromips_insn (&micromips_opcodes[i]))
2926               broken = 1;
2927
2928             if (micromips_insn_length (micromips_opcodes + i) == 2)
2929               micromips_nop_insn = &micromips_nop16_insn;
2930             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2931               micromips_nop_insn = &micromips_nop32_insn;
2932             else
2933               continue;
2934
2935             if (micromips_nop_insn->insn_mo == NULL
2936                 && strcmp (name, "nop") == 0)
2937               {
2938                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2939                 micromips_nop_insn->fixed_p = 1;
2940               }
2941           }
2942       while (++i < bfd_micromips_num_opcodes
2943              && strcmp (micromips_opcodes[i].name, name) == 0);
2944     }
2945
2946   if (broken)
2947     as_fatal (_("Broken assembler.  No assembly attempted."));
2948
2949   /* We add all the general register names to the symbol table.  This
2950      helps us detect invalid uses of them.  */
2951   for (i = 0; reg_names[i].name; i++) 
2952     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2953                                      reg_names[i].num, /* & RNUM_MASK, */
2954                                      &zero_address_frag));
2955   if (HAVE_NEWABI)
2956     for (i = 0; reg_names_n32n64[i].name; i++) 
2957       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2958                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2959                                        &zero_address_frag));
2960   else
2961     for (i = 0; reg_names_o32[i].name; i++) 
2962       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2963                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2964                                        &zero_address_frag));
2965
2966   mips_no_prev_insn ();
2967
2968   mips_gprmask = 0;
2969   mips_cprmask[0] = 0;
2970   mips_cprmask[1] = 0;
2971   mips_cprmask[2] = 0;
2972   mips_cprmask[3] = 0;
2973
2974   /* set the default alignment for the text section (2**2) */
2975   record_alignment (text_section, 2);
2976
2977   bfd_set_gp_size (stdoutput, g_switch_value);
2978
2979   /* On a native system other than VxWorks, sections must be aligned
2980      to 16 byte boundaries.  When configured for an embedded ELF
2981      target, we don't bother.  */
2982   if (strncmp (TARGET_OS, "elf", 3) != 0
2983       && strncmp (TARGET_OS, "vxworks", 7) != 0)
2984     {
2985       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2986       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2987       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2988     }
2989
2990   /* Create a .reginfo section for register masks and a .mdebug
2991      section for debugging information.  */
2992   {
2993     segT seg;
2994     subsegT subseg;
2995     flagword flags;
2996     segT sec;
2997
2998     seg = now_seg;
2999     subseg = now_subseg;
3000
3001     /* The ABI says this section should be loaded so that the
3002        running program can access it.  However, we don't load it
3003        if we are configured for an embedded target */
3004     flags = SEC_READONLY | SEC_DATA;
3005     if (strncmp (TARGET_OS, "elf", 3) != 0)
3006       flags |= SEC_ALLOC | SEC_LOAD;
3007
3008     if (mips_abi != N64_ABI)
3009       {
3010         sec = subseg_new (".reginfo", (subsegT) 0);
3011
3012         bfd_set_section_flags (stdoutput, sec, flags);
3013         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3014
3015         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3016       }
3017     else
3018       {
3019         /* The 64-bit ABI uses a .MIPS.options section rather than
3020            .reginfo section.  */
3021         sec = subseg_new (".MIPS.options", (subsegT) 0);
3022         bfd_set_section_flags (stdoutput, sec, flags);
3023         bfd_set_section_alignment (stdoutput, sec, 3);
3024
3025         /* Set up the option header.  */
3026         {
3027           Elf_Internal_Options opthdr;
3028           char *f;
3029
3030           opthdr.kind = ODK_REGINFO;
3031           opthdr.size = (sizeof (Elf_External_Options)
3032                          + sizeof (Elf64_External_RegInfo));
3033           opthdr.section = 0;
3034           opthdr.info = 0;
3035           f = frag_more (sizeof (Elf_External_Options));
3036           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3037                                          (Elf_External_Options *) f);
3038
3039           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3040         }
3041       }
3042
3043     if (ECOFF_DEBUGGING)
3044       {
3045         sec = subseg_new (".mdebug", (subsegT) 0);
3046         (void) bfd_set_section_flags (stdoutput, sec,
3047                                       SEC_HAS_CONTENTS | SEC_READONLY);
3048         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3049       }
3050     else if (mips_flag_pdr)
3051       {
3052         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3053         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3054                                       SEC_READONLY | SEC_RELOC
3055                                       | SEC_DEBUGGING);
3056         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3057       }
3058
3059     subseg_set (seg, subseg);
3060   }
3061
3062   if (! ECOFF_DEBUGGING)
3063     md_obj_begin ();
3064
3065   if (mips_fix_vr4120)
3066     init_vr4120_conflicts ();
3067 }
3068
3069 void
3070 md_mips_end (void)
3071 {
3072   mips_emit_delays ();
3073   if (! ECOFF_DEBUGGING)
3074     md_obj_end ();
3075 }
3076
3077 void
3078 md_assemble (char *str)
3079 {
3080   struct mips_cl_insn insn;
3081   bfd_reloc_code_real_type unused_reloc[3]
3082     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3083
3084   imm_expr.X_op = O_absent;
3085   imm2_expr.X_op = O_absent;
3086   offset_expr.X_op = O_absent;
3087   offset_reloc[0] = BFD_RELOC_UNUSED;
3088   offset_reloc[1] = BFD_RELOC_UNUSED;
3089   offset_reloc[2] = BFD_RELOC_UNUSED;
3090
3091   mips_mark_labels ();
3092   mips_assembling_insn = TRUE;
3093
3094   if (mips_opts.mips16)
3095     mips16_ip (str, &insn);
3096   else
3097     {
3098       mips_ip (str, &insn);
3099       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3100             str, insn.insn_opcode));
3101     }
3102
3103   if (insn_error)
3104     as_bad ("%s `%s'", insn_error, str);
3105   else if (insn.insn_mo->pinfo == INSN_MACRO)
3106     {
3107       macro_start ();
3108       if (mips_opts.mips16)
3109         mips16_macro (&insn);
3110       else
3111         macro (&insn, str);
3112       macro_end ();
3113     }
3114   else
3115     {
3116       if (offset_expr.X_op != O_absent)
3117         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3118       else
3119         append_insn (&insn, NULL, unused_reloc, FALSE);
3120     }
3121
3122   mips_assembling_insn = FALSE;
3123 }
3124
3125 /* Convenience functions for abstracting away the differences between
3126    MIPS16 and non-MIPS16 relocations.  */
3127
3128 static inline bfd_boolean
3129 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3130 {
3131   switch (reloc)
3132     {
3133     case BFD_RELOC_MIPS16_JMP:
3134     case BFD_RELOC_MIPS16_GPREL:
3135     case BFD_RELOC_MIPS16_GOT16:
3136     case BFD_RELOC_MIPS16_CALL16:
3137     case BFD_RELOC_MIPS16_HI16_S:
3138     case BFD_RELOC_MIPS16_HI16:
3139     case BFD_RELOC_MIPS16_LO16:
3140       return TRUE;
3141
3142     default:
3143       return FALSE;
3144     }
3145 }
3146
3147 static inline bfd_boolean
3148 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3149 {
3150   switch (reloc)
3151     {
3152     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3153     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3154     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3155     case BFD_RELOC_MICROMIPS_GPREL16:
3156     case BFD_RELOC_MICROMIPS_JMP:
3157     case BFD_RELOC_MICROMIPS_HI16:
3158     case BFD_RELOC_MICROMIPS_HI16_S:
3159     case BFD_RELOC_MICROMIPS_LO16:
3160     case BFD_RELOC_MICROMIPS_LITERAL:
3161     case BFD_RELOC_MICROMIPS_GOT16:
3162     case BFD_RELOC_MICROMIPS_CALL16:
3163     case BFD_RELOC_MICROMIPS_GOT_HI16:
3164     case BFD_RELOC_MICROMIPS_GOT_LO16:
3165     case BFD_RELOC_MICROMIPS_CALL_HI16:
3166     case BFD_RELOC_MICROMIPS_CALL_LO16:
3167     case BFD_RELOC_MICROMIPS_SUB:
3168     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3169     case BFD_RELOC_MICROMIPS_GOT_OFST:
3170     case BFD_RELOC_MICROMIPS_GOT_DISP:
3171     case BFD_RELOC_MICROMIPS_HIGHEST:
3172     case BFD_RELOC_MICROMIPS_HIGHER:
3173     case BFD_RELOC_MICROMIPS_SCN_DISP:
3174     case BFD_RELOC_MICROMIPS_JALR:
3175       return TRUE;
3176
3177     default:
3178       return FALSE;
3179     }
3180 }
3181
3182 static inline bfd_boolean
3183 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3184 {
3185   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3186 }
3187
3188 static inline bfd_boolean
3189 got16_reloc_p (bfd_reloc_code_real_type reloc)
3190 {
3191   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3192           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3193 }
3194
3195 static inline bfd_boolean
3196 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3197 {
3198   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3199           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3200 }
3201
3202 static inline bfd_boolean
3203 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3204 {
3205   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3206           || reloc == BFD_RELOC_MICROMIPS_LO16);
3207 }
3208
3209 static inline bfd_boolean
3210 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3211 {
3212   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3213 }
3214
3215 static inline bfd_boolean
3216 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3217 {
3218   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3219           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3220 }
3221
3222 /* Return true if RELOC is a PC-relative relocation that does not have
3223    full address range.  */
3224
3225 static inline bfd_boolean
3226 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3227 {
3228   switch (reloc)
3229     {
3230     case BFD_RELOC_16_PCREL_S2:
3231     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3232     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3233     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3234       return TRUE;
3235
3236     case BFD_RELOC_32_PCREL:
3237       return HAVE_64BIT_ADDRESSES;
3238
3239     default:
3240       return FALSE;
3241     }
3242 }
3243
3244 /* Return true if the given relocation might need a matching %lo().
3245    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3246    need a matching %lo() when applied to local symbols.  */
3247
3248 static inline bfd_boolean
3249 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3250 {
3251   return (HAVE_IN_PLACE_ADDENDS
3252           && (hi16_reloc_p (reloc)
3253               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3254                  all GOT16 relocations evaluate to "G".  */
3255               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3256 }
3257
3258 /* Return the type of %lo() reloc needed by RELOC, given that
3259    reloc_needs_lo_p.  */
3260
3261 static inline bfd_reloc_code_real_type
3262 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3263 {
3264   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3265           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3266              : BFD_RELOC_LO16));
3267 }
3268
3269 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3270    relocation.  */
3271
3272 static inline bfd_boolean
3273 fixup_has_matching_lo_p (fixS *fixp)
3274 {
3275   return (fixp->fx_next != NULL
3276           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3277           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3278           && fixp->fx_offset == fixp->fx_next->fx_offset);
3279 }
3280
3281 /* This function returns true if modifying a register requires a
3282    delay.  */
3283
3284 static int
3285 reg_needs_delay (unsigned int reg)
3286 {
3287   unsigned long prev_pinfo;
3288
3289   prev_pinfo = history[0].insn_mo->pinfo;
3290   if (! mips_opts.noreorder
3291       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3292            && ! gpr_interlocks)
3293           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3294               && ! cop_interlocks)))
3295     {
3296       /* A load from a coprocessor or from memory.  All load delays
3297          delay the use of general register rt for one instruction.  */
3298       /* Itbl support may require additional care here.  */
3299       know (prev_pinfo & INSN_WRITE_GPR_T);
3300       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3301         return 1;
3302     }
3303
3304   return 0;
3305 }
3306
3307 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3308    says whether the labels refer to text or data.  */
3309
3310 static void
3311 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3312 {
3313   struct insn_label_list *l;
3314   valueT val;
3315
3316   for (l = labels; l != NULL; l = l->next)
3317     {
3318       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3319       symbol_set_frag (l->label, frag_now);
3320       val = (valueT) frag_now_fix ();
3321       /* MIPS16/microMIPS text labels are stored as odd.  */
3322       if (text_p && HAVE_CODE_COMPRESSION)
3323         ++val;
3324       S_SET_VALUE (l->label, val);
3325     }
3326 }
3327
3328 /* Move all labels in insn_labels to the current insertion point
3329    and treat them as text labels.  */
3330
3331 static void
3332 mips_move_text_labels (void)
3333 {
3334   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3335 }
3336
3337 static bfd_boolean
3338 s_is_linkonce (symbolS *sym, segT from_seg)
3339 {
3340   bfd_boolean linkonce = FALSE;
3341   segT symseg = S_GET_SEGMENT (sym);
3342
3343   if (symseg != from_seg && !S_IS_LOCAL (sym))
3344     {
3345       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3346         linkonce = TRUE;
3347       /* The GNU toolchain uses an extension for ELF: a section
3348          beginning with the magic string .gnu.linkonce is a
3349          linkonce section.  */
3350       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3351                    sizeof ".gnu.linkonce" - 1) == 0)
3352         linkonce = TRUE;
3353     }
3354   return linkonce;
3355 }
3356
3357 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3358    linker to handle them specially, such as generating jalx instructions
3359    when needed.  We also make them odd for the duration of the assembly,
3360    in order to generate the right sort of code.  We will make them even
3361    in the adjust_symtab routine, while leaving them marked.  This is
3362    convenient for the debugger and the disassembler.  The linker knows
3363    to make them odd again.  */
3364
3365 static void
3366 mips_compressed_mark_label (symbolS *label)
3367 {
3368   gas_assert (HAVE_CODE_COMPRESSION);
3369
3370   if (mips_opts.mips16)
3371     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3372   else
3373     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3374   if ((S_GET_VALUE (label) & 1) == 0
3375       /* Don't adjust the address if the label is global or weak, or
3376          in a link-once section, since we'll be emitting symbol reloc
3377          references to it which will be patched up by the linker, and
3378          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3379       && !S_IS_WEAK (label)
3380       && !S_IS_EXTERNAL (label)
3381       && !s_is_linkonce (label, now_seg))
3382     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3383 }
3384
3385 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3386
3387 static void
3388 mips_compressed_mark_labels (void)
3389 {
3390   struct insn_label_list *l;
3391
3392   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3393     mips_compressed_mark_label (l->label);
3394 }
3395
3396 /* End the current frag.  Make it a variant frag and record the
3397    relaxation info.  */
3398
3399 static void
3400 relax_close_frag (void)
3401 {
3402   mips_macro_warning.first_frag = frag_now;
3403   frag_var (rs_machine_dependent, 0, 0,
3404             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3405             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3406
3407   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3408   mips_relax.first_fixup = 0;
3409 }
3410
3411 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3412    See the comment above RELAX_ENCODE for more details.  */
3413
3414 static void
3415 relax_start (symbolS *symbol)
3416 {
3417   gas_assert (mips_relax.sequence == 0);
3418   mips_relax.sequence = 1;
3419   mips_relax.symbol = symbol;
3420 }
3421
3422 /* Start generating the second version of a relaxable sequence.
3423    See the comment above RELAX_ENCODE for more details.  */
3424
3425 static void
3426 relax_switch (void)
3427 {
3428   gas_assert (mips_relax.sequence == 1);
3429   mips_relax.sequence = 2;
3430 }
3431
3432 /* End the current relaxable sequence.  */
3433
3434 static void
3435 relax_end (void)
3436 {
3437   gas_assert (mips_relax.sequence == 2);
3438   relax_close_frag ();
3439   mips_relax.sequence = 0;
3440 }
3441
3442 /* Return true if IP is a delayed branch or jump.  */
3443
3444 static inline bfd_boolean
3445 delayed_branch_p (const struct mips_cl_insn *ip)
3446 {
3447   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3448                                 | INSN_COND_BRANCH_DELAY
3449                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3450 }
3451
3452 /* Return true if IP is a compact branch or jump.  */
3453
3454 static inline bfd_boolean
3455 compact_branch_p (const struct mips_cl_insn *ip)
3456 {
3457   if (mips_opts.mips16)
3458     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3459                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3460   else
3461     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3462                                    | INSN2_COND_BRANCH)) != 0;
3463 }
3464
3465 /* Return true if IP is an unconditional branch or jump.  */
3466
3467 static inline bfd_boolean
3468 uncond_branch_p (const struct mips_cl_insn *ip)
3469 {
3470   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3471           || (mips_opts.mips16
3472               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3473               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3474 }
3475
3476 /* Return true if IP is a branch-likely instruction.  */
3477
3478 static inline bfd_boolean
3479 branch_likely_p (const struct mips_cl_insn *ip)
3480 {
3481   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3482 }
3483
3484 /* Return the type of nop that should be used to fill the delay slot
3485    of delayed branch IP.  */
3486
3487 static struct mips_cl_insn *
3488 get_delay_slot_nop (const struct mips_cl_insn *ip)
3489 {
3490   if (mips_opts.micromips
3491       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3492     return &micromips_nop32_insn;
3493   return NOP_INSN;
3494 }
3495
3496 /* Return the mask of core registers that IP reads or writes.  */
3497
3498 static unsigned int
3499 gpr_mod_mask (const struct mips_cl_insn *ip)
3500 {
3501   unsigned long pinfo2;
3502   unsigned int mask;
3503
3504   mask = 0;
3505   pinfo2 = ip->insn_mo->pinfo2;
3506   if (mips_opts.micromips)
3507     {
3508       if (pinfo2 & INSN2_MOD_GPR_MD)
3509         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3510       if (pinfo2 & INSN2_MOD_GPR_MF)
3511         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3512       if (pinfo2 & INSN2_MOD_SP)
3513         mask |= 1 << SP;
3514     }
3515   return mask;
3516 }
3517
3518 /* Return the mask of core registers that IP reads.  */
3519
3520 static unsigned int
3521 gpr_read_mask (const struct mips_cl_insn *ip)
3522 {
3523   unsigned long pinfo, pinfo2;
3524   unsigned int mask;
3525
3526   mask = gpr_mod_mask (ip);
3527   pinfo = ip->insn_mo->pinfo;
3528   pinfo2 = ip->insn_mo->pinfo2;
3529   if (mips_opts.mips16)
3530     {
3531       if (pinfo & MIPS16_INSN_READ_X)
3532         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3533       if (pinfo & MIPS16_INSN_READ_Y)
3534         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3535       if (pinfo & MIPS16_INSN_READ_T)
3536         mask |= 1 << TREG;
3537       if (pinfo & MIPS16_INSN_READ_SP)
3538         mask |= 1 << SP;
3539       if (pinfo & MIPS16_INSN_READ_31)
3540         mask |= 1 << RA;
3541       if (pinfo & MIPS16_INSN_READ_Z)
3542         mask |= 1 << (mips16_to_32_reg_map
3543                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3544       if (pinfo & MIPS16_INSN_READ_GPR_X)
3545         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3546     }
3547   else
3548     {
3549       if (pinfo2 & INSN2_READ_GPR_D)
3550         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3551       if (pinfo & INSN_READ_GPR_T)
3552         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3553       if (pinfo & INSN_READ_GPR_S)
3554         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3555       if (pinfo2 & INSN2_READ_GP)
3556         mask |= 1 << GP;
3557       if (pinfo2 & INSN2_READ_GPR_31)
3558         mask |= 1 << RA;
3559       if (pinfo2 & INSN2_READ_GPR_Z)
3560         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3561     }
3562   if (mips_opts.micromips)
3563     {
3564       if (pinfo2 & INSN2_READ_GPR_MC)
3565         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3566       if (pinfo2 & INSN2_READ_GPR_ME)
3567         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3568       if (pinfo2 & INSN2_READ_GPR_MG)
3569         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3570       if (pinfo2 & INSN2_READ_GPR_MJ)
3571         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3572       if (pinfo2 & INSN2_READ_GPR_MMN)
3573         {
3574           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3575           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3576         }
3577       if (pinfo2 & INSN2_READ_GPR_MP)
3578         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3579       if (pinfo2 & INSN2_READ_GPR_MQ)
3580         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3581     }
3582   /* Don't include register 0.  */
3583   return mask & ~1;
3584 }
3585
3586 /* Return the mask of core registers that IP writes.  */
3587
3588 static unsigned int
3589 gpr_write_mask (const struct mips_cl_insn *ip)
3590 {
3591   unsigned long pinfo, pinfo2;
3592   unsigned int mask;
3593
3594   mask = gpr_mod_mask (ip);
3595   pinfo = ip->insn_mo->pinfo;
3596   pinfo2 = ip->insn_mo->pinfo2;
3597   if (mips_opts.mips16)
3598     {
3599       if (pinfo & MIPS16_INSN_WRITE_X)
3600         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3601       if (pinfo & MIPS16_INSN_WRITE_Y)
3602         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3603       if (pinfo & MIPS16_INSN_WRITE_Z)
3604         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3605       if (pinfo & MIPS16_INSN_WRITE_T)
3606         mask |= 1 << TREG;
3607       if (pinfo & MIPS16_INSN_WRITE_SP)
3608         mask |= 1 << SP;
3609       if (pinfo & MIPS16_INSN_WRITE_31)
3610         mask |= 1 << RA;
3611       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3612         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3613     }
3614   else
3615     {
3616       if (pinfo & INSN_WRITE_GPR_D)
3617         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3618       if (pinfo & INSN_WRITE_GPR_T)
3619         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3620       if (pinfo & INSN_WRITE_GPR_S)
3621         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3622       if (pinfo & INSN_WRITE_GPR_31)
3623         mask |= 1 << RA;
3624       if (pinfo2 & INSN2_WRITE_GPR_Z)
3625         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3626     }
3627   if (mips_opts.micromips)
3628     {
3629       if (pinfo2 & INSN2_WRITE_GPR_MB)
3630         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3631       if (pinfo2 & INSN2_WRITE_GPR_MH)
3632         {
3633           mask |= 1 << micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
3634           mask |= 1 << micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
3635         }
3636       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3637         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3638       if (pinfo2 & INSN2_WRITE_GPR_MP)
3639         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3640     }
3641   /* Don't include register 0.  */
3642   return mask & ~1;
3643 }
3644
3645 /* Return the mask of floating-point registers that IP reads.  */
3646
3647 static unsigned int
3648 fpr_read_mask (const struct mips_cl_insn *ip)
3649 {
3650   unsigned long pinfo, pinfo2;
3651   unsigned int mask;
3652
3653   mask = 0;
3654   pinfo = ip->insn_mo->pinfo;
3655   pinfo2 = ip->insn_mo->pinfo2;
3656   if (!mips_opts.mips16)
3657     {
3658       if (pinfo2 & INSN2_READ_FPR_D)
3659         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3660       if (pinfo & INSN_READ_FPR_S)
3661         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3662       if (pinfo & INSN_READ_FPR_T)
3663         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3664       if (pinfo & INSN_READ_FPR_R)
3665         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3666       if (pinfo2 & INSN2_READ_FPR_Z)
3667         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3668     }
3669   /* Conservatively treat all operands to an FP_D instruction are doubles.
3670      (This is overly pessimistic for things like cvt.d.s.)  */
3671   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3672     mask |= mask << 1;
3673   return mask;
3674 }
3675
3676 /* Return the mask of floating-point registers that IP writes.  */
3677
3678 static unsigned int
3679 fpr_write_mask (const struct mips_cl_insn *ip)
3680 {
3681   unsigned long pinfo, pinfo2;
3682   unsigned int mask;
3683
3684   mask = 0;
3685   pinfo = ip->insn_mo->pinfo;
3686   pinfo2 = ip->insn_mo->pinfo2;
3687   if (!mips_opts.mips16)
3688     {
3689       if (pinfo & INSN_WRITE_FPR_D)
3690         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3691       if (pinfo & INSN_WRITE_FPR_S)
3692         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3693       if (pinfo & INSN_WRITE_FPR_T)
3694         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3695       if (pinfo2 & INSN2_WRITE_FPR_Z)
3696         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3697     }
3698   /* Conservatively treat all operands to an FP_D instruction are doubles.
3699      (This is overly pessimistic for things like cvt.s.d.)  */
3700   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3701     mask |= mask << 1;
3702   return mask;
3703 }
3704
3705 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
3706    Check whether that is allowed.  */
3707
3708 static bfd_boolean
3709 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
3710 {
3711   const char *s = insn->name;
3712
3713   if (insn->pinfo == INSN_MACRO)
3714     /* Let a macro pass, we'll catch it later when it is expanded.  */
3715     return TRUE;
3716
3717   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
3718     {
3719       /* Allow odd registers for single-precision ops.  */
3720       switch (insn->pinfo & (FP_S | FP_D))
3721         {
3722         case FP_S:
3723         case 0:
3724           return TRUE;
3725         case FP_D:
3726           return FALSE;
3727         default:
3728           break;
3729         }
3730
3731       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
3732       s = strchr (insn->name, '.');
3733       if (s != NULL && opnum == 2)
3734         s = strchr (s + 1, '.');
3735       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
3736     }
3737
3738   /* Single-precision coprocessor loads and moves are OK too.  */
3739   if ((insn->pinfo & FP_S)
3740       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
3741                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
3742     return TRUE;
3743
3744   return FALSE;
3745 }
3746
3747 #if 0
3748 /* Report that user-supplied argument ARGNUM for INSN was VAL, but should
3749    have been in the range [MIN_VAL, MAX_VAL].  PRINT_HEX says whether
3750    this operand is normally printed in hex or decimal.  */
3751
3752 static void
3753 report_bad_range (struct mips_cl_insn *insn, int argnum,
3754                   offsetT val, int min_val, int max_val,
3755                   bfd_boolean print_hex)
3756 {
3757   if (print_hex && val >= 0)
3758     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3759               " was 0x%lx."),
3760             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3761   else if (print_hex)
3762     as_bad (_("Operand %d of `%s' must be in the range [0x%x, 0x%x],"
3763               " was %ld."),
3764             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3765   else
3766     as_bad (_("Operand %d of `%s' must be in the range [%d, %d],"
3767               " was %ld."),
3768             argnum, insn->insn_mo->name, min_val, max_val, (unsigned long) val);
3769 }
3770
3771 /* Report an invalid combination of position and size operands for a bitfield
3772    operation.  POS and SIZE are the values that were given.  */
3773
3774 static void
3775 report_bad_field (offsetT pos, offsetT size)
3776 {
3777   as_bad (_("Invalid field specification (position %ld, size %ld)"),
3778           (unsigned long) pos, (unsigned long) size);
3779 }
3780
3781 /* Information about an instruction argument that we're trying to match.  */
3782 struct mips_arg_info
3783 {
3784   /* The instruction so far.  */
3785   struct mips_cl_insn *insn;
3786
3787   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
3788   int opnum;
3789
3790   /* The 1-based argument number, for error reporting.  This does not
3791      count elided optional registers, etc..  */
3792   int argnum;
3793
3794   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
3795   unsigned int last_regno;
3796
3797   /* If the first operand was an OP_REG, this is the register that it
3798      specified, otherwise it is ILLEGAL_REG.  */
3799   unsigned int dest_regno;
3800
3801   /* The value of the last OP_INT operand.  Only used for OP_MSB,
3802      where it gives the lsb position.  */
3803   unsigned int last_op_int;
3804
3805   /* If true, match routines should silently reject invalid arguments.
3806      If false, match routines can accept invalid arguments as long as
3807      they report an appropriate error.  They still have the option of
3808      silently rejecting arguments, in which case a generic "Invalid operands"
3809      style of error will be used instead.  */
3810   bfd_boolean soft_match;
3811
3812   /* If true, the OP_INT match routine should treat plain symbolic operands
3813      as if a relocation operator like %lo(...) had been used.  This is only
3814      ever true if the operand can be relocated.  */
3815   bfd_boolean allow_nonconst;
3816
3817   /* When true, the OP_INT match routine should allow unsigned N-bit
3818      arguments to be used where a signed N-bit operand is expected.  */
3819   bfd_boolean lax_max;
3820
3821   /* When true, the OP_REG match routine should assume that another operand
3822      appears after this one.  It should fail the match if the register it
3823      sees is at the end of the argument list.  */
3824   bfd_boolean optional_reg;
3825
3826   /* True if a reference to the current AT register was seen.  */
3827   bfd_boolean seen_at;
3828 };
3829
3830 /* Match a constant integer at S for ARG.  Return null if the match failed.
3831    Otherwise return the end of the matched string and store the constant value
3832    in *VALUE.  In the latter case, use FALLBACK as the value if the match
3833    succeeded with an error.  */
3834
3835 static char *
3836 match_const_int (struct mips_arg_info *arg, char *s, offsetT *value,
3837                  offsetT fallback)
3838 {
3839   expressionS ex;
3840   bfd_reloc_code_real_type r[3];
3841   int num_relocs;
3842
3843   num_relocs = my_getSmallExpression (&ex, r, s);
3844   if (*s == '(' && ex.X_op == O_register)
3845     {
3846       /* Assume that the constant has been elided and that S is a base
3847          register.  The rest of the match will fail if the assumption
3848          turns out to be wrong.  */
3849       *value = 0;
3850       return s;
3851     }
3852
3853   if (num_relocs == 0 && ex.X_op == O_constant)
3854     *value = ex.X_add_number;
3855   else
3856     {
3857       /* If we got a register rather than an expression, the default
3858          "Invalid operands" style of error seems more appropriate.  */
3859       if (arg->soft_match || ex.X_op == O_register)
3860         return 0;
3861       as_bad (_("Operand %d of `%s' must be constant"),
3862               arg->argnum, arg->insn->insn_mo->name);
3863       *value = fallback;
3864     }
3865   return expr_end;
3866 }
3867
3868 /* Return the RTYPE_* flags for a register operand of type TYPE that
3869    appears in instruction OPCODE.  */
3870
3871 static unsigned int
3872 convert_reg_type (const struct mips_opcode *opcode,
3873                   enum mips_reg_operand_type type)
3874 {
3875   switch (type)
3876     {
3877     case OP_REG_GP:
3878       return RTYPE_NUM | RTYPE_GP;
3879
3880     case OP_REG_FP:
3881       /* Allow vector register names for MDMX if the instruction is a 64-bit
3882          FPR load, store or move (including moves to and from GPRs).  */
3883       if ((mips_opts.ase & ASE_MDMX)
3884           && (opcode->pinfo & FP_D)
3885           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
3886                                | INSN_COPROC_MEMORY_DELAY
3887                                | INSN_LOAD_COPROC_DELAY
3888                                | INSN_LOAD_MEMORY_DELAY
3889                                | INSN_STORE_MEMORY)))
3890         return RTYPE_FPU | RTYPE_VEC;
3891       return RTYPE_FPU;
3892
3893     case OP_REG_CCC:
3894       if (opcode->pinfo & (FP_D | FP_S))
3895         return RTYPE_CCC | RTYPE_FCC;
3896       return RTYPE_CCC;
3897
3898     case OP_REG_VEC:
3899       if (opcode->membership & INSN_5400)
3900         return RTYPE_FPU;
3901       return RTYPE_FPU | RTYPE_VEC;
3902
3903     case OP_REG_ACC:
3904       return RTYPE_ACC;
3905
3906     case OP_REG_COPRO:
3907       if (opcode->name[strlen (opcode->name) - 1] == '0')
3908         return RTYPE_NUM | RTYPE_CP0;
3909       return RTYPE_NUM;
3910
3911     case OP_REG_HW:
3912       return RTYPE_NUM;
3913     }
3914   abort ();
3915 }
3916
3917 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
3918
3919 static void
3920 check_regno (struct mips_arg_info *arg,
3921              enum mips_reg_operand_type type, unsigned int regno)
3922 {
3923   if (AT && type == OP_REG_GP && regno == AT)
3924     arg->seen_at = TRUE;
3925
3926   if (type == OP_REG_FP
3927       && (regno & 1) != 0
3928       && HAVE_32BIT_FPRS
3929       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
3930     as_warn (_("Float register should be even, was %d"), regno);
3931
3932   if (type == OP_REG_CCC)
3933     {
3934       const char *name;
3935       size_t length;
3936
3937       name = arg->insn->insn_mo->name;
3938       length = strlen (name);
3939       if ((regno & 1) != 0
3940           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
3941               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
3942         as_warn (_("Condition code register should be even for %s, was %d"),
3943                  name, regno);
3944
3945       if ((regno & 3) != 0
3946           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
3947         as_warn (_("Condition code register should be 0 or 4 for %s, was %d"),
3948                  name, regno);
3949     }
3950 }
3951
3952 /* OP_INT matcher.  */
3953
3954 static char *
3955 match_int_operand (struct mips_arg_info *arg,
3956                    const struct mips_operand *operand_base, char *s)
3957 {
3958   const struct mips_int_operand *operand;
3959   unsigned int uval, mask;
3960   int min_val, max_val, factor;
3961   offsetT sval;
3962   bfd_boolean print_hex;
3963
3964   operand = (const struct mips_int_operand *) operand_base;
3965   factor = 1 << operand->shift;
3966   mask = (1 << operand_base->size) - 1;
3967   max_val = (operand->max_val + operand->bias) << operand->shift;
3968   min_val = max_val - (mask << operand->shift);
3969   if (arg->lax_max)
3970     max_val = mask << operand->shift;
3971
3972   if (operand_base->lsb == 0
3973       && operand_base->size == 16
3974       && operand->shift == 0
3975       && operand->bias == 0
3976       && (operand->max_val == 32767 || operand->max_val == 65535))
3977     {
3978       /* The operand can be relocated.  */
3979       offset_reloc[0] = BFD_RELOC_LO16;
3980       offset_reloc[1] = BFD_RELOC_UNUSED;
3981       offset_reloc[2] = BFD_RELOC_UNUSED;
3982       if (my_getSmallExpression (&offset_expr, offset_reloc, s) > 0)
3983         /* Relocation operators were used.  Accept the arguent and
3984            leave the relocation value in offset_expr and offset_relocs
3985            for the caller to process.  */
3986         return expr_end;
3987       if (*s == '(' && offset_expr.X_op == O_register)
3988         /* Assume that the constant has been elided and that S is a base
3989            register.  The rest of the match will fail if the assumption
3990            turns out to be wrong.  */
3991         sval = 0;
3992       else
3993         {
3994           s = expr_end;
3995           if (offset_expr.X_op != O_constant)
3996             /* If non-constant operands are allowed then leave them for
3997                the caller to process, otherwise fail the match.  */
3998             return arg->allow_nonconst ? s : 0;
3999           sval = offset_expr.X_add_number;
4000         }
4001       /* Clear the global state; we're going to install the operand
4002          ourselves.  */
4003       offset_reloc[0] = BFD_RELOC_UNUSED;
4004       offset_expr.X_op = O_absent;
4005     }
4006   else
4007     {
4008       s = match_const_int (arg, s, &sval, min_val);
4009       if (!s)
4010         return 0;
4011     }
4012
4013   arg->last_op_int = sval;
4014
4015   /* Check the range.  If there's a problem, record the lowest acceptable
4016      value in arg->last_op_int in order to prevent an unhelpful error
4017      from OP_MSB too.
4018
4019      Bit counts have traditionally been printed in hex by the disassembler
4020      but printed as decimal in error messages.  Only resort to hex if
4021      the operand is bigger than 6 bits.  */
4022   print_hex = operand->print_hex && operand_base->size > 6;
4023   if (sval < min_val || sval > max_val)
4024     {
4025       if (arg->soft_match)
4026         return 0;
4027       report_bad_range (arg->insn, arg->argnum, sval, min_val, max_val,
4028                         print_hex);
4029       arg->last_op_int = min_val;
4030     }
4031   else if (sval % factor)
4032     {
4033       if (arg->soft_match)
4034         return 0;
4035       as_bad (print_hex && sval >= 0
4036               ? _("Operand %d of `%s' must be a factor of %d, was 0x%lx.")
4037               : _("Operand %d of `%s' must be a factor of %d, was %ld."),
4038               arg->argnum, arg->insn->insn_mo->name, factor,
4039               (unsigned long) sval);
4040       arg->last_op_int = min_val;
4041     }
4042
4043   uval = (unsigned int) sval >> operand->shift;
4044   uval -= operand->bias;
4045
4046   /* Handle -mfix-cn63xxp1.  */
4047   if (arg->opnum == 1
4048       && mips_fix_cn63xxp1
4049       && !mips_opts.micromips
4050       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4051     switch (uval)
4052       {
4053       case 5:
4054       case 25:
4055       case 26:
4056       case 27:
4057       case 28:
4058       case 29:
4059       case 30:
4060       case 31:
4061         /* These are ok.  */
4062         break;
4063
4064       default:
4065         /* The rest must be changed to 28.  */
4066         uval = 28;
4067         break;
4068       }
4069
4070   insn_insert_operand (arg->insn, operand_base, uval);
4071   return s;
4072 }
4073
4074 /* OP_MAPPED_INT matcher.  */
4075
4076 static char *
4077 match_mapped_int_operand (struct mips_arg_info *arg,
4078                           const struct mips_operand *operand_base, char *s)
4079 {
4080   const struct mips_mapped_int_operand *operand;
4081   unsigned int uval, num_vals;
4082   offsetT sval;
4083
4084   operand = (const struct mips_mapped_int_operand *) operand_base;
4085   s = match_const_int (arg, s, &sval, operand->int_map[0]);
4086   if (!s)
4087     return 0;
4088
4089   num_vals = 1 << operand_base->size;
4090   for (uval = 0; uval < num_vals; uval++)
4091     if (operand->int_map[uval] == sval)
4092       break;
4093   if (uval == num_vals)
4094     return 0;
4095
4096   insn_insert_operand (arg->insn, operand_base, uval);
4097   return s;
4098 }
4099
4100 /* OP_MSB matcher.  */
4101
4102 static char *
4103 match_msb_operand (struct mips_arg_info *arg,
4104                    const struct mips_operand *operand_base, char *s)
4105 {
4106   const struct mips_msb_operand *operand;
4107   int min_val, max_val, max_high;
4108   offsetT size, sval, high;
4109
4110   operand = (const struct mips_msb_operand *) operand_base;
4111   min_val = operand->bias;
4112   max_val = min_val + (1 << operand_base->size) - 1;
4113   max_high = operand->opsize;
4114
4115   s = match_const_int (arg, s, &size, 1);
4116   if (!s)
4117     return 0;
4118
4119   high = size + arg->last_op_int;
4120   sval = operand->add_lsb ? high : size;
4121
4122   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4123     {
4124       if (arg->soft_match)
4125         return 0;
4126       report_bad_field (arg->last_op_int, size);
4127       sval = min_val;
4128     }
4129   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4130   return s;
4131 }
4132
4133 /* OP_REG matcher.  */
4134
4135 static char *
4136 match_reg_operand (struct mips_arg_info *arg,
4137                    const struct mips_operand *operand_base, char *s)
4138 {
4139   const struct mips_reg_operand *operand;
4140   unsigned int regno, uval, num_vals, types;
4141
4142   operand = (const struct mips_reg_operand *) operand_base;
4143   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4144   if (!reg_lookup (&s, types, &regno))
4145     return 0;
4146
4147   SKIP_SPACE_TABS (s);
4148   if (arg->optional_reg && *s == 0)
4149     return 0;
4150
4151   if (operand->reg_map)
4152     {
4153       num_vals = 1 << operand->root.size;
4154       for (uval = 0; uval < num_vals; uval++)
4155         if (operand->reg_map[uval] == regno)
4156           break;
4157       if (num_vals == uval)
4158         return 0;
4159     }
4160   else
4161     uval = regno;
4162
4163   check_regno (arg, operand->reg_type, regno);
4164   arg->last_regno = regno;
4165   if (arg->opnum == 1)
4166     arg->dest_regno = regno;
4167   insn_insert_operand (arg->insn, operand_base, uval);
4168   return s;
4169 }
4170
4171 /* OP_REG_PAIR matcher.  */
4172
4173 static char *
4174 match_reg_pair_operand (struct mips_arg_info *arg,
4175                         const struct mips_operand *operand_base, char *s)
4176 {
4177   const struct mips_reg_pair_operand *operand;
4178   unsigned int regno1, regno2, uval, num_vals, types;
4179
4180   operand = (const struct mips_reg_pair_operand *) operand_base;
4181   types = convert_reg_type (arg->insn->insn_mo, operand->reg_type);
4182
4183   if (!reg_lookup (&s, types, &regno1))
4184     return 0;
4185
4186   SKIP_SPACE_TABS (s);
4187   if (*s++ != ',')
4188     return 0;
4189   arg->argnum += 1;
4190
4191   if (!reg_lookup (&s, types, &regno2))
4192     return 0;
4193
4194   num_vals = 1 << operand_base->size;
4195   for (uval = 0; uval < num_vals; uval++)
4196     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4197       break;
4198   if (uval == num_vals)
4199     return 0;
4200
4201   check_regno (arg, operand->reg_type, regno1);
4202   check_regno (arg, operand->reg_type, regno2);
4203   insn_insert_operand (arg->insn, operand_base, uval);
4204   return s;
4205 }
4206
4207 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4208
4209 static char *
4210 match_pcrel_operand (char *s)
4211 {
4212   my_getExpression (&offset_expr, s);
4213   return expr_end;
4214 }
4215
4216 /* OP_PERF_REG matcher.  */
4217
4218 static char *
4219 match_perf_reg_operand (struct mips_arg_info *arg,
4220                         const struct mips_operand *operand, char *s)
4221 {
4222   offsetT sval;
4223
4224   s = match_const_int (arg, s, &sval, 0);
4225   if (!s)
4226     return 0;
4227
4228   if (sval != 0
4229       && (sval != 1
4230           || (mips_opts.arch == CPU_R5900
4231               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4232                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4233     {
4234       if (arg->soft_match)
4235         return 0;
4236       as_bad (_("Invalid performance register (%ld)"), (unsigned long) sval);
4237     }
4238
4239   insn_insert_operand (arg->insn, operand, sval);
4240   return s;
4241 }
4242
4243 /* OP_ADDIUSP matcher.  */
4244
4245 static char *
4246 match_addiusp_operand (struct mips_arg_info *arg,
4247                        const struct mips_operand *operand, char *s)
4248 {
4249   offsetT sval;
4250   unsigned int uval;
4251
4252   s = match_const_int (arg, s, &sval, -256);
4253   if (!s)
4254     return 0;
4255
4256   if (sval % 4)
4257     return 0;
4258
4259   sval /= 4;
4260   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4261     return 0;
4262
4263   uval = (unsigned int) sval;
4264   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4265   insn_insert_operand (arg->insn, operand, uval);
4266   return s;
4267 }
4268
4269 /* OP_CLO_CLZ_DEST matcher.  */
4270
4271 static char *
4272 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4273                             const struct mips_operand *operand, char *s)
4274 {
4275   unsigned int regno;
4276
4277   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
4278     return 0;
4279
4280   check_regno (arg, OP_REG_GP, regno);
4281   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4282   return s;
4283 }
4284
4285 /* OP_LWM_SWM_LIST matcher.  */
4286
4287 static char *
4288 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4289                             const struct mips_operand *operand, char *s)
4290 {
4291   unsigned int reglist, sregs, ra;
4292
4293   if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
4294     return 0;
4295
4296   if (operand->size == 2)
4297     {
4298       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4299
4300          s0, ra
4301          s0, s1, ra, s2, s3
4302          s0-s2, ra
4303
4304          and any permutations of these.  */
4305       if ((reglist & 0xfff1ffff) != 0x80010000)
4306         return 0;
4307
4308       sregs = (reglist >> 17) & 7;
4309       ra = 0;
4310     }
4311   else
4312     {
4313       /* The list must include at least one of ra and s0-sN,
4314          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4315          which are $23 and $30 respectively.)  E.g.:
4316
4317          ra
4318          s0
4319          ra, s0, s1, s2
4320          s0-s8
4321          s0-s5, ra
4322
4323          and any permutations of these.  */
4324       if ((reglist & 0x3f00ffff) != 0)
4325         return 0;
4326
4327       ra = (reglist >> 27) & 0x10;
4328       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4329     }
4330   sregs += 1;
4331   if ((sregs & -sregs) != sregs)
4332     return 0;
4333
4334   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4335   return s;
4336 }
4337
4338 /* OP_MDMX_IMM_REG matcher.  */
4339
4340 static char *
4341 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
4342                             const struct mips_operand *operand, char *s)
4343 {
4344   unsigned int regno, uval, types;
4345   bfd_boolean is_qh;
4346   const struct mips_opcode *opcode;
4347
4348   /* The mips_opcode records whether this is an octobyte or quadhalf
4349      instruction.  Start out with that bit in place.  */
4350   opcode = arg->insn->insn_mo;
4351   uval = mips_extract_operand (operand, opcode->match);
4352   is_qh = (uval != 0);
4353
4354   types = convert_reg_type (arg->insn->insn_mo, OP_REG_VEC);
4355   if (reg_lookup (&s, types, &regno))
4356     {
4357       if ((opcode->membership & INSN_5400)
4358           && strcmp (opcode->name, "rzu.ob") == 0)
4359         {
4360           if (arg->soft_match)
4361             return 0;
4362           as_bad (_("Operand %d of `%s' must be an immediate"),
4363                   arg->argnum, opcode->name);
4364         }
4365
4366       /* Check whether this is a vector register or a broadcast of
4367          a single element.  */
4368       SKIP_SPACE_TABS (s);
4369       if (*s == '[')
4370         {
4371           /* Read the element number.  */
4372           expressionS value;
4373
4374           ++s;
4375           SKIP_SPACE_TABS (s);
4376           my_getExpression (&value, s);
4377           s = expr_end;
4378           if (value.X_op != O_constant
4379               || value.X_add_number < 0
4380               || value.X_add_number > (is_qh ? 3 : 7))
4381             {
4382               if (arg->soft_match)
4383                 return 0;
4384               as_bad (_("Invalid element selector"));
4385               value.X_add_number = 0;
4386             }
4387           uval |= (unsigned int) value.X_add_number << (is_qh ? 2 : 1) << 5;
4388           SKIP_SPACE_TABS (s);
4389           if (*s == ']')
4390             ++s;
4391           else
4392             {
4393               if (arg->soft_match)
4394                 return 0;
4395               as_bad (_("Expecting ']' found '%s'"), s);
4396             }
4397         }
4398       else
4399         {
4400           /* A full vector.  */
4401           if ((opcode->membership & INSN_5400)
4402               && (strcmp (opcode->name, "sll.ob") == 0
4403                   || strcmp (opcode->name, "srl.ob") == 0))
4404             {
4405               if (arg->soft_match)
4406                 return 0;
4407               as_bad (_("Operand %d of `%s' must be scalar"),
4408                       arg->argnum, opcode->name);
4409             }
4410
4411           if (is_qh)
4412             uval |= MDMX_FMTSEL_VEC_QH << 5;
4413           else
4414             uval |= MDMX_FMTSEL_VEC_OB << 5;
4415         }
4416       check_regno (arg, OP_REG_FP, regno);
4417       uval |= regno;
4418     }
4419   else
4420     {
4421       offsetT sval;
4422
4423       s = match_const_int (arg, s, &sval, 0);
4424       if (!s)
4425         return 0;
4426       if (sval < 0 || sval > 31)
4427         {
4428           if (arg->soft_match)
4429             return 0;
4430           report_bad_range (arg->insn, arg->argnum, sval, 0, 31, FALSE);
4431         }
4432       uval |= (sval & 31);
4433       if (is_qh)
4434         uval |= MDMX_FMTSEL_IMM_QH << 5;
4435       else
4436         uval |= MDMX_FMTSEL_IMM_OB << 5;
4437     }
4438   insn_insert_operand (arg->insn, operand, uval);
4439   return s;
4440 }
4441
4442 /* OP_PC matcher.  */
4443
4444 static char *
4445 match_pc_operand (char *s)
4446 {
4447   if (strncmp (s, "$pc", 3) != 0)
4448     return 0;
4449   s += 3;
4450   SKIP_SPACE_TABS (s);
4451   return s;
4452 }
4453
4454 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
4455    register that we need to match.  */
4456
4457 static char *
4458 match_tied_reg_operand (struct mips_arg_info *arg, char *s,
4459                         unsigned int other_regno)
4460 {
4461   unsigned int regno;
4462
4463   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno)
4464       || regno != other_regno)
4465     return 0;
4466   SKIP_SPACE_TABS (s);
4467   if (arg->optional_reg && *s == 0)
4468     return 0;
4469   return s;
4470 }
4471
4472 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
4473    of the argument text if the match is successful, otherwise return null.  */
4474
4475 static char *
4476 match_operand (struct mips_arg_info *arg,
4477                const struct mips_operand *operand, char *s)
4478 {
4479   switch (operand->type)
4480     {
4481     case OP_INT:
4482       return match_int_operand (arg, operand, s);
4483
4484     case OP_MAPPED_INT:
4485       return match_mapped_int_operand (arg, operand, s);
4486
4487     case OP_MSB:
4488       return match_msb_operand (arg, operand, s);
4489
4490     case OP_REG:
4491       return match_reg_operand (arg, operand, s);
4492
4493     case OP_REG_PAIR:
4494       return match_reg_pair_operand (arg, operand, s);
4495
4496     case OP_PCREL:
4497       return match_pcrel_operand (s);
4498
4499     case OP_PERF_REG:
4500       return match_perf_reg_operand (arg, operand, s);
4501
4502     case OP_ADDIUSP_INT:
4503       return match_addiusp_operand (arg, operand, s);
4504
4505     case OP_CLO_CLZ_DEST:
4506       return match_clo_clz_dest_operand (arg, operand, s);
4507
4508     case OP_LWM_SWM_LIST:
4509       return match_lwm_swm_list_operand (arg, operand, s);
4510
4511     case OP_ENTRY_EXIT_LIST:
4512     case OP_SAVE_RESTORE_LIST:
4513       abort ();
4514
4515     case OP_MDMX_IMM_REG:
4516       return match_mdmx_imm_reg_operand (arg, operand, s);
4517
4518     case OP_REPEAT_DEST_REG:
4519       return match_tied_reg_operand (arg, s, arg->dest_regno);
4520
4521     case OP_REPEAT_PREV_REG:
4522       return match_tied_reg_operand (arg, s, arg->last_regno);
4523
4524     case OP_PC:
4525       return match_pc_operand (s);
4526     }
4527   abort ();
4528 }
4529
4530 /* ARG is the state after successfully matching an instruction.
4531    Issue any queued-up warnings.  */
4532
4533 static void
4534 check_completed_insn (struct mips_arg_info *arg)
4535 {
4536   if (arg->seen_at)
4537     {
4538       if (AT == ATREG)
4539         as_warn (_("Used $at without \".set noat\""));
4540       else
4541         as_warn (_("Used $%u with \".set at=$%u\""), AT, AT);
4542     }
4543 }
4544 #endif
4545
4546 /* Classify an instruction according to the FIX_VR4120_* enumeration.
4547    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
4548    by VR4120 errata.  */
4549
4550 static unsigned int
4551 classify_vr4120_insn (const char *name)
4552 {
4553   if (strncmp (name, "macc", 4) == 0)
4554     return FIX_VR4120_MACC;
4555   if (strncmp (name, "dmacc", 5) == 0)
4556     return FIX_VR4120_DMACC;
4557   if (strncmp (name, "mult", 4) == 0)
4558     return FIX_VR4120_MULT;
4559   if (strncmp (name, "dmult", 5) == 0)
4560     return FIX_VR4120_DMULT;
4561   if (strstr (name, "div"))
4562     return FIX_VR4120_DIV;
4563   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
4564     return FIX_VR4120_MTHILO;
4565   return NUM_FIX_VR4120_CLASSES;
4566 }
4567
4568 #define INSN_ERET  0x42000018
4569 #define INSN_DERET 0x4200001f
4570
4571 /* Return the number of instructions that must separate INSN1 and INSN2,
4572    where INSN1 is the earlier instruction.  Return the worst-case value
4573    for any INSN2 if INSN2 is null.  */
4574
4575 static unsigned int
4576 insns_between (const struct mips_cl_insn *insn1,
4577                const struct mips_cl_insn *insn2)
4578 {
4579   unsigned long pinfo1, pinfo2;
4580   unsigned int mask;
4581
4582   /* This function needs to know which pinfo flags are set for INSN2
4583      and which registers INSN2 uses.  The former is stored in PINFO2 and
4584      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
4585      will have every flag set and INSN2_USES_GPR will always return true.  */
4586   pinfo1 = insn1->insn_mo->pinfo;
4587   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
4588
4589 #define INSN2_USES_GPR(REG) \
4590   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
4591
4592   /* For most targets, write-after-read dependencies on the HI and LO
4593      registers must be separated by at least two instructions.  */
4594   if (!hilo_interlocks)
4595     {
4596       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
4597         return 2;
4598       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
4599         return 2;
4600     }
4601
4602   /* If we're working around r7000 errata, there must be two instructions
4603      between an mfhi or mflo and any instruction that uses the result.  */
4604   if (mips_7000_hilo_fix
4605       && !mips_opts.micromips
4606       && MF_HILO_INSN (pinfo1)
4607       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
4608     return 2;
4609
4610   /* If we're working around 24K errata, one instruction is required
4611      if an ERET or DERET is followed by a branch instruction.  */
4612   if (mips_fix_24k && !mips_opts.micromips)
4613     {
4614       if (insn1->insn_opcode == INSN_ERET
4615           || insn1->insn_opcode == INSN_DERET)
4616         {
4617           if (insn2 == NULL
4618               || insn2->insn_opcode == INSN_ERET
4619               || insn2->insn_opcode == INSN_DERET
4620               || delayed_branch_p (insn2))
4621             return 1;
4622         }
4623     }
4624
4625   /* If working around VR4120 errata, check for combinations that need
4626      a single intervening instruction.  */
4627   if (mips_fix_vr4120 && !mips_opts.micromips)
4628     {
4629       unsigned int class1, class2;
4630
4631       class1 = classify_vr4120_insn (insn1->insn_mo->name);
4632       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
4633         {
4634           if (insn2 == NULL)
4635             return 1;
4636           class2 = classify_vr4120_insn (insn2->insn_mo->name);
4637           if (vr4120_conflicts[class1] & (1 << class2))
4638             return 1;
4639         }
4640     }
4641
4642   if (!HAVE_CODE_COMPRESSION)
4643     {
4644       /* Check for GPR or coprocessor load delays.  All such delays
4645          are on the RT register.  */
4646       /* Itbl support may require additional care here.  */
4647       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
4648           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
4649         {
4650           know (pinfo1 & INSN_WRITE_GPR_T);
4651           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
4652             return 1;
4653         }
4654
4655       /* Check for generic coprocessor hazards.
4656
4657          This case is not handled very well.  There is no special
4658          knowledge of CP0 handling, and the coprocessors other than
4659          the floating point unit are not distinguished at all.  */
4660       /* Itbl support may require additional care here. FIXME!
4661          Need to modify this to include knowledge about
4662          user specified delays!  */
4663       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
4664                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
4665         {
4666           /* Handle cases where INSN1 writes to a known general coprocessor
4667              register.  There must be a one instruction delay before INSN2
4668              if INSN2 reads that register, otherwise no delay is needed.  */
4669           mask = fpr_write_mask (insn1);
4670           if (mask != 0)
4671             {
4672               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
4673                 return 1;
4674             }
4675           else
4676             {
4677               /* Read-after-write dependencies on the control registers
4678                  require a two-instruction gap.  */
4679               if ((pinfo1 & INSN_WRITE_COND_CODE)
4680                   && (pinfo2 & INSN_READ_COND_CODE))
4681                 return 2;
4682
4683               /* We don't know exactly what INSN1 does.  If INSN2 is
4684                  also a coprocessor instruction, assume there must be
4685                  a one instruction gap.  */
4686               if (pinfo2 & INSN_COP)
4687                 return 1;
4688             }
4689         }
4690
4691       /* Check for read-after-write dependencies on the coprocessor
4692          control registers in cases where INSN1 does not need a general
4693          coprocessor delay.  This means that INSN1 is a floating point
4694          comparison instruction.  */
4695       /* Itbl support may require additional care here.  */
4696       else if (!cop_interlocks
4697                && (pinfo1 & INSN_WRITE_COND_CODE)
4698                && (pinfo2 & INSN_READ_COND_CODE))
4699         return 1;
4700     }
4701
4702 #undef INSN2_USES_GPR
4703
4704   return 0;
4705 }
4706
4707 /* Return the number of nops that would be needed to work around the
4708    VR4130 mflo/mfhi errata if instruction INSN immediately followed
4709    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
4710    that are contained within the first IGNORE instructions of HIST.  */
4711
4712 static int
4713 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
4714                  const struct mips_cl_insn *insn)
4715 {
4716   int i, j;
4717   unsigned int mask;
4718
4719   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
4720      are not affected by the errata.  */
4721   if (insn != 0
4722       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
4723           || strcmp (insn->insn_mo->name, "mtlo") == 0
4724           || strcmp (insn->insn_mo->name, "mthi") == 0))
4725     return 0;
4726
4727   /* Search for the first MFLO or MFHI.  */
4728   for (i = 0; i < MAX_VR4130_NOPS; i++)
4729     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
4730       {
4731         /* Extract the destination register.  */
4732         mask = gpr_write_mask (&hist[i]);
4733
4734         /* No nops are needed if INSN reads that register.  */
4735         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
4736           return 0;
4737
4738         /* ...or if any of the intervening instructions do.  */
4739         for (j = 0; j < i; j++)
4740           if (gpr_read_mask (&hist[j]) & mask)
4741             return 0;
4742
4743         if (i >= ignore)
4744           return MAX_VR4130_NOPS - i;
4745       }
4746   return 0;
4747 }
4748
4749 #define BASE_REG_EQ(INSN1, INSN2)       \
4750   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
4751       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
4752
4753 /* Return the minimum alignment for this store instruction.  */
4754
4755 static int
4756 fix_24k_align_to (const struct mips_opcode *mo)
4757 {
4758   if (strcmp (mo->name, "sh") == 0)
4759     return 2;
4760
4761   if (strcmp (mo->name, "swc1") == 0
4762       || strcmp (mo->name, "swc2") == 0
4763       || strcmp (mo->name, "sw") == 0
4764       || strcmp (mo->name, "sc") == 0
4765       || strcmp (mo->name, "s.s") == 0)
4766     return 4;
4767
4768   if (strcmp (mo->name, "sdc1") == 0
4769       || strcmp (mo->name, "sdc2") == 0
4770       || strcmp (mo->name, "s.d") == 0)
4771     return 8;
4772
4773   /* sb, swl, swr */
4774   return 1;
4775 }
4776
4777 struct fix_24k_store_info
4778   {
4779     /* Immediate offset, if any, for this store instruction.  */
4780     short off;
4781     /* Alignment required by this store instruction.  */
4782     int align_to;
4783     /* True for register offsets.  */
4784     int register_offset;
4785   };
4786
4787 /* Comparison function used by qsort.  */
4788
4789 static int
4790 fix_24k_sort (const void *a, const void *b)
4791 {
4792   const struct fix_24k_store_info *pos1 = a;
4793   const struct fix_24k_store_info *pos2 = b;
4794
4795   return (pos1->off - pos2->off);
4796 }
4797
4798 /* INSN is a store instruction.  Try to record the store information
4799    in STINFO.  Return false if the information isn't known.  */
4800
4801 static bfd_boolean
4802 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
4803                            const struct mips_cl_insn *insn)
4804 {
4805   /* The instruction must have a known offset.  */
4806   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
4807     return FALSE;
4808
4809   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
4810   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
4811   return TRUE;
4812 }
4813
4814 /* Return the number of nops that would be needed to work around the 24k
4815    "lost data on stores during refill" errata if instruction INSN
4816    immediately followed the 2 instructions described by HIST.
4817    Ignore hazards that are contained within the first IGNORE
4818    instructions of HIST.
4819
4820    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
4821    for the data cache refills and store data. The following describes
4822    the scenario where the store data could be lost.
4823
4824    * A data cache miss, due to either a load or a store, causing fill
4825      data to be supplied by the memory subsystem
4826    * The first three doublewords of fill data are returned and written
4827      into the cache
4828    * A sequence of four stores occurs in consecutive cycles around the
4829      final doubleword of the fill:
4830    * Store A
4831    * Store B
4832    * Store C
4833    * Zero, One or more instructions
4834    * Store D
4835
4836    The four stores A-D must be to different doublewords of the line that
4837    is being filled. The fourth instruction in the sequence above permits
4838    the fill of the final doubleword to be transferred from the FSB into
4839    the cache. In the sequence above, the stores may be either integer
4840    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
4841    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
4842    different doublewords on the line. If the floating point unit is
4843    running in 1:2 mode, it is not possible to create the sequence above
4844    using only floating point store instructions.
4845
4846    In this case, the cache line being filled is incorrectly marked
4847    invalid, thereby losing the data from any store to the line that
4848    occurs between the original miss and the completion of the five
4849    cycle sequence shown above.
4850
4851    The workarounds are:
4852
4853    * Run the data cache in write-through mode.
4854    * Insert a non-store instruction between
4855      Store A and Store B or Store B and Store C.  */
4856   
4857 static int
4858 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
4859               const struct mips_cl_insn *insn)
4860 {
4861   struct fix_24k_store_info pos[3];
4862   int align, i, base_offset;
4863
4864   if (ignore >= 2)
4865     return 0;
4866
4867   /* If the previous instruction wasn't a store, there's nothing to
4868      worry about.  */
4869   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4870     return 0;
4871
4872   /* If the instructions after the previous one are unknown, we have
4873      to assume the worst.  */
4874   if (!insn)
4875     return 1;
4876
4877   /* Check whether we are dealing with three consecutive stores.  */
4878   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
4879       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4880     return 0;
4881
4882   /* If we don't know the relationship between the store addresses,
4883      assume the worst.  */
4884   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
4885       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
4886     return 1;
4887
4888   if (!fix_24k_record_store_info (&pos[0], insn)
4889       || !fix_24k_record_store_info (&pos[1], &hist[0])
4890       || !fix_24k_record_store_info (&pos[2], &hist[1]))
4891     return 1;
4892
4893   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
4894
4895   /* Pick a value of ALIGN and X such that all offsets are adjusted by
4896      X bytes and such that the base register + X is known to be aligned
4897      to align bytes.  */
4898
4899   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
4900     align = 8;
4901   else
4902     {
4903       align = pos[0].align_to;
4904       base_offset = pos[0].off;
4905       for (i = 1; i < 3; i++)
4906         if (align < pos[i].align_to)
4907           {
4908             align = pos[i].align_to;
4909             base_offset = pos[i].off;
4910           }
4911       for (i = 0; i < 3; i++)
4912         pos[i].off -= base_offset;
4913     }
4914
4915   pos[0].off &= ~align + 1;
4916   pos[1].off &= ~align + 1;
4917   pos[2].off &= ~align + 1;
4918
4919   /* If any two stores write to the same chunk, they also write to the
4920      same doubleword.  The offsets are still sorted at this point.  */
4921   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
4922     return 0;
4923
4924   /* A range of at least 9 bytes is needed for the stores to be in
4925      non-overlapping doublewords.  */
4926   if (pos[2].off - pos[0].off <= 8)
4927     return 0;
4928
4929   if (pos[2].off - pos[1].off >= 24
4930       || pos[1].off - pos[0].off >= 24
4931       || pos[2].off - pos[0].off >= 32)
4932     return 0;
4933
4934   return 1;
4935 }
4936
4937 /* Return the number of nops that would be needed if instruction INSN
4938    immediately followed the MAX_NOPS instructions given by HIST,
4939    where HIST[0] is the most recent instruction.  Ignore hazards
4940    between INSN and the first IGNORE instructions in HIST.
4941
4942    If INSN is null, return the worse-case number of nops for any
4943    instruction.  */
4944
4945 static int
4946 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
4947                const struct mips_cl_insn *insn)
4948 {
4949   int i, nops, tmp_nops;
4950
4951   nops = 0;
4952   for (i = ignore; i < MAX_DELAY_NOPS; i++)
4953     {
4954       tmp_nops = insns_between (hist + i, insn) - i;
4955       if (tmp_nops > nops)
4956         nops = tmp_nops;
4957     }
4958
4959   if (mips_fix_vr4130 && !mips_opts.micromips)
4960     {
4961       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
4962       if (tmp_nops > nops)
4963         nops = tmp_nops;
4964     }
4965
4966   if (mips_fix_24k && !mips_opts.micromips)
4967     {
4968       tmp_nops = nops_for_24k (ignore, hist, insn);
4969       if (tmp_nops > nops)
4970         nops = tmp_nops;
4971     }
4972
4973   return nops;
4974 }
4975
4976 /* The variable arguments provide NUM_INSNS extra instructions that
4977    might be added to HIST.  Return the largest number of nops that
4978    would be needed after the extended sequence, ignoring hazards
4979    in the first IGNORE instructions.  */
4980
4981 static int
4982 nops_for_sequence (int num_insns, int ignore,
4983                    const struct mips_cl_insn *hist, ...)
4984 {
4985   va_list args;
4986   struct mips_cl_insn buffer[MAX_NOPS];
4987   struct mips_cl_insn *cursor;
4988   int nops;
4989
4990   va_start (args, hist);
4991   cursor = buffer + num_insns;
4992   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
4993   while (cursor > buffer)
4994     *--cursor = *va_arg (args, const struct mips_cl_insn *);
4995
4996   nops = nops_for_insn (ignore, buffer, NULL);
4997   va_end (args);
4998   return nops;
4999 }
5000
5001 /* Like nops_for_insn, but if INSN is a branch, take into account the
5002    worst-case delay for the branch target.  */
5003
5004 static int
5005 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5006                          const struct mips_cl_insn *insn)
5007 {
5008   int nops, tmp_nops;
5009
5010   nops = nops_for_insn (ignore, hist, insn);
5011   if (delayed_branch_p (insn))
5012     {
5013       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5014                                     hist, insn, get_delay_slot_nop (insn));
5015       if (tmp_nops > nops)
5016         nops = tmp_nops;
5017     }
5018   else if (compact_branch_p (insn))
5019     {
5020       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5021       if (tmp_nops > nops)
5022         nops = tmp_nops;
5023     }
5024   return nops;
5025 }
5026
5027 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5028
5029 static void
5030 fix_loongson2f_nop (struct mips_cl_insn * ip)
5031 {
5032   gas_assert (!HAVE_CODE_COMPRESSION);
5033   if (strcmp (ip->insn_mo->name, "nop") == 0)
5034     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5035 }
5036
5037 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5038                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5039
5040 static void
5041 fix_loongson2f_jump (struct mips_cl_insn * ip)
5042 {
5043   gas_assert (!HAVE_CODE_COMPRESSION);
5044   if (strcmp (ip->insn_mo->name, "j") == 0
5045       || strcmp (ip->insn_mo->name, "jr") == 0
5046       || strcmp (ip->insn_mo->name, "jalr") == 0)
5047     {
5048       int sreg;
5049       expressionS ep;
5050
5051       if (! mips_opts.at)
5052         return;
5053
5054       sreg = EXTRACT_OPERAND (0, RS, *ip);
5055       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5056         return;
5057
5058       ep.X_op = O_constant;
5059       ep.X_add_number = 0xcfff0000;
5060       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5061       ep.X_add_number = 0xffff;
5062       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5063       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5064     }
5065 }
5066
5067 static void
5068 fix_loongson2f (struct mips_cl_insn * ip)
5069 {
5070   if (mips_fix_loongson2f_nop)
5071     fix_loongson2f_nop (ip);
5072
5073   if (mips_fix_loongson2f_jump)
5074     fix_loongson2f_jump (ip);
5075 }
5076
5077 /* IP is a branch that has a delay slot, and we need to fill it
5078    automatically.   Return true if we can do that by swapping IP
5079    with the previous instruction.
5080    ADDRESS_EXPR is an operand of the instruction to be used with
5081    RELOC_TYPE.  */
5082
5083 static bfd_boolean
5084 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5085   bfd_reloc_code_real_type *reloc_type)
5086 {
5087   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5088   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
5089
5090   /* -O2 and above is required for this optimization.  */
5091   if (mips_optimize < 2)
5092     return FALSE;
5093
5094   /* If we have seen .set volatile or .set nomove, don't optimize.  */
5095   if (mips_opts.nomove)
5096     return FALSE;
5097
5098   /* We can't swap if the previous instruction's position is fixed.  */
5099   if (history[0].fixed_p)
5100     return FALSE;
5101
5102   /* If the previous previous insn was in a .set noreorder, we can't
5103      swap.  Actually, the MIPS assembler will swap in this situation.
5104      However, gcc configured -with-gnu-as will generate code like
5105
5106         .set    noreorder
5107         lw      $4,XXX
5108         .set    reorder
5109         INSN
5110         bne     $4,$0,foo
5111
5112      in which we can not swap the bne and INSN.  If gcc is not configured
5113      -with-gnu-as, it does not output the .set pseudo-ops.  */
5114   if (history[1].noreorder_p)
5115     return FALSE;
5116
5117   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
5118      This means that the previous instruction was a 4-byte one anyhow.  */
5119   if (mips_opts.mips16 && history[0].fixp[0])
5120     return FALSE;
5121
5122   /* If the branch is itself the target of a branch, we can not swap.
5123      We cheat on this; all we check for is whether there is a label on
5124      this instruction.  If there are any branches to anything other than
5125      a label, users must use .set noreorder.  */
5126   if (seg_info (now_seg)->label_list)
5127     return FALSE;
5128
5129   /* If the previous instruction is in a variant frag other than this
5130      branch's one, we cannot do the swap.  This does not apply to
5131      MIPS16 code, which uses variant frags for different purposes.  */
5132   if (!mips_opts.mips16
5133       && history[0].frag
5134       && history[0].frag->fr_type == rs_machine_dependent)
5135     return FALSE;
5136
5137   /* We do not swap with instructions that cannot architecturally
5138      be placed in a branch delay slot, such as SYNC or ERET.  We
5139      also refrain from swapping with a trap instruction, since it
5140      complicates trap handlers to have the trap instruction be in
5141      a delay slot.  */
5142   prev_pinfo = history[0].insn_mo->pinfo;
5143   if (prev_pinfo & INSN_NO_DELAY_SLOT)
5144     return FALSE;
5145
5146   /* Check for conflicts between the branch and the instructions
5147      before the candidate delay slot.  */
5148   if (nops_for_insn (0, history + 1, ip) > 0)
5149     return FALSE;
5150
5151   /* Check for conflicts between the swapped sequence and the
5152      target of the branch.  */
5153   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
5154     return FALSE;
5155
5156   /* If the branch reads a register that the previous
5157      instruction sets, we can not swap.  */
5158   gpr_read = gpr_read_mask (ip);
5159   prev_gpr_write = gpr_write_mask (&history[0]);
5160   if (gpr_read & prev_gpr_write)
5161     return FALSE;
5162
5163   /* If the branch writes a register that the previous
5164      instruction sets, we can not swap.  */
5165   gpr_write = gpr_write_mask (ip);
5166   if (gpr_write & prev_gpr_write)
5167     return FALSE;
5168
5169   /* If the branch writes a register that the previous
5170      instruction reads, we can not swap.  */
5171   prev_gpr_read = gpr_read_mask (&history[0]);
5172   if (gpr_write & prev_gpr_read)
5173     return FALSE;
5174
5175   /* If one instruction sets a condition code and the
5176      other one uses a condition code, we can not swap.  */
5177   pinfo = ip->insn_mo->pinfo;
5178   if ((pinfo & INSN_READ_COND_CODE)
5179       && (prev_pinfo & INSN_WRITE_COND_CODE))
5180     return FALSE;
5181   if ((pinfo & INSN_WRITE_COND_CODE)
5182       && (prev_pinfo & INSN_READ_COND_CODE))
5183     return FALSE;
5184
5185   /* If the previous instruction uses the PC, we can not swap.  */
5186   prev_pinfo2 = history[0].insn_mo->pinfo2;
5187   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
5188     return FALSE;
5189   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
5190     return FALSE;
5191
5192   /* If the previous instruction has an incorrect size for a fixed
5193      branch delay slot in microMIPS mode, we cannot swap.  */
5194   pinfo2 = ip->insn_mo->pinfo2;
5195   if (mips_opts.micromips
5196       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
5197       && insn_length (history) != 2)
5198     return FALSE;
5199   if (mips_opts.micromips
5200       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
5201       && insn_length (history) != 4)
5202     return FALSE;
5203
5204   /* On R5900 short loops need to be fixed by inserting a nop in
5205      the branch delay slots.
5206      A short loop can be terminated too early.  */
5207   if (mips_opts.arch == CPU_R5900
5208       /* Check if instruction has a parameter, ignore "j $31". */
5209       && (address_expr != NULL)
5210       /* Parameter must be 16 bit. */
5211       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
5212       /* Branch to same segment. */
5213       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
5214       /* Branch to same code fragment. */
5215       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
5216       /* Can only calculate branch offset if value is known. */
5217       && symbol_constant_p(address_expr->X_add_symbol)
5218       /* Check if branch is really conditional. */
5219       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
5220         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
5221         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
5222     {
5223       int distance;
5224       /* Check if loop is shorter than 6 instructions including
5225          branch and delay slot.  */
5226       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
5227       if (distance <= 20)
5228         {
5229           int i;
5230           int rv;
5231
5232           rv = FALSE;
5233           /* When the loop includes branches or jumps,
5234              it is not a short loop. */
5235           for (i = 0; i < (distance / 4); i++)
5236             {
5237               if ((history[i].cleared_p)
5238                   || delayed_branch_p(&history[i]))
5239                 {
5240                   rv = TRUE;
5241                   break;
5242                 }
5243             }
5244           if (rv == FALSE)
5245             {
5246               /* Insert nop after branch to fix short loop. */
5247               return FALSE;
5248             }
5249         }
5250     }
5251
5252   return TRUE;
5253 }
5254
5255 /* Decide how we should add IP to the instruction stream.
5256    ADDRESS_EXPR is an operand of the instruction to be used with
5257    RELOC_TYPE.  */
5258
5259 static enum append_method
5260 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
5261   bfd_reloc_code_real_type *reloc_type)
5262 {
5263   unsigned long pinfo;
5264
5265   /* The relaxed version of a macro sequence must be inherently
5266      hazard-free.  */
5267   if (mips_relax.sequence == 2)
5268     return APPEND_ADD;
5269
5270   /* We must not dabble with instructions in a ".set norerorder" block.  */
5271   if (mips_opts.noreorder)
5272     return APPEND_ADD;
5273
5274   /* Otherwise, it's our responsibility to fill branch delay slots.  */
5275   if (delayed_branch_p (ip))
5276     {
5277       if (!branch_likely_p (ip)
5278           && can_swap_branch_p (ip, address_expr, reloc_type))
5279         return APPEND_SWAP;
5280
5281       pinfo = ip->insn_mo->pinfo;
5282       if (mips_opts.mips16
5283           && ISA_SUPPORTS_MIPS16E
5284           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
5285         return APPEND_ADD_COMPACT;
5286
5287       return APPEND_ADD_WITH_NOP;
5288     }
5289
5290   return APPEND_ADD;
5291 }
5292
5293 /* IP is a MIPS16 instruction whose opcode we have just changed.
5294    Point IP->insn_mo to the new opcode's definition.  */
5295
5296 static void
5297 find_altered_mips16_opcode (struct mips_cl_insn *ip)
5298 {
5299   const struct mips_opcode *mo, *end;
5300
5301   end = &mips16_opcodes[bfd_mips16_num_opcodes];
5302   for (mo = ip->insn_mo; mo < end; mo++)
5303     if ((ip->insn_opcode & mo->mask) == mo->match)
5304       {
5305         ip->insn_mo = mo;
5306         return;
5307       }
5308   abort ();
5309 }
5310
5311 /* For microMIPS macros, we need to generate a local number label
5312    as the target of branches.  */
5313 #define MICROMIPS_LABEL_CHAR            '\037'
5314 static unsigned long micromips_target_label;
5315 static char micromips_target_name[32];
5316
5317 static char *
5318 micromips_label_name (void)
5319 {
5320   char *p = micromips_target_name;
5321   char symbol_name_temporary[24];
5322   unsigned long l;
5323   int i;
5324
5325   if (*p)
5326     return p;
5327
5328   i = 0;
5329   l = micromips_target_label;
5330 #ifdef LOCAL_LABEL_PREFIX
5331   *p++ = LOCAL_LABEL_PREFIX;
5332 #endif
5333   *p++ = 'L';
5334   *p++ = MICROMIPS_LABEL_CHAR;
5335   do
5336     {
5337       symbol_name_temporary[i++] = l % 10 + '0';
5338       l /= 10;
5339     }
5340   while (l != 0);
5341   while (i > 0)
5342     *p++ = symbol_name_temporary[--i];
5343   *p = '\0';
5344
5345   return micromips_target_name;
5346 }
5347
5348 static void
5349 micromips_label_expr (expressionS *label_expr)
5350 {
5351   label_expr->X_op = O_symbol;
5352   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
5353   label_expr->X_add_number = 0;
5354 }
5355
5356 static void
5357 micromips_label_inc (void)
5358 {
5359   micromips_target_label++;
5360   *micromips_target_name = '\0';
5361 }
5362
5363 static void
5364 micromips_add_label (void)
5365 {
5366   symbolS *s;
5367
5368   s = colon (micromips_label_name ());
5369   micromips_label_inc ();
5370   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
5371 }
5372
5373 /* If assembling microMIPS code, then return the microMIPS reloc
5374    corresponding to the requested one if any.  Otherwise return
5375    the reloc unchanged.  */
5376
5377 static bfd_reloc_code_real_type
5378 micromips_map_reloc (bfd_reloc_code_real_type reloc)
5379 {
5380   static const bfd_reloc_code_real_type relocs[][2] =
5381     {
5382       /* Keep sorted incrementally by the left-hand key.  */
5383       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
5384       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
5385       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
5386       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
5387       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
5388       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
5389       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
5390       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
5391       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
5392       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
5393       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
5394       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
5395       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
5396       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
5397       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
5398       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
5399       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
5400       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
5401       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
5402       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
5403       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
5404       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
5405       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
5406       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
5407       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
5408       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
5409       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
5410     };
5411   bfd_reloc_code_real_type r;
5412   size_t i;
5413
5414   if (!mips_opts.micromips)
5415     return reloc;
5416   for (i = 0; i < ARRAY_SIZE (relocs); i++)
5417     {
5418       r = relocs[i][0];
5419       if (r > reloc)
5420         return reloc;
5421       if (r == reloc)
5422         return relocs[i][1];
5423     }
5424   return reloc;
5425 }
5426
5427 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
5428    Return true on success, storing the resolved value in RESULT.  */
5429
5430 static bfd_boolean
5431 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
5432                  offsetT *result)
5433 {
5434   switch (reloc)
5435     {
5436     case BFD_RELOC_MIPS_HIGHEST:
5437     case BFD_RELOC_MICROMIPS_HIGHEST:
5438       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
5439       return TRUE;
5440
5441     case BFD_RELOC_MIPS_HIGHER:
5442     case BFD_RELOC_MICROMIPS_HIGHER:
5443       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
5444       return TRUE;
5445
5446     case BFD_RELOC_HI16_S:
5447     case BFD_RELOC_MICROMIPS_HI16_S:
5448     case BFD_RELOC_MIPS16_HI16_S:
5449       *result = ((operand + 0x8000) >> 16) & 0xffff;
5450       return TRUE;
5451
5452     case BFD_RELOC_HI16:
5453     case BFD_RELOC_MICROMIPS_HI16:
5454     case BFD_RELOC_MIPS16_HI16:
5455       *result = (operand >> 16) & 0xffff;
5456       return TRUE;
5457
5458     case BFD_RELOC_LO16:
5459     case BFD_RELOC_MICROMIPS_LO16:
5460     case BFD_RELOC_MIPS16_LO16:
5461       *result = operand & 0xffff;
5462       return TRUE;
5463
5464     case BFD_RELOC_UNUSED:
5465       *result = operand;
5466       return TRUE;
5467
5468     default:
5469       return FALSE;
5470     }
5471 }
5472
5473 /* Output an instruction.  IP is the instruction information.
5474    ADDRESS_EXPR is an operand of the instruction to be used with
5475    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
5476    a macro expansion.  */
5477
5478 static void
5479 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
5480              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
5481 {
5482   unsigned long prev_pinfo2, pinfo;
5483   bfd_boolean relaxed_branch = FALSE;
5484   enum append_method method;
5485   bfd_boolean relax32;
5486   int branch_disp;
5487
5488   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
5489     fix_loongson2f (ip);
5490
5491   file_ase_mips16 |= mips_opts.mips16;
5492   file_ase_micromips |= mips_opts.micromips;
5493
5494   prev_pinfo2 = history[0].insn_mo->pinfo2;
5495   pinfo = ip->insn_mo->pinfo;
5496
5497   if (mips_opts.micromips
5498       && !expansionp
5499       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
5500            && micromips_insn_length (ip->insn_mo) != 2)
5501           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
5502               && micromips_insn_length (ip->insn_mo) != 4)))
5503     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
5504              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
5505
5506   if (address_expr == NULL)
5507     ip->complete_p = 1;
5508   else if (reloc_type[0] <= BFD_RELOC_UNUSED
5509            && reloc_type[1] == BFD_RELOC_UNUSED
5510            && reloc_type[2] == BFD_RELOC_UNUSED
5511            && address_expr->X_op == O_constant)
5512     {
5513       switch (*reloc_type)
5514         {
5515         case BFD_RELOC_MIPS_JMP:
5516           {
5517             int shift;
5518
5519             shift = mips_opts.micromips ? 1 : 2;
5520             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5521               as_bad (_("jump to misaligned address (0x%lx)"),
5522                       (unsigned long) address_expr->X_add_number);
5523             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5524                                 & 0x3ffffff);
5525             ip->complete_p = 1;
5526           }
5527           break;
5528
5529         case BFD_RELOC_MIPS16_JMP:
5530           if ((address_expr->X_add_number & 3) != 0)
5531             as_bad (_("jump to misaligned address (0x%lx)"),
5532                     (unsigned long) address_expr->X_add_number);
5533           ip->insn_opcode |=
5534             (((address_expr->X_add_number & 0x7c0000) << 3)
5535                | ((address_expr->X_add_number & 0xf800000) >> 7)
5536                | ((address_expr->X_add_number & 0x3fffc) >> 2));
5537           ip->complete_p = 1;
5538           break;
5539
5540         case BFD_RELOC_16_PCREL_S2:
5541           {
5542             int shift;
5543
5544             shift = mips_opts.micromips ? 1 : 2;
5545             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
5546               as_bad (_("branch to misaligned address (0x%lx)"),
5547                       (unsigned long) address_expr->X_add_number);
5548             if (!mips_relax_branch)
5549               {
5550                 if ((address_expr->X_add_number + (1 << (shift + 15)))
5551                     & ~((1 << (shift + 16)) - 1))
5552                   as_bad (_("branch address range overflow (0x%lx)"),
5553                           (unsigned long) address_expr->X_add_number);
5554                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
5555                                     & 0xffff);
5556               }
5557           }
5558           break;
5559
5560         default:
5561           {
5562             offsetT value;
5563
5564             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
5565                                  &value))
5566               {
5567                 ip->insn_opcode |= value & 0xffff;
5568                 ip->complete_p = 1;
5569               }
5570           }
5571           break;
5572         }
5573     }
5574
5575   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
5576     {
5577       /* There are a lot of optimizations we could do that we don't.
5578          In particular, we do not, in general, reorder instructions.
5579          If you use gcc with optimization, it will reorder
5580          instructions and generally do much more optimization then we
5581          do here; repeating all that work in the assembler would only
5582          benefit hand written assembly code, and does not seem worth
5583          it.  */
5584       int nops = (mips_optimize == 0
5585                   ? nops_for_insn (0, history, NULL)
5586                   : nops_for_insn_or_target (0, history, ip));
5587       if (nops > 0)
5588         {
5589           fragS *old_frag;
5590           unsigned long old_frag_offset;
5591           int i;
5592
5593           old_frag = frag_now;
5594           old_frag_offset = frag_now_fix ();
5595
5596           for (i = 0; i < nops; i++)
5597             add_fixed_insn (NOP_INSN);
5598           insert_into_history (0, nops, NOP_INSN);
5599
5600           if (listing)
5601             {
5602               listing_prev_line ();
5603               /* We may be at the start of a variant frag.  In case we
5604                  are, make sure there is enough space for the frag
5605                  after the frags created by listing_prev_line.  The
5606                  argument to frag_grow here must be at least as large
5607                  as the argument to all other calls to frag_grow in
5608                  this file.  We don't have to worry about being in the
5609                  middle of a variant frag, because the variants insert
5610                  all needed nop instructions themselves.  */
5611               frag_grow (40);
5612             }
5613
5614           mips_move_text_labels ();
5615
5616 #ifndef NO_ECOFF_DEBUGGING
5617           if (ECOFF_DEBUGGING)
5618             ecoff_fix_loc (old_frag, old_frag_offset);
5619 #endif
5620         }
5621     }
5622   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
5623     {
5624       int nops;
5625
5626       /* Work out how many nops in prev_nop_frag are needed by IP,
5627          ignoring hazards generated by the first prev_nop_frag_since
5628          instructions.  */
5629       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
5630       gas_assert (nops <= prev_nop_frag_holds);
5631
5632       /* Enforce NOPS as a minimum.  */
5633       if (nops > prev_nop_frag_required)
5634         prev_nop_frag_required = nops;
5635
5636       if (prev_nop_frag_holds == prev_nop_frag_required)
5637         {
5638           /* Settle for the current number of nops.  Update the history
5639              accordingly (for the benefit of any future .set reorder code).  */
5640           prev_nop_frag = NULL;
5641           insert_into_history (prev_nop_frag_since,
5642                                prev_nop_frag_holds, NOP_INSN);
5643         }
5644       else
5645         {
5646           /* Allow this instruction to replace one of the nops that was
5647              tentatively added to prev_nop_frag.  */
5648           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
5649           prev_nop_frag_holds--;
5650           prev_nop_frag_since++;
5651         }
5652     }
5653
5654   method = get_append_method (ip, address_expr, reloc_type);
5655   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
5656
5657   dwarf2_emit_insn (0);
5658   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
5659      so "move" the instruction address accordingly.
5660
5661      Also, it doesn't seem appropriate for the assembler to reorder .loc
5662      entries.  If this instruction is a branch that we are going to swap
5663      with the previous instruction, the two instructions should be
5664      treated as a unit, and the debug information for both instructions
5665      should refer to the start of the branch sequence.  Using the
5666      current position is certainly wrong when swapping a 32-bit branch
5667      and a 16-bit delay slot, since the current position would then be
5668      in the middle of a branch.  */
5669   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
5670
5671   relax32 = (mips_relax_branch
5672              /* Don't try branch relaxation within .set nomacro, or within
5673                 .set noat if we use $at for PIC computations.  If it turns
5674                 out that the branch was out-of-range, we'll get an error.  */
5675              && !mips_opts.warn_about_macros
5676              && (mips_opts.at || mips_pic == NO_PIC)
5677              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
5678                 as they have no complementing branches.  */
5679              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
5680
5681   if (!HAVE_CODE_COMPRESSION
5682       && address_expr
5683       && relax32
5684       && *reloc_type == BFD_RELOC_16_PCREL_S2
5685       && delayed_branch_p (ip))
5686     {
5687       relaxed_branch = TRUE;
5688       add_relaxed_insn (ip, (relaxed_branch_length
5689                              (NULL, NULL,
5690                               uncond_branch_p (ip) ? -1
5691                               : branch_likely_p (ip) ? 1
5692                               : 0)), 4,
5693                         RELAX_BRANCH_ENCODE
5694                         (AT,
5695                          uncond_branch_p (ip),
5696                          branch_likely_p (ip),
5697                          pinfo & INSN_WRITE_GPR_31,
5698                          0),
5699                         address_expr->X_add_symbol,
5700                         address_expr->X_add_number);
5701       *reloc_type = BFD_RELOC_UNUSED;
5702     }
5703   else if (mips_opts.micromips
5704            && address_expr
5705            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
5706                || *reloc_type > BFD_RELOC_UNUSED)
5707            && (delayed_branch_p (ip) || compact_branch_p (ip))
5708            /* Don't try branch relaxation when users specify
5709               16-bit/32-bit instructions.  */
5710            && !forced_insn_length)
5711     {
5712       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
5713       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
5714       int uncond = uncond_branch_p (ip) ? -1 : 0;
5715       int compact = compact_branch_p (ip);
5716       int al = pinfo & INSN_WRITE_GPR_31;
5717       int length32;
5718
5719       gas_assert (address_expr != NULL);
5720       gas_assert (!mips_relax.sequence);
5721
5722       relaxed_branch = TRUE;
5723       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
5724       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
5725                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
5726                                                 relax32, 0, 0),
5727                         address_expr->X_add_symbol,
5728                         address_expr->X_add_number);
5729       *reloc_type = BFD_RELOC_UNUSED;
5730     }
5731   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
5732     {
5733       /* We need to set up a variant frag.  */
5734       gas_assert (address_expr != NULL);
5735       add_relaxed_insn (ip, 4, 0,
5736                         RELAX_MIPS16_ENCODE
5737                         (*reloc_type - BFD_RELOC_UNUSED,
5738                          forced_insn_length == 2, forced_insn_length == 4,
5739                          delayed_branch_p (&history[0]),
5740                          history[0].mips16_absolute_jump_p),
5741                         make_expr_symbol (address_expr), 0);
5742     }
5743   else if (mips_opts.mips16 && insn_length (ip) == 2)
5744     {
5745       if (!delayed_branch_p (ip))
5746         /* Make sure there is enough room to swap this instruction with
5747            a following jump instruction.  */
5748         frag_grow (6);
5749       add_fixed_insn (ip);
5750     }
5751   else
5752     {
5753       if (mips_opts.mips16
5754           && mips_opts.noreorder
5755           && delayed_branch_p (&history[0]))
5756         as_warn (_("extended instruction in delay slot"));
5757
5758       if (mips_relax.sequence)
5759         {
5760           /* If we've reached the end of this frag, turn it into a variant
5761              frag and record the information for the instructions we've
5762              written so far.  */
5763           if (frag_room () < 4)
5764             relax_close_frag ();
5765           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
5766         }
5767
5768       if (mips_relax.sequence != 2)
5769         {
5770           if (mips_macro_warning.first_insn_sizes[0] == 0)
5771             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
5772           mips_macro_warning.sizes[0] += insn_length (ip);
5773           mips_macro_warning.insns[0]++;
5774         }
5775       if (mips_relax.sequence != 1)
5776         {
5777           if (mips_macro_warning.first_insn_sizes[1] == 0)
5778             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
5779           mips_macro_warning.sizes[1] += insn_length (ip);
5780           mips_macro_warning.insns[1]++;
5781         }
5782
5783       if (mips_opts.mips16)
5784         {
5785           ip->fixed_p = 1;
5786           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
5787         }
5788       add_fixed_insn (ip);
5789     }
5790
5791   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
5792     {
5793       bfd_reloc_code_real_type final_type[3];
5794       reloc_howto_type *howto0;
5795       reloc_howto_type *howto;
5796       int i;
5797
5798       /* Perform any necessary conversion to microMIPS relocations
5799          and find out how many relocations there actually are.  */
5800       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
5801         final_type[i] = micromips_map_reloc (reloc_type[i]);
5802
5803       /* In a compound relocation, it is the final (outermost)
5804          operator that determines the relocated field.  */
5805       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
5806       if (!howto)
5807         abort ();
5808
5809       if (i > 1)
5810         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
5811       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
5812                                  bfd_get_reloc_size (howto),
5813                                  address_expr,
5814                                  howto0 && howto0->pc_relative,
5815                                  final_type[0]);
5816
5817       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
5818       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
5819         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
5820
5821       /* These relocations can have an addend that won't fit in
5822          4 octets for 64bit assembly.  */
5823       if (HAVE_64BIT_GPRS
5824           && ! howto->partial_inplace
5825           && (reloc_type[0] == BFD_RELOC_16
5826               || reloc_type[0] == BFD_RELOC_32
5827               || reloc_type[0] == BFD_RELOC_MIPS_JMP
5828               || reloc_type[0] == BFD_RELOC_GPREL16
5829               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
5830               || reloc_type[0] == BFD_RELOC_GPREL32
5831               || reloc_type[0] == BFD_RELOC_64
5832               || reloc_type[0] == BFD_RELOC_CTOR
5833               || reloc_type[0] == BFD_RELOC_MIPS_SUB
5834               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
5835               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
5836               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
5837               || reloc_type[0] == BFD_RELOC_MIPS_REL16
5838               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
5839               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
5840               || hi16_reloc_p (reloc_type[0])
5841               || lo16_reloc_p (reloc_type[0])))
5842         ip->fixp[0]->fx_no_overflow = 1;
5843
5844       /* These relocations can have an addend that won't fit in 2 octets.  */
5845       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
5846           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
5847         ip->fixp[0]->fx_no_overflow = 1;
5848
5849       if (mips_relax.sequence)
5850         {
5851           if (mips_relax.first_fixup == 0)
5852             mips_relax.first_fixup = ip->fixp[0];
5853         }
5854       else if (reloc_needs_lo_p (*reloc_type))
5855         {
5856           struct mips_hi_fixup *hi_fixup;
5857
5858           /* Reuse the last entry if it already has a matching %lo.  */
5859           hi_fixup = mips_hi_fixup_list;
5860           if (hi_fixup == 0
5861               || !fixup_has_matching_lo_p (hi_fixup->fixp))
5862             {
5863               hi_fixup = ((struct mips_hi_fixup *)
5864                           xmalloc (sizeof (struct mips_hi_fixup)));
5865               hi_fixup->next = mips_hi_fixup_list;
5866               mips_hi_fixup_list = hi_fixup;
5867             }
5868           hi_fixup->fixp = ip->fixp[0];
5869           hi_fixup->seg = now_seg;
5870         }
5871
5872       /* Add fixups for the second and third relocations, if given.
5873          Note that the ABI allows the second relocation to be
5874          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
5875          moment we only use RSS_UNDEF, but we could add support
5876          for the others if it ever becomes necessary.  */
5877       for (i = 1; i < 3; i++)
5878         if (reloc_type[i] != BFD_RELOC_UNUSED)
5879           {
5880             ip->fixp[i] = fix_new (ip->frag, ip->where,
5881                                    ip->fixp[0]->fx_size, NULL, 0,
5882                                    FALSE, final_type[i]);
5883
5884             /* Use fx_tcbit to mark compound relocs.  */
5885             ip->fixp[0]->fx_tcbit = 1;
5886             ip->fixp[i]->fx_tcbit = 1;
5887           }
5888     }
5889   install_insn (ip);
5890
5891   /* Update the register mask information.  */
5892   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
5893   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
5894
5895   switch (method)
5896     {
5897     case APPEND_ADD:
5898       insert_into_history (0, 1, ip);
5899       break;
5900
5901     case APPEND_ADD_WITH_NOP:
5902       {
5903         struct mips_cl_insn *nop;
5904
5905         insert_into_history (0, 1, ip);
5906         nop = get_delay_slot_nop (ip);
5907         add_fixed_insn (nop);
5908         insert_into_history (0, 1, nop);
5909         if (mips_relax.sequence)
5910           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
5911       }
5912       break;
5913
5914     case APPEND_ADD_COMPACT:
5915       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
5916       gas_assert (mips_opts.mips16);
5917       ip->insn_opcode |= 0x0080;
5918       find_altered_mips16_opcode (ip);
5919       install_insn (ip);
5920       insert_into_history (0, 1, ip);
5921       break;
5922
5923     case APPEND_SWAP:
5924       {
5925         struct mips_cl_insn delay = history[0];
5926         if (mips_opts.mips16)
5927           {
5928             know (delay.frag == ip->frag);
5929             move_insn (ip, delay.frag, delay.where);
5930             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
5931           }
5932         else if (relaxed_branch || delay.frag != ip->frag)
5933           {
5934             /* Add the delay slot instruction to the end of the
5935                current frag and shrink the fixed part of the
5936                original frag.  If the branch occupies the tail of
5937                the latter, move it backwards to cover the gap.  */
5938             delay.frag->fr_fix -= branch_disp;
5939             if (delay.frag == ip->frag)
5940               move_insn (ip, ip->frag, ip->where - branch_disp);
5941             add_fixed_insn (&delay);
5942           }
5943         else
5944           {
5945             move_insn (&delay, ip->frag,
5946                        ip->where - branch_disp + insn_length (ip));
5947             move_insn (ip, history[0].frag, history[0].where);
5948           }
5949         history[0] = *ip;
5950         delay.fixed_p = 1;
5951         insert_into_history (0, 1, &delay);
5952       }
5953       break;
5954     }
5955
5956   /* If we have just completed an unconditional branch, clear the history.  */
5957   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
5958       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
5959     {
5960       unsigned int i;
5961
5962       mips_no_prev_insn ();
5963
5964       for (i = 0; i < ARRAY_SIZE (history); i++)
5965         history[i].cleared_p = 1;
5966     }
5967
5968   /* We need to emit a label at the end of branch-likely macros.  */
5969   if (emit_branch_likely_macro)
5970     {
5971       emit_branch_likely_macro = FALSE;
5972       micromips_add_label ();
5973     }
5974
5975   /* We just output an insn, so the next one doesn't have a label.  */
5976   mips_clear_insn_labels ();
5977 }
5978
5979 /* Forget that there was any previous instruction or label.
5980    When BRANCH is true, the branch history is also flushed.  */
5981
5982 static void
5983 mips_no_prev_insn (void)
5984 {
5985   prev_nop_frag = NULL;
5986   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
5987   mips_clear_insn_labels ();
5988 }
5989
5990 /* This function must be called before we emit something other than
5991    instructions.  It is like mips_no_prev_insn except that it inserts
5992    any NOPS that might be needed by previous instructions.  */
5993
5994 void
5995 mips_emit_delays (void)
5996 {
5997   if (! mips_opts.noreorder)
5998     {
5999       int nops = nops_for_insn (0, history, NULL);
6000       if (nops > 0)
6001         {
6002           while (nops-- > 0)
6003             add_fixed_insn (NOP_INSN);
6004           mips_move_text_labels ();
6005         }
6006     }
6007   mips_no_prev_insn ();
6008 }
6009
6010 /* Start a (possibly nested) noreorder block.  */
6011
6012 static void
6013 start_noreorder (void)
6014 {
6015   if (mips_opts.noreorder == 0)
6016     {
6017       unsigned int i;
6018       int nops;
6019
6020       /* None of the instructions before the .set noreorder can be moved.  */
6021       for (i = 0; i < ARRAY_SIZE (history); i++)
6022         history[i].fixed_p = 1;
6023
6024       /* Insert any nops that might be needed between the .set noreorder
6025          block and the previous instructions.  We will later remove any
6026          nops that turn out not to be needed.  */
6027       nops = nops_for_insn (0, history, NULL);
6028       if (nops > 0)
6029         {
6030           if (mips_optimize != 0)
6031             {
6032               /* Record the frag which holds the nop instructions, so
6033                  that we can remove them if we don't need them.  */
6034               frag_grow (nops * NOP_INSN_SIZE);
6035               prev_nop_frag = frag_now;
6036               prev_nop_frag_holds = nops;
6037               prev_nop_frag_required = 0;
6038               prev_nop_frag_since = 0;
6039             }
6040
6041           for (; nops > 0; --nops)
6042             add_fixed_insn (NOP_INSN);
6043
6044           /* Move on to a new frag, so that it is safe to simply
6045              decrease the size of prev_nop_frag.  */
6046           frag_wane (frag_now);
6047           frag_new (0);
6048           mips_move_text_labels ();
6049         }
6050       mips_mark_labels ();
6051       mips_clear_insn_labels ();
6052     }
6053   mips_opts.noreorder++;
6054   mips_any_noreorder = 1;
6055 }
6056
6057 /* End a nested noreorder block.  */
6058
6059 static void
6060 end_noreorder (void)
6061 {
6062   mips_opts.noreorder--;
6063   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6064     {
6065       /* Commit to inserting prev_nop_frag_required nops and go back to
6066          handling nop insertion the .set reorder way.  */
6067       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6068                                 * NOP_INSN_SIZE);
6069       insert_into_history (prev_nop_frag_since,
6070                            prev_nop_frag_required, NOP_INSN);
6071       prev_nop_frag = NULL;
6072     }
6073 }
6074
6075 /* Set up global variables for the start of a new macro.  */
6076
6077 static void
6078 macro_start (void)
6079 {
6080   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
6081   memset (&mips_macro_warning.first_insn_sizes, 0,
6082           sizeof (mips_macro_warning.first_insn_sizes));
6083   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
6084   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
6085                                      && delayed_branch_p (&history[0]));
6086   switch (history[0].insn_mo->pinfo2
6087           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
6088     {
6089     case INSN2_BRANCH_DELAY_32BIT:
6090       mips_macro_warning.delay_slot_length = 4;
6091       break;
6092     case INSN2_BRANCH_DELAY_16BIT:
6093       mips_macro_warning.delay_slot_length = 2;
6094       break;
6095     default:
6096       mips_macro_warning.delay_slot_length = 0;
6097       break;
6098     }
6099   mips_macro_warning.first_frag = NULL;
6100 }
6101
6102 /* Given that a macro is longer than one instruction or of the wrong size,
6103    return the appropriate warning for it.  Return null if no warning is
6104    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
6105    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
6106    and RELAX_NOMACRO.  */
6107
6108 static const char *
6109 macro_warning (relax_substateT subtype)
6110 {
6111   if (subtype & RELAX_DELAY_SLOT)
6112     return _("Macro instruction expanded into multiple instructions"
6113              " in a branch delay slot");
6114   else if (subtype & RELAX_NOMACRO)
6115     return _("Macro instruction expanded into multiple instructions");
6116   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
6117                       | RELAX_DELAY_SLOT_SIZE_SECOND))
6118     return ((subtype & RELAX_DELAY_SLOT_16BIT)
6119             ? _("Macro instruction expanded into a wrong size instruction"
6120                 " in a 16-bit branch delay slot")
6121             : _("Macro instruction expanded into a wrong size instruction"
6122                 " in a 32-bit branch delay slot"));
6123   else
6124     return 0;
6125 }
6126
6127 /* Finish up a macro.  Emit warnings as appropriate.  */
6128
6129 static void
6130 macro_end (void)
6131 {
6132   /* Relaxation warning flags.  */
6133   relax_substateT subtype = 0;
6134
6135   /* Check delay slot size requirements.  */
6136   if (mips_macro_warning.delay_slot_length == 2)
6137     subtype |= RELAX_DELAY_SLOT_16BIT;
6138   if (mips_macro_warning.delay_slot_length != 0)
6139     {
6140       if (mips_macro_warning.delay_slot_length
6141           != mips_macro_warning.first_insn_sizes[0])
6142         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
6143       if (mips_macro_warning.delay_slot_length
6144           != mips_macro_warning.first_insn_sizes[1])
6145         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
6146     }
6147
6148   /* Check instruction count requirements.  */
6149   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
6150     {
6151       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
6152         subtype |= RELAX_SECOND_LONGER;
6153       if (mips_opts.warn_about_macros)
6154         subtype |= RELAX_NOMACRO;
6155       if (mips_macro_warning.delay_slot_p)
6156         subtype |= RELAX_DELAY_SLOT;
6157     }
6158
6159   /* If both alternatives fail to fill a delay slot correctly,
6160      emit the warning now.  */
6161   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
6162       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
6163     {
6164       relax_substateT s;
6165       const char *msg;
6166
6167       s = subtype & (RELAX_DELAY_SLOT_16BIT
6168                      | RELAX_DELAY_SLOT_SIZE_FIRST
6169                      | RELAX_DELAY_SLOT_SIZE_SECOND);
6170       msg = macro_warning (s);
6171       if (msg != NULL)
6172         as_warn ("%s", msg);
6173       subtype &= ~s;
6174     }
6175
6176   /* If both implementations are longer than 1 instruction, then emit the
6177      warning now.  */
6178   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
6179     {
6180       relax_substateT s;
6181       const char *msg;
6182
6183       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
6184       msg = macro_warning (s);
6185       if (msg != NULL)
6186         as_warn ("%s", msg);
6187       subtype &= ~s;
6188     }
6189
6190   /* If any flags still set, then one implementation might need a warning
6191      and the other either will need one of a different kind or none at all.
6192      Pass any remaining flags over to relaxation.  */
6193   if (mips_macro_warning.first_frag != NULL)
6194     mips_macro_warning.first_frag->fr_subtype |= subtype;
6195 }
6196
6197 /* Instruction operand formats used in macros that vary between
6198    standard MIPS and microMIPS code.  */
6199
6200 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
6201 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
6202 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
6203 static const char * const lui_fmt[2] = { "t,u", "s,u" };
6204 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
6205 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
6206 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
6207 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
6208
6209 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
6210 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
6211 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
6212 #define LUI_FMT (lui_fmt[mips_opts.micromips])
6213 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
6214 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
6215 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
6216 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
6217
6218 /* Read a macro's relocation codes from *ARGS and store them in *R.
6219    The first argument in *ARGS will be either the code for a single
6220    relocation or -1 followed by the three codes that make up a
6221    composite relocation.  */
6222
6223 static void
6224 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
6225 {
6226   int i, next;
6227
6228   next = va_arg (*args, int);
6229   if (next >= 0)
6230     r[0] = (bfd_reloc_code_real_type) next;
6231   else
6232     {
6233       for (i = 0; i < 3; i++)
6234         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
6235       /* This function is only used for 16-bit relocation fields.
6236          To make the macro code simpler, treat an unrelocated value
6237          in the same way as BFD_RELOC_LO16.  */
6238       if (r[0] == BFD_RELOC_UNUSED)
6239         r[0] = BFD_RELOC_LO16;
6240     }
6241 }
6242
6243 /* Build an instruction created by a macro expansion.  This is passed
6244    a pointer to the count of instructions created so far, an
6245    expression, the name of the instruction to build, an operand format
6246    string, and corresponding arguments.  */
6247
6248 static void
6249 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
6250 {
6251   const struct mips_opcode *mo = NULL;
6252   bfd_reloc_code_real_type r[3];
6253   const struct mips_opcode *amo;
6254   const struct mips_operand *operand;
6255   struct hash_control *hash;
6256   struct mips_cl_insn insn;
6257   va_list args;
6258   unsigned int uval;
6259
6260   va_start (args, fmt);
6261
6262   if (mips_opts.mips16)
6263     {
6264       mips16_macro_build (ep, name, fmt, &args);
6265       va_end (args);
6266       return;
6267     }
6268
6269   r[0] = BFD_RELOC_UNUSED;
6270   r[1] = BFD_RELOC_UNUSED;
6271   r[2] = BFD_RELOC_UNUSED;
6272   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
6273   amo = (struct mips_opcode *) hash_find (hash, name);
6274   gas_assert (amo);
6275   gas_assert (strcmp (name, amo->name) == 0);
6276
6277   do
6278     {
6279       /* Search until we get a match for NAME.  It is assumed here that
6280          macros will never generate MDMX, MIPS-3D, or MT instructions.
6281          We try to match an instruction that fulfils the branch delay
6282          slot instruction length requirement (if any) of the previous
6283          instruction.  While doing this we record the first instruction
6284          seen that matches all the other conditions and use it anyway
6285          if the requirement cannot be met; we will issue an appropriate
6286          warning later on.  */
6287       if (strcmp (fmt, amo->args) == 0
6288           && amo->pinfo != INSN_MACRO
6289           && is_opcode_valid (amo)
6290           && is_size_valid (amo))
6291         {
6292           if (is_delay_slot_valid (amo))
6293             {
6294               mo = amo;
6295               break;
6296             }
6297           else if (!mo)
6298             mo = amo;
6299         }
6300
6301       ++amo;
6302       gas_assert (amo->name);
6303     }
6304   while (strcmp (name, amo->name) == 0);
6305
6306   gas_assert (mo);
6307   create_insn (&insn, mo);
6308   for (; *fmt; ++fmt)
6309     {
6310       switch (*fmt)
6311         {
6312         case ',':
6313         case '(':
6314         case ')':
6315         case 'z':
6316           break;
6317
6318         case 'i':
6319         case 'j':
6320           macro_read_relocs (&args, r);
6321           gas_assert (*r == BFD_RELOC_GPREL16
6322                       || *r == BFD_RELOC_MIPS_HIGHER
6323                       || *r == BFD_RELOC_HI16_S
6324                       || *r == BFD_RELOC_LO16
6325                       || *r == BFD_RELOC_MIPS_GOT_OFST);
6326           break;
6327
6328         case 'o':
6329           macro_read_relocs (&args, r);
6330           break;
6331
6332         case 'u':
6333           macro_read_relocs (&args, r);
6334           gas_assert (ep != NULL
6335                       && (ep->X_op == O_constant
6336                           || (ep->X_op == O_symbol
6337                               && (*r == BFD_RELOC_MIPS_HIGHEST
6338                                   || *r == BFD_RELOC_HI16_S
6339                                   || *r == BFD_RELOC_HI16
6340                                   || *r == BFD_RELOC_GPREL16
6341                                   || *r == BFD_RELOC_MIPS_GOT_HI16
6342                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
6343           break;
6344
6345         case 'p':
6346           gas_assert (ep != NULL);
6347
6348           /*
6349            * This allows macro() to pass an immediate expression for
6350            * creating short branches without creating a symbol.
6351            *
6352            * We don't allow branch relaxation for these branches, as
6353            * they should only appear in ".set nomacro" anyway.
6354            */
6355           if (ep->X_op == O_constant)
6356             {
6357               /* For microMIPS we always use relocations for branches.
6358                  So we should not resolve immediate values.  */
6359               gas_assert (!mips_opts.micromips);
6360
6361               if ((ep->X_add_number & 3) != 0)
6362                 as_bad (_("branch to misaligned address (0x%lx)"),
6363                         (unsigned long) ep->X_add_number);
6364               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
6365                 as_bad (_("branch address range overflow (0x%lx)"),
6366                         (unsigned long) ep->X_add_number);
6367               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
6368               ep = NULL;
6369             }
6370           else
6371             *r = BFD_RELOC_16_PCREL_S2;
6372           break;
6373
6374         case 'a':
6375           gas_assert (ep != NULL);
6376           *r = BFD_RELOC_MIPS_JMP;
6377           break;
6378
6379         default:
6380           operand = (mips_opts.micromips
6381                      ? decode_micromips_operand (fmt)
6382                      : decode_mips_operand (fmt));
6383           if (!operand)
6384             abort ();
6385
6386           uval = va_arg (args, int);
6387           if (operand->type == OP_CLO_CLZ_DEST)
6388             uval |= (uval << 5);
6389           insn_insert_operand (&insn, operand, uval);
6390
6391           if (*fmt == '+' || *fmt == 'm')
6392             ++fmt;
6393           break;
6394         }
6395     }
6396   va_end (args);
6397   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6398
6399   append_insn (&insn, ep, r, TRUE);
6400 }
6401
6402 static void
6403 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
6404                     va_list *args)
6405 {
6406   struct mips_opcode *mo;
6407   struct mips_cl_insn insn;
6408   const struct mips_operand *operand;
6409   bfd_reloc_code_real_type r[3]
6410     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
6411
6412   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
6413   gas_assert (mo);
6414   gas_assert (strcmp (name, mo->name) == 0);
6415
6416   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
6417     {
6418       ++mo;
6419       gas_assert (mo->name);
6420       gas_assert (strcmp (name, mo->name) == 0);
6421     }
6422
6423   create_insn (&insn, mo);
6424   for (; *fmt; ++fmt)
6425     {
6426       int c;
6427
6428       c = *fmt;
6429       switch (c)
6430         {
6431         case ',':
6432         case '(':
6433         case ')':
6434           break;
6435
6436         case '0':
6437         case 'S':
6438         case 'P':
6439         case 'R':
6440           break;
6441
6442         case '<':
6443         case '>':
6444         case '4':
6445         case '5':
6446         case 'H':
6447         case 'W':
6448         case 'D':
6449         case 'j':
6450         case '8':
6451         case 'V':
6452         case 'C':
6453         case 'U':
6454         case 'k':
6455         case 'K':
6456         case 'p':
6457         case 'q':
6458           {
6459             offsetT value;
6460
6461             gas_assert (ep != NULL);
6462
6463             if (ep->X_op != O_constant)
6464               *r = (int) BFD_RELOC_UNUSED + c;
6465             else if (calculate_reloc (*r, ep->X_add_number, &value))
6466               {
6467                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
6468                 ep = NULL;
6469                 *r = BFD_RELOC_UNUSED;
6470               }
6471           }
6472           break;
6473
6474         default:
6475           operand = decode_mips16_operand (c, FALSE);
6476           if (!operand)
6477             abort ();
6478
6479           insn_insert_operand (&insn, operand, va_arg (args, int));
6480           break;
6481         }
6482     }
6483
6484   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
6485
6486   append_insn (&insn, ep, r, TRUE);
6487 }
6488
6489 /*
6490  * Sign-extend 32-bit mode constants that have bit 31 set and all
6491  * higher bits unset.
6492  */
6493 static void
6494 normalize_constant_expr (expressionS *ex)
6495 {
6496   if (ex->X_op == O_constant
6497       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6498     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6499                         - 0x80000000);
6500 }
6501
6502 /*
6503  * Sign-extend 32-bit mode address offsets that have bit 31 set and
6504  * all higher bits unset.
6505  */
6506 static void
6507 normalize_address_expr (expressionS *ex)
6508 {
6509   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
6510         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
6511       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6512     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6513                         - 0x80000000);
6514 }
6515
6516 /*
6517  * Generate a "jalr" instruction with a relocation hint to the called
6518  * function.  This occurs in NewABI PIC code.
6519  */
6520 static void
6521 macro_build_jalr (expressionS *ep, int cprestore)
6522 {
6523   static const bfd_reloc_code_real_type jalr_relocs[2]
6524     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
6525   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
6526   const char *jalr;
6527   char *f = NULL;
6528
6529   if (MIPS_JALR_HINT_P (ep))
6530     {
6531       frag_grow (8);
6532       f = frag_more (0);
6533     }
6534   if (mips_opts.micromips)
6535     {
6536       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
6537               ? "jalr" : "jalrs");
6538       if (MIPS_JALR_HINT_P (ep)
6539           || mips_opts.insn32
6540           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6541         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
6542       else
6543         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
6544     }
6545   else
6546     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
6547   if (MIPS_JALR_HINT_P (ep))
6548     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
6549 }
6550
6551 /*
6552  * Generate a "lui" instruction.
6553  */
6554 static void
6555 macro_build_lui (expressionS *ep, int regnum)
6556 {
6557   gas_assert (! mips_opts.mips16);
6558
6559   if (ep->X_op != O_constant)
6560     {
6561       gas_assert (ep->X_op == O_symbol);
6562       /* _gp_disp is a special case, used from s_cpload.
6563          __gnu_local_gp is used if mips_no_shared.  */
6564       gas_assert (mips_pic == NO_PIC
6565               || (! HAVE_NEWABI
6566                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
6567               || (! mips_in_shared
6568                   && strcmp (S_GET_NAME (ep->X_add_symbol),
6569                              "__gnu_local_gp") == 0));
6570     }
6571
6572   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
6573 }
6574
6575 /* Generate a sequence of instructions to do a load or store from a constant
6576    offset off of a base register (breg) into/from a target register (treg),
6577    using AT if necessary.  */
6578 static void
6579 macro_build_ldst_constoffset (expressionS *ep, const char *op,
6580                               int treg, int breg, int dbl)
6581 {
6582   gas_assert (ep->X_op == O_constant);
6583
6584   /* Sign-extending 32-bit constants makes their handling easier.  */
6585   if (!dbl)
6586     normalize_constant_expr (ep);
6587
6588   /* Right now, this routine can only handle signed 32-bit constants.  */
6589   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
6590     as_warn (_("operand overflow"));
6591
6592   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
6593     {
6594       /* Signed 16-bit offset will fit in the op.  Easy!  */
6595       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
6596     }
6597   else
6598     {
6599       /* 32-bit offset, need multiple instructions and AT, like:
6600            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
6601            addu     $tempreg,$tempreg,$breg
6602            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
6603          to handle the complete offset.  */
6604       macro_build_lui (ep, AT);
6605       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
6606       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
6607
6608       if (!mips_opts.at)
6609         as_bad (_("Macro used $at after \".set noat\""));
6610     }
6611 }
6612
6613 /*                      set_at()
6614  * Generates code to set the $at register to true (one)
6615  * if reg is less than the immediate expression.
6616  */
6617 static void
6618 set_at (int reg, int unsignedp)
6619 {
6620   if (imm_expr.X_op == O_constant
6621       && imm_expr.X_add_number >= -0x8000
6622       && imm_expr.X_add_number < 0x8000)
6623     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
6624                  AT, reg, BFD_RELOC_LO16);
6625   else
6626     {
6627       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
6628       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
6629     }
6630 }
6631
6632 /* Warn if an expression is not a constant.  */
6633
6634 static void
6635 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
6636 {
6637   if (ex->X_op == O_big)
6638     as_bad (_("unsupported large constant"));
6639   else if (ex->X_op != O_constant)
6640     as_bad (_("Instruction %s requires absolute expression"),
6641             ip->insn_mo->name);
6642
6643   if (HAVE_32BIT_GPRS)
6644     normalize_constant_expr (ex);
6645 }
6646
6647 /* Count the leading zeroes by performing a binary chop. This is a
6648    bulky bit of source, but performance is a LOT better for the
6649    majority of values than a simple loop to count the bits:
6650        for (lcnt = 0; (lcnt < 32); lcnt++)
6651          if ((v) & (1 << (31 - lcnt)))
6652            break;
6653   However it is not code size friendly, and the gain will drop a bit
6654   on certain cached systems.
6655 */
6656 #define COUNT_TOP_ZEROES(v)             \
6657   (((v) & ~0xffff) == 0                 \
6658    ? ((v) & ~0xff) == 0                 \
6659      ? ((v) & ~0xf) == 0                \
6660        ? ((v) & ~0x3) == 0              \
6661          ? ((v) & ~0x1) == 0            \
6662            ? !(v)                       \
6663              ? 32                       \
6664              : 31                       \
6665            : 30                         \
6666          : ((v) & ~0x7) == 0            \
6667            ? 29                         \
6668            : 28                         \
6669        : ((v) & ~0x3f) == 0             \
6670          ? ((v) & ~0x1f) == 0           \
6671            ? 27                         \
6672            : 26                         \
6673          : ((v) & ~0x7f) == 0           \
6674            ? 25                         \
6675            : 24                         \
6676      : ((v) & ~0xfff) == 0              \
6677        ? ((v) & ~0x3ff) == 0            \
6678          ? ((v) & ~0x1ff) == 0          \
6679            ? 23                         \
6680            : 22                         \
6681          : ((v) & ~0x7ff) == 0          \
6682            ? 21                         \
6683            : 20                         \
6684        : ((v) & ~0x3fff) == 0           \
6685          ? ((v) & ~0x1fff) == 0         \
6686            ? 19                         \
6687            : 18                         \
6688          : ((v) & ~0x7fff) == 0         \
6689            ? 17                         \
6690            : 16                         \
6691    : ((v) & ~0xffffff) == 0             \
6692      ? ((v) & ~0xfffff) == 0            \
6693        ? ((v) & ~0x3ffff) == 0          \
6694          ? ((v) & ~0x1ffff) == 0        \
6695            ? 15                         \
6696            : 14                         \
6697          : ((v) & ~0x7ffff) == 0        \
6698            ? 13                         \
6699            : 12                         \
6700        : ((v) & ~0x3fffff) == 0         \
6701          ? ((v) & ~0x1fffff) == 0       \
6702            ? 11                         \
6703            : 10                         \
6704          : ((v) & ~0x7fffff) == 0       \
6705            ? 9                          \
6706            : 8                          \
6707      : ((v) & ~0xfffffff) == 0          \
6708        ? ((v) & ~0x3ffffff) == 0        \
6709          ? ((v) & ~0x1ffffff) == 0      \
6710            ? 7                          \
6711            : 6                          \
6712          : ((v) & ~0x7ffffff) == 0      \
6713            ? 5                          \
6714            : 4                          \
6715        : ((v) & ~0x3fffffff) == 0       \
6716          ? ((v) & ~0x1fffffff) == 0     \
6717            ? 3                          \
6718            : 2                          \
6719          : ((v) & ~0x7fffffff) == 0     \
6720            ? 1                          \
6721            : 0)
6722
6723 /*                      load_register()
6724  *  This routine generates the least number of instructions necessary to load
6725  *  an absolute expression value into a register.
6726  */
6727 static void
6728 load_register (int reg, expressionS *ep, int dbl)
6729 {
6730   int freg;
6731   expressionS hi32, lo32;
6732
6733   if (ep->X_op != O_big)
6734     {
6735       gas_assert (ep->X_op == O_constant);
6736
6737       /* Sign-extending 32-bit constants makes their handling easier.  */
6738       if (!dbl)
6739         normalize_constant_expr (ep);
6740
6741       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
6742         {
6743           /* We can handle 16 bit signed values with an addiu to
6744              $zero.  No need to ever use daddiu here, since $zero and
6745              the result are always correct in 32 bit mode.  */
6746           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6747           return;
6748         }
6749       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
6750         {
6751           /* We can handle 16 bit unsigned values with an ori to
6752              $zero.  */
6753           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6754           return;
6755         }
6756       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
6757         {
6758           /* 32 bit values require an lui.  */
6759           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6760           if ((ep->X_add_number & 0xffff) != 0)
6761             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6762           return;
6763         }
6764     }
6765
6766   /* The value is larger than 32 bits.  */
6767
6768   if (!dbl || HAVE_32BIT_GPRS)
6769     {
6770       char value[32];
6771
6772       sprintf_vma (value, ep->X_add_number);
6773       as_bad (_("Number (0x%s) larger than 32 bits"), value);
6774       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6775       return;
6776     }
6777
6778   if (ep->X_op != O_big)
6779     {
6780       hi32 = *ep;
6781       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6782       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6783       hi32.X_add_number &= 0xffffffff;
6784       lo32 = *ep;
6785       lo32.X_add_number &= 0xffffffff;
6786     }
6787   else
6788     {
6789       gas_assert (ep->X_add_number > 2);
6790       if (ep->X_add_number == 3)
6791         generic_bignum[3] = 0;
6792       else if (ep->X_add_number > 4)
6793         as_bad (_("Number larger than 64 bits"));
6794       lo32.X_op = O_constant;
6795       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
6796       hi32.X_op = O_constant;
6797       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
6798     }
6799
6800   if (hi32.X_add_number == 0)
6801     freg = 0;
6802   else
6803     {
6804       int shift, bit;
6805       unsigned long hi, lo;
6806
6807       if (hi32.X_add_number == (offsetT) 0xffffffff)
6808         {
6809           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
6810             {
6811               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6812               return;
6813             }
6814           if (lo32.X_add_number & 0x80000000)
6815             {
6816               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6817               if (lo32.X_add_number & 0xffff)
6818                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6819               return;
6820             }
6821         }
6822
6823       /* Check for 16bit shifted constant.  We know that hi32 is
6824          non-zero, so start the mask on the first bit of the hi32
6825          value.  */
6826       shift = 17;
6827       do
6828         {
6829           unsigned long himask, lomask;
6830
6831           if (shift < 32)
6832             {
6833               himask = 0xffff >> (32 - shift);
6834               lomask = (0xffff << shift) & 0xffffffff;
6835             }
6836           else
6837             {
6838               himask = 0xffff << (shift - 32);
6839               lomask = 0;
6840             }
6841           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6842               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6843             {
6844               expressionS tmp;
6845
6846               tmp.X_op = O_constant;
6847               if (shift < 32)
6848                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6849                                     | (lo32.X_add_number >> shift));
6850               else
6851                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
6852               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6853               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6854                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6855               return;
6856             }
6857           ++shift;
6858         }
6859       while (shift <= (64 - 16));
6860
6861       /* Find the bit number of the lowest one bit, and store the
6862          shifted value in hi/lo.  */
6863       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
6864       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
6865       if (lo != 0)
6866         {
6867           bit = 0;
6868           while ((lo & 1) == 0)
6869             {
6870               lo >>= 1;
6871               ++bit;
6872             }
6873           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
6874           hi >>= bit;
6875         }
6876       else
6877         {
6878           bit = 32;
6879           while ((hi & 1) == 0)
6880             {
6881               hi >>= 1;
6882               ++bit;
6883             }
6884           lo = hi;
6885           hi = 0;
6886         }
6887
6888       /* Optimize if the shifted value is a (power of 2) - 1.  */
6889       if ((hi == 0 && ((lo + 1) & lo) == 0)
6890           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
6891         {
6892           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
6893           if (shift != 0)
6894             {
6895               expressionS tmp;
6896
6897               /* This instruction will set the register to be all
6898                  ones.  */
6899               tmp.X_op = O_constant;
6900               tmp.X_add_number = (offsetT) -1;
6901               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6902               if (bit != 0)
6903                 {
6904                   bit += shift;
6905                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6906                                reg, reg, (bit >= 32) ? bit - 32 : bit);
6907                 }
6908               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
6909                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6910               return;
6911             }
6912         }
6913
6914       /* Sign extend hi32 before calling load_register, because we can
6915          generally get better code when we load a sign extended value.  */
6916       if ((hi32.X_add_number & 0x80000000) != 0)
6917         hi32.X_add_number |= ~(offsetT) 0xffffffff;
6918       load_register (reg, &hi32, 0);
6919       freg = reg;
6920     }
6921   if ((lo32.X_add_number & 0xffff0000) == 0)
6922     {
6923       if (freg != 0)
6924         {
6925           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
6926           freg = reg;
6927         }
6928     }
6929   else
6930     {
6931       expressionS mid16;
6932
6933       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
6934         {
6935           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6936           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
6937           return;
6938         }
6939
6940       if (freg != 0)
6941         {
6942           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
6943           freg = reg;
6944         }
6945       mid16 = lo32;
6946       mid16.X_add_number >>= 16;
6947       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6948       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6949       freg = reg;
6950     }
6951   if ((lo32.X_add_number & 0xffff) != 0)
6952     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6953 }
6954
6955 static inline void
6956 load_delay_nop (void)
6957 {
6958   if (!gpr_interlocks)
6959     macro_build (NULL, "nop", "");
6960 }
6961
6962 /* Load an address into a register.  */
6963
6964 static void
6965 load_address (int reg, expressionS *ep, int *used_at)
6966 {
6967   if (ep->X_op != O_constant
6968       && ep->X_op != O_symbol)
6969     {
6970       as_bad (_("expression too complex"));
6971       ep->X_op = O_constant;
6972     }
6973
6974   if (ep->X_op == O_constant)
6975     {
6976       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
6977       return;
6978     }
6979
6980   if (mips_pic == NO_PIC)
6981     {
6982       /* If this is a reference to a GP relative symbol, we want
6983            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
6984          Otherwise we want
6985            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
6986            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6987          If we have an addend, we always use the latter form.
6988
6989          With 64bit address space and a usable $at we want
6990            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6991            lui          $at,<sym>               (BFD_RELOC_HI16_S)
6992            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6993            daddiu       $at,<sym>               (BFD_RELOC_LO16)
6994            dsll32       $reg,0
6995            daddu        $reg,$reg,$at
6996
6997          If $at is already in use, we use a path which is suboptimal
6998          on superscalar processors.
6999            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
7000            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
7001            dsll         $reg,16
7002            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
7003            dsll         $reg,16
7004            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
7005
7006          For GP relative symbols in 64bit address space we can use
7007          the same sequence as in 32bit address space.  */
7008       if (HAVE_64BIT_SYMBOLS)
7009         {
7010           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7011               && !nopic_need_relax (ep->X_add_symbol, 1))
7012             {
7013               relax_start (ep->X_add_symbol);
7014               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7015                            mips_gp_register, BFD_RELOC_GPREL16);
7016               relax_switch ();
7017             }
7018
7019           if (*used_at == 0 && mips_opts.at)
7020             {
7021               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7022               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
7023               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7024                            BFD_RELOC_MIPS_HIGHER);
7025               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
7026               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
7027               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
7028               *used_at = 1;
7029             }
7030           else
7031             {
7032               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
7033               macro_build (ep, "daddiu", "t,r,j", reg, reg,
7034                            BFD_RELOC_MIPS_HIGHER);
7035               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7036               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
7037               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
7038               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
7039             }
7040
7041           if (mips_relax.sequence)
7042             relax_end ();
7043         }
7044       else
7045         {
7046           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
7047               && !nopic_need_relax (ep->X_add_symbol, 1))
7048             {
7049               relax_start (ep->X_add_symbol);
7050               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
7051                            mips_gp_register, BFD_RELOC_GPREL16);
7052               relax_switch ();
7053             }
7054           macro_build_lui (ep, reg);
7055           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
7056                        reg, reg, BFD_RELOC_LO16);
7057           if (mips_relax.sequence)
7058             relax_end ();
7059         }
7060     }
7061   else if (!mips_big_got)
7062     {
7063       expressionS ex;
7064
7065       /* If this is a reference to an external symbol, we want
7066            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7067          Otherwise we want
7068            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7069            nop
7070            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7071          If there is a constant, it must be added in after.
7072
7073          If we have NewABI, we want
7074            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7075          unless we're referencing a global symbol with a non-zero
7076          offset, in which case cst must be added separately.  */
7077       if (HAVE_NEWABI)
7078         {
7079           if (ep->X_add_number)
7080             {
7081               ex.X_add_number = ep->X_add_number;
7082               ep->X_add_number = 0;
7083               relax_start (ep->X_add_symbol);
7084               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7085                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7086               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7087                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7088               ex.X_op = O_constant;
7089               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7090                            reg, reg, BFD_RELOC_LO16);
7091               ep->X_add_number = ex.X_add_number;
7092               relax_switch ();
7093             }
7094           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7095                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7096           if (mips_relax.sequence)
7097             relax_end ();
7098         }
7099       else
7100         {
7101           ex.X_add_number = ep->X_add_number;
7102           ep->X_add_number = 0;
7103           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7104                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7105           load_delay_nop ();
7106           relax_start (ep->X_add_symbol);
7107           relax_switch ();
7108           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7109                        BFD_RELOC_LO16);
7110           relax_end ();
7111
7112           if (ex.X_add_number != 0)
7113             {
7114               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7115                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7116               ex.X_op = O_constant;
7117               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
7118                            reg, reg, BFD_RELOC_LO16);
7119             }
7120         }
7121     }
7122   else if (mips_big_got)
7123     {
7124       expressionS ex;
7125
7126       /* This is the large GOT case.  If this is a reference to an
7127          external symbol, we want
7128            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
7129            addu         $reg,$reg,$gp
7130            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
7131
7132          Otherwise, for a reference to a local symbol in old ABI, we want
7133            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
7134            nop
7135            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
7136          If there is a constant, it must be added in after.
7137
7138          In the NewABI, for local symbols, with or without offsets, we want:
7139            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
7140            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
7141       */
7142       if (HAVE_NEWABI)
7143         {
7144           ex.X_add_number = ep->X_add_number;
7145           ep->X_add_number = 0;
7146           relax_start (ep->X_add_symbol);
7147           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7148           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7149                        reg, reg, mips_gp_register);
7150           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7151                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7152           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7153             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7154           else if (ex.X_add_number)
7155             {
7156               ex.X_op = O_constant;
7157               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7158                            BFD_RELOC_LO16);
7159             }
7160
7161           ep->X_add_number = ex.X_add_number;
7162           relax_switch ();
7163           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7164                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
7165           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7166                        BFD_RELOC_MIPS_GOT_OFST);
7167           relax_end ();
7168         }
7169       else
7170         {
7171           ex.X_add_number = ep->X_add_number;
7172           ep->X_add_number = 0;
7173           relax_start (ep->X_add_symbol);
7174           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
7175           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7176                        reg, reg, mips_gp_register);
7177           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
7178                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
7179           relax_switch ();
7180           if (reg_needs_delay (mips_gp_register))
7181             {
7182               /* We need a nop before loading from $gp.  This special
7183                  check is required because the lui which starts the main
7184                  instruction stream does not refer to $gp, and so will not
7185                  insert the nop which may be required.  */
7186               macro_build (NULL, "nop", "");
7187             }
7188           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
7189                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
7190           load_delay_nop ();
7191           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7192                        BFD_RELOC_LO16);
7193           relax_end ();
7194
7195           if (ex.X_add_number != 0)
7196             {
7197               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
7198                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
7199               ex.X_op = O_constant;
7200               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
7201                            BFD_RELOC_LO16);
7202             }
7203         }
7204     }
7205   else
7206     abort ();
7207
7208   if (!mips_opts.at && *used_at == 1)
7209     as_bad (_("Macro used $at after \".set noat\""));
7210 }
7211
7212 /* Move the contents of register SOURCE into register DEST.  */
7213
7214 static void
7215 move_register (int dest, int source)
7216 {
7217   /* Prefer to use a 16-bit microMIPS instruction unless the previous
7218      instruction specifically requires a 32-bit one.  */
7219   if (mips_opts.micromips
7220       && !mips_opts.insn32
7221       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7222     macro_build (NULL, "move", "mp,mj", dest, source);
7223   else
7224     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
7225                  dest, source, 0);
7226 }
7227
7228 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
7229    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
7230    The two alternatives are:
7231
7232    Global symbol                Local sybmol
7233    -------------                ------------
7234    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
7235    ...                          ...
7236    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
7237
7238    load_got_offset emits the first instruction and add_got_offset
7239    emits the second for a 16-bit offset or add_got_offset_hilo emits
7240    a sequence to add a 32-bit offset using a scratch register.  */
7241
7242 static void
7243 load_got_offset (int dest, expressionS *local)
7244 {
7245   expressionS global;
7246
7247   global = *local;
7248   global.X_add_number = 0;
7249
7250   relax_start (local->X_add_symbol);
7251   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7252                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7253   relax_switch ();
7254   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
7255                BFD_RELOC_MIPS_GOT16, mips_gp_register);
7256   relax_end ();
7257 }
7258
7259 static void
7260 add_got_offset (int dest, expressionS *local)
7261 {
7262   expressionS global;
7263
7264   global.X_op = O_constant;
7265   global.X_op_symbol = NULL;
7266   global.X_add_symbol = NULL;
7267   global.X_add_number = local->X_add_number;
7268
7269   relax_start (local->X_add_symbol);
7270   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
7271                dest, dest, BFD_RELOC_LO16);
7272   relax_switch ();
7273   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
7274   relax_end ();
7275 }
7276
7277 static void
7278 add_got_offset_hilo (int dest, expressionS *local, int tmp)
7279 {
7280   expressionS global;
7281   int hold_mips_optimize;
7282
7283   global.X_op = O_constant;
7284   global.X_op_symbol = NULL;
7285   global.X_add_symbol = NULL;
7286   global.X_add_number = local->X_add_number;
7287
7288   relax_start (local->X_add_symbol);
7289   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
7290   relax_switch ();
7291   /* Set mips_optimize around the lui instruction to avoid
7292      inserting an unnecessary nop after the lw.  */
7293   hold_mips_optimize = mips_optimize;
7294   mips_optimize = 2;
7295   macro_build_lui (&global, tmp);
7296   mips_optimize = hold_mips_optimize;
7297   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
7298   relax_end ();
7299
7300   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
7301 }
7302
7303 /* Emit a sequence of instructions to emulate a branch likely operation.
7304    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
7305    is its complementing branch with the original condition negated.
7306    CALL is set if the original branch specified the link operation.
7307    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
7308
7309    Code like this is produced in the noreorder mode:
7310
7311         BRNEG   <args>, 1f
7312          nop
7313         b       <sym>
7314          delay slot (executed only if branch taken)
7315     1:
7316
7317    or, if CALL is set:
7318
7319         BRNEG   <args>, 1f
7320          nop
7321         bal     <sym>
7322          delay slot (executed only if branch taken)
7323     1:
7324
7325    In the reorder mode the delay slot would be filled with a nop anyway,
7326    so code produced is simply:
7327
7328         BR      <args>, <sym>
7329          nop
7330
7331    This function is used when producing code for the microMIPS ASE that
7332    does not implement branch likely instructions in hardware.  */
7333
7334 static void
7335 macro_build_branch_likely (const char *br, const char *brneg,
7336                            int call, expressionS *ep, const char *fmt,
7337                            unsigned int sreg, unsigned int treg)
7338 {
7339   int noreorder = mips_opts.noreorder;
7340   expressionS expr1;
7341
7342   gas_assert (mips_opts.micromips);
7343   start_noreorder ();
7344   if (noreorder)
7345     {
7346       micromips_label_expr (&expr1);
7347       macro_build (&expr1, brneg, fmt, sreg, treg);
7348       macro_build (NULL, "nop", "");
7349       macro_build (ep, call ? "bal" : "b", "p");
7350
7351       /* Set to true so that append_insn adds a label.  */
7352       emit_branch_likely_macro = TRUE;
7353     }
7354   else
7355     {
7356       macro_build (ep, br, fmt, sreg, treg);
7357       macro_build (NULL, "nop", "");
7358     }
7359   end_noreorder ();
7360 }
7361
7362 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
7363    the condition code tested.  EP specifies the branch target.  */
7364
7365 static void
7366 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
7367 {
7368   const int call = 0;
7369   const char *brneg;
7370   const char *br;
7371
7372   switch (type)
7373     {
7374     case M_BC1FL:
7375       br = "bc1f";
7376       brneg = "bc1t";
7377       break;
7378     case M_BC1TL:
7379       br = "bc1t";
7380       brneg = "bc1f";
7381       break;
7382     case M_BC2FL:
7383       br = "bc2f";
7384       brneg = "bc2t";
7385       break;
7386     case M_BC2TL:
7387       br = "bc2t";
7388       brneg = "bc2f";
7389       break;
7390     default:
7391       abort ();
7392     }
7393   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
7394 }
7395
7396 /* Emit a two-argument branch macro specified by TYPE, using SREG as
7397    the register tested.  EP specifies the branch target.  */
7398
7399 static void
7400 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
7401 {
7402   const char *brneg = NULL;
7403   const char *br;
7404   int call = 0;
7405
7406   switch (type)
7407     {
7408     case M_BGEZ:
7409       br = "bgez";
7410       break;
7411     case M_BGEZL:
7412       br = mips_opts.micromips ? "bgez" : "bgezl";
7413       brneg = "bltz";
7414       break;
7415     case M_BGEZALL:
7416       gas_assert (mips_opts.micromips);
7417       br = mips_opts.insn32 ? "bgezal" : "bgezals";
7418       brneg = "bltz";
7419       call = 1;
7420       break;
7421     case M_BGTZ:
7422       br = "bgtz";
7423       break;
7424     case M_BGTZL:
7425       br = mips_opts.micromips ? "bgtz" : "bgtzl";
7426       brneg = "blez";
7427       break;
7428     case M_BLEZ:
7429       br = "blez";
7430       break;
7431     case M_BLEZL:
7432       br = mips_opts.micromips ? "blez" : "blezl";
7433       brneg = "bgtz";
7434       break;
7435     case M_BLTZ:
7436       br = "bltz";
7437       break;
7438     case M_BLTZL:
7439       br = mips_opts.micromips ? "bltz" : "bltzl";
7440       brneg = "bgez";
7441       break;
7442     case M_BLTZALL:
7443       gas_assert (mips_opts.micromips);
7444       br = mips_opts.insn32 ? "bltzal" : "bltzals";
7445       brneg = "bgez";
7446       call = 1;
7447       break;
7448     default:
7449       abort ();
7450     }
7451   if (mips_opts.micromips && brneg)
7452     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
7453   else
7454     macro_build (ep, br, "s,p", sreg);
7455 }
7456
7457 /* Emit a three-argument branch macro specified by TYPE, using SREG and
7458    TREG as the registers tested.  EP specifies the branch target.  */
7459
7460 static void
7461 macro_build_branch_rsrt (int type, expressionS *ep,
7462                          unsigned int sreg, unsigned int treg)
7463 {
7464   const char *brneg = NULL;
7465   const int call = 0;
7466   const char *br;
7467
7468   switch (type)
7469     {
7470     case M_BEQ:
7471     case M_BEQ_I:
7472       br = "beq";
7473       break;
7474     case M_BEQL:
7475     case M_BEQL_I:
7476       br = mips_opts.micromips ? "beq" : "beql";
7477       brneg = "bne";
7478       break;
7479     case M_BNE:
7480     case M_BNE_I:
7481       br = "bne";
7482       break;
7483     case M_BNEL:
7484     case M_BNEL_I:
7485       br = mips_opts.micromips ? "bne" : "bnel";
7486       brneg = "beq";
7487       break;
7488     default:
7489       abort ();
7490     }
7491   if (mips_opts.micromips && brneg)
7492     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
7493   else
7494     macro_build (ep, br, "s,t,p", sreg, treg);
7495 }
7496
7497 /* Return the high part that should be loaded in order to make the low
7498    part of VALUE accessible using an offset of OFFBITS bits.  */
7499
7500 static offsetT
7501 offset_high_part (offsetT value, unsigned int offbits)
7502 {
7503   offsetT bias;
7504   addressT low_mask;
7505
7506   if (offbits == 0)
7507     return value;
7508   bias = 1 << (offbits - 1);
7509   low_mask = bias * 2 - 1;
7510   return (value + bias) & ~low_mask;
7511 }
7512
7513 /* Return true if the value stored in offset_expr and offset_reloc
7514    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
7515    amount that the caller wants to add without inducing overflow
7516    and ALIGN is the known alignment of the value in bytes.  */
7517
7518 static bfd_boolean
7519 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
7520 {
7521   if (offbits == 16)
7522     {
7523       /* Accept any relocation operator if overflow isn't a concern.  */
7524       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
7525         return TRUE;
7526
7527       /* These relocations are guaranteed not to overflow in correct links.  */
7528       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
7529           || gprel16_reloc_p (*offset_reloc))
7530         return TRUE;
7531     }
7532   if (offset_expr.X_op == O_constant
7533       && offset_high_part (offset_expr.X_add_number, offbits) == 0
7534       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
7535     return TRUE;
7536   return FALSE;
7537 }
7538
7539 /*
7540  *                      Build macros
7541  *   This routine implements the seemingly endless macro or synthesized
7542  * instructions and addressing modes in the mips assembly language. Many
7543  * of these macros are simple and are similar to each other. These could
7544  * probably be handled by some kind of table or grammar approach instead of
7545  * this verbose method. Others are not simple macros but are more like
7546  * optimizing code generation.
7547  *   One interesting optimization is when several store macros appear
7548  * consecutively that would load AT with the upper half of the same address.
7549  * The ensuing load upper instructions are ommited. This implies some kind
7550  * of global optimization. We currently only optimize within a single macro.
7551  *   For many of the load and store macros if the address is specified as a
7552  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
7553  * first load register 'at' with zero and use it as the base register. The
7554  * mips assembler simply uses register $zero. Just one tiny optimization
7555  * we're missing.
7556  */
7557 static void
7558 macro (struct mips_cl_insn *ip, char *str)
7559 {
7560   unsigned int treg, sreg, dreg, breg;
7561   unsigned int tempreg;
7562   int mask;
7563   int used_at = 0;
7564   expressionS label_expr;
7565   expressionS expr1;
7566   expressionS *ep;
7567   const char *s;
7568   const char *s2;
7569   const char *fmt;
7570   int likely = 0;
7571   int coproc = 0;
7572   int offbits = 16;
7573   int call = 0;
7574   int jals = 0;
7575   int dbl = 0;
7576   int imm = 0;
7577   int ust = 0;
7578   int lp = 0;
7579   bfd_boolean large_offset;
7580   int off;
7581   int hold_mips_optimize;
7582   unsigned int align;
7583
7584   gas_assert (! mips_opts.mips16);
7585
7586   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
7587   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
7588   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
7589   mask = ip->insn_mo->mask;
7590
7591   label_expr.X_op = O_constant;
7592   label_expr.X_op_symbol = NULL;
7593   label_expr.X_add_symbol = NULL;
7594   label_expr.X_add_number = 0;
7595
7596   expr1.X_op = O_constant;
7597   expr1.X_op_symbol = NULL;
7598   expr1.X_add_symbol = NULL;
7599   expr1.X_add_number = 1;
7600   align = 1;
7601
7602   switch (mask)
7603     {
7604     case M_DABS:
7605       dbl = 1;
7606     case M_ABS:
7607       /*    bgez    $a0,1f
7608             move    v0,$a0
7609             sub     v0,$zero,$a0
7610          1:
7611        */
7612
7613       start_noreorder ();
7614
7615       if (mips_opts.micromips)
7616         micromips_label_expr (&label_expr);
7617       else
7618         label_expr.X_add_number = 8;
7619       macro_build (&label_expr, "bgez", "s,p", sreg);
7620       if (dreg == sreg)
7621         macro_build (NULL, "nop", "");
7622       else
7623         move_register (dreg, sreg);
7624       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
7625       if (mips_opts.micromips)
7626         micromips_add_label ();
7627
7628       end_noreorder ();
7629       break;
7630
7631     case M_ADD_I:
7632       s = "addi";
7633       s2 = "add";
7634       goto do_addi;
7635     case M_ADDU_I:
7636       s = "addiu";
7637       s2 = "addu";
7638       goto do_addi;
7639     case M_DADD_I:
7640       dbl = 1;
7641       s = "daddi";
7642       s2 = "dadd";
7643       if (!mips_opts.micromips)
7644         goto do_addi;
7645       if (imm_expr.X_op == O_constant
7646           && imm_expr.X_add_number >= -0x200
7647           && imm_expr.X_add_number < 0x200)
7648         {
7649           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
7650           break;
7651         }
7652       goto do_addi_i;
7653     case M_DADDU_I:
7654       dbl = 1;
7655       s = "daddiu";
7656       s2 = "daddu";
7657     do_addi:
7658       if (imm_expr.X_op == O_constant
7659           && imm_expr.X_add_number >= -0x8000
7660           && imm_expr.X_add_number < 0x8000)
7661         {
7662           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
7663           break;
7664         }
7665     do_addi_i:
7666       used_at = 1;
7667       load_register (AT, &imm_expr, dbl);
7668       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7669       break;
7670
7671     case M_AND_I:
7672       s = "andi";
7673       s2 = "and";
7674       goto do_bit;
7675     case M_OR_I:
7676       s = "ori";
7677       s2 = "or";
7678       goto do_bit;
7679     case M_NOR_I:
7680       s = "";
7681       s2 = "nor";
7682       goto do_bit;
7683     case M_XOR_I:
7684       s = "xori";
7685       s2 = "xor";
7686     do_bit:
7687       if (imm_expr.X_op == O_constant
7688           && imm_expr.X_add_number >= 0
7689           && imm_expr.X_add_number < 0x10000)
7690         {
7691           if (mask != M_NOR_I)
7692             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
7693           else
7694             {
7695               macro_build (&imm_expr, "ori", "t,r,i",
7696                            treg, sreg, BFD_RELOC_LO16);
7697               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
7698             }
7699           break;
7700         }
7701
7702       used_at = 1;
7703       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7704       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7705       break;
7706
7707     case M_BALIGN:
7708       switch (imm_expr.X_add_number)
7709         {
7710         case 0:
7711           macro_build (NULL, "nop", "");
7712           break;
7713         case 2:
7714           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
7715           break;
7716         case 1:
7717         case 3:
7718           macro_build (NULL, "balign", "t,s,2", treg, sreg,
7719                        (int) imm_expr.X_add_number);
7720           break;
7721         default:
7722           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
7723                   (unsigned long) imm_expr.X_add_number);
7724           break;
7725         }
7726       break;
7727
7728     case M_BC1FL:
7729     case M_BC1TL:
7730     case M_BC2FL:
7731     case M_BC2TL:
7732       gas_assert (mips_opts.micromips);
7733       macro_build_branch_ccl (mask, &offset_expr,
7734                               EXTRACT_OPERAND (1, BCC, *ip));
7735       break;
7736
7737     case M_BEQ_I:
7738     case M_BEQL_I:
7739     case M_BNE_I:
7740     case M_BNEL_I:
7741       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7742         treg = 0;
7743       else
7744         {
7745           treg = AT;
7746           used_at = 1;
7747           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
7748         }
7749       /* Fall through.  */
7750     case M_BEQL:
7751     case M_BNEL:
7752       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
7753       break;
7754
7755     case M_BGEL:
7756       likely = 1;
7757     case M_BGE:
7758       if (treg == 0)
7759         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
7760       else if (sreg == 0)
7761         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
7762       else
7763         {
7764           used_at = 1;
7765           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7766           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7767                                    &offset_expr, AT, ZERO);
7768         }
7769       break;
7770
7771     case M_BGEZL:
7772     case M_BGEZALL:
7773     case M_BGTZL:
7774     case M_BLEZL:
7775     case M_BLTZL:
7776     case M_BLTZALL:
7777       macro_build_branch_rs (mask, &offset_expr, sreg);
7778       break;
7779
7780     case M_BGTL_I:
7781       likely = 1;
7782     case M_BGT_I:
7783       /* Check for > max integer.  */
7784       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7785         {
7786         do_false:
7787           /* Result is always false.  */
7788           if (! likely)
7789             macro_build (NULL, "nop", "");
7790           else
7791             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
7792           break;
7793         }
7794       if (imm_expr.X_op != O_constant)
7795         as_bad (_("Unsupported large constant"));
7796       ++imm_expr.X_add_number;
7797       /* FALLTHROUGH */
7798     case M_BGE_I:
7799     case M_BGEL_I:
7800       if (mask == M_BGEL_I)
7801         likely = 1;
7802       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7803         {
7804           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
7805                                  &offset_expr, sreg);
7806           break;
7807         }
7808       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7809         {
7810           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
7811                                  &offset_expr, sreg);
7812           break;
7813         }
7814       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
7815         {
7816         do_true:
7817           /* result is always true */
7818           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
7819           macro_build (&offset_expr, "b", "p");
7820           break;
7821         }
7822       used_at = 1;
7823       set_at (sreg, 0);
7824       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7825                                &offset_expr, AT, ZERO);
7826       break;
7827
7828     case M_BGEUL:
7829       likely = 1;
7830     case M_BGEU:
7831       if (treg == 0)
7832         goto do_true;
7833       else if (sreg == 0)
7834         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7835                                  &offset_expr, ZERO, treg);
7836       else
7837         {
7838           used_at = 1;
7839           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7840           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7841                                    &offset_expr, AT, ZERO);
7842         }
7843       break;
7844
7845     case M_BGTUL_I:
7846       likely = 1;
7847     case M_BGTU_I:
7848       if (sreg == 0
7849           || (HAVE_32BIT_GPRS
7850               && imm_expr.X_op == O_constant
7851               && imm_expr.X_add_number == -1))
7852         goto do_false;
7853       if (imm_expr.X_op != O_constant)
7854         as_bad (_("Unsupported large constant"));
7855       ++imm_expr.X_add_number;
7856       /* FALLTHROUGH */
7857     case M_BGEU_I:
7858     case M_BGEUL_I:
7859       if (mask == M_BGEUL_I)
7860         likely = 1;
7861       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7862         goto do_true;
7863       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7864         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7865                                  &offset_expr, sreg, ZERO);
7866       else
7867         {
7868           used_at = 1;
7869           set_at (sreg, 1);
7870           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7871                                    &offset_expr, AT, ZERO);
7872         }
7873       break;
7874
7875     case M_BGTL:
7876       likely = 1;
7877     case M_BGT:
7878       if (treg == 0)
7879         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
7880       else if (sreg == 0)
7881         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
7882       else
7883         {
7884           used_at = 1;
7885           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7886           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7887                                    &offset_expr, AT, ZERO);
7888         }
7889       break;
7890
7891     case M_BGTUL:
7892       likely = 1;
7893     case M_BGTU:
7894       if (treg == 0)
7895         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7896                                  &offset_expr, sreg, ZERO);
7897       else if (sreg == 0)
7898         goto do_false;
7899       else
7900         {
7901           used_at = 1;
7902           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7903           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7904                                    &offset_expr, AT, ZERO);
7905         }
7906       break;
7907
7908     case M_BLEL:
7909       likely = 1;
7910     case M_BLE:
7911       if (treg == 0)
7912         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7913       else if (sreg == 0)
7914         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
7915       else
7916         {
7917           used_at = 1;
7918           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7919           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7920                                    &offset_expr, AT, ZERO);
7921         }
7922       break;
7923
7924     case M_BLEL_I:
7925       likely = 1;
7926     case M_BLE_I:
7927       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7928         goto do_true;
7929       if (imm_expr.X_op != O_constant)
7930         as_bad (_("Unsupported large constant"));
7931       ++imm_expr.X_add_number;
7932       /* FALLTHROUGH */
7933     case M_BLT_I:
7934     case M_BLTL_I:
7935       if (mask == M_BLTL_I)
7936         likely = 1;
7937       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7938         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7939       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7940         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7941       else
7942         {
7943           used_at = 1;
7944           set_at (sreg, 0);
7945           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7946                                    &offset_expr, AT, ZERO);
7947         }
7948       break;
7949
7950     case M_BLEUL:
7951       likely = 1;
7952     case M_BLEU:
7953       if (treg == 0)
7954         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7955                                  &offset_expr, sreg, ZERO);
7956       else if (sreg == 0)
7957         goto do_true;
7958       else
7959         {
7960           used_at = 1;
7961           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7962           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7963                                    &offset_expr, AT, ZERO);
7964         }
7965       break;
7966
7967     case M_BLEUL_I:
7968       likely = 1;
7969     case M_BLEU_I:
7970       if (sreg == 0
7971           || (HAVE_32BIT_GPRS
7972               && imm_expr.X_op == O_constant
7973               && imm_expr.X_add_number == -1))
7974         goto do_true;
7975       if (imm_expr.X_op != O_constant)
7976         as_bad (_("Unsupported large constant"));
7977       ++imm_expr.X_add_number;
7978       /* FALLTHROUGH */
7979     case M_BLTU_I:
7980     case M_BLTUL_I:
7981       if (mask == M_BLTUL_I)
7982         likely = 1;
7983       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7984         goto do_false;
7985       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7986         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7987                                  &offset_expr, sreg, ZERO);
7988       else
7989         {
7990           used_at = 1;
7991           set_at (sreg, 1);
7992           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7993                                    &offset_expr, AT, ZERO);
7994         }
7995       break;
7996
7997     case M_BLTL:
7998       likely = 1;
7999     case M_BLT:
8000       if (treg == 0)
8001         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
8002       else if (sreg == 0)
8003         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
8004       else
8005         {
8006           used_at = 1;
8007           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
8008           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8009                                    &offset_expr, AT, ZERO);
8010         }
8011       break;
8012
8013     case M_BLTUL:
8014       likely = 1;
8015     case M_BLTU:
8016       if (treg == 0)
8017         goto do_false;
8018       else if (sreg == 0)
8019         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8020                                  &offset_expr, ZERO, treg);
8021       else
8022         {
8023           used_at = 1;
8024           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
8025           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
8026                                    &offset_expr, AT, ZERO);
8027         }
8028       break;
8029
8030     case M_DEXT:
8031       {
8032         /* Use unsigned arithmetic.  */
8033         addressT pos;
8034         addressT size;
8035
8036         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8037           {
8038             as_bad (_("Unsupported large constant"));
8039             pos = size = 1;
8040           }
8041         else
8042           {
8043             pos = imm_expr.X_add_number;
8044             size = imm2_expr.X_add_number;
8045           }
8046
8047         if (pos > 63)
8048           {
8049             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
8050             pos = 1;
8051           }
8052         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8053           {
8054             as_bad (_("Improper extract size (%lu, position %lu)"),
8055                     (unsigned long) size, (unsigned long) pos);
8056             size = 1;
8057           }
8058
8059         if (size <= 32 && pos < 32)
8060           {
8061             s = "dext";
8062             fmt = "t,r,+A,+C";
8063           }
8064         else if (size <= 32)
8065           {
8066             s = "dextu";
8067             fmt = "t,r,+E,+H";
8068           }
8069         else
8070           {
8071             s = "dextm";
8072             fmt = "t,r,+A,+G";
8073           }
8074         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8075                      (int) (size - 1));
8076       }
8077       break;
8078
8079     case M_DINS:
8080       {
8081         /* Use unsigned arithmetic.  */
8082         addressT pos;
8083         addressT size;
8084
8085         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
8086           {
8087             as_bad (_("Unsupported large constant"));
8088             pos = size = 1;
8089           }
8090         else
8091           {
8092             pos = imm_expr.X_add_number;
8093             size = imm2_expr.X_add_number;
8094           }
8095
8096         if (pos > 63)
8097           {
8098             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
8099             pos = 1;
8100           }
8101         if (size == 0 || size > 64 || (pos + size - 1) > 63)
8102           {
8103             as_bad (_("Improper insert size (%lu, position %lu)"),
8104                     (unsigned long) size, (unsigned long) pos);
8105             size = 1;
8106           }
8107
8108         if (pos < 32 && (pos + size - 1) < 32)
8109           {
8110             s = "dins";
8111             fmt = "t,r,+A,+B";
8112           }
8113         else if (pos >= 32)
8114           {
8115             s = "dinsu";
8116             fmt = "t,r,+E,+F";
8117           }
8118         else
8119           {
8120             s = "dinsm";
8121             fmt = "t,r,+A,+F";
8122           }
8123         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
8124                      (int) (pos + size - 1));
8125       }
8126       break;
8127
8128     case M_DDIV_3:
8129       dbl = 1;
8130     case M_DIV_3:
8131       s = "mflo";
8132       goto do_div3;
8133     case M_DREM_3:
8134       dbl = 1;
8135     case M_REM_3:
8136       s = "mfhi";
8137     do_div3:
8138       if (treg == 0)
8139         {
8140           as_warn (_("Divide by zero."));
8141           if (mips_trap)
8142             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8143           else
8144             macro_build (NULL, "break", BRK_FMT, 7);
8145           break;
8146         }
8147
8148       start_noreorder ();
8149       if (mips_trap)
8150         {
8151           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8152           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8153         }
8154       else
8155         {
8156           if (mips_opts.micromips)
8157             micromips_label_expr (&label_expr);
8158           else
8159             label_expr.X_add_number = 8;
8160           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8161           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
8162           macro_build (NULL, "break", BRK_FMT, 7);
8163           if (mips_opts.micromips)
8164             micromips_add_label ();
8165         }
8166       expr1.X_add_number = -1;
8167       used_at = 1;
8168       load_register (AT, &expr1, dbl);
8169       if (mips_opts.micromips)
8170         micromips_label_expr (&label_expr);
8171       else
8172         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
8173       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
8174       if (dbl)
8175         {
8176           expr1.X_add_number = 1;
8177           load_register (AT, &expr1, dbl);
8178           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
8179         }
8180       else
8181         {
8182           expr1.X_add_number = 0x80000000;
8183           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
8184         }
8185       if (mips_trap)
8186         {
8187           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
8188           /* We want to close the noreorder block as soon as possible, so
8189              that later insns are available for delay slot filling.  */
8190           end_noreorder ();
8191         }
8192       else
8193         {
8194           if (mips_opts.micromips)
8195             micromips_label_expr (&label_expr);
8196           else
8197             label_expr.X_add_number = 8;
8198           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
8199           macro_build (NULL, "nop", "");
8200
8201           /* We want to close the noreorder block as soon as possible, so
8202              that later insns are available for delay slot filling.  */
8203           end_noreorder ();
8204
8205           macro_build (NULL, "break", BRK_FMT, 6);
8206         }
8207       if (mips_opts.micromips)
8208         micromips_add_label ();
8209       macro_build (NULL, s, MFHL_FMT, dreg);
8210       break;
8211
8212     case M_DIV_3I:
8213       s = "div";
8214       s2 = "mflo";
8215       goto do_divi;
8216     case M_DIVU_3I:
8217       s = "divu";
8218       s2 = "mflo";
8219       goto do_divi;
8220     case M_REM_3I:
8221       s = "div";
8222       s2 = "mfhi";
8223       goto do_divi;
8224     case M_REMU_3I:
8225       s = "divu";
8226       s2 = "mfhi";
8227       goto do_divi;
8228     case M_DDIV_3I:
8229       dbl = 1;
8230       s = "ddiv";
8231       s2 = "mflo";
8232       goto do_divi;
8233     case M_DDIVU_3I:
8234       dbl = 1;
8235       s = "ddivu";
8236       s2 = "mflo";
8237       goto do_divi;
8238     case M_DREM_3I:
8239       dbl = 1;
8240       s = "ddiv";
8241       s2 = "mfhi";
8242       goto do_divi;
8243     case M_DREMU_3I:
8244       dbl = 1;
8245       s = "ddivu";
8246       s2 = "mfhi";
8247     do_divi:
8248       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
8249         {
8250           as_warn (_("Divide by zero."));
8251           if (mips_trap)
8252             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
8253           else
8254             macro_build (NULL, "break", BRK_FMT, 7);
8255           break;
8256         }
8257       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
8258         {
8259           if (strcmp (s2, "mflo") == 0)
8260             move_register (dreg, sreg);
8261           else
8262             move_register (dreg, ZERO);
8263           break;
8264         }
8265       if (imm_expr.X_op == O_constant
8266           && imm_expr.X_add_number == -1
8267           && s[strlen (s) - 1] != 'u')
8268         {
8269           if (strcmp (s2, "mflo") == 0)
8270             {
8271               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
8272             }
8273           else
8274             move_register (dreg, ZERO);
8275           break;
8276         }
8277
8278       used_at = 1;
8279       load_register (AT, &imm_expr, dbl);
8280       macro_build (NULL, s, "z,s,t", sreg, AT);
8281       macro_build (NULL, s2, MFHL_FMT, dreg);
8282       break;
8283
8284     case M_DIVU_3:
8285       s = "divu";
8286       s2 = "mflo";
8287       goto do_divu3;
8288     case M_REMU_3:
8289       s = "divu";
8290       s2 = "mfhi";
8291       goto do_divu3;
8292     case M_DDIVU_3:
8293       s = "ddivu";
8294       s2 = "mflo";
8295       goto do_divu3;
8296     case M_DREMU_3:
8297       s = "ddivu";
8298       s2 = "mfhi";
8299     do_divu3:
8300       start_noreorder ();
8301       if (mips_trap)
8302         {
8303           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
8304           macro_build (NULL, s, "z,s,t", sreg, treg);
8305           /* We want to close the noreorder block as soon as possible, so
8306              that later insns are available for delay slot filling.  */
8307           end_noreorder ();
8308         }
8309       else
8310         {
8311           if (mips_opts.micromips)
8312             micromips_label_expr (&label_expr);
8313           else
8314             label_expr.X_add_number = 8;
8315           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
8316           macro_build (NULL, s, "z,s,t", sreg, treg);
8317
8318           /* We want to close the noreorder block as soon as possible, so
8319              that later insns are available for delay slot filling.  */
8320           end_noreorder ();
8321           macro_build (NULL, "break", BRK_FMT, 7);
8322           if (mips_opts.micromips)
8323             micromips_add_label ();
8324         }
8325       macro_build (NULL, s2, MFHL_FMT, dreg);
8326       break;
8327
8328     case M_DLCA_AB:
8329       dbl = 1;
8330     case M_LCA_AB:
8331       call = 1;
8332       goto do_la;
8333     case M_DLA_AB:
8334       dbl = 1;
8335     case M_LA_AB:
8336     do_la:
8337       /* Load the address of a symbol into a register.  If breg is not
8338          zero, we then add a base register to it.  */
8339
8340       if (dbl && HAVE_32BIT_GPRS)
8341         as_warn (_("dla used to load 32-bit register"));
8342
8343       if (!dbl && HAVE_64BIT_OBJECTS)
8344         as_warn (_("la used to load 64-bit address"));
8345
8346       if (small_offset_p (0, align, 16))
8347         {
8348           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
8349                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
8350           break;
8351         }
8352
8353       if (mips_opts.at && (treg == breg))
8354         {
8355           tempreg = AT;
8356           used_at = 1;
8357         }
8358       else
8359         {
8360           tempreg = treg;
8361         }
8362
8363       if (offset_expr.X_op != O_symbol
8364           && offset_expr.X_op != O_constant)
8365         {
8366           as_bad (_("Expression too complex"));
8367           offset_expr.X_op = O_constant;
8368         }
8369
8370       if (offset_expr.X_op == O_constant)
8371         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
8372       else if (mips_pic == NO_PIC)
8373         {
8374           /* If this is a reference to a GP relative symbol, we want
8375                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
8376              Otherwise we want
8377                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
8378                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8379              If we have a constant, we need two instructions anyhow,
8380              so we may as well always use the latter form.
8381
8382              With 64bit address space and a usable $at we want
8383                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8384                lui      $at,<sym>               (BFD_RELOC_HI16_S)
8385                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8386                daddiu   $at,<sym>               (BFD_RELOC_LO16)
8387                dsll32   $tempreg,0
8388                daddu    $tempreg,$tempreg,$at
8389
8390              If $at is already in use, we use a path which is suboptimal
8391              on superscalar processors.
8392                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
8393                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
8394                dsll     $tempreg,16
8395                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
8396                dsll     $tempreg,16
8397                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
8398
8399              For GP relative symbols in 64bit address space we can use
8400              the same sequence as in 32bit address space.  */
8401           if (HAVE_64BIT_SYMBOLS)
8402             {
8403               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8404                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8405                 {
8406                   relax_start (offset_expr.X_add_symbol);
8407                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8408                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8409                   relax_switch ();
8410                 }
8411
8412               if (used_at == 0 && mips_opts.at)
8413                 {
8414                   macro_build (&offset_expr, "lui", LUI_FMT,
8415                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8416                   macro_build (&offset_expr, "lui", LUI_FMT,
8417                                AT, BFD_RELOC_HI16_S);
8418                   macro_build (&offset_expr, "daddiu", "t,r,j",
8419                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8420                   macro_build (&offset_expr, "daddiu", "t,r,j",
8421                                AT, AT, BFD_RELOC_LO16);
8422                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
8423                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
8424                   used_at = 1;
8425                 }
8426               else
8427                 {
8428                   macro_build (&offset_expr, "lui", LUI_FMT,
8429                                tempreg, BFD_RELOC_MIPS_HIGHEST);
8430                   macro_build (&offset_expr, "daddiu", "t,r,j",
8431                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
8432                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8433                   macro_build (&offset_expr, "daddiu", "t,r,j",
8434                                tempreg, tempreg, BFD_RELOC_HI16_S);
8435                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
8436                   macro_build (&offset_expr, "daddiu", "t,r,j",
8437                                tempreg, tempreg, BFD_RELOC_LO16);
8438                 }
8439
8440               if (mips_relax.sequence)
8441                 relax_end ();
8442             }
8443           else
8444             {
8445               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
8446                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
8447                 {
8448                   relax_start (offset_expr.X_add_symbol);
8449                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8450                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
8451                   relax_switch ();
8452                 }
8453               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8454                 as_bad (_("Offset too large"));
8455               macro_build_lui (&offset_expr, tempreg);
8456               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8457                            tempreg, tempreg, BFD_RELOC_LO16);
8458               if (mips_relax.sequence)
8459                 relax_end ();
8460             }
8461         }
8462       else if (!mips_big_got && !HAVE_NEWABI)
8463         {
8464           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8465
8466           /* If this is a reference to an external symbol, and there
8467              is no constant, we want
8468                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8469              or for lca or if tempreg is PIC_CALL_REG
8470                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8471              For a local symbol, we want
8472                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8473                nop
8474                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8475
8476              If we have a small constant, and this is a reference to
8477              an external symbol, we want
8478                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8479                nop
8480                addiu    $tempreg,$tempreg,<constant>
8481              For a local symbol, we want the same instruction
8482              sequence, but we output a BFD_RELOC_LO16 reloc on the
8483              addiu instruction.
8484
8485              If we have a large constant, and this is a reference to
8486              an external symbol, we want
8487                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8488                lui      $at,<hiconstant>
8489                addiu    $at,$at,<loconstant>
8490                addu     $tempreg,$tempreg,$at
8491              For a local symbol, we want the same instruction
8492              sequence, but we output a BFD_RELOC_LO16 reloc on the
8493              addiu instruction.
8494            */
8495
8496           if (offset_expr.X_add_number == 0)
8497             {
8498               if (mips_pic == SVR4_PIC
8499                   && breg == 0
8500                   && (call || tempreg == PIC_CALL_REG))
8501                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
8502
8503               relax_start (offset_expr.X_add_symbol);
8504               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8505                            lw_reloc_type, mips_gp_register);
8506               if (breg != 0)
8507                 {
8508                   /* We're going to put in an addu instruction using
8509                      tempreg, so we may as well insert the nop right
8510                      now.  */
8511                   load_delay_nop ();
8512                 }
8513               relax_switch ();
8514               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8515                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
8516               load_delay_nop ();
8517               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8518                            tempreg, tempreg, BFD_RELOC_LO16);
8519               relax_end ();
8520               /* FIXME: If breg == 0, and the next instruction uses
8521                  $tempreg, then if this variant case is used an extra
8522                  nop will be generated.  */
8523             }
8524           else if (offset_expr.X_add_number >= -0x8000
8525                    && offset_expr.X_add_number < 0x8000)
8526             {
8527               load_got_offset (tempreg, &offset_expr);
8528               load_delay_nop ();
8529               add_got_offset (tempreg, &offset_expr);
8530             }
8531           else
8532             {
8533               expr1.X_add_number = offset_expr.X_add_number;
8534               offset_expr.X_add_number =
8535                 SEXT_16BIT (offset_expr.X_add_number);
8536               load_got_offset (tempreg, &offset_expr);
8537               offset_expr.X_add_number = expr1.X_add_number;
8538               /* If we are going to add in a base register, and the
8539                  target register and the base register are the same,
8540                  then we are using AT as a temporary register.  Since
8541                  we want to load the constant into AT, we add our
8542                  current AT (from the global offset table) and the
8543                  register into the register now, and pretend we were
8544                  not using a base register.  */
8545               if (breg == treg)
8546                 {
8547                   load_delay_nop ();
8548                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8549                                treg, AT, breg);
8550                   breg = 0;
8551                   tempreg = treg;
8552                 }
8553               add_got_offset_hilo (tempreg, &offset_expr, AT);
8554               used_at = 1;
8555             }
8556         }
8557       else if (!mips_big_got && HAVE_NEWABI)
8558         {
8559           int add_breg_early = 0;
8560
8561           /* If this is a reference to an external, and there is no
8562              constant, or local symbol (*), with or without a
8563              constant, we want
8564                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8565              or for lca or if tempreg is PIC_CALL_REG
8566                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
8567
8568              If we have a small constant, and this is a reference to
8569              an external symbol, we want
8570                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8571                addiu    $tempreg,$tempreg,<constant>
8572
8573              If we have a large constant, and this is a reference to
8574              an external symbol, we want
8575                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8576                lui      $at,<hiconstant>
8577                addiu    $at,$at,<loconstant>
8578                addu     $tempreg,$tempreg,$at
8579
8580              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
8581              local symbols, even though it introduces an additional
8582              instruction.  */
8583
8584           if (offset_expr.X_add_number)
8585             {
8586               expr1.X_add_number = offset_expr.X_add_number;
8587               offset_expr.X_add_number = 0;
8588
8589               relax_start (offset_expr.X_add_symbol);
8590               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8591                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8592
8593               if (expr1.X_add_number >= -0x8000
8594                   && expr1.X_add_number < 0x8000)
8595                 {
8596                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8597                                tempreg, tempreg, BFD_RELOC_LO16);
8598                 }
8599               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8600                 {
8601                   /* If we are going to add in a base register, and the
8602                      target register and the base register are the same,
8603                      then we are using AT as a temporary register.  Since
8604                      we want to load the constant into AT, we add our
8605                      current AT (from the global offset table) and the
8606                      register into the register now, and pretend we were
8607                      not using a base register.  */
8608                   if (breg != treg)
8609                     dreg = tempreg;
8610                   else
8611                     {
8612                       gas_assert (tempreg == AT);
8613                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8614                                    treg, AT, breg);
8615                       dreg = treg;
8616                       add_breg_early = 1;
8617                     }
8618
8619                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8620                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8621                                dreg, dreg, AT);
8622
8623                   used_at = 1;
8624                 }
8625               else
8626                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8627
8628               relax_switch ();
8629               offset_expr.X_add_number = expr1.X_add_number;
8630
8631               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8632                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8633               if (add_breg_early)
8634                 {
8635                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8636                                treg, tempreg, breg);
8637                   breg = 0;
8638                   tempreg = treg;
8639                 }
8640               relax_end ();
8641             }
8642           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
8643             {
8644               relax_start (offset_expr.X_add_symbol);
8645               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8646                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
8647               relax_switch ();
8648               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8649                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8650               relax_end ();
8651             }
8652           else
8653             {
8654               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8655                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8656             }
8657         }
8658       else if (mips_big_got && !HAVE_NEWABI)
8659         {
8660           int gpdelay;
8661           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8662           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8663           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8664
8665           /* This is the large GOT case.  If this is a reference to an
8666              external symbol, and there is no constant, we want
8667                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8668                addu     $tempreg,$tempreg,$gp
8669                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8670              or for lca or if tempreg is PIC_CALL_REG
8671                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8672                addu     $tempreg,$tempreg,$gp
8673                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8674              For a local symbol, we want
8675                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8676                nop
8677                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8678
8679              If we have a small constant, and this is a reference to
8680              an external symbol, we want
8681                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8682                addu     $tempreg,$tempreg,$gp
8683                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8684                nop
8685                addiu    $tempreg,$tempreg,<constant>
8686              For a local symbol, we want
8687                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8688                nop
8689                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
8690
8691              If we have a large constant, and this is a reference to
8692              an external symbol, we want
8693                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8694                addu     $tempreg,$tempreg,$gp
8695                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8696                lui      $at,<hiconstant>
8697                addiu    $at,$at,<loconstant>
8698                addu     $tempreg,$tempreg,$at
8699              For a local symbol, we want
8700                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8701                lui      $at,<hiconstant>
8702                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
8703                addu     $tempreg,$tempreg,$at
8704           */
8705
8706           expr1.X_add_number = offset_expr.X_add_number;
8707           offset_expr.X_add_number = 0;
8708           relax_start (offset_expr.X_add_symbol);
8709           gpdelay = reg_needs_delay (mips_gp_register);
8710           if (expr1.X_add_number == 0 && breg == 0
8711               && (call || tempreg == PIC_CALL_REG))
8712             {
8713               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8714               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8715             }
8716           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8717           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8718                        tempreg, tempreg, mips_gp_register);
8719           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8720                        tempreg, lw_reloc_type, tempreg);
8721           if (expr1.X_add_number == 0)
8722             {
8723               if (breg != 0)
8724                 {
8725                   /* We're going to put in an addu instruction using
8726                      tempreg, so we may as well insert the nop right
8727                      now.  */
8728                   load_delay_nop ();
8729                 }
8730             }
8731           else if (expr1.X_add_number >= -0x8000
8732                    && expr1.X_add_number < 0x8000)
8733             {
8734               load_delay_nop ();
8735               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8736                            tempreg, tempreg, BFD_RELOC_LO16);
8737             }
8738           else
8739             {
8740               /* If we are going to add in a base register, and the
8741                  target register and the base register are the same,
8742                  then we are using AT as a temporary register.  Since
8743                  we want to load the constant into AT, we add our
8744                  current AT (from the global offset table) and the
8745                  register into the register now, and pretend we were
8746                  not using a base register.  */
8747               if (breg != treg)
8748                 dreg = tempreg;
8749               else
8750                 {
8751                   gas_assert (tempreg == AT);
8752                   load_delay_nop ();
8753                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8754                                treg, AT, breg);
8755                   dreg = treg;
8756                 }
8757
8758               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8759               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8760
8761               used_at = 1;
8762             }
8763           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
8764           relax_switch ();
8765
8766           if (gpdelay)
8767             {
8768               /* This is needed because this instruction uses $gp, but
8769                  the first instruction on the main stream does not.  */
8770               macro_build (NULL, "nop", "");
8771             }
8772
8773           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8774                        local_reloc_type, mips_gp_register);
8775           if (expr1.X_add_number >= -0x8000
8776               && expr1.X_add_number < 0x8000)
8777             {
8778               load_delay_nop ();
8779               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8780                            tempreg, tempreg, BFD_RELOC_LO16);
8781               /* FIXME: If add_number is 0, and there was no base
8782                  register, the external symbol case ended with a load,
8783                  so if the symbol turns out to not be external, and
8784                  the next instruction uses tempreg, an unnecessary nop
8785                  will be inserted.  */
8786             }
8787           else
8788             {
8789               if (breg == treg)
8790                 {
8791                   /* We must add in the base register now, as in the
8792                      external symbol case.  */
8793                   gas_assert (tempreg == AT);
8794                   load_delay_nop ();
8795                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8796                                treg, AT, breg);
8797                   tempreg = treg;
8798                   /* We set breg to 0 because we have arranged to add
8799                      it in in both cases.  */
8800                   breg = 0;
8801                 }
8802
8803               macro_build_lui (&expr1, AT);
8804               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8805                            AT, AT, BFD_RELOC_LO16);
8806               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8807                            tempreg, tempreg, AT);
8808               used_at = 1;
8809             }
8810           relax_end ();
8811         }
8812       else if (mips_big_got && HAVE_NEWABI)
8813         {
8814           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8815           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8816           int add_breg_early = 0;
8817
8818           /* This is the large GOT case.  If this is a reference to an
8819              external symbol, and there is no constant, we want
8820                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8821                add      $tempreg,$tempreg,$gp
8822                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8823              or for lca or if tempreg is PIC_CALL_REG
8824                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8825                add      $tempreg,$tempreg,$gp
8826                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8827
8828              If we have a small constant, and this is a reference to
8829              an external symbol, we want
8830                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8831                add      $tempreg,$tempreg,$gp
8832                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8833                addi     $tempreg,$tempreg,<constant>
8834
8835              If we have a large constant, and this is a reference to
8836              an external symbol, we want
8837                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8838                addu     $tempreg,$tempreg,$gp
8839                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8840                lui      $at,<hiconstant>
8841                addi     $at,$at,<loconstant>
8842                add      $tempreg,$tempreg,$at
8843
8844              If we have NewABI, and we know it's a local symbol, we want
8845                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8846                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8847              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8848
8849           relax_start (offset_expr.X_add_symbol);
8850
8851           expr1.X_add_number = offset_expr.X_add_number;
8852           offset_expr.X_add_number = 0;
8853
8854           if (expr1.X_add_number == 0 && breg == 0
8855               && (call || tempreg == PIC_CALL_REG))
8856             {
8857               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8858               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8859             }
8860           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8861           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8862                        tempreg, tempreg, mips_gp_register);
8863           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8864                        tempreg, lw_reloc_type, tempreg);
8865
8866           if (expr1.X_add_number == 0)
8867             ;
8868           else if (expr1.X_add_number >= -0x8000
8869                    && expr1.X_add_number < 0x8000)
8870             {
8871               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8872                            tempreg, tempreg, BFD_RELOC_LO16);
8873             }
8874           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8875             {
8876               /* If we are going to add in a base register, and the
8877                  target register and the base register are the same,
8878                  then we are using AT as a temporary register.  Since
8879                  we want to load the constant into AT, we add our
8880                  current AT (from the global offset table) and the
8881                  register into the register now, and pretend we were
8882                  not using a base register.  */
8883               if (breg != treg)
8884                 dreg = tempreg;
8885               else
8886                 {
8887                   gas_assert (tempreg == AT);
8888                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8889                                treg, AT, breg);
8890                   dreg = treg;
8891                   add_breg_early = 1;
8892                 }
8893
8894               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8895               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8896
8897               used_at = 1;
8898             }
8899           else
8900             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8901
8902           relax_switch ();
8903           offset_expr.X_add_number = expr1.X_add_number;
8904           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8905                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8906           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8907                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
8908           if (add_breg_early)
8909             {
8910               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8911                            treg, tempreg, breg);
8912               breg = 0;
8913               tempreg = treg;
8914             }
8915           relax_end ();
8916         }
8917       else
8918         abort ();
8919
8920       if (breg != 0)
8921         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
8922       break;
8923
8924     case M_MSGSND:
8925       gas_assert (!mips_opts.micromips);
8926       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
8927       break;
8928
8929     case M_MSGLD:
8930       gas_assert (!mips_opts.micromips);
8931       macro_build (NULL, "c2", "C", 0x02);
8932       break;
8933
8934     case M_MSGLD_T:
8935       gas_assert (!mips_opts.micromips);
8936       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
8937       break;
8938
8939     case M_MSGWAIT:
8940       gas_assert (!mips_opts.micromips);
8941       macro_build (NULL, "c2", "C", 3);
8942       break;
8943
8944     case M_MSGWAIT_T:
8945       gas_assert (!mips_opts.micromips);
8946       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
8947       break;
8948
8949     case M_J_A:
8950       /* The j instruction may not be used in PIC code, since it
8951          requires an absolute address.  We convert it to a b
8952          instruction.  */
8953       if (mips_pic == NO_PIC)
8954         macro_build (&offset_expr, "j", "a");
8955       else
8956         macro_build (&offset_expr, "b", "p");
8957       break;
8958
8959       /* The jal instructions must be handled as macros because when
8960          generating PIC code they expand to multi-instruction
8961          sequences.  Normally they are simple instructions.  */
8962     case M_JALS_1:
8963       dreg = RA;
8964       /* Fall through.  */
8965     case M_JALS_2:
8966       gas_assert (mips_opts.micromips);
8967       if (mips_opts.insn32)
8968         {
8969           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
8970           break;
8971         }
8972       jals = 1;
8973       goto jal;
8974     case M_JAL_1:
8975       dreg = RA;
8976       /* Fall through.  */
8977     case M_JAL_2:
8978     jal:
8979       if (mips_pic == NO_PIC)
8980         {
8981           s = jals ? "jalrs" : "jalr";
8982           if (mips_opts.micromips
8983               && !mips_opts.insn32
8984               && dreg == RA
8985               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8986             macro_build (NULL, s, "mj", sreg);
8987           else
8988             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8989         }
8990       else
8991         {
8992           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
8993                            && mips_cprestore_offset >= 0);
8994
8995           if (sreg != PIC_CALL_REG)
8996             as_warn (_("MIPS PIC call to register other than $25"));
8997
8998           s = ((mips_opts.micromips
8999                 && !mips_opts.insn32
9000                 && (!mips_opts.noreorder || cprestore))
9001                ? "jalrs" : "jalr");
9002           if (mips_opts.micromips
9003               && !mips_opts.insn32
9004               && dreg == RA
9005               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9006             macro_build (NULL, s, "mj", sreg);
9007           else
9008             macro_build (NULL, s, JALR_FMT, dreg, sreg);
9009           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
9010             {
9011               if (mips_cprestore_offset < 0)
9012                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9013               else
9014                 {
9015                   if (!mips_frame_reg_valid)
9016                     {
9017                       as_warn (_("No .frame pseudo-op used in PIC code"));
9018                       /* Quiet this warning.  */
9019                       mips_frame_reg_valid = 1;
9020                     }
9021                   if (!mips_cprestore_valid)
9022                     {
9023                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9024                       /* Quiet this warning.  */
9025                       mips_cprestore_valid = 1;
9026                     }
9027                   if (mips_opts.noreorder)
9028                     macro_build (NULL, "nop", "");
9029                   expr1.X_add_number = mips_cprestore_offset;
9030                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9031                                                 mips_gp_register,
9032                                                 mips_frame_reg,
9033                                                 HAVE_64BIT_ADDRESSES);
9034                 }
9035             }
9036         }
9037
9038       break;
9039
9040     case M_JALS_A:
9041       gas_assert (mips_opts.micromips);
9042       if (mips_opts.insn32)
9043         {
9044           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
9045           break;
9046         }
9047       jals = 1;
9048       /* Fall through.  */
9049     case M_JAL_A:
9050       if (mips_pic == NO_PIC)
9051         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
9052       else if (mips_pic == SVR4_PIC)
9053         {
9054           /* If this is a reference to an external symbol, and we are
9055              using a small GOT, we want
9056                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
9057                nop
9058                jalr     $ra,$25
9059                nop
9060                lw       $gp,cprestore($sp)
9061              The cprestore value is set using the .cprestore
9062              pseudo-op.  If we are using a big GOT, we want
9063                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
9064                addu     $25,$25,$gp
9065                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
9066                nop
9067                jalr     $ra,$25
9068                nop
9069                lw       $gp,cprestore($sp)
9070              If the symbol is not external, we want
9071                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9072                nop
9073                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
9074                jalr     $ra,$25
9075                nop
9076                lw $gp,cprestore($sp)
9077
9078              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
9079              sequences above, minus nops, unless the symbol is local,
9080              which enables us to use GOT_PAGE/GOT_OFST (big got) or
9081              GOT_DISP.  */
9082           if (HAVE_NEWABI)
9083             {
9084               if (!mips_big_got)
9085                 {
9086                   relax_start (offset_expr.X_add_symbol);
9087                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9088                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9089                                mips_gp_register);
9090                   relax_switch ();
9091                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9092                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
9093                                mips_gp_register);
9094                   relax_end ();
9095                 }
9096               else
9097                 {
9098                   relax_start (offset_expr.X_add_symbol);
9099                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9100                                BFD_RELOC_MIPS_CALL_HI16);
9101                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9102                                PIC_CALL_REG, mips_gp_register);
9103                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9104                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9105                                PIC_CALL_REG);
9106                   relax_switch ();
9107                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9108                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
9109                                mips_gp_register);
9110                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9111                                PIC_CALL_REG, PIC_CALL_REG,
9112                                BFD_RELOC_MIPS_GOT_OFST);
9113                   relax_end ();
9114                 }
9115
9116               macro_build_jalr (&offset_expr, 0);
9117             }
9118           else
9119             {
9120               relax_start (offset_expr.X_add_symbol);
9121               if (!mips_big_got)
9122                 {
9123                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9124                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
9125                                mips_gp_register);
9126                   load_delay_nop ();
9127                   relax_switch ();
9128                 }
9129               else
9130                 {
9131                   int gpdelay;
9132
9133                   gpdelay = reg_needs_delay (mips_gp_register);
9134                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
9135                                BFD_RELOC_MIPS_CALL_HI16);
9136                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
9137                                PIC_CALL_REG, mips_gp_register);
9138                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9139                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
9140                                PIC_CALL_REG);
9141                   load_delay_nop ();
9142                   relax_switch ();
9143                   if (gpdelay)
9144                     macro_build (NULL, "nop", "");
9145                 }
9146               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9147                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
9148                            mips_gp_register);
9149               load_delay_nop ();
9150               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9151                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
9152               relax_end ();
9153               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
9154
9155               if (mips_cprestore_offset < 0)
9156                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
9157               else
9158                 {
9159                   if (!mips_frame_reg_valid)
9160                     {
9161                       as_warn (_("No .frame pseudo-op used in PIC code"));
9162                       /* Quiet this warning.  */
9163                       mips_frame_reg_valid = 1;
9164                     }
9165                   if (!mips_cprestore_valid)
9166                     {
9167                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
9168                       /* Quiet this warning.  */
9169                       mips_cprestore_valid = 1;
9170                     }
9171                   if (mips_opts.noreorder)
9172                     macro_build (NULL, "nop", "");
9173                   expr1.X_add_number = mips_cprestore_offset;
9174                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
9175                                                 mips_gp_register,
9176                                                 mips_frame_reg,
9177                                                 HAVE_64BIT_ADDRESSES);
9178                 }
9179             }
9180         }
9181       else if (mips_pic == VXWORKS_PIC)
9182         as_bad (_("Non-PIC jump used in PIC library"));
9183       else
9184         abort ();
9185
9186       break;
9187
9188     case M_LBUE_AB:
9189       s = "lbue";
9190       fmt = "t,+j(b)";
9191       offbits = 9;
9192       goto ld_st;
9193     case M_LHUE_AB:
9194       s = "lhue";
9195       fmt = "t,+j(b)";
9196       offbits = 9;
9197       goto ld_st;
9198     case M_LBE_AB:
9199       s = "lbe";
9200       fmt = "t,+j(b)";
9201       offbits = 9;
9202       goto ld_st;
9203     case M_LHE_AB:
9204       s = "lhe";
9205       fmt = "t,+j(b)";
9206       offbits = 9;
9207       goto ld_st;
9208     case M_LLE_AB:
9209       s = "lle";
9210       fmt = "t,+j(b)";
9211       offbits = 9;
9212       goto ld_st;
9213     case M_LWE_AB:
9214       s = "lwe";
9215       fmt = "t,+j(b)";
9216       offbits = 9;
9217       goto ld_st;
9218     case M_LWLE_AB:
9219       s = "lwle";
9220       fmt = "t,+j(b)";
9221       offbits = 9;
9222       goto ld_st;
9223     case M_LWRE_AB:
9224       s = "lwre";
9225       fmt = "t,+j(b)";
9226       offbits = 9;
9227       goto ld_st;
9228     case M_SBE_AB:
9229       s = "sbe";
9230       fmt = "t,+j(b)";
9231       offbits = 9;
9232       goto ld_st;
9233     case M_SCE_AB:
9234       s = "sce";
9235       fmt = "t,+j(b)";
9236       offbits = 9;
9237       goto ld_st;
9238     case M_SHE_AB:
9239       s = "she";
9240       fmt = "t,+j(b)";
9241       offbits = 9;
9242       goto ld_st;
9243     case M_SWE_AB:
9244       s = "swe";
9245       fmt = "t,+j(b)";
9246       offbits = 9;
9247       goto ld_st;
9248     case M_SWLE_AB:
9249       s = "swle";
9250       fmt = "t,+j(b)";
9251       offbits = 9;
9252       goto ld_st;
9253     case M_SWRE_AB:
9254       s = "swre";
9255       fmt = "t,+j(b)";
9256       offbits = 9;
9257       goto ld_st;
9258     case M_ACLR_AB:
9259       s = "aclr";
9260       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9261       fmt = "\\,~(b)";
9262       offbits = 12;
9263       goto ld_st;
9264     case M_ASET_AB:
9265       s = "aset";
9266       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
9267       fmt = "\\,~(b)";
9268       offbits = 12;
9269       goto ld_st;
9270     case M_LB_AB:
9271       s = "lb";
9272       fmt = "t,o(b)";
9273       goto ld;
9274     case M_LBU_AB:
9275       s = "lbu";
9276       fmt = "t,o(b)";
9277       goto ld;
9278     case M_LH_AB:
9279       s = "lh";
9280       fmt = "t,o(b)";
9281       goto ld;
9282     case M_LHU_AB:
9283       s = "lhu";
9284       fmt = "t,o(b)";
9285       goto ld;
9286     case M_LW_AB:
9287       s = "lw";
9288       fmt = "t,o(b)";
9289       goto ld;
9290     case M_LWC0_AB:
9291       gas_assert (!mips_opts.micromips);
9292       s = "lwc0";
9293       fmt = "E,o(b)";
9294       /* Itbl support may require additional care here.  */
9295       coproc = 1;
9296       goto ld_st;
9297     case M_LWC1_AB:
9298       s = "lwc1";
9299       fmt = "T,o(b)";
9300       /* Itbl support may require additional care here.  */
9301       coproc = 1;
9302       goto ld_st;
9303     case M_LWC2_AB:
9304       s = "lwc2";
9305       fmt = COP12_FMT;
9306       offbits = (mips_opts.micromips ? 12 : 16);
9307       /* Itbl support may require additional care here.  */
9308       coproc = 1;
9309       goto ld_st;
9310     case M_LWC3_AB:
9311       gas_assert (!mips_opts.micromips);
9312       s = "lwc3";
9313       fmt = "E,o(b)";
9314       /* Itbl support may require additional care here.  */
9315       coproc = 1;
9316       goto ld_st;
9317     case M_LWL_AB:
9318       s = "lwl";
9319       fmt = MEM12_FMT;
9320       offbits = (mips_opts.micromips ? 12 : 16);
9321       goto ld_st;
9322     case M_LWR_AB:
9323       s = "lwr";
9324       fmt = MEM12_FMT;
9325       offbits = (mips_opts.micromips ? 12 : 16);
9326       goto ld_st;
9327     case M_LDC1_AB:
9328       s = "ldc1";
9329       fmt = "T,o(b)";
9330       /* Itbl support may require additional care here.  */
9331       coproc = 1;
9332       goto ld_st;
9333     case M_LDC2_AB:
9334       s = "ldc2";
9335       fmt = COP12_FMT;
9336       offbits = (mips_opts.micromips ? 12 : 16);
9337       /* Itbl support may require additional care here.  */
9338       coproc = 1;
9339       goto ld_st;
9340     case M_LQC2_AB:
9341       s = "lqc2";
9342       fmt = "E,o(b)";
9343       /* Itbl support may require additional care here.  */
9344       coproc = 1;
9345       goto ld_st;
9346     case M_LDC3_AB:
9347       s = "ldc3";
9348       fmt = "E,o(b)";
9349       /* Itbl support may require additional care here.  */
9350       coproc = 1;
9351       goto ld_st;
9352     case M_LDL_AB:
9353       s = "ldl";
9354       fmt = MEM12_FMT;
9355       offbits = (mips_opts.micromips ? 12 : 16);
9356       goto ld_st;
9357     case M_LDR_AB:
9358       s = "ldr";
9359       fmt = MEM12_FMT;
9360       offbits = (mips_opts.micromips ? 12 : 16);
9361       goto ld_st;
9362     case M_LL_AB:
9363       s = "ll";
9364       fmt = MEM12_FMT;
9365       offbits = (mips_opts.micromips ? 12 : 16);
9366       goto ld;
9367     case M_LLD_AB:
9368       s = "lld";
9369       fmt = MEM12_FMT;
9370       offbits = (mips_opts.micromips ? 12 : 16);
9371       goto ld;
9372     case M_LWU_AB:
9373       s = "lwu";
9374       fmt = MEM12_FMT;
9375       offbits = (mips_opts.micromips ? 12 : 16);
9376       goto ld;
9377     case M_LWP_AB:
9378       gas_assert (mips_opts.micromips);
9379       s = "lwp";
9380       fmt = "t,~(b)";
9381       offbits = 12;
9382       lp = 1;
9383       goto ld;
9384     case M_LDP_AB:
9385       gas_assert (mips_opts.micromips);
9386       s = "ldp";
9387       fmt = "t,~(b)";
9388       offbits = 12;
9389       lp = 1;
9390       goto ld;
9391     case M_LWM_AB:
9392       gas_assert (mips_opts.micromips);
9393       s = "lwm";
9394       fmt = "n,~(b)";
9395       offbits = 12;
9396       goto ld_st;
9397     case M_LDM_AB:
9398       gas_assert (mips_opts.micromips);
9399       s = "ldm";
9400       fmt = "n,~(b)";
9401       offbits = 12;
9402       goto ld_st;
9403
9404     ld:
9405       /* We don't want to use $0 as tempreg.  */
9406       if (breg == treg + lp || treg + lp == ZERO)
9407         goto ld_st;
9408       else
9409         tempreg = treg + lp;
9410       goto ld_noat;
9411
9412     case M_SB_AB:
9413       s = "sb";
9414       fmt = "t,o(b)";
9415       goto ld_st;
9416     case M_SH_AB:
9417       s = "sh";
9418       fmt = "t,o(b)";
9419       goto ld_st;
9420     case M_SW_AB:
9421       s = "sw";
9422       fmt = "t,o(b)";
9423       goto ld_st;
9424     case M_SWC0_AB:
9425       gas_assert (!mips_opts.micromips);
9426       s = "swc0";
9427       fmt = "E,o(b)";
9428       /* Itbl support may require additional care here.  */
9429       coproc = 1;
9430       goto ld_st;
9431     case M_SWC1_AB:
9432       s = "swc1";
9433       fmt = "T,o(b)";
9434       /* Itbl support may require additional care here.  */
9435       coproc = 1;
9436       goto ld_st;
9437     case M_SWC2_AB:
9438       s = "swc2";
9439       fmt = COP12_FMT;
9440       offbits = (mips_opts.micromips ? 12 : 16);
9441       /* Itbl support may require additional care here.  */
9442       coproc = 1;
9443       goto ld_st;
9444     case M_SWC3_AB:
9445       gas_assert (!mips_opts.micromips);
9446       s = "swc3";
9447       fmt = "E,o(b)";
9448       /* Itbl support may require additional care here.  */
9449       coproc = 1;
9450       goto ld_st;
9451     case M_SWL_AB:
9452       s = "swl";
9453       fmt = MEM12_FMT;
9454       offbits = (mips_opts.micromips ? 12 : 16);
9455       goto ld_st;
9456     case M_SWR_AB:
9457       s = "swr";
9458       fmt = MEM12_FMT;
9459       offbits = (mips_opts.micromips ? 12 : 16);
9460       goto ld_st;
9461     case M_SC_AB:
9462       s = "sc";
9463       fmt = MEM12_FMT;
9464       offbits = (mips_opts.micromips ? 12 : 16);
9465       goto ld_st;
9466     case M_SCD_AB:
9467       s = "scd";
9468       fmt = MEM12_FMT;
9469       offbits = (mips_opts.micromips ? 12 : 16);
9470       goto ld_st;
9471     case M_CACHE_AB:
9472       s = "cache";
9473       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
9474       offbits = (mips_opts.micromips ? 12 : 16);
9475       goto ld_st;
9476     case M_CACHEE_AB:
9477       s = "cachee";
9478       fmt = "k,+j(b)";
9479       offbits = 9;
9480       goto ld_st;
9481     case M_PREF_AB:
9482       s = "pref";
9483       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
9484       offbits = (mips_opts.micromips ? 12 : 16);
9485       goto ld_st;
9486     case M_PREFE_AB:
9487       s = "prefe";
9488       fmt = "k,+j(b)";
9489       offbits = 9;
9490       goto ld_st;
9491     case M_SDC1_AB:
9492       s = "sdc1";
9493       fmt = "T,o(b)";
9494       coproc = 1;
9495       /* Itbl support may require additional care here.  */
9496       goto ld_st;
9497     case M_SDC2_AB:
9498       s = "sdc2";
9499       fmt = COP12_FMT;
9500       offbits = (mips_opts.micromips ? 12 : 16);
9501       /* Itbl support may require additional care here.  */
9502       coproc = 1;
9503       goto ld_st;
9504     case M_SQC2_AB:
9505       s = "sqc2";
9506       fmt = "E,o(b)";
9507       /* Itbl support may require additional care here.  */
9508       coproc = 1;
9509       goto ld_st;
9510     case M_SDC3_AB:
9511       gas_assert (!mips_opts.micromips);
9512       s = "sdc3";
9513       fmt = "E,o(b)";
9514       /* Itbl support may require additional care here.  */
9515       coproc = 1;
9516       goto ld_st;
9517     case M_SDL_AB:
9518       s = "sdl";
9519       fmt = MEM12_FMT;
9520       offbits = (mips_opts.micromips ? 12 : 16);
9521       goto ld_st;
9522     case M_SDR_AB:
9523       s = "sdr";
9524       fmt = MEM12_FMT;
9525       offbits = (mips_opts.micromips ? 12 : 16);
9526       goto ld_st;
9527     case M_SWP_AB:
9528       gas_assert (mips_opts.micromips);
9529       s = "swp";
9530       fmt = "t,~(b)";
9531       offbits = 12;
9532       goto ld_st;
9533     case M_SDP_AB:
9534       gas_assert (mips_opts.micromips);
9535       s = "sdp";
9536       fmt = "t,~(b)";
9537       offbits = 12;
9538       goto ld_st;
9539     case M_SWM_AB:
9540       gas_assert (mips_opts.micromips);
9541       s = "swm";
9542       fmt = "n,~(b)";
9543       offbits = 12;
9544       goto ld_st;
9545     case M_SDM_AB:
9546       gas_assert (mips_opts.micromips);
9547       s = "sdm";
9548       fmt = "n,~(b)";
9549       offbits = 12;
9550
9551     ld_st:
9552       tempreg = AT;
9553     ld_noat:
9554       if (small_offset_p (0, align, 16))
9555         {
9556           /* The first case exists for M_LD_AB and M_SD_AB, which are
9557              macros for o32 but which should act like normal instructions
9558              otherwise.  */
9559           if (offbits == 16)
9560             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
9561                          offset_reloc[1], offset_reloc[2], breg);
9562           else if (small_offset_p (0, align, offbits))
9563             {
9564               if (offbits == 0)
9565                 macro_build (NULL, s, fmt, treg, breg);
9566               else
9567                 macro_build (NULL, s, fmt, treg,
9568                              (int) offset_expr.X_add_number, breg);
9569             }
9570           else
9571             {
9572               if (tempreg == AT)
9573                 used_at = 1;
9574               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9575                            tempreg, breg, -1, offset_reloc[0],
9576                            offset_reloc[1], offset_reloc[2]);
9577               if (offbits == 0)
9578                 macro_build (NULL, s, fmt, treg, tempreg);
9579               else
9580                 macro_build (NULL, s, fmt, treg, 0, tempreg);
9581             }
9582           break;
9583         }
9584
9585       if (tempreg == AT)
9586         used_at = 1;
9587
9588       if (offset_expr.X_op != O_constant
9589           && offset_expr.X_op != O_symbol)
9590         {
9591           as_bad (_("Expression too complex"));
9592           offset_expr.X_op = O_constant;
9593         }
9594
9595       if (HAVE_32BIT_ADDRESSES
9596           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9597         {
9598           char value [32];
9599
9600           sprintf_vma (value, offset_expr.X_add_number);
9601           as_bad (_("Number (0x%s) larger than 32 bits"), value);
9602         }
9603
9604       /* A constant expression in PIC code can be handled just as it
9605          is in non PIC code.  */
9606       if (offset_expr.X_op == O_constant)
9607         {
9608           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
9609                                                  offbits == 0 ? 16 : offbits);
9610           offset_expr.X_add_number -= expr1.X_add_number;
9611
9612           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
9613           if (breg != 0)
9614             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9615                          tempreg, tempreg, breg);
9616           if (offbits == 0)
9617             {
9618               if (offset_expr.X_add_number != 0)
9619                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
9620                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
9621               macro_build (NULL, s, fmt, treg, tempreg);
9622             }
9623           else if (offbits == 16)
9624             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9625           else
9626             macro_build (NULL, s, fmt, treg,
9627                          (int) offset_expr.X_add_number, tempreg);
9628         }
9629       else if (offbits != 16)
9630         {
9631           /* The offset field is too narrow to be used for a low-part
9632              relocation, so load the whole address into the auxillary
9633              register.  */
9634           load_address (tempreg, &offset_expr, &used_at);
9635           if (breg != 0)
9636             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9637                          tempreg, tempreg, breg);
9638           if (offbits == 0)
9639             macro_build (NULL, s, fmt, treg, tempreg);
9640           else
9641             macro_build (NULL, s, fmt, treg, 0, tempreg);
9642         }
9643       else if (mips_pic == NO_PIC)
9644         {
9645           /* If this is a reference to a GP relative symbol, and there
9646              is no base register, we want
9647                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9648              Otherwise, if there is no base register, we want
9649                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9650                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9651              If we have a constant, we need two instructions anyhow,
9652              so we always use the latter form.
9653
9654              If we have a base register, and this is a reference to a
9655              GP relative symbol, we want
9656                addu     $tempreg,$breg,$gp
9657                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9658              Otherwise we want
9659                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9660                addu     $tempreg,$tempreg,$breg
9661                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9662              With a constant we always use the latter case.
9663
9664              With 64bit address space and no base register and $at usable,
9665              we want
9666                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9667                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9668                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9669                dsll32   $tempreg,0
9670                daddu    $tempreg,$at
9671                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9672              If we have a base register, we want
9673                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9674                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9675                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9676                daddu    $at,$breg
9677                dsll32   $tempreg,0
9678                daddu    $tempreg,$at
9679                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9680
9681              Without $at we can't generate the optimal path for superscalar
9682              processors here since this would require two temporary registers.
9683                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9684                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9685                dsll     $tempreg,16
9686                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9687                dsll     $tempreg,16
9688                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9689              If we have a base register, we want
9690                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9691                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9692                dsll     $tempreg,16
9693                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9694                dsll     $tempreg,16
9695                daddu    $tempreg,$tempreg,$breg
9696                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9697
9698              For GP relative symbols in 64bit address space we can use
9699              the same sequence as in 32bit address space.  */
9700           if (HAVE_64BIT_SYMBOLS)
9701             {
9702               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9703                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9704                 {
9705                   relax_start (offset_expr.X_add_symbol);
9706                   if (breg == 0)
9707                     {
9708                       macro_build (&offset_expr, s, fmt, treg,
9709                                    BFD_RELOC_GPREL16, mips_gp_register);
9710                     }
9711                   else
9712                     {
9713                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9714                                    tempreg, breg, mips_gp_register);
9715                       macro_build (&offset_expr, s, fmt, treg,
9716                                    BFD_RELOC_GPREL16, tempreg);
9717                     }
9718                   relax_switch ();
9719                 }
9720
9721               if (used_at == 0 && mips_opts.at)
9722                 {
9723                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9724                                BFD_RELOC_MIPS_HIGHEST);
9725                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
9726                                BFD_RELOC_HI16_S);
9727                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9728                                tempreg, BFD_RELOC_MIPS_HIGHER);
9729                   if (breg != 0)
9730                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
9731                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9732                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9733                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
9734                                tempreg);
9735                   used_at = 1;
9736                 }
9737               else
9738                 {
9739                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9740                                BFD_RELOC_MIPS_HIGHEST);
9741                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9742                                tempreg, BFD_RELOC_MIPS_HIGHER);
9743                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9744                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9745                                tempreg, BFD_RELOC_HI16_S);
9746                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9747                   if (breg != 0)
9748                     macro_build (NULL, "daddu", "d,v,t",
9749                                  tempreg, tempreg, breg);
9750                   macro_build (&offset_expr, s, fmt, treg,
9751                                BFD_RELOC_LO16, tempreg);
9752                 }
9753
9754               if (mips_relax.sequence)
9755                 relax_end ();
9756               break;
9757             }
9758
9759           if (breg == 0)
9760             {
9761               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9762                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9763                 {
9764                   relax_start (offset_expr.X_add_symbol);
9765                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
9766                                mips_gp_register);
9767                   relax_switch ();
9768                 }
9769               macro_build_lui (&offset_expr, tempreg);
9770               macro_build (&offset_expr, s, fmt, treg,
9771                            BFD_RELOC_LO16, tempreg);
9772               if (mips_relax.sequence)
9773                 relax_end ();
9774             }
9775           else
9776             {
9777               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9778                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9779                 {
9780                   relax_start (offset_expr.X_add_symbol);
9781                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9782                                tempreg, breg, mips_gp_register);
9783                   macro_build (&offset_expr, s, fmt, treg,
9784                                BFD_RELOC_GPREL16, tempreg);
9785                   relax_switch ();
9786                 }
9787               macro_build_lui (&offset_expr, tempreg);
9788               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9789                            tempreg, tempreg, breg);
9790               macro_build (&offset_expr, s, fmt, treg,
9791                            BFD_RELOC_LO16, tempreg);
9792               if (mips_relax.sequence)
9793                 relax_end ();
9794             }
9795         }
9796       else if (!mips_big_got)
9797         {
9798           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9799
9800           /* If this is a reference to an external symbol, we want
9801                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9802                nop
9803                <op>     $treg,0($tempreg)
9804              Otherwise we want
9805                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9806                nop
9807                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9808                <op>     $treg,0($tempreg)
9809
9810              For NewABI, we want
9811                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9812                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
9813
9814              If there is a base register, we add it to $tempreg before
9815              the <op>.  If there is a constant, we stick it in the
9816              <op> instruction.  We don't handle constants larger than
9817              16 bits, because we have no way to load the upper 16 bits
9818              (actually, we could handle them for the subset of cases
9819              in which we are not using $at).  */
9820           gas_assert (offset_expr.X_op == O_symbol);
9821           if (HAVE_NEWABI)
9822             {
9823               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9824                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9825               if (breg != 0)
9826                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9827                              tempreg, tempreg, breg);
9828               macro_build (&offset_expr, s, fmt, treg,
9829                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
9830               break;
9831             }
9832           expr1.X_add_number = offset_expr.X_add_number;
9833           offset_expr.X_add_number = 0;
9834           if (expr1.X_add_number < -0x8000
9835               || expr1.X_add_number >= 0x8000)
9836             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9837           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9838                        lw_reloc_type, mips_gp_register);
9839           load_delay_nop ();
9840           relax_start (offset_expr.X_add_symbol);
9841           relax_switch ();
9842           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9843                        tempreg, BFD_RELOC_LO16);
9844           relax_end ();
9845           if (breg != 0)
9846             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9847                          tempreg, tempreg, breg);
9848           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9849         }
9850       else if (mips_big_got && !HAVE_NEWABI)
9851         {
9852           int gpdelay;
9853
9854           /* If this is a reference to an external symbol, we want
9855                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9856                addu     $tempreg,$tempreg,$gp
9857                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9858                <op>     $treg,0($tempreg)
9859              Otherwise we want
9860                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9861                nop
9862                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9863                <op>     $treg,0($tempreg)
9864              If there is a base register, we add it to $tempreg before
9865              the <op>.  If there is a constant, we stick it in the
9866              <op> instruction.  We don't handle constants larger than
9867              16 bits, because we have no way to load the upper 16 bits
9868              (actually, we could handle them for the subset of cases
9869              in which we are not using $at).  */
9870           gas_assert (offset_expr.X_op == O_symbol);
9871           expr1.X_add_number = offset_expr.X_add_number;
9872           offset_expr.X_add_number = 0;
9873           if (expr1.X_add_number < -0x8000
9874               || expr1.X_add_number >= 0x8000)
9875             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9876           gpdelay = reg_needs_delay (mips_gp_register);
9877           relax_start (offset_expr.X_add_symbol);
9878           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9879                        BFD_RELOC_MIPS_GOT_HI16);
9880           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9881                        mips_gp_register);
9882           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9883                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9884           relax_switch ();
9885           if (gpdelay)
9886             macro_build (NULL, "nop", "");
9887           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9888                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9889           load_delay_nop ();
9890           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9891                        tempreg, BFD_RELOC_LO16);
9892           relax_end ();
9893
9894           if (breg != 0)
9895             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9896                          tempreg, tempreg, breg);
9897           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9898         }
9899       else if (mips_big_got && HAVE_NEWABI)
9900         {
9901           /* If this is a reference to an external symbol, we want
9902                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9903                add      $tempreg,$tempreg,$gp
9904                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9905                <op>     $treg,<ofst>($tempreg)
9906              Otherwise, for local symbols, we want:
9907                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9908                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
9909           gas_assert (offset_expr.X_op == O_symbol);
9910           expr1.X_add_number = offset_expr.X_add_number;
9911           offset_expr.X_add_number = 0;
9912           if (expr1.X_add_number < -0x8000
9913               || expr1.X_add_number >= 0x8000)
9914             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9915           relax_start (offset_expr.X_add_symbol);
9916           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9917                        BFD_RELOC_MIPS_GOT_HI16);
9918           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9919                        mips_gp_register);
9920           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9921                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9922           if (breg != 0)
9923             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9924                          tempreg, tempreg, breg);
9925           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9926
9927           relax_switch ();
9928           offset_expr.X_add_number = expr1.X_add_number;
9929           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9930                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9931           if (breg != 0)
9932             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9933                          tempreg, tempreg, breg);
9934           macro_build (&offset_expr, s, fmt, treg,
9935                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
9936           relax_end ();
9937         }
9938       else
9939         abort ();
9940
9941       break;
9942
9943     case M_JRADDIUSP:
9944       gas_assert (mips_opts.micromips);
9945       gas_assert (mips_opts.insn32);
9946       start_noreorder ();
9947       macro_build (NULL, "jr", "s", RA);
9948       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
9949       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
9950       end_noreorder ();
9951       break;
9952
9953     case M_JRC:
9954       gas_assert (mips_opts.micromips);
9955       gas_assert (mips_opts.insn32);
9956       macro_build (NULL, "jr", "s", sreg);
9957       if (mips_opts.noreorder)
9958         macro_build (NULL, "nop", "");
9959       break;
9960
9961     case M_LI:
9962     case M_LI_S:
9963       load_register (treg, &imm_expr, 0);
9964       break;
9965
9966     case M_DLI:
9967       load_register (treg, &imm_expr, 1);
9968       break;
9969
9970     case M_LI_SS:
9971       if (imm_expr.X_op == O_constant)
9972         {
9973           used_at = 1;
9974           load_register (AT, &imm_expr, 0);
9975           macro_build (NULL, "mtc1", "t,G", AT, treg);
9976           break;
9977         }
9978       else
9979         {
9980           gas_assert (offset_expr.X_op == O_symbol
9981                       && strcmp (segment_name (S_GET_SEGMENT
9982                                                (offset_expr.X_add_symbol)),
9983                                  ".lit4") == 0
9984                       && offset_expr.X_add_number == 0);
9985           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
9986                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
9987           break;
9988         }
9989
9990     case M_LI_D:
9991       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
9992          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
9993          order 32 bits of the value and the low order 32 bits are either
9994          zero or in OFFSET_EXPR.  */
9995       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9996         {
9997           if (HAVE_64BIT_GPRS)
9998             load_register (treg, &imm_expr, 1);
9999           else
10000             {
10001               int hreg, lreg;
10002
10003               if (target_big_endian)
10004                 {
10005                   hreg = treg;
10006                   lreg = treg + 1;
10007                 }
10008               else
10009                 {
10010                   hreg = treg + 1;
10011                   lreg = treg;
10012                 }
10013
10014               if (hreg <= 31)
10015                 load_register (hreg, &imm_expr, 0);
10016               if (lreg <= 31)
10017                 {
10018                   if (offset_expr.X_op == O_absent)
10019                     move_register (lreg, 0);
10020                   else
10021                     {
10022                       gas_assert (offset_expr.X_op == O_constant);
10023                       load_register (lreg, &offset_expr, 0);
10024                     }
10025                 }
10026             }
10027           break;
10028         }
10029
10030       /* We know that sym is in the .rdata section.  First we get the
10031          upper 16 bits of the address.  */
10032       if (mips_pic == NO_PIC)
10033         {
10034           macro_build_lui (&offset_expr, AT);
10035           used_at = 1;
10036         }
10037       else
10038         {
10039           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10040                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10041           used_at = 1;
10042         }
10043
10044       /* Now we load the register(s).  */
10045       if (HAVE_64BIT_GPRS)
10046         {
10047           used_at = 1;
10048           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10049         }
10050       else
10051         {
10052           used_at = 1;
10053           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
10054           if (treg != RA)
10055             {
10056               /* FIXME: How in the world do we deal with the possible
10057                  overflow here?  */
10058               offset_expr.X_add_number += 4;
10059               macro_build (&offset_expr, "lw", "t,o(b)",
10060                            treg + 1, BFD_RELOC_LO16, AT);
10061             }
10062         }
10063       break;
10064
10065     case M_LI_DD:
10066       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
10067          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
10068          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
10069          the value and the low order 32 bits are either zero or in
10070          OFFSET_EXPR.  */
10071       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
10072         {
10073           used_at = 1;
10074           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
10075           if (HAVE_64BIT_FPRS)
10076             {
10077               gas_assert (HAVE_64BIT_GPRS);
10078               macro_build (NULL, "dmtc1", "t,S", AT, treg);
10079             }
10080           else
10081             {
10082               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
10083               if (offset_expr.X_op == O_absent)
10084                 macro_build (NULL, "mtc1", "t,G", 0, treg);
10085               else
10086                 {
10087                   gas_assert (offset_expr.X_op == O_constant);
10088                   load_register (AT, &offset_expr, 0);
10089                   macro_build (NULL, "mtc1", "t,G", AT, treg);
10090                 }
10091             }
10092           break;
10093         }
10094
10095       gas_assert (offset_expr.X_op == O_symbol
10096                   && offset_expr.X_add_number == 0);
10097       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
10098       if (strcmp (s, ".lit8") == 0)
10099         {
10100           breg = mips_gp_register;
10101           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
10102           offset_reloc[1] = BFD_RELOC_UNUSED;
10103           offset_reloc[2] = BFD_RELOC_UNUSED;
10104         }
10105       else
10106         {
10107           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
10108           used_at = 1;
10109           if (mips_pic != NO_PIC)
10110             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10111                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
10112           else
10113             {
10114               /* FIXME: This won't work for a 64 bit address.  */
10115               macro_build_lui (&offset_expr, AT);
10116             }
10117
10118           breg = AT;
10119           offset_reloc[0] = BFD_RELOC_LO16;
10120           offset_reloc[1] = BFD_RELOC_UNUSED;
10121           offset_reloc[2] = BFD_RELOC_UNUSED;
10122         }
10123       align = 8;
10124       /* Fall through */
10125
10126     case M_L_DAB:
10127       /*
10128        * The MIPS assembler seems to check for X_add_number not
10129        * being double aligned and generating:
10130        *        lui     at,%hi(foo+1)
10131        *        addu    at,at,v1
10132        *        addiu   at,at,%lo(foo+1)
10133        *        lwc1    f2,0(at)
10134        *        lwc1    f3,4(at)
10135        * But, the resulting address is the same after relocation so why
10136        * generate the extra instruction?
10137        */
10138       /* Itbl support may require additional care here.  */
10139       coproc = 1;
10140       fmt = "T,o(b)";
10141       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10142         {
10143           s = "ldc1";
10144           goto ld_st;
10145         }
10146       s = "lwc1";
10147       goto ldd_std;
10148
10149     case M_S_DAB:
10150       gas_assert (!mips_opts.micromips);
10151       /* Itbl support may require additional care here.  */
10152       coproc = 1;
10153       fmt = "T,o(b)";
10154       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
10155         {
10156           s = "sdc1";
10157           goto ld_st;
10158         }
10159       s = "swc1";
10160       goto ldd_std;
10161
10162     case M_LQ_AB:
10163       fmt = "t,o(b)";
10164       s = "lq";
10165       goto ld;
10166
10167     case M_SQ_AB:
10168       fmt = "t,o(b)";
10169       s = "sq";
10170       goto ld_st;
10171
10172     case M_LD_AB:
10173       fmt = "t,o(b)";
10174       if (HAVE_64BIT_GPRS)
10175         {
10176           s = "ld";
10177           goto ld;
10178         }
10179       s = "lw";
10180       goto ldd_std;
10181
10182     case M_SD_AB:
10183       fmt = "t,o(b)";
10184       if (HAVE_64BIT_GPRS)
10185         {
10186           s = "sd";
10187           goto ld_st;
10188         }
10189       s = "sw";
10190
10191     ldd_std:
10192       /* Even on a big endian machine $fn comes before $fn+1.  We have
10193          to adjust when loading from memory.  We set coproc if we must
10194          load $fn+1 first.  */
10195       /* Itbl support may require additional care here.  */
10196       if (!target_big_endian)
10197         coproc = 0;
10198
10199       if (small_offset_p (0, align, 16))
10200         {
10201           ep = &offset_expr;
10202           if (!small_offset_p (4, align, 16))
10203             {
10204               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
10205                            -1, offset_reloc[0], offset_reloc[1],
10206                            offset_reloc[2]);
10207               expr1.X_add_number = 0;
10208               ep = &expr1;
10209               breg = AT;
10210               used_at = 1;
10211               offset_reloc[0] = BFD_RELOC_LO16;
10212               offset_reloc[1] = BFD_RELOC_UNUSED;
10213               offset_reloc[2] = BFD_RELOC_UNUSED;
10214             }
10215           if (strcmp (s, "lw") == 0 && treg == breg)
10216             {
10217               ep->X_add_number += 4;
10218               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
10219                            offset_reloc[1], offset_reloc[2], breg);
10220               ep->X_add_number -= 4;
10221               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
10222                            offset_reloc[1], offset_reloc[2], breg);
10223             }
10224           else
10225             {
10226               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
10227                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10228                            breg);
10229               ep->X_add_number += 4;
10230               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
10231                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
10232                            breg);
10233             }
10234           break;
10235         }
10236
10237       if (offset_expr.X_op != O_symbol
10238           && offset_expr.X_op != O_constant)
10239         {
10240           as_bad (_("Expression too complex"));
10241           offset_expr.X_op = O_constant;
10242         }
10243
10244       if (HAVE_32BIT_ADDRESSES
10245           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10246         {
10247           char value [32];
10248
10249           sprintf_vma (value, offset_expr.X_add_number);
10250           as_bad (_("Number (0x%s) larger than 32 bits"), value);
10251         }
10252
10253       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
10254         {
10255           /* If this is a reference to a GP relative symbol, we want
10256                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
10257                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
10258              If we have a base register, we use this
10259                addu     $at,$breg,$gp
10260                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
10261                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
10262              If this is not a GP relative symbol, we want
10263                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10264                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10265                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10266              If there is a base register, we add it to $at after the
10267              lui instruction.  If there is a constant, we always use
10268              the last case.  */
10269           if (offset_expr.X_op == O_symbol
10270               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10271               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10272             {
10273               relax_start (offset_expr.X_add_symbol);
10274               if (breg == 0)
10275                 {
10276                   tempreg = mips_gp_register;
10277                 }
10278               else
10279                 {
10280                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10281                                AT, breg, mips_gp_register);
10282                   tempreg = AT;
10283                   used_at = 1;
10284                 }
10285
10286               /* Itbl support may require additional care here.  */
10287               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10288                            BFD_RELOC_GPREL16, tempreg);
10289               offset_expr.X_add_number += 4;
10290
10291               /* Set mips_optimize to 2 to avoid inserting an
10292                  undesired nop.  */
10293               hold_mips_optimize = mips_optimize;
10294               mips_optimize = 2;
10295               /* Itbl support may require additional care here.  */
10296               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10297                            BFD_RELOC_GPREL16, tempreg);
10298               mips_optimize = hold_mips_optimize;
10299
10300               relax_switch ();
10301
10302               offset_expr.X_add_number -= 4;
10303             }
10304           used_at = 1;
10305           if (offset_high_part (offset_expr.X_add_number, 16)
10306               != offset_high_part (offset_expr.X_add_number + 4, 16))
10307             {
10308               load_address (AT, &offset_expr, &used_at);
10309               offset_expr.X_op = O_constant;
10310               offset_expr.X_add_number = 0;
10311             }
10312           else
10313             macro_build_lui (&offset_expr, AT);
10314           if (breg != 0)
10315             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10316           /* Itbl support may require additional care here.  */
10317           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10318                        BFD_RELOC_LO16, AT);
10319           /* FIXME: How do we handle overflow here?  */
10320           offset_expr.X_add_number += 4;
10321           /* Itbl support may require additional care here.  */
10322           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10323                        BFD_RELOC_LO16, AT);
10324           if (mips_relax.sequence)
10325             relax_end ();
10326         }
10327       else if (!mips_big_got)
10328         {
10329           /* If this is a reference to an external symbol, we want
10330                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10331                nop
10332                <op>     $treg,0($at)
10333                <op>     $treg+1,4($at)
10334              Otherwise we want
10335                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10336                nop
10337                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10338                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10339              If there is a base register we add it to $at before the
10340              lwc1 instructions.  If there is a constant we include it
10341              in the lwc1 instructions.  */
10342           used_at = 1;
10343           expr1.X_add_number = offset_expr.X_add_number;
10344           if (expr1.X_add_number < -0x8000
10345               || expr1.X_add_number >= 0x8000 - 4)
10346             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10347           load_got_offset (AT, &offset_expr);
10348           load_delay_nop ();
10349           if (breg != 0)
10350             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10351
10352           /* Set mips_optimize to 2 to avoid inserting an undesired
10353              nop.  */
10354           hold_mips_optimize = mips_optimize;
10355           mips_optimize = 2;
10356
10357           /* Itbl support may require additional care here.  */
10358           relax_start (offset_expr.X_add_symbol);
10359           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10360                        BFD_RELOC_LO16, AT);
10361           expr1.X_add_number += 4;
10362           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10363                        BFD_RELOC_LO16, AT);
10364           relax_switch ();
10365           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10366                        BFD_RELOC_LO16, AT);
10367           offset_expr.X_add_number += 4;
10368           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10369                        BFD_RELOC_LO16, AT);
10370           relax_end ();
10371
10372           mips_optimize = hold_mips_optimize;
10373         }
10374       else if (mips_big_got)
10375         {
10376           int gpdelay;
10377
10378           /* If this is a reference to an external symbol, we want
10379                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
10380                addu     $at,$at,$gp
10381                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
10382                nop
10383                <op>     $treg,0($at)
10384                <op>     $treg+1,4($at)
10385              Otherwise we want
10386                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10387                nop
10388                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
10389                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
10390              If there is a base register we add it to $at before the
10391              lwc1 instructions.  If there is a constant we include it
10392              in the lwc1 instructions.  */
10393           used_at = 1;
10394           expr1.X_add_number = offset_expr.X_add_number;
10395           offset_expr.X_add_number = 0;
10396           if (expr1.X_add_number < -0x8000
10397               || expr1.X_add_number >= 0x8000 - 4)
10398             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
10399           gpdelay = reg_needs_delay (mips_gp_register);
10400           relax_start (offset_expr.X_add_symbol);
10401           macro_build (&offset_expr, "lui", LUI_FMT,
10402                        AT, BFD_RELOC_MIPS_GOT_HI16);
10403           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10404                        AT, AT, mips_gp_register);
10405           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10406                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
10407           load_delay_nop ();
10408           if (breg != 0)
10409             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10410           /* Itbl support may require additional care here.  */
10411           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
10412                        BFD_RELOC_LO16, AT);
10413           expr1.X_add_number += 4;
10414
10415           /* Set mips_optimize to 2 to avoid inserting an undesired
10416              nop.  */
10417           hold_mips_optimize = mips_optimize;
10418           mips_optimize = 2;
10419           /* Itbl support may require additional care here.  */
10420           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
10421                        BFD_RELOC_LO16, AT);
10422           mips_optimize = hold_mips_optimize;
10423           expr1.X_add_number -= 4;
10424
10425           relax_switch ();
10426           offset_expr.X_add_number = expr1.X_add_number;
10427           if (gpdelay)
10428             macro_build (NULL, "nop", "");
10429           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
10430                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
10431           load_delay_nop ();
10432           if (breg != 0)
10433             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
10434           /* Itbl support may require additional care here.  */
10435           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
10436                        BFD_RELOC_LO16, AT);
10437           offset_expr.X_add_number += 4;
10438
10439           /* Set mips_optimize to 2 to avoid inserting an undesired
10440              nop.  */
10441           hold_mips_optimize = mips_optimize;
10442           mips_optimize = 2;
10443           /* Itbl support may require additional care here.  */
10444           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
10445                        BFD_RELOC_LO16, AT);
10446           mips_optimize = hold_mips_optimize;
10447           relax_end ();
10448         }
10449       else
10450         abort ();
10451
10452       break;
10453         
10454     case M_SAA_AB:
10455       s = "saa";
10456       offbits = 0;
10457       fmt = "t,(b)";
10458       goto ld_st;
10459     case M_SAAD_AB:
10460       s = "saad";
10461       offbits = 0;
10462       fmt = "t,(b)";
10463       goto ld_st;
10464
10465    /* New code added to support COPZ instructions.
10466       This code builds table entries out of the macros in mip_opcodes.
10467       R4000 uses interlocks to handle coproc delays.
10468       Other chips (like the R3000) require nops to be inserted for delays.
10469
10470       FIXME: Currently, we require that the user handle delays.
10471       In order to fill delay slots for non-interlocked chips,
10472       we must have a way to specify delays based on the coprocessor.
10473       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
10474       What are the side-effects of the cop instruction?
10475       What cache support might we have and what are its effects?
10476       Both coprocessor & memory require delays. how long???
10477       What registers are read/set/modified?
10478
10479       If an itbl is provided to interpret cop instructions,
10480       this knowledge can be encoded in the itbl spec.  */
10481
10482     case M_COP0:
10483       s = "c0";
10484       goto copz;
10485     case M_COP1:
10486       s = "c1";
10487       goto copz;
10488     case M_COP2:
10489       s = "c2";
10490       goto copz;
10491     case M_COP3:
10492       s = "c3";
10493     copz:
10494       gas_assert (!mips_opts.micromips);
10495       /* For now we just do C (same as Cz).  The parameter will be
10496          stored in insn_opcode by mips_ip.  */
10497       macro_build (NULL, s, "C", (int) ip->insn_opcode);
10498       break;
10499
10500     case M_MOVE:
10501       move_register (dreg, sreg);
10502       break;
10503
10504     case M_MOVEP:
10505       gas_assert (mips_opts.micromips);
10506       gas_assert (mips_opts.insn32);
10507       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
10508       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
10509       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
10510       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
10511       move_register (dreg, sreg);
10512       move_register (breg, treg);
10513       break;
10514
10515     case M_DMUL:
10516       dbl = 1;
10517     case M_MUL:
10518       if (mips_opts.arch == CPU_R5900)
10519         {
10520           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
10521         }
10522       else
10523         {
10524       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
10525       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10526         }
10527       break;
10528
10529     case M_DMUL_I:
10530       dbl = 1;
10531     case M_MUL_I:
10532       /* The MIPS assembler some times generates shifts and adds.  I'm
10533          not trying to be that fancy. GCC should do this for us
10534          anyway.  */
10535       used_at = 1;
10536       load_register (AT, &imm_expr, dbl);
10537       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
10538       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10539       break;
10540
10541     case M_DMULO_I:
10542       dbl = 1;
10543     case M_MULO_I:
10544       imm = 1;
10545       goto do_mulo;
10546
10547     case M_DMULO:
10548       dbl = 1;
10549     case M_MULO:
10550     do_mulo:
10551       start_noreorder ();
10552       used_at = 1;
10553       if (imm)
10554         load_register (AT, &imm_expr, dbl);
10555       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
10556       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10557       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
10558       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10559       if (mips_trap)
10560         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
10561       else
10562         {
10563           if (mips_opts.micromips)
10564             micromips_label_expr (&label_expr);
10565           else
10566             label_expr.X_add_number = 8;
10567           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
10568           macro_build (NULL, "nop", "");
10569           macro_build (NULL, "break", BRK_FMT, 6);
10570           if (mips_opts.micromips)
10571             micromips_add_label ();
10572         }
10573       end_noreorder ();
10574       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10575       break;
10576
10577     case M_DMULOU_I:
10578       dbl = 1;
10579     case M_MULOU_I:
10580       imm = 1;
10581       goto do_mulou;
10582
10583     case M_DMULOU:
10584       dbl = 1;
10585     case M_MULOU:
10586     do_mulou:
10587       start_noreorder ();
10588       used_at = 1;
10589       if (imm)
10590         load_register (AT, &imm_expr, dbl);
10591       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
10592                    sreg, imm ? AT : treg);
10593       macro_build (NULL, "mfhi", MFHL_FMT, AT);
10594       macro_build (NULL, "mflo", MFHL_FMT, dreg);
10595       if (mips_trap)
10596         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
10597       else
10598         {
10599           if (mips_opts.micromips)
10600             micromips_label_expr (&label_expr);
10601           else
10602             label_expr.X_add_number = 8;
10603           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
10604           macro_build (NULL, "nop", "");
10605           macro_build (NULL, "break", BRK_FMT, 6);
10606           if (mips_opts.micromips)
10607             micromips_add_label ();
10608         }
10609       end_noreorder ();
10610       break;
10611
10612     case M_DROL:
10613       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10614         {
10615           if (dreg == sreg)
10616             {
10617               tempreg = AT;
10618               used_at = 1;
10619             }
10620           else
10621             {
10622               tempreg = dreg;
10623             }
10624           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
10625           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
10626           break;
10627         }
10628       used_at = 1;
10629       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10630       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
10631       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
10632       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10633       break;
10634
10635     case M_ROL:
10636       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10637         {
10638           if (dreg == sreg)
10639             {
10640               tempreg = AT;
10641               used_at = 1;
10642             }
10643           else
10644             {
10645               tempreg = dreg;
10646             }
10647           macro_build (NULL, "negu", "d,w", tempreg, treg);
10648           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
10649           break;
10650         }
10651       used_at = 1;
10652       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10653       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
10654       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
10655       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10656       break;
10657
10658     case M_DROL_I:
10659       {
10660         unsigned int rot;
10661         char *l;
10662         char *rr;
10663
10664         if (imm_expr.X_op != O_constant)
10665           as_bad (_("Improper rotate count"));
10666         rot = imm_expr.X_add_number & 0x3f;
10667         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10668           {
10669             rot = (64 - rot) & 0x3f;
10670             if (rot >= 32)
10671               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10672             else
10673               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10674             break;
10675           }
10676         if (rot == 0)
10677           {
10678             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10679             break;
10680           }
10681         l = (rot < 0x20) ? "dsll" : "dsll32";
10682         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10683         rot &= 0x1f;
10684         used_at = 1;
10685         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10686         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10687         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10688       }
10689       break;
10690
10691     case M_ROL_I:
10692       {
10693         unsigned int rot;
10694
10695         if (imm_expr.X_op != O_constant)
10696           as_bad (_("Improper rotate count"));
10697         rot = imm_expr.X_add_number & 0x1f;
10698         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10699           {
10700             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10701             break;
10702           }
10703         if (rot == 0)
10704           {
10705             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10706             break;
10707           }
10708         used_at = 1;
10709         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10710         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10711         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10712       }
10713       break;
10714
10715     case M_DROR:
10716       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10717         {
10718           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
10719           break;
10720         }
10721       used_at = 1;
10722       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10723       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
10724       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
10725       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10726       break;
10727
10728     case M_ROR:
10729       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10730         {
10731           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
10732           break;
10733         }
10734       used_at = 1;
10735       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10736       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
10737       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
10738       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10739       break;
10740
10741     case M_DROR_I:
10742       {
10743         unsigned int rot;
10744         char *l;
10745         char *rr;
10746
10747         if (imm_expr.X_op != O_constant)
10748           as_bad (_("Improper rotate count"));
10749         rot = imm_expr.X_add_number & 0x3f;
10750         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10751           {
10752             if (rot >= 32)
10753               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10754             else
10755               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10756             break;
10757           }
10758         if (rot == 0)
10759           {
10760             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10761             break;
10762           }
10763         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
10764         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
10765         rot &= 0x1f;
10766         used_at = 1;
10767         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
10768         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10769         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10770       }
10771       break;
10772
10773     case M_ROR_I:
10774       {
10775         unsigned int rot;
10776
10777         if (imm_expr.X_op != O_constant)
10778           as_bad (_("Improper rotate count"));
10779         rot = imm_expr.X_add_number & 0x1f;
10780         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10781           {
10782             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
10783             break;
10784           }
10785         if (rot == 0)
10786           {
10787             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10788             break;
10789           }
10790         used_at = 1;
10791         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
10792         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10793         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10794       }
10795       break;
10796
10797     case M_SEQ:
10798       if (sreg == 0)
10799         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
10800       else if (treg == 0)
10801         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10802       else
10803         {
10804           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10805           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10806         }
10807       break;
10808
10809     case M_SEQ_I:
10810       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10811         {
10812           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10813           break;
10814         }
10815       if (sreg == 0)
10816         {
10817           as_warn (_("Instruction %s: result is always false"),
10818                    ip->insn_mo->name);
10819           move_register (dreg, 0);
10820           break;
10821         }
10822       if (CPU_HAS_SEQ (mips_opts.arch)
10823           && -512 <= imm_expr.X_add_number
10824           && imm_expr.X_add_number < 512)
10825         {
10826           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
10827                        (int) imm_expr.X_add_number);
10828           break;
10829         }
10830       if (imm_expr.X_op == O_constant
10831           && imm_expr.X_add_number >= 0
10832           && imm_expr.X_add_number < 0x10000)
10833         {
10834           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10835         }
10836       else if (imm_expr.X_op == O_constant
10837                && imm_expr.X_add_number > -0x8000
10838                && imm_expr.X_add_number < 0)
10839         {
10840           imm_expr.X_add_number = -imm_expr.X_add_number;
10841           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10842                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10843         }
10844       else if (CPU_HAS_SEQ (mips_opts.arch))
10845         {
10846           used_at = 1;
10847           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10848           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10849           break;
10850         }
10851       else
10852         {
10853           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10854           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10855           used_at = 1;
10856         }
10857       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10858       break;
10859
10860     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
10861       s = "slt";
10862       goto sge;
10863     case M_SGEU:
10864       s = "sltu";
10865     sge:
10866       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
10867       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10868       break;
10869
10870     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
10871     case M_SGEU_I:
10872       if (imm_expr.X_op == O_constant
10873           && imm_expr.X_add_number >= -0x8000
10874           && imm_expr.X_add_number < 0x8000)
10875         {
10876           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
10877                        dreg, sreg, BFD_RELOC_LO16);
10878         }
10879       else
10880         {
10881           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10882           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
10883                        dreg, sreg, AT);
10884           used_at = 1;
10885         }
10886       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10887       break;
10888
10889     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
10890       s = "slt";
10891       goto sgt;
10892     case M_SGTU:
10893       s = "sltu";
10894     sgt:
10895       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10896       break;
10897
10898     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
10899       s = "slt";
10900       goto sgti;
10901     case M_SGTU_I:
10902       s = "sltu";
10903     sgti:
10904       used_at = 1;
10905       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10906       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10907       break;
10908
10909     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
10910       s = "slt";
10911       goto sle;
10912     case M_SLEU:
10913       s = "sltu";
10914     sle:
10915       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10916       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10917       break;
10918
10919     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
10920       s = "slt";
10921       goto slei;
10922     case M_SLEU_I:
10923       s = "sltu";
10924     slei:
10925       used_at = 1;
10926       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10927       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10928       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10929       break;
10930
10931     case M_SLT_I:
10932       if (imm_expr.X_op == O_constant
10933           && imm_expr.X_add_number >= -0x8000
10934           && imm_expr.X_add_number < 0x8000)
10935         {
10936           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10937           break;
10938         }
10939       used_at = 1;
10940       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10941       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
10942       break;
10943
10944     case M_SLTU_I:
10945       if (imm_expr.X_op == O_constant
10946           && imm_expr.X_add_number >= -0x8000
10947           && imm_expr.X_add_number < 0x8000)
10948         {
10949           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
10950                        BFD_RELOC_LO16);
10951           break;
10952         }
10953       used_at = 1;
10954       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10955       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
10956       break;
10957
10958     case M_SNE:
10959       if (sreg == 0)
10960         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
10961       else if (treg == 0)
10962         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10963       else
10964         {
10965           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10966           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10967         }
10968       break;
10969
10970     case M_SNE_I:
10971       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10972         {
10973           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10974           break;
10975         }
10976       if (sreg == 0)
10977         {
10978           as_warn (_("Instruction %s: result is always true"),
10979                    ip->insn_mo->name);
10980           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
10981                        dreg, 0, BFD_RELOC_LO16);
10982           break;
10983         }
10984       if (CPU_HAS_SEQ (mips_opts.arch)
10985           && -512 <= imm_expr.X_add_number
10986           && imm_expr.X_add_number < 512)
10987         {
10988           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
10989                        (int) imm_expr.X_add_number);
10990           break;
10991         }
10992       if (imm_expr.X_op == O_constant
10993           && imm_expr.X_add_number >= 0
10994           && imm_expr.X_add_number < 0x10000)
10995         {
10996           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10997         }
10998       else if (imm_expr.X_op == O_constant
10999                && imm_expr.X_add_number > -0x8000
11000                && imm_expr.X_add_number < 0)
11001         {
11002           imm_expr.X_add_number = -imm_expr.X_add_number;
11003           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
11004                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11005         }
11006       else if (CPU_HAS_SEQ (mips_opts.arch))
11007         {
11008           used_at = 1;
11009           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11010           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
11011           break;
11012         }
11013       else
11014         {
11015           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11016           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
11017           used_at = 1;
11018         }
11019       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
11020       break;
11021
11022     case M_SUB_I:
11023       s = "addi";
11024       s2 = "sub";
11025       goto do_subi;
11026     case M_SUBU_I:
11027       s = "addiu";
11028       s2 = "subu";
11029       goto do_subi;
11030     case M_DSUB_I:
11031       dbl = 1;
11032       s = "daddi";
11033       s2 = "dsub";
11034       if (!mips_opts.micromips)
11035         goto do_subi;
11036       if (imm_expr.X_op == O_constant
11037           && imm_expr.X_add_number > -0x200
11038           && imm_expr.X_add_number <= 0x200)
11039         {
11040           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
11041           break;
11042         }
11043       goto do_subi_i;
11044     case M_DSUBU_I:
11045       dbl = 1;
11046       s = "daddiu";
11047       s2 = "dsubu";
11048     do_subi:
11049       if (imm_expr.X_op == O_constant
11050           && imm_expr.X_add_number > -0x8000
11051           && imm_expr.X_add_number <= 0x8000)
11052         {
11053           imm_expr.X_add_number = -imm_expr.X_add_number;
11054           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
11055           break;
11056         }
11057     do_subi_i:
11058       used_at = 1;
11059       load_register (AT, &imm_expr, dbl);
11060       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
11061       break;
11062
11063     case M_TEQ_I:
11064       s = "teq";
11065       goto trap;
11066     case M_TGE_I:
11067       s = "tge";
11068       goto trap;
11069     case M_TGEU_I:
11070       s = "tgeu";
11071       goto trap;
11072     case M_TLT_I:
11073       s = "tlt";
11074       goto trap;
11075     case M_TLTU_I:
11076       s = "tltu";
11077       goto trap;
11078     case M_TNE_I:
11079       s = "tne";
11080     trap:
11081       used_at = 1;
11082       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
11083       macro_build (NULL, s, "s,t", sreg, AT);
11084       break;
11085
11086     case M_TRUNCWS:
11087     case M_TRUNCWD:
11088       gas_assert (!mips_opts.micromips);
11089       gas_assert (mips_opts.isa == ISA_MIPS1);
11090       used_at = 1;
11091       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
11092       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
11093
11094       /*
11095        * Is the double cfc1 instruction a bug in the mips assembler;
11096        * or is there a reason for it?
11097        */
11098       start_noreorder ();
11099       macro_build (NULL, "cfc1", "t,G", treg, RA);
11100       macro_build (NULL, "cfc1", "t,G", treg, RA);
11101       macro_build (NULL, "nop", "");
11102       expr1.X_add_number = 3;
11103       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
11104       expr1.X_add_number = 2;
11105       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
11106       macro_build (NULL, "ctc1", "t,G", AT, RA);
11107       macro_build (NULL, "nop", "");
11108       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
11109                    dreg, sreg);
11110       macro_build (NULL, "ctc1", "t,G", treg, RA);
11111       macro_build (NULL, "nop", "");
11112       end_noreorder ();
11113       break;
11114
11115     case M_ULH_AB:
11116       s = "lb";
11117       s2 = "lbu";
11118       off = 1;
11119       goto uld_st;
11120     case M_ULHU_AB:
11121       s = "lbu";
11122       s2 = "lbu";
11123       off = 1;
11124       goto uld_st;
11125     case M_ULW_AB:
11126       s = "lwl";
11127       s2 = "lwr";
11128       offbits = (mips_opts.micromips ? 12 : 16);
11129       off = 3;
11130       goto uld_st;
11131     case M_ULD_AB:
11132       s = "ldl";
11133       s2 = "ldr";
11134       offbits = (mips_opts.micromips ? 12 : 16);
11135       off = 7;
11136       goto uld_st;
11137     case M_USH_AB:
11138       s = "sb";
11139       s2 = "sb";
11140       off = 1;
11141       ust = 1;
11142       goto uld_st;
11143     case M_USW_AB:
11144       s = "swl";
11145       s2 = "swr";
11146       offbits = (mips_opts.micromips ? 12 : 16);
11147       off = 3;
11148       ust = 1;
11149       goto uld_st;
11150     case M_USD_AB:
11151       s = "sdl";
11152       s2 = "sdr";
11153       offbits = (mips_opts.micromips ? 12 : 16);
11154       off = 7;
11155       ust = 1;
11156
11157     uld_st:
11158       large_offset = !small_offset_p (off, align, offbits);
11159       ep = &offset_expr;
11160       expr1.X_add_number = 0;
11161       if (large_offset)
11162         {
11163           used_at = 1;
11164           tempreg = AT;
11165           if (small_offset_p (0, align, 16))
11166             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
11167                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
11168           else
11169             {
11170               load_address (tempreg, ep, &used_at);
11171               if (breg != 0)
11172                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11173                              tempreg, tempreg, breg);
11174             }
11175           offset_reloc[0] = BFD_RELOC_LO16;
11176           offset_reloc[1] = BFD_RELOC_UNUSED;
11177           offset_reloc[2] = BFD_RELOC_UNUSED;
11178           breg = tempreg;
11179           tempreg = treg;
11180           ep = &expr1;
11181         }
11182       else if (!ust && treg == breg)
11183         {
11184           used_at = 1;
11185           tempreg = AT;
11186         }
11187       else
11188         tempreg = treg;
11189
11190       if (off == 1)
11191         goto ulh_sh;
11192
11193       if (!target_big_endian)
11194         ep->X_add_number += off;
11195       if (offbits == 12)
11196         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
11197       else
11198         macro_build (ep, s, "t,o(b)", tempreg, -1,
11199                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11200
11201       if (!target_big_endian)
11202         ep->X_add_number -= off;
11203       else
11204         ep->X_add_number += off;
11205       if (offbits == 12)
11206         macro_build (NULL, s2, "t,~(b)",
11207                      tempreg, (int) ep->X_add_number, breg);
11208       else
11209         macro_build (ep, s2, "t,o(b)", tempreg, -1,
11210                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11211
11212       /* If necessary, move the result in tempreg to the final destination.  */
11213       if (!ust && treg != tempreg)
11214         {
11215           /* Protect second load's delay slot.  */
11216           load_delay_nop ();
11217           move_register (treg, tempreg);
11218         }
11219       break;
11220
11221     ulh_sh:
11222       used_at = 1;
11223       if (target_big_endian == ust)
11224         ep->X_add_number += off;
11225       tempreg = ust || large_offset ? treg : AT;
11226       macro_build (ep, s, "t,o(b)", tempreg, -1,
11227                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11228
11229       /* For halfword transfers we need a temporary register to shuffle
11230          bytes.  Unfortunately for M_USH_A we have none available before
11231          the next store as AT holds the base address.  We deal with this
11232          case by clobbering TREG and then restoring it as with ULH.  */
11233       tempreg = ust == large_offset ? treg : AT;
11234       if (ust)
11235         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
11236
11237       if (target_big_endian == ust)
11238         ep->X_add_number -= off;
11239       else
11240         ep->X_add_number += off;
11241       macro_build (ep, s2, "t,o(b)", tempreg, -1,
11242                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
11243
11244       /* For M_USH_A re-retrieve the LSB.  */
11245       if (ust && large_offset)
11246         {
11247           if (target_big_endian)
11248             ep->X_add_number += off;
11249           else
11250             ep->X_add_number -= off;
11251           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
11252                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
11253         }
11254       /* For ULH and M_USH_A OR the LSB in.  */
11255       if (!ust || large_offset)
11256         {
11257           tempreg = !large_offset ? AT : treg;
11258           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
11259           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
11260         }
11261       break;
11262
11263     default:
11264       /* FIXME: Check if this is one of the itbl macros, since they
11265          are added dynamically.  */
11266       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
11267       break;
11268     }
11269   if (!mips_opts.at && used_at)
11270     as_bad (_("Macro used $at after \".set noat\""));
11271 }
11272
11273 /* Implement macros in mips16 mode.  */
11274
11275 static void
11276 mips16_macro (struct mips_cl_insn *ip)
11277 {
11278   int mask;
11279   int xreg, yreg, zreg, tmp;
11280   expressionS expr1;
11281   int dbl;
11282   const char *s, *s2, *s3;
11283
11284   mask = ip->insn_mo->mask;
11285
11286   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
11287   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
11288   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
11289
11290   expr1.X_op = O_constant;
11291   expr1.X_op_symbol = NULL;
11292   expr1.X_add_symbol = NULL;
11293   expr1.X_add_number = 1;
11294
11295   dbl = 0;
11296
11297   switch (mask)
11298     {
11299     default:
11300       abort ();
11301
11302     case M_DDIV_3:
11303       dbl = 1;
11304     case M_DIV_3:
11305       s = "mflo";
11306       goto do_div3;
11307     case M_DREM_3:
11308       dbl = 1;
11309     case M_REM_3:
11310       s = "mfhi";
11311     do_div3:
11312       start_noreorder ();
11313       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
11314       expr1.X_add_number = 2;
11315       macro_build (&expr1, "bnez", "x,p", yreg);
11316       macro_build (NULL, "break", "6", 7);
11317
11318       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
11319          since that causes an overflow.  We should do that as well,
11320          but I don't see how to do the comparisons without a temporary
11321          register.  */
11322       end_noreorder ();
11323       macro_build (NULL, s, "x", zreg);
11324       break;
11325
11326     case M_DIVU_3:
11327       s = "divu";
11328       s2 = "mflo";
11329       goto do_divu3;
11330     case M_REMU_3:
11331       s = "divu";
11332       s2 = "mfhi";
11333       goto do_divu3;
11334     case M_DDIVU_3:
11335       s = "ddivu";
11336       s2 = "mflo";
11337       goto do_divu3;
11338     case M_DREMU_3:
11339       s = "ddivu";
11340       s2 = "mfhi";
11341     do_divu3:
11342       start_noreorder ();
11343       macro_build (NULL, s, "0,x,y", xreg, yreg);
11344       expr1.X_add_number = 2;
11345       macro_build (&expr1, "bnez", "x,p", yreg);
11346       macro_build (NULL, "break", "6", 7);
11347       end_noreorder ();
11348       macro_build (NULL, s2, "x", zreg);
11349       break;
11350
11351     case M_DMUL:
11352       dbl = 1;
11353     case M_MUL:
11354       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
11355       macro_build (NULL, "mflo", "x", zreg);
11356       break;
11357
11358     case M_DSUBU_I:
11359       dbl = 1;
11360       goto do_subu;
11361     case M_SUBU_I:
11362     do_subu:
11363       if (imm_expr.X_op != O_constant)
11364         as_bad (_("Unsupported large constant"));
11365       imm_expr.X_add_number = -imm_expr.X_add_number;
11366       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
11367       break;
11368
11369     case M_SUBU_I_2:
11370       if (imm_expr.X_op != O_constant)
11371         as_bad (_("Unsupported large constant"));
11372       imm_expr.X_add_number = -imm_expr.X_add_number;
11373       macro_build (&imm_expr, "addiu", "x,k", xreg);
11374       break;
11375
11376     case M_DSUBU_I_2:
11377       if (imm_expr.X_op != O_constant)
11378         as_bad (_("Unsupported large constant"));
11379       imm_expr.X_add_number = -imm_expr.X_add_number;
11380       macro_build (&imm_expr, "daddiu", "y,j", yreg);
11381       break;
11382
11383     case M_BEQ:
11384       s = "cmp";
11385       s2 = "bteqz";
11386       goto do_branch;
11387     case M_BNE:
11388       s = "cmp";
11389       s2 = "btnez";
11390       goto do_branch;
11391     case M_BLT:
11392       s = "slt";
11393       s2 = "btnez";
11394       goto do_branch;
11395     case M_BLTU:
11396       s = "sltu";
11397       s2 = "btnez";
11398       goto do_branch;
11399     case M_BLE:
11400       s = "slt";
11401       s2 = "bteqz";
11402       goto do_reverse_branch;
11403     case M_BLEU:
11404       s = "sltu";
11405       s2 = "bteqz";
11406       goto do_reverse_branch;
11407     case M_BGE:
11408       s = "slt";
11409       s2 = "bteqz";
11410       goto do_branch;
11411     case M_BGEU:
11412       s = "sltu";
11413       s2 = "bteqz";
11414       goto do_branch;
11415     case M_BGT:
11416       s = "slt";
11417       s2 = "btnez";
11418       goto do_reverse_branch;
11419     case M_BGTU:
11420       s = "sltu";
11421       s2 = "btnez";
11422
11423     do_reverse_branch:
11424       tmp = xreg;
11425       xreg = yreg;
11426       yreg = tmp;
11427
11428     do_branch:
11429       macro_build (NULL, s, "x,y", xreg, yreg);
11430       macro_build (&offset_expr, s2, "p");
11431       break;
11432
11433     case M_BEQ_I:
11434       s = "cmpi";
11435       s2 = "bteqz";
11436       s3 = "x,U";
11437       goto do_branch_i;
11438     case M_BNE_I:
11439       s = "cmpi";
11440       s2 = "btnez";
11441       s3 = "x,U";
11442       goto do_branch_i;
11443     case M_BLT_I:
11444       s = "slti";
11445       s2 = "btnez";
11446       s3 = "x,8";
11447       goto do_branch_i;
11448     case M_BLTU_I:
11449       s = "sltiu";
11450       s2 = "btnez";
11451       s3 = "x,8";
11452       goto do_branch_i;
11453     case M_BLE_I:
11454       s = "slti";
11455       s2 = "btnez";
11456       s3 = "x,8";
11457       goto do_addone_branch_i;
11458     case M_BLEU_I:
11459       s = "sltiu";
11460       s2 = "btnez";
11461       s3 = "x,8";
11462       goto do_addone_branch_i;
11463     case M_BGE_I:
11464       s = "slti";
11465       s2 = "bteqz";
11466       s3 = "x,8";
11467       goto do_branch_i;
11468     case M_BGEU_I:
11469       s = "sltiu";
11470       s2 = "bteqz";
11471       s3 = "x,8";
11472       goto do_branch_i;
11473     case M_BGT_I:
11474       s = "slti";
11475       s2 = "bteqz";
11476       s3 = "x,8";
11477       goto do_addone_branch_i;
11478     case M_BGTU_I:
11479       s = "sltiu";
11480       s2 = "bteqz";
11481       s3 = "x,8";
11482
11483     do_addone_branch_i:
11484       if (imm_expr.X_op != O_constant)
11485         as_bad (_("Unsupported large constant"));
11486       ++imm_expr.X_add_number;
11487
11488     do_branch_i:
11489       macro_build (&imm_expr, s, s3, xreg);
11490       macro_build (&offset_expr, s2, "p");
11491       break;
11492
11493     case M_ABS:
11494       expr1.X_add_number = 0;
11495       macro_build (&expr1, "slti", "x,8", yreg);
11496       if (xreg != yreg)
11497         move_register (xreg, yreg);
11498       expr1.X_add_number = 2;
11499       macro_build (&expr1, "bteqz", "p");
11500       macro_build (NULL, "neg", "x,w", xreg, xreg);
11501     }
11502 }
11503
11504 /* UDI immediates.  */
11505 struct mips_immed {
11506   char          type;
11507   unsigned int  shift;
11508   unsigned long mask;
11509   const char *  desc;
11510 };
11511
11512 static const struct mips_immed mips_immed[] = {
11513   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
11514   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
11515   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
11516   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
11517   { 0,0,0,0 }
11518 };
11519
11520 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
11521    taking bits from BIT up.  */
11522 static int
11523 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
11524 {
11525   return (ep->X_op == O_constant
11526           && (ep->X_add_number & ((1 << bit) - 1)) == 0
11527           && ep->X_add_number >= min << bit
11528           && ep->X_add_number < max << bit);
11529 }
11530
11531 /* Assemble an instruction into its binary format.  If the instruction
11532    is a macro, set imm_expr, imm2_expr and offset_expr to the values
11533    associated with "I", "+I" and "A" operands respectively.  Otherwise
11534    store the value of the relocatable field (if any) in offset_expr.
11535    In both cases set offset_reloc to the relocation operators applied
11536    to offset_expr.  */
11537
11538 static void
11539 mips_ip (char *str, struct mips_cl_insn *ip)
11540 {
11541   bfd_boolean wrong_delay_slot_insns = FALSE;
11542   bfd_boolean need_delay_slot_ok = TRUE;
11543   struct mips_opcode *firstinsn = NULL;
11544   const struct mips_opcode *past;
11545   struct hash_control *hash;
11546   char *s;
11547   const char *args;
11548   char c = 0;
11549   struct mips_opcode *insn;
11550   char *argsStart;
11551   unsigned int regno, regno2;
11552   unsigned int lastregno;
11553   unsigned int destregno = 0;
11554   unsigned int lastpos = 0;
11555   unsigned int limlo, limhi;
11556   int sizelo;
11557   char *s_reset;
11558   offsetT min_range, max_range;
11559   long opend;
11560   char *name;
11561   int argnum;
11562   unsigned int rtype;
11563   char *dot;
11564   long end;
11565
11566   insn_error = NULL;
11567
11568   if (mips_opts.micromips)
11569     {
11570       hash = micromips_op_hash;
11571       past = &micromips_opcodes[bfd_micromips_num_opcodes];
11572     }
11573   else
11574     {
11575       hash = op_hash;
11576       past = &mips_opcodes[NUMOPCODES];
11577     }
11578   forced_insn_length = 0;
11579   insn = NULL;
11580
11581   /* We first try to match an instruction up to a space or to the end.  */
11582   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
11583     continue;
11584
11585   /* Make a copy of the instruction so that we can fiddle with it.  */
11586   name = alloca (end + 1);
11587   memcpy (name, str, end);
11588   name[end] = '\0';
11589
11590   for (;;)
11591     {
11592       insn = (struct mips_opcode *) hash_find (hash, name);
11593
11594       if (insn != NULL || !mips_opts.micromips)
11595         break;
11596       if (forced_insn_length)
11597         break;
11598
11599       /* See if there's an instruction size override suffix,
11600          either `16' or `32', at the end of the mnemonic proper,
11601          that defines the operation, i.e. before the first `.'
11602          character if any.  Strip it and retry.  */
11603       dot = strchr (name, '.');
11604       opend = dot != NULL ? dot - name : end;
11605       if (opend < 3)
11606         break;
11607       if (name[opend - 2] == '1' && name[opend - 1] == '6')
11608         forced_insn_length = 2;
11609       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11610         forced_insn_length = 4;
11611       else
11612         break;
11613       memcpy (name + opend - 2, name + opend, end - opend + 1);
11614     }
11615   if (insn == NULL)
11616     {
11617       insn_error = _("Unrecognized opcode");
11618       return;
11619     }
11620
11621   /* For microMIPS instructions placed in a fixed-length branch delay slot
11622      we make up to two passes over the relevant fragment of the opcode
11623      table.  First we try instructions that meet the delay slot's length
11624      requirement.  If none matched, then we retry with the remaining ones
11625      and if one matches, then we use it and then issue an appropriate
11626      warning later on.  */
11627   argsStart = s = str + end;
11628   for (;;)
11629     {
11630       bfd_boolean delay_slot_ok;
11631       bfd_boolean size_ok;
11632       bfd_boolean ok;
11633
11634       gas_assert (strcmp (insn->name, name) == 0);
11635
11636       ok = is_opcode_valid (insn);
11637       size_ok = is_size_valid (insn);
11638       delay_slot_ok = is_delay_slot_valid (insn);
11639       if (!delay_slot_ok && !wrong_delay_slot_insns)
11640         {
11641           firstinsn = insn;
11642           wrong_delay_slot_insns = TRUE;
11643         }
11644       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11645         {
11646           static char buf[256];
11647
11648           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
11649             {
11650               ++insn;
11651               continue;
11652             }
11653           if (wrong_delay_slot_insns && need_delay_slot_ok)
11654             {
11655               gas_assert (firstinsn);
11656               need_delay_slot_ok = FALSE;
11657               past = insn + 1;
11658               insn = firstinsn;
11659               continue;
11660             }
11661
11662           if (insn_error)
11663             return;
11664
11665           if (!ok)
11666             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11667                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11668                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11669           else if (mips_opts.insn32)
11670             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
11671           else
11672             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11673                      8 * forced_insn_length);
11674           insn_error = buf;
11675
11676           return;
11677         }
11678
11679       imm_expr.X_op = O_absent;
11680       imm2_expr.X_op = O_absent;
11681       offset_expr.X_op = O_absent;
11682       offset_reloc[0] = BFD_RELOC_UNUSED;
11683       offset_reloc[1] = BFD_RELOC_UNUSED;
11684       offset_reloc[2] = BFD_RELOC_UNUSED;
11685
11686       create_insn (ip, insn);
11687       insn_error = NULL;
11688       argnum = 1;
11689       lastregno = 0xffffffff;
11690       for (args = insn->args;; ++args)
11691         {
11692           int is_mdmx;
11693
11694           s += strspn (s, " \t");
11695           is_mdmx = 0;
11696           switch (*args)
11697             {
11698             case '\0':          /* end of args */
11699               if (*s == '\0')
11700                 return;
11701               break;
11702
11703             case '2':
11704               /* DSP 2-bit unsigned immediate in bit 11 (for standard MIPS
11705                  code) or 14 (for microMIPS code).  */
11706               my_getExpression (&imm_expr, s);
11707               check_absolute_expr (ip, &imm_expr);
11708               if ((unsigned long) imm_expr.X_add_number != 1
11709                   && (unsigned long) imm_expr.X_add_number != 3)
11710                 {
11711                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
11712                           (unsigned long) imm_expr.X_add_number);
11713                 }
11714               INSERT_OPERAND (mips_opts.micromips,
11715                               BP, *ip, imm_expr.X_add_number);
11716               imm_expr.X_op = O_absent;
11717               s = expr_end;
11718               continue;
11719
11720             case '3':
11721               /* DSP 3-bit unsigned immediate in bit 21 (for standard MIPS
11722                  code) or 13 (for microMIPS code).  */
11723               {
11724                 unsigned long mask = (mips_opts.micromips
11725                                       ? MICROMIPSOP_MASK_SA3 : OP_MASK_SA3);
11726
11727                 my_getExpression (&imm_expr, s);
11728                 check_absolute_expr (ip, &imm_expr);
11729                 if ((unsigned long) imm_expr.X_add_number > mask)
11730                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11731                           mask, (unsigned long) imm_expr.X_add_number);
11732                 INSERT_OPERAND (mips_opts.micromips,
11733                                 SA3, *ip, imm_expr.X_add_number);
11734                 imm_expr.X_op = O_absent;
11735                 s = expr_end;
11736               }
11737               continue;
11738
11739             case '4':
11740               /* DSP 4-bit unsigned immediate in bit 21 (for standard MIPS
11741                  code) or 12 (for microMIPS code).  */
11742               {
11743                 unsigned long mask = (mips_opts.micromips
11744                                       ? MICROMIPSOP_MASK_SA4 : OP_MASK_SA4);
11745
11746                 my_getExpression (&imm_expr, s);
11747                 check_absolute_expr (ip, &imm_expr);
11748                 if ((unsigned long) imm_expr.X_add_number > mask)
11749                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11750                           mask, (unsigned long) imm_expr.X_add_number);
11751                 INSERT_OPERAND (mips_opts.micromips,
11752                                 SA4, *ip, imm_expr.X_add_number);
11753                 imm_expr.X_op = O_absent;
11754                 s = expr_end;
11755               }
11756               continue;
11757
11758             case '5':
11759               /* DSP 8-bit unsigned immediate in bit 16 (for standard MIPS
11760                  code) or 13 (for microMIPS code).  */
11761               {
11762                 unsigned long mask = (mips_opts.micromips
11763                                       ? MICROMIPSOP_MASK_IMM8 : OP_MASK_IMM8);
11764
11765                 my_getExpression (&imm_expr, s);
11766                 check_absolute_expr (ip, &imm_expr);
11767                 if ((unsigned long) imm_expr.X_add_number > mask)
11768                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11769                           mask, (unsigned long) imm_expr.X_add_number);
11770                 INSERT_OPERAND (mips_opts.micromips,
11771                                 IMM8, *ip, imm_expr.X_add_number);
11772                 imm_expr.X_op = O_absent;
11773                 s = expr_end;
11774               }
11775               continue;
11776
11777             case '6':
11778               /* DSP 5-bit unsigned immediate in bit 21 (for standard MIPS
11779                  code) or 16 (for microMIPS code).  */
11780               {
11781                 unsigned long mask = (mips_opts.micromips
11782                                       ? MICROMIPSOP_MASK_RS : OP_MASK_RS);
11783
11784                 my_getExpression (&imm_expr, s);
11785                 check_absolute_expr (ip, &imm_expr);
11786                 if ((unsigned long) imm_expr.X_add_number > mask)
11787                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11788                           mask, (unsigned long) imm_expr.X_add_number);
11789                 INSERT_OPERAND (mips_opts.micromips,
11790                                 RS, *ip, imm_expr.X_add_number);
11791                 imm_expr.X_op = O_absent;
11792                 s = expr_end;
11793               }
11794               continue;
11795
11796             case '7':
11797               /* Four DSP accumulators in bit 11 (for standard MIPS code)
11798                  or 14 (for microMIPS code).  */
11799               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11800                   && s[3] >= '0' && s[3] <= '3')
11801                 {
11802                   regno = s[3] - '0';
11803                   s += 4;
11804                   INSERT_OPERAND (mips_opts.micromips, DSPACC, *ip, regno);
11805                   continue;
11806                 }
11807               else
11808                 as_bad (_("Invalid dsp acc register"));
11809               break;
11810
11811             case '8':
11812               /* DSP 6-bit unsigned immediate in bit 11 (for standard MIPS
11813                  code) or 14 (for microMIPS code).  */
11814               {
11815                 unsigned long mask = (mips_opts.micromips
11816                                       ? MICROMIPSOP_MASK_WRDSP
11817                                       : OP_MASK_WRDSP);
11818
11819                 my_getExpression (&imm_expr, s);
11820                 check_absolute_expr (ip, &imm_expr);
11821                 if ((unsigned long) imm_expr.X_add_number > mask)
11822                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11823                           mask, (unsigned long) imm_expr.X_add_number);
11824                 INSERT_OPERAND (mips_opts.micromips,
11825                                 WRDSP, *ip, imm_expr.X_add_number);
11826                 imm_expr.X_op = O_absent;
11827                 s = expr_end;
11828               }
11829               continue;
11830
11831             case '9': /* Four DSP accumulators in bits 21,22.  */
11832               gas_assert (!mips_opts.micromips);
11833               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11834                   && s[3] >= '0' && s[3] <= '3')
11835                 {
11836                   regno = s[3] - '0';
11837                   s += 4;
11838                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
11839                   continue;
11840                 }
11841               else
11842                 as_bad (_("Invalid dsp acc register"));
11843               break;
11844
11845             case '0':
11846               /* DSP 6-bit signed immediate in bit 20 (for standard MIPS
11847                  code) or 16 (for microMIPS code).  */
11848               {
11849                 long mask = (mips_opts.micromips
11850                              ? MICROMIPSOP_MASK_DSPSFT : OP_MASK_DSPSFT);
11851
11852                 my_getExpression (&imm_expr, s);
11853                 check_absolute_expr (ip, &imm_expr);
11854                 min_range = -((mask + 1) >> 1);
11855                 max_range = ((mask + 1) >> 1) - 1;
11856                 if (imm_expr.X_add_number < min_range
11857                     || imm_expr.X_add_number > max_range)
11858                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11859                           (long) min_range, (long) max_range,
11860                           (long) imm_expr.X_add_number);
11861                 INSERT_OPERAND (mips_opts.micromips,
11862                                 DSPSFT, *ip, imm_expr.X_add_number);
11863                 imm_expr.X_op = O_absent;
11864                 s = expr_end;
11865               }
11866               continue;
11867
11868             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
11869               gas_assert (!mips_opts.micromips);
11870               my_getExpression (&imm_expr, s);
11871               check_absolute_expr (ip, &imm_expr);
11872               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
11873                 {
11874                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11875                           OP_MASK_RDDSP,
11876                           (unsigned long) imm_expr.X_add_number);
11877                 }
11878               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
11879               imm_expr.X_op = O_absent;
11880               s = expr_end;
11881               continue;
11882
11883             case ':': /* DSP 7-bit signed immediate in bit 19.  */
11884               gas_assert (!mips_opts.micromips);
11885               my_getExpression (&imm_expr, s);
11886               check_absolute_expr (ip, &imm_expr);
11887               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
11888               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
11889               if (imm_expr.X_add_number < min_range ||
11890                   imm_expr.X_add_number > max_range)
11891                 {
11892                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11893                           (long) min_range, (long) max_range,
11894                           (long) imm_expr.X_add_number);
11895                 }
11896               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
11897               imm_expr.X_op = O_absent;
11898               s = expr_end;
11899               continue;
11900
11901             case '@': /* DSP 10-bit signed immediate in bit 16.  */
11902               {
11903                 long mask = (mips_opts.micromips
11904                              ? MICROMIPSOP_MASK_IMM10 : OP_MASK_IMM10);
11905
11906                 my_getExpression (&imm_expr, s);
11907                 check_absolute_expr (ip, &imm_expr);
11908                 min_range = -((mask + 1) >> 1);
11909                 max_range = ((mask + 1) >> 1) - 1;
11910                 if (imm_expr.X_add_number < min_range
11911                     || imm_expr.X_add_number > max_range)
11912                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11913                           (long) min_range, (long) max_range,
11914                           (long) imm_expr.X_add_number);
11915                 INSERT_OPERAND (mips_opts.micromips,
11916                                 IMM10, *ip, imm_expr.X_add_number);
11917                 imm_expr.X_op = O_absent;
11918                 s = expr_end;
11919               }
11920               continue;
11921
11922             case '^': /* DSP 5-bit unsigned immediate in bit 11.  */
11923               gas_assert (mips_opts.micromips);
11924               my_getExpression (&imm_expr, s);
11925               check_absolute_expr (ip, &imm_expr);
11926               if (imm_expr.X_add_number & ~MICROMIPSOP_MASK_RD)
11927                 as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11928                         MICROMIPSOP_MASK_RD,
11929                         (unsigned long) imm_expr.X_add_number);
11930               INSERT_OPERAND (1, RD, *ip, imm_expr.X_add_number);
11931               imm_expr.X_op = O_absent;
11932               s = expr_end;
11933               continue;
11934
11935             case '!': /* MT usermode flag bit.  */
11936               gas_assert (!mips_opts.micromips);
11937               my_getExpression (&imm_expr, s);
11938               check_absolute_expr (ip, &imm_expr);
11939               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
11940                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
11941                         (unsigned long) imm_expr.X_add_number);
11942               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
11943               imm_expr.X_op = O_absent;
11944               s = expr_end;
11945               continue;
11946
11947             case '$': /* MT load high flag bit.  */
11948               gas_assert (!mips_opts.micromips);
11949               my_getExpression (&imm_expr, s);
11950               check_absolute_expr (ip, &imm_expr);
11951               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
11952                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
11953                         (unsigned long) imm_expr.X_add_number);
11954               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
11955               imm_expr.X_op = O_absent;
11956               s = expr_end;
11957               continue;
11958
11959             case '*': /* Four DSP accumulators in bits 18,19.  */
11960               gas_assert (!mips_opts.micromips);
11961               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11962                   s[3] >= '0' && s[3] <= '3')
11963                 {
11964                   regno = s[3] - '0';
11965                   s += 4;
11966                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
11967                   continue;
11968                 }
11969               else
11970                 as_bad (_("Invalid dsp/smartmips acc register"));
11971               break;
11972
11973             case '&': /* Four DSP accumulators in bits 13,14.  */
11974               gas_assert (!mips_opts.micromips);
11975               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11976                   s[3] >= '0' && s[3] <= '3')
11977                 {
11978                   regno = s[3] - '0';
11979                   s += 4;
11980                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
11981                   continue;
11982                 }
11983               else
11984                 as_bad (_("Invalid dsp/smartmips acc register"));
11985               break;
11986
11987             case '\\':          /* 3-bit bit position.  */
11988               {
11989                 unsigned long mask = (mips_opts.micromips
11990                                       ? MICROMIPSOP_MASK_3BITPOS
11991                                       : OP_MASK_3BITPOS);
11992
11993                 my_getExpression (&imm_expr, s);
11994                 check_absolute_expr (ip, &imm_expr);
11995                 if ((unsigned long) imm_expr.X_add_number > mask)
11996                   as_warn (_("Bit position for %s not in range 0..%lu (%lu)"),
11997                            ip->insn_mo->name,
11998                            mask, (unsigned long) imm_expr.X_add_number);
11999                 INSERT_OPERAND (mips_opts.micromips,
12000                                 3BITPOS, *ip, imm_expr.X_add_number);
12001                 imm_expr.X_op = O_absent;
12002                 s = expr_end;
12003               }
12004               continue;
12005
12006             case ',':
12007               ++argnum;
12008               if (*s++ == *args)
12009                 continue;
12010               s--;
12011               switch (*++args)
12012                 {
12013                 case 'r':
12014                 case 'v':
12015                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
12016                   continue;
12017
12018                 case 'w':
12019                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
12020                   continue;
12021
12022                 case 'W':
12023                   gas_assert (!mips_opts.micromips);
12024                   INSERT_OPERAND (0, FT, *ip, lastregno);
12025                   continue;
12026
12027                 case 'V':
12028                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
12029                   continue;
12030                 }
12031               break;
12032
12033             case '(':
12034               /* Handle optional base register.
12035                  Either the base register is omitted or
12036                  we must have a left paren.  */
12037               /* This is dependent on the next operand specifier
12038                  is a base register specification.  */
12039               gas_assert (args[1] == 'b'
12040                           || (mips_opts.micromips
12041                               && args[1] == 'm'
12042                               && (args[2] == 'l' || args[2] == 'n'
12043                                   || args[2] == 's' || args[2] == 'a')));
12044               if (*s == '\0' && args[1] == 'b')
12045                 return;
12046               /* Fall through.  */
12047
12048             case ')':           /* These must match exactly.  */
12049               if (*s++ == *args)
12050                 continue;
12051               break;
12052
12053             case '+':           /* Opcode extension character.  */
12054               switch (*++args)
12055                 {
12056                 case '1':       /* UDI immediates.  */
12057                 case '2':
12058                 case '3':
12059                 case '4':
12060                   gas_assert (!mips_opts.micromips);
12061                   {
12062                     const struct mips_immed *imm = mips_immed;
12063
12064                     while (imm->type && imm->type != *args)
12065                       ++imm;
12066                     if (! imm->type)
12067                       abort ();
12068                     my_getExpression (&imm_expr, s);
12069                     check_absolute_expr (ip, &imm_expr);
12070                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
12071                       {
12072                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
12073                                  imm->desc ? imm->desc : ip->insn_mo->name,
12074                                  (unsigned long) imm_expr.X_add_number,
12075                                  (unsigned long) imm_expr.X_add_number);
12076                         imm_expr.X_add_number &= imm->mask;
12077                       }
12078                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
12079                                         << imm->shift);
12080                     imm_expr.X_op = O_absent;
12081                     s = expr_end;
12082                   }
12083                   continue;
12084
12085                 case 'J':               /* 10-bit hypcall code.  */
12086                   gas_assert (!mips_opts.micromips);
12087                   {
12088                     unsigned long mask = OP_MASK_CODE10;
12089
12090                     my_getExpression (&imm_expr, s);
12091                     check_absolute_expr (ip, &imm_expr);
12092                     if ((unsigned long) imm_expr.X_add_number > mask)
12093                       as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12094                                ip->insn_mo->name,
12095                                mask, (unsigned long) imm_expr.X_add_number);
12096                     INSERT_OPERAND (0, CODE10, *ip, imm_expr.X_add_number);
12097                     imm_expr.X_op = O_absent;
12098                     s = expr_end;
12099                   }
12100                   continue;
12101
12102                 case 'A':               /* ins/ext position, becomes LSB.  */
12103                   limlo = 0;
12104                   limhi = 31;
12105                   goto do_lsb;
12106                 case 'E':
12107                   limlo = 32;
12108                   limhi = 63;
12109                   goto do_lsb;
12110                 do_lsb:
12111                   my_getExpression (&imm_expr, s);
12112                   check_absolute_expr (ip, &imm_expr);
12113                   if ((unsigned long) imm_expr.X_add_number < limlo
12114                       || (unsigned long) imm_expr.X_add_number > limhi)
12115                     {
12116                       as_bad (_("Improper position (%lu)"),
12117                               (unsigned long) imm_expr.X_add_number);
12118                       imm_expr.X_add_number = limlo;
12119                     }
12120                   lastpos = imm_expr.X_add_number;
12121                   INSERT_OPERAND (mips_opts.micromips,
12122                                   EXTLSB, *ip, imm_expr.X_add_number);
12123                   imm_expr.X_op = O_absent;
12124                   s = expr_end;
12125                   continue;
12126
12127                 case 'B':               /* ins size, becomes MSB.  */
12128                   limlo = 1;
12129                   limhi = 32;
12130                   goto do_msb;
12131                 case 'F':
12132                   limlo = 33;
12133                   limhi = 64;
12134                   goto do_msb;
12135                 do_msb:
12136                   my_getExpression (&imm_expr, s);
12137                   check_absolute_expr (ip, &imm_expr);
12138                   /* Check for negative input so that small negative numbers
12139                      will not succeed incorrectly.  The checks against
12140                      (pos+size) transitively check "size" itself,
12141                      assuming that "pos" is reasonable.  */
12142                   if ((long) imm_expr.X_add_number < 0
12143                       || ((unsigned long) imm_expr.X_add_number
12144                           + lastpos) < limlo
12145                       || ((unsigned long) imm_expr.X_add_number
12146                           + lastpos) > limhi)
12147                     {
12148                       as_bad (_("Improper insert size (%lu, position %lu)"),
12149                               (unsigned long) imm_expr.X_add_number,
12150                               (unsigned long) lastpos);
12151                       imm_expr.X_add_number = limlo - lastpos;
12152                     }
12153                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
12154                                   lastpos + imm_expr.X_add_number - 1);
12155                   imm_expr.X_op = O_absent;
12156                   s = expr_end;
12157                   continue;
12158
12159                 case 'C':               /* ext size, becomes MSBD.  */
12160                   limlo = 1;
12161                   limhi = 32;
12162                   sizelo = 1;
12163                   goto do_msbd;
12164                 case 'G':
12165                   limlo = 33;
12166                   limhi = 64;
12167                   sizelo = 33;
12168                   goto do_msbd;
12169                 case 'H':
12170                   limlo = 33;
12171                   limhi = 64;
12172                   sizelo = 1;
12173                   goto do_msbd;
12174                 do_msbd:
12175                   my_getExpression (&imm_expr, s);
12176                   check_absolute_expr (ip, &imm_expr);
12177                   /* The checks against (pos+size) don't transitively check
12178                      "size" itself, assuming that "pos" is reasonable.
12179                      We also need to check the lower bound of "size".  */
12180                   if ((long) imm_expr.X_add_number < sizelo
12181                       || ((unsigned long) imm_expr.X_add_number
12182                           + lastpos) < limlo
12183                       || ((unsigned long) imm_expr.X_add_number
12184                           + lastpos) > limhi)
12185                     {
12186                       as_bad (_("Improper extract size (%lu, position %lu)"),
12187                               (unsigned long) imm_expr.X_add_number,
12188                               (unsigned long) lastpos);
12189                       imm_expr.X_add_number = limlo - lastpos;
12190                     }
12191                   INSERT_OPERAND (mips_opts.micromips,
12192                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
12193                   imm_expr.X_op = O_absent;
12194                   s = expr_end;
12195                   continue;
12196
12197                 case 'I':
12198                   /* "+I" is like "I", except that imm2_expr is used.  */
12199                   my_getExpression (&imm2_expr, s);
12200                   if (imm2_expr.X_op != O_big
12201                       && imm2_expr.X_op != O_constant)
12202                   insn_error = _("absolute expression required");
12203                   if (HAVE_32BIT_GPRS)
12204                     normalize_constant_expr (&imm2_expr);
12205                   s = expr_end;
12206                   continue;
12207
12208                 case 't': /* Coprocessor register number.  */
12209                   gas_assert (!mips_opts.micromips);
12210                   if (s[0] == '$' && ISDIGIT (s[1]))
12211                     {
12212                       ++s;
12213                       regno = 0;
12214                       do
12215                         {
12216                           regno *= 10;
12217                           regno += *s - '0';
12218                           ++s;
12219                         }
12220                       while (ISDIGIT (*s));
12221                       if (regno > 31)
12222                         as_bad (_("Invalid register number (%d)"), regno);
12223                       else
12224                         {
12225                           INSERT_OPERAND (0, RT, *ip, regno);
12226                           continue;
12227                         }
12228                     }
12229                   else
12230                     as_bad (_("Invalid coprocessor 0 register number"));
12231                   break;
12232
12233                 case 'x':
12234                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
12235                      is not in the valid range.  */
12236                   gas_assert (!mips_opts.micromips);
12237                   my_getExpression (&imm_expr, s);
12238                   check_absolute_expr (ip, &imm_expr);
12239                   if ((unsigned) imm_expr.X_add_number > 31)
12240                     {
12241                       as_bad (_("Improper bit index (%lu)"),
12242                               (unsigned long) imm_expr.X_add_number);
12243                       imm_expr.X_add_number = 0;
12244                     }
12245                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
12246                   imm_expr.X_op = O_absent;
12247                   s = expr_end;
12248                   continue;
12249
12250                 case 'X':
12251                   /* bbit[01] bit index when bbit is used but we generate
12252                      bbit[01]32 because the index is over 32.  Move to the
12253                      next candidate if index is not in the valid range.  */
12254                   gas_assert (!mips_opts.micromips);
12255                   my_getExpression (&imm_expr, s);
12256                   check_absolute_expr (ip, &imm_expr);
12257                   if ((unsigned) imm_expr.X_add_number < 32
12258                       || (unsigned) imm_expr.X_add_number > 63)
12259                     break;
12260                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
12261                   imm_expr.X_op = O_absent;
12262                   s = expr_end;
12263                   continue;
12264
12265                 case 'p':
12266                   /* cins, cins32, exts and exts32 position field.  Give error
12267                      if it's not in the valid range.  */
12268                   gas_assert (!mips_opts.micromips);
12269                   my_getExpression (&imm_expr, s);
12270                   check_absolute_expr (ip, &imm_expr);
12271                   if ((unsigned) imm_expr.X_add_number > 31)
12272                     {
12273                       as_bad (_("Improper position (%lu)"),
12274                               (unsigned long) imm_expr.X_add_number);
12275                       imm_expr.X_add_number = 0;
12276                     }
12277                   lastpos = imm_expr.X_add_number;
12278                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
12279                   imm_expr.X_op = O_absent;
12280                   s = expr_end;
12281                   continue;
12282
12283                 case 'P':
12284                   /* cins, cins32, exts and exts32 position field.  Move to
12285                      the next candidate if it's not in the valid range.  */
12286                   gas_assert (!mips_opts.micromips);
12287                   my_getExpression (&imm_expr, s);
12288                   check_absolute_expr (ip, &imm_expr);
12289                   if ((unsigned) imm_expr.X_add_number < 32
12290                       || (unsigned) imm_expr.X_add_number > 63)
12291                     break;
12292                   lastpos = imm_expr.X_add_number;
12293                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
12294                   imm_expr.X_op = O_absent;
12295                   s = expr_end;
12296                   continue;
12297
12298                 case 's':
12299                   /* cins32 and exts32 length-minus-one field.  */
12300                   gas_assert (!mips_opts.micromips);
12301                   my_getExpression (&imm_expr, s);
12302                   check_absolute_expr (ip, &imm_expr);
12303                   if ((unsigned long) imm_expr.X_add_number > 31
12304                       || (unsigned long) imm_expr.X_add_number + lastpos > 31)
12305                     {
12306                       as_bad (_("Improper size (%lu)"),
12307                               (unsigned long) imm_expr.X_add_number);
12308                       imm_expr.X_add_number = 0;
12309                     }
12310                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
12311                   imm_expr.X_op = O_absent;
12312                   s = expr_end;
12313                   continue;
12314
12315                 case 'S':
12316                   /* cins/exts length-minus-one field.  */
12317                   gas_assert (!mips_opts.micromips);
12318                   my_getExpression (&imm_expr, s);
12319                   check_absolute_expr (ip, &imm_expr);
12320                   if ((unsigned long) imm_expr.X_add_number > 31
12321                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
12322                     {
12323                       as_bad (_("Improper size (%lu)"),
12324                               (unsigned long) imm_expr.X_add_number);
12325                       imm_expr.X_add_number = 0;
12326                     }
12327                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
12328                   imm_expr.X_op = O_absent;
12329                   s = expr_end;
12330                   continue;
12331
12332                 case 'Q':
12333                   /* seqi/snei immediate field.  */
12334                   gas_assert (!mips_opts.micromips);
12335                   my_getExpression (&imm_expr, s);
12336                   check_absolute_expr (ip, &imm_expr);
12337                   if ((long) imm_expr.X_add_number < -512
12338                       || (long) imm_expr.X_add_number >= 512)
12339                     {
12340                       as_bad (_("Improper immediate (%ld)"),
12341                                (long) imm_expr.X_add_number);
12342                       imm_expr.X_add_number = 0;
12343                     }
12344                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
12345                   imm_expr.X_op = O_absent;
12346                   s = expr_end;
12347                   continue;
12348
12349                 case 'a': /* 8-bit signed offset in bit 6 */
12350                   gas_assert (!mips_opts.micromips);
12351                   my_getExpression (&imm_expr, s);
12352                   check_absolute_expr (ip, &imm_expr);
12353                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
12354                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
12355                   if (imm_expr.X_add_number < min_range
12356                       || imm_expr.X_add_number > max_range)
12357                     {
12358                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12359                               (long) min_range, (long) max_range,
12360                               (long) imm_expr.X_add_number);
12361                     }
12362                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
12363                   imm_expr.X_op = O_absent;
12364                   s = expr_end;
12365                   continue;
12366
12367                 case 'b': /* 8-bit signed offset in bit 3 */
12368                   gas_assert (!mips_opts.micromips);
12369                   my_getExpression (&imm_expr, s);
12370                   check_absolute_expr (ip, &imm_expr);
12371                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
12372                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
12373                   if (imm_expr.X_add_number < min_range
12374                       || imm_expr.X_add_number > max_range)
12375                     {
12376                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12377                               (long) min_range, (long) max_range,
12378                               (long) imm_expr.X_add_number);
12379                     }
12380                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
12381                   imm_expr.X_op = O_absent;
12382                   s = expr_end;
12383                   continue;
12384
12385                 case 'c': /* 9-bit signed offset in bit 6 */
12386                   gas_assert (!mips_opts.micromips);
12387                   my_getExpression (&imm_expr, s);
12388                   check_absolute_expr (ip, &imm_expr);
12389                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
12390                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
12391                   /* We check the offset range before adjusted.  */
12392                   min_range <<= 4;
12393                   max_range <<= 4;
12394                   if (imm_expr.X_add_number < min_range
12395                       || imm_expr.X_add_number > max_range)
12396                     {
12397                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
12398                               (long) min_range, (long) max_range,
12399                               (long) imm_expr.X_add_number);
12400                     }
12401                   if (imm_expr.X_add_number & 0xf)
12402                     {
12403                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
12404                               (long) imm_expr.X_add_number);
12405                     }
12406                   /* Right shift 4 bits to adjust the offset operand.  */
12407                   INSERT_OPERAND (0, OFFSET_C, *ip,
12408                                   imm_expr.X_add_number >> 4);
12409                   imm_expr.X_op = O_absent;
12410                   s = expr_end;
12411                   continue;
12412
12413                 case 'z':
12414                   gas_assert (!mips_opts.micromips);
12415                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
12416                     break;
12417                   if (regno == AT && mips_opts.at)
12418                     {
12419                       if (mips_opts.at == ATREG)
12420                         as_warn (_("used $at without \".set noat\""));
12421                       else
12422                         as_warn (_("used $%u with \".set at=$%u\""),
12423                                  regno, mips_opts.at);
12424                     }
12425                   INSERT_OPERAND (0, RZ, *ip, regno);
12426                   continue;
12427
12428                 case 'Z':
12429                   gas_assert (!mips_opts.micromips);
12430                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
12431                     break;
12432                   INSERT_OPERAND (0, FZ, *ip, regno);
12433                   continue;
12434
12435                 case 'i':
12436                   goto jump;
12437
12438                 case 'j':
12439                   {
12440                     int shift = 8;
12441                     size_t i;
12442                     bfd_reloc_code_real_type r[3];
12443
12444                     /* Check whether there is only a single bracketed expression
12445                        left.  If so, it must be the base register and the
12446                        constant must be zero.  */
12447                     if (*s == '(' && strchr (s + 1, '(') == 0)
12448                       continue;
12449
12450                     /* If this value won't fit into the offset, then go find
12451                        a macro that will generate a 16- or 32-bit offset code
12452                        pattern.  */
12453                     i = my_getSmallExpression (&imm_expr, r, s);
12454                     if ((i == 0 && (imm_expr.X_op != O_constant
12455                                     || imm_expr.X_add_number >= 1 << shift
12456                                     || imm_expr.X_add_number < -1 << shift))
12457                         || i > 0)
12458                       {
12459                         imm_expr.X_op = O_absent;
12460                         break;
12461                       }
12462                     INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, *ip,
12463                                     imm_expr.X_add_number);
12464                     imm_expr.X_op = O_absent;
12465                     s = expr_end;
12466                   }
12467                   continue;
12468
12469                 default:
12470                   as_bad (_("Internal error: bad %s opcode "
12471                             "(unknown extension operand type `+%c'): %s %s"),
12472                           mips_opts.micromips ? "microMIPS" : "MIPS",
12473                           *args, insn->name, insn->args);
12474                   /* Further processing is fruitless.  */
12475                   return;
12476                 }
12477               break;
12478
12479             case '.':           /* 10-bit offset.  */
12480               gas_assert (mips_opts.micromips);
12481             case '~':           /* 12-bit offset.  */
12482               {
12483                 int shift = *args == '.' ? 9 : 11;
12484                 size_t i;
12485                 bfd_reloc_code_real_type r[3];
12486
12487                 /* Check whether there is only a single bracketed expression
12488                    left.  If so, it must be the base register and the
12489                    constant must be zero.  */
12490                 if (*s == '(' && strchr (s + 1, '(') == 0)
12491                   continue;
12492
12493                 /* If this value won't fit into the offset, then go find
12494                    a macro that will generate a 16- or 32-bit offset code
12495                    pattern.  */
12496                 i = my_getSmallExpression (&imm_expr, r, s);
12497                 if ((i == 0 && (imm_expr.X_op != O_constant
12498                                 || imm_expr.X_add_number >= 1 << shift
12499                                 || imm_expr.X_add_number < -1 << shift))
12500                     || i > 0)
12501                   {
12502                     imm_expr.X_op = O_absent;
12503                     break;
12504                   }
12505                 if (shift == 9)
12506                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
12507                 else
12508                   INSERT_OPERAND (mips_opts.micromips,
12509                                   OFFSET12, *ip, imm_expr.X_add_number);
12510                 imm_expr.X_op = O_absent;
12511                 s = expr_end;
12512               }
12513               continue;
12514
12515             case '<':           /* must be at least one digit */
12516               /*
12517                * According to the manual, if the shift amount is greater
12518                * than 31 or less than 0, then the shift amount should be
12519                * mod 32.  In reality the mips assembler issues an error.
12520                * We issue a warning and mask out all but the low 5 bits.
12521                */
12522               my_getExpression (&imm_expr, s);
12523               check_absolute_expr (ip, &imm_expr);
12524               if ((unsigned long) imm_expr.X_add_number > 31)
12525                 as_warn (_("Improper shift amount (%lu)"),
12526                          (unsigned long) imm_expr.X_add_number);
12527               INSERT_OPERAND (mips_opts.micromips,
12528                               SHAMT, *ip, imm_expr.X_add_number);
12529               imm_expr.X_op = O_absent;
12530               s = expr_end;
12531               continue;
12532
12533             case '>':           /* shift amount minus 32 */
12534               my_getExpression (&imm_expr, s);
12535               check_absolute_expr (ip, &imm_expr);
12536               if ((unsigned long) imm_expr.X_add_number < 32
12537                   || (unsigned long) imm_expr.X_add_number > 63)
12538                 break;
12539               INSERT_OPERAND (mips_opts.micromips,
12540                               SHAMT, *ip, imm_expr.X_add_number - 32);
12541               imm_expr.X_op = O_absent;
12542               s = expr_end;
12543               continue;
12544
12545             case 'k':           /* CACHE code.  */
12546             case 'h':           /* PREFX code.  */
12547             case '1':           /* SYNC type.  */
12548               my_getExpression (&imm_expr, s);
12549               check_absolute_expr (ip, &imm_expr);
12550               if ((unsigned long) imm_expr.X_add_number > 31)
12551                 as_warn (_("Invalid value for `%s' (%lu)"),
12552                          ip->insn_mo->name,
12553                          (unsigned long) imm_expr.X_add_number);
12554               switch (*args)
12555                 {
12556                 case 'k':
12557                   if (mips_fix_cn63xxp1
12558                       && !mips_opts.micromips
12559                       && strcmp ("pref", insn->name) == 0)
12560                     switch (imm_expr.X_add_number)
12561                       {
12562                       case 5:
12563                       case 25:
12564                       case 26:
12565                       case 27:
12566                       case 28:
12567                       case 29:
12568                       case 30:
12569                       case 31:  /* These are ok.  */
12570                         break;
12571
12572                       default:  /* The rest must be changed to 28.  */
12573                         imm_expr.X_add_number = 28;
12574                         break;
12575                       }
12576                   INSERT_OPERAND (mips_opts.micromips,
12577                                   CACHE, *ip, imm_expr.X_add_number);
12578                   break;
12579                 case 'h':
12580                   INSERT_OPERAND (mips_opts.micromips,
12581                                   PREFX, *ip, imm_expr.X_add_number);
12582                   break;
12583                 case '1':
12584                   INSERT_OPERAND (mips_opts.micromips,
12585                                   STYPE, *ip, imm_expr.X_add_number);
12586                   break;
12587                 }
12588               imm_expr.X_op = O_absent;
12589               s = expr_end;
12590               continue;
12591
12592             case 'c':           /* BREAK code.  */
12593               {
12594                 unsigned long mask = (mips_opts.micromips
12595                                       ? MICROMIPSOP_MASK_CODE
12596                                       : OP_MASK_CODE);
12597
12598                 my_getExpression (&imm_expr, s);
12599                 check_absolute_expr (ip, &imm_expr);
12600                 if ((unsigned long) imm_expr.X_add_number > mask)
12601                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12602                            ip->insn_mo->name,
12603                            mask, (unsigned long) imm_expr.X_add_number);
12604                 INSERT_OPERAND (mips_opts.micromips,
12605                                 CODE, *ip, imm_expr.X_add_number);
12606                 imm_expr.X_op = O_absent;
12607                 s = expr_end;
12608               }
12609               continue;
12610
12611             case 'q':           /* Lower BREAK code.  */
12612               {
12613                 unsigned long mask = (mips_opts.micromips
12614                                       ? MICROMIPSOP_MASK_CODE2
12615                                       : OP_MASK_CODE2);
12616
12617                 my_getExpression (&imm_expr, s);
12618                 check_absolute_expr (ip, &imm_expr);
12619                 if ((unsigned long) imm_expr.X_add_number > mask)
12620                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
12621                            ip->insn_mo->name,
12622                            mask, (unsigned long) imm_expr.X_add_number);
12623                 INSERT_OPERAND (mips_opts.micromips,
12624                                 CODE2, *ip, imm_expr.X_add_number);
12625                 imm_expr.X_op = O_absent;
12626                 s = expr_end;
12627               }
12628               continue;
12629
12630             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
12631               {
12632                 unsigned long mask = (mips_opts.micromips
12633                                       ? MICROMIPSOP_MASK_CODE10
12634                                       : OP_MASK_CODE20);
12635
12636                 my_getExpression (&imm_expr, s);
12637                 check_absolute_expr (ip, &imm_expr);
12638                 if ((unsigned long) imm_expr.X_add_number > mask)
12639                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12640                            ip->insn_mo->name,
12641                            mask, (unsigned long) imm_expr.X_add_number);
12642                 if (mips_opts.micromips)
12643                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
12644                 else
12645                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
12646                 imm_expr.X_op = O_absent;
12647                 s = expr_end;
12648               }
12649               continue;
12650
12651             case 'C':           /* 25- or 23-bit coprocessor code.  */
12652               {
12653                 unsigned long mask = (mips_opts.micromips
12654                                       ? MICROMIPSOP_MASK_COPZ
12655                                       : OP_MASK_COPZ);
12656
12657                 my_getExpression (&imm_expr, s);
12658                 check_absolute_expr (ip, &imm_expr);
12659                 if ((unsigned long) imm_expr.X_add_number > mask)
12660                   as_warn (_("Coproccesor code > %u bits (%lu)"),
12661                            mips_opts.micromips ? 23U : 25U,
12662                            (unsigned long) imm_expr.X_add_number);
12663                 INSERT_OPERAND (mips_opts.micromips,
12664                                 COPZ, *ip, imm_expr.X_add_number);
12665                 imm_expr.X_op = O_absent;
12666                 s = expr_end;
12667               }
12668               continue;
12669
12670             case 'J':           /* 19-bit WAIT code.  */
12671               gas_assert (!mips_opts.micromips);
12672               my_getExpression (&imm_expr, s);
12673               check_absolute_expr (ip, &imm_expr);
12674               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
12675                 {
12676                   as_warn (_("Illegal 19-bit code (%lu)"),
12677                            (unsigned long) imm_expr.X_add_number);
12678                   imm_expr.X_add_number &= OP_MASK_CODE19;
12679                 }
12680               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
12681               imm_expr.X_op = O_absent;
12682               s = expr_end;
12683               continue;
12684
12685             case 'P':           /* Performance register.  */
12686               gas_assert (!mips_opts.micromips);
12687               my_getExpression (&imm_expr, s);
12688               check_absolute_expr (ip, &imm_expr);
12689               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
12690                 as_warn (_("Invalid performance register (%lu)"),
12691                          (unsigned long) imm_expr.X_add_number);
12692               if (imm_expr.X_add_number != 0 && mips_opts.arch == CPU_R5900
12693                 && (!strcmp(insn->name,"mfps") || !strcmp(insn->name,"mtps")))
12694                 as_warn (_("Invalid performance register (%lu)"),
12695                   (unsigned long) imm_expr.X_add_number);
12696               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
12697               imm_expr.X_op = O_absent;
12698               s = expr_end;
12699               continue;
12700
12701             case 'G':           /* Coprocessor destination register.  */
12702               {
12703                 unsigned long opcode = ip->insn_opcode;
12704                 unsigned long mask;
12705                 unsigned int types;
12706                 int cop0;
12707
12708                 if (mips_opts.micromips)
12709                   {
12710                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
12711                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
12712                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
12713                     opcode &= mask;
12714                     switch (opcode)
12715                       {
12716                       case 0x000000fc:                          /* mfc0  */
12717                       case 0x000002fc:                          /* mtc0  */
12718                       case 0x580000fc:                          /* dmfc0 */
12719                       case 0x580002fc:                          /* dmtc0 */
12720                         cop0 = 1;
12721                         break;
12722                       default:
12723                         cop0 = 0;
12724                         break;
12725                       }
12726                   }
12727                 else
12728                   {
12729                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
12730                     cop0 = opcode == OP_OP_COP0;
12731                   }
12732                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
12733                 ok = reg_lookup (&s, types, &regno);
12734                 if (mips_opts.micromips)
12735                   INSERT_OPERAND (1, RS, *ip, regno);
12736                 else
12737                   INSERT_OPERAND (0, RD, *ip, regno);
12738                 if (ok)
12739                   {
12740                     lastregno = regno;
12741                     continue;
12742                   }
12743               }
12744               break;
12745
12746             case 'y':           /* ALNV.PS source register.  */
12747               gas_assert (mips_opts.micromips);
12748               goto do_reg;
12749             case 'x':           /* Ignore register name.  */
12750             case 'U':           /* Destination register (CLO/CLZ).  */
12751             case 'g':           /* Coprocessor destination register.  */
12752               gas_assert (!mips_opts.micromips);
12753             case 'b':           /* Base register.  */
12754             case 'd':           /* Destination register.  */
12755             case 's':           /* Source register.  */
12756             case 't':           /* Target register.  */
12757             case 'r':           /* Both target and source.  */
12758             case 'v':           /* Both dest and source.  */
12759             case 'w':           /* Both dest and target.  */
12760             case 'E':           /* Coprocessor target register.  */
12761             case 'K':           /* RDHWR destination register.  */
12762             case 'z':           /* Must be zero register.  */
12763             do_reg:
12764               s_reset = s;
12765               if (*args == 'E' || *args == 'K')
12766                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
12767               else
12768                 {
12769                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12770                   if (regno == AT && mips_opts.at)
12771                     {
12772                       if (mips_opts.at == ATREG)
12773                         as_warn (_("Used $at without \".set noat\""));
12774                       else
12775                         as_warn (_("Used $%u with \".set at=$%u\""),
12776                                  regno, mips_opts.at);
12777                     }
12778                 }
12779               if (ok)
12780                 {
12781                   c = *args;
12782                   if (*s == ' ')
12783                     ++s;
12784                   if (args[1] != *s)
12785                     {
12786                       if (c == 'r' || c == 'v' || c == 'w')
12787                         {
12788                           regno = lastregno;
12789                           s = s_reset;
12790                           ++args;
12791                         }
12792                     }
12793                   /* 'z' only matches $0.  */
12794                   if (c == 'z' && regno != 0)
12795                     break;
12796
12797                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
12798                     {
12799                       if (regno == lastregno)
12800                         {
12801                           insn_error
12802                             = _("Source and destination must be different");
12803                           continue;
12804                         }
12805                       if (regno == 31 && lastregno == 0xffffffff)
12806                         {
12807                           insn_error
12808                             = _("A destination register must be supplied");
12809                           continue;
12810                         }
12811                     }
12812                   /* Now that we have assembled one operand, we use the args
12813                      string to figure out where it goes in the instruction.  */
12814                   switch (c)
12815                     {
12816                     case 'r':
12817                     case 's':
12818                     case 'v':
12819                     case 'b':
12820                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
12821                       break;
12822
12823                     case 'K':
12824                       if (mips_opts.micromips)
12825                         INSERT_OPERAND (1, RS, *ip, regno);
12826                       else
12827                         INSERT_OPERAND (0, RD, *ip, regno);
12828                       break;
12829
12830                     case 'd':
12831                     case 'g':
12832                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
12833                       break;
12834
12835                     case 'U':
12836                       gas_assert (!mips_opts.micromips);
12837                       INSERT_OPERAND (0, RD, *ip, regno);
12838                       INSERT_OPERAND (0, RT, *ip, regno);
12839                       break;
12840
12841                     case 'w':
12842                     case 't':
12843                     case 'E':
12844                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
12845                       break;
12846
12847                     case 'y':
12848                       gas_assert (mips_opts.micromips);
12849                       INSERT_OPERAND (1, RS3, *ip, regno);
12850                       break;
12851
12852                     case 'x':
12853                       /* This case exists because on the r3000 trunc
12854                          expands into a macro which requires a gp
12855                          register.  On the r6000 or r4000 it is
12856                          assembled into a single instruction which
12857                          ignores the register.  Thus the insn version
12858                          is MIPS_ISA2 and uses 'x', and the macro
12859                          version is MIPS_ISA1 and uses 't'.  */
12860                       break;
12861
12862                     case 'z':
12863                       /* This case is for the div instruction, which
12864                          acts differently if the destination argument
12865                          is $0.  This only matches $0, and is checked
12866                          outside the switch.  */
12867                       break;
12868                     }
12869                   lastregno = regno;
12870                   continue;
12871                 }
12872               switch (*args++)
12873                 {
12874                 case 'r':
12875                 case 'v':
12876                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
12877                   continue;
12878
12879                 case 'w':
12880                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
12881                   continue;
12882                 }
12883               break;
12884
12885             case 'O':           /* MDMX alignment immediate constant.  */
12886               gas_assert (!mips_opts.micromips);
12887               my_getExpression (&imm_expr, s);
12888               check_absolute_expr (ip, &imm_expr);
12889               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
12890                 as_warn (_("Improper align amount (%ld), using low bits"),
12891                          (long) imm_expr.X_add_number);
12892               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
12893               imm_expr.X_op = O_absent;
12894               s = expr_end;
12895               continue;
12896
12897             case 'Q':           /* MDMX vector, element sel, or const.  */
12898               if (s[0] != '$')
12899                 {
12900                   /* MDMX Immediate.  */
12901                   gas_assert (!mips_opts.micromips);
12902                   my_getExpression (&imm_expr, s);
12903                   check_absolute_expr (ip, &imm_expr);
12904                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
12905                     as_warn (_("Invalid MDMX Immediate (%ld)"),
12906                              (long) imm_expr.X_add_number);
12907                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
12908                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12909                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
12910                   else
12911                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
12912                   imm_expr.X_op = O_absent;
12913                   s = expr_end;
12914                   continue;
12915                 }
12916               /* Not MDMX Immediate.  Fall through.  */
12917             case 'X':           /* MDMX destination register.  */
12918             case 'Y':           /* MDMX source register.  */
12919             case 'Z':           /* MDMX target register.  */
12920               is_mdmx = !(insn->membership & INSN_5400);
12921             case 'W':
12922               gas_assert (!mips_opts.micromips);
12923             case 'D':           /* Floating point destination register.  */
12924             case 'S':           /* Floating point source register.  */
12925             case 'T':           /* Floating point target register.  */
12926             case 'R':           /* Floating point source register.  */
12927             case 'V':
12928               rtype = RTYPE_FPU;
12929               if (is_mdmx
12930                   || ((mips_opts.ase & ASE_MDMX)
12931                       && (ip->insn_mo->pinfo & FP_D)
12932                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
12933                                                 | INSN_COPROC_MEMORY_DELAY
12934                                                 | INSN_LOAD_COPROC_DELAY
12935                                                 | INSN_LOAD_MEMORY_DELAY
12936                                                 | INSN_STORE_MEMORY))))
12937                 rtype |= RTYPE_VEC;
12938               s_reset = s;
12939               if (reg_lookup (&s, rtype, &regno))
12940                 {
12941                   if ((regno & 1) != 0
12942                       && HAVE_32BIT_FPRS
12943                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
12944                     as_warn (_("Float register should be even, was %d"),
12945                              regno);
12946
12947                   c = *args;
12948                   if (*s == ' ')
12949                     ++s;
12950                   if (args[1] != *s)
12951                     {
12952                       if (c == 'V' || c == 'W')
12953                         {
12954                           regno = lastregno;
12955                           s = s_reset;
12956                           ++args;
12957                         }
12958                     }
12959                   switch (c)
12960                     {
12961                     case 'D':
12962                     case 'X':
12963                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
12964                       break;
12965
12966                     case 'V':
12967                     case 'S':
12968                     case 'Y':
12969                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
12970                       break;
12971
12972                     case 'Q':
12973                       /* This is like 'Z', but also needs to fix the MDMX
12974                          vector/scalar select bits.  Note that the
12975                          scalar immediate case is handled above.  */
12976                       if ((ip->insn_mo->membership & INSN_5400)
12977                           && strcmp (insn->name, "rzu.ob") == 0)
12978                         as_bad (_("Operand %d of `%s' must be an immediate"),
12979                                 argnum, ip->insn_mo->name);
12980
12981                       if (*s == '[')
12982                         {
12983                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
12984                           int max_el = (is_qh ? 3 : 7);
12985                           s++;
12986                           my_getExpression(&imm_expr, s);
12987                           check_absolute_expr (ip, &imm_expr);
12988                           s = expr_end;
12989                           if (imm_expr.X_add_number > max_el)
12990                             as_bad (_("Bad element selector %ld"),
12991                                     (long) imm_expr.X_add_number);
12992                           imm_expr.X_add_number &= max_el;
12993                           ip->insn_opcode |= (imm_expr.X_add_number
12994                                               << (OP_SH_VSEL +
12995                                                   (is_qh ? 2 : 1)));
12996                           imm_expr.X_op = O_absent;
12997                           if (*s != ']')
12998                             as_warn (_("Expecting ']' found '%s'"), s);
12999                           else
13000                             s++;
13001                         }
13002                       else
13003                         {
13004                           if ((ip->insn_mo->membership & INSN_5400)
13005                               && (strcmp (insn->name, "sll.ob") == 0
13006                                   || strcmp (insn->name, "srl.ob") == 0))
13007                             as_bad (_("Operand %d of `%s' must be scalar"),
13008                                     argnum, ip->insn_mo->name);
13009
13010                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
13011                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
13012                                                 << OP_SH_VSEL);
13013                           else
13014                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
13015                                                 OP_SH_VSEL);
13016                         }
13017                       /* Fall through.  */
13018                     case 'W':
13019                     case 'T':
13020                     case 'Z':
13021                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
13022                       break;
13023
13024                     case 'R':
13025                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
13026                       break;
13027                     }
13028                   lastregno = regno;
13029                   continue;
13030                 }
13031
13032               switch (*args++)
13033                 {
13034                 case 'V':
13035                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
13036                   continue;
13037
13038                 case 'W':
13039                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
13040                   continue;
13041                 }
13042               break;
13043
13044             case 'I':
13045               my_getExpression (&imm_expr, s);
13046               if (imm_expr.X_op != O_big
13047                   && imm_expr.X_op != O_constant)
13048                 insn_error = _("absolute expression required");
13049               if (HAVE_32BIT_GPRS)
13050                 normalize_constant_expr (&imm_expr);
13051               s = expr_end;
13052               continue;
13053
13054             case 'A':
13055               my_getSmallExpression (&offset_expr, offset_reloc, s);
13056               if (offset_expr.X_op == O_register)
13057                 {
13058                   /* Assume that the offset has been elided and that what
13059                      we saw was a base register.  The match will fail later
13060                      if that assumption turns out to be wrong.  */
13061                   offset_expr.X_op = O_constant;
13062                   offset_expr.X_add_number = 0;
13063                 }
13064               else
13065                 {
13066                   normalize_address_expr (&offset_expr);
13067                   s = expr_end;
13068                 }
13069               continue;
13070
13071             case 'F':
13072             case 'L':
13073             case 'f':
13074             case 'l':
13075               {
13076                 int f64;
13077                 int using_gprs;
13078                 char *save_in;
13079                 char *err;
13080                 unsigned char temp[8];
13081                 int len;
13082                 unsigned int length;
13083                 segT seg;
13084                 subsegT subseg;
13085                 char *p;
13086
13087                 /* These only appear as the last operand in an
13088                    instruction, and every instruction that accepts
13089                    them in any variant accepts them in all variants.
13090                    This means we don't have to worry about backing out
13091                    any changes if the instruction does not match.
13092
13093                    The difference between them is the size of the
13094                    floating point constant and where it goes.  For 'F'
13095                    and 'L' the constant is 64 bits; for 'f' and 'l' it
13096                    is 32 bits.  Where the constant is placed is based
13097                    on how the MIPS assembler does things:
13098                     F -- .rdata
13099                     L -- .lit8
13100                     f -- immediate value
13101                     l -- .lit4
13102
13103                     The .lit4 and .lit8 sections are only used if
13104                     permitted by the -G argument.
13105
13106                     The code below needs to know whether the target register
13107                     is 32 or 64 bits wide.  It relies on the fact 'f' and
13108                     'F' are used with GPR-based instructions and 'l' and
13109                     'L' are used with FPR-based instructions.  */
13110
13111                 f64 = *args == 'F' || *args == 'L';
13112                 using_gprs = *args == 'F' || *args == 'f';
13113
13114                 save_in = input_line_pointer;
13115                 input_line_pointer = s;
13116                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
13117                 length = len;
13118                 s = input_line_pointer;
13119                 input_line_pointer = save_in;
13120                 if (err != NULL && *err != '\0')
13121                   {
13122                     as_bad (_("Bad floating point constant: %s"), err);
13123                     memset (temp, '\0', sizeof temp);
13124                     length = f64 ? 8 : 4;
13125                   }
13126
13127                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
13128
13129                 if (*args == 'f'
13130                     || (*args == 'l'
13131                         && (g_switch_value < 4
13132                             || (temp[0] == 0 && temp[1] == 0)
13133                             || (temp[2] == 0 && temp[3] == 0))))
13134                   {
13135                     imm_expr.X_op = O_constant;
13136                     if (!target_big_endian)
13137                       imm_expr.X_add_number = bfd_getl32 (temp);
13138                     else
13139                       imm_expr.X_add_number = bfd_getb32 (temp);
13140                   }
13141                 else if (length > 4
13142                          && !mips_disable_float_construction
13143                          /* Constants can only be constructed in GPRs and
13144                             copied to FPRs if the GPRs are at least as wide
13145                             as the FPRs.  Force the constant into memory if
13146                             we are using 64-bit FPRs but the GPRs are only
13147                             32 bits wide.  */
13148                          && (using_gprs
13149                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
13150                          && ((temp[0] == 0 && temp[1] == 0)
13151                              || (temp[2] == 0 && temp[3] == 0))
13152                          && ((temp[4] == 0 && temp[5] == 0)
13153                              || (temp[6] == 0 && temp[7] == 0)))
13154                   {
13155                     /* The value is simple enough to load with a couple of
13156                        instructions.  If using 32-bit registers, set
13157                        imm_expr to the high order 32 bits and offset_expr to
13158                        the low order 32 bits.  Otherwise, set imm_expr to
13159                        the entire 64 bit constant.  */
13160                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
13161                       {
13162                         imm_expr.X_op = O_constant;
13163                         offset_expr.X_op = O_constant;
13164                         if (!target_big_endian)
13165                           {
13166                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
13167                             offset_expr.X_add_number = bfd_getl32 (temp);
13168                           }
13169                         else
13170                           {
13171                             imm_expr.X_add_number = bfd_getb32 (temp);
13172                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
13173                           }
13174                         if (offset_expr.X_add_number == 0)
13175                           offset_expr.X_op = O_absent;
13176                       }
13177                     else
13178                       {
13179                         imm_expr.X_op = O_constant;
13180                         if (!target_big_endian)
13181                           imm_expr.X_add_number = bfd_getl64 (temp);
13182                         else
13183                           imm_expr.X_add_number = bfd_getb64 (temp);
13184                       }
13185                   }
13186                 else
13187                   {
13188                     const char *newname;
13189                     segT new_seg;
13190
13191                     /* Switch to the right section.  */
13192                     seg = now_seg;
13193                     subseg = now_subseg;
13194                     switch (*args)
13195                       {
13196                       default: /* unused default case avoids warnings.  */
13197                       case 'L':
13198                         newname = RDATA_SECTION_NAME;
13199                         if (g_switch_value >= 8)
13200                           newname = ".lit8";
13201                         break;
13202                       case 'F':
13203                         newname = RDATA_SECTION_NAME;
13204                         break;
13205                       case 'l':
13206                         gas_assert (g_switch_value >= 4);
13207                         newname = ".lit4";
13208                         break;
13209                       }
13210                     new_seg = subseg_new (newname, (subsegT) 0);
13211                     bfd_set_section_flags (stdoutput, new_seg,
13212                                            (SEC_ALLOC
13213                                             | SEC_LOAD
13214                                             | SEC_READONLY
13215                                             | SEC_DATA));
13216                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
13217                     if (strncmp (TARGET_OS, "elf", 3) != 0)
13218                       record_alignment (new_seg, 4);
13219                     else
13220                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
13221                     if (seg == now_seg)
13222                       as_bad (_("Can't use floating point insn in this section"));
13223
13224                     /* Set the argument to the current address in the
13225                        section.  */
13226                     offset_expr.X_op = O_symbol;
13227                     offset_expr.X_add_symbol = symbol_temp_new_now ();
13228                     offset_expr.X_add_number = 0;
13229
13230                     /* Put the floating point number into the section.  */
13231                     p = frag_more ((int) length);
13232                     memcpy (p, temp, length);
13233
13234                     /* Switch back to the original section.  */
13235                     subseg_set (seg, subseg);
13236                   }
13237               }
13238               continue;
13239
13240             case 'i':           /* 16-bit unsigned immediate.  */
13241             case 'j':           /* 16-bit signed immediate.  */
13242               *offset_reloc = BFD_RELOC_LO16;
13243               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0)
13244                 {
13245                   int more;
13246                   offsetT minval, maxval;
13247
13248                   more = (insn + 1 < past
13249                           && strcmp (insn->name, insn[1].name) == 0);
13250
13251                   /* For compatibility with older assemblers, we accept
13252                      0x8000-0xffff as signed 16-bit numbers when only
13253                      signed numbers are allowed.  */
13254                   if (*args == 'i')
13255                     minval = 0, maxval = 0xffff;
13256                   else if (more)
13257                     minval = -0x8000, maxval = 0x7fff;
13258                   else
13259                     minval = -0x8000, maxval = 0xffff;
13260
13261                   if (offset_expr.X_op != O_constant
13262                       || offset_expr.X_add_number < minval
13263                       || offset_expr.X_add_number > maxval)
13264                     {
13265                       if (more)
13266                         break;
13267                       if (offset_expr.X_op == O_constant
13268                           || offset_expr.X_op == O_big)
13269                         as_bad (_("Expression out of range"));
13270                     }
13271                 }
13272               s = expr_end;
13273               continue;
13274
13275             case 'o':           /* 16-bit offset.  */
13276               offset_reloc[0] = BFD_RELOC_LO16;
13277               offset_reloc[1] = BFD_RELOC_UNUSED;
13278               offset_reloc[2] = BFD_RELOC_UNUSED;
13279
13280               /* Check whether there is only a single bracketed expression
13281                  left.  If so, it must be the base register and the
13282                  constant must be zero.  */
13283               if (*s == '(' && strchr (s + 1, '(') == 0)
13284                 {
13285                   offset_expr.X_op = O_constant;
13286                   offset_expr.X_add_number = 0;
13287                   continue;
13288                 }
13289
13290               /* If this value won't fit into a 16 bit offset, then go
13291                  find a macro that will generate the 32 bit offset
13292                  code pattern.  */
13293               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
13294                   && (offset_expr.X_op != O_constant
13295                       || offset_expr.X_add_number >= 0x8000
13296                       || offset_expr.X_add_number < -0x8000))
13297                 break;
13298
13299               s = expr_end;
13300               continue;
13301
13302             case 'p':           /* PC-relative offset.  */
13303               *offset_reloc = BFD_RELOC_16_PCREL_S2;
13304               my_getExpression (&offset_expr, s);
13305               s = expr_end;
13306               continue;
13307
13308             case 'u':           /* Upper 16 bits.  */
13309               *offset_reloc = BFD_RELOC_LO16;
13310               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
13311                   && offset_expr.X_op == O_constant
13312                   && (offset_expr.X_add_number < 0
13313                       || offset_expr.X_add_number >= 0x10000))
13314                 as_bad (_("lui expression (%lu) not in range 0..65535"),
13315                         (unsigned long) offset_expr.X_add_number);
13316               s = expr_end;
13317               continue;
13318
13319             case 'a':           /* 26-bit address.  */
13320             jump:
13321               *offset_reloc = BFD_RELOC_MIPS_JMP;
13322               my_getExpression (&offset_expr, s);
13323               s = expr_end;
13324               continue;
13325
13326             case 'N':           /* 3-bit branch condition code.  */
13327             case 'M':           /* 3-bit compare condition code.  */
13328               rtype = RTYPE_CCC;
13329               if (ip->insn_mo->pinfo & (FP_D | FP_S))
13330                 rtype |= RTYPE_FCC;
13331               if (!reg_lookup (&s, rtype, &regno))
13332                 break;
13333               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
13334                    || strcmp (str + strlen (str) - 5, "any2f") == 0
13335                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
13336                   && (regno & 1) != 0)
13337                 as_warn (_("Condition code register should be even for %s, "
13338                            "was %d"),
13339                          str, regno);
13340               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
13341                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
13342                   && (regno & 3) != 0)
13343                 as_warn (_("Condition code register should be 0 or 4 for %s, "
13344                            "was %d"),
13345                          str, regno);
13346               if (*args == 'N')
13347                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
13348               else
13349                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
13350               continue;
13351
13352             case 'H':
13353               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
13354                 s += 2;
13355               if (ISDIGIT (*s))
13356                 {
13357                   c = 0;
13358                   do
13359                     {
13360                       c *= 10;
13361                       c += *s - '0';
13362                       ++s;
13363                     }
13364                   while (ISDIGIT (*s));
13365                 }
13366               else
13367                 c = 8; /* Invalid sel value.  */
13368
13369               if (c > 7)
13370                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
13371               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
13372               continue;
13373
13374             case 'e':
13375               gas_assert (!mips_opts.micromips);
13376               /* Must be at least one digit.  */
13377               my_getExpression (&imm_expr, s);
13378               check_absolute_expr (ip, &imm_expr);
13379
13380               if ((unsigned long) imm_expr.X_add_number
13381                   > (unsigned long) OP_MASK_VECBYTE)
13382                 {
13383                   as_bad (_("bad byte vector index (%ld)"),
13384                            (long) imm_expr.X_add_number);
13385                   imm_expr.X_add_number = 0;
13386                 }
13387
13388               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
13389               imm_expr.X_op = O_absent;
13390               s = expr_end;
13391               continue;
13392
13393             case '%':
13394               gas_assert (!mips_opts.micromips);
13395               my_getExpression (&imm_expr, s);
13396               check_absolute_expr (ip, &imm_expr);
13397
13398               if ((unsigned long) imm_expr.X_add_number
13399                   > (unsigned long) OP_MASK_VECALIGN)
13400                 {
13401                   as_bad (_("bad byte vector index (%ld)"),
13402                            (long) imm_expr.X_add_number);
13403                   imm_expr.X_add_number = 0;
13404                 }
13405
13406               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
13407               imm_expr.X_op = O_absent;
13408               s = expr_end;
13409               continue;
13410
13411             case 'm':           /* Opcode extension character.  */
13412               gas_assert (mips_opts.micromips);
13413               c = *++args;
13414               switch (c)
13415                 {
13416                 case 'r':
13417                   if (strncmp (s, "$pc", 3) == 0)
13418                     {
13419                       s += 3;
13420                       continue;
13421                     }
13422                   break;
13423
13424                 case 'a':
13425                 case 'b':
13426                 case 'c':
13427                 case 'd':
13428                 case 'e':
13429                 case 'f':
13430                 case 'g':
13431                 case 'h':
13432                 case 'j':
13433                 case 'l':
13434                 case 'm':
13435                 case 'n':
13436                 case 'p':
13437                 case 'q':
13438                 case 's':
13439                 case 't':
13440                 case 'x':
13441                 case 'y':
13442                 case 'z':
13443                   s_reset = s;
13444                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
13445                   if (regno == AT && mips_opts.at)
13446                     {
13447                       if (mips_opts.at == ATREG)
13448                         as_warn (_("Used $at without \".set noat\""));
13449                       else
13450                         as_warn (_("Used $%u with \".set at=$%u\""),
13451                                  regno, mips_opts.at);
13452                     }
13453                   if (!ok)
13454                     {
13455                       if (c == 'c')
13456                         {
13457                           gas_assert (args[1] == ',');
13458                           regno = lastregno;
13459                           ++args;
13460                         }
13461                       else if (c == 't')
13462                         {
13463                           gas_assert (args[1] == ',');
13464                           ++args;
13465                           continue;                     /* Nothing to do.  */
13466                         }
13467                       else
13468                         break;
13469                     }
13470
13471                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
13472                     {
13473                       if (regno == lastregno)
13474                         {
13475                           insn_error
13476                             = _("Source and destination must be different");
13477                           continue;
13478                         }
13479                       if (regno == 31 && lastregno == 0xffffffff)
13480                         {
13481                           insn_error
13482                             = _("A destination register must be supplied");
13483                           continue;
13484                         }
13485                     }
13486
13487                   if (*s == ' ')
13488                     ++s;
13489                   if (args[1] != *s)
13490                     {
13491                       if (c == 'e')
13492                         {
13493                           gas_assert (args[1] == ',');
13494                           regno = lastregno;
13495                           s = s_reset;
13496                           ++args;
13497                         }
13498                       else if (c == 't')
13499                         {
13500                           gas_assert (args[1] == ',');
13501                           s = s_reset;
13502                           ++args;
13503                           continue;                     /* Nothing to do.  */
13504                         }
13505                     }
13506
13507                   /* Make sure regno is the same as lastregno.  */
13508                   if (c == 't' && regno != lastregno)
13509                     break;
13510
13511                   /* Make sure regno is the same as destregno.  */
13512                   if (c == 'x' && regno != destregno)
13513                     break;
13514
13515                   /* We need to save regno, before regno maps to the
13516                      microMIPS register encoding.  */
13517                   lastregno = regno;
13518
13519                   if (c == 'f')
13520                     destregno = regno;
13521
13522                   switch (c)
13523                     {
13524                       case 'a':
13525                         if (regno != GP)
13526                           regno = ILLEGAL_REG;
13527                         break;
13528
13529                       case 'b':
13530                         regno = mips32_to_micromips_reg_b_map[regno];
13531                         break;
13532
13533                       case 'c':
13534                         regno = mips32_to_micromips_reg_c_map[regno];
13535                         break;
13536
13537                       case 'd':
13538                         regno = mips32_to_micromips_reg_d_map[regno];
13539                         break;
13540
13541                       case 'e':
13542                         regno = mips32_to_micromips_reg_e_map[regno];
13543                         break;
13544
13545                       case 'f':
13546                         regno = mips32_to_micromips_reg_f_map[regno];
13547                         break;
13548
13549                       case 'g':
13550                         regno = mips32_to_micromips_reg_g_map[regno];
13551                         break;
13552
13553                       case 'h':
13554                         s += strspn (s, " \t");
13555                         if (*s != ',')
13556                           {
13557                             regno = ILLEGAL_REG;
13558                             break;
13559                           }
13560                         ++s;
13561                         s += strspn (s, " \t");
13562                         ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno2);
13563                         if (!ok)
13564                           {
13565                             regno = ILLEGAL_REG;
13566                             break;
13567                           }
13568                         if (regno2 == AT && mips_opts.at)
13569                           {
13570                             if (mips_opts.at == ATREG)
13571                               as_warn (_("Used $at without \".set noat\""));
13572                             else
13573                               as_warn (_("Used $%u with \".set at=$%u\""),
13574                                        regno2, mips_opts.at);
13575                           }
13576                         regno = (mips_lookup_reg_pair
13577                                  (regno, regno2,
13578                                   micromips_to_32_reg_h_map1,
13579                                   micromips_to_32_reg_h_map2, 8));
13580                         break;
13581
13582                       case 'l':
13583                         regno = mips32_to_micromips_reg_l_map[regno];
13584                         break;
13585
13586                       case 'm':
13587                         regno = mips32_to_micromips_reg_m_map[regno];
13588                         break;
13589
13590                       case 'n':
13591                         regno = mips32_to_micromips_reg_n_map[regno];
13592                         break;
13593
13594                       case 'q':
13595                         regno = mips32_to_micromips_reg_q_map[regno];
13596                         break;
13597
13598                       case 's':
13599                         if (regno != SP)
13600                           regno = ILLEGAL_REG;
13601                         break;
13602
13603                       case 'y':
13604                         if (regno != 31)
13605                           regno = ILLEGAL_REG;
13606                         break;
13607
13608                       case 'z':
13609                         if (regno != ZERO)
13610                           regno = ILLEGAL_REG;
13611                         break;
13612
13613                       case 'j': /* Do nothing.  */
13614                       case 'p':
13615                       case 't':
13616                       case 'x':
13617                         break;
13618
13619                       default:
13620                         abort ();
13621                     }
13622
13623                   if (regno == ILLEGAL_REG)
13624                     break;
13625
13626                   switch (c)
13627                     {
13628                       case 'b':
13629                         INSERT_OPERAND (1, MB, *ip, regno);
13630                         break;
13631
13632                       case 'c':
13633                         INSERT_OPERAND (1, MC, *ip, regno);
13634                         break;
13635
13636                       case 'd':
13637                         INSERT_OPERAND (1, MD, *ip, regno);
13638                         break;
13639
13640                       case 'e':
13641                         INSERT_OPERAND (1, ME, *ip, regno);
13642                         break;
13643
13644                       case 'f':
13645                         INSERT_OPERAND (1, MF, *ip, regno);
13646                         break;
13647
13648                       case 'g':
13649                         INSERT_OPERAND (1, MG, *ip, regno);
13650                         break;
13651
13652                       case 'h':
13653                         INSERT_OPERAND (1, MH, *ip, regno);
13654                         break;
13655
13656                       case 'j':
13657                         INSERT_OPERAND (1, MJ, *ip, regno);
13658                         break;
13659
13660                       case 'l':
13661                         INSERT_OPERAND (1, ML, *ip, regno);
13662                         break;
13663
13664                       case 'm':
13665                         INSERT_OPERAND (1, MM, *ip, regno);
13666                         break;
13667
13668                       case 'n':
13669                         INSERT_OPERAND (1, MN, *ip, regno);
13670                         break;
13671
13672                       case 'p':
13673                         INSERT_OPERAND (1, MP, *ip, regno);
13674                         break;
13675
13676                       case 'q':
13677                         INSERT_OPERAND (1, MQ, *ip, regno);
13678                         break;
13679
13680                       case 'a': /* Do nothing.  */
13681                       case 's': /* Do nothing.  */
13682                       case 't': /* Do nothing.  */
13683                       case 'x': /* Do nothing.  */
13684                       case 'y': /* Do nothing.  */
13685                       case 'z': /* Do nothing.  */
13686                         break;
13687
13688                       default:
13689                         abort ();
13690                     }
13691                   continue;
13692
13693                 case 'A':
13694                   {
13695                     bfd_reloc_code_real_type r[3];
13696                     expressionS ep;
13697                     int imm;
13698
13699                     /* Check whether there is only a single bracketed
13700                        expression left.  If so, it must be the base register
13701                        and the constant must be zero.  */
13702                     if (*s == '(' && strchr (s + 1, '(') == 0)
13703                       {
13704                         INSERT_OPERAND (1, IMMA, *ip, 0);
13705                         continue;
13706                       }
13707
13708                     if (my_getSmallExpression (&ep, r, s) > 0
13709                         || !expr_const_in_range (&ep, -64, 64, 2))
13710                       break;
13711
13712                     imm = ep.X_add_number >> 2;
13713                     INSERT_OPERAND (1, IMMA, *ip, imm);
13714                   }
13715                   s = expr_end;
13716                   continue;
13717
13718                 case 'B':
13719                   {
13720                     bfd_reloc_code_real_type r[3];
13721                     expressionS ep;
13722                     int imm;
13723
13724                     if (my_getSmallExpression (&ep, r, s) > 0
13725                         || ep.X_op != O_constant)
13726                       break;
13727
13728                     for (imm = 0; imm < 8; imm++)
13729                       if (micromips_imm_b_map[imm] == ep.X_add_number)
13730                         break;
13731                     if (imm >= 8)
13732                       break;
13733
13734                     INSERT_OPERAND (1, IMMB, *ip, imm);
13735                   }
13736                   s = expr_end;
13737                   continue;
13738
13739                 case 'C':
13740                   {
13741                     bfd_reloc_code_real_type r[3];
13742                     expressionS ep;
13743                     int imm;
13744
13745                     if (my_getSmallExpression (&ep, r, s) > 0
13746                         || ep.X_op != O_constant)
13747                       break;
13748
13749                     for (imm = 0; imm < 16; imm++)
13750                       if (micromips_imm_c_map[imm] == ep.X_add_number)
13751                         break;
13752                     if (imm >= 16)
13753                       break;
13754
13755                     INSERT_OPERAND (1, IMMC, *ip, imm);
13756                   }
13757                   s = expr_end;
13758                   continue;
13759
13760                 case 'D':       /* pc relative offset */
13761                 case 'E':       /* pc relative offset */
13762                   my_getExpression (&offset_expr, s);
13763                   if (offset_expr.X_op == O_register)
13764                     break;
13765
13766                   if (!forced_insn_length)
13767                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13768                   else if (c == 'D')
13769                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
13770                   else
13771                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
13772                   s = expr_end;
13773                   continue;
13774
13775                 case 'F':
13776                   {
13777                     bfd_reloc_code_real_type r[3];
13778                     expressionS ep;
13779                     int imm;
13780
13781                     if (my_getSmallExpression (&ep, r, s) > 0
13782                         || !expr_const_in_range (&ep, 0, 16, 0))
13783                       break;
13784
13785                     imm = ep.X_add_number;
13786                     INSERT_OPERAND (1, IMMF, *ip, imm);
13787                   }
13788                   s = expr_end;
13789                   continue;
13790
13791                 case 'G':
13792                   {
13793                     bfd_reloc_code_real_type r[3];
13794                     expressionS ep;
13795                     int imm;
13796
13797                     /* Check whether there is only a single bracketed
13798                        expression left.  If so, it must be the base register
13799                        and the constant must be zero.  */
13800                     if (*s == '(' && strchr (s + 1, '(') == 0)
13801                       {
13802                         INSERT_OPERAND (1, IMMG, *ip, 0);
13803                         continue;
13804                       }
13805
13806                     if (my_getSmallExpression (&ep, r, s) > 0
13807                         || !expr_const_in_range (&ep, -1, 15, 0))
13808                       break;
13809
13810                     imm = ep.X_add_number & 15;
13811                     INSERT_OPERAND (1, IMMG, *ip, imm);
13812                   }
13813                   s = expr_end;
13814                   continue;
13815
13816                 case 'H':
13817                   {
13818                     bfd_reloc_code_real_type r[3];
13819                     expressionS ep;
13820                     int imm;
13821
13822                     /* Check whether there is only a single bracketed
13823                        expression left.  If so, it must be the base register
13824                        and the constant must be zero.  */
13825                     if (*s == '(' && strchr (s + 1, '(') == 0)
13826                       {
13827                         INSERT_OPERAND (1, IMMH, *ip, 0);
13828                         continue;
13829                       }
13830
13831                     if (my_getSmallExpression (&ep, r, s) > 0
13832                         || !expr_const_in_range (&ep, 0, 16, 1))
13833                       break;
13834
13835                     imm = ep.X_add_number >> 1;
13836                     INSERT_OPERAND (1, IMMH, *ip, imm);
13837                   }
13838                   s = expr_end;
13839                   continue;
13840
13841                 case 'I':
13842                   {
13843                     bfd_reloc_code_real_type r[3];
13844                     expressionS ep;
13845                     int imm;
13846
13847                     if (my_getSmallExpression (&ep, r, s) > 0
13848                         || !expr_const_in_range (&ep, -1, 127, 0))
13849                       break;
13850
13851                     imm = ep.X_add_number & 127;
13852                     INSERT_OPERAND (1, IMMI, *ip, imm);
13853                   }
13854                   s = expr_end;
13855                   continue;
13856
13857                 case 'J':
13858                   {
13859                     bfd_reloc_code_real_type r[3];
13860                     expressionS ep;
13861                     int imm;
13862
13863                     /* Check whether there is only a single bracketed
13864                        expression left.  If so, it must be the base register
13865                        and the constant must be zero.  */
13866                     if (*s == '(' && strchr (s + 1, '(') == 0)
13867                       {
13868                         INSERT_OPERAND (1, IMMJ, *ip, 0);
13869                         continue;
13870                       }
13871
13872                     if (my_getSmallExpression (&ep, r, s) > 0
13873                         || !expr_const_in_range (&ep, 0, 16, 2))
13874                       break;
13875
13876                     imm = ep.X_add_number >> 2;
13877                     INSERT_OPERAND (1, IMMJ, *ip, imm);
13878                   }
13879                   s = expr_end;
13880                   continue;
13881
13882                 case 'L':
13883                   {
13884                     bfd_reloc_code_real_type r[3];
13885                     expressionS ep;
13886                     int imm;
13887
13888                     /* Check whether there is only a single bracketed
13889                        expression left.  If so, it must be the base register
13890                        and the constant must be zero.  */
13891                     if (*s == '(' && strchr (s + 1, '(') == 0)
13892                       {
13893                         INSERT_OPERAND (1, IMML, *ip, 0);
13894                         continue;
13895                       }
13896
13897                     if (my_getSmallExpression (&ep, r, s) > 0
13898                         || !expr_const_in_range (&ep, 0, 16, 0))
13899                       break;
13900
13901                     imm = ep.X_add_number;
13902                     INSERT_OPERAND (1, IMML, *ip, imm);
13903                   }
13904                   s = expr_end;
13905                   continue;
13906
13907                 case 'M':
13908                   {
13909                     bfd_reloc_code_real_type r[3];
13910                     expressionS ep;
13911                     int imm;
13912
13913                     if (my_getSmallExpression (&ep, r, s) > 0
13914                         || !expr_const_in_range (&ep, 1, 9, 0))
13915                       break;
13916
13917                     imm = ep.X_add_number & 7;
13918                     INSERT_OPERAND (1, IMMM, *ip, imm);
13919                   }
13920                   s = expr_end;
13921                   continue;
13922
13923                 case 'N':       /* Register list for lwm and swm.  */
13924                   {
13925                     /* A comma-separated list of registers and/or
13926                        dash-separated contiguous ranges including
13927                        both ra and a set of one or more registers
13928                        starting at s0 up to s3 which have to be
13929                        consecutive, e.g.:
13930
13931                        s0, ra
13932                        s0, s1, ra, s2, s3
13933                        s0-s2, ra
13934
13935                        and any permutations of these.  */
13936                     unsigned int reglist;
13937                     int imm;
13938
13939                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13940                       break;
13941
13942                     if ((reglist & 0xfff1ffff) != 0x80010000)
13943                       break;
13944
13945                     reglist = (reglist >> 17) & 7;
13946                     reglist += 1;
13947                     if ((reglist & -reglist) != reglist)
13948                       break;
13949
13950                     imm = ffs (reglist) - 1;
13951                     INSERT_OPERAND (1, IMMN, *ip, imm);
13952                   }
13953                   continue;
13954
13955                 case 'O':       /* sdbbp 4-bit code.  */
13956                   {
13957                     bfd_reloc_code_real_type r[3];
13958                     expressionS ep;
13959                     int imm;
13960
13961                     if (my_getSmallExpression (&ep, r, s) > 0
13962                         || !expr_const_in_range (&ep, 0, 16, 0))
13963                       break;
13964
13965                     imm = ep.X_add_number;
13966                     INSERT_OPERAND (1, IMMO, *ip, imm);
13967                   }
13968                   s = expr_end;
13969                   continue;
13970
13971                 case 'P':
13972                   {
13973                     bfd_reloc_code_real_type r[3];
13974                     expressionS ep;
13975                     int imm;
13976
13977                     if (my_getSmallExpression (&ep, r, s) > 0
13978                         || !expr_const_in_range (&ep, 0, 32, 2))
13979                       break;
13980
13981                     imm = ep.X_add_number >> 2;
13982                     INSERT_OPERAND (1, IMMP, *ip, imm);
13983                   }
13984                   s = expr_end;
13985                   continue;
13986
13987                 case 'Q':
13988                   {
13989                     bfd_reloc_code_real_type r[3];
13990                     expressionS ep;
13991                     int imm;
13992
13993                     if (my_getSmallExpression (&ep, r, s) > 0
13994                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
13995                       break;
13996
13997                     imm = ep.X_add_number >> 2;
13998                     INSERT_OPERAND (1, IMMQ, *ip, imm);
13999                   }
14000                   s = expr_end;
14001                   continue;
14002
14003                 case 'U':
14004                   {
14005                     bfd_reloc_code_real_type r[3];
14006                     expressionS ep;
14007                     int imm;
14008
14009                     /* Check whether there is only a single bracketed
14010                        expression left.  If so, it must be the base register
14011                        and the constant must be zero.  */
14012                     if (*s == '(' && strchr (s + 1, '(') == 0)
14013                       {
14014                         INSERT_OPERAND (1, IMMU, *ip, 0);
14015                         continue;
14016                       }
14017
14018                     if (my_getSmallExpression (&ep, r, s) > 0
14019                         || !expr_const_in_range (&ep, 0, 32, 2))
14020                       break;
14021
14022                     imm = ep.X_add_number >> 2;
14023                     INSERT_OPERAND (1, IMMU, *ip, imm);
14024                   }
14025                   s = expr_end;
14026                   continue;
14027
14028                 case 'W':
14029                   {
14030                     bfd_reloc_code_real_type r[3];
14031                     expressionS ep;
14032                     int imm;
14033
14034                     if (my_getSmallExpression (&ep, r, s) > 0
14035                         || !expr_const_in_range (&ep, 0, 64, 2))
14036                       break;
14037
14038                     imm = ep.X_add_number >> 2;
14039                     INSERT_OPERAND (1, IMMW, *ip, imm);
14040                   }
14041                   s = expr_end;
14042                   continue;
14043
14044                 case 'X':
14045                   {
14046                     bfd_reloc_code_real_type r[3];
14047                     expressionS ep;
14048                     int imm;
14049
14050                     if (my_getSmallExpression (&ep, r, s) > 0
14051                         || !expr_const_in_range (&ep, -8, 8, 0))
14052                       break;
14053
14054                     imm = ep.X_add_number;
14055                     INSERT_OPERAND (1, IMMX, *ip, imm);
14056                   }
14057                   s = expr_end;
14058                   continue;
14059
14060                 case 'Y':
14061                   {
14062                     bfd_reloc_code_real_type r[3];
14063                     expressionS ep;
14064                     int imm;
14065
14066                     if (my_getSmallExpression (&ep, r, s) > 0
14067                         || expr_const_in_range (&ep, -2, 2, 2)
14068                         || !expr_const_in_range (&ep, -258, 258, 2))
14069                       break;
14070
14071                     imm = ep.X_add_number >> 2;
14072                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
14073                     INSERT_OPERAND (1, IMMY, *ip, imm);
14074                   }
14075                   s = expr_end;
14076                   continue;
14077
14078                 case 'Z':
14079                   {
14080                     bfd_reloc_code_real_type r[3];
14081                     expressionS ep;
14082
14083                     if (my_getSmallExpression (&ep, r, s) > 0
14084                         || !expr_const_in_range (&ep, 0, 1, 0))
14085                       break;
14086                   }
14087                   s = expr_end;
14088                   continue;
14089
14090                 default:
14091                   as_bad (_("Internal error: bad microMIPS opcode "
14092                             "(unknown extension operand type `m%c'): %s %s"),
14093                           *args, insn->name, insn->args);
14094                   /* Further processing is fruitless.  */
14095                   return;
14096                 }
14097               break;
14098
14099             case 'n':           /* Register list for 32-bit lwm and swm.  */
14100               gas_assert (mips_opts.micromips);
14101               {
14102                 /* A comma-separated list of registers and/or
14103                    dash-separated contiguous ranges including
14104                    at least one of ra and a set of one or more
14105                    registers starting at s0 up to s7 and then
14106                    s8 which have to be consecutive, e.g.:
14107
14108                    ra
14109                    s0
14110                    ra, s0, s1, s2
14111                    s0-s8
14112                    s0-s5, ra
14113
14114                    and any permutations of these.  */
14115                 unsigned int reglist;
14116                 int imm;
14117                 int ra;
14118
14119                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
14120                   break;
14121
14122                 if ((reglist & 0x3f00ffff) != 0)
14123                   break;
14124
14125                 ra = (reglist >> 27) & 0x10;
14126                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
14127                 reglist += 1;
14128                 if ((reglist & -reglist) != reglist)
14129                   break;
14130
14131                 imm = (ffs (reglist) - 1) | ra;
14132                 INSERT_OPERAND (1, RT, *ip, imm);
14133                 imm_expr.X_op = O_absent;
14134               }
14135               continue;
14136
14137             case '|':           /* 4-bit trap code.  */
14138               gas_assert (mips_opts.micromips);
14139               my_getExpression (&imm_expr, s);
14140               check_absolute_expr (ip, &imm_expr);
14141               if ((unsigned long) imm_expr.X_add_number
14142                   > MICROMIPSOP_MASK_TRAP)
14143                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
14144                         (unsigned long) imm_expr.X_add_number,
14145                         ip->insn_mo->name);
14146               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
14147               imm_expr.X_op = O_absent;
14148               s = expr_end;
14149               continue;
14150
14151             default:
14152               as_bad (_("Bad char = '%c'\n"), *args);
14153               abort ();
14154             }
14155           break;
14156         }
14157       /* Args don't match.  */
14158       s = argsStart;
14159       insn_error = _("Illegal operands");
14160       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
14161         {
14162           ++insn;
14163           continue;
14164         }
14165       else if (wrong_delay_slot_insns && need_delay_slot_ok)
14166         {
14167           gas_assert (firstinsn);
14168           need_delay_slot_ok = FALSE;
14169           past = insn + 1;
14170           insn = firstinsn;
14171           continue;
14172         }
14173       return;
14174     }
14175 }
14176
14177 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
14178
14179 /* As for mips_ip, but used when assembling MIPS16 code.
14180    Also set forced_insn_length to the resulting instruction size in
14181    bytes if the user explicitly requested a small or extended instruction.  */
14182
14183 static void
14184 mips16_ip (char *str, struct mips_cl_insn *ip)
14185 {
14186   char *s;
14187   const char *args;
14188   struct mips_opcode *insn;
14189   char *argsstart;
14190   unsigned int regno;
14191   unsigned int lastregno = 0;
14192   char *s_reset;
14193   size_t i;
14194
14195   insn_error = NULL;
14196
14197   forced_insn_length = 0;
14198
14199   for (s = str; ISLOWER (*s); ++s)
14200     ;
14201   switch (*s)
14202     {
14203     case '\0':
14204       break;
14205
14206     case ' ':
14207       *s++ = '\0';
14208       break;
14209
14210     case '.':
14211       if (s[1] == 't' && s[2] == ' ')
14212         {
14213           *s = '\0';
14214           forced_insn_length = 2;
14215           s += 3;
14216           break;
14217         }
14218       else if (s[1] == 'e' && s[2] == ' ')
14219         {
14220           *s = '\0';
14221           forced_insn_length = 4;
14222           s += 3;
14223           break;
14224         }
14225       /* Fall through.  */
14226     default:
14227       insn_error = _("unknown opcode");
14228       return;
14229     }
14230
14231   if (mips_opts.noautoextend && !forced_insn_length)
14232     forced_insn_length = 2;
14233
14234   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
14235     {
14236       insn_error = _("unrecognized opcode");
14237       return;
14238     }
14239
14240   argsstart = s;
14241   for (;;)
14242     {
14243       bfd_boolean ok;
14244       char relax_char;
14245
14246       gas_assert (strcmp (insn->name, str) == 0);
14247
14248       ok = is_opcode_valid_16 (insn);
14249       if (! ok)
14250         {
14251           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
14252               && strcmp (insn->name, insn[1].name) == 0)
14253             {
14254               ++insn;
14255               continue;
14256             }
14257           else
14258             {
14259               if (!insn_error)
14260                 {
14261                   static char buf[100];
14262                   sprintf (buf,
14263                            _("Opcode not supported on this processor: %s (%s)"),
14264                            mips_cpu_info_from_arch (mips_opts.arch)->name,
14265                            mips_cpu_info_from_isa (mips_opts.isa)->name);
14266                   insn_error = buf;
14267                 }
14268               return;
14269             }
14270         }
14271
14272       create_insn (ip, insn);
14273       imm_expr.X_op = O_absent;
14274       imm2_expr.X_op = O_absent;
14275       offset_expr.X_op = O_absent;
14276       offset_reloc[0] = BFD_RELOC_UNUSED;
14277       offset_reloc[1] = BFD_RELOC_UNUSED;
14278       offset_reloc[2] = BFD_RELOC_UNUSED;
14279       relax_char = 0;
14280       for (args = insn->args; 1; ++args)
14281         {
14282           int c;
14283
14284           if (*s == ' ')
14285             ++s;
14286
14287           /* In this switch statement we call break if we did not find
14288              a match, continue if we did find a match, or return if we
14289              are done.  */
14290
14291           c = *args;
14292           switch (c)
14293             {
14294             case '\0':
14295               if (*s == '\0')
14296                 {
14297                   offsetT value;
14298
14299                   /* Stuff the immediate value in now, if we can.  */
14300                   if (insn->pinfo == INSN_MACRO)
14301                     {
14302                       gas_assert (relax_char == 0);
14303                       gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
14304                     }
14305                   else if (relax_char
14306                            && offset_expr.X_op == O_constant
14307                            && calculate_reloc (*offset_reloc,
14308                                                offset_expr.X_add_number,
14309                                                &value))
14310                     {
14311                       mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
14312                                     forced_insn_length, &ip->insn_opcode);
14313                       offset_expr.X_op = O_absent;
14314                       *offset_reloc = BFD_RELOC_UNUSED;
14315                     }
14316                   else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
14317                     {
14318                       if (forced_insn_length == 2)
14319                         as_bad (_("invalid unextended operand value"));
14320                       forced_insn_length = 4;
14321                       ip->insn_opcode |= MIPS16_EXTEND;
14322                     }
14323                   else if (relax_char)
14324                     *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
14325
14326                   return;
14327                 }
14328               break;
14329
14330             case ',':
14331               if (*s++ == c)
14332                 continue;
14333               s--;
14334               switch (*++args)
14335                 {
14336                 case 'v':
14337                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14338                   continue;
14339                 case 'w':
14340                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14341                   continue;
14342                 }
14343               break;
14344
14345             case '(':
14346             case ')':
14347               if (*s++ == c)
14348                 continue;
14349               break;
14350
14351             case 'v':
14352             case 'w':
14353               if (s[0] != '$')
14354                 {
14355                   if (c == 'v')
14356                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14357                   else
14358                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14359                   ++args;
14360                   continue;
14361                 }
14362               /* Fall through.  */
14363             case 'x':
14364             case 'y':
14365             case 'z':
14366             case 'Z':
14367             case '0':
14368             case 'S':
14369             case 'R':
14370             case 'X':
14371             case 'Y':
14372               s_reset = s;
14373               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
14374                 {
14375                   if (c == 'v' || c == 'w')
14376                     {
14377                       if (c == 'v')
14378                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
14379                       else
14380                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
14381                       ++args;
14382                       continue;
14383                     }
14384                   break;
14385                 }
14386
14387               if (*s == ' ')
14388                 ++s;
14389               if (args[1] != *s)
14390                 {
14391                   if (c == 'v' || c == 'w')
14392                     {
14393                       regno = mips16_to_32_reg_map[lastregno];
14394                       s = s_reset;
14395                       ++args;
14396                     }
14397                 }
14398
14399               switch (c)
14400                 {
14401                 case 'x':
14402                 case 'y':
14403                 case 'z':
14404                 case 'v':
14405                 case 'w':
14406                 case 'Z':
14407                   regno = mips32_to_16_reg_map[regno];
14408                   break;
14409
14410                 case '0':
14411                   if (regno != 0)
14412                     regno = ILLEGAL_REG;
14413                   break;
14414
14415                 case 'S':
14416                   if (regno != SP)
14417                     regno = ILLEGAL_REG;
14418                   break;
14419
14420                 case 'R':
14421                   if (regno != RA)
14422                     regno = ILLEGAL_REG;
14423                   break;
14424
14425                 case 'X':
14426                 case 'Y':
14427                   if (regno == AT && mips_opts.at)
14428                     {
14429                       if (mips_opts.at == ATREG)
14430                         as_warn (_("used $at without \".set noat\""));
14431                       else
14432                         as_warn (_("used $%u with \".set at=$%u\""),
14433                                  regno, mips_opts.at);
14434                     }
14435                   break;
14436
14437                 default:
14438                   abort ();
14439                 }
14440
14441               if (regno == ILLEGAL_REG)
14442                 break;
14443
14444               switch (c)
14445                 {
14446                 case 'x':
14447                 case 'v':
14448                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
14449                   break;
14450                 case 'y':
14451                 case 'w':
14452                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
14453                   break;
14454                 case 'z':
14455                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
14456                   break;
14457                 case 'Z':
14458                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
14459                 case '0':
14460                 case 'S':
14461                 case 'R':
14462                   break;
14463                 case 'X':
14464                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
14465                   break;
14466                 case 'Y':
14467                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
14468                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
14469                   break;
14470                 default:
14471                   abort ();
14472                 }
14473
14474               lastregno = regno;
14475               continue;
14476
14477             case 'P':
14478               if (strncmp (s, "$pc", 3) == 0)
14479                 {
14480                   s += 3;
14481                   continue;
14482                 }
14483               break;
14484
14485             case '5':
14486             case 'H':
14487             case 'W':
14488             case 'D':
14489             case 'j':
14490             case 'V':
14491             case 'C':
14492             case 'U':
14493             case 'k':
14494             case 'K':
14495               i = my_getSmallExpression (&offset_expr, offset_reloc, s);
14496               if (i > 0)
14497                 {
14498                   relax_char = c;
14499                   s = expr_end;
14500                   continue;
14501                 }
14502               *offset_reloc = BFD_RELOC_UNUSED;
14503               /* Fall through.  */
14504             case '<':
14505             case '>':
14506             case '[':
14507             case ']':
14508             case '4':
14509             case '8':
14510               my_getExpression (&offset_expr, s);
14511               if (offset_expr.X_op == O_register)
14512                 {
14513                   /* What we thought was an expression turned out to
14514                      be a register.  */
14515
14516                   if (s[0] == '(' && args[1] == '(')
14517                     {
14518                       /* It looks like the expression was omitted
14519                          before a register indirection, which means
14520                          that the expression is implicitly zero.  We
14521                          still set up offset_expr, so that we handle
14522                          explicit extensions correctly.  */
14523                       offset_expr.X_op = O_constant;
14524                       offset_expr.X_add_number = 0;
14525                       relax_char = c;
14526                       continue;
14527                     }
14528
14529                   break;
14530                 }
14531
14532               /* We need to relax this instruction.  */
14533               relax_char = c;
14534               s = expr_end;
14535               continue;
14536
14537             case 'p':
14538             case 'q':
14539             case 'A':
14540             case 'B':
14541             case 'E':
14542               /* We use offset_reloc rather than imm_reloc for the PC
14543                  relative operands.  This lets macros with both
14544                  immediate and address operands work correctly.  */
14545               my_getExpression (&offset_expr, s);
14546
14547               if (offset_expr.X_op == O_register)
14548                 break;
14549
14550               /* We need to relax this instruction.  */
14551               relax_char = c;
14552               s = expr_end;
14553               continue;
14554
14555             case '6':           /* break code */
14556               my_getExpression (&imm_expr, s);
14557               check_absolute_expr (ip, &imm_expr);
14558               if ((unsigned long) imm_expr.X_add_number > 63)
14559                 as_warn (_("Invalid value for `%s' (%lu)"),
14560                          ip->insn_mo->name,
14561                          (unsigned long) imm_expr.X_add_number);
14562               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
14563               imm_expr.X_op = O_absent;
14564               s = expr_end;
14565               continue;
14566
14567             case 'I':
14568               my_getExpression (&imm_expr, s);
14569               if (imm_expr.X_op != O_big
14570                   && imm_expr.X_op != O_constant)
14571                 insn_error = _("absolute expression required");
14572               if (HAVE_32BIT_GPRS)
14573                 normalize_constant_expr (&imm_expr);
14574               s = expr_end;
14575               continue;
14576
14577             case 'a':           /* 26 bit address */
14578             case 'i':
14579               my_getExpression (&offset_expr, s);
14580               s = expr_end;
14581               *offset_reloc = BFD_RELOC_MIPS16_JMP;
14582               ip->insn_opcode <<= 16;
14583               continue;
14584
14585             case 'l':           /* register list for entry macro */
14586             case 'L':           /* register list for exit macro */
14587               {
14588                 int mask;
14589
14590                 if (c == 'l')
14591                   mask = 0;
14592                 else
14593                   mask = 7 << 3;
14594                 while (*s != '\0')
14595                   {
14596                     unsigned int freg, reg1, reg2;
14597
14598                     while (*s == ' ' || *s == ',')
14599                       ++s;
14600                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
14601                       freg = 0;
14602                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
14603                       freg = 1;
14604                     else
14605                       {
14606                         as_bad (_("can't parse register list"));
14607                         break;
14608                       }
14609                     if (*s == ' ')
14610                       ++s;
14611                     if (*s != '-')
14612                       reg2 = reg1;
14613                     else
14614                       {
14615                         ++s;
14616                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
14617                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
14618                           {
14619                             as_bad (_("invalid register list"));
14620                             break;
14621                           }
14622                       }
14623                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
14624                       {
14625                         mask &= ~ (7 << 3);
14626                         mask |= 5 << 3;
14627                       }
14628                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
14629                       {
14630                         mask &= ~ (7 << 3);
14631                         mask |= 6 << 3;
14632                       }
14633                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
14634                       mask |= (reg2 - 3) << 3;
14635                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
14636                       mask |= (reg2 - 15) << 1;
14637                     else if (reg1 == RA && reg2 == RA)
14638                       mask |= 1;
14639                     else
14640                       {
14641                         as_bad (_("invalid register list"));
14642                         break;
14643                       }
14644                   }
14645                 /* The mask is filled in in the opcode table for the
14646                    benefit of the disassembler.  We remove it before
14647                    applying the actual mask.  */
14648                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
14649                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
14650               }
14651             continue;
14652
14653             case 'm':           /* Register list for save insn.  */
14654             case 'M':           /* Register list for restore insn.  */
14655               {
14656                 int opcode = ip->insn_opcode;
14657                 int framesz = 0, seen_framesz = 0;
14658                 int nargs = 0, statics = 0, sregs = 0;
14659
14660                 while (*s != '\0')
14661                   {
14662                     unsigned int reg1, reg2;
14663
14664                     SKIP_SPACE_TABS (s);
14665                     while (*s == ',')
14666                       ++s;
14667                     SKIP_SPACE_TABS (s);
14668
14669                     my_getExpression (&imm_expr, s);
14670                     if (imm_expr.X_op == O_constant)
14671                       {
14672                         /* Handle the frame size.  */
14673                         if (seen_framesz)
14674                           {
14675                             as_bad (_("more than one frame size in list"));
14676                             break;
14677                           }
14678                         seen_framesz = 1;
14679                         framesz = imm_expr.X_add_number;
14680                         imm_expr.X_op = O_absent;
14681                         s = expr_end;
14682                         continue;
14683                       }
14684
14685                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
14686                       {
14687                         as_bad (_("can't parse register list"));
14688                         break;
14689                       }
14690
14691                     while (*s == ' ')
14692                       ++s;
14693
14694                     if (*s != '-')
14695                       reg2 = reg1;
14696                     else
14697                       {
14698                         ++s;
14699                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
14700                             || reg2 < reg1)
14701                           {
14702                             as_bad (_("can't parse register list"));
14703                             break;
14704                           }
14705                       }
14706
14707                     while (reg1 <= reg2)
14708                       {
14709                         if (reg1 >= 4 && reg1 <= 7)
14710                           {
14711                             if (!seen_framesz)
14712                                 /* args $a0-$a3 */
14713                                 nargs |= 1 << (reg1 - 4);
14714                             else
14715                                 /* statics $a0-$a3 */
14716                                 statics |= 1 << (reg1 - 4);
14717                           }
14718                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
14719                           {
14720                             /* $s0-$s8 */
14721                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
14722                           }
14723                         else if (reg1 == 31)
14724                           {
14725                             /* Add $ra to insn.  */
14726                             opcode |= 0x40;
14727                           }
14728                         else
14729                           {
14730                             as_bad (_("unexpected register in list"));
14731                             break;
14732                           }
14733                         if (++reg1 == 24)
14734                           reg1 = 30;
14735                       }
14736                   }
14737
14738                 /* Encode args/statics combination.  */
14739                 if (nargs & statics)
14740                   as_bad (_("arg/static registers overlap"));
14741                 else if (nargs == 0xf)
14742                   /* All $a0-$a3 are args.  */
14743                   opcode |= MIPS16_ALL_ARGS << 16;
14744                 else if (statics == 0xf)
14745                   /* All $a0-$a3 are statics.  */
14746                   opcode |= MIPS16_ALL_STATICS << 16;
14747                 else 
14748                   {
14749                     int narg = 0, nstat = 0;
14750
14751                     /* Count arg registers.  */
14752                     while (nargs & 0x1)
14753                       {
14754                         nargs >>= 1;
14755                         narg++;
14756                       }
14757                     if (nargs != 0)
14758                       as_bad (_("invalid arg register list"));
14759
14760                     /* Count static registers.  */
14761                     while (statics & 0x8)
14762                       {
14763                         statics = (statics << 1) & 0xf;
14764                         nstat++;
14765                       }
14766                     if (statics != 0) 
14767                       as_bad (_("invalid static register list"));
14768
14769                     /* Encode args/statics.  */
14770                     opcode |= ((narg << 2) | nstat) << 16;
14771                   }
14772
14773                 /* Encode $s0/$s1.  */
14774                 if (sregs & (1 << 0))           /* $s0 */
14775                   opcode |= 0x20;
14776                 if (sregs & (1 << 1))           /* $s1 */
14777                   opcode |= 0x10;
14778                 sregs >>= 2;
14779
14780                 if (sregs != 0)
14781                   {
14782                     /* Count regs $s2-$s8.  */
14783                     int nsreg = 0;
14784                     while (sregs & 1)
14785                       {
14786                         sregs >>= 1;
14787                         nsreg++;
14788                       }
14789                     if (sregs != 0)
14790                       as_bad (_("invalid static register list"));
14791                     /* Encode $s2-$s8. */
14792                     opcode |= nsreg << 24;
14793                   }
14794
14795                 /* Encode frame size.  */
14796                 if (!seen_framesz)
14797                   as_bad (_("missing frame size"));
14798                 else if ((framesz & 7) != 0 || framesz < 0
14799                          || framesz > 0xff * 8)
14800                   as_bad (_("invalid frame size"));
14801                 else if (framesz != 128 || (opcode >> 16) != 0)
14802                   {
14803                     framesz /= 8;
14804                     opcode |= (((framesz & 0xf0) << 16)
14805                              | (framesz & 0x0f));
14806                   }
14807
14808                 /* Finally build the instruction.  */
14809                 if ((opcode >> 16) != 0 || framesz == 0)
14810                   opcode |= MIPS16_EXTEND;
14811                 ip->insn_opcode = opcode;
14812               }
14813             continue;
14814
14815             case 'e':           /* extend code */
14816               my_getExpression (&imm_expr, s);
14817               check_absolute_expr (ip, &imm_expr);
14818               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
14819                 {
14820                   as_warn (_("Invalid value for `%s' (%lu)"),
14821                            ip->insn_mo->name,
14822                            (unsigned long) imm_expr.X_add_number);
14823                   imm_expr.X_add_number &= 0x7ff;
14824                 }
14825               ip->insn_opcode |= imm_expr.X_add_number;
14826               imm_expr.X_op = O_absent;
14827               s = expr_end;
14828               continue;
14829
14830             default:
14831               abort ();
14832             }
14833           break;
14834         }
14835
14836       /* Args don't match.  */
14837       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
14838           strcmp (insn->name, insn[1].name) == 0)
14839         {
14840           ++insn;
14841           s = argsstart;
14842           continue;
14843         }
14844
14845       insn_error = _("illegal operands");
14846
14847       return;
14848     }
14849 }
14850
14851 /* This structure holds information we know about a mips16 immediate
14852    argument type.  */
14853
14854 struct mips16_immed_operand
14855 {
14856   /* The type code used in the argument string in the opcode table.  */
14857   int type;
14858   /* The number of bits in the short form of the opcode.  */
14859   int nbits;
14860   /* The number of bits in the extended form of the opcode.  */
14861   int extbits;
14862   /* The amount by which the short form is shifted when it is used;
14863      for example, the sw instruction has a shift count of 2.  */
14864   int shift;
14865   /* The amount by which the short form is shifted when it is stored
14866      into the instruction code.  */
14867   int op_shift;
14868   /* Non-zero if the short form is unsigned.  */
14869   int unsp;
14870   /* Non-zero if the extended form is unsigned.  */
14871   int extu;
14872   /* Non-zero if the value is PC relative.  */
14873   int pcrel;
14874 };
14875
14876 /* The mips16 immediate operand types.  */
14877
14878 static const struct mips16_immed_operand mips16_immed_operands[] =
14879 {
14880   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14881   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14882   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14883   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14884   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
14885   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
14886   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
14887   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
14888   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
14889   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
14890   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
14891   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
14892   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
14893   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
14894   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
14895   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
14896   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14897   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14898   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
14899   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
14900   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
14901 };
14902
14903 #define MIPS16_NUM_IMMED \
14904   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
14905
14906 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14907    NBITS is the number of significant bits in VAL.  */
14908
14909 static unsigned long
14910 mips16_immed_extend (offsetT val, unsigned int nbits)
14911 {
14912   int extval;
14913   if (nbits == 16)
14914     {
14915       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14916       val &= 0x1f;
14917     }
14918   else if (nbits == 15)
14919     {
14920       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14921       val &= 0xf;
14922     }
14923   else
14924     {
14925       extval = ((val & 0x1f) << 6) | (val & 0x20);
14926       val = 0;
14927     }
14928   return (extval << 16) | val;
14929 }
14930
14931 /* Install immediate value VAL into MIPS16 instruction *INSN,
14932    extending it if necessary.  The instruction in *INSN may
14933    already be extended.
14934
14935    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14936    if none.  In the former case, VAL is a 16-bit number with no
14937    defined signedness.
14938
14939    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14940    is the length that the user requested, or 0 if none.  */
14941
14942 static void
14943 mips16_immed (char *file, unsigned int line, int type,
14944               bfd_reloc_code_real_type reloc, offsetT val,
14945               unsigned int user_insn_length, unsigned long *insn)
14946 {
14947   const struct mips16_immed_operand *op;
14948   int mintiny, maxtiny;
14949
14950   op = mips16_immed_operands;
14951   while (op->type != type)
14952     {
14953       ++op;
14954       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
14955     }
14956
14957   if (op->unsp)
14958     {
14959       if (type == '<' || type == '>' || type == '[' || type == ']')
14960         {
14961           mintiny = 1;
14962           maxtiny = 1 << op->nbits;
14963         }
14964       else
14965         {
14966           mintiny = 0;
14967           maxtiny = (1 << op->nbits) - 1;
14968         }
14969       if (reloc != BFD_RELOC_UNUSED)
14970         val &= 0xffff;
14971     }
14972   else
14973     {
14974       mintiny = - (1 << (op->nbits - 1));
14975       maxtiny = (1 << (op->nbits - 1)) - 1;
14976       if (reloc != BFD_RELOC_UNUSED)
14977         val = SEXT_16BIT (val);
14978     }
14979
14980   /* Branch offsets have an implicit 0 in the lowest bit.  */
14981   if (type == 'p' || type == 'q')
14982     val /= 2;
14983
14984   if ((val & ((1 << op->shift) - 1)) != 0
14985       || val < (mintiny << op->shift)
14986       || val > (maxtiny << op->shift))
14987     {
14988       /* We need an extended instruction.  */
14989       if (user_insn_length == 2)
14990         as_bad_where (file, line, _("invalid unextended operand value"));
14991       else
14992         *insn |= MIPS16_EXTEND;
14993     }
14994   else if (user_insn_length == 4)
14995     {
14996       /* The operand doesn't force an unextended instruction to be extended.
14997          Warn if the user wanted an extended instruction anyway.  */
14998       *insn |= MIPS16_EXTEND;
14999       as_warn_where (file, line,
15000                      _("extended operand requested but not required"));
15001     }
15002
15003   if (mips16_opcode_length (*insn) == 2)
15004     {
15005       int insnval;
15006
15007       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
15008       insnval <<= op->op_shift;
15009       *insn |= insnval;
15010     }
15011   else
15012     {
15013       long minext, maxext;
15014
15015       if (reloc == BFD_RELOC_UNUSED)
15016         {
15017           if (op->extu)
15018             {
15019               minext = 0;
15020               maxext = (1 << op->extbits) - 1;
15021             }
15022           else
15023             {
15024               minext = - (1 << (op->extbits - 1));
15025               maxext = (1 << (op->extbits - 1)) - 1;
15026             }
15027           if (val < minext || val > maxext)
15028             as_bad_where (file, line,
15029                           _("operand value out of range for instruction"));
15030         }
15031
15032       *insn |= mips16_immed_extend (val, op->extbits);
15033     }
15034 }
15035 \f
15036 struct percent_op_match
15037 {
15038   const char *str;
15039   bfd_reloc_code_real_type reloc;
15040 };
15041
15042 static const struct percent_op_match mips_percent_op[] =
15043 {
15044   {"%lo", BFD_RELOC_LO16},
15045   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
15046   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
15047   {"%call16", BFD_RELOC_MIPS_CALL16},
15048   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
15049   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
15050   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
15051   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
15052   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
15053   {"%got", BFD_RELOC_MIPS_GOT16},
15054   {"%gp_rel", BFD_RELOC_GPREL16},
15055   {"%half", BFD_RELOC_16},
15056   {"%highest", BFD_RELOC_MIPS_HIGHEST},
15057   {"%higher", BFD_RELOC_MIPS_HIGHER},
15058   {"%neg", BFD_RELOC_MIPS_SUB},
15059   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
15060   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
15061   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
15062   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
15063   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
15064   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
15065   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
15066   {"%hi", BFD_RELOC_HI16_S}
15067 };
15068
15069 static const struct percent_op_match mips16_percent_op[] =
15070 {
15071   {"%lo", BFD_RELOC_MIPS16_LO16},
15072   {"%gprel", BFD_RELOC_MIPS16_GPREL},
15073   {"%got", BFD_RELOC_MIPS16_GOT16},
15074   {"%call16", BFD_RELOC_MIPS16_CALL16},
15075   {"%hi", BFD_RELOC_MIPS16_HI16_S},
15076   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
15077   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
15078   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
15079   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
15080   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
15081   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
15082   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
15083 };
15084
15085
15086 /* Return true if *STR points to a relocation operator.  When returning true,
15087    move *STR over the operator and store its relocation code in *RELOC.
15088    Leave both *STR and *RELOC alone when returning false.  */
15089
15090 static bfd_boolean
15091 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
15092 {
15093   const struct percent_op_match *percent_op;
15094   size_t limit, i;
15095
15096   if (mips_opts.mips16)
15097     {
15098       percent_op = mips16_percent_op;
15099       limit = ARRAY_SIZE (mips16_percent_op);
15100     }
15101   else
15102     {
15103       percent_op = mips_percent_op;
15104       limit = ARRAY_SIZE (mips_percent_op);
15105     }
15106
15107   for (i = 0; i < limit; i++)
15108     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
15109       {
15110         int len = strlen (percent_op[i].str);
15111
15112         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
15113           continue;
15114
15115         *str += strlen (percent_op[i].str);
15116         *reloc = percent_op[i].reloc;
15117
15118         /* Check whether the output BFD supports this relocation.
15119            If not, issue an error and fall back on something safe.  */
15120         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
15121           {
15122             as_bad (_("relocation %s isn't supported by the current ABI"),
15123                     percent_op[i].str);
15124             *reloc = BFD_RELOC_UNUSED;
15125           }
15126         return TRUE;
15127       }
15128   return FALSE;
15129 }
15130
15131
15132 /* Parse string STR as a 16-bit relocatable operand.  Store the
15133    expression in *EP and the relocations in the array starting
15134    at RELOC.  Return the number of relocation operators used.
15135
15136    On exit, EXPR_END points to the first character after the expression.  */
15137
15138 static size_t
15139 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
15140                        char *str)
15141 {
15142   bfd_reloc_code_real_type reversed_reloc[3];
15143   size_t reloc_index, i;
15144   int crux_depth, str_depth;
15145   char *crux;
15146
15147   /* Search for the start of the main expression, recoding relocations
15148      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
15149      of the main expression and with CRUX_DEPTH containing the number
15150      of open brackets at that point.  */
15151   reloc_index = -1;
15152   str_depth = 0;
15153   do
15154     {
15155       reloc_index++;
15156       crux = str;
15157       crux_depth = str_depth;
15158
15159       /* Skip over whitespace and brackets, keeping count of the number
15160          of brackets.  */
15161       while (*str == ' ' || *str == '\t' || *str == '(')
15162         if (*str++ == '(')
15163           str_depth++;
15164     }
15165   while (*str == '%'
15166          && reloc_index < (HAVE_NEWABI ? 3 : 1)
15167          && parse_relocation (&str, &reversed_reloc[reloc_index]));
15168
15169   my_getExpression (ep, crux);
15170   str = expr_end;
15171
15172   /* Match every open bracket.  */
15173   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
15174     if (*str++ == ')')
15175       crux_depth--;
15176
15177   if (crux_depth > 0)
15178     as_bad (_("unclosed '('"));
15179
15180   expr_end = str;
15181
15182   if (reloc_index != 0)
15183     {
15184       prev_reloc_op_frag = frag_now;
15185       for (i = 0; i < reloc_index; i++)
15186         reloc[i] = reversed_reloc[reloc_index - 1 - i];
15187     }
15188
15189   return reloc_index;
15190 }
15191
15192 static void
15193 my_getExpression (expressionS *ep, char *str)
15194 {
15195   char *save_in;
15196
15197   save_in = input_line_pointer;
15198   input_line_pointer = str;
15199   expression (ep);
15200   expr_end = input_line_pointer;
15201   input_line_pointer = save_in;
15202 }
15203
15204 char *
15205 md_atof (int type, char *litP, int *sizeP)
15206 {
15207   return ieee_md_atof (type, litP, sizeP, target_big_endian);
15208 }
15209
15210 void
15211 md_number_to_chars (char *buf, valueT val, int n)
15212 {
15213   if (target_big_endian)
15214     number_to_chars_bigendian (buf, val, n);
15215   else
15216     number_to_chars_littleendian (buf, val, n);
15217 }
15218 \f
15219 static int support_64bit_objects(void)
15220 {
15221   const char **list, **l;
15222   int yes;
15223
15224   list = bfd_target_list ();
15225   for (l = list; *l != NULL; l++)
15226     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
15227         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
15228       break;
15229   yes = (*l != NULL);
15230   free (list);
15231   return yes;
15232 }
15233
15234 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
15235    NEW_VALUE.  Warn if another value was already specified.  Note:
15236    we have to defer parsing the -march and -mtune arguments in order
15237    to handle 'from-abi' correctly, since the ABI might be specified
15238    in a later argument.  */
15239
15240 static void
15241 mips_set_option_string (const char **string_ptr, const char *new_value)
15242 {
15243   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
15244     as_warn (_("A different %s was already specified, is now %s"),
15245              string_ptr == &mips_arch_string ? "-march" : "-mtune",
15246              new_value);
15247
15248   *string_ptr = new_value;
15249 }
15250
15251 int
15252 md_parse_option (int c, char *arg)
15253 {
15254   unsigned int i;
15255
15256   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
15257     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
15258       {
15259         file_ase_explicit |= mips_set_ase (&mips_ases[i],
15260                                            c == mips_ases[i].option_on);
15261         return 1;
15262       }
15263
15264   switch (c)
15265     {
15266     case OPTION_CONSTRUCT_FLOATS:
15267       mips_disable_float_construction = 0;
15268       break;
15269
15270     case OPTION_NO_CONSTRUCT_FLOATS:
15271       mips_disable_float_construction = 1;
15272       break;
15273
15274     case OPTION_TRAP:
15275       mips_trap = 1;
15276       break;
15277
15278     case OPTION_BREAK:
15279       mips_trap = 0;
15280       break;
15281
15282     case OPTION_EB:
15283       target_big_endian = 1;
15284       break;
15285
15286     case OPTION_EL:
15287       target_big_endian = 0;
15288       break;
15289
15290     case 'O':
15291       if (arg == NULL)
15292         mips_optimize = 1;
15293       else if (arg[0] == '0')
15294         mips_optimize = 0;
15295       else if (arg[0] == '1')
15296         mips_optimize = 1;
15297       else
15298         mips_optimize = 2;
15299       break;
15300
15301     case 'g':
15302       if (arg == NULL)
15303         mips_debug = 2;
15304       else
15305         mips_debug = atoi (arg);
15306       break;
15307
15308     case OPTION_MIPS1:
15309       file_mips_isa = ISA_MIPS1;
15310       break;
15311
15312     case OPTION_MIPS2:
15313       file_mips_isa = ISA_MIPS2;
15314       break;
15315
15316     case OPTION_MIPS3:
15317       file_mips_isa = ISA_MIPS3;
15318       break;
15319
15320     case OPTION_MIPS4:
15321       file_mips_isa = ISA_MIPS4;
15322       break;
15323
15324     case OPTION_MIPS5:
15325       file_mips_isa = ISA_MIPS5;
15326       break;
15327
15328     case OPTION_MIPS32:
15329       file_mips_isa = ISA_MIPS32;
15330       break;
15331
15332     case OPTION_MIPS32R2:
15333       file_mips_isa = ISA_MIPS32R2;
15334       break;
15335
15336     case OPTION_MIPS64R2:
15337       file_mips_isa = ISA_MIPS64R2;
15338       break;
15339
15340     case OPTION_MIPS64:
15341       file_mips_isa = ISA_MIPS64;
15342       break;
15343
15344     case OPTION_MTUNE:
15345       mips_set_option_string (&mips_tune_string, arg);
15346       break;
15347
15348     case OPTION_MARCH:
15349       mips_set_option_string (&mips_arch_string, arg);
15350       break;
15351
15352     case OPTION_M4650:
15353       mips_set_option_string (&mips_arch_string, "4650");
15354       mips_set_option_string (&mips_tune_string, "4650");
15355       break;
15356
15357     case OPTION_NO_M4650:
15358       break;
15359
15360     case OPTION_M4010:
15361       mips_set_option_string (&mips_arch_string, "4010");
15362       mips_set_option_string (&mips_tune_string, "4010");
15363       break;
15364
15365     case OPTION_NO_M4010:
15366       break;
15367
15368     case OPTION_M4100:
15369       mips_set_option_string (&mips_arch_string, "4100");
15370       mips_set_option_string (&mips_tune_string, "4100");
15371       break;
15372
15373     case OPTION_NO_M4100:
15374       break;
15375
15376     case OPTION_M3900:
15377       mips_set_option_string (&mips_arch_string, "3900");
15378       mips_set_option_string (&mips_tune_string, "3900");
15379       break;
15380
15381     case OPTION_NO_M3900:
15382       break;
15383
15384     case OPTION_MICROMIPS:
15385       if (mips_opts.mips16 == 1)
15386         {
15387           as_bad (_("-mmicromips cannot be used with -mips16"));
15388           return 0;
15389         }
15390       mips_opts.micromips = 1;
15391       mips_no_prev_insn ();
15392       break;
15393
15394     case OPTION_NO_MICROMIPS:
15395       mips_opts.micromips = 0;
15396       mips_no_prev_insn ();
15397       break;
15398
15399     case OPTION_MIPS16:
15400       if (mips_opts.micromips == 1)
15401         {
15402           as_bad (_("-mips16 cannot be used with -micromips"));
15403           return 0;
15404         }
15405       mips_opts.mips16 = 1;
15406       mips_no_prev_insn ();
15407       break;
15408
15409     case OPTION_NO_MIPS16:
15410       mips_opts.mips16 = 0;
15411       mips_no_prev_insn ();
15412       break;
15413
15414     case OPTION_FIX_24K:
15415       mips_fix_24k = 1;
15416       break;
15417
15418     case OPTION_NO_FIX_24K:
15419       mips_fix_24k = 0;
15420       break;
15421
15422     case OPTION_FIX_LOONGSON2F_JUMP:
15423       mips_fix_loongson2f_jump = TRUE;
15424       break;
15425
15426     case OPTION_NO_FIX_LOONGSON2F_JUMP:
15427       mips_fix_loongson2f_jump = FALSE;
15428       break;
15429
15430     case OPTION_FIX_LOONGSON2F_NOP:
15431       mips_fix_loongson2f_nop = TRUE;
15432       break;
15433
15434     case OPTION_NO_FIX_LOONGSON2F_NOP:
15435       mips_fix_loongson2f_nop = FALSE;
15436       break;
15437
15438     case OPTION_FIX_VR4120:
15439       mips_fix_vr4120 = 1;
15440       break;
15441
15442     case OPTION_NO_FIX_VR4120:
15443       mips_fix_vr4120 = 0;
15444       break;
15445
15446     case OPTION_FIX_VR4130:
15447       mips_fix_vr4130 = 1;
15448       break;
15449
15450     case OPTION_NO_FIX_VR4130:
15451       mips_fix_vr4130 = 0;
15452       break;
15453
15454     case OPTION_FIX_CN63XXP1:
15455       mips_fix_cn63xxp1 = TRUE;
15456       break;
15457
15458     case OPTION_NO_FIX_CN63XXP1:
15459       mips_fix_cn63xxp1 = FALSE;
15460       break;
15461
15462     case OPTION_RELAX_BRANCH:
15463       mips_relax_branch = 1;
15464       break;
15465
15466     case OPTION_NO_RELAX_BRANCH:
15467       mips_relax_branch = 0;
15468       break;
15469
15470     case OPTION_INSN32:
15471       mips_opts.insn32 = TRUE;
15472       break;
15473
15474     case OPTION_NO_INSN32:
15475       mips_opts.insn32 = FALSE;
15476       break;
15477
15478     case OPTION_MSHARED:
15479       mips_in_shared = TRUE;
15480       break;
15481
15482     case OPTION_MNO_SHARED:
15483       mips_in_shared = FALSE;
15484       break;
15485
15486     case OPTION_MSYM32:
15487       mips_opts.sym32 = TRUE;
15488       break;
15489
15490     case OPTION_MNO_SYM32:
15491       mips_opts.sym32 = FALSE;
15492       break;
15493
15494       /* When generating ELF code, we permit -KPIC and -call_shared to
15495          select SVR4_PIC, and -non_shared to select no PIC.  This is
15496          intended to be compatible with Irix 5.  */
15497     case OPTION_CALL_SHARED:
15498       mips_pic = SVR4_PIC;
15499       mips_abicalls = TRUE;
15500       break;
15501
15502     case OPTION_CALL_NONPIC:
15503       mips_pic = NO_PIC;
15504       mips_abicalls = TRUE;
15505       break;
15506
15507     case OPTION_NON_SHARED:
15508       mips_pic = NO_PIC;
15509       mips_abicalls = FALSE;
15510       break;
15511
15512       /* The -xgot option tells the assembler to use 32 bit offsets
15513          when accessing the got in SVR4_PIC mode.  It is for Irix
15514          compatibility.  */
15515     case OPTION_XGOT:
15516       mips_big_got = 1;
15517       break;
15518
15519     case 'G':
15520       g_switch_value = atoi (arg);
15521       g_switch_seen = 1;
15522       break;
15523
15524       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
15525          and -mabi=64.  */
15526     case OPTION_32:
15527       mips_abi = O32_ABI;
15528       break;
15529
15530     case OPTION_N32:
15531       mips_abi = N32_ABI;
15532       break;
15533
15534     case OPTION_64:
15535       mips_abi = N64_ABI;
15536       if (!support_64bit_objects())
15537         as_fatal (_("No compiled in support for 64 bit object file format"));
15538       break;
15539
15540     case OPTION_GP32:
15541       file_mips_gp32 = 1;
15542       break;
15543
15544     case OPTION_GP64:
15545       file_mips_gp32 = 0;
15546       break;
15547
15548     case OPTION_FP32:
15549       file_mips_fp32 = 1;
15550       break;
15551
15552     case OPTION_FP64:
15553       file_mips_fp32 = 0;
15554       break;
15555
15556     case OPTION_SINGLE_FLOAT:
15557       file_mips_single_float = 1;
15558       break;
15559
15560     case OPTION_DOUBLE_FLOAT:
15561       file_mips_single_float = 0;
15562       break;
15563
15564     case OPTION_SOFT_FLOAT:
15565       file_mips_soft_float = 1;
15566       break;
15567
15568     case OPTION_HARD_FLOAT:
15569       file_mips_soft_float = 0;
15570       break;
15571
15572     case OPTION_MABI:
15573       if (strcmp (arg, "32") == 0)
15574         mips_abi = O32_ABI;
15575       else if (strcmp (arg, "o64") == 0)
15576         mips_abi = O64_ABI;
15577       else if (strcmp (arg, "n32") == 0)
15578         mips_abi = N32_ABI;
15579       else if (strcmp (arg, "64") == 0)
15580         {
15581           mips_abi = N64_ABI;
15582           if (! support_64bit_objects())
15583             as_fatal (_("No compiled in support for 64 bit object file "
15584                         "format"));
15585         }
15586       else if (strcmp (arg, "eabi") == 0)
15587         mips_abi = EABI_ABI;
15588       else
15589         {
15590           as_fatal (_("invalid abi -mabi=%s"), arg);
15591           return 0;
15592         }
15593       break;
15594
15595     case OPTION_M7000_HILO_FIX:
15596       mips_7000_hilo_fix = TRUE;
15597       break;
15598
15599     case OPTION_MNO_7000_HILO_FIX:
15600       mips_7000_hilo_fix = FALSE;
15601       break;
15602
15603     case OPTION_MDEBUG:
15604       mips_flag_mdebug = TRUE;
15605       break;
15606
15607     case OPTION_NO_MDEBUG:
15608       mips_flag_mdebug = FALSE;
15609       break;
15610
15611     case OPTION_PDR:
15612       mips_flag_pdr = TRUE;
15613       break;
15614
15615     case OPTION_NO_PDR:
15616       mips_flag_pdr = FALSE;
15617       break;
15618
15619     case OPTION_MVXWORKS_PIC:
15620       mips_pic = VXWORKS_PIC;
15621       break;
15622
15623     case OPTION_NAN:
15624       if (strcmp (arg, "2008") == 0)
15625         mips_flag_nan2008 = TRUE;
15626       else if (strcmp (arg, "legacy") == 0)
15627         mips_flag_nan2008 = FALSE;
15628       else
15629         {
15630           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
15631           return 0;
15632         }
15633       break;
15634
15635     default:
15636       return 0;
15637     }
15638
15639     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
15640
15641   return 1;
15642 }
15643 \f
15644 /* Set up globals to generate code for the ISA or processor
15645    described by INFO.  */
15646
15647 static void
15648 mips_set_architecture (const struct mips_cpu_info *info)
15649 {
15650   if (info != 0)
15651     {
15652       file_mips_arch = info->cpu;
15653       mips_opts.arch = info->cpu;
15654       mips_opts.isa = info->isa;
15655     }
15656 }
15657
15658
15659 /* Likewise for tuning.  */
15660
15661 static void
15662 mips_set_tune (const struct mips_cpu_info *info)
15663 {
15664   if (info != 0)
15665     mips_tune = info->cpu;
15666 }
15667
15668
15669 void
15670 mips_after_parse_args (void)
15671 {
15672   const struct mips_cpu_info *arch_info = 0;
15673   const struct mips_cpu_info *tune_info = 0;
15674
15675   /* GP relative stuff not working for PE */
15676   if (strncmp (TARGET_OS, "pe", 2) == 0)
15677     {
15678       if (g_switch_seen && g_switch_value != 0)
15679         as_bad (_("-G not supported in this configuration."));
15680       g_switch_value = 0;
15681     }
15682
15683   if (mips_abi == NO_ABI)
15684     mips_abi = MIPS_DEFAULT_ABI;
15685
15686   /* The following code determines the architecture and register size.
15687      Similar code was added to GCC 3.3 (see override_options() in
15688      config/mips/mips.c).  The GAS and GCC code should be kept in sync
15689      as much as possible.  */
15690
15691   if (mips_arch_string != 0)
15692     arch_info = mips_parse_cpu ("-march", mips_arch_string);
15693
15694   if (file_mips_isa != ISA_UNKNOWN)
15695     {
15696       /* Handle -mipsN.  At this point, file_mips_isa contains the
15697          ISA level specified by -mipsN, while arch_info->isa contains
15698          the -march selection (if any).  */
15699       if (arch_info != 0)
15700         {
15701           /* -march takes precedence over -mipsN, since it is more descriptive.
15702              There's no harm in specifying both as long as the ISA levels
15703              are the same.  */
15704           if (file_mips_isa != arch_info->isa)
15705             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
15706                     mips_cpu_info_from_isa (file_mips_isa)->name,
15707                     mips_cpu_info_from_isa (arch_info->isa)->name);
15708         }
15709       else
15710         arch_info = mips_cpu_info_from_isa (file_mips_isa);
15711     }
15712
15713   if (arch_info == 0)
15714     {
15715       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15716       gas_assert (arch_info);
15717     }
15718
15719   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15720     as_bad (_("-march=%s is not compatible with the selected ABI"),
15721             arch_info->name);
15722
15723   mips_set_architecture (arch_info);
15724
15725   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
15726   if (mips_tune_string != 0)
15727     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15728
15729   if (tune_info == 0)
15730     mips_set_tune (arch_info);
15731   else
15732     mips_set_tune (tune_info);
15733
15734   if (file_mips_gp32 >= 0)
15735     {
15736       /* The user specified the size of the integer registers.  Make sure
15737          it agrees with the ABI and ISA.  */
15738       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
15739         as_bad (_("-mgp64 used with a 32-bit processor"));
15740       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
15741         as_bad (_("-mgp32 used with a 64-bit ABI"));
15742       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
15743         as_bad (_("-mgp64 used with a 32-bit ABI"));
15744     }
15745   else
15746     {
15747       /* Infer the integer register size from the ABI and processor.
15748          Restrict ourselves to 32-bit registers if that's all the
15749          processor has, or if the ABI cannot handle 64-bit registers.  */
15750       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
15751                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
15752     }
15753
15754   switch (file_mips_fp32)
15755     {
15756     default:
15757     case -1:
15758       /* No user specified float register size.
15759          ??? GAS treats single-float processors as though they had 64-bit
15760          float registers (although it complains when double-precision
15761          instructions are used).  As things stand, saying they have 32-bit
15762          registers would lead to spurious "register must be even" messages.
15763          So here we assume float registers are never smaller than the
15764          integer ones.  */
15765       if (file_mips_gp32 == 0)
15766         /* 64-bit integer registers implies 64-bit float registers.  */
15767         file_mips_fp32 = 0;
15768       else if ((mips_opts.ase & FP64_ASES)
15769                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
15770         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
15771         file_mips_fp32 = 0;
15772       else
15773         /* 32-bit float registers.  */
15774         file_mips_fp32 = 1;
15775       break;
15776
15777     /* The user specified the size of the float registers.  Check if it
15778        agrees with the ABI and ISA.  */
15779     case 0:
15780       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15781         as_bad (_("-mfp64 used with a 32-bit fpu"));
15782       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
15783                && !ISA_HAS_MXHC1 (mips_opts.isa))
15784         as_warn (_("-mfp64 used with a 32-bit ABI"));
15785       break;
15786     case 1:
15787       if (ABI_NEEDS_64BIT_REGS (mips_abi))
15788         as_warn (_("-mfp32 used with a 64-bit ABI"));
15789       break;
15790     }
15791
15792   /* End of GCC-shared inference code.  */
15793
15794   /* This flag is set when we have a 64-bit capable CPU but use only
15795      32-bit wide registers.  Note that EABI does not use it.  */
15796   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
15797       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
15798           || mips_abi == O32_ABI))
15799     mips_32bitmode = 1;
15800
15801   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
15802     as_bad (_("trap exception not supported at ISA 1"));
15803
15804   /* If the selected architecture includes support for ASEs, enable
15805      generation of code for them.  */
15806   if (mips_opts.mips16 == -1)
15807     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
15808   if (mips_opts.micromips == -1)
15809     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15810
15811   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
15812      ASEs from being selected implicitly.  */
15813   if (file_mips_fp32 == 1)
15814     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
15815
15816   /* If the user didn't explicitly select or deselect a particular ASE,
15817      use the default setting for the CPU.  */
15818   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
15819
15820   file_mips_isa = mips_opts.isa;
15821   file_ase = mips_opts.ase;
15822   mips_opts.gp32 = file_mips_gp32;
15823   mips_opts.fp32 = file_mips_fp32;
15824   mips_opts.soft_float = file_mips_soft_float;
15825   mips_opts.single_float = file_mips_single_float;
15826
15827   mips_check_isa_supports_ases ();
15828
15829   if (mips_flag_mdebug < 0)
15830     mips_flag_mdebug = 0;
15831 }
15832 \f
15833 void
15834 mips_init_after_args (void)
15835 {
15836   /* initialize opcodes */
15837   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15838   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15839 }
15840
15841 long
15842 md_pcrel_from (fixS *fixP)
15843 {
15844   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15845   switch (fixP->fx_r_type)
15846     {
15847     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15848     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15849       /* Return the address of the delay slot.  */
15850       return addr + 2;
15851
15852     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15853     case BFD_RELOC_MICROMIPS_JMP:
15854     case BFD_RELOC_16_PCREL_S2:
15855     case BFD_RELOC_MIPS_JMP:
15856       /* Return the address of the delay slot.  */
15857       return addr + 4;
15858
15859     case BFD_RELOC_32_PCREL:
15860       return addr;
15861
15862     default:
15863       /* We have no relocation type for PC relative MIPS16 instructions.  */
15864       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15865         as_bad_where (fixP->fx_file, fixP->fx_line,
15866                       _("PC relative MIPS16 instruction references a different section"));
15867       return addr;
15868     }
15869 }
15870
15871 /* This is called before the symbol table is processed.  In order to
15872    work with gcc when using mips-tfile, we must keep all local labels.
15873    However, in other cases, we want to discard them.  If we were
15874    called with -g, but we didn't see any debugging information, it may
15875    mean that gcc is smuggling debugging information through to
15876    mips-tfile, in which case we must generate all local labels.  */
15877
15878 void
15879 mips_frob_file_before_adjust (void)
15880 {
15881 #ifndef NO_ECOFF_DEBUGGING
15882   if (ECOFF_DEBUGGING
15883       && mips_debug != 0
15884       && ! ecoff_debugging_seen)
15885     flag_keep_locals = 1;
15886 #endif
15887 }
15888
15889 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15890    the corresponding LO16 reloc.  This is called before md_apply_fix and
15891    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15892    relocation operators.
15893
15894    For our purposes, a %lo() expression matches a %got() or %hi()
15895    expression if:
15896
15897       (a) it refers to the same symbol; and
15898       (b) the offset applied in the %lo() expression is no lower than
15899           the offset applied in the %got() or %hi().
15900
15901    (b) allows us to cope with code like:
15902
15903         lui     $4,%hi(foo)
15904         lh      $4,%lo(foo+2)($4)
15905
15906    ...which is legal on RELA targets, and has a well-defined behaviour
15907    if the user knows that adding 2 to "foo" will not induce a carry to
15908    the high 16 bits.
15909
15910    When several %lo()s match a particular %got() or %hi(), we use the
15911    following rules to distinguish them:
15912
15913      (1) %lo()s with smaller offsets are a better match than %lo()s with
15914          higher offsets.
15915
15916      (2) %lo()s with no matching %got() or %hi() are better than those
15917          that already have a matching %got() or %hi().
15918
15919      (3) later %lo()s are better than earlier %lo()s.
15920
15921    These rules are applied in order.
15922
15923    (1) means, among other things, that %lo()s with identical offsets are
15924    chosen if they exist.
15925
15926    (2) means that we won't associate several high-part relocations with
15927    the same low-part relocation unless there's no alternative.  Having
15928    several high parts for the same low part is a GNU extension; this rule
15929    allows careful users to avoid it.
15930
15931    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15932    with the last high-part relocation being at the front of the list.
15933    It therefore makes sense to choose the last matching low-part
15934    relocation, all other things being equal.  It's also easier
15935    to code that way.  */
15936
15937 void
15938 mips_frob_file (void)
15939 {
15940   struct mips_hi_fixup *l;
15941   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15942
15943   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15944     {
15945       segment_info_type *seginfo;
15946       bfd_boolean matched_lo_p;
15947       fixS **hi_pos, **lo_pos, **pos;
15948
15949       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15950
15951       /* If a GOT16 relocation turns out to be against a global symbol,
15952          there isn't supposed to be a matching LO.  Ignore %gots against
15953          constants; we'll report an error for those later.  */
15954       if (got16_reloc_p (l->fixp->fx_r_type)
15955           && !(l->fixp->fx_addsy
15956                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
15957         continue;
15958
15959       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15960       if (fixup_has_matching_lo_p (l->fixp))
15961         continue;
15962
15963       seginfo = seg_info (l->seg);
15964
15965       /* Set HI_POS to the position of this relocation in the chain.
15966          Set LO_POS to the position of the chosen low-part relocation.
15967          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15968          relocation that matches an immediately-preceding high-part
15969          relocation.  */
15970       hi_pos = NULL;
15971       lo_pos = NULL;
15972       matched_lo_p = FALSE;
15973       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15974
15975       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15976         {
15977           if (*pos == l->fixp)
15978             hi_pos = pos;
15979
15980           if ((*pos)->fx_r_type == looking_for_rtype
15981               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15982               && (*pos)->fx_offset >= l->fixp->fx_offset
15983               && (lo_pos == NULL
15984                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15985                   || (!matched_lo_p
15986                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15987             lo_pos = pos;
15988
15989           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15990                           && fixup_has_matching_lo_p (*pos));
15991         }
15992
15993       /* If we found a match, remove the high-part relocation from its
15994          current position and insert it before the low-part relocation.
15995          Make the offsets match so that fixup_has_matching_lo_p()
15996          will return true.
15997
15998          We don't warn about unmatched high-part relocations since some
15999          versions of gcc have been known to emit dead "lui ...%hi(...)"
16000          instructions.  */
16001       if (lo_pos != NULL)
16002         {
16003           l->fixp->fx_offset = (*lo_pos)->fx_offset;
16004           if (l->fixp->fx_next != *lo_pos)
16005             {
16006               *hi_pos = l->fixp->fx_next;
16007               l->fixp->fx_next = *lo_pos;
16008               *lo_pos = l->fixp;
16009             }
16010         }
16011     }
16012 }
16013
16014 int
16015 mips_force_relocation (fixS *fixp)
16016 {
16017   if (generic_force_reloc (fixp))
16018     return 1;
16019
16020   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
16021      so that the linker relaxation can update targets.  */
16022   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16023       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16024       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
16025     return 1;
16026
16027   return 0;
16028 }
16029
16030 /* Read the instruction associated with RELOC from BUF.  */
16031
16032 static unsigned int
16033 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
16034 {
16035   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
16036     return read_compressed_insn (buf, 4);
16037   else
16038     return read_insn (buf);
16039 }
16040
16041 /* Write instruction INSN to BUF, given that it has been relocated
16042    by RELOC.  */
16043
16044 static void
16045 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
16046                   unsigned long insn)
16047 {
16048   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
16049     write_compressed_insn (buf, insn, 4);
16050   else
16051     write_insn (buf, insn);
16052 }
16053
16054 /* Apply a fixup to the object file.  */
16055
16056 void
16057 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
16058 {
16059   char *buf;
16060   unsigned long insn;
16061   reloc_howto_type *howto;
16062
16063   /* We ignore generic BFD relocations we don't know about.  */
16064   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
16065   if (! howto)
16066     return;
16067
16068   gas_assert (fixP->fx_size == 2
16069               || fixP->fx_size == 4
16070               || fixP->fx_r_type == BFD_RELOC_16
16071               || fixP->fx_r_type == BFD_RELOC_64
16072               || fixP->fx_r_type == BFD_RELOC_CTOR
16073               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
16074               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
16075               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16076               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
16077               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
16078
16079   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
16080
16081   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
16082               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16083               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16084               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16085               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
16086
16087   /* Don't treat parts of a composite relocation as done.  There are two
16088      reasons for this:
16089
16090      (1) The second and third parts will be against 0 (RSS_UNDEF) but
16091          should nevertheless be emitted if the first part is.
16092
16093      (2) In normal usage, composite relocations are never assembly-time
16094          constants.  The easiest way of dealing with the pathological
16095          exceptions is to generate a relocation against STN_UNDEF and
16096          leave everything up to the linker.  */
16097   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
16098     fixP->fx_done = 1;
16099
16100   switch (fixP->fx_r_type)
16101     {
16102     case BFD_RELOC_MIPS_TLS_GD:
16103     case BFD_RELOC_MIPS_TLS_LDM:
16104     case BFD_RELOC_MIPS_TLS_DTPREL32:
16105     case BFD_RELOC_MIPS_TLS_DTPREL64:
16106     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
16107     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
16108     case BFD_RELOC_MIPS_TLS_GOTTPREL:
16109     case BFD_RELOC_MIPS_TLS_TPREL32:
16110     case BFD_RELOC_MIPS_TLS_TPREL64:
16111     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
16112     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
16113     case BFD_RELOC_MICROMIPS_TLS_GD:
16114     case BFD_RELOC_MICROMIPS_TLS_LDM:
16115     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
16116     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
16117     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
16118     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
16119     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
16120     case BFD_RELOC_MIPS16_TLS_GD:
16121     case BFD_RELOC_MIPS16_TLS_LDM:
16122     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
16123     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
16124     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
16125     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
16126     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
16127       if (!fixP->fx_addsy)
16128         {
16129           as_bad_where (fixP->fx_file, fixP->fx_line,
16130                         _("TLS relocation against a constant"));
16131           break;
16132         }
16133       S_SET_THREAD_LOCAL (fixP->fx_addsy);
16134       /* fall through */
16135
16136     case BFD_RELOC_MIPS_JMP:
16137     case BFD_RELOC_MIPS_SHIFT5:
16138     case BFD_RELOC_MIPS_SHIFT6:
16139     case BFD_RELOC_MIPS_GOT_DISP:
16140     case BFD_RELOC_MIPS_GOT_PAGE:
16141     case BFD_RELOC_MIPS_GOT_OFST:
16142     case BFD_RELOC_MIPS_SUB:
16143     case BFD_RELOC_MIPS_INSERT_A:
16144     case BFD_RELOC_MIPS_INSERT_B:
16145     case BFD_RELOC_MIPS_DELETE:
16146     case BFD_RELOC_MIPS_HIGHEST:
16147     case BFD_RELOC_MIPS_HIGHER:
16148     case BFD_RELOC_MIPS_SCN_DISP:
16149     case BFD_RELOC_MIPS_REL16:
16150     case BFD_RELOC_MIPS_RELGOT:
16151     case BFD_RELOC_MIPS_JALR:
16152     case BFD_RELOC_HI16:
16153     case BFD_RELOC_HI16_S:
16154     case BFD_RELOC_LO16:
16155     case BFD_RELOC_GPREL16:
16156     case BFD_RELOC_MIPS_LITERAL:
16157     case BFD_RELOC_MIPS_CALL16:
16158     case BFD_RELOC_MIPS_GOT16:
16159     case BFD_RELOC_GPREL32:
16160     case BFD_RELOC_MIPS_GOT_HI16:
16161     case BFD_RELOC_MIPS_GOT_LO16:
16162     case BFD_RELOC_MIPS_CALL_HI16:
16163     case BFD_RELOC_MIPS_CALL_LO16:
16164     case BFD_RELOC_MIPS16_GPREL:
16165     case BFD_RELOC_MIPS16_GOT16:
16166     case BFD_RELOC_MIPS16_CALL16:
16167     case BFD_RELOC_MIPS16_HI16:
16168     case BFD_RELOC_MIPS16_HI16_S:
16169     case BFD_RELOC_MIPS16_LO16:
16170     case BFD_RELOC_MIPS16_JMP:
16171     case BFD_RELOC_MICROMIPS_JMP:
16172     case BFD_RELOC_MICROMIPS_GOT_DISP:
16173     case BFD_RELOC_MICROMIPS_GOT_PAGE:
16174     case BFD_RELOC_MICROMIPS_GOT_OFST:
16175     case BFD_RELOC_MICROMIPS_SUB:
16176     case BFD_RELOC_MICROMIPS_HIGHEST:
16177     case BFD_RELOC_MICROMIPS_HIGHER:
16178     case BFD_RELOC_MICROMIPS_SCN_DISP:
16179     case BFD_RELOC_MICROMIPS_JALR:
16180     case BFD_RELOC_MICROMIPS_HI16:
16181     case BFD_RELOC_MICROMIPS_HI16_S:
16182     case BFD_RELOC_MICROMIPS_LO16:
16183     case BFD_RELOC_MICROMIPS_GPREL16:
16184     case BFD_RELOC_MICROMIPS_LITERAL:
16185     case BFD_RELOC_MICROMIPS_CALL16:
16186     case BFD_RELOC_MICROMIPS_GOT16:
16187     case BFD_RELOC_MICROMIPS_GOT_HI16:
16188     case BFD_RELOC_MICROMIPS_GOT_LO16:
16189     case BFD_RELOC_MICROMIPS_CALL_HI16:
16190     case BFD_RELOC_MICROMIPS_CALL_LO16:
16191     case BFD_RELOC_MIPS_EH:
16192       if (fixP->fx_done)
16193         {
16194           offsetT value;
16195
16196           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
16197             {
16198               insn = read_reloc_insn (buf, fixP->fx_r_type);
16199               if (mips16_reloc_p (fixP->fx_r_type))
16200                 insn |= mips16_immed_extend (value, 16);
16201               else
16202                 insn |= (value & 0xffff);
16203               write_reloc_insn (buf, fixP->fx_r_type, insn);
16204             }
16205           else
16206             as_bad_where (fixP->fx_file, fixP->fx_line,
16207                           _("Unsupported constant in relocation"));
16208         }
16209       break;
16210
16211     case BFD_RELOC_64:
16212       /* This is handled like BFD_RELOC_32, but we output a sign
16213          extended value if we are only 32 bits.  */
16214       if (fixP->fx_done)
16215         {
16216           if (8 <= sizeof (valueT))
16217             md_number_to_chars (buf, *valP, 8);
16218           else
16219             {
16220               valueT hiv;
16221
16222               if ((*valP & 0x80000000) != 0)
16223                 hiv = 0xffffffff;
16224               else
16225                 hiv = 0;
16226               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
16227               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
16228             }
16229         }
16230       break;
16231
16232     case BFD_RELOC_RVA:
16233     case BFD_RELOC_32:
16234     case BFD_RELOC_32_PCREL:
16235     case BFD_RELOC_16:
16236       /* If we are deleting this reloc entry, we must fill in the
16237          value now.  This can happen if we have a .word which is not
16238          resolved when it appears but is later defined.  */
16239       if (fixP->fx_done)
16240         md_number_to_chars (buf, *valP, fixP->fx_size);
16241       break;
16242
16243     case BFD_RELOC_16_PCREL_S2:
16244       if ((*valP & 0x3) != 0)
16245         as_bad_where (fixP->fx_file, fixP->fx_line,
16246                       _("Branch to misaligned address (%lx)"), (long) *valP);
16247
16248       /* We need to save the bits in the instruction since fixup_segment()
16249          might be deleting the relocation entry (i.e., a branch within
16250          the current segment).  */
16251       if (! fixP->fx_done)
16252         break;
16253
16254       /* Update old instruction data.  */
16255       insn = read_insn (buf);
16256
16257       if (*valP + 0x20000 <= 0x3ffff)
16258         {
16259           insn |= (*valP >> 2) & 0xffff;
16260           write_insn (buf, insn);
16261         }
16262       else if (mips_pic == NO_PIC
16263                && fixP->fx_done
16264                && fixP->fx_frag->fr_address >= text_section->vma
16265                && (fixP->fx_frag->fr_address
16266                    < text_section->vma + bfd_get_section_size (text_section))
16267                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
16268                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
16269                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
16270         {
16271           /* The branch offset is too large.  If this is an
16272              unconditional branch, and we are not generating PIC code,
16273              we can convert it to an absolute jump instruction.  */
16274           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
16275             insn = 0x0c000000;  /* jal */
16276           else
16277             insn = 0x08000000;  /* j */
16278           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
16279           fixP->fx_done = 0;
16280           fixP->fx_addsy = section_symbol (text_section);
16281           *valP += md_pcrel_from (fixP);
16282           write_insn (buf, insn);
16283         }
16284       else
16285         {
16286           /* If we got here, we have branch-relaxation disabled,
16287              and there's nothing we can do to fix this instruction
16288              without turning it into a longer sequence.  */
16289           as_bad_where (fixP->fx_file, fixP->fx_line,
16290                         _("Branch out of range"));
16291         }
16292       break;
16293
16294     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
16295     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
16296     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
16297       /* We adjust the offset back to even.  */
16298       if ((*valP & 0x1) != 0)
16299         --(*valP);
16300
16301       if (! fixP->fx_done)
16302         break;
16303
16304       /* Should never visit here, because we keep the relocation.  */
16305       abort ();
16306       break;
16307
16308     case BFD_RELOC_VTABLE_INHERIT:
16309       fixP->fx_done = 0;
16310       if (fixP->fx_addsy
16311           && !S_IS_DEFINED (fixP->fx_addsy)
16312           && !S_IS_WEAK (fixP->fx_addsy))
16313         S_SET_WEAK (fixP->fx_addsy);
16314       break;
16315
16316     case BFD_RELOC_VTABLE_ENTRY:
16317       fixP->fx_done = 0;
16318       break;
16319
16320     default:
16321       abort ();
16322     }
16323
16324   /* Remember value for tc_gen_reloc.  */
16325   fixP->fx_addnumber = *valP;
16326 }
16327
16328 static symbolS *
16329 get_symbol (void)
16330 {
16331   int c;
16332   char *name;
16333   symbolS *p;
16334
16335   name = input_line_pointer;
16336   c = get_symbol_end ();
16337   p = (symbolS *) symbol_find_or_make (name);
16338   *input_line_pointer = c;
16339   return p;
16340 }
16341
16342 /* Align the current frag to a given power of two.  If a particular
16343    fill byte should be used, FILL points to an integer that contains
16344    that byte, otherwise FILL is null.
16345
16346    This function used to have the comment:
16347
16348       The MIPS assembler also automatically adjusts any preceding label.
16349
16350    The implementation therefore applied the adjustment to a maximum of
16351    one label.  However, other label adjustments are applied to batches
16352    of labels, and adjusting just one caused problems when new labels
16353    were added for the sake of debugging or unwind information.
16354    We therefore adjust all preceding labels (given as LABELS) instead.  */
16355
16356 static void
16357 mips_align (int to, int *fill, struct insn_label_list *labels)
16358 {
16359   mips_emit_delays ();
16360   mips_record_compressed_mode ();
16361   if (fill == NULL && subseg_text_p (now_seg))
16362     frag_align_code (to, 0);
16363   else
16364     frag_align (to, fill ? *fill : 0, 0);
16365   record_alignment (now_seg, to);
16366   mips_move_labels (labels, FALSE);
16367 }
16368
16369 /* Align to a given power of two.  .align 0 turns off the automatic
16370    alignment used by the data creating pseudo-ops.  */
16371
16372 static void
16373 s_align (int x ATTRIBUTE_UNUSED)
16374 {
16375   int temp, fill_value, *fill_ptr;
16376   long max_alignment = 28;
16377
16378   /* o Note that the assembler pulls down any immediately preceding label
16379        to the aligned address.
16380      o It's not documented but auto alignment is reinstated by
16381        a .align pseudo instruction.
16382      o Note also that after auto alignment is turned off the mips assembler
16383        issues an error on attempt to assemble an improperly aligned data item.
16384        We don't.  */
16385
16386   temp = get_absolute_expression ();
16387   if (temp > max_alignment)
16388     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
16389   else if (temp < 0)
16390     {
16391       as_warn (_("Alignment negative: 0 assumed."));
16392       temp = 0;
16393     }
16394   if (*input_line_pointer == ',')
16395     {
16396       ++input_line_pointer;
16397       fill_value = get_absolute_expression ();
16398       fill_ptr = &fill_value;
16399     }
16400   else
16401     fill_ptr = 0;
16402   if (temp)
16403     {
16404       segment_info_type *si = seg_info (now_seg);
16405       struct insn_label_list *l = si->label_list;
16406       /* Auto alignment should be switched on by next section change.  */
16407       auto_align = 1;
16408       mips_align (temp, fill_ptr, l);
16409     }
16410   else
16411     {
16412       auto_align = 0;
16413     }
16414
16415   demand_empty_rest_of_line ();
16416 }
16417
16418 static void
16419 s_change_sec (int sec)
16420 {
16421   segT seg;
16422
16423   /* The ELF backend needs to know that we are changing sections, so
16424      that .previous works correctly.  We could do something like check
16425      for an obj_section_change_hook macro, but that might be confusing
16426      as it would not be appropriate to use it in the section changing
16427      functions in read.c, since obj-elf.c intercepts those.  FIXME:
16428      This should be cleaner, somehow.  */
16429   obj_elf_section_change_hook ();
16430
16431   mips_emit_delays ();
16432
16433   switch (sec)
16434     {
16435     case 't':
16436       s_text (0);
16437       break;
16438     case 'd':
16439       s_data (0);
16440       break;
16441     case 'b':
16442       subseg_set (bss_section, (subsegT) get_absolute_expression ());
16443       demand_empty_rest_of_line ();
16444       break;
16445
16446     case 'r':
16447       seg = subseg_new (RDATA_SECTION_NAME,
16448                         (subsegT) get_absolute_expression ());
16449       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
16450                                               | SEC_READONLY | SEC_RELOC
16451                                               | SEC_DATA));
16452       if (strncmp (TARGET_OS, "elf", 3) != 0)
16453         record_alignment (seg, 4);
16454       demand_empty_rest_of_line ();
16455       break;
16456
16457     case 's':
16458       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
16459       bfd_set_section_flags (stdoutput, seg,
16460                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
16461       if (strncmp (TARGET_OS, "elf", 3) != 0)
16462         record_alignment (seg, 4);
16463       demand_empty_rest_of_line ();
16464       break;
16465
16466     case 'B':
16467       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
16468       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
16469       if (strncmp (TARGET_OS, "elf", 3) != 0)
16470         record_alignment (seg, 4);
16471       demand_empty_rest_of_line ();
16472       break;
16473     }
16474
16475   auto_align = 1;
16476 }
16477
16478 void
16479 s_change_section (int ignore ATTRIBUTE_UNUSED)
16480 {
16481   char *section_name;
16482   char c;
16483   char next_c = 0;
16484   int section_type;
16485   int section_flag;
16486   int section_entry_size;
16487   int section_alignment;
16488
16489   section_name = input_line_pointer;
16490   c = get_symbol_end ();
16491   if (c)
16492     next_c = *(input_line_pointer + 1);
16493
16494   /* Do we have .section Name<,"flags">?  */
16495   if (c != ',' || (c == ',' && next_c == '"'))
16496     {
16497       /* just after name is now '\0'.  */
16498       *input_line_pointer = c;
16499       input_line_pointer = section_name;
16500       obj_elf_section (ignore);
16501       return;
16502     }
16503   input_line_pointer++;
16504
16505   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
16506   if (c == ',')
16507     section_type = get_absolute_expression ();
16508   else
16509     section_type = 0;
16510   if (*input_line_pointer++ == ',')
16511     section_flag = get_absolute_expression ();
16512   else
16513     section_flag = 0;
16514   if (*input_line_pointer++ == ',')
16515     section_entry_size = get_absolute_expression ();
16516   else
16517     section_entry_size = 0;
16518   if (*input_line_pointer++ == ',')
16519     section_alignment = get_absolute_expression ();
16520   else
16521     section_alignment = 0;
16522   /* FIXME: really ignore?  */
16523   (void) section_alignment;
16524
16525   section_name = xstrdup (section_name);
16526
16527   /* When using the generic form of .section (as implemented by obj-elf.c),
16528      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
16529      traditionally had to fall back on the more common @progbits instead.
16530
16531      There's nothing really harmful in this, since bfd will correct
16532      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
16533      means that, for backwards compatibility, the special_section entries
16534      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
16535
16536      Even so, we shouldn't force users of the MIPS .section syntax to
16537      incorrectly label the sections as SHT_PROGBITS.  The best compromise
16538      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
16539      generic type-checking code.  */
16540   if (section_type == SHT_MIPS_DWARF)
16541     section_type = SHT_PROGBITS;
16542
16543   obj_elf_change_section (section_name, section_type, section_flag,
16544                           section_entry_size, 0, 0, 0);
16545
16546   if (now_seg->name != section_name)
16547     free (section_name);
16548 }
16549
16550 void
16551 mips_enable_auto_align (void)
16552 {
16553   auto_align = 1;
16554 }
16555
16556 static void
16557 s_cons (int log_size)
16558 {
16559   segment_info_type *si = seg_info (now_seg);
16560   struct insn_label_list *l = si->label_list;
16561
16562   mips_emit_delays ();
16563   if (log_size > 0 && auto_align)
16564     mips_align (log_size, 0, l);
16565   cons (1 << log_size);
16566   mips_clear_insn_labels ();
16567 }
16568
16569 static void
16570 s_float_cons (int type)
16571 {
16572   segment_info_type *si = seg_info (now_seg);
16573   struct insn_label_list *l = si->label_list;
16574
16575   mips_emit_delays ();
16576
16577   if (auto_align)
16578     {
16579       if (type == 'd')
16580         mips_align (3, 0, l);
16581       else
16582         mips_align (2, 0, l);
16583     }
16584
16585   float_cons (type);
16586   mips_clear_insn_labels ();
16587 }
16588
16589 /* Handle .globl.  We need to override it because on Irix 5 you are
16590    permitted to say
16591        .globl foo .text
16592    where foo is an undefined symbol, to mean that foo should be
16593    considered to be the address of a function.  */
16594
16595 static void
16596 s_mips_globl (int x ATTRIBUTE_UNUSED)
16597 {
16598   char *name;
16599   int c;
16600   symbolS *symbolP;
16601   flagword flag;
16602
16603   do
16604     {
16605       name = input_line_pointer;
16606       c = get_symbol_end ();
16607       symbolP = symbol_find_or_make (name);
16608       S_SET_EXTERNAL (symbolP);
16609
16610       *input_line_pointer = c;
16611       SKIP_WHITESPACE ();
16612
16613       /* On Irix 5, every global symbol that is not explicitly labelled as
16614          being a function is apparently labelled as being an object.  */
16615       flag = BSF_OBJECT;
16616
16617       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16618           && (*input_line_pointer != ','))
16619         {
16620           char *secname;
16621           asection *sec;
16622
16623           secname = input_line_pointer;
16624           c = get_symbol_end ();
16625           sec = bfd_get_section_by_name (stdoutput, secname);
16626           if (sec == NULL)
16627             as_bad (_("%s: no such section"), secname);
16628           *input_line_pointer = c;
16629
16630           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16631             flag = BSF_FUNCTION;
16632         }
16633
16634       symbol_get_bfdsym (symbolP)->flags |= flag;
16635
16636       c = *input_line_pointer;
16637       if (c == ',')
16638         {
16639           input_line_pointer++;
16640           SKIP_WHITESPACE ();
16641           if (is_end_of_line[(unsigned char) *input_line_pointer])
16642             c = '\n';
16643         }
16644     }
16645   while (c == ',');
16646
16647   demand_empty_rest_of_line ();
16648 }
16649
16650 static void
16651 s_option (int x ATTRIBUTE_UNUSED)
16652 {
16653   char *opt;
16654   char c;
16655
16656   opt = input_line_pointer;
16657   c = get_symbol_end ();
16658
16659   if (*opt == 'O')
16660     {
16661       /* FIXME: What does this mean?  */
16662     }
16663   else if (strncmp (opt, "pic", 3) == 0)
16664     {
16665       int i;
16666
16667       i = atoi (opt + 3);
16668       if (i == 0)
16669         mips_pic = NO_PIC;
16670       else if (i == 2)
16671         {
16672           mips_pic = SVR4_PIC;
16673           mips_abicalls = TRUE;
16674         }
16675       else
16676         as_bad (_(".option pic%d not supported"), i);
16677
16678       if (mips_pic == SVR4_PIC)
16679         {
16680           if (g_switch_seen && g_switch_value != 0)
16681             as_warn (_("-G may not be used with SVR4 PIC code"));
16682           g_switch_value = 0;
16683           bfd_set_gp_size (stdoutput, 0);
16684         }
16685     }
16686   else
16687     as_warn (_("Unrecognized option \"%s\""), opt);
16688
16689   *input_line_pointer = c;
16690   demand_empty_rest_of_line ();
16691 }
16692
16693 /* This structure is used to hold a stack of .set values.  */
16694
16695 struct mips_option_stack
16696 {
16697   struct mips_option_stack *next;
16698   struct mips_set_options options;
16699 };
16700
16701 static struct mips_option_stack *mips_opts_stack;
16702
16703 /* Handle the .set pseudo-op.  */
16704
16705 static void
16706 s_mipsset (int x ATTRIBUTE_UNUSED)
16707 {
16708   char *name = input_line_pointer, ch;
16709   const struct mips_ase *ase;
16710
16711   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16712     ++input_line_pointer;
16713   ch = *input_line_pointer;
16714   *input_line_pointer = '\0';
16715
16716   if (strcmp (name, "reorder") == 0)
16717     {
16718       if (mips_opts.noreorder)
16719         end_noreorder ();
16720     }
16721   else if (strcmp (name, "noreorder") == 0)
16722     {
16723       if (!mips_opts.noreorder)
16724         start_noreorder ();
16725     }
16726   else if (strncmp (name, "at=", 3) == 0)
16727     {
16728       char *s = name + 3;
16729
16730       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16731         as_bad (_("Unrecognized register name `%s'"), s);
16732     }
16733   else if (strcmp (name, "at") == 0)
16734     {
16735       mips_opts.at = ATREG;
16736     }
16737   else if (strcmp (name, "noat") == 0)
16738     {
16739       mips_opts.at = ZERO;
16740     }
16741   else if (strcmp (name, "macro") == 0)
16742     {
16743       mips_opts.warn_about_macros = 0;
16744     }
16745   else if (strcmp (name, "nomacro") == 0)
16746     {
16747       if (mips_opts.noreorder == 0)
16748         as_bad (_("`noreorder' must be set before `nomacro'"));
16749       mips_opts.warn_about_macros = 1;
16750     }
16751   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16752     {
16753       mips_opts.nomove = 0;
16754     }
16755   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16756     {
16757       mips_opts.nomove = 1;
16758     }
16759   else if (strcmp (name, "bopt") == 0)
16760     {
16761       mips_opts.nobopt = 0;
16762     }
16763   else if (strcmp (name, "nobopt") == 0)
16764     {
16765       mips_opts.nobopt = 1;
16766     }
16767   else if (strcmp (name, "gp=default") == 0)
16768     mips_opts.gp32 = file_mips_gp32;
16769   else if (strcmp (name, "gp=32") == 0)
16770     mips_opts.gp32 = 1;
16771   else if (strcmp (name, "gp=64") == 0)
16772     {
16773       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
16774         as_warn (_("%s isa does not support 64-bit registers"),
16775                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16776       mips_opts.gp32 = 0;
16777     }
16778   else if (strcmp (name, "fp=default") == 0)
16779     mips_opts.fp32 = file_mips_fp32;
16780   else if (strcmp (name, "fp=32") == 0)
16781     mips_opts.fp32 = 1;
16782   else if (strcmp (name, "fp=64") == 0)
16783     {
16784       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
16785         as_warn (_("%s isa does not support 64-bit floating point registers"),
16786                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16787       mips_opts.fp32 = 0;
16788     }
16789   else if (strcmp (name, "softfloat") == 0)
16790     mips_opts.soft_float = 1;
16791   else if (strcmp (name, "hardfloat") == 0)
16792     mips_opts.soft_float = 0;
16793   else if (strcmp (name, "singlefloat") == 0)
16794     mips_opts.single_float = 1;
16795   else if (strcmp (name, "doublefloat") == 0)
16796     mips_opts.single_float = 0;
16797   else if (strcmp (name, "mips16") == 0
16798            || strcmp (name, "MIPS-16") == 0)
16799     {
16800       if (mips_opts.micromips == 1)
16801         as_fatal (_("`mips16' cannot be used with `micromips'"));
16802       mips_opts.mips16 = 1;
16803     }
16804   else if (strcmp (name, "nomips16") == 0
16805            || strcmp (name, "noMIPS-16") == 0)
16806     mips_opts.mips16 = 0;
16807   else if (strcmp (name, "micromips") == 0)
16808     {
16809       if (mips_opts.mips16 == 1)
16810         as_fatal (_("`micromips' cannot be used with `mips16'"));
16811       mips_opts.micromips = 1;
16812     }
16813   else if (strcmp (name, "nomicromips") == 0)
16814     mips_opts.micromips = 0;
16815   else if (name[0] == 'n'
16816            && name[1] == 'o'
16817            && (ase = mips_lookup_ase (name + 2)))
16818     mips_set_ase (ase, FALSE);
16819   else if ((ase = mips_lookup_ase (name)))
16820     mips_set_ase (ase, TRUE);
16821   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16822     {
16823       int reset = 0;
16824
16825       /* Permit the user to change the ISA and architecture on the fly.
16826          Needless to say, misuse can cause serious problems.  */
16827       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16828         {
16829           reset = 1;
16830           mips_opts.isa = file_mips_isa;
16831           mips_opts.arch = file_mips_arch;
16832         }
16833       else if (strncmp (name, "arch=", 5) == 0)
16834         {
16835           const struct mips_cpu_info *p;
16836
16837           p = mips_parse_cpu("internal use", name + 5);
16838           if (!p)
16839             as_bad (_("unknown architecture %s"), name + 5);
16840           else
16841             {
16842               mips_opts.arch = p->cpu;
16843               mips_opts.isa = p->isa;
16844             }
16845         }
16846       else if (strncmp (name, "mips", 4) == 0)
16847         {
16848           const struct mips_cpu_info *p;
16849
16850           p = mips_parse_cpu("internal use", name);
16851           if (!p)
16852             as_bad (_("unknown ISA level %s"), name + 4);
16853           else
16854             {
16855               mips_opts.arch = p->cpu;
16856               mips_opts.isa = p->isa;
16857             }
16858         }
16859       else
16860         as_bad (_("unknown ISA or architecture %s"), name);
16861
16862       switch (mips_opts.isa)
16863         {
16864         case  0:
16865           break;
16866         case ISA_MIPS1:
16867         case ISA_MIPS2:
16868         case ISA_MIPS32:
16869         case ISA_MIPS32R2:
16870           mips_opts.gp32 = 1;
16871           mips_opts.fp32 = 1;
16872           break;
16873         case ISA_MIPS3:
16874         case ISA_MIPS4:
16875         case ISA_MIPS5:
16876         case ISA_MIPS64:
16877         case ISA_MIPS64R2:
16878           mips_opts.gp32 = 0;
16879           if (mips_opts.arch == CPU_R5900)
16880             {
16881                 mips_opts.fp32 = 1;
16882             }
16883           else
16884             {
16885           mips_opts.fp32 = 0;
16886             }
16887           break;
16888         default:
16889           as_bad (_("unknown ISA level %s"), name + 4);
16890           break;
16891         }
16892       if (reset)
16893         {
16894           mips_opts.gp32 = file_mips_gp32;
16895           mips_opts.fp32 = file_mips_fp32;
16896         }
16897     }
16898   else if (strcmp (name, "autoextend") == 0)
16899     mips_opts.noautoextend = 0;
16900   else if (strcmp (name, "noautoextend") == 0)
16901     mips_opts.noautoextend = 1;
16902   else if (strcmp (name, "insn32") == 0)
16903     mips_opts.insn32 = TRUE;
16904   else if (strcmp (name, "noinsn32") == 0)
16905     mips_opts.insn32 = FALSE;
16906   else if (strcmp (name, "push") == 0)
16907     {
16908       struct mips_option_stack *s;
16909
16910       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16911       s->next = mips_opts_stack;
16912       s->options = mips_opts;
16913       mips_opts_stack = s;
16914     }
16915   else if (strcmp (name, "pop") == 0)
16916     {
16917       struct mips_option_stack *s;
16918
16919       s = mips_opts_stack;
16920       if (s == NULL)
16921         as_bad (_(".set pop with no .set push"));
16922       else
16923         {
16924           /* If we're changing the reorder mode we need to handle
16925              delay slots correctly.  */
16926           if (s->options.noreorder && ! mips_opts.noreorder)
16927             start_noreorder ();
16928           else if (! s->options.noreorder && mips_opts.noreorder)
16929             end_noreorder ();
16930
16931           mips_opts = s->options;
16932           mips_opts_stack = s->next;
16933           free (s);
16934         }
16935     }
16936   else if (strcmp (name, "sym32") == 0)
16937     mips_opts.sym32 = TRUE;
16938   else if (strcmp (name, "nosym32") == 0)
16939     mips_opts.sym32 = FALSE;
16940   else if (strchr (name, ','))
16941     {
16942       /* Generic ".set" directive; use the generic handler.  */
16943       *input_line_pointer = ch;
16944       input_line_pointer = name;
16945       s_set (0);
16946       return;
16947     }
16948   else
16949     {
16950       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16951     }
16952   mips_check_isa_supports_ases ();
16953   *input_line_pointer = ch;
16954   demand_empty_rest_of_line ();
16955 }
16956
16957 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16958    .option pic2.  It means to generate SVR4 PIC calls.  */
16959
16960 static void
16961 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16962 {
16963   mips_pic = SVR4_PIC;
16964   mips_abicalls = TRUE;
16965
16966   if (g_switch_seen && g_switch_value != 0)
16967     as_warn (_("-G may not be used with SVR4 PIC code"));
16968   g_switch_value = 0;
16969
16970   bfd_set_gp_size (stdoutput, 0);
16971   demand_empty_rest_of_line ();
16972 }
16973
16974 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16975    PIC code.  It sets the $gp register for the function based on the
16976    function address, which is in the register named in the argument.
16977    This uses a relocation against _gp_disp, which is handled specially
16978    by the linker.  The result is:
16979         lui     $gp,%hi(_gp_disp)
16980         addiu   $gp,$gp,%lo(_gp_disp)
16981         addu    $gp,$gp,.cpload argument
16982    The .cpload argument is normally $25 == $t9.
16983
16984    The -mno-shared option changes this to:
16985         lui     $gp,%hi(__gnu_local_gp)
16986         addiu   $gp,$gp,%lo(__gnu_local_gp)
16987    and the argument is ignored.  This saves an instruction, but the
16988    resulting code is not position independent; it uses an absolute
16989    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16990    can go into an ordinary executable, but not into a shared library.  */
16991
16992 static void
16993 s_cpload (int ignore ATTRIBUTE_UNUSED)
16994 {
16995   expressionS ex;
16996   int reg;
16997   int in_shared;
16998
16999   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
17000      .cpload is ignored.  */
17001   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
17002     {
17003       s_ignore (0);
17004       return;
17005     }
17006
17007   if (mips_opts.mips16)
17008     {
17009       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
17010       ignore_rest_of_line ();
17011       return;
17012     }
17013
17014   /* .cpload should be in a .set noreorder section.  */
17015   if (mips_opts.noreorder == 0)
17016     as_warn (_(".cpload not in noreorder section"));
17017
17018   reg = tc_get_register (0);
17019
17020   /* If we need to produce a 64-bit address, we are better off using
17021      the default instruction sequence.  */
17022   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
17023
17024   ex.X_op = O_symbol;
17025   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
17026                                          "__gnu_local_gp");
17027   ex.X_op_symbol = NULL;
17028   ex.X_add_number = 0;
17029
17030   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
17031   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
17032
17033   mips_mark_labels ();
17034   mips_assembling_insn = TRUE;
17035
17036   macro_start ();
17037   macro_build_lui (&ex, mips_gp_register);
17038   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
17039                mips_gp_register, BFD_RELOC_LO16);
17040   if (in_shared)
17041     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
17042                  mips_gp_register, reg);
17043   macro_end ();
17044
17045   mips_assembling_insn = FALSE;
17046   demand_empty_rest_of_line ();
17047 }
17048
17049 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
17050      .cpsetup $reg1, offset|$reg2, label
17051
17052    If offset is given, this results in:
17053      sd         $gp, offset($sp)
17054      lui        $gp, %hi(%neg(%gp_rel(label)))
17055      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
17056      daddu      $gp, $gp, $reg1
17057
17058    If $reg2 is given, this results in:
17059      daddu      $reg2, $gp, $0
17060      lui        $gp, %hi(%neg(%gp_rel(label)))
17061      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
17062      daddu      $gp, $gp, $reg1
17063    $reg1 is normally $25 == $t9.
17064
17065    The -mno-shared option replaces the last three instructions with
17066         lui     $gp,%hi(_gp)
17067         addiu   $gp,$gp,%lo(_gp)  */
17068
17069 static void
17070 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
17071 {
17072   expressionS ex_off;
17073   expressionS ex_sym;
17074   int reg1;
17075
17076   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
17077      We also need NewABI support.  */
17078   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17079     {
17080       s_ignore (0);
17081       return;
17082     }
17083
17084   if (mips_opts.mips16)
17085     {
17086       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
17087       ignore_rest_of_line ();
17088       return;
17089     }
17090
17091   reg1 = tc_get_register (0);
17092   SKIP_WHITESPACE ();
17093   if (*input_line_pointer != ',')
17094     {
17095       as_bad (_("missing argument separator ',' for .cpsetup"));
17096       return;
17097     }
17098   else
17099     ++input_line_pointer;
17100   SKIP_WHITESPACE ();
17101   if (*input_line_pointer == '$')
17102     {
17103       mips_cpreturn_register = tc_get_register (0);
17104       mips_cpreturn_offset = -1;
17105     }
17106   else
17107     {
17108       mips_cpreturn_offset = get_absolute_expression ();
17109       mips_cpreturn_register = -1;
17110     }
17111   SKIP_WHITESPACE ();
17112   if (*input_line_pointer != ',')
17113     {
17114       as_bad (_("missing argument separator ',' for .cpsetup"));
17115       return;
17116     }
17117   else
17118     ++input_line_pointer;
17119   SKIP_WHITESPACE ();
17120   expression (&ex_sym);
17121
17122   mips_mark_labels ();
17123   mips_assembling_insn = TRUE;
17124
17125   macro_start ();
17126   if (mips_cpreturn_register == -1)
17127     {
17128       ex_off.X_op = O_constant;
17129       ex_off.X_add_symbol = NULL;
17130       ex_off.X_op_symbol = NULL;
17131       ex_off.X_add_number = mips_cpreturn_offset;
17132
17133       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
17134                    BFD_RELOC_LO16, SP);
17135     }
17136   else
17137     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
17138                  mips_gp_register, 0);
17139
17140   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
17141     {
17142       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
17143                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
17144                    BFD_RELOC_HI16_S);
17145
17146       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
17147                    mips_gp_register, -1, BFD_RELOC_GPREL16,
17148                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
17149
17150       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
17151                    mips_gp_register, reg1);
17152     }
17153   else
17154     {
17155       expressionS ex;
17156
17157       ex.X_op = O_symbol;
17158       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
17159       ex.X_op_symbol = NULL;
17160       ex.X_add_number = 0;
17161
17162       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
17163       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
17164
17165       macro_build_lui (&ex, mips_gp_register);
17166       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
17167                    mips_gp_register, BFD_RELOC_LO16);
17168     }
17169
17170   macro_end ();
17171
17172   mips_assembling_insn = FALSE;
17173   demand_empty_rest_of_line ();
17174 }
17175
17176 static void
17177 s_cplocal (int ignore ATTRIBUTE_UNUSED)
17178 {
17179   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
17180      .cplocal is ignored.  */
17181   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17182     {
17183       s_ignore (0);
17184       return;
17185     }
17186
17187   if (mips_opts.mips16)
17188     {
17189       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
17190       ignore_rest_of_line ();
17191       return;
17192     }
17193
17194   mips_gp_register = tc_get_register (0);
17195   demand_empty_rest_of_line ();
17196 }
17197
17198 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
17199    offset from $sp.  The offset is remembered, and after making a PIC
17200    call $gp is restored from that location.  */
17201
17202 static void
17203 s_cprestore (int ignore ATTRIBUTE_UNUSED)
17204 {
17205   expressionS ex;
17206
17207   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
17208      .cprestore is ignored.  */
17209   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
17210     {
17211       s_ignore (0);
17212       return;
17213     }
17214
17215   if (mips_opts.mips16)
17216     {
17217       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
17218       ignore_rest_of_line ();
17219       return;
17220     }
17221
17222   mips_cprestore_offset = get_absolute_expression ();
17223   mips_cprestore_valid = 1;
17224
17225   ex.X_op = O_constant;
17226   ex.X_add_symbol = NULL;
17227   ex.X_op_symbol = NULL;
17228   ex.X_add_number = mips_cprestore_offset;
17229
17230   mips_mark_labels ();
17231   mips_assembling_insn = TRUE;
17232
17233   macro_start ();
17234   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
17235                                 SP, HAVE_64BIT_ADDRESSES);
17236   macro_end ();
17237
17238   mips_assembling_insn = FALSE;
17239   demand_empty_rest_of_line ();
17240 }
17241
17242 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
17243    was given in the preceding .cpsetup, it results in:
17244      ld         $gp, offset($sp)
17245
17246    If a register $reg2 was given there, it results in:
17247      daddu      $gp, $reg2, $0  */
17248
17249 static void
17250 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
17251 {
17252   expressionS ex;
17253
17254   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
17255      We also need NewABI support.  */
17256   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17257     {
17258       s_ignore (0);
17259       return;
17260     }
17261
17262   if (mips_opts.mips16)
17263     {
17264       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
17265       ignore_rest_of_line ();
17266       return;
17267     }
17268
17269   mips_mark_labels ();
17270   mips_assembling_insn = TRUE;
17271
17272   macro_start ();
17273   if (mips_cpreturn_register == -1)
17274     {
17275       ex.X_op = O_constant;
17276       ex.X_add_symbol = NULL;
17277       ex.X_op_symbol = NULL;
17278       ex.X_add_number = mips_cpreturn_offset;
17279
17280       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
17281     }
17282   else
17283     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
17284                  mips_cpreturn_register, 0);
17285   macro_end ();
17286
17287   mips_assembling_insn = FALSE;
17288   demand_empty_rest_of_line ();
17289 }
17290
17291 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
17292    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
17293    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
17294    debug information or MIPS16 TLS.  */
17295
17296 static void
17297 s_tls_rel_directive (const size_t bytes, const char *dirstr,
17298                      bfd_reloc_code_real_type rtype)
17299 {
17300   expressionS ex;
17301   char *p;
17302
17303   expression (&ex);
17304
17305   if (ex.X_op != O_symbol)
17306     {
17307       as_bad (_("Unsupported use of %s"), dirstr);
17308       ignore_rest_of_line ();
17309     }
17310
17311   p = frag_more (bytes);
17312   md_number_to_chars (p, 0, bytes);
17313   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
17314   demand_empty_rest_of_line ();
17315   mips_clear_insn_labels ();
17316 }
17317
17318 /* Handle .dtprelword.  */
17319
17320 static void
17321 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
17322 {
17323   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
17324 }
17325
17326 /* Handle .dtpreldword.  */
17327
17328 static void
17329 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
17330 {
17331   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
17332 }
17333
17334 /* Handle .tprelword.  */
17335
17336 static void
17337 s_tprelword (int ignore ATTRIBUTE_UNUSED)
17338 {
17339   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
17340 }
17341
17342 /* Handle .tpreldword.  */
17343
17344 static void
17345 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
17346 {
17347   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
17348 }
17349
17350 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
17351    code.  It sets the offset to use in gp_rel relocations.  */
17352
17353 static void
17354 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
17355 {
17356   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
17357      We also need NewABI support.  */
17358   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
17359     {
17360       s_ignore (0);
17361       return;
17362     }
17363
17364   mips_gprel_offset = get_absolute_expression ();
17365
17366   demand_empty_rest_of_line ();
17367 }
17368
17369 /* Handle the .gpword pseudo-op.  This is used when generating PIC
17370    code.  It generates a 32 bit GP relative reloc.  */
17371
17372 static void
17373 s_gpword (int ignore ATTRIBUTE_UNUSED)
17374 {
17375   segment_info_type *si;
17376   struct insn_label_list *l;
17377   expressionS ex;
17378   char *p;
17379
17380   /* When not generating PIC code, this is treated as .word.  */
17381   if (mips_pic != SVR4_PIC)
17382     {
17383       s_cons (2);
17384       return;
17385     }
17386
17387   si = seg_info (now_seg);
17388   l = si->label_list;
17389   mips_emit_delays ();
17390   if (auto_align)
17391     mips_align (2, 0, l);
17392
17393   expression (&ex);
17394   mips_clear_insn_labels ();
17395
17396   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17397     {
17398       as_bad (_("Unsupported use of .gpword"));
17399       ignore_rest_of_line ();
17400     }
17401
17402   p = frag_more (4);
17403   md_number_to_chars (p, 0, 4);
17404   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17405                BFD_RELOC_GPREL32);
17406
17407   demand_empty_rest_of_line ();
17408 }
17409
17410 static void
17411 s_gpdword (int ignore ATTRIBUTE_UNUSED)
17412 {
17413   segment_info_type *si;
17414   struct insn_label_list *l;
17415   expressionS ex;
17416   char *p;
17417
17418   /* When not generating PIC code, this is treated as .dword.  */
17419   if (mips_pic != SVR4_PIC)
17420     {
17421       s_cons (3);
17422       return;
17423     }
17424
17425   si = seg_info (now_seg);
17426   l = si->label_list;
17427   mips_emit_delays ();
17428   if (auto_align)
17429     mips_align (3, 0, l);
17430
17431   expression (&ex);
17432   mips_clear_insn_labels ();
17433
17434   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17435     {
17436       as_bad (_("Unsupported use of .gpdword"));
17437       ignore_rest_of_line ();
17438     }
17439
17440   p = frag_more (8);
17441   md_number_to_chars (p, 0, 8);
17442   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17443                BFD_RELOC_GPREL32)->fx_tcbit = 1;
17444
17445   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
17446   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
17447            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
17448
17449   demand_empty_rest_of_line ();
17450 }
17451
17452 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
17453    tables.  It generates a R_MIPS_EH reloc.  */
17454
17455 static void
17456 s_ehword (int ignore ATTRIBUTE_UNUSED)
17457 {
17458   expressionS ex;
17459   char *p;
17460
17461   mips_emit_delays ();
17462
17463   expression (&ex);
17464   mips_clear_insn_labels ();
17465
17466   if (ex.X_op != O_symbol || ex.X_add_number != 0)
17467     {
17468       as_bad (_("Unsupported use of .ehword"));
17469       ignore_rest_of_line ();
17470     }
17471
17472   p = frag_more (4);
17473   md_number_to_chars (p, 0, 4);
17474   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
17475                BFD_RELOC_MIPS_EH);
17476
17477   demand_empty_rest_of_line ();
17478 }
17479
17480 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
17481    tables in SVR4 PIC code.  */
17482
17483 static void
17484 s_cpadd (int ignore ATTRIBUTE_UNUSED)
17485 {
17486   int reg;
17487
17488   /* This is ignored when not generating SVR4 PIC code.  */
17489   if (mips_pic != SVR4_PIC)
17490     {
17491       s_ignore (0);
17492       return;
17493     }
17494
17495   mips_mark_labels ();
17496   mips_assembling_insn = TRUE;
17497
17498   /* Add $gp to the register named as an argument.  */
17499   macro_start ();
17500   reg = tc_get_register (0);
17501   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
17502   macro_end ();
17503
17504   mips_assembling_insn = FALSE;
17505   demand_empty_rest_of_line ();
17506 }
17507
17508 /* Handle the .insn pseudo-op.  This marks instruction labels in
17509    mips16/micromips mode.  This permits the linker to handle them specially,
17510    such as generating jalx instructions when needed.  We also make
17511    them odd for the duration of the assembly, in order to generate the
17512    right sort of code.  We will make them even in the adjust_symtab
17513    routine, while leaving them marked.  This is convenient for the
17514    debugger and the disassembler.  The linker knows to make them odd
17515    again.  */
17516
17517 static void
17518 s_insn (int ignore ATTRIBUTE_UNUSED)
17519 {
17520   mips_mark_labels ();
17521
17522   demand_empty_rest_of_line ();
17523 }
17524
17525 /* Handle the .nan pseudo-op.  */
17526
17527 static void
17528 s_nan (int ignore ATTRIBUTE_UNUSED)
17529 {
17530   static const char str_legacy[] = "legacy";
17531   static const char str_2008[] = "2008";
17532   size_t i;
17533
17534   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
17535
17536   if (i == sizeof (str_2008) - 1
17537       && memcmp (input_line_pointer, str_2008, i) == 0)
17538     mips_flag_nan2008 = TRUE;
17539   else if (i == sizeof (str_legacy) - 1
17540            && memcmp (input_line_pointer, str_legacy, i) == 0)
17541     mips_flag_nan2008 = FALSE;
17542   else
17543     as_bad (_("Bad .nan directive"));
17544
17545   input_line_pointer += i;
17546   demand_empty_rest_of_line ();
17547 }
17548
17549 /* Handle a .stab[snd] directive.  Ideally these directives would be
17550    implemented in a transparent way, so that removing them would not
17551    have any effect on the generated instructions.  However, s_stab
17552    internally changes the section, so in practice we need to decide
17553    now whether the preceding label marks compressed code.  We do not
17554    support changing the compression mode of a label after a .stab*
17555    directive, such as in:
17556
17557    foo:
17558         .stabs ...
17559         .set mips16
17560
17561    so the current mode wins.  */
17562
17563 static void
17564 s_mips_stab (int type)
17565 {
17566   mips_mark_labels ();
17567   s_stab (type);
17568 }
17569
17570 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
17571
17572 static void
17573 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
17574 {
17575   char *name;
17576   int c;
17577   symbolS *symbolP;
17578   expressionS exp;
17579
17580   name = input_line_pointer;
17581   c = get_symbol_end ();
17582   symbolP = symbol_find_or_make (name);
17583   S_SET_WEAK (symbolP);
17584   *input_line_pointer = c;
17585
17586   SKIP_WHITESPACE ();
17587
17588   if (! is_end_of_line[(unsigned char) *input_line_pointer])
17589     {
17590       if (S_IS_DEFINED (symbolP))
17591         {
17592           as_bad (_("ignoring attempt to redefine symbol %s"),
17593                   S_GET_NAME (symbolP));
17594           ignore_rest_of_line ();
17595           return;
17596         }
17597
17598       if (*input_line_pointer == ',')
17599         {
17600           ++input_line_pointer;
17601           SKIP_WHITESPACE ();
17602         }
17603
17604       expression (&exp);
17605       if (exp.X_op != O_symbol)
17606         {
17607           as_bad (_("bad .weakext directive"));
17608           ignore_rest_of_line ();
17609           return;
17610         }
17611       symbol_set_value_expression (symbolP, &exp);
17612     }
17613
17614   demand_empty_rest_of_line ();
17615 }
17616
17617 /* Parse a register string into a number.  Called from the ECOFF code
17618    to parse .frame.  The argument is non-zero if this is the frame
17619    register, so that we can record it in mips_frame_reg.  */
17620
17621 int
17622 tc_get_register (int frame)
17623 {
17624   unsigned int reg;
17625
17626   SKIP_WHITESPACE ();
17627   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17628     reg = 0;
17629   if (frame)
17630     {
17631       mips_frame_reg = reg != 0 ? reg : SP;
17632       mips_frame_reg_valid = 1;
17633       mips_cprestore_valid = 0;
17634     }
17635   return reg;
17636 }
17637
17638 valueT
17639 md_section_align (asection *seg, valueT addr)
17640 {
17641   int align = bfd_get_section_alignment (stdoutput, seg);
17642
17643   /* We don't need to align ELF sections to the full alignment.
17644      However, Irix 5 may prefer that we align them at least to a 16
17645      byte boundary.  We don't bother to align the sections if we
17646      are targeted for an embedded system.  */
17647   if (strncmp (TARGET_OS, "elf", 3) == 0)
17648     return addr;
17649   if (align > 4)
17650     align = 4;
17651
17652   return ((addr + (1 << align) - 1) & (-1 << align));
17653 }
17654
17655 /* Utility routine, called from above as well.  If called while the
17656    input file is still being read, it's only an approximation.  (For
17657    example, a symbol may later become defined which appeared to be
17658    undefined earlier.)  */
17659
17660 static int
17661 nopic_need_relax (symbolS *sym, int before_relaxing)
17662 {
17663   if (sym == 0)
17664     return 0;
17665
17666   if (g_switch_value > 0)
17667     {
17668       const char *symname;
17669       int change;
17670
17671       /* Find out whether this symbol can be referenced off the $gp
17672          register.  It can be if it is smaller than the -G size or if
17673          it is in the .sdata or .sbss section.  Certain symbols can
17674          not be referenced off the $gp, although it appears as though
17675          they can.  */
17676       symname = S_GET_NAME (sym);
17677       if (symname != (const char *) NULL
17678           && (strcmp (symname, "eprol") == 0
17679               || strcmp (symname, "etext") == 0
17680               || strcmp (symname, "_gp") == 0
17681               || strcmp (symname, "edata") == 0
17682               || strcmp (symname, "_fbss") == 0
17683               || strcmp (symname, "_fdata") == 0
17684               || strcmp (symname, "_ftext") == 0
17685               || strcmp (symname, "end") == 0
17686               || strcmp (symname, "_gp_disp") == 0))
17687         change = 1;
17688       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17689                && (0
17690 #ifndef NO_ECOFF_DEBUGGING
17691                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17692                        && (symbol_get_obj (sym)->ecoff_extern_size
17693                            <= g_switch_value))
17694 #endif
17695                    /* We must defer this decision until after the whole
17696                       file has been read, since there might be a .extern
17697                       after the first use of this symbol.  */
17698                    || (before_relaxing
17699 #ifndef NO_ECOFF_DEBUGGING
17700                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17701 #endif
17702                        && S_GET_VALUE (sym) == 0)
17703                    || (S_GET_VALUE (sym) != 0
17704                        && S_GET_VALUE (sym) <= g_switch_value)))
17705         change = 0;
17706       else
17707         {
17708           const char *segname;
17709
17710           segname = segment_name (S_GET_SEGMENT (sym));
17711           gas_assert (strcmp (segname, ".lit8") != 0
17712                   && strcmp (segname, ".lit4") != 0);
17713           change = (strcmp (segname, ".sdata") != 0
17714                     && strcmp (segname, ".sbss") != 0
17715                     && strncmp (segname, ".sdata.", 7) != 0
17716                     && strncmp (segname, ".sbss.", 6) != 0
17717                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17718                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17719         }
17720       return change;
17721     }
17722   else
17723     /* We are not optimizing for the $gp register.  */
17724     return 1;
17725 }
17726
17727
17728 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17729
17730 static bfd_boolean
17731 pic_need_relax (symbolS *sym, asection *segtype)
17732 {
17733   asection *symsec;
17734
17735   /* Handle the case of a symbol equated to another symbol.  */
17736   while (symbol_equated_reloc_p (sym))
17737     {
17738       symbolS *n;
17739
17740       /* It's possible to get a loop here in a badly written program.  */
17741       n = symbol_get_value_expression (sym)->X_add_symbol;
17742       if (n == sym)
17743         break;
17744       sym = n;
17745     }
17746
17747   if (symbol_section_p (sym))
17748     return TRUE;
17749
17750   symsec = S_GET_SEGMENT (sym);
17751
17752   /* This must duplicate the test in adjust_reloc_syms.  */
17753   return (!bfd_is_und_section (symsec)
17754           && !bfd_is_abs_section (symsec)
17755           && !bfd_is_com_section (symsec)
17756           && !s_is_linkonce (sym, segtype)
17757           /* A global or weak symbol is treated as external.  */
17758           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17759 }
17760
17761
17762 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17763    extended opcode.  SEC is the section the frag is in.  */
17764
17765 static int
17766 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17767 {
17768   int type;
17769   const struct mips16_immed_operand *op;
17770   offsetT val;
17771   int mintiny, maxtiny;
17772   segT symsec;
17773   fragS *sym_frag;
17774
17775   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17776     return 0;
17777   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17778     return 1;
17779
17780   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17781   op = mips16_immed_operands;
17782   while (op->type != type)
17783     {
17784       ++op;
17785       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
17786     }
17787
17788   if (op->unsp)
17789     {
17790       if (type == '<' || type == '>' || type == '[' || type == ']')
17791         {
17792           mintiny = 1;
17793           maxtiny = 1 << op->nbits;
17794         }
17795       else
17796         {
17797           mintiny = 0;
17798           maxtiny = (1 << op->nbits) - 1;
17799         }
17800     }
17801   else
17802     {
17803       mintiny = - (1 << (op->nbits - 1));
17804       maxtiny = (1 << (op->nbits - 1)) - 1;
17805     }
17806
17807   sym_frag = symbol_get_frag (fragp->fr_symbol);
17808   val = S_GET_VALUE (fragp->fr_symbol);
17809   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17810
17811   if (op->pcrel)
17812     {
17813       addressT addr;
17814
17815       /* We won't have the section when we are called from
17816          mips_relax_frag.  However, we will always have been called
17817          from md_estimate_size_before_relax first.  If this is a
17818          branch to a different section, we mark it as such.  If SEC is
17819          NULL, and the frag is not marked, then it must be a branch to
17820          the same section.  */
17821       if (sec == NULL)
17822         {
17823           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17824             return 1;
17825         }
17826       else
17827         {
17828           /* Must have been called from md_estimate_size_before_relax.  */
17829           if (symsec != sec)
17830             {
17831               fragp->fr_subtype =
17832                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17833
17834               /* FIXME: We should support this, and let the linker
17835                  catch branches and loads that are out of range.  */
17836               as_bad_where (fragp->fr_file, fragp->fr_line,
17837                             _("unsupported PC relative reference to different section"));
17838
17839               return 1;
17840             }
17841           if (fragp != sym_frag && sym_frag->fr_address == 0)
17842             /* Assume non-extended on the first relaxation pass.
17843                The address we have calculated will be bogus if this is
17844                a forward branch to another frag, as the forward frag
17845                will have fr_address == 0.  */
17846             return 0;
17847         }
17848
17849       /* In this case, we know for sure that the symbol fragment is in
17850          the same section.  If the relax_marker of the symbol fragment
17851          differs from the relax_marker of this fragment, we have not
17852          yet adjusted the symbol fragment fr_address.  We want to add
17853          in STRETCH in order to get a better estimate of the address.
17854          This particularly matters because of the shift bits.  */
17855       if (stretch != 0
17856           && sym_frag->relax_marker != fragp->relax_marker)
17857         {
17858           fragS *f;
17859
17860           /* Adjust stretch for any alignment frag.  Note that if have
17861              been expanding the earlier code, the symbol may be
17862              defined in what appears to be an earlier frag.  FIXME:
17863              This doesn't handle the fr_subtype field, which specifies
17864              a maximum number of bytes to skip when doing an
17865              alignment.  */
17866           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17867             {
17868               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17869                 {
17870                   if (stretch < 0)
17871                     stretch = - ((- stretch)
17872                                  & ~ ((1 << (int) f->fr_offset) - 1));
17873                   else
17874                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17875                   if (stretch == 0)
17876                     break;
17877                 }
17878             }
17879           if (f != NULL)
17880             val += stretch;
17881         }
17882
17883       addr = fragp->fr_address + fragp->fr_fix;
17884
17885       /* The base address rules are complicated.  The base address of
17886          a branch is the following instruction.  The base address of a
17887          PC relative load or add is the instruction itself, but if it
17888          is in a delay slot (in which case it can not be extended) use
17889          the address of the instruction whose delay slot it is in.  */
17890       if (type == 'p' || type == 'q')
17891         {
17892           addr += 2;
17893
17894           /* If we are currently assuming that this frag should be
17895              extended, then, the current address is two bytes
17896              higher.  */
17897           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17898             addr += 2;
17899
17900           /* Ignore the low bit in the target, since it will be set
17901              for a text label.  */
17902           if ((val & 1) != 0)
17903             --val;
17904         }
17905       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17906         addr -= 4;
17907       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17908         addr -= 2;
17909
17910       val -= addr & ~ ((1 << op->shift) - 1);
17911
17912       /* Branch offsets have an implicit 0 in the lowest bit.  */
17913       if (type == 'p' || type == 'q')
17914         val /= 2;
17915
17916       /* If any of the shifted bits are set, we must use an extended
17917          opcode.  If the address depends on the size of this
17918          instruction, this can lead to a loop, so we arrange to always
17919          use an extended opcode.  We only check this when we are in
17920          the main relaxation loop, when SEC is NULL.  */
17921       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17922         {
17923           fragp->fr_subtype =
17924             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17925           return 1;
17926         }
17927
17928       /* If we are about to mark a frag as extended because the value
17929          is precisely maxtiny + 1, then there is a chance of an
17930          infinite loop as in the following code:
17931              la $4,foo
17932              .skip      1020
17933              .align     2
17934            foo:
17935          In this case when the la is extended, foo is 0x3fc bytes
17936          away, so the la can be shrunk, but then foo is 0x400 away, so
17937          the la must be extended.  To avoid this loop, we mark the
17938          frag as extended if it was small, and is about to become
17939          extended with a value of maxtiny + 1.  */
17940       if (val == ((maxtiny + 1) << op->shift)
17941           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17942           && sec == NULL)
17943         {
17944           fragp->fr_subtype =
17945             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17946           return 1;
17947         }
17948     }
17949   else if (symsec != absolute_section && sec != NULL)
17950     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17951
17952   if ((val & ((1 << op->shift) - 1)) != 0
17953       || val < (mintiny << op->shift)
17954       || val > (maxtiny << op->shift))
17955     return 1;
17956   else
17957     return 0;
17958 }
17959
17960 /* Compute the length of a branch sequence, and adjust the
17961    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17962    worst-case length is computed, with UPDATE being used to indicate
17963    whether an unconditional (-1), branch-likely (+1) or regular (0)
17964    branch is to be computed.  */
17965 static int
17966 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17967 {
17968   bfd_boolean toofar;
17969   int length;
17970
17971   if (fragp
17972       && S_IS_DEFINED (fragp->fr_symbol)
17973       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17974     {
17975       addressT addr;
17976       offsetT val;
17977
17978       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17979
17980       addr = fragp->fr_address + fragp->fr_fix + 4;
17981
17982       val -= addr;
17983
17984       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17985     }
17986   else if (fragp)
17987     /* If the symbol is not defined or it's in a different segment,
17988        assume the user knows what's going on and emit a short
17989        branch.  */
17990     toofar = FALSE;
17991   else
17992     toofar = TRUE;
17993
17994   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17995     fragp->fr_subtype
17996       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17997                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17998                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17999                              RELAX_BRANCH_LINK (fragp->fr_subtype),
18000                              toofar);
18001
18002   length = 4;
18003   if (toofar)
18004     {
18005       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
18006         length += 8;
18007
18008       if (mips_pic != NO_PIC)
18009         {
18010           /* Additional space for PIC loading of target address.  */
18011           length += 8;
18012           if (mips_opts.isa == ISA_MIPS1)
18013             /* Additional space for $at-stabilizing nop.  */
18014             length += 4;
18015         }
18016
18017       /* If branch is conditional.  */
18018       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
18019         length += 8;
18020     }
18021
18022   return length;
18023 }
18024
18025 /* Compute the length of a branch sequence, and adjust the
18026    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
18027    worst-case length is computed, with UPDATE being used to indicate
18028    whether an unconditional (-1), or regular (0) branch is to be
18029    computed.  */
18030
18031 static int
18032 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
18033 {
18034   bfd_boolean toofar;
18035   int length;
18036
18037   if (fragp
18038       && S_IS_DEFINED (fragp->fr_symbol)
18039       && sec == S_GET_SEGMENT (fragp->fr_symbol))
18040     {
18041       addressT addr;
18042       offsetT val;
18043
18044       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18045       /* Ignore the low bit in the target, since it will be set
18046          for a text label.  */
18047       if ((val & 1) != 0)
18048         --val;
18049
18050       addr = fragp->fr_address + fragp->fr_fix + 4;
18051
18052       val -= addr;
18053
18054       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
18055     }
18056   else if (fragp)
18057     /* If the symbol is not defined or it's in a different segment,
18058        assume the user knows what's going on and emit a short
18059        branch.  */
18060     toofar = FALSE;
18061   else
18062     toofar = TRUE;
18063
18064   if (fragp && update
18065       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18066     fragp->fr_subtype = (toofar
18067                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
18068                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
18069
18070   length = 4;
18071   if (toofar)
18072     {
18073       bfd_boolean compact_known = fragp != NULL;
18074       bfd_boolean compact = FALSE;
18075       bfd_boolean uncond;
18076
18077       if (compact_known)
18078         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18079       if (fragp)
18080         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
18081       else
18082         uncond = update < 0;
18083
18084       /* If label is out of range, we turn branch <br>:
18085
18086                 <br>    label                   # 4 bytes
18087             0:
18088
18089          into:
18090
18091                 j       label                   # 4 bytes
18092                 nop                             # 2 bytes if compact && !PIC
18093             0:
18094        */
18095       if (mips_pic == NO_PIC && (!compact_known || compact))
18096         length += 2;
18097
18098       /* If assembling PIC code, we further turn:
18099
18100                         j       label                   # 4 bytes
18101
18102          into:
18103
18104                         lw/ld   at, %got(label)(gp)     # 4 bytes
18105                         d/addiu at, %lo(label)          # 4 bytes
18106                         jr/c    at                      # 2 bytes
18107        */
18108       if (mips_pic != NO_PIC)
18109         length += 6;
18110
18111       /* If branch <br> is conditional, we prepend negated branch <brneg>:
18112
18113                         <brneg> 0f                      # 4 bytes
18114                         nop                             # 2 bytes if !compact
18115        */
18116       if (!uncond)
18117         length += (compact_known && compact) ? 4 : 6;
18118     }
18119
18120   return length;
18121 }
18122
18123 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
18124    bit accordingly.  */
18125
18126 static int
18127 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
18128 {
18129   bfd_boolean toofar;
18130
18131   if (fragp
18132       && S_IS_DEFINED (fragp->fr_symbol)
18133       && sec == S_GET_SEGMENT (fragp->fr_symbol))
18134     {
18135       addressT addr;
18136       offsetT val;
18137       int type;
18138
18139       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
18140       /* Ignore the low bit in the target, since it will be set
18141          for a text label.  */
18142       if ((val & 1) != 0)
18143         --val;
18144
18145       /* Assume this is a 2-byte branch.  */
18146       addr = fragp->fr_address + fragp->fr_fix + 2;
18147
18148       /* We try to avoid the infinite loop by not adding 2 more bytes for
18149          long branches.  */
18150
18151       val -= addr;
18152
18153       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18154       if (type == 'D')
18155         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
18156       else if (type == 'E')
18157         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
18158       else
18159         abort ();
18160     }
18161   else
18162     /* If the symbol is not defined or it's in a different segment,
18163        we emit a normal 32-bit branch.  */
18164     toofar = TRUE;
18165
18166   if (fragp && update
18167       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18168     fragp->fr_subtype
18169       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
18170                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
18171
18172   if (toofar)
18173     return 4;
18174
18175   return 2;
18176 }
18177
18178 /* Estimate the size of a frag before relaxing.  Unless this is the
18179    mips16, we are not really relaxing here, and the final size is
18180    encoded in the subtype information.  For the mips16, we have to
18181    decide whether we are using an extended opcode or not.  */
18182
18183 int
18184 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
18185 {
18186   int change;
18187
18188   if (RELAX_BRANCH_P (fragp->fr_subtype))
18189     {
18190
18191       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
18192
18193       return fragp->fr_var;
18194     }
18195
18196   if (RELAX_MIPS16_P (fragp->fr_subtype))
18197     /* We don't want to modify the EXTENDED bit here; it might get us
18198        into infinite loops.  We change it only in mips_relax_frag().  */
18199     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
18200
18201   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18202     {
18203       int length = 4;
18204
18205       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18206         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
18207       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18208         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
18209       fragp->fr_var = length;
18210
18211       return length;
18212     }
18213
18214   if (mips_pic == NO_PIC)
18215     change = nopic_need_relax (fragp->fr_symbol, 0);
18216   else if (mips_pic == SVR4_PIC)
18217     change = pic_need_relax (fragp->fr_symbol, segtype);
18218   else if (mips_pic == VXWORKS_PIC)
18219     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
18220     change = 0;
18221   else
18222     abort ();
18223
18224   if (change)
18225     {
18226       fragp->fr_subtype |= RELAX_USE_SECOND;
18227       return -RELAX_FIRST (fragp->fr_subtype);
18228     }
18229   else
18230     return -RELAX_SECOND (fragp->fr_subtype);
18231 }
18232
18233 /* This is called to see whether a reloc against a defined symbol
18234    should be converted into a reloc against a section.  */
18235
18236 int
18237 mips_fix_adjustable (fixS *fixp)
18238 {
18239   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
18240       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18241     return 0;
18242
18243   if (fixp->fx_addsy == NULL)
18244     return 1;
18245
18246   /* If symbol SYM is in a mergeable section, relocations of the form
18247      SYM + 0 can usually be made section-relative.  The mergeable data
18248      is then identified by the section offset rather than by the symbol.
18249
18250      However, if we're generating REL LO16 relocations, the offset is split
18251      between the LO16 and parterning high part relocation.  The linker will
18252      need to recalculate the complete offset in order to correctly identify
18253      the merge data.
18254
18255      The linker has traditionally not looked for the parterning high part
18256      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
18257      placed anywhere.  Rather than break backwards compatibility by changing
18258      this, it seems better not to force the issue, and instead keep the
18259      original symbol.  This will work with either linker behavior.  */
18260   if ((lo16_reloc_p (fixp->fx_r_type)
18261        || reloc_needs_lo_p (fixp->fx_r_type))
18262       && HAVE_IN_PLACE_ADDENDS
18263       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
18264     return 0;
18265
18266   /* There is no place to store an in-place offset for JALR relocations.
18267      Likewise an in-range offset of limited PC-relative relocations may
18268      overflow the in-place relocatable field if recalculated against the
18269      start address of the symbol's containing section.  */
18270   if (HAVE_IN_PLACE_ADDENDS
18271       && (limited_pcrel_reloc_p (fixp->fx_r_type)
18272           || jalr_reloc_p (fixp->fx_r_type)))
18273     return 0;
18274
18275   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
18276      to a floating-point stub.  The same is true for non-R_MIPS16_26
18277      relocations against MIPS16 functions; in this case, the stub becomes
18278      the function's canonical address.
18279
18280      Floating-point stubs are stored in unique .mips16.call.* or
18281      .mips16.fn.* sections.  If a stub T for function F is in section S,
18282      the first relocation in section S must be against F; this is how the
18283      linker determines the target function.  All relocations that might
18284      resolve to T must also be against F.  We therefore have the following
18285      restrictions, which are given in an intentionally-redundant way:
18286
18287        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
18288           symbols.
18289
18290        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
18291           if that stub might be used.
18292
18293        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
18294           symbols.
18295
18296        4. We cannot reduce a stub's relocations against MIPS16 symbols if
18297           that stub might be used.
18298
18299      There is a further restriction:
18300
18301        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
18302           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
18303           targets with in-place addends; the relocation field cannot
18304           encode the low bit.
18305
18306      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
18307      against a MIPS16 symbol.  We deal with (5) by by not reducing any
18308      such relocations on REL targets.
18309
18310      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
18311      relocation against some symbol R, no relocation against R may be
18312      reduced.  (Note that this deals with (2) as well as (1) because
18313      relocations against global symbols will never be reduced on ELF
18314      targets.)  This approach is a little simpler than trying to detect
18315      stub sections, and gives the "all or nothing" per-symbol consistency
18316      that we have for MIPS16 symbols.  */
18317   if (fixp->fx_subsy == NULL
18318       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
18319           || *symbol_get_tc (fixp->fx_addsy)
18320           || (HAVE_IN_PLACE_ADDENDS
18321               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
18322               && jmp_reloc_p (fixp->fx_r_type))))
18323     return 0;
18324
18325   return 1;
18326 }
18327
18328 /* Translate internal representation of relocation info to BFD target
18329    format.  */
18330
18331 arelent **
18332 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
18333 {
18334   static arelent *retval[4];
18335   arelent *reloc;
18336   bfd_reloc_code_real_type code;
18337
18338   memset (retval, 0, sizeof(retval));
18339   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
18340   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
18341   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
18342   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
18343
18344   if (fixp->fx_pcrel)
18345     {
18346       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
18347                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
18348                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
18349                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
18350                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
18351
18352       /* At this point, fx_addnumber is "symbol offset - pcrel address".
18353          Relocations want only the symbol offset.  */
18354       reloc->addend = fixp->fx_addnumber + reloc->address;
18355     }
18356   else
18357     reloc->addend = fixp->fx_addnumber;
18358
18359   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
18360      entry to be used in the relocation's section offset.  */
18361   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
18362     {
18363       reloc->address = reloc->addend;
18364       reloc->addend = 0;
18365     }
18366
18367   code = fixp->fx_r_type;
18368
18369   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
18370   if (reloc->howto == NULL)
18371     {
18372       as_bad_where (fixp->fx_file, fixp->fx_line,
18373                     _("Can not represent %s relocation in this object file format"),
18374                     bfd_get_reloc_code_name (code));
18375       retval[0] = NULL;
18376     }
18377
18378   return retval;
18379 }
18380
18381 /* Relax a machine dependent frag.  This returns the amount by which
18382    the current size of the frag should change.  */
18383
18384 int
18385 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
18386 {
18387   if (RELAX_BRANCH_P (fragp->fr_subtype))
18388     {
18389       offsetT old_var = fragp->fr_var;
18390
18391       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
18392
18393       return fragp->fr_var - old_var;
18394     }
18395
18396   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18397     {
18398       offsetT old_var = fragp->fr_var;
18399       offsetT new_var = 4;
18400
18401       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
18402         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
18403       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
18404         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
18405       fragp->fr_var = new_var;
18406
18407       return new_var - old_var;
18408     }
18409
18410   if (! RELAX_MIPS16_P (fragp->fr_subtype))
18411     return 0;
18412
18413   if (mips16_extended_frag (fragp, NULL, stretch))
18414     {
18415       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18416         return 0;
18417       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
18418       return 2;
18419     }
18420   else
18421     {
18422       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
18423         return 0;
18424       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
18425       return -2;
18426     }
18427
18428   return 0;
18429 }
18430
18431 /* Convert a machine dependent frag.  */
18432
18433 void
18434 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
18435 {
18436   if (RELAX_BRANCH_P (fragp->fr_subtype))
18437     {
18438       char *buf;
18439       unsigned long insn;
18440       expressionS exp;
18441       fixS *fixp;
18442
18443       buf = fragp->fr_literal + fragp->fr_fix;
18444       insn = read_insn (buf);
18445
18446       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
18447         {
18448           /* We generate a fixup instead of applying it right now
18449              because, if there are linker relaxations, we're going to
18450              need the relocations.  */
18451           exp.X_op = O_symbol;
18452           exp.X_add_symbol = fragp->fr_symbol;
18453           exp.X_add_number = fragp->fr_offset;
18454
18455           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18456                               BFD_RELOC_16_PCREL_S2);
18457           fixp->fx_file = fragp->fr_file;
18458           fixp->fx_line = fragp->fr_line;
18459
18460           buf = write_insn (buf, insn);
18461         }
18462       else
18463         {
18464           int i;
18465
18466           as_warn_where (fragp->fr_file, fragp->fr_line,
18467                          _("Relaxed out-of-range branch into a jump"));
18468
18469           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
18470             goto uncond;
18471
18472           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18473             {
18474               /* Reverse the branch.  */
18475               switch ((insn >> 28) & 0xf)
18476                 {
18477                 case 4:
18478                   /* bc[0-3][tf]l? instructions can have the condition
18479                      reversed by tweaking a single TF bit, and their
18480                      opcodes all have 0x4???????.  */
18481                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
18482                   insn ^= 0x00010000;
18483                   break;
18484
18485                 case 0:
18486                   /* bltz       0x04000000      bgez    0x04010000
18487                      bltzal     0x04100000      bgezal  0x04110000  */
18488                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
18489                   insn ^= 0x00010000;
18490                   break;
18491
18492                 case 1:
18493                   /* beq        0x10000000      bne     0x14000000
18494                      blez       0x18000000      bgtz    0x1c000000  */
18495                   insn ^= 0x04000000;
18496                   break;
18497
18498                 default:
18499                   abort ();
18500                 }
18501             }
18502
18503           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18504             {
18505               /* Clear the and-link bit.  */
18506               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
18507
18508               /* bltzal         0x04100000      bgezal  0x04110000
18509                  bltzall        0x04120000      bgezall 0x04130000  */
18510               insn &= ~0x00100000;
18511             }
18512
18513           /* Branch over the branch (if the branch was likely) or the
18514              full jump (not likely case).  Compute the offset from the
18515              current instruction to branch to.  */
18516           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18517             i = 16;
18518           else
18519             {
18520               /* How many bytes in instructions we've already emitted?  */
18521               i = buf - fragp->fr_literal - fragp->fr_fix;
18522               /* How many bytes in instructions from here to the end?  */
18523               i = fragp->fr_var - i;
18524             }
18525           /* Convert to instruction count.  */
18526           i >>= 2;
18527           /* Branch counts from the next instruction.  */
18528           i--;
18529           insn |= i;
18530           /* Branch over the jump.  */
18531           buf = write_insn (buf, insn);
18532
18533           /* nop */
18534           buf = write_insn (buf, 0);
18535
18536           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
18537             {
18538               /* beql $0, $0, 2f */
18539               insn = 0x50000000;
18540               /* Compute the PC offset from the current instruction to
18541                  the end of the variable frag.  */
18542               /* How many bytes in instructions we've already emitted?  */
18543               i = buf - fragp->fr_literal - fragp->fr_fix;
18544               /* How many bytes in instructions from here to the end?  */
18545               i = fragp->fr_var - i;
18546               /* Convert to instruction count.  */
18547               i >>= 2;
18548               /* Don't decrement i, because we want to branch over the
18549                  delay slot.  */
18550               insn |= i;
18551
18552               buf = write_insn (buf, insn);
18553               buf = write_insn (buf, 0);
18554             }
18555
18556         uncond:
18557           if (mips_pic == NO_PIC)
18558             {
18559               /* j or jal.  */
18560               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
18561                       ? 0x0c000000 : 0x08000000);
18562               exp.X_op = O_symbol;
18563               exp.X_add_symbol = fragp->fr_symbol;
18564               exp.X_add_number = fragp->fr_offset;
18565
18566               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18567                                   FALSE, BFD_RELOC_MIPS_JMP);
18568               fixp->fx_file = fragp->fr_file;
18569               fixp->fx_line = fragp->fr_line;
18570
18571               buf = write_insn (buf, insn);
18572             }
18573           else
18574             {
18575               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
18576
18577               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
18578               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
18579               insn |= at << OP_SH_RT;
18580               exp.X_op = O_symbol;
18581               exp.X_add_symbol = fragp->fr_symbol;
18582               exp.X_add_number = fragp->fr_offset;
18583
18584               if (fragp->fr_offset)
18585                 {
18586                   exp.X_add_symbol = make_expr_symbol (&exp);
18587                   exp.X_add_number = 0;
18588                 }
18589
18590               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18591                                   FALSE, BFD_RELOC_MIPS_GOT16);
18592               fixp->fx_file = fragp->fr_file;
18593               fixp->fx_line = fragp->fr_line;
18594
18595               buf = write_insn (buf, insn);
18596
18597               if (mips_opts.isa == ISA_MIPS1)
18598                 /* nop */
18599                 buf = write_insn (buf, 0);
18600
18601               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
18602               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
18603               insn |= at << OP_SH_RS | at << OP_SH_RT;
18604
18605               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
18606                                   FALSE, BFD_RELOC_LO16);
18607               fixp->fx_file = fragp->fr_file;
18608               fixp->fx_line = fragp->fr_line;
18609
18610               buf = write_insn (buf, insn);
18611
18612               /* j(al)r $at.  */
18613               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18614                 insn = 0x0000f809;
18615               else
18616                 insn = 0x00000008;
18617               insn |= at << OP_SH_RS;
18618
18619               buf = write_insn (buf, insn);
18620             }
18621         }
18622
18623       fragp->fr_fix += fragp->fr_var;
18624       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18625       return;
18626     }
18627
18628   /* Relax microMIPS branches.  */
18629   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18630     {
18631       char *buf = fragp->fr_literal + fragp->fr_fix;
18632       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18633       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18634       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18635       bfd_boolean short_ds;
18636       unsigned long insn;
18637       expressionS exp;
18638       fixS *fixp;
18639
18640       exp.X_op = O_symbol;
18641       exp.X_add_symbol = fragp->fr_symbol;
18642       exp.X_add_number = fragp->fr_offset;
18643
18644       fragp->fr_fix += fragp->fr_var;
18645
18646       /* Handle 16-bit branches that fit or are forced to fit.  */
18647       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18648         {
18649           /* We generate a fixup instead of applying it right now,
18650              because if there is linker relaxation, we're going to
18651              need the relocations.  */
18652           if (type == 'D')
18653             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18654                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18655           else if (type == 'E')
18656             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18657                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18658           else
18659             abort ();
18660
18661           fixp->fx_file = fragp->fr_file;
18662           fixp->fx_line = fragp->fr_line;
18663
18664           /* These relocations can have an addend that won't fit in
18665              2 octets.  */
18666           fixp->fx_no_overflow = 1;
18667
18668           return;
18669         }
18670
18671       /* Handle 32-bit branches that fit or are forced to fit.  */
18672       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18673           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18674         {
18675           /* We generate a fixup instead of applying it right now,
18676              because if there is linker relaxation, we're going to
18677              need the relocations.  */
18678           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18679                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18680           fixp->fx_file = fragp->fr_file;
18681           fixp->fx_line = fragp->fr_line;
18682
18683           if (type == 0)
18684             return;
18685         }
18686
18687       /* Relax 16-bit branches to 32-bit branches.  */
18688       if (type != 0)
18689         {
18690           insn = read_compressed_insn (buf, 2);
18691
18692           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18693             insn = 0x94000000;                          /* beq  */
18694           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18695             {
18696               unsigned long regno;
18697
18698               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18699               regno = micromips_to_32_reg_d_map [regno];
18700               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18701               insn |= regno << MICROMIPSOP_SH_RS;
18702             }
18703           else
18704             abort ();
18705
18706           /* Nothing else to do, just write it out.  */
18707           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18708               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18709             {
18710               buf = write_compressed_insn (buf, insn, 4);
18711               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18712               return;
18713             }
18714         }
18715       else
18716         insn = read_compressed_insn (buf, 4);
18717
18718       /* Relax 32-bit branches to a sequence of instructions.  */
18719       as_warn_where (fragp->fr_file, fragp->fr_line,
18720                      _("Relaxed out-of-range branch into a jump"));
18721
18722       /* Set the short-delay-slot bit.  */
18723       short_ds = al && (insn & 0x02000000) != 0;
18724
18725       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18726         {
18727           symbolS *l;
18728
18729           /* Reverse the branch.  */
18730           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18731               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18732             insn ^= 0x20000000;
18733           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18734                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18735                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18736                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18737                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18738                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18739                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18740                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18741                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18742                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18743             insn ^= 0x00400000;
18744           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18745                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18746                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18747                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18748             insn ^= 0x00200000;
18749           else
18750             abort ();
18751
18752           if (al)
18753             {
18754               /* Clear the and-link and short-delay-slot bits.  */
18755               gas_assert ((insn & 0xfda00000) == 0x40200000);
18756
18757               /* bltzal  0x40200000     bgezal  0x40600000  */
18758               /* bltzals 0x42200000     bgezals 0x42600000  */
18759               insn &= ~0x02200000;
18760             }
18761
18762           /* Make a label at the end for use with the branch.  */
18763           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18764           micromips_label_inc ();
18765           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18766
18767           /* Refer to it.  */
18768           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18769                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18770           fixp->fx_file = fragp->fr_file;
18771           fixp->fx_line = fragp->fr_line;
18772
18773           /* Branch over the jump.  */
18774           buf = write_compressed_insn (buf, insn, 4);
18775           if (!compact)
18776             /* nop */
18777             buf = write_compressed_insn (buf, 0x0c00, 2);
18778         }
18779
18780       if (mips_pic == NO_PIC)
18781         {
18782           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
18783
18784           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18785           insn = al ? jal : 0xd4000000;
18786
18787           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18788                               BFD_RELOC_MICROMIPS_JMP);
18789           fixp->fx_file = fragp->fr_file;
18790           fixp->fx_line = fragp->fr_line;
18791
18792           buf = write_compressed_insn (buf, insn, 4);
18793           if (compact)
18794             /* nop */
18795             buf = write_compressed_insn (buf, 0x0c00, 2);
18796         }
18797       else
18798         {
18799           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18800           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18801           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18802
18803           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18804           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18805           insn |= at << MICROMIPSOP_SH_RT;
18806
18807           if (exp.X_add_number)
18808             {
18809               exp.X_add_symbol = make_expr_symbol (&exp);
18810               exp.X_add_number = 0;
18811             }
18812
18813           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18814                               BFD_RELOC_MICROMIPS_GOT16);
18815           fixp->fx_file = fragp->fr_file;
18816           fixp->fx_line = fragp->fr_line;
18817
18818           buf = write_compressed_insn (buf, insn, 4);
18819
18820           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18821           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18822           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18823
18824           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18825                               BFD_RELOC_MICROMIPS_LO16);
18826           fixp->fx_file = fragp->fr_file;
18827           fixp->fx_line = fragp->fr_line;
18828
18829           buf = write_compressed_insn (buf, insn, 4);
18830
18831           /* jr/jrc/jalr/jalrs $at  */
18832           insn = al ? jalr : jr;
18833           insn |= at << MICROMIPSOP_SH_MJ;
18834
18835           buf = write_compressed_insn (buf, insn, 2);
18836         }
18837
18838       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18839       return;
18840     }
18841
18842   if (RELAX_MIPS16_P (fragp->fr_subtype))
18843     {
18844       int type;
18845       const struct mips16_immed_operand *op;
18846       offsetT val;
18847       char *buf;
18848       unsigned int user_length, length;
18849       unsigned long insn;
18850       bfd_boolean ext;
18851
18852       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18853       op = mips16_immed_operands;
18854       while (op->type != type)
18855         ++op;
18856
18857       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18858       val = resolve_symbol_value (fragp->fr_symbol);
18859       if (op->pcrel)
18860         {
18861           addressT addr;
18862
18863           addr = fragp->fr_address + fragp->fr_fix;
18864
18865           /* The rules for the base address of a PC relative reloc are
18866              complicated; see mips16_extended_frag.  */
18867           if (type == 'p' || type == 'q')
18868             {
18869               addr += 2;
18870               if (ext)
18871                 addr += 2;
18872               /* Ignore the low bit in the target, since it will be
18873                  set for a text label.  */
18874               if ((val & 1) != 0)
18875                 --val;
18876             }
18877           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18878             addr -= 4;
18879           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18880             addr -= 2;
18881
18882           addr &= ~ (addressT) ((1 << op->shift) - 1);
18883           val -= addr;
18884
18885           /* Make sure the section winds up with the alignment we have
18886              assumed.  */
18887           if (op->shift > 0)
18888             record_alignment (asec, op->shift);
18889         }
18890
18891       if (ext
18892           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18893               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18894         as_warn_where (fragp->fr_file, fragp->fr_line,
18895                        _("extended instruction in delay slot"));
18896
18897       buf = fragp->fr_literal + fragp->fr_fix;
18898
18899       insn = read_compressed_insn (buf, 2);
18900       if (ext)
18901         insn |= MIPS16_EXTEND;
18902
18903       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18904         user_length = 4;
18905       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18906         user_length = 2;
18907       else
18908         user_length = 0;
18909
18910       mips16_immed (fragp->fr_file, fragp->fr_line, type,
18911                     BFD_RELOC_UNUSED, val, user_length, &insn);
18912
18913       length = (ext ? 4 : 2);
18914       gas_assert (mips16_opcode_length (insn) == length);
18915       write_compressed_insn (buf, insn, length);
18916       fragp->fr_fix += length;
18917     }
18918   else
18919     {
18920       relax_substateT subtype = fragp->fr_subtype;
18921       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18922       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18923       int first, second;
18924       fixS *fixp;
18925
18926       first = RELAX_FIRST (subtype);
18927       second = RELAX_SECOND (subtype);
18928       fixp = (fixS *) fragp->fr_opcode;
18929
18930       /* If the delay slot chosen does not match the size of the instruction,
18931          then emit a warning.  */
18932       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18933            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18934         {
18935           relax_substateT s;
18936           const char *msg;
18937
18938           s = subtype & (RELAX_DELAY_SLOT_16BIT
18939                          | RELAX_DELAY_SLOT_SIZE_FIRST
18940                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18941           msg = macro_warning (s);
18942           if (msg != NULL)
18943             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18944           subtype &= ~s;
18945         }
18946
18947       /* Possibly emit a warning if we've chosen the longer option.  */
18948       if (use_second == second_longer)
18949         {
18950           relax_substateT s;
18951           const char *msg;
18952
18953           s = (subtype
18954                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18955           msg = macro_warning (s);
18956           if (msg != NULL)
18957             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18958           subtype &= ~s;
18959         }
18960
18961       /* Go through all the fixups for the first sequence.  Disable them
18962          (by marking them as done) if we're going to use the second
18963          sequence instead.  */
18964       while (fixp
18965              && fixp->fx_frag == fragp
18966              && fixp->fx_where < fragp->fr_fix - second)
18967         {
18968           if (subtype & RELAX_USE_SECOND)
18969             fixp->fx_done = 1;
18970           fixp = fixp->fx_next;
18971         }
18972
18973       /* Go through the fixups for the second sequence.  Disable them if
18974          we're going to use the first sequence, otherwise adjust their
18975          addresses to account for the relaxation.  */
18976       while (fixp && fixp->fx_frag == fragp)
18977         {
18978           if (subtype & RELAX_USE_SECOND)
18979             fixp->fx_where -= first;
18980           else
18981             fixp->fx_done = 1;
18982           fixp = fixp->fx_next;
18983         }
18984
18985       /* Now modify the frag contents.  */
18986       if (subtype & RELAX_USE_SECOND)
18987         {
18988           char *start;
18989
18990           start = fragp->fr_literal + fragp->fr_fix - first - second;
18991           memmove (start, start + first, second);
18992           fragp->fr_fix -= first;
18993         }
18994       else
18995         fragp->fr_fix -= second;
18996     }
18997 }
18998
18999 /* This function is called after the relocs have been generated.
19000    We've been storing mips16 text labels as odd.  Here we convert them
19001    back to even for the convenience of the debugger.  */
19002
19003 void
19004 mips_frob_file_after_relocs (void)
19005 {
19006   asymbol **syms;
19007   unsigned int count, i;
19008
19009   syms = bfd_get_outsymbols (stdoutput);
19010   count = bfd_get_symcount (stdoutput);
19011   for (i = 0; i < count; i++, syms++)
19012     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
19013         && ((*syms)->value & 1) != 0)
19014       {
19015         (*syms)->value &= ~1;
19016         /* If the symbol has an odd size, it was probably computed
19017            incorrectly, so adjust that as well.  */
19018         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
19019           ++elf_symbol (*syms)->internal_elf_sym.st_size;
19020       }
19021 }
19022
19023 /* This function is called whenever a label is defined, including fake
19024    labels instantiated off the dot special symbol.  It is used when
19025    handling branch delays; if a branch has a label, we assume we cannot
19026    move it.  This also bumps the value of the symbol by 1 in compressed
19027    code.  */
19028
19029 static void
19030 mips_record_label (symbolS *sym)
19031 {
19032   segment_info_type *si = seg_info (now_seg);
19033   struct insn_label_list *l;
19034
19035   if (free_insn_labels == NULL)
19036     l = (struct insn_label_list *) xmalloc (sizeof *l);
19037   else
19038     {
19039       l = free_insn_labels;
19040       free_insn_labels = l->next;
19041     }
19042
19043   l->label = sym;
19044   l->next = si->label_list;
19045   si->label_list = l;
19046 }
19047
19048 /* This function is called as tc_frob_label() whenever a label is defined
19049    and adds a DWARF-2 record we only want for true labels.  */
19050
19051 void
19052 mips_define_label (symbolS *sym)
19053 {
19054   mips_record_label (sym);
19055   dwarf2_emit_label (sym);
19056 }
19057
19058 /* This function is called by tc_new_dot_label whenever a new dot symbol
19059    is defined.  */
19060
19061 void
19062 mips_add_dot_label (symbolS *sym)
19063 {
19064   mips_record_label (sym);
19065   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
19066     mips_compressed_mark_label (sym);
19067 }
19068 \f
19069 /* Some special processing for a MIPS ELF file.  */
19070
19071 void
19072 mips_elf_final_processing (void)
19073 {
19074   /* Write out the register information.  */
19075   if (mips_abi != N64_ABI)
19076     {
19077       Elf32_RegInfo s;
19078
19079       s.ri_gprmask = mips_gprmask;
19080       s.ri_cprmask[0] = mips_cprmask[0];
19081       s.ri_cprmask[1] = mips_cprmask[1];
19082       s.ri_cprmask[2] = mips_cprmask[2];
19083       s.ri_cprmask[3] = mips_cprmask[3];
19084       /* The gp_value field is set by the MIPS ELF backend.  */
19085
19086       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
19087                                        ((Elf32_External_RegInfo *)
19088                                         mips_regmask_frag));
19089     }
19090   else
19091     {
19092       Elf64_Internal_RegInfo s;
19093
19094       s.ri_gprmask = mips_gprmask;
19095       s.ri_pad = 0;
19096       s.ri_cprmask[0] = mips_cprmask[0];
19097       s.ri_cprmask[1] = mips_cprmask[1];
19098       s.ri_cprmask[2] = mips_cprmask[2];
19099       s.ri_cprmask[3] = mips_cprmask[3];
19100       /* The gp_value field is set by the MIPS ELF backend.  */
19101
19102       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
19103                                        ((Elf64_External_RegInfo *)
19104                                         mips_regmask_frag));
19105     }
19106
19107   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
19108      sort of BFD interface for this.  */
19109   if (mips_any_noreorder)
19110     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
19111   if (mips_pic != NO_PIC)
19112     {
19113       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
19114       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19115     }
19116   if (mips_abicalls)
19117     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
19118
19119   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
19120      defined at present; this might need to change in future.  */
19121   if (file_ase_mips16)
19122     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
19123   if (file_ase_micromips)
19124     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
19125   if (file_ase & ASE_MDMX)
19126     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
19127
19128   /* Set the MIPS ELF ABI flags.  */
19129   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
19130     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
19131   else if (mips_abi == O64_ABI)
19132     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
19133   else if (mips_abi == EABI_ABI)
19134     {
19135       if (!file_mips_gp32)
19136         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
19137       else
19138         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
19139     }
19140   else if (mips_abi == N32_ABI)
19141     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
19142
19143   /* Nothing to do for N64_ABI.  */
19144
19145   if (mips_32bitmode)
19146     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
19147
19148   if (mips_flag_nan2008)
19149     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
19150
19151 #if 0 /* XXX FIXME */
19152   /* 32 bit code with 64 bit FP registers.  */
19153   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
19154     elf_elfheader (stdoutput)->e_flags |= ???;
19155 #endif
19156 }
19157 \f
19158 typedef struct proc {
19159   symbolS *func_sym;
19160   symbolS *func_end_sym;
19161   unsigned long reg_mask;
19162   unsigned long reg_offset;
19163   unsigned long fpreg_mask;
19164   unsigned long fpreg_offset;
19165   unsigned long frame_offset;
19166   unsigned long frame_reg;
19167   unsigned long pc_reg;
19168 } procS;
19169
19170 static procS cur_proc;
19171 static procS *cur_proc_ptr;
19172 static int numprocs;
19173
19174 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
19175    as "2", and a normal nop as "0".  */
19176
19177 #define NOP_OPCODE_MIPS         0
19178 #define NOP_OPCODE_MIPS16       1
19179 #define NOP_OPCODE_MICROMIPS    2
19180
19181 char
19182 mips_nop_opcode (void)
19183 {
19184   if (seg_info (now_seg)->tc_segment_info_data.micromips)
19185     return NOP_OPCODE_MICROMIPS;
19186   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
19187     return NOP_OPCODE_MIPS16;
19188   else
19189     return NOP_OPCODE_MIPS;
19190 }
19191
19192 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
19193    32-bit microMIPS NOPs here (if applicable).  */
19194
19195 void
19196 mips_handle_align (fragS *fragp)
19197 {
19198   char nop_opcode;
19199   char *p;
19200   int bytes, size, excess;
19201   valueT opcode;
19202
19203   if (fragp->fr_type != rs_align_code)
19204     return;
19205
19206   p = fragp->fr_literal + fragp->fr_fix;
19207   nop_opcode = *p;
19208   switch (nop_opcode)
19209     {
19210     case NOP_OPCODE_MICROMIPS:
19211       opcode = micromips_nop32_insn.insn_opcode;
19212       size = 4;
19213       break;
19214     case NOP_OPCODE_MIPS16:
19215       opcode = mips16_nop_insn.insn_opcode;
19216       size = 2;
19217       break;
19218     case NOP_OPCODE_MIPS:
19219     default:
19220       opcode = nop_insn.insn_opcode;
19221       size = 4;
19222       break;
19223     }
19224
19225   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
19226   excess = bytes % size;
19227
19228   /* Handle the leading part if we're not inserting a whole number of
19229      instructions, and make it the end of the fixed part of the frag.
19230      Try to fit in a short microMIPS NOP if applicable and possible,
19231      and use zeroes otherwise.  */
19232   gas_assert (excess < 4);
19233   fragp->fr_fix += excess;
19234   switch (excess)
19235     {
19236     case 3:
19237       *p++ = '\0';
19238       /* Fall through.  */
19239     case 2:
19240       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
19241         {
19242           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
19243           break;
19244         }
19245       *p++ = '\0';
19246       /* Fall through.  */
19247     case 1:
19248       *p++ = '\0';
19249       /* Fall through.  */
19250     case 0:
19251       break;
19252     }
19253
19254   md_number_to_chars (p, opcode, size);
19255   fragp->fr_var = size;
19256 }
19257
19258 static void
19259 md_obj_begin (void)
19260 {
19261 }
19262
19263 static void
19264 md_obj_end (void)
19265 {
19266   /* Check for premature end, nesting errors, etc.  */
19267   if (cur_proc_ptr)
19268     as_warn (_("missing .end at end of assembly"));
19269 }
19270
19271 static long
19272 get_number (void)
19273 {
19274   int negative = 0;
19275   long val = 0;
19276
19277   if (*input_line_pointer == '-')
19278     {
19279       ++input_line_pointer;
19280       negative = 1;
19281     }
19282   if (!ISDIGIT (*input_line_pointer))
19283     as_bad (_("expected simple number"));
19284   if (input_line_pointer[0] == '0')
19285     {
19286       if (input_line_pointer[1] == 'x')
19287         {
19288           input_line_pointer += 2;
19289           while (ISXDIGIT (*input_line_pointer))
19290             {
19291               val <<= 4;
19292               val |= hex_value (*input_line_pointer++);
19293             }
19294           return negative ? -val : val;
19295         }
19296       else
19297         {
19298           ++input_line_pointer;
19299           while (ISDIGIT (*input_line_pointer))
19300             {
19301               val <<= 3;
19302               val |= *input_line_pointer++ - '0';
19303             }
19304           return negative ? -val : val;
19305         }
19306     }
19307   if (!ISDIGIT (*input_line_pointer))
19308     {
19309       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
19310               *input_line_pointer, *input_line_pointer);
19311       as_warn (_("invalid number"));
19312       return -1;
19313     }
19314   while (ISDIGIT (*input_line_pointer))
19315     {
19316       val *= 10;
19317       val += *input_line_pointer++ - '0';
19318     }
19319   return negative ? -val : val;
19320 }
19321
19322 /* The .file directive; just like the usual .file directive, but there
19323    is an initial number which is the ECOFF file index.  In the non-ECOFF
19324    case .file implies DWARF-2.  */
19325
19326 static void
19327 s_mips_file (int x ATTRIBUTE_UNUSED)
19328 {
19329   static int first_file_directive = 0;
19330
19331   if (ECOFF_DEBUGGING)
19332     {
19333       get_number ();
19334       s_app_file (0);
19335     }
19336   else
19337     {
19338       char *filename;
19339
19340       filename = dwarf2_directive_file (0);
19341
19342       /* Versions of GCC up to 3.1 start files with a ".file"
19343          directive even for stabs output.  Make sure that this
19344          ".file" is handled.  Note that you need a version of GCC
19345          after 3.1 in order to support DWARF-2 on MIPS.  */
19346       if (filename != NULL && ! first_file_directive)
19347         {
19348           (void) new_logical_line (filename, -1);
19349           s_app_file_string (filename, 0);
19350         }
19351       first_file_directive = 1;
19352     }
19353 }
19354
19355 /* The .loc directive, implying DWARF-2.  */
19356
19357 static void
19358 s_mips_loc (int x ATTRIBUTE_UNUSED)
19359 {
19360   if (!ECOFF_DEBUGGING)
19361     dwarf2_directive_loc (0);
19362 }
19363
19364 /* The .end directive.  */
19365
19366 static void
19367 s_mips_end (int x ATTRIBUTE_UNUSED)
19368 {
19369   symbolS *p;
19370
19371   /* Following functions need their own .frame and .cprestore directives.  */
19372   mips_frame_reg_valid = 0;
19373   mips_cprestore_valid = 0;
19374
19375   if (!is_end_of_line[(unsigned char) *input_line_pointer])
19376     {
19377       p = get_symbol ();
19378       demand_empty_rest_of_line ();
19379     }
19380   else
19381     p = NULL;
19382
19383   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19384     as_warn (_(".end not in text section"));
19385
19386   if (!cur_proc_ptr)
19387     {
19388       as_warn (_(".end directive without a preceding .ent directive."));
19389       demand_empty_rest_of_line ();
19390       return;
19391     }
19392
19393   if (p != NULL)
19394     {
19395       gas_assert (S_GET_NAME (p));
19396       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
19397         as_warn (_(".end symbol does not match .ent symbol."));
19398
19399       if (debug_type == DEBUG_STABS)
19400         stabs_generate_asm_endfunc (S_GET_NAME (p),
19401                                     S_GET_NAME (p));
19402     }
19403   else
19404     as_warn (_(".end directive missing or unknown symbol"));
19405
19406   /* Create an expression to calculate the size of the function.  */
19407   if (p && cur_proc_ptr)
19408     {
19409       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
19410       expressionS *exp = xmalloc (sizeof (expressionS));
19411
19412       obj->size = exp;
19413       exp->X_op = O_subtract;
19414       exp->X_add_symbol = symbol_temp_new_now ();
19415       exp->X_op_symbol = p;
19416       exp->X_add_number = 0;
19417
19418       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
19419     }
19420
19421   /* Generate a .pdr section.  */
19422   if (!ECOFF_DEBUGGING && mips_flag_pdr)
19423     {
19424       segT saved_seg = now_seg;
19425       subsegT saved_subseg = now_subseg;
19426       expressionS exp;
19427       char *fragp;
19428
19429 #ifdef md_flush_pending_output
19430       md_flush_pending_output ();
19431 #endif
19432
19433       gas_assert (pdr_seg);
19434       subseg_set (pdr_seg, 0);
19435
19436       /* Write the symbol.  */
19437       exp.X_op = O_symbol;
19438       exp.X_add_symbol = p;
19439       exp.X_add_number = 0;
19440       emit_expr (&exp, 4);
19441
19442       fragp = frag_more (7 * 4);
19443
19444       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
19445       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
19446       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
19447       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
19448       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
19449       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
19450       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
19451
19452       subseg_set (saved_seg, saved_subseg);
19453     }
19454
19455   cur_proc_ptr = NULL;
19456 }
19457
19458 /* The .aent and .ent directives.  */
19459
19460 static void
19461 s_mips_ent (int aent)
19462 {
19463   symbolS *symbolP;
19464
19465   symbolP = get_symbol ();
19466   if (*input_line_pointer == ',')
19467     ++input_line_pointer;
19468   SKIP_WHITESPACE ();
19469   if (ISDIGIT (*input_line_pointer)
19470       || *input_line_pointer == '-')
19471     get_number ();
19472
19473   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
19474     as_warn (_(".ent or .aent not in text section."));
19475
19476   if (!aent && cur_proc_ptr)
19477     as_warn (_("missing .end"));
19478
19479   if (!aent)
19480     {
19481       /* This function needs its own .frame and .cprestore directives.  */
19482       mips_frame_reg_valid = 0;
19483       mips_cprestore_valid = 0;
19484
19485       cur_proc_ptr = &cur_proc;
19486       memset (cur_proc_ptr, '\0', sizeof (procS));
19487
19488       cur_proc_ptr->func_sym = symbolP;
19489
19490       ++numprocs;
19491
19492       if (debug_type == DEBUG_STABS)
19493         stabs_generate_asm_func (S_GET_NAME (symbolP),
19494                                  S_GET_NAME (symbolP));
19495     }
19496
19497   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
19498
19499   demand_empty_rest_of_line ();
19500 }
19501
19502 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
19503    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
19504    s_mips_frame is used so that we can set the PDR information correctly.
19505    We can't use the ecoff routines because they make reference to the ecoff
19506    symbol table (in the mdebug section).  */
19507
19508 static void
19509 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
19510 {
19511   if (ECOFF_DEBUGGING)
19512     s_ignore (ignore);
19513   else
19514     {
19515       long val;
19516
19517       if (cur_proc_ptr == (procS *) NULL)
19518         {
19519           as_warn (_(".frame outside of .ent"));
19520           demand_empty_rest_of_line ();
19521           return;
19522         }
19523
19524       cur_proc_ptr->frame_reg = tc_get_register (1);
19525
19526       SKIP_WHITESPACE ();
19527       if (*input_line_pointer++ != ','
19528           || get_absolute_expression_and_terminator (&val) != ',')
19529         {
19530           as_warn (_("Bad .frame directive"));
19531           --input_line_pointer;
19532           demand_empty_rest_of_line ();
19533           return;
19534         }
19535
19536       cur_proc_ptr->frame_offset = val;
19537       cur_proc_ptr->pc_reg = tc_get_register (0);
19538
19539       demand_empty_rest_of_line ();
19540     }
19541 }
19542
19543 /* The .fmask and .mask directives. If the mdebug section is present
19544    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
19545    embedded targets, s_mips_mask is used so that we can set the PDR
19546    information correctly. We can't use the ecoff routines because they
19547    make reference to the ecoff symbol table (in the mdebug section).  */
19548
19549 static void
19550 s_mips_mask (int reg_type)
19551 {
19552   if (ECOFF_DEBUGGING)
19553     s_ignore (reg_type);
19554   else
19555     {
19556       long mask, off;
19557
19558       if (cur_proc_ptr == (procS *) NULL)
19559         {
19560           as_warn (_(".mask/.fmask outside of .ent"));
19561           demand_empty_rest_of_line ();
19562           return;
19563         }
19564
19565       if (get_absolute_expression_and_terminator (&mask) != ',')
19566         {
19567           as_warn (_("Bad .mask/.fmask directive"));
19568           --input_line_pointer;
19569           demand_empty_rest_of_line ();
19570           return;
19571         }
19572
19573       off = get_absolute_expression ();
19574
19575       if (reg_type == 'F')
19576         {
19577           cur_proc_ptr->fpreg_mask = mask;
19578           cur_proc_ptr->fpreg_offset = off;
19579         }
19580       else
19581         {
19582           cur_proc_ptr->reg_mask = mask;
19583           cur_proc_ptr->reg_offset = off;
19584         }
19585
19586       demand_empty_rest_of_line ();
19587     }
19588 }
19589
19590 /* A table describing all the processors gas knows about.  Names are
19591    matched in the order listed.
19592
19593    To ease comparison, please keep this table in the same order as
19594    gcc's mips_cpu_info_table[].  */
19595 static const struct mips_cpu_info mips_cpu_info_table[] =
19596 {
19597   /* Entries for generic ISAs */
19598   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
19599   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
19600   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
19601   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
19602   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
19603   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
19604   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
19605   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
19606   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
19607
19608   /* MIPS I */
19609   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19610   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19611   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19612
19613   /* MIPS II */
19614   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19615
19616   /* MIPS III */
19617   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19618   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19619   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19620   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19621   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19622   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19623   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19624   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19625   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19626   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19627   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19628   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19629   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19630   /* ST Microelectronics Loongson 2E and 2F cores */
19631   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19632   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19633
19634   /* MIPS IV */
19635   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19636   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19637   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19638   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19639   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19640   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19641   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19642   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19643   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19644   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19645   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19646   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19647   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19648   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19649   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19650
19651   /* MIPS 32 */
19652   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19653   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19654   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19655   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19656
19657   /* MIPS 32 Release 2 */
19658   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19659   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19660   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19661   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19662   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19663   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19664   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19665   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19666   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19667                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19668   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19669                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19670   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19671   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19672   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19673   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19674   /* Deprecated forms of the above.  */
19675   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19676   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19677   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19678   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19679   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19680   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19681   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19682   /* Deprecated forms of the above.  */
19683   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19684   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19685   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19686   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19687   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19688   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19689   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19690   /* Deprecated forms of the above.  */
19691   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19692   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19693   /* 34Kn is a 34kc without DSP.  */
19694   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19695   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19696   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19697   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19698   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19699   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19700   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19701   /* Deprecated forms of the above.  */
19702   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19703   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19704   /* 1004K cores are multiprocessor versions of the 34K.  */
19705   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19706   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19707   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19708   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19709
19710   /* MIPS 64 */
19711   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19712   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19713   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19714   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19715
19716   /* Broadcom SB-1 CPU core */
19717   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19718   /* Broadcom SB-1A CPU core */
19719   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19720   
19721   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
19722
19723   /* MIPS 64 Release 2 */
19724
19725   /* Cavium Networks Octeon CPU core */
19726   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19727   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19728   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19729
19730   /* RMI Xlr */
19731   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19732
19733   /* Broadcom XLP.
19734      XLP is mostly like XLR, with the prominent exception that it is
19735      MIPS64R2 rather than MIPS64.  */
19736   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19737
19738   /* End marker */
19739   { NULL, 0, 0, 0, 0 }
19740 };
19741
19742
19743 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19744    with a final "000" replaced by "k".  Ignore case.
19745
19746    Note: this function is shared between GCC and GAS.  */
19747
19748 static bfd_boolean
19749 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19750 {
19751   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19752     given++, canonical++;
19753
19754   return ((*given == 0 && *canonical == 0)
19755           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19756 }
19757
19758
19759 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19760    CPU name.  We've traditionally allowed a lot of variation here.
19761
19762    Note: this function is shared between GCC and GAS.  */
19763
19764 static bfd_boolean
19765 mips_matching_cpu_name_p (const char *canonical, const char *given)
19766 {
19767   /* First see if the name matches exactly, or with a final "000"
19768      turned into "k".  */
19769   if (mips_strict_matching_cpu_name_p (canonical, given))
19770     return TRUE;
19771
19772   /* If not, try comparing based on numerical designation alone.
19773      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19774   if (TOLOWER (*given) == 'r')
19775     given++;
19776   if (!ISDIGIT (*given))
19777     return FALSE;
19778
19779   /* Skip over some well-known prefixes in the canonical name,
19780      hoping to find a number there too.  */
19781   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19782     canonical += 2;
19783   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19784     canonical += 2;
19785   else if (TOLOWER (canonical[0]) == 'r')
19786     canonical += 1;
19787
19788   return mips_strict_matching_cpu_name_p (canonical, given);
19789 }
19790
19791
19792 /* Parse an option that takes the name of a processor as its argument.
19793    OPTION is the name of the option and CPU_STRING is the argument.
19794    Return the corresponding processor enumeration if the CPU_STRING is
19795    recognized, otherwise report an error and return null.
19796
19797    A similar function exists in GCC.  */
19798
19799 static const struct mips_cpu_info *
19800 mips_parse_cpu (const char *option, const char *cpu_string)
19801 {
19802   const struct mips_cpu_info *p;
19803
19804   /* 'from-abi' selects the most compatible architecture for the given
19805      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19806      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19807      version.  Look first at the -mgp options, if given, otherwise base
19808      the choice on MIPS_DEFAULT_64BIT.
19809
19810      Treat NO_ABI like the EABIs.  One reason to do this is that the
19811      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19812      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19813      'mips64', just as we did in the days before 'from-abi'.  */
19814   if (strcasecmp (cpu_string, "from-abi") == 0)
19815     {
19816       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19817         return mips_cpu_info_from_isa (ISA_MIPS1);
19818
19819       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19820         return mips_cpu_info_from_isa (ISA_MIPS3);
19821
19822       if (file_mips_gp32 >= 0)
19823         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19824
19825       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19826                                      ? ISA_MIPS3
19827                                      : ISA_MIPS1);
19828     }
19829
19830   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19831   if (strcasecmp (cpu_string, "default") == 0)
19832     return 0;
19833
19834   for (p = mips_cpu_info_table; p->name != 0; p++)
19835     if (mips_matching_cpu_name_p (p->name, cpu_string))
19836       return p;
19837
19838   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19839   return 0;
19840 }
19841
19842 /* Return the canonical processor information for ISA (a member of the
19843    ISA_MIPS* enumeration).  */
19844
19845 static const struct mips_cpu_info *
19846 mips_cpu_info_from_isa (int isa)
19847 {
19848   int i;
19849
19850   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19851     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19852         && isa == mips_cpu_info_table[i].isa)
19853       return (&mips_cpu_info_table[i]);
19854
19855   return NULL;
19856 }
19857
19858 static const struct mips_cpu_info *
19859 mips_cpu_info_from_arch (int arch)
19860 {
19861   int i;
19862
19863   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19864     if (arch == mips_cpu_info_table[i].cpu)
19865       return (&mips_cpu_info_table[i]);
19866
19867   return NULL;
19868 }
19869 \f
19870 static void
19871 show (FILE *stream, const char *string, int *col_p, int *first_p)
19872 {
19873   if (*first_p)
19874     {
19875       fprintf (stream, "%24s", "");
19876       *col_p = 24;
19877     }
19878   else
19879     {
19880       fprintf (stream, ", ");
19881       *col_p += 2;
19882     }
19883
19884   if (*col_p + strlen (string) > 72)
19885     {
19886       fprintf (stream, "\n%24s", "");
19887       *col_p = 24;
19888     }
19889
19890   fprintf (stream, "%s", string);
19891   *col_p += strlen (string);
19892
19893   *first_p = 0;
19894 }
19895
19896 void
19897 md_show_usage (FILE *stream)
19898 {
19899   int column, first;
19900   size_t i;
19901
19902   fprintf (stream, _("\
19903 MIPS options:\n\
19904 -EB                     generate big endian output\n\
19905 -EL                     generate little endian output\n\
19906 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19907 -G NUM                  allow referencing objects up to NUM bytes\n\
19908                         implicitly with the gp register [default 8]\n"));
19909   fprintf (stream, _("\
19910 -mips1                  generate MIPS ISA I instructions\n\
19911 -mips2                  generate MIPS ISA II instructions\n\
19912 -mips3                  generate MIPS ISA III instructions\n\
19913 -mips4                  generate MIPS ISA IV instructions\n\
19914 -mips5                  generate MIPS ISA V instructions\n\
19915 -mips32                 generate MIPS32 ISA instructions\n\
19916 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19917 -mips64                 generate MIPS64 ISA instructions\n\
19918 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19919 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19920
19921   first = 1;
19922
19923   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19924     show (stream, mips_cpu_info_table[i].name, &column, &first);
19925   show (stream, "from-abi", &column, &first);
19926   fputc ('\n', stream);
19927
19928   fprintf (stream, _("\
19929 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19930 -no-mCPU                don't generate code specific to CPU.\n\
19931                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19932
19933   first = 1;
19934
19935   show (stream, "3900", &column, &first);
19936   show (stream, "4010", &column, &first);
19937   show (stream, "4100", &column, &first);
19938   show (stream, "4650", &column, &first);
19939   fputc ('\n', stream);
19940
19941   fprintf (stream, _("\
19942 -mips16                 generate mips16 instructions\n\
19943 -no-mips16              do not generate mips16 instructions\n"));
19944   fprintf (stream, _("\
19945 -mmicromips             generate microMIPS instructions\n\
19946 -mno-micromips          do not generate microMIPS instructions\n"));
19947   fprintf (stream, _("\
19948 -msmartmips             generate smartmips instructions\n\
19949 -mno-smartmips          do not generate smartmips instructions\n"));  
19950   fprintf (stream, _("\
19951 -mdsp                   generate DSP instructions\n\
19952 -mno-dsp                do not generate DSP instructions\n"));
19953   fprintf (stream, _("\
19954 -mdspr2                 generate DSP R2 instructions\n\
19955 -mno-dspr2              do not generate DSP R2 instructions\n"));
19956   fprintf (stream, _("\
19957 -mmt                    generate MT instructions\n\
19958 -mno-mt                 do not generate MT instructions\n"));
19959   fprintf (stream, _("\
19960 -mmcu                   generate MCU instructions\n\
19961 -mno-mcu                do not generate MCU instructions\n"));
19962   fprintf (stream, _("\
19963 -mvirt                  generate Virtualization instructions\n\
19964 -mno-virt               do not generate Virtualization instructions\n"));
19965   fprintf (stream, _("\
19966 -minsn32                only generate 32-bit microMIPS instructions\n\
19967 -mno-insn32             generate all microMIPS instructions\n"));
19968   fprintf (stream, _("\
19969 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19970 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19971 -mfix-vr4120            work around certain VR4120 errata\n\
19972 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19973 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19974 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19975 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19976 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19977 -msym32                 assume all symbols have 32-bit values\n\
19978 -O0                     remove unneeded NOPs, do not swap branches\n\
19979 -O                      remove unneeded NOPs and swap branches\n\
19980 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19981 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19982   fprintf (stream, _("\
19983 -mhard-float            allow floating-point instructions\n\
19984 -msoft-float            do not allow floating-point instructions\n\
19985 -msingle-float          only allow 32-bit floating-point operations\n\
19986 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19987 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19988 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19989 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19990
19991   first = 1;
19992
19993   show (stream, "legacy", &column, &first);
19994   show (stream, "2008", &column, &first);
19995
19996   fputc ('\n', stream);
19997
19998   fprintf (stream, _("\
19999 -KPIC, -call_shared     generate SVR4 position independent code\n\
20000 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
20001 -mvxworks-pic           generate VxWorks position independent code\n\
20002 -non_shared             do not generate code that can operate with DSOs\n\
20003 -xgot                   assume a 32 bit GOT\n\
20004 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
20005 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
20006                         position dependent (non shared) code\n\
20007 -mabi=ABI               create ABI conformant object file for:\n"));
20008
20009   first = 1;
20010
20011   show (stream, "32", &column, &first);
20012   show (stream, "o64", &column, &first);
20013   show (stream, "n32", &column, &first);
20014   show (stream, "64", &column, &first);
20015   show (stream, "eabi", &column, &first);
20016
20017   fputc ('\n', stream);
20018
20019   fprintf (stream, _("\
20020 -32                     create o32 ABI object file (default)\n\
20021 -n32                    create n32 ABI object file\n\
20022 -64                     create 64 ABI object file\n"));
20023 }
20024
20025 #ifdef TE_IRIX
20026 enum dwarf2_format
20027 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
20028 {
20029   if (HAVE_64BIT_SYMBOLS)
20030     return dwarf2_format_64bit_irix;
20031   else
20032     return dwarf2_format_32bit;
20033 }
20034 #endif
20035
20036 int
20037 mips_dwarf2_addr_size (void)
20038 {
20039   if (HAVE_64BIT_OBJECTS)
20040     return 8;
20041   else
20042     return 4;
20043 }
20044
20045 /* Standard calling conventions leave the CFA at SP on entry.  */
20046 void
20047 mips_cfi_frame_initial_instructions (void)
20048 {
20049   cfi_add_CFA_def_cfa_register (SP);
20050 }
20051
20052 int
20053 tc_mips_regname_to_dw2regnum (char *regname)
20054 {
20055   unsigned int regnum = -1;
20056   unsigned int reg;
20057
20058   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
20059     regnum = reg;
20060
20061   return regnum;
20062 }