include/opcode/
[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 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2048
2049 static void
2050 mips_record_compressed_mode (void)
2051 {
2052   segment_info_type *si;
2053
2054   si = seg_info (now_seg);
2055   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2056     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2057   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2058     si->tc_segment_info_data.micromips = mips_opts.micromips;
2059 }
2060
2061 /* Read a standard MIPS instruction from BUF.  */
2062
2063 static unsigned long
2064 read_insn (char *buf)
2065 {
2066   if (target_big_endian)
2067     return bfd_getb32 ((bfd_byte *) buf);
2068   else
2069     return bfd_getl32 ((bfd_byte *) buf);
2070 }
2071
2072 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2073    the next byte.  */
2074
2075 static char *
2076 write_insn (char *buf, unsigned int insn)
2077 {
2078   md_number_to_chars (buf, insn, 4);
2079   return buf + 4;
2080 }
2081
2082 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2083    has length LENGTH.  */
2084
2085 static unsigned long
2086 read_compressed_insn (char *buf, unsigned int length)
2087 {
2088   unsigned long insn;
2089   unsigned int i;
2090
2091   insn = 0;
2092   for (i = 0; i < length; i += 2)
2093     {
2094       insn <<= 16;
2095       if (target_big_endian)
2096         insn |= bfd_getb16 ((char *) buf);
2097       else
2098         insn |= bfd_getl16 ((char *) buf);
2099       buf += 2;
2100     }
2101   return insn;
2102 }
2103
2104 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2105    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2106
2107 static char *
2108 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2109 {
2110   unsigned int i;
2111
2112   for (i = 0; i < length; i += 2)
2113     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2114   return buf + length;
2115 }
2116
2117 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2118
2119 static void
2120 install_insn (const struct mips_cl_insn *insn)
2121 {
2122   char *f = insn->frag->fr_literal + insn->where;
2123   if (HAVE_CODE_COMPRESSION)
2124     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2125   else
2126     write_insn (f, insn->insn_opcode);
2127   mips_record_compressed_mode ();
2128 }
2129
2130 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2131    and install the opcode in the new location.  */
2132
2133 static void
2134 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2135 {
2136   size_t i;
2137
2138   insn->frag = frag;
2139   insn->where = where;
2140   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2141     if (insn->fixp[i] != NULL)
2142       {
2143         insn->fixp[i]->fx_frag = frag;
2144         insn->fixp[i]->fx_where = where;
2145       }
2146   install_insn (insn);
2147 }
2148
2149 /* Add INSN to the end of the output.  */
2150
2151 static void
2152 add_fixed_insn (struct mips_cl_insn *insn)
2153 {
2154   char *f = frag_more (insn_length (insn));
2155   move_insn (insn, frag_now, f - frag_now->fr_literal);
2156 }
2157
2158 /* Start a variant frag and move INSN to the start of the variant part,
2159    marking it as fixed.  The other arguments are as for frag_var.  */
2160
2161 static void
2162 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2163                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2164 {
2165   frag_grow (max_chars);
2166   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2167   insn->fixed_p = 1;
2168   frag_var (rs_machine_dependent, max_chars, var,
2169             subtype, symbol, offset, NULL);
2170 }
2171
2172 /* Insert N copies of INSN into the history buffer, starting at
2173    position FIRST.  Neither FIRST nor N need to be clipped.  */
2174
2175 static void
2176 insert_into_history (unsigned int first, unsigned int n,
2177                      const struct mips_cl_insn *insn)
2178 {
2179   if (mips_relax.sequence != 2)
2180     {
2181       unsigned int i;
2182
2183       for (i = ARRAY_SIZE (history); i-- > first;)
2184         if (i >= first + n)
2185           history[i] = history[i - n];
2186         else
2187           history[i] = *insn;
2188     }
2189 }
2190
2191 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2192    the idea is to make it obvious at a glance that each errata is
2193    included.  */
2194
2195 static void
2196 init_vr4120_conflicts (void)
2197 {
2198 #define CONFLICT(FIRST, SECOND) \
2199     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2200
2201   /* Errata 21 - [D]DIV[U] after [D]MACC */
2202   CONFLICT (MACC, DIV);
2203   CONFLICT (DMACC, DIV);
2204
2205   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2206   CONFLICT (DMULT, DMULT);
2207   CONFLICT (DMULT, DMACC);
2208   CONFLICT (DMACC, DMULT);
2209   CONFLICT (DMACC, DMACC);
2210
2211   /* Errata 24 - MT{LO,HI} after [D]MACC */
2212   CONFLICT (MACC, MTHILO);
2213   CONFLICT (DMACC, MTHILO);
2214
2215   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2216      instruction is executed immediately after a MACC or DMACC
2217      instruction, the result of [either instruction] is incorrect."  */
2218   CONFLICT (MACC, MULT);
2219   CONFLICT (MACC, DMULT);
2220   CONFLICT (DMACC, MULT);
2221   CONFLICT (DMACC, DMULT);
2222
2223   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2224      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2225      DDIV or DDIVU instruction, the result of the MACC or
2226      DMACC instruction is incorrect.".  */
2227   CONFLICT (DMULT, MACC);
2228   CONFLICT (DMULT, DMACC);
2229   CONFLICT (DIV, MACC);
2230   CONFLICT (DIV, DMACC);
2231
2232 #undef CONFLICT
2233 }
2234
2235 struct regname {
2236   const char *name;
2237   unsigned int num;
2238 };
2239
2240 #define RTYPE_MASK      0x1ff00
2241 #define RTYPE_NUM       0x00100
2242 #define RTYPE_FPU       0x00200
2243 #define RTYPE_FCC       0x00400
2244 #define RTYPE_VEC       0x00800
2245 #define RTYPE_GP        0x01000
2246 #define RTYPE_CP0       0x02000
2247 #define RTYPE_PC        0x04000
2248 #define RTYPE_ACC       0x08000
2249 #define RTYPE_CCC       0x10000
2250 #define RNUM_MASK       0x000ff
2251 #define RWARN           0x80000
2252
2253 #define GENERIC_REGISTER_NUMBERS \
2254     {"$0",      RTYPE_NUM | 0},  \
2255     {"$1",      RTYPE_NUM | 1},  \
2256     {"$2",      RTYPE_NUM | 2},  \
2257     {"$3",      RTYPE_NUM | 3},  \
2258     {"$4",      RTYPE_NUM | 4},  \
2259     {"$5",      RTYPE_NUM | 5},  \
2260     {"$6",      RTYPE_NUM | 6},  \
2261     {"$7",      RTYPE_NUM | 7},  \
2262     {"$8",      RTYPE_NUM | 8},  \
2263     {"$9",      RTYPE_NUM | 9},  \
2264     {"$10",     RTYPE_NUM | 10}, \
2265     {"$11",     RTYPE_NUM | 11}, \
2266     {"$12",     RTYPE_NUM | 12}, \
2267     {"$13",     RTYPE_NUM | 13}, \
2268     {"$14",     RTYPE_NUM | 14}, \
2269     {"$15",     RTYPE_NUM | 15}, \
2270     {"$16",     RTYPE_NUM | 16}, \
2271     {"$17",     RTYPE_NUM | 17}, \
2272     {"$18",     RTYPE_NUM | 18}, \
2273     {"$19",     RTYPE_NUM | 19}, \
2274     {"$20",     RTYPE_NUM | 20}, \
2275     {"$21",     RTYPE_NUM | 21}, \
2276     {"$22",     RTYPE_NUM | 22}, \
2277     {"$23",     RTYPE_NUM | 23}, \
2278     {"$24",     RTYPE_NUM | 24}, \
2279     {"$25",     RTYPE_NUM | 25}, \
2280     {"$26",     RTYPE_NUM | 26}, \
2281     {"$27",     RTYPE_NUM | 27}, \
2282     {"$28",     RTYPE_NUM | 28}, \
2283     {"$29",     RTYPE_NUM | 29}, \
2284     {"$30",     RTYPE_NUM | 30}, \
2285     {"$31",     RTYPE_NUM | 31} 
2286
2287 #define FPU_REGISTER_NAMES       \
2288     {"$f0",     RTYPE_FPU | 0},  \
2289     {"$f1",     RTYPE_FPU | 1},  \
2290     {"$f2",     RTYPE_FPU | 2},  \
2291     {"$f3",     RTYPE_FPU | 3},  \
2292     {"$f4",     RTYPE_FPU | 4},  \
2293     {"$f5",     RTYPE_FPU | 5},  \
2294     {"$f6",     RTYPE_FPU | 6},  \
2295     {"$f7",     RTYPE_FPU | 7},  \
2296     {"$f8",     RTYPE_FPU | 8},  \
2297     {"$f9",     RTYPE_FPU | 9},  \
2298     {"$f10",    RTYPE_FPU | 10}, \
2299     {"$f11",    RTYPE_FPU | 11}, \
2300     {"$f12",    RTYPE_FPU | 12}, \
2301     {"$f13",    RTYPE_FPU | 13}, \
2302     {"$f14",    RTYPE_FPU | 14}, \
2303     {"$f15",    RTYPE_FPU | 15}, \
2304     {"$f16",    RTYPE_FPU | 16}, \
2305     {"$f17",    RTYPE_FPU | 17}, \
2306     {"$f18",    RTYPE_FPU | 18}, \
2307     {"$f19",    RTYPE_FPU | 19}, \
2308     {"$f20",    RTYPE_FPU | 20}, \
2309     {"$f21",    RTYPE_FPU | 21}, \
2310     {"$f22",    RTYPE_FPU | 22}, \
2311     {"$f23",    RTYPE_FPU | 23}, \
2312     {"$f24",    RTYPE_FPU | 24}, \
2313     {"$f25",    RTYPE_FPU | 25}, \
2314     {"$f26",    RTYPE_FPU | 26}, \
2315     {"$f27",    RTYPE_FPU | 27}, \
2316     {"$f28",    RTYPE_FPU | 28}, \
2317     {"$f29",    RTYPE_FPU | 29}, \
2318     {"$f30",    RTYPE_FPU | 30}, \
2319     {"$f31",    RTYPE_FPU | 31}
2320
2321 #define FPU_CONDITION_CODE_NAMES \
2322     {"$fcc0",   RTYPE_FCC | 0},  \
2323     {"$fcc1",   RTYPE_FCC | 1},  \
2324     {"$fcc2",   RTYPE_FCC | 2},  \
2325     {"$fcc3",   RTYPE_FCC | 3},  \
2326     {"$fcc4",   RTYPE_FCC | 4},  \
2327     {"$fcc5",   RTYPE_FCC | 5},  \
2328     {"$fcc6",   RTYPE_FCC | 6},  \
2329     {"$fcc7",   RTYPE_FCC | 7}
2330
2331 #define COPROC_CONDITION_CODE_NAMES         \
2332     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2333     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2334     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2335     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2336     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2337     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2338     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2339     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2340
2341 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2342     {"$a4",     RTYPE_GP | 8},  \
2343     {"$a5",     RTYPE_GP | 9},  \
2344     {"$a6",     RTYPE_GP | 10}, \
2345     {"$a7",     RTYPE_GP | 11}, \
2346     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2347     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2348     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2349     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2350     {"$t0",     RTYPE_GP | 12}, \
2351     {"$t1",     RTYPE_GP | 13}, \
2352     {"$t2",     RTYPE_GP | 14}, \
2353     {"$t3",     RTYPE_GP | 15}
2354
2355 #define O32_SYMBOLIC_REGISTER_NAMES \
2356     {"$t0",     RTYPE_GP | 8},  \
2357     {"$t1",     RTYPE_GP | 9},  \
2358     {"$t2",     RTYPE_GP | 10}, \
2359     {"$t3",     RTYPE_GP | 11}, \
2360     {"$t4",     RTYPE_GP | 12}, \
2361     {"$t5",     RTYPE_GP | 13}, \
2362     {"$t6",     RTYPE_GP | 14}, \
2363     {"$t7",     RTYPE_GP | 15}, \
2364     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2365     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2366     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2367     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2368
2369 /* Remaining symbolic register names */
2370 #define SYMBOLIC_REGISTER_NAMES \
2371     {"$zero",   RTYPE_GP | 0},  \
2372     {"$at",     RTYPE_GP | 1},  \
2373     {"$AT",     RTYPE_GP | 1},  \
2374     {"$v0",     RTYPE_GP | 2},  \
2375     {"$v1",     RTYPE_GP | 3},  \
2376     {"$a0",     RTYPE_GP | 4},  \
2377     {"$a1",     RTYPE_GP | 5},  \
2378     {"$a2",     RTYPE_GP | 6},  \
2379     {"$a3",     RTYPE_GP | 7},  \
2380     {"$s0",     RTYPE_GP | 16}, \
2381     {"$s1",     RTYPE_GP | 17}, \
2382     {"$s2",     RTYPE_GP | 18}, \
2383     {"$s3",     RTYPE_GP | 19}, \
2384     {"$s4",     RTYPE_GP | 20}, \
2385     {"$s5",     RTYPE_GP | 21}, \
2386     {"$s6",     RTYPE_GP | 22}, \
2387     {"$s7",     RTYPE_GP | 23}, \
2388     {"$t8",     RTYPE_GP | 24}, \
2389     {"$t9",     RTYPE_GP | 25}, \
2390     {"$k0",     RTYPE_GP | 26}, \
2391     {"$kt0",    RTYPE_GP | 26}, \
2392     {"$k1",     RTYPE_GP | 27}, \
2393     {"$kt1",    RTYPE_GP | 27}, \
2394     {"$gp",     RTYPE_GP | 28}, \
2395     {"$sp",     RTYPE_GP | 29}, \
2396     {"$s8",     RTYPE_GP | 30}, \
2397     {"$fp",     RTYPE_GP | 30}, \
2398     {"$ra",     RTYPE_GP | 31}
2399
2400 #define MIPS16_SPECIAL_REGISTER_NAMES \
2401     {"$pc",     RTYPE_PC | 0}
2402
2403 #define MDMX_VECTOR_REGISTER_NAMES \
2404     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2405     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2406     {"$v2",     RTYPE_VEC | 2},  \
2407     {"$v3",     RTYPE_VEC | 3},  \
2408     {"$v4",     RTYPE_VEC | 4},  \
2409     {"$v5",     RTYPE_VEC | 5},  \
2410     {"$v6",     RTYPE_VEC | 6},  \
2411     {"$v7",     RTYPE_VEC | 7},  \
2412     {"$v8",     RTYPE_VEC | 8},  \
2413     {"$v9",     RTYPE_VEC | 9},  \
2414     {"$v10",    RTYPE_VEC | 10}, \
2415     {"$v11",    RTYPE_VEC | 11}, \
2416     {"$v12",    RTYPE_VEC | 12}, \
2417     {"$v13",    RTYPE_VEC | 13}, \
2418     {"$v14",    RTYPE_VEC | 14}, \
2419     {"$v15",    RTYPE_VEC | 15}, \
2420     {"$v16",    RTYPE_VEC | 16}, \
2421     {"$v17",    RTYPE_VEC | 17}, \
2422     {"$v18",    RTYPE_VEC | 18}, \
2423     {"$v19",    RTYPE_VEC | 19}, \
2424     {"$v20",    RTYPE_VEC | 20}, \
2425     {"$v21",    RTYPE_VEC | 21}, \
2426     {"$v22",    RTYPE_VEC | 22}, \
2427     {"$v23",    RTYPE_VEC | 23}, \
2428     {"$v24",    RTYPE_VEC | 24}, \
2429     {"$v25",    RTYPE_VEC | 25}, \
2430     {"$v26",    RTYPE_VEC | 26}, \
2431     {"$v27",    RTYPE_VEC | 27}, \
2432     {"$v28",    RTYPE_VEC | 28}, \
2433     {"$v29",    RTYPE_VEC | 29}, \
2434     {"$v30",    RTYPE_VEC | 30}, \
2435     {"$v31",    RTYPE_VEC | 31}
2436
2437 #define MIPS_DSP_ACCUMULATOR_NAMES \
2438     {"$ac0",    RTYPE_ACC | 0}, \
2439     {"$ac1",    RTYPE_ACC | 1}, \
2440     {"$ac2",    RTYPE_ACC | 2}, \
2441     {"$ac3",    RTYPE_ACC | 3}
2442
2443 static const struct regname reg_names[] = {
2444   GENERIC_REGISTER_NUMBERS,
2445   FPU_REGISTER_NAMES,
2446   FPU_CONDITION_CODE_NAMES,
2447   COPROC_CONDITION_CODE_NAMES,
2448
2449   /* The $txx registers depends on the abi,
2450      these will be added later into the symbol table from
2451      one of the tables below once mips_abi is set after 
2452      parsing of arguments from the command line. */
2453   SYMBOLIC_REGISTER_NAMES,
2454
2455   MIPS16_SPECIAL_REGISTER_NAMES,
2456   MDMX_VECTOR_REGISTER_NAMES,
2457   MIPS_DSP_ACCUMULATOR_NAMES,
2458   {0, 0}
2459 };
2460
2461 static const struct regname reg_names_o32[] = {
2462   O32_SYMBOLIC_REGISTER_NAMES,
2463   {0, 0}
2464 };
2465
2466 static const struct regname reg_names_n32n64[] = {
2467   N32N64_SYMBOLIC_REGISTER_NAMES,
2468   {0, 0}
2469 };
2470
2471 /* Check if S points at a valid register specifier according to TYPES.
2472    If so, then return 1, advance S to consume the specifier and store
2473    the register's number in REGNOP, otherwise return 0.  */
2474
2475 static int
2476 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2477 {
2478   symbolS *symbolP;
2479   char *e;
2480   char save_c;
2481   int reg = -1;
2482
2483   /* Find end of name.  */
2484   e = *s;
2485   if (is_name_beginner (*e))
2486     ++e;
2487   while (is_part_of_name (*e))
2488     ++e;
2489
2490   /* Terminate name.  */
2491   save_c = *e;
2492   *e = '\0';
2493
2494   /* Look for a register symbol.  */
2495   if ((symbolP = symbol_find (*s)) && S_GET_SEGMENT (symbolP) == reg_section)
2496     {
2497       int r = S_GET_VALUE (symbolP);
2498       if (r & types)
2499         reg = r & RNUM_MASK;
2500       else if ((types & RTYPE_VEC) && (r & ~1) == (RTYPE_GP | 2))
2501         /* Convert GP reg $v0/1 to MDMX reg $v0/1!  */
2502         reg = (r & RNUM_MASK) - 2;
2503     }
2504   /* Else see if this is a register defined in an itbl entry.  */
2505   else if ((types & RTYPE_GP) && itbl_have_entries)
2506     {
2507       char *n = *s;
2508       unsigned long r;
2509
2510       if (*n == '$')
2511         ++n;
2512       if (itbl_get_reg_val (n, &r))
2513         reg = r & RNUM_MASK;
2514     }
2515
2516   /* Advance to next token if a register was recognised.  */
2517   if (reg >= 0)
2518     *s = e;
2519   else if (types & RWARN)
2520     as_warn (_("Unrecognized register name `%s'"), *s);
2521
2522   *e = save_c;
2523   if (regnop)
2524     *regnop = reg;
2525   return reg >= 0;
2526 }
2527
2528 /* Check if S points at a valid register list according to TYPES.
2529    If so, then return 1, advance S to consume the list and store
2530    the registers present on the list as a bitmask of ones in REGLISTP,
2531    otherwise return 0.  A valid list comprises a comma-separated
2532    enumeration of valid single registers and/or dash-separated
2533    contiguous register ranges as determined by their numbers.
2534
2535    As a special exception if one of s0-s7 registers is specified as
2536    the range's lower delimiter and s8 (fp) is its upper one, then no
2537    registers whose numbers place them between s7 and s8 (i.e. $24-$29)
2538    are selected; they have to be listed separately if needed.  */
2539
2540 static int
2541 reglist_lookup (char **s, unsigned int types, unsigned int *reglistp)
2542 {
2543   unsigned int reglist = 0;
2544   unsigned int lastregno;
2545   bfd_boolean ok = TRUE;
2546   unsigned int regmask;
2547   char *s_endlist = *s;
2548   char *s_reset = *s;
2549   unsigned int regno;
2550
2551   while (reg_lookup (s, types, &regno))
2552     {
2553       lastregno = regno;
2554       if (**s == '-')
2555         {
2556           (*s)++;
2557           ok = reg_lookup (s, types, &lastregno);
2558           if (ok && lastregno < regno)
2559             ok = FALSE;
2560           if (!ok)
2561             break;
2562         }
2563
2564       if (lastregno == FP && regno >= S0 && regno <= S7)
2565         {
2566           lastregno = S7;
2567           reglist |= 1 << FP;
2568         }
2569       regmask = 1 << lastregno;
2570       regmask = (regmask << 1) - 1;
2571       regmask ^= (1 << regno) - 1;
2572       reglist |= regmask;
2573
2574       s_endlist = *s;
2575       if (**s != ',')
2576         break;
2577       (*s)++;
2578     }
2579
2580   if (ok)
2581     *s = s_endlist;
2582   else
2583     *s = s_reset;
2584   if (reglistp)
2585     *reglistp = reglist;
2586   return ok && reglist != 0;
2587 }
2588
2589 static unsigned int
2590 mips_lookup_reg_pair (unsigned int regno1, unsigned int regno2,
2591                       const unsigned int *map1, const unsigned int *map2,
2592                       unsigned int count)
2593 {
2594   unsigned int i;
2595
2596   for (i = 0; i < count; i++)
2597     if (map1[i] == regno1 && map2[i] == regno2)
2598       return i;
2599   return ILLEGAL_REG;
2600 }
2601
2602 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
2603    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
2604
2605 static bfd_boolean
2606 is_opcode_valid (const struct mips_opcode *mo)
2607 {
2608   int isa = mips_opts.isa;
2609   int ase = mips_opts.ase;
2610   int fp_s, fp_d;
2611   unsigned int i;
2612
2613   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2614     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2615       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
2616         ase |= mips_ases[i].flags64;
2617
2618   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
2619     return FALSE;
2620
2621   /* Check whether the instruction or macro requires single-precision or
2622      double-precision floating-point support.  Note that this information is
2623      stored differently in the opcode table for insns and macros.  */
2624   if (mo->pinfo == INSN_MACRO)
2625     {
2626       fp_s = mo->pinfo2 & INSN2_M_FP_S;
2627       fp_d = mo->pinfo2 & INSN2_M_FP_D;
2628     }
2629   else
2630     {
2631       fp_s = mo->pinfo & FP_S;
2632       fp_d = mo->pinfo & FP_D;
2633     }
2634
2635   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
2636     return FALSE;
2637
2638   if (fp_s && mips_opts.soft_float)
2639     return FALSE;
2640
2641   return TRUE;
2642 }
2643
2644 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
2645    selected ISA and architecture.  */
2646
2647 static bfd_boolean
2648 is_opcode_valid_16 (const struct mips_opcode *mo)
2649 {
2650   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
2651 }
2652
2653 /* Return TRUE if the size of the microMIPS opcode MO matches one
2654    explicitly requested.  Always TRUE in the standard MIPS mode.  */
2655
2656 static bfd_boolean
2657 is_size_valid (const struct mips_opcode *mo)
2658 {
2659   if (!mips_opts.micromips)
2660     return TRUE;
2661
2662   if (mips_opts.insn32)
2663     {
2664       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
2665         return FALSE;
2666       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
2667         return FALSE;
2668     }
2669   if (!forced_insn_length)
2670     return TRUE;
2671   if (mo->pinfo == INSN_MACRO)
2672     return FALSE;
2673   return forced_insn_length == micromips_insn_length (mo);
2674 }
2675
2676 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
2677    of the preceding instruction.  Always TRUE in the standard MIPS mode.
2678
2679    We don't accept macros in 16-bit delay slots to avoid a case where
2680    a macro expansion fails because it relies on a preceding 32-bit real
2681    instruction to have matched and does not handle the operands correctly.
2682    The only macros that may expand to 16-bit instructions are JAL that
2683    cannot be placed in a delay slot anyway, and corner cases of BALIGN
2684    and BGT (that likewise cannot be placed in a delay slot) that decay to
2685    a NOP.  In all these cases the macros precede any corresponding real
2686    instruction definitions in the opcode table, so they will match in the
2687    second pass where the size of the delay slot is ignored and therefore
2688    produce correct code.  */
2689
2690 static bfd_boolean
2691 is_delay_slot_valid (const struct mips_opcode *mo)
2692 {
2693   if (!mips_opts.micromips)
2694     return TRUE;
2695
2696   if (mo->pinfo == INSN_MACRO)
2697     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
2698   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
2699       && micromips_insn_length (mo) != 4)
2700     return FALSE;
2701   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
2702       && micromips_insn_length (mo) != 2)
2703     return FALSE;
2704
2705   return TRUE;
2706 }
2707
2708 /* For consistency checking, verify that all bits of OPCODE are
2709    specified either by the match/mask part of the instruction
2710    definition, or by the operand list.  INSN_BITS says which
2711    bits of the instruction are significant and DECODE_OPERAND
2712    provides the mips_operand description of each operand.  */
2713
2714 static int
2715 validate_mips_insn (const struct mips_opcode *opcode,
2716                     unsigned long insn_bits,
2717                     const struct mips_operand *(*decode_operand) (const char *))
2718 {
2719   const char *s;
2720   unsigned long used_bits, doubled, undefined;
2721   const struct mips_operand *operand;
2722
2723   if ((opcode->mask & opcode->match) != opcode->match)
2724     {
2725       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
2726               opcode->name, opcode->args);
2727       return 0;
2728     }
2729   used_bits = 0;
2730   for (s = opcode->args; *s; ++s)
2731     switch (*s)
2732       {
2733       case ',':
2734       case '(':
2735       case ')':
2736         break;
2737
2738       default:
2739         operand = decode_operand (s);
2740         if (!operand)
2741           {
2742             as_bad (_("internal: unknown operand type: %s %s"),
2743                     opcode->name, opcode->args);
2744             return 0;
2745           }
2746         used_bits |= ((1 << operand->size) - 1) << operand->lsb;
2747         if (operand->type == OP_MDMX_IMM_REG)
2748           /* Bit 5 is the format selector (OB vs QH).  The opcode table
2749              has separate entries for each format.  */
2750           used_bits &= ~(1 << (operand->lsb + 5));
2751         /* Skip prefix characters.  */
2752         if (*s == '+' || *s == 'm')
2753           ++s;
2754         break;
2755       }
2756   doubled = used_bits & opcode->mask & insn_bits;
2757   if (doubled)
2758     {
2759       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
2760                 " %s %s"), doubled, opcode->name, opcode->args);
2761       return 0;
2762     }
2763   used_bits |= opcode->mask;
2764   undefined = ~used_bits & insn_bits;
2765   if (undefined)
2766     {
2767       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
2768               undefined, opcode->name, opcode->args);
2769       return 0;
2770     }
2771   used_bits &= ~insn_bits;
2772   if (used_bits)
2773     {
2774       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
2775               used_bits, opcode->name, opcode->args);
2776       return 0;
2777     }
2778   return 1;
2779 }
2780
2781 /* The microMIPS version of validate_mips_insn.  */
2782
2783 static int
2784 validate_micromips_insn (const struct mips_opcode *opc)
2785 {
2786   unsigned long insn_bits;
2787   unsigned long major;
2788   unsigned int length;
2789
2790   length = micromips_insn_length (opc);
2791   if (length != 2 && length != 4)
2792     {
2793       as_bad (_("Internal error: bad microMIPS opcode (incorrect length: %u): "
2794                 "%s %s"), length, opc->name, opc->args);
2795       return 0;
2796     }
2797   major = opc->match >> (10 + 8 * (length - 2));
2798   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
2799       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
2800     {
2801       as_bad (_("Internal error: bad microMIPS opcode "
2802                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
2803       return 0;
2804     }
2805
2806   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
2807   insn_bits = 1 << 4 * length;
2808   insn_bits <<= 4 * length;
2809   insn_bits -= 1;
2810   return validate_mips_insn (opc, insn_bits, decode_micromips_operand);
2811 }
2812
2813 /* This function is called once, at assembler startup time.  It should set up
2814    all the tables, etc. that the MD part of the assembler will need.  */
2815
2816 void
2817 md_begin (void)
2818 {
2819   const char *retval = NULL;
2820   int i = 0;
2821   int broken = 0;
2822
2823   if (mips_pic != NO_PIC)
2824     {
2825       if (g_switch_seen && g_switch_value != 0)
2826         as_bad (_("-G may not be used in position-independent code"));
2827       g_switch_value = 0;
2828     }
2829
2830   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
2831     as_warn (_("Could not set architecture and machine"));
2832
2833   op_hash = hash_new ();
2834
2835   for (i = 0; i < NUMOPCODES;)
2836     {
2837       const char *name = mips_opcodes[i].name;
2838
2839       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
2840       if (retval != NULL)
2841         {
2842           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
2843                    mips_opcodes[i].name, retval);
2844           /* Probably a memory allocation problem?  Give up now.  */
2845           as_fatal (_("Broken assembler.  No assembly attempted."));
2846         }
2847       do
2848         {
2849           if (mips_opcodes[i].pinfo != INSN_MACRO)
2850             {
2851               if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
2852                                        decode_mips_operand))
2853                 broken = 1;
2854               if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2855                 {
2856                   create_insn (&nop_insn, mips_opcodes + i);
2857                   if (mips_fix_loongson2f_nop)
2858                     nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
2859                   nop_insn.fixed_p = 1;
2860                 }
2861             }
2862           ++i;
2863         }
2864       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
2865     }
2866
2867   mips16_op_hash = hash_new ();
2868
2869   i = 0;
2870   while (i < bfd_mips16_num_opcodes)
2871     {
2872       const char *name = mips16_opcodes[i].name;
2873
2874       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
2875       if (retval != NULL)
2876         as_fatal (_("internal: can't hash `%s': %s"),
2877                   mips16_opcodes[i].name, retval);
2878       do
2879         {
2880           if (mips16_opcodes[i].pinfo != INSN_MACRO
2881               && ((mips16_opcodes[i].match & mips16_opcodes[i].mask)
2882                   != mips16_opcodes[i].match))
2883             {
2884               fprintf (stderr, _("internal error: bad mips16 opcode: %s %s\n"),
2885                        mips16_opcodes[i].name, mips16_opcodes[i].args);
2886               broken = 1;
2887             }
2888           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
2889             {
2890               create_insn (&mips16_nop_insn, mips16_opcodes + i);
2891               mips16_nop_insn.fixed_p = 1;
2892             }
2893           ++i;
2894         }
2895       while (i < bfd_mips16_num_opcodes
2896              && strcmp (mips16_opcodes[i].name, name) == 0);
2897     }
2898
2899   micromips_op_hash = hash_new ();
2900
2901   i = 0;
2902   while (i < bfd_micromips_num_opcodes)
2903     {
2904       const char *name = micromips_opcodes[i].name;
2905
2906       retval = hash_insert (micromips_op_hash, name,
2907                             (void *) &micromips_opcodes[i]);
2908       if (retval != NULL)
2909         as_fatal (_("internal: can't hash `%s': %s"),
2910                   micromips_opcodes[i].name, retval);
2911       do
2912         if (micromips_opcodes[i].pinfo != INSN_MACRO)
2913           {
2914             struct mips_cl_insn *micromips_nop_insn;
2915
2916             if (!validate_micromips_insn (&micromips_opcodes[i]))
2917               broken = 1;
2918
2919             if (micromips_insn_length (micromips_opcodes + i) == 2)
2920               micromips_nop_insn = &micromips_nop16_insn;
2921             else if (micromips_insn_length (micromips_opcodes + i) == 4)
2922               micromips_nop_insn = &micromips_nop32_insn;
2923             else
2924               continue;
2925
2926             if (micromips_nop_insn->insn_mo == NULL
2927                 && strcmp (name, "nop") == 0)
2928               {
2929                 create_insn (micromips_nop_insn, micromips_opcodes + i);
2930                 micromips_nop_insn->fixed_p = 1;
2931               }
2932           }
2933       while (++i < bfd_micromips_num_opcodes
2934              && strcmp (micromips_opcodes[i].name, name) == 0);
2935     }
2936
2937   if (broken)
2938     as_fatal (_("Broken assembler.  No assembly attempted."));
2939
2940   /* We add all the general register names to the symbol table.  This
2941      helps us detect invalid uses of them.  */
2942   for (i = 0; reg_names[i].name; i++) 
2943     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
2944                                      reg_names[i].num, /* & RNUM_MASK, */
2945                                      &zero_address_frag));
2946   if (HAVE_NEWABI)
2947     for (i = 0; reg_names_n32n64[i].name; i++) 
2948       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
2949                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
2950                                        &zero_address_frag));
2951   else
2952     for (i = 0; reg_names_o32[i].name; i++) 
2953       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
2954                                        reg_names_o32[i].num, /* & RNUM_MASK, */
2955                                        &zero_address_frag));
2956
2957   mips_no_prev_insn ();
2958
2959   mips_gprmask = 0;
2960   mips_cprmask[0] = 0;
2961   mips_cprmask[1] = 0;
2962   mips_cprmask[2] = 0;
2963   mips_cprmask[3] = 0;
2964
2965   /* set the default alignment for the text section (2**2) */
2966   record_alignment (text_section, 2);
2967
2968   bfd_set_gp_size (stdoutput, g_switch_value);
2969
2970   /* On a native system other than VxWorks, sections must be aligned
2971      to 16 byte boundaries.  When configured for an embedded ELF
2972      target, we don't bother.  */
2973   if (strncmp (TARGET_OS, "elf", 3) != 0
2974       && strncmp (TARGET_OS, "vxworks", 7) != 0)
2975     {
2976       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
2977       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
2978       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
2979     }
2980
2981   /* Create a .reginfo section for register masks and a .mdebug
2982      section for debugging information.  */
2983   {
2984     segT seg;
2985     subsegT subseg;
2986     flagword flags;
2987     segT sec;
2988
2989     seg = now_seg;
2990     subseg = now_subseg;
2991
2992     /* The ABI says this section should be loaded so that the
2993        running program can access it.  However, we don't load it
2994        if we are configured for an embedded target */
2995     flags = SEC_READONLY | SEC_DATA;
2996     if (strncmp (TARGET_OS, "elf", 3) != 0)
2997       flags |= SEC_ALLOC | SEC_LOAD;
2998
2999     if (mips_abi != N64_ABI)
3000       {
3001         sec = subseg_new (".reginfo", (subsegT) 0);
3002
3003         bfd_set_section_flags (stdoutput, sec, flags);
3004         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3005
3006         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3007       }
3008     else
3009       {
3010         /* The 64-bit ABI uses a .MIPS.options section rather than
3011            .reginfo section.  */
3012         sec = subseg_new (".MIPS.options", (subsegT) 0);
3013         bfd_set_section_flags (stdoutput, sec, flags);
3014         bfd_set_section_alignment (stdoutput, sec, 3);
3015
3016         /* Set up the option header.  */
3017         {
3018           Elf_Internal_Options opthdr;
3019           char *f;
3020
3021           opthdr.kind = ODK_REGINFO;
3022           opthdr.size = (sizeof (Elf_External_Options)
3023                          + sizeof (Elf64_External_RegInfo));
3024           opthdr.section = 0;
3025           opthdr.info = 0;
3026           f = frag_more (sizeof (Elf_External_Options));
3027           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3028                                          (Elf_External_Options *) f);
3029
3030           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3031         }
3032       }
3033
3034     if (ECOFF_DEBUGGING)
3035       {
3036         sec = subseg_new (".mdebug", (subsegT) 0);
3037         (void) bfd_set_section_flags (stdoutput, sec,
3038                                       SEC_HAS_CONTENTS | SEC_READONLY);
3039         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3040       }
3041     else if (mips_flag_pdr)
3042       {
3043         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3044         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3045                                       SEC_READONLY | SEC_RELOC
3046                                       | SEC_DEBUGGING);
3047         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3048       }
3049
3050     subseg_set (seg, subseg);
3051   }
3052
3053   if (! ECOFF_DEBUGGING)
3054     md_obj_begin ();
3055
3056   if (mips_fix_vr4120)
3057     init_vr4120_conflicts ();
3058 }
3059
3060 void
3061 md_mips_end (void)
3062 {
3063   mips_emit_delays ();
3064   if (! ECOFF_DEBUGGING)
3065     md_obj_end ();
3066 }
3067
3068 void
3069 md_assemble (char *str)
3070 {
3071   struct mips_cl_insn insn;
3072   bfd_reloc_code_real_type unused_reloc[3]
3073     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3074
3075   imm_expr.X_op = O_absent;
3076   imm2_expr.X_op = O_absent;
3077   offset_expr.X_op = O_absent;
3078   offset_reloc[0] = BFD_RELOC_UNUSED;
3079   offset_reloc[1] = BFD_RELOC_UNUSED;
3080   offset_reloc[2] = BFD_RELOC_UNUSED;
3081
3082   mips_mark_labels ();
3083   mips_assembling_insn = TRUE;
3084
3085   if (mips_opts.mips16)
3086     mips16_ip (str, &insn);
3087   else
3088     {
3089       mips_ip (str, &insn);
3090       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3091             str, insn.insn_opcode));
3092     }
3093
3094   if (insn_error)
3095     as_bad ("%s `%s'", insn_error, str);
3096   else if (insn.insn_mo->pinfo == INSN_MACRO)
3097     {
3098       macro_start ();
3099       if (mips_opts.mips16)
3100         mips16_macro (&insn);
3101       else
3102         macro (&insn, str);
3103       macro_end ();
3104     }
3105   else
3106     {
3107       if (offset_expr.X_op != O_absent)
3108         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3109       else
3110         append_insn (&insn, NULL, unused_reloc, FALSE);
3111     }
3112
3113   mips_assembling_insn = FALSE;
3114 }
3115
3116 /* Convenience functions for abstracting away the differences between
3117    MIPS16 and non-MIPS16 relocations.  */
3118
3119 static inline bfd_boolean
3120 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3121 {
3122   switch (reloc)
3123     {
3124     case BFD_RELOC_MIPS16_JMP:
3125     case BFD_RELOC_MIPS16_GPREL:
3126     case BFD_RELOC_MIPS16_GOT16:
3127     case BFD_RELOC_MIPS16_CALL16:
3128     case BFD_RELOC_MIPS16_HI16_S:
3129     case BFD_RELOC_MIPS16_HI16:
3130     case BFD_RELOC_MIPS16_LO16:
3131       return TRUE;
3132
3133     default:
3134       return FALSE;
3135     }
3136 }
3137
3138 static inline bfd_boolean
3139 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3140 {
3141   switch (reloc)
3142     {
3143     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3144     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3145     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3146     case BFD_RELOC_MICROMIPS_GPREL16:
3147     case BFD_RELOC_MICROMIPS_JMP:
3148     case BFD_RELOC_MICROMIPS_HI16:
3149     case BFD_RELOC_MICROMIPS_HI16_S:
3150     case BFD_RELOC_MICROMIPS_LO16:
3151     case BFD_RELOC_MICROMIPS_LITERAL:
3152     case BFD_RELOC_MICROMIPS_GOT16:
3153     case BFD_RELOC_MICROMIPS_CALL16:
3154     case BFD_RELOC_MICROMIPS_GOT_HI16:
3155     case BFD_RELOC_MICROMIPS_GOT_LO16:
3156     case BFD_RELOC_MICROMIPS_CALL_HI16:
3157     case BFD_RELOC_MICROMIPS_CALL_LO16:
3158     case BFD_RELOC_MICROMIPS_SUB:
3159     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3160     case BFD_RELOC_MICROMIPS_GOT_OFST:
3161     case BFD_RELOC_MICROMIPS_GOT_DISP:
3162     case BFD_RELOC_MICROMIPS_HIGHEST:
3163     case BFD_RELOC_MICROMIPS_HIGHER:
3164     case BFD_RELOC_MICROMIPS_SCN_DISP:
3165     case BFD_RELOC_MICROMIPS_JALR:
3166       return TRUE;
3167
3168     default:
3169       return FALSE;
3170     }
3171 }
3172
3173 static inline bfd_boolean
3174 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3175 {
3176   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3177 }
3178
3179 static inline bfd_boolean
3180 got16_reloc_p (bfd_reloc_code_real_type reloc)
3181 {
3182   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3183           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3184 }
3185
3186 static inline bfd_boolean
3187 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3188 {
3189   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3190           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3191 }
3192
3193 static inline bfd_boolean
3194 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3195 {
3196   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3197           || reloc == BFD_RELOC_MICROMIPS_LO16);
3198 }
3199
3200 static inline bfd_boolean
3201 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3202 {
3203   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3204 }
3205
3206 static inline bfd_boolean
3207 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3208 {
3209   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3210           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3211 }
3212
3213 /* Return true if RELOC is a PC-relative relocation that does not have
3214    full address range.  */
3215
3216 static inline bfd_boolean
3217 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3218 {
3219   switch (reloc)
3220     {
3221     case BFD_RELOC_16_PCREL_S2:
3222     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3223     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3224     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3225       return TRUE;
3226
3227     case BFD_RELOC_32_PCREL:
3228       return HAVE_64BIT_ADDRESSES;
3229
3230     default:
3231       return FALSE;
3232     }
3233 }
3234
3235 /* Return true if the given relocation might need a matching %lo().
3236    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3237    need a matching %lo() when applied to local symbols.  */
3238
3239 static inline bfd_boolean
3240 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3241 {
3242   return (HAVE_IN_PLACE_ADDENDS
3243           && (hi16_reloc_p (reloc)
3244               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3245                  all GOT16 relocations evaluate to "G".  */
3246               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3247 }
3248
3249 /* Return the type of %lo() reloc needed by RELOC, given that
3250    reloc_needs_lo_p.  */
3251
3252 static inline bfd_reloc_code_real_type
3253 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3254 {
3255   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3256           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3257              : BFD_RELOC_LO16));
3258 }
3259
3260 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3261    relocation.  */
3262
3263 static inline bfd_boolean
3264 fixup_has_matching_lo_p (fixS *fixp)
3265 {
3266   return (fixp->fx_next != NULL
3267           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3268           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3269           && fixp->fx_offset == fixp->fx_next->fx_offset);
3270 }
3271
3272 /* This function returns true if modifying a register requires a
3273    delay.  */
3274
3275 static int
3276 reg_needs_delay (unsigned int reg)
3277 {
3278   unsigned long prev_pinfo;
3279
3280   prev_pinfo = history[0].insn_mo->pinfo;
3281   if (! mips_opts.noreorder
3282       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY)
3283            && ! gpr_interlocks)
3284           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY)
3285               && ! cop_interlocks)))
3286     {
3287       /* A load from a coprocessor or from memory.  All load delays
3288          delay the use of general register rt for one instruction.  */
3289       /* Itbl support may require additional care here.  */
3290       know (prev_pinfo & INSN_WRITE_GPR_T);
3291       if (reg == EXTRACT_OPERAND (mips_opts.micromips, RT, history[0]))
3292         return 1;
3293     }
3294
3295   return 0;
3296 }
3297
3298 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3299    says whether the labels refer to text or data.  */
3300
3301 static void
3302 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3303 {
3304   struct insn_label_list *l;
3305   valueT val;
3306
3307   for (l = labels; l != NULL; l = l->next)
3308     {
3309       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3310       symbol_set_frag (l->label, frag_now);
3311       val = (valueT) frag_now_fix ();
3312       /* MIPS16/microMIPS text labels are stored as odd.  */
3313       if (text_p && HAVE_CODE_COMPRESSION)
3314         ++val;
3315       S_SET_VALUE (l->label, val);
3316     }
3317 }
3318
3319 /* Move all labels in insn_labels to the current insertion point
3320    and treat them as text labels.  */
3321
3322 static void
3323 mips_move_text_labels (void)
3324 {
3325   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3326 }
3327
3328 static bfd_boolean
3329 s_is_linkonce (symbolS *sym, segT from_seg)
3330 {
3331   bfd_boolean linkonce = FALSE;
3332   segT symseg = S_GET_SEGMENT (sym);
3333
3334   if (symseg != from_seg && !S_IS_LOCAL (sym))
3335     {
3336       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3337         linkonce = TRUE;
3338       /* The GNU toolchain uses an extension for ELF: a section
3339          beginning with the magic string .gnu.linkonce is a
3340          linkonce section.  */
3341       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3342                    sizeof ".gnu.linkonce" - 1) == 0)
3343         linkonce = TRUE;
3344     }
3345   return linkonce;
3346 }
3347
3348 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3349    linker to handle them specially, such as generating jalx instructions
3350    when needed.  We also make them odd for the duration of the assembly,
3351    in order to generate the right sort of code.  We will make them even
3352    in the adjust_symtab routine, while leaving them marked.  This is
3353    convenient for the debugger and the disassembler.  The linker knows
3354    to make them odd again.  */
3355
3356 static void
3357 mips_compressed_mark_label (symbolS *label)
3358 {
3359   gas_assert (HAVE_CODE_COMPRESSION);
3360
3361   if (mips_opts.mips16)
3362     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3363   else
3364     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3365   if ((S_GET_VALUE (label) & 1) == 0
3366       /* Don't adjust the address if the label is global or weak, or
3367          in a link-once section, since we'll be emitting symbol reloc
3368          references to it which will be patched up by the linker, and
3369          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3370       && !S_IS_WEAK (label)
3371       && !S_IS_EXTERNAL (label)
3372       && !s_is_linkonce (label, now_seg))
3373     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3374 }
3375
3376 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3377
3378 static void
3379 mips_compressed_mark_labels (void)
3380 {
3381   struct insn_label_list *l;
3382
3383   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3384     mips_compressed_mark_label (l->label);
3385 }
3386
3387 /* End the current frag.  Make it a variant frag and record the
3388    relaxation info.  */
3389
3390 static void
3391 relax_close_frag (void)
3392 {
3393   mips_macro_warning.first_frag = frag_now;
3394   frag_var (rs_machine_dependent, 0, 0,
3395             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3396             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3397
3398   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3399   mips_relax.first_fixup = 0;
3400 }
3401
3402 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3403    See the comment above RELAX_ENCODE for more details.  */
3404
3405 static void
3406 relax_start (symbolS *symbol)
3407 {
3408   gas_assert (mips_relax.sequence == 0);
3409   mips_relax.sequence = 1;
3410   mips_relax.symbol = symbol;
3411 }
3412
3413 /* Start generating the second version of a relaxable sequence.
3414    See the comment above RELAX_ENCODE for more details.  */
3415
3416 static void
3417 relax_switch (void)
3418 {
3419   gas_assert (mips_relax.sequence == 1);
3420   mips_relax.sequence = 2;
3421 }
3422
3423 /* End the current relaxable sequence.  */
3424
3425 static void
3426 relax_end (void)
3427 {
3428   gas_assert (mips_relax.sequence == 2);
3429   relax_close_frag ();
3430   mips_relax.sequence = 0;
3431 }
3432
3433 /* Return true if IP is a delayed branch or jump.  */
3434
3435 static inline bfd_boolean
3436 delayed_branch_p (const struct mips_cl_insn *ip)
3437 {
3438   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3439                                 | INSN_COND_BRANCH_DELAY
3440                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3441 }
3442
3443 /* Return true if IP is a compact branch or jump.  */
3444
3445 static inline bfd_boolean
3446 compact_branch_p (const struct mips_cl_insn *ip)
3447 {
3448   if (mips_opts.mips16)
3449     return (ip->insn_mo->pinfo & (MIPS16_INSN_UNCOND_BRANCH
3450                                   | MIPS16_INSN_COND_BRANCH)) != 0;
3451   else
3452     return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3453                                    | INSN2_COND_BRANCH)) != 0;
3454 }
3455
3456 /* Return true if IP is an unconditional branch or jump.  */
3457
3458 static inline bfd_boolean
3459 uncond_branch_p (const struct mips_cl_insn *ip)
3460 {
3461   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3462           || (mips_opts.mips16
3463               ? (ip->insn_mo->pinfo & MIPS16_INSN_UNCOND_BRANCH) != 0
3464               : (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0));
3465 }
3466
3467 /* Return true if IP is a branch-likely instruction.  */
3468
3469 static inline bfd_boolean
3470 branch_likely_p (const struct mips_cl_insn *ip)
3471 {
3472   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3473 }
3474
3475 /* Return the type of nop that should be used to fill the delay slot
3476    of delayed branch IP.  */
3477
3478 static struct mips_cl_insn *
3479 get_delay_slot_nop (const struct mips_cl_insn *ip)
3480 {
3481   if (mips_opts.micromips
3482       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3483     return &micromips_nop32_insn;
3484   return NOP_INSN;
3485 }
3486
3487 /* Return the mask of core registers that IP reads or writes.  */
3488
3489 static unsigned int
3490 gpr_mod_mask (const struct mips_cl_insn *ip)
3491 {
3492   unsigned long pinfo2;
3493   unsigned int mask;
3494
3495   mask = 0;
3496   pinfo2 = ip->insn_mo->pinfo2;
3497   if (mips_opts.micromips)
3498     {
3499       if (pinfo2 & INSN2_MOD_GPR_MD)
3500         mask |= 1 << micromips_to_32_reg_d_map[EXTRACT_OPERAND (1, MD, *ip)];
3501       if (pinfo2 & INSN2_MOD_GPR_MF)
3502         mask |= 1 << micromips_to_32_reg_f_map[EXTRACT_OPERAND (1, MF, *ip)];
3503       if (pinfo2 & INSN2_MOD_SP)
3504         mask |= 1 << SP;
3505     }
3506   return mask;
3507 }
3508
3509 /* Return the mask of core registers that IP reads.  */
3510
3511 static unsigned int
3512 gpr_read_mask (const struct mips_cl_insn *ip)
3513 {
3514   unsigned long pinfo, pinfo2;
3515   unsigned int mask;
3516
3517   mask = gpr_mod_mask (ip);
3518   pinfo = ip->insn_mo->pinfo;
3519   pinfo2 = ip->insn_mo->pinfo2;
3520   if (mips_opts.mips16)
3521     {
3522       if (pinfo & MIPS16_INSN_READ_X)
3523         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3524       if (pinfo & MIPS16_INSN_READ_Y)
3525         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3526       if (pinfo & MIPS16_INSN_READ_T)
3527         mask |= 1 << TREG;
3528       if (pinfo & MIPS16_INSN_READ_SP)
3529         mask |= 1 << SP;
3530       if (pinfo & MIPS16_INSN_READ_31)
3531         mask |= 1 << RA;
3532       if (pinfo & MIPS16_INSN_READ_Z)
3533         mask |= 1 << (mips16_to_32_reg_map
3534                       [MIPS16_EXTRACT_OPERAND (MOVE32Z, *ip)]);
3535       if (pinfo & MIPS16_INSN_READ_GPR_X)
3536         mask |= 1 << MIPS16_EXTRACT_OPERAND (REGR32, *ip);
3537     }
3538   else
3539     {
3540       if (pinfo2 & INSN2_READ_GPR_D)
3541         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3542       if (pinfo & INSN_READ_GPR_T)
3543         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3544       if (pinfo & INSN_READ_GPR_S)
3545         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3546       if (pinfo2 & INSN2_READ_GP)
3547         mask |= 1 << GP;
3548       if (pinfo2 & INSN2_READ_GPR_31)
3549         mask |= 1 << RA;
3550       if (pinfo2 & INSN2_READ_GPR_Z)
3551         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3552     }
3553   if (mips_opts.micromips)
3554     {
3555       if (pinfo2 & INSN2_READ_GPR_MC)
3556         mask |= 1 << micromips_to_32_reg_c_map[EXTRACT_OPERAND (1, MC, *ip)];
3557       if (pinfo2 & INSN2_READ_GPR_ME)
3558         mask |= 1 << micromips_to_32_reg_e_map[EXTRACT_OPERAND (1, ME, *ip)];
3559       if (pinfo2 & INSN2_READ_GPR_MG)
3560         mask |= 1 << micromips_to_32_reg_g_map[EXTRACT_OPERAND (1, MG, *ip)];
3561       if (pinfo2 & INSN2_READ_GPR_MJ)
3562         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3563       if (pinfo2 & INSN2_READ_GPR_MMN)
3564         {
3565           mask |= 1 << micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
3566           mask |= 1 << micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
3567         }
3568       if (pinfo2 & INSN2_READ_GPR_MP)
3569         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3570       if (pinfo2 & INSN2_READ_GPR_MQ)
3571         mask |= 1 << micromips_to_32_reg_q_map[EXTRACT_OPERAND (1, MQ, *ip)];
3572     }
3573   /* Don't include register 0.  */
3574   return mask & ~1;
3575 }
3576
3577 /* Return the mask of core registers that IP writes.  */
3578
3579 static unsigned int
3580 gpr_write_mask (const struct mips_cl_insn *ip)
3581 {
3582   unsigned long pinfo, pinfo2;
3583   unsigned int mask;
3584
3585   mask = gpr_mod_mask (ip);
3586   pinfo = ip->insn_mo->pinfo;
3587   pinfo2 = ip->insn_mo->pinfo2;
3588   if (mips_opts.mips16)
3589     {
3590       if (pinfo & MIPS16_INSN_WRITE_X)
3591         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RX, *ip)];
3592       if (pinfo & MIPS16_INSN_WRITE_Y)
3593         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RY, *ip)];
3594       if (pinfo & MIPS16_INSN_WRITE_Z)
3595         mask |= 1 << mips16_to_32_reg_map[MIPS16_EXTRACT_OPERAND (RZ, *ip)];
3596       if (pinfo & MIPS16_INSN_WRITE_T)
3597         mask |= 1 << TREG;
3598       if (pinfo & MIPS16_INSN_WRITE_SP)
3599         mask |= 1 << SP;
3600       if (pinfo & MIPS16_INSN_WRITE_31)
3601         mask |= 1 << RA;
3602       if (pinfo & MIPS16_INSN_WRITE_GPR_Y)
3603         mask |= 1 << MIPS16OP_EXTRACT_REG32R (ip->insn_opcode);
3604     }
3605   else
3606     {
3607       if (pinfo & INSN_WRITE_GPR_D)
3608         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
3609       if (pinfo & INSN_WRITE_GPR_T)
3610         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
3611       if (pinfo & INSN_WRITE_GPR_S)
3612         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
3613       if (pinfo & INSN_WRITE_GPR_31)
3614         mask |= 1 << RA;
3615       if (pinfo2 & INSN2_WRITE_GPR_Z)
3616         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RZ, *ip);
3617     }
3618   if (mips_opts.micromips)
3619     {
3620       if (pinfo2 & INSN2_WRITE_GPR_MB)
3621         mask |= 1 << micromips_to_32_reg_b_map[EXTRACT_OPERAND (1, MB, *ip)];
3622       if (pinfo2 & INSN2_WRITE_GPR_MH)
3623         {
3624           mask |= 1 << micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
3625           mask |= 1 << micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
3626         }
3627       if (pinfo2 & INSN2_WRITE_GPR_MJ)
3628         mask |= 1 << EXTRACT_OPERAND (1, MJ, *ip);
3629       if (pinfo2 & INSN2_WRITE_GPR_MP)
3630         mask |= 1 << EXTRACT_OPERAND (1, MP, *ip);
3631     }
3632   /* Don't include register 0.  */
3633   return mask & ~1;
3634 }
3635
3636 /* Return the mask of floating-point registers that IP reads.  */
3637
3638 static unsigned int
3639 fpr_read_mask (const struct mips_cl_insn *ip)
3640 {
3641   unsigned long pinfo, pinfo2;
3642   unsigned int mask;
3643
3644   mask = 0;
3645   pinfo = ip->insn_mo->pinfo;
3646   pinfo2 = ip->insn_mo->pinfo2;
3647   if (!mips_opts.mips16)
3648     {
3649       if (pinfo2 & INSN2_READ_FPR_D)
3650         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3651       if (pinfo & INSN_READ_FPR_S)
3652         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3653       if (pinfo & INSN_READ_FPR_T)
3654         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3655       if (pinfo & INSN_READ_FPR_R)
3656         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FR, *ip);
3657       if (pinfo2 & INSN2_READ_FPR_Z)
3658         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3659     }
3660   /* Conservatively treat all operands to an FP_D instruction are doubles.
3661      (This is overly pessimistic for things like cvt.d.s.)  */
3662   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3663     mask |= mask << 1;
3664   return mask;
3665 }
3666
3667 /* Return the mask of floating-point registers that IP writes.  */
3668
3669 static unsigned int
3670 fpr_write_mask (const struct mips_cl_insn *ip)
3671 {
3672   unsigned long pinfo, pinfo2;
3673   unsigned int mask;
3674
3675   mask = 0;
3676   pinfo = ip->insn_mo->pinfo;
3677   pinfo2 = ip->insn_mo->pinfo2;
3678   if (!mips_opts.mips16)
3679     {
3680       if (pinfo & INSN_WRITE_FPR_D)
3681         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FD, *ip);
3682       if (pinfo & INSN_WRITE_FPR_S)
3683         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FS, *ip);
3684       if (pinfo & INSN_WRITE_FPR_T)
3685         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FT, *ip);
3686       if (pinfo2 & INSN2_WRITE_FPR_Z)
3687         mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, FZ, *ip);
3688     }
3689   /* Conservatively treat all operands to an FP_D instruction are doubles.
3690      (This is overly pessimistic for things like cvt.s.d.)  */
3691   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
3692     mask |= mask << 1;
3693   return mask;
3694 }
3695
3696 /* Classify an instruction according to the FIX_VR4120_* enumeration.
3697    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
3698    by VR4120 errata.  */
3699
3700 static unsigned int
3701 classify_vr4120_insn (const char *name)
3702 {
3703   if (strncmp (name, "macc", 4) == 0)
3704     return FIX_VR4120_MACC;
3705   if (strncmp (name, "dmacc", 5) == 0)
3706     return FIX_VR4120_DMACC;
3707   if (strncmp (name, "mult", 4) == 0)
3708     return FIX_VR4120_MULT;
3709   if (strncmp (name, "dmult", 5) == 0)
3710     return FIX_VR4120_DMULT;
3711   if (strstr (name, "div"))
3712     return FIX_VR4120_DIV;
3713   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
3714     return FIX_VR4120_MTHILO;
3715   return NUM_FIX_VR4120_CLASSES;
3716 }
3717
3718 #define INSN_ERET  0x42000018
3719 #define INSN_DERET 0x4200001f
3720
3721 /* Return the number of instructions that must separate INSN1 and INSN2,
3722    where INSN1 is the earlier instruction.  Return the worst-case value
3723    for any INSN2 if INSN2 is null.  */
3724
3725 static unsigned int
3726 insns_between (const struct mips_cl_insn *insn1,
3727                const struct mips_cl_insn *insn2)
3728 {
3729   unsigned long pinfo1, pinfo2;
3730   unsigned int mask;
3731
3732   /* This function needs to know which pinfo flags are set for INSN2
3733      and which registers INSN2 uses.  The former is stored in PINFO2 and
3734      the latter is tested via INSN2_USES_GPR.  If INSN2 is null, PINFO2
3735      will have every flag set and INSN2_USES_GPR will always return true.  */
3736   pinfo1 = insn1->insn_mo->pinfo;
3737   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
3738
3739 #define INSN2_USES_GPR(REG) \
3740   (insn2 == NULL || (gpr_read_mask (insn2) & (1U << (REG))) != 0)
3741
3742   /* For most targets, write-after-read dependencies on the HI and LO
3743      registers must be separated by at least two instructions.  */
3744   if (!hilo_interlocks)
3745     {
3746       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
3747         return 2;
3748       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
3749         return 2;
3750     }
3751
3752   /* If we're working around r7000 errata, there must be two instructions
3753      between an mfhi or mflo and any instruction that uses the result.  */
3754   if (mips_7000_hilo_fix
3755       && !mips_opts.micromips
3756       && MF_HILO_INSN (pinfo1)
3757       && INSN2_USES_GPR (EXTRACT_OPERAND (0, RD, *insn1)))
3758     return 2;
3759
3760   /* If we're working around 24K errata, one instruction is required
3761      if an ERET or DERET is followed by a branch instruction.  */
3762   if (mips_fix_24k && !mips_opts.micromips)
3763     {
3764       if (insn1->insn_opcode == INSN_ERET
3765           || insn1->insn_opcode == INSN_DERET)
3766         {
3767           if (insn2 == NULL
3768               || insn2->insn_opcode == INSN_ERET
3769               || insn2->insn_opcode == INSN_DERET
3770               || delayed_branch_p (insn2))
3771             return 1;
3772         }
3773     }
3774
3775   /* If working around VR4120 errata, check for combinations that need
3776      a single intervening instruction.  */
3777   if (mips_fix_vr4120 && !mips_opts.micromips)
3778     {
3779       unsigned int class1, class2;
3780
3781       class1 = classify_vr4120_insn (insn1->insn_mo->name);
3782       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
3783         {
3784           if (insn2 == NULL)
3785             return 1;
3786           class2 = classify_vr4120_insn (insn2->insn_mo->name);
3787           if (vr4120_conflicts[class1] & (1 << class2))
3788             return 1;
3789         }
3790     }
3791
3792   if (!HAVE_CODE_COMPRESSION)
3793     {
3794       /* Check for GPR or coprocessor load delays.  All such delays
3795          are on the RT register.  */
3796       /* Itbl support may require additional care here.  */
3797       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
3798           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
3799         {
3800           know (pinfo1 & INSN_WRITE_GPR_T);
3801           if (INSN2_USES_GPR (EXTRACT_OPERAND (0, RT, *insn1)))
3802             return 1;
3803         }
3804
3805       /* Check for generic coprocessor hazards.
3806
3807          This case is not handled very well.  There is no special
3808          knowledge of CP0 handling, and the coprocessors other than
3809          the floating point unit are not distinguished at all.  */
3810       /* Itbl support may require additional care here. FIXME!
3811          Need to modify this to include knowledge about
3812          user specified delays!  */
3813       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
3814                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
3815         {
3816           /* Handle cases where INSN1 writes to a known general coprocessor
3817              register.  There must be a one instruction delay before INSN2
3818              if INSN2 reads that register, otherwise no delay is needed.  */
3819           mask = fpr_write_mask (insn1);
3820           if (mask != 0)
3821             {
3822               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
3823                 return 1;
3824             }
3825           else
3826             {
3827               /* Read-after-write dependencies on the control registers
3828                  require a two-instruction gap.  */
3829               if ((pinfo1 & INSN_WRITE_COND_CODE)
3830                   && (pinfo2 & INSN_READ_COND_CODE))
3831                 return 2;
3832
3833               /* We don't know exactly what INSN1 does.  If INSN2 is
3834                  also a coprocessor instruction, assume there must be
3835                  a one instruction gap.  */
3836               if (pinfo2 & INSN_COP)
3837                 return 1;
3838             }
3839         }
3840
3841       /* Check for read-after-write dependencies on the coprocessor
3842          control registers in cases where INSN1 does not need a general
3843          coprocessor delay.  This means that INSN1 is a floating point
3844          comparison instruction.  */
3845       /* Itbl support may require additional care here.  */
3846       else if (!cop_interlocks
3847                && (pinfo1 & INSN_WRITE_COND_CODE)
3848                && (pinfo2 & INSN_READ_COND_CODE))
3849         return 1;
3850     }
3851
3852 #undef INSN2_USES_GPR
3853
3854   return 0;
3855 }
3856
3857 /* Return the number of nops that would be needed to work around the
3858    VR4130 mflo/mfhi errata if instruction INSN immediately followed
3859    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
3860    that are contained within the first IGNORE instructions of HIST.  */
3861
3862 static int
3863 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
3864                  const struct mips_cl_insn *insn)
3865 {
3866   int i, j;
3867   unsigned int mask;
3868
3869   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
3870      are not affected by the errata.  */
3871   if (insn != 0
3872       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
3873           || strcmp (insn->insn_mo->name, "mtlo") == 0
3874           || strcmp (insn->insn_mo->name, "mthi") == 0))
3875     return 0;
3876
3877   /* Search for the first MFLO or MFHI.  */
3878   for (i = 0; i < MAX_VR4130_NOPS; i++)
3879     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
3880       {
3881         /* Extract the destination register.  */
3882         mask = gpr_write_mask (&hist[i]);
3883
3884         /* No nops are needed if INSN reads that register.  */
3885         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
3886           return 0;
3887
3888         /* ...or if any of the intervening instructions do.  */
3889         for (j = 0; j < i; j++)
3890           if (gpr_read_mask (&hist[j]) & mask)
3891             return 0;
3892
3893         if (i >= ignore)
3894           return MAX_VR4130_NOPS - i;
3895       }
3896   return 0;
3897 }
3898
3899 #define BASE_REG_EQ(INSN1, INSN2)       \
3900   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
3901       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
3902
3903 /* Return the minimum alignment for this store instruction.  */
3904
3905 static int
3906 fix_24k_align_to (const struct mips_opcode *mo)
3907 {
3908   if (strcmp (mo->name, "sh") == 0)
3909     return 2;
3910
3911   if (strcmp (mo->name, "swc1") == 0
3912       || strcmp (mo->name, "swc2") == 0
3913       || strcmp (mo->name, "sw") == 0
3914       || strcmp (mo->name, "sc") == 0
3915       || strcmp (mo->name, "s.s") == 0)
3916     return 4;
3917
3918   if (strcmp (mo->name, "sdc1") == 0
3919       || strcmp (mo->name, "sdc2") == 0
3920       || strcmp (mo->name, "s.d") == 0)
3921     return 8;
3922
3923   /* sb, swl, swr */
3924   return 1;
3925 }
3926
3927 struct fix_24k_store_info
3928   {
3929     /* Immediate offset, if any, for this store instruction.  */
3930     short off;
3931     /* Alignment required by this store instruction.  */
3932     int align_to;
3933     /* True for register offsets.  */
3934     int register_offset;
3935   };
3936
3937 /* Comparison function used by qsort.  */
3938
3939 static int
3940 fix_24k_sort (const void *a, const void *b)
3941 {
3942   const struct fix_24k_store_info *pos1 = a;
3943   const struct fix_24k_store_info *pos2 = b;
3944
3945   return (pos1->off - pos2->off);
3946 }
3947
3948 /* INSN is a store instruction.  Try to record the store information
3949    in STINFO.  Return false if the information isn't known.  */
3950
3951 static bfd_boolean
3952 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
3953                            const struct mips_cl_insn *insn)
3954 {
3955   /* The instruction must have a known offset.  */
3956   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
3957     return FALSE;
3958
3959   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
3960   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
3961   return TRUE;
3962 }
3963
3964 /* Return the number of nops that would be needed to work around the 24k
3965    "lost data on stores during refill" errata if instruction INSN
3966    immediately followed the 2 instructions described by HIST.
3967    Ignore hazards that are contained within the first IGNORE
3968    instructions of HIST.
3969
3970    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
3971    for the data cache refills and store data. The following describes
3972    the scenario where the store data could be lost.
3973
3974    * A data cache miss, due to either a load or a store, causing fill
3975      data to be supplied by the memory subsystem
3976    * The first three doublewords of fill data are returned and written
3977      into the cache
3978    * A sequence of four stores occurs in consecutive cycles around the
3979      final doubleword of the fill:
3980    * Store A
3981    * Store B
3982    * Store C
3983    * Zero, One or more instructions
3984    * Store D
3985
3986    The four stores A-D must be to different doublewords of the line that
3987    is being filled. The fourth instruction in the sequence above permits
3988    the fill of the final doubleword to be transferred from the FSB into
3989    the cache. In the sequence above, the stores may be either integer
3990    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
3991    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
3992    different doublewords on the line. If the floating point unit is
3993    running in 1:2 mode, it is not possible to create the sequence above
3994    using only floating point store instructions.
3995
3996    In this case, the cache line being filled is incorrectly marked
3997    invalid, thereby losing the data from any store to the line that
3998    occurs between the original miss and the completion of the five
3999    cycle sequence shown above.
4000
4001    The workarounds are:
4002
4003    * Run the data cache in write-through mode.
4004    * Insert a non-store instruction between
4005      Store A and Store B or Store B and Store C.  */
4006   
4007 static int
4008 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
4009               const struct mips_cl_insn *insn)
4010 {
4011   struct fix_24k_store_info pos[3];
4012   int align, i, base_offset;
4013
4014   if (ignore >= 2)
4015     return 0;
4016
4017   /* If the previous instruction wasn't a store, there's nothing to
4018      worry about.  */
4019   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4020     return 0;
4021
4022   /* If the instructions after the previous one are unknown, we have
4023      to assume the worst.  */
4024   if (!insn)
4025     return 1;
4026
4027   /* Check whether we are dealing with three consecutive stores.  */
4028   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
4029       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
4030     return 0;
4031
4032   /* If we don't know the relationship between the store addresses,
4033      assume the worst.  */
4034   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
4035       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
4036     return 1;
4037
4038   if (!fix_24k_record_store_info (&pos[0], insn)
4039       || !fix_24k_record_store_info (&pos[1], &hist[0])
4040       || !fix_24k_record_store_info (&pos[2], &hist[1]))
4041     return 1;
4042
4043   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
4044
4045   /* Pick a value of ALIGN and X such that all offsets are adjusted by
4046      X bytes and such that the base register + X is known to be aligned
4047      to align bytes.  */
4048
4049   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
4050     align = 8;
4051   else
4052     {
4053       align = pos[0].align_to;
4054       base_offset = pos[0].off;
4055       for (i = 1; i < 3; i++)
4056         if (align < pos[i].align_to)
4057           {
4058             align = pos[i].align_to;
4059             base_offset = pos[i].off;
4060           }
4061       for (i = 0; i < 3; i++)
4062         pos[i].off -= base_offset;
4063     }
4064
4065   pos[0].off &= ~align + 1;
4066   pos[1].off &= ~align + 1;
4067   pos[2].off &= ~align + 1;
4068
4069   /* If any two stores write to the same chunk, they also write to the
4070      same doubleword.  The offsets are still sorted at this point.  */
4071   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
4072     return 0;
4073
4074   /* A range of at least 9 bytes is needed for the stores to be in
4075      non-overlapping doublewords.  */
4076   if (pos[2].off - pos[0].off <= 8)
4077     return 0;
4078
4079   if (pos[2].off - pos[1].off >= 24
4080       || pos[1].off - pos[0].off >= 24
4081       || pos[2].off - pos[0].off >= 32)
4082     return 0;
4083
4084   return 1;
4085 }
4086
4087 /* Return the number of nops that would be needed if instruction INSN
4088    immediately followed the MAX_NOPS instructions given by HIST,
4089    where HIST[0] is the most recent instruction.  Ignore hazards
4090    between INSN and the first IGNORE instructions in HIST.
4091
4092    If INSN is null, return the worse-case number of nops for any
4093    instruction.  */
4094
4095 static int
4096 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
4097                const struct mips_cl_insn *insn)
4098 {
4099   int i, nops, tmp_nops;
4100
4101   nops = 0;
4102   for (i = ignore; i < MAX_DELAY_NOPS; i++)
4103     {
4104       tmp_nops = insns_between (hist + i, insn) - i;
4105       if (tmp_nops > nops)
4106         nops = tmp_nops;
4107     }
4108
4109   if (mips_fix_vr4130 && !mips_opts.micromips)
4110     {
4111       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
4112       if (tmp_nops > nops)
4113         nops = tmp_nops;
4114     }
4115
4116   if (mips_fix_24k && !mips_opts.micromips)
4117     {
4118       tmp_nops = nops_for_24k (ignore, hist, insn);
4119       if (tmp_nops > nops)
4120         nops = tmp_nops;
4121     }
4122
4123   return nops;
4124 }
4125
4126 /* The variable arguments provide NUM_INSNS extra instructions that
4127    might be added to HIST.  Return the largest number of nops that
4128    would be needed after the extended sequence, ignoring hazards
4129    in the first IGNORE instructions.  */
4130
4131 static int
4132 nops_for_sequence (int num_insns, int ignore,
4133                    const struct mips_cl_insn *hist, ...)
4134 {
4135   va_list args;
4136   struct mips_cl_insn buffer[MAX_NOPS];
4137   struct mips_cl_insn *cursor;
4138   int nops;
4139
4140   va_start (args, hist);
4141   cursor = buffer + num_insns;
4142   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
4143   while (cursor > buffer)
4144     *--cursor = *va_arg (args, const struct mips_cl_insn *);
4145
4146   nops = nops_for_insn (ignore, buffer, NULL);
4147   va_end (args);
4148   return nops;
4149 }
4150
4151 /* Like nops_for_insn, but if INSN is a branch, take into account the
4152    worst-case delay for the branch target.  */
4153
4154 static int
4155 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
4156                          const struct mips_cl_insn *insn)
4157 {
4158   int nops, tmp_nops;
4159
4160   nops = nops_for_insn (ignore, hist, insn);
4161   if (delayed_branch_p (insn))
4162     {
4163       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
4164                                     hist, insn, get_delay_slot_nop (insn));
4165       if (tmp_nops > nops)
4166         nops = tmp_nops;
4167     }
4168   else if (compact_branch_p (insn))
4169     {
4170       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
4171       if (tmp_nops > nops)
4172         nops = tmp_nops;
4173     }
4174   return nops;
4175 }
4176
4177 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
4178
4179 static void
4180 fix_loongson2f_nop (struct mips_cl_insn * ip)
4181 {
4182   gas_assert (!HAVE_CODE_COMPRESSION);
4183   if (strcmp (ip->insn_mo->name, "nop") == 0)
4184     ip->insn_opcode = LOONGSON2F_NOP_INSN;
4185 }
4186
4187 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
4188                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
4189
4190 static void
4191 fix_loongson2f_jump (struct mips_cl_insn * ip)
4192 {
4193   gas_assert (!HAVE_CODE_COMPRESSION);
4194   if (strcmp (ip->insn_mo->name, "j") == 0
4195       || strcmp (ip->insn_mo->name, "jr") == 0
4196       || strcmp (ip->insn_mo->name, "jalr") == 0)
4197     {
4198       int sreg;
4199       expressionS ep;
4200
4201       if (! mips_opts.at)
4202         return;
4203
4204       sreg = EXTRACT_OPERAND (0, RS, *ip);
4205       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
4206         return;
4207
4208       ep.X_op = O_constant;
4209       ep.X_add_number = 0xcfff0000;
4210       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
4211       ep.X_add_number = 0xffff;
4212       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
4213       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
4214     }
4215 }
4216
4217 static void
4218 fix_loongson2f (struct mips_cl_insn * ip)
4219 {
4220   if (mips_fix_loongson2f_nop)
4221     fix_loongson2f_nop (ip);
4222
4223   if (mips_fix_loongson2f_jump)
4224     fix_loongson2f_jump (ip);
4225 }
4226
4227 /* IP is a branch that has a delay slot, and we need to fill it
4228    automatically.   Return true if we can do that by swapping IP
4229    with the previous instruction.
4230    ADDRESS_EXPR is an operand of the instruction to be used with
4231    RELOC_TYPE.  */
4232
4233 static bfd_boolean
4234 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
4235   bfd_reloc_code_real_type *reloc_type)
4236 {
4237   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
4238   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
4239
4240   /* -O2 and above is required for this optimization.  */
4241   if (mips_optimize < 2)
4242     return FALSE;
4243
4244   /* If we have seen .set volatile or .set nomove, don't optimize.  */
4245   if (mips_opts.nomove)
4246     return FALSE;
4247
4248   /* We can't swap if the previous instruction's position is fixed.  */
4249   if (history[0].fixed_p)
4250     return FALSE;
4251
4252   /* If the previous previous insn was in a .set noreorder, we can't
4253      swap.  Actually, the MIPS assembler will swap in this situation.
4254      However, gcc configured -with-gnu-as will generate code like
4255
4256         .set    noreorder
4257         lw      $4,XXX
4258         .set    reorder
4259         INSN
4260         bne     $4,$0,foo
4261
4262      in which we can not swap the bne and INSN.  If gcc is not configured
4263      -with-gnu-as, it does not output the .set pseudo-ops.  */
4264   if (history[1].noreorder_p)
4265     return FALSE;
4266
4267   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
4268      This means that the previous instruction was a 4-byte one anyhow.  */
4269   if (mips_opts.mips16 && history[0].fixp[0])
4270     return FALSE;
4271
4272   /* If the branch is itself the target of a branch, we can not swap.
4273      We cheat on this; all we check for is whether there is a label on
4274      this instruction.  If there are any branches to anything other than
4275      a label, users must use .set noreorder.  */
4276   if (seg_info (now_seg)->label_list)
4277     return FALSE;
4278
4279   /* If the previous instruction is in a variant frag other than this
4280      branch's one, we cannot do the swap.  This does not apply to
4281      MIPS16 code, which uses variant frags for different purposes.  */
4282   if (!mips_opts.mips16
4283       && history[0].frag
4284       && history[0].frag->fr_type == rs_machine_dependent)
4285     return FALSE;
4286
4287   /* We do not swap with instructions that cannot architecturally
4288      be placed in a branch delay slot, such as SYNC or ERET.  We
4289      also refrain from swapping with a trap instruction, since it
4290      complicates trap handlers to have the trap instruction be in
4291      a delay slot.  */
4292   prev_pinfo = history[0].insn_mo->pinfo;
4293   if (prev_pinfo & INSN_NO_DELAY_SLOT)
4294     return FALSE;
4295
4296   /* Check for conflicts between the branch and the instructions
4297      before the candidate delay slot.  */
4298   if (nops_for_insn (0, history + 1, ip) > 0)
4299     return FALSE;
4300
4301   /* Check for conflicts between the swapped sequence and the
4302      target of the branch.  */
4303   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
4304     return FALSE;
4305
4306   /* If the branch reads a register that the previous
4307      instruction sets, we can not swap.  */
4308   gpr_read = gpr_read_mask (ip);
4309   prev_gpr_write = gpr_write_mask (&history[0]);
4310   if (gpr_read & prev_gpr_write)
4311     return FALSE;
4312
4313   /* If the branch writes a register that the previous
4314      instruction sets, we can not swap.  */
4315   gpr_write = gpr_write_mask (ip);
4316   if (gpr_write & prev_gpr_write)
4317     return FALSE;
4318
4319   /* If the branch writes a register that the previous
4320      instruction reads, we can not swap.  */
4321   prev_gpr_read = gpr_read_mask (&history[0]);
4322   if (gpr_write & prev_gpr_read)
4323     return FALSE;
4324
4325   /* If one instruction sets a condition code and the
4326      other one uses a condition code, we can not swap.  */
4327   pinfo = ip->insn_mo->pinfo;
4328   if ((pinfo & INSN_READ_COND_CODE)
4329       && (prev_pinfo & INSN_WRITE_COND_CODE))
4330     return FALSE;
4331   if ((pinfo & INSN_WRITE_COND_CODE)
4332       && (prev_pinfo & INSN_READ_COND_CODE))
4333     return FALSE;
4334
4335   /* If the previous instruction uses the PC, we can not swap.  */
4336   prev_pinfo2 = history[0].insn_mo->pinfo2;
4337   if (mips_opts.mips16 && (prev_pinfo & MIPS16_INSN_READ_PC))
4338     return FALSE;
4339   if (mips_opts.micromips && (prev_pinfo2 & INSN2_READ_PC))
4340     return FALSE;
4341
4342   /* If the previous instruction has an incorrect size for a fixed
4343      branch delay slot in microMIPS mode, we cannot swap.  */
4344   pinfo2 = ip->insn_mo->pinfo2;
4345   if (mips_opts.micromips
4346       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
4347       && insn_length (history) != 2)
4348     return FALSE;
4349   if (mips_opts.micromips
4350       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
4351       && insn_length (history) != 4)
4352     return FALSE;
4353
4354   /* On R5900 short loops need to be fixed by inserting a nop in
4355      the branch delay slots.
4356      A short loop can be terminated too early.  */
4357   if (mips_opts.arch == CPU_R5900
4358       /* Check if instruction has a parameter, ignore "j $31". */
4359       && (address_expr != NULL)
4360       /* Parameter must be 16 bit. */
4361       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
4362       /* Branch to same segment. */
4363       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
4364       /* Branch to same code fragment. */
4365       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
4366       /* Can only calculate branch offset if value is known. */
4367       && symbol_constant_p(address_expr->X_add_symbol)
4368       /* Check if branch is really conditional. */
4369       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
4370         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
4371         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
4372     {
4373       int distance;
4374       /* Check if loop is shorter than 6 instructions including
4375          branch and delay slot.  */
4376       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
4377       if (distance <= 20)
4378         {
4379           int i;
4380           int rv;
4381
4382           rv = FALSE;
4383           /* When the loop includes branches or jumps,
4384              it is not a short loop. */
4385           for (i = 0; i < (distance / 4); i++)
4386             {
4387               if ((history[i].cleared_p)
4388                   || delayed_branch_p(&history[i]))
4389                 {
4390                   rv = TRUE;
4391                   break;
4392                 }
4393             }
4394           if (rv == FALSE)
4395             {
4396               /* Insert nop after branch to fix short loop. */
4397               return FALSE;
4398             }
4399         }
4400     }
4401
4402   return TRUE;
4403 }
4404
4405 /* Decide how we should add IP to the instruction stream.
4406    ADDRESS_EXPR is an operand of the instruction to be used with
4407    RELOC_TYPE.  */
4408
4409 static enum append_method
4410 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
4411   bfd_reloc_code_real_type *reloc_type)
4412 {
4413   unsigned long pinfo;
4414
4415   /* The relaxed version of a macro sequence must be inherently
4416      hazard-free.  */
4417   if (mips_relax.sequence == 2)
4418     return APPEND_ADD;
4419
4420   /* We must not dabble with instructions in a ".set norerorder" block.  */
4421   if (mips_opts.noreorder)
4422     return APPEND_ADD;
4423
4424   /* Otherwise, it's our responsibility to fill branch delay slots.  */
4425   if (delayed_branch_p (ip))
4426     {
4427       if (!branch_likely_p (ip)
4428           && can_swap_branch_p (ip, address_expr, reloc_type))
4429         return APPEND_SWAP;
4430
4431       pinfo = ip->insn_mo->pinfo;
4432       if (mips_opts.mips16
4433           && ISA_SUPPORTS_MIPS16E
4434           && (pinfo & (MIPS16_INSN_READ_X | MIPS16_INSN_READ_31)))
4435         return APPEND_ADD_COMPACT;
4436
4437       return APPEND_ADD_WITH_NOP;
4438     }
4439
4440   return APPEND_ADD;
4441 }
4442
4443 /* IP is a MIPS16 instruction whose opcode we have just changed.
4444    Point IP->insn_mo to the new opcode's definition.  */
4445
4446 static void
4447 find_altered_mips16_opcode (struct mips_cl_insn *ip)
4448 {
4449   const struct mips_opcode *mo, *end;
4450
4451   end = &mips16_opcodes[bfd_mips16_num_opcodes];
4452   for (mo = ip->insn_mo; mo < end; mo++)
4453     if ((ip->insn_opcode & mo->mask) == mo->match)
4454       {
4455         ip->insn_mo = mo;
4456         return;
4457       }
4458   abort ();
4459 }
4460
4461 /* For microMIPS macros, we need to generate a local number label
4462    as the target of branches.  */
4463 #define MICROMIPS_LABEL_CHAR            '\037'
4464 static unsigned long micromips_target_label;
4465 static char micromips_target_name[32];
4466
4467 static char *
4468 micromips_label_name (void)
4469 {
4470   char *p = micromips_target_name;
4471   char symbol_name_temporary[24];
4472   unsigned long l;
4473   int i;
4474
4475   if (*p)
4476     return p;
4477
4478   i = 0;
4479   l = micromips_target_label;
4480 #ifdef LOCAL_LABEL_PREFIX
4481   *p++ = LOCAL_LABEL_PREFIX;
4482 #endif
4483   *p++ = 'L';
4484   *p++ = MICROMIPS_LABEL_CHAR;
4485   do
4486     {
4487       symbol_name_temporary[i++] = l % 10 + '0';
4488       l /= 10;
4489     }
4490   while (l != 0);
4491   while (i > 0)
4492     *p++ = symbol_name_temporary[--i];
4493   *p = '\0';
4494
4495   return micromips_target_name;
4496 }
4497
4498 static void
4499 micromips_label_expr (expressionS *label_expr)
4500 {
4501   label_expr->X_op = O_symbol;
4502   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
4503   label_expr->X_add_number = 0;
4504 }
4505
4506 static void
4507 micromips_label_inc (void)
4508 {
4509   micromips_target_label++;
4510   *micromips_target_name = '\0';
4511 }
4512
4513 static void
4514 micromips_add_label (void)
4515 {
4516   symbolS *s;
4517
4518   s = colon (micromips_label_name ());
4519   micromips_label_inc ();
4520   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
4521 }
4522
4523 /* If assembling microMIPS code, then return the microMIPS reloc
4524    corresponding to the requested one if any.  Otherwise return
4525    the reloc unchanged.  */
4526
4527 static bfd_reloc_code_real_type
4528 micromips_map_reloc (bfd_reloc_code_real_type reloc)
4529 {
4530   static const bfd_reloc_code_real_type relocs[][2] =
4531     {
4532       /* Keep sorted incrementally by the left-hand key.  */
4533       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
4534       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
4535       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
4536       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
4537       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
4538       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
4539       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
4540       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
4541       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
4542       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
4543       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
4544       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
4545       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
4546       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
4547       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
4548       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
4549       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
4550       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
4551       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
4552       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
4553       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
4554       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
4555       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
4556       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
4557       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
4558       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
4559       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
4560     };
4561   bfd_reloc_code_real_type r;
4562   size_t i;
4563
4564   if (!mips_opts.micromips)
4565     return reloc;
4566   for (i = 0; i < ARRAY_SIZE (relocs); i++)
4567     {
4568       r = relocs[i][0];
4569       if (r > reloc)
4570         return reloc;
4571       if (r == reloc)
4572         return relocs[i][1];
4573     }
4574   return reloc;
4575 }
4576
4577 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
4578    Return true on success, storing the resolved value in RESULT.  */
4579
4580 static bfd_boolean
4581 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
4582                  offsetT *result)
4583 {
4584   switch (reloc)
4585     {
4586     case BFD_RELOC_MIPS_HIGHEST:
4587     case BFD_RELOC_MICROMIPS_HIGHEST:
4588       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
4589       return TRUE;
4590
4591     case BFD_RELOC_MIPS_HIGHER:
4592     case BFD_RELOC_MICROMIPS_HIGHER:
4593       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
4594       return TRUE;
4595
4596     case BFD_RELOC_HI16_S:
4597     case BFD_RELOC_MICROMIPS_HI16_S:
4598     case BFD_RELOC_MIPS16_HI16_S:
4599       *result = ((operand + 0x8000) >> 16) & 0xffff;
4600       return TRUE;
4601
4602     case BFD_RELOC_HI16:
4603     case BFD_RELOC_MICROMIPS_HI16:
4604     case BFD_RELOC_MIPS16_HI16:
4605       *result = (operand >> 16) & 0xffff;
4606       return TRUE;
4607
4608     case BFD_RELOC_LO16:
4609     case BFD_RELOC_MICROMIPS_LO16:
4610     case BFD_RELOC_MIPS16_LO16:
4611       *result = operand & 0xffff;
4612       return TRUE;
4613
4614     case BFD_RELOC_UNUSED:
4615       *result = operand;
4616       return TRUE;
4617
4618     default:
4619       return FALSE;
4620     }
4621 }
4622
4623 /* Output an instruction.  IP is the instruction information.
4624    ADDRESS_EXPR is an operand of the instruction to be used with
4625    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
4626    a macro expansion.  */
4627
4628 static void
4629 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
4630              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
4631 {
4632   unsigned long prev_pinfo2, pinfo;
4633   bfd_boolean relaxed_branch = FALSE;
4634   enum append_method method;
4635   bfd_boolean relax32;
4636   int branch_disp;
4637
4638   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
4639     fix_loongson2f (ip);
4640
4641   file_ase_mips16 |= mips_opts.mips16;
4642   file_ase_micromips |= mips_opts.micromips;
4643
4644   prev_pinfo2 = history[0].insn_mo->pinfo2;
4645   pinfo = ip->insn_mo->pinfo;
4646
4647   if (mips_opts.micromips
4648       && !expansionp
4649       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
4650            && micromips_insn_length (ip->insn_mo) != 2)
4651           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
4652               && micromips_insn_length (ip->insn_mo) != 4)))
4653     as_warn (_("Wrong size instruction in a %u-bit branch delay slot"),
4654              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
4655
4656   if (address_expr == NULL)
4657     ip->complete_p = 1;
4658   else if (reloc_type[0] <= BFD_RELOC_UNUSED
4659            && reloc_type[1] == BFD_RELOC_UNUSED
4660            && reloc_type[2] == BFD_RELOC_UNUSED
4661            && address_expr->X_op == O_constant)
4662     {
4663       switch (*reloc_type)
4664         {
4665         case BFD_RELOC_MIPS_JMP:
4666           {
4667             int shift;
4668
4669             shift = mips_opts.micromips ? 1 : 2;
4670             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4671               as_bad (_("jump to misaligned address (0x%lx)"),
4672                       (unsigned long) address_expr->X_add_number);
4673             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4674                                 & 0x3ffffff);
4675             ip->complete_p = 1;
4676           }
4677           break;
4678
4679         case BFD_RELOC_MIPS16_JMP:
4680           if ((address_expr->X_add_number & 3) != 0)
4681             as_bad (_("jump to misaligned address (0x%lx)"),
4682                     (unsigned long) address_expr->X_add_number);
4683           ip->insn_opcode |=
4684             (((address_expr->X_add_number & 0x7c0000) << 3)
4685                | ((address_expr->X_add_number & 0xf800000) >> 7)
4686                | ((address_expr->X_add_number & 0x3fffc) >> 2));
4687           ip->complete_p = 1;
4688           break;
4689
4690         case BFD_RELOC_16_PCREL_S2:
4691           {
4692             int shift;
4693
4694             shift = mips_opts.micromips ? 1 : 2;
4695             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
4696               as_bad (_("branch to misaligned address (0x%lx)"),
4697                       (unsigned long) address_expr->X_add_number);
4698             if (!mips_relax_branch)
4699               {
4700                 if ((address_expr->X_add_number + (1 << (shift + 15)))
4701                     & ~((1 << (shift + 16)) - 1))
4702                   as_bad (_("branch address range overflow (0x%lx)"),
4703                           (unsigned long) address_expr->X_add_number);
4704                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
4705                                     & 0xffff);
4706               }
4707           }
4708           break;
4709
4710         default:
4711           {
4712             offsetT value;
4713
4714             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
4715                                  &value))
4716               {
4717                 ip->insn_opcode |= value & 0xffff;
4718                 ip->complete_p = 1;
4719               }
4720           }
4721           break;
4722         }
4723     }
4724
4725   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
4726     {
4727       /* There are a lot of optimizations we could do that we don't.
4728          In particular, we do not, in general, reorder instructions.
4729          If you use gcc with optimization, it will reorder
4730          instructions and generally do much more optimization then we
4731          do here; repeating all that work in the assembler would only
4732          benefit hand written assembly code, and does not seem worth
4733          it.  */
4734       int nops = (mips_optimize == 0
4735                   ? nops_for_insn (0, history, NULL)
4736                   : nops_for_insn_or_target (0, history, ip));
4737       if (nops > 0)
4738         {
4739           fragS *old_frag;
4740           unsigned long old_frag_offset;
4741           int i;
4742
4743           old_frag = frag_now;
4744           old_frag_offset = frag_now_fix ();
4745
4746           for (i = 0; i < nops; i++)
4747             add_fixed_insn (NOP_INSN);
4748           insert_into_history (0, nops, NOP_INSN);
4749
4750           if (listing)
4751             {
4752               listing_prev_line ();
4753               /* We may be at the start of a variant frag.  In case we
4754                  are, make sure there is enough space for the frag
4755                  after the frags created by listing_prev_line.  The
4756                  argument to frag_grow here must be at least as large
4757                  as the argument to all other calls to frag_grow in
4758                  this file.  We don't have to worry about being in the
4759                  middle of a variant frag, because the variants insert
4760                  all needed nop instructions themselves.  */
4761               frag_grow (40);
4762             }
4763
4764           mips_move_text_labels ();
4765
4766 #ifndef NO_ECOFF_DEBUGGING
4767           if (ECOFF_DEBUGGING)
4768             ecoff_fix_loc (old_frag, old_frag_offset);
4769 #endif
4770         }
4771     }
4772   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
4773     {
4774       int nops;
4775
4776       /* Work out how many nops in prev_nop_frag are needed by IP,
4777          ignoring hazards generated by the first prev_nop_frag_since
4778          instructions.  */
4779       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
4780       gas_assert (nops <= prev_nop_frag_holds);
4781
4782       /* Enforce NOPS as a minimum.  */
4783       if (nops > prev_nop_frag_required)
4784         prev_nop_frag_required = nops;
4785
4786       if (prev_nop_frag_holds == prev_nop_frag_required)
4787         {
4788           /* Settle for the current number of nops.  Update the history
4789              accordingly (for the benefit of any future .set reorder code).  */
4790           prev_nop_frag = NULL;
4791           insert_into_history (prev_nop_frag_since,
4792                                prev_nop_frag_holds, NOP_INSN);
4793         }
4794       else
4795         {
4796           /* Allow this instruction to replace one of the nops that was
4797              tentatively added to prev_nop_frag.  */
4798           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
4799           prev_nop_frag_holds--;
4800           prev_nop_frag_since++;
4801         }
4802     }
4803
4804   method = get_append_method (ip, address_expr, reloc_type);
4805   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
4806
4807   dwarf2_emit_insn (0);
4808   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
4809      so "move" the instruction address accordingly.
4810
4811      Also, it doesn't seem appropriate for the assembler to reorder .loc
4812      entries.  If this instruction is a branch that we are going to swap
4813      with the previous instruction, the two instructions should be
4814      treated as a unit, and the debug information for both instructions
4815      should refer to the start of the branch sequence.  Using the
4816      current position is certainly wrong when swapping a 32-bit branch
4817      and a 16-bit delay slot, since the current position would then be
4818      in the middle of a branch.  */
4819   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
4820
4821   relax32 = (mips_relax_branch
4822              /* Don't try branch relaxation within .set nomacro, or within
4823                 .set noat if we use $at for PIC computations.  If it turns
4824                 out that the branch was out-of-range, we'll get an error.  */
4825              && !mips_opts.warn_about_macros
4826              && (mips_opts.at || mips_pic == NO_PIC)
4827              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
4828                 as they have no complementing branches.  */
4829              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
4830
4831   if (!HAVE_CODE_COMPRESSION
4832       && address_expr
4833       && relax32
4834       && *reloc_type == BFD_RELOC_16_PCREL_S2
4835       && delayed_branch_p (ip))
4836     {
4837       relaxed_branch = TRUE;
4838       add_relaxed_insn (ip, (relaxed_branch_length
4839                              (NULL, NULL,
4840                               uncond_branch_p (ip) ? -1
4841                               : branch_likely_p (ip) ? 1
4842                               : 0)), 4,
4843                         RELAX_BRANCH_ENCODE
4844                         (AT,
4845                          uncond_branch_p (ip),
4846                          branch_likely_p (ip),
4847                          pinfo & INSN_WRITE_GPR_31,
4848                          0),
4849                         address_expr->X_add_symbol,
4850                         address_expr->X_add_number);
4851       *reloc_type = BFD_RELOC_UNUSED;
4852     }
4853   else if (mips_opts.micromips
4854            && address_expr
4855            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
4856                || *reloc_type > BFD_RELOC_UNUSED)
4857            && (delayed_branch_p (ip) || compact_branch_p (ip))
4858            /* Don't try branch relaxation when users specify
4859               16-bit/32-bit instructions.  */
4860            && !forced_insn_length)
4861     {
4862       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
4863       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
4864       int uncond = uncond_branch_p (ip) ? -1 : 0;
4865       int compact = compact_branch_p (ip);
4866       int al = pinfo & INSN_WRITE_GPR_31;
4867       int length32;
4868
4869       gas_assert (address_expr != NULL);
4870       gas_assert (!mips_relax.sequence);
4871
4872       relaxed_branch = TRUE;
4873       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
4874       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
4875                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
4876                                                 relax32, 0, 0),
4877                         address_expr->X_add_symbol,
4878                         address_expr->X_add_number);
4879       *reloc_type = BFD_RELOC_UNUSED;
4880     }
4881   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
4882     {
4883       /* We need to set up a variant frag.  */
4884       gas_assert (address_expr != NULL);
4885       add_relaxed_insn (ip, 4, 0,
4886                         RELAX_MIPS16_ENCODE
4887                         (*reloc_type - BFD_RELOC_UNUSED,
4888                          forced_insn_length == 2, forced_insn_length == 4,
4889                          delayed_branch_p (&history[0]),
4890                          history[0].mips16_absolute_jump_p),
4891                         make_expr_symbol (address_expr), 0);
4892     }
4893   else if (mips_opts.mips16 && insn_length (ip) == 2)
4894     {
4895       if (!delayed_branch_p (ip))
4896         /* Make sure there is enough room to swap this instruction with
4897            a following jump instruction.  */
4898         frag_grow (6);
4899       add_fixed_insn (ip);
4900     }
4901   else
4902     {
4903       if (mips_opts.mips16
4904           && mips_opts.noreorder
4905           && delayed_branch_p (&history[0]))
4906         as_warn (_("extended instruction in delay slot"));
4907
4908       if (mips_relax.sequence)
4909         {
4910           /* If we've reached the end of this frag, turn it into a variant
4911              frag and record the information for the instructions we've
4912              written so far.  */
4913           if (frag_room () < 4)
4914             relax_close_frag ();
4915           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
4916         }
4917
4918       if (mips_relax.sequence != 2)
4919         {
4920           if (mips_macro_warning.first_insn_sizes[0] == 0)
4921             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
4922           mips_macro_warning.sizes[0] += insn_length (ip);
4923           mips_macro_warning.insns[0]++;
4924         }
4925       if (mips_relax.sequence != 1)
4926         {
4927           if (mips_macro_warning.first_insn_sizes[1] == 0)
4928             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
4929           mips_macro_warning.sizes[1] += insn_length (ip);
4930           mips_macro_warning.insns[1]++;
4931         }
4932
4933       if (mips_opts.mips16)
4934         {
4935           ip->fixed_p = 1;
4936           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
4937         }
4938       add_fixed_insn (ip);
4939     }
4940
4941   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
4942     {
4943       bfd_reloc_code_real_type final_type[3];
4944       reloc_howto_type *howto0;
4945       reloc_howto_type *howto;
4946       int i;
4947
4948       /* Perform any necessary conversion to microMIPS relocations
4949          and find out how many relocations there actually are.  */
4950       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
4951         final_type[i] = micromips_map_reloc (reloc_type[i]);
4952
4953       /* In a compound relocation, it is the final (outermost)
4954          operator that determines the relocated field.  */
4955       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
4956       if (!howto)
4957         abort ();
4958
4959       if (i > 1)
4960         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
4961       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
4962                                  bfd_get_reloc_size (howto),
4963                                  address_expr,
4964                                  howto0 && howto0->pc_relative,
4965                                  final_type[0]);
4966
4967       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
4968       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
4969         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
4970
4971       /* These relocations can have an addend that won't fit in
4972          4 octets for 64bit assembly.  */
4973       if (HAVE_64BIT_GPRS
4974           && ! howto->partial_inplace
4975           && (reloc_type[0] == BFD_RELOC_16
4976               || reloc_type[0] == BFD_RELOC_32
4977               || reloc_type[0] == BFD_RELOC_MIPS_JMP
4978               || reloc_type[0] == BFD_RELOC_GPREL16
4979               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
4980               || reloc_type[0] == BFD_RELOC_GPREL32
4981               || reloc_type[0] == BFD_RELOC_64
4982               || reloc_type[0] == BFD_RELOC_CTOR
4983               || reloc_type[0] == BFD_RELOC_MIPS_SUB
4984               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
4985               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
4986               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
4987               || reloc_type[0] == BFD_RELOC_MIPS_REL16
4988               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
4989               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
4990               || hi16_reloc_p (reloc_type[0])
4991               || lo16_reloc_p (reloc_type[0])))
4992         ip->fixp[0]->fx_no_overflow = 1;
4993
4994       /* These relocations can have an addend that won't fit in 2 octets.  */
4995       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
4996           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
4997         ip->fixp[0]->fx_no_overflow = 1;
4998
4999       if (mips_relax.sequence)
5000         {
5001           if (mips_relax.first_fixup == 0)
5002             mips_relax.first_fixup = ip->fixp[0];
5003         }
5004       else if (reloc_needs_lo_p (*reloc_type))
5005         {
5006           struct mips_hi_fixup *hi_fixup;
5007
5008           /* Reuse the last entry if it already has a matching %lo.  */
5009           hi_fixup = mips_hi_fixup_list;
5010           if (hi_fixup == 0
5011               || !fixup_has_matching_lo_p (hi_fixup->fixp))
5012             {
5013               hi_fixup = ((struct mips_hi_fixup *)
5014                           xmalloc (sizeof (struct mips_hi_fixup)));
5015               hi_fixup->next = mips_hi_fixup_list;
5016               mips_hi_fixup_list = hi_fixup;
5017             }
5018           hi_fixup->fixp = ip->fixp[0];
5019           hi_fixup->seg = now_seg;
5020         }
5021
5022       /* Add fixups for the second and third relocations, if given.
5023          Note that the ABI allows the second relocation to be
5024          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
5025          moment we only use RSS_UNDEF, but we could add support
5026          for the others if it ever becomes necessary.  */
5027       for (i = 1; i < 3; i++)
5028         if (reloc_type[i] != BFD_RELOC_UNUSED)
5029           {
5030             ip->fixp[i] = fix_new (ip->frag, ip->where,
5031                                    ip->fixp[0]->fx_size, NULL, 0,
5032                                    FALSE, final_type[i]);
5033
5034             /* Use fx_tcbit to mark compound relocs.  */
5035             ip->fixp[0]->fx_tcbit = 1;
5036             ip->fixp[i]->fx_tcbit = 1;
5037           }
5038     }
5039   install_insn (ip);
5040
5041   /* Update the register mask information.  */
5042   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
5043   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
5044
5045   switch (method)
5046     {
5047     case APPEND_ADD:
5048       insert_into_history (0, 1, ip);
5049       break;
5050
5051     case APPEND_ADD_WITH_NOP:
5052       {
5053         struct mips_cl_insn *nop;
5054
5055         insert_into_history (0, 1, ip);
5056         nop = get_delay_slot_nop (ip);
5057         add_fixed_insn (nop);
5058         insert_into_history (0, 1, nop);
5059         if (mips_relax.sequence)
5060           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
5061       }
5062       break;
5063
5064     case APPEND_ADD_COMPACT:
5065       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
5066       gas_assert (mips_opts.mips16);
5067       ip->insn_opcode |= 0x0080;
5068       find_altered_mips16_opcode (ip);
5069       install_insn (ip);
5070       insert_into_history (0, 1, ip);
5071       break;
5072
5073     case APPEND_SWAP:
5074       {
5075         struct mips_cl_insn delay = history[0];
5076         if (mips_opts.mips16)
5077           {
5078             know (delay.frag == ip->frag);
5079             move_insn (ip, delay.frag, delay.where);
5080             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
5081           }
5082         else if (relaxed_branch || delay.frag != ip->frag)
5083           {
5084             /* Add the delay slot instruction to the end of the
5085                current frag and shrink the fixed part of the
5086                original frag.  If the branch occupies the tail of
5087                the latter, move it backwards to cover the gap.  */
5088             delay.frag->fr_fix -= branch_disp;
5089             if (delay.frag == ip->frag)
5090               move_insn (ip, ip->frag, ip->where - branch_disp);
5091             add_fixed_insn (&delay);
5092           }
5093         else
5094           {
5095             move_insn (&delay, ip->frag,
5096                        ip->where - branch_disp + insn_length (ip));
5097             move_insn (ip, history[0].frag, history[0].where);
5098           }
5099         history[0] = *ip;
5100         delay.fixed_p = 1;
5101         insert_into_history (0, 1, &delay);
5102       }
5103       break;
5104     }
5105
5106   /* If we have just completed an unconditional branch, clear the history.  */
5107   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
5108       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
5109     {
5110       unsigned int i;
5111
5112       mips_no_prev_insn ();
5113
5114       for (i = 0; i < ARRAY_SIZE (history); i++)
5115         history[i].cleared_p = 1;
5116     }
5117
5118   /* We need to emit a label at the end of branch-likely macros.  */
5119   if (emit_branch_likely_macro)
5120     {
5121       emit_branch_likely_macro = FALSE;
5122       micromips_add_label ();
5123     }
5124
5125   /* We just output an insn, so the next one doesn't have a label.  */
5126   mips_clear_insn_labels ();
5127 }
5128
5129 /* Forget that there was any previous instruction or label.
5130    When BRANCH is true, the branch history is also flushed.  */
5131
5132 static void
5133 mips_no_prev_insn (void)
5134 {
5135   prev_nop_frag = NULL;
5136   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
5137   mips_clear_insn_labels ();
5138 }
5139
5140 /* This function must be called before we emit something other than
5141    instructions.  It is like mips_no_prev_insn except that it inserts
5142    any NOPS that might be needed by previous instructions.  */
5143
5144 void
5145 mips_emit_delays (void)
5146 {
5147   if (! mips_opts.noreorder)
5148     {
5149       int nops = nops_for_insn (0, history, NULL);
5150       if (nops > 0)
5151         {
5152           while (nops-- > 0)
5153             add_fixed_insn (NOP_INSN);
5154           mips_move_text_labels ();
5155         }
5156     }
5157   mips_no_prev_insn ();
5158 }
5159
5160 /* Start a (possibly nested) noreorder block.  */
5161
5162 static void
5163 start_noreorder (void)
5164 {
5165   if (mips_opts.noreorder == 0)
5166     {
5167       unsigned int i;
5168       int nops;
5169
5170       /* None of the instructions before the .set noreorder can be moved.  */
5171       for (i = 0; i < ARRAY_SIZE (history); i++)
5172         history[i].fixed_p = 1;
5173
5174       /* Insert any nops that might be needed between the .set noreorder
5175          block and the previous instructions.  We will later remove any
5176          nops that turn out not to be needed.  */
5177       nops = nops_for_insn (0, history, NULL);
5178       if (nops > 0)
5179         {
5180           if (mips_optimize != 0)
5181             {
5182               /* Record the frag which holds the nop instructions, so
5183                  that we can remove them if we don't need them.  */
5184               frag_grow (nops * NOP_INSN_SIZE);
5185               prev_nop_frag = frag_now;
5186               prev_nop_frag_holds = nops;
5187               prev_nop_frag_required = 0;
5188               prev_nop_frag_since = 0;
5189             }
5190
5191           for (; nops > 0; --nops)
5192             add_fixed_insn (NOP_INSN);
5193
5194           /* Move on to a new frag, so that it is safe to simply
5195              decrease the size of prev_nop_frag.  */
5196           frag_wane (frag_now);
5197           frag_new (0);
5198           mips_move_text_labels ();
5199         }
5200       mips_mark_labels ();
5201       mips_clear_insn_labels ();
5202     }
5203   mips_opts.noreorder++;
5204   mips_any_noreorder = 1;
5205 }
5206
5207 /* End a nested noreorder block.  */
5208
5209 static void
5210 end_noreorder (void)
5211 {
5212   mips_opts.noreorder--;
5213   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
5214     {
5215       /* Commit to inserting prev_nop_frag_required nops and go back to
5216          handling nop insertion the .set reorder way.  */
5217       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
5218                                 * NOP_INSN_SIZE);
5219       insert_into_history (prev_nop_frag_since,
5220                            prev_nop_frag_required, NOP_INSN);
5221       prev_nop_frag = NULL;
5222     }
5223 }
5224
5225 /* Set up global variables for the start of a new macro.  */
5226
5227 static void
5228 macro_start (void)
5229 {
5230   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
5231   memset (&mips_macro_warning.first_insn_sizes, 0,
5232           sizeof (mips_macro_warning.first_insn_sizes));
5233   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
5234   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
5235                                      && delayed_branch_p (&history[0]));
5236   switch (history[0].insn_mo->pinfo2
5237           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
5238     {
5239     case INSN2_BRANCH_DELAY_32BIT:
5240       mips_macro_warning.delay_slot_length = 4;
5241       break;
5242     case INSN2_BRANCH_DELAY_16BIT:
5243       mips_macro_warning.delay_slot_length = 2;
5244       break;
5245     default:
5246       mips_macro_warning.delay_slot_length = 0;
5247       break;
5248     }
5249   mips_macro_warning.first_frag = NULL;
5250 }
5251
5252 /* Given that a macro is longer than one instruction or of the wrong size,
5253    return the appropriate warning for it.  Return null if no warning is
5254    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
5255    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
5256    and RELAX_NOMACRO.  */
5257
5258 static const char *
5259 macro_warning (relax_substateT subtype)
5260 {
5261   if (subtype & RELAX_DELAY_SLOT)
5262     return _("Macro instruction expanded into multiple instructions"
5263              " in a branch delay slot");
5264   else if (subtype & RELAX_NOMACRO)
5265     return _("Macro instruction expanded into multiple instructions");
5266   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
5267                       | RELAX_DELAY_SLOT_SIZE_SECOND))
5268     return ((subtype & RELAX_DELAY_SLOT_16BIT)
5269             ? _("Macro instruction expanded into a wrong size instruction"
5270                 " in a 16-bit branch delay slot")
5271             : _("Macro instruction expanded into a wrong size instruction"
5272                 " in a 32-bit branch delay slot"));
5273   else
5274     return 0;
5275 }
5276
5277 /* Finish up a macro.  Emit warnings as appropriate.  */
5278
5279 static void
5280 macro_end (void)
5281 {
5282   /* Relaxation warning flags.  */
5283   relax_substateT subtype = 0;
5284
5285   /* Check delay slot size requirements.  */
5286   if (mips_macro_warning.delay_slot_length == 2)
5287     subtype |= RELAX_DELAY_SLOT_16BIT;
5288   if (mips_macro_warning.delay_slot_length != 0)
5289     {
5290       if (mips_macro_warning.delay_slot_length
5291           != mips_macro_warning.first_insn_sizes[0])
5292         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
5293       if (mips_macro_warning.delay_slot_length
5294           != mips_macro_warning.first_insn_sizes[1])
5295         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
5296     }
5297
5298   /* Check instruction count requirements.  */
5299   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
5300     {
5301       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
5302         subtype |= RELAX_SECOND_LONGER;
5303       if (mips_opts.warn_about_macros)
5304         subtype |= RELAX_NOMACRO;
5305       if (mips_macro_warning.delay_slot_p)
5306         subtype |= RELAX_DELAY_SLOT;
5307     }
5308
5309   /* If both alternatives fail to fill a delay slot correctly,
5310      emit the warning now.  */
5311   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
5312       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
5313     {
5314       relax_substateT s;
5315       const char *msg;
5316
5317       s = subtype & (RELAX_DELAY_SLOT_16BIT
5318                      | RELAX_DELAY_SLOT_SIZE_FIRST
5319                      | RELAX_DELAY_SLOT_SIZE_SECOND);
5320       msg = macro_warning (s);
5321       if (msg != NULL)
5322         as_warn ("%s", msg);
5323       subtype &= ~s;
5324     }
5325
5326   /* If both implementations are longer than 1 instruction, then emit the
5327      warning now.  */
5328   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
5329     {
5330       relax_substateT s;
5331       const char *msg;
5332
5333       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
5334       msg = macro_warning (s);
5335       if (msg != NULL)
5336         as_warn ("%s", msg);
5337       subtype &= ~s;
5338     }
5339
5340   /* If any flags still set, then one implementation might need a warning
5341      and the other either will need one of a different kind or none at all.
5342      Pass any remaining flags over to relaxation.  */
5343   if (mips_macro_warning.first_frag != NULL)
5344     mips_macro_warning.first_frag->fr_subtype |= subtype;
5345 }
5346
5347 /* Instruction operand formats used in macros that vary between
5348    standard MIPS and microMIPS code.  */
5349
5350 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
5351 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
5352 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
5353 static const char * const lui_fmt[2] = { "t,u", "s,u" };
5354 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
5355 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
5356 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
5357 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
5358
5359 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
5360 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
5361 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
5362 #define LUI_FMT (lui_fmt[mips_opts.micromips])
5363 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
5364 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
5365 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
5366 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
5367
5368 /* Read a macro's relocation codes from *ARGS and store them in *R.
5369    The first argument in *ARGS will be either the code for a single
5370    relocation or -1 followed by the three codes that make up a
5371    composite relocation.  */
5372
5373 static void
5374 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
5375 {
5376   int i, next;
5377
5378   next = va_arg (*args, int);
5379   if (next >= 0)
5380     r[0] = (bfd_reloc_code_real_type) next;
5381   else
5382     {
5383       for (i = 0; i < 3; i++)
5384         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
5385       /* This function is only used for 16-bit relocation fields.
5386          To make the macro code simpler, treat an unrelocated value
5387          in the same way as BFD_RELOC_LO16.  */
5388       if (r[0] == BFD_RELOC_UNUSED)
5389         r[0] = BFD_RELOC_LO16;
5390     }
5391 }
5392
5393 /* Build an instruction created by a macro expansion.  This is passed
5394    a pointer to the count of instructions created so far, an
5395    expression, the name of the instruction to build, an operand format
5396    string, and corresponding arguments.  */
5397
5398 static void
5399 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
5400 {
5401   const struct mips_opcode *mo = NULL;
5402   bfd_reloc_code_real_type r[3];
5403   const struct mips_opcode *amo;
5404   struct hash_control *hash;
5405   struct mips_cl_insn insn;
5406   va_list args;
5407
5408   va_start (args, fmt);
5409
5410   if (mips_opts.mips16)
5411     {
5412       mips16_macro_build (ep, name, fmt, &args);
5413       va_end (args);
5414       return;
5415     }
5416
5417   r[0] = BFD_RELOC_UNUSED;
5418   r[1] = BFD_RELOC_UNUSED;
5419   r[2] = BFD_RELOC_UNUSED;
5420   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
5421   amo = (struct mips_opcode *) hash_find (hash, name);
5422   gas_assert (amo);
5423   gas_assert (strcmp (name, amo->name) == 0);
5424
5425   do
5426     {
5427       /* Search until we get a match for NAME.  It is assumed here that
5428          macros will never generate MDMX, MIPS-3D, or MT instructions.
5429          We try to match an instruction that fulfils the branch delay
5430          slot instruction length requirement (if any) of the previous
5431          instruction.  While doing this we record the first instruction
5432          seen that matches all the other conditions and use it anyway
5433          if the requirement cannot be met; we will issue an appropriate
5434          warning later on.  */
5435       if (strcmp (fmt, amo->args) == 0
5436           && amo->pinfo != INSN_MACRO
5437           && is_opcode_valid (amo)
5438           && is_size_valid (amo))
5439         {
5440           if (is_delay_slot_valid (amo))
5441             {
5442               mo = amo;
5443               break;
5444             }
5445           else if (!mo)
5446             mo = amo;
5447         }
5448
5449       ++amo;
5450       gas_assert (amo->name);
5451     }
5452   while (strcmp (name, amo->name) == 0);
5453
5454   gas_assert (mo);
5455   create_insn (&insn, mo);
5456   for (;;)
5457     {
5458       switch (*fmt++)
5459         {
5460         case '\0':
5461           break;
5462
5463         case ',':
5464         case '(':
5465         case ')':
5466           continue;
5467
5468         case '+':
5469           switch (*fmt++)
5470             {
5471             case 'A':
5472             case 'E':
5473               INSERT_OPERAND (mips_opts.micromips,
5474                               EXTLSB, insn, va_arg (args, int));
5475               continue;
5476
5477             case 'B':
5478             case 'F':
5479               /* Note that in the macro case, these arguments are already
5480                  in MSB form.  (When handling the instruction in the
5481                  non-macro case, these arguments are sizes from which
5482                  MSB values must be calculated.)  */
5483               INSERT_OPERAND (mips_opts.micromips,
5484                               INSMSB, insn, va_arg (args, int));
5485               continue;
5486
5487             case 'J':
5488               gas_assert (!mips_opts.micromips);
5489               INSERT_OPERAND (0, CODE10, insn, va_arg (args, int));
5490               continue;
5491
5492             case 'C':
5493             case 'G':
5494             case 'H':
5495               /* Note that in the macro case, these arguments are already
5496                  in MSBD form.  (When handling the instruction in the
5497                  non-macro case, these arguments are sizes from which
5498                  MSBD values must be calculated.)  */
5499               INSERT_OPERAND (mips_opts.micromips,
5500                               EXTMSBD, insn, va_arg (args, int));
5501               continue;
5502
5503             case 'Q':
5504               gas_assert (!mips_opts.micromips);
5505               INSERT_OPERAND (0, SEQI, insn, va_arg (args, int));
5506               continue;
5507
5508             case 'j':
5509               INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, insn, va_arg (args, int));
5510               continue;
5511
5512             default:
5513               abort ();
5514             }
5515           continue;
5516
5517         case '2':
5518           INSERT_OPERAND (mips_opts.micromips, BP, insn, va_arg (args, int));
5519           continue;
5520
5521         case 'n':
5522           gas_assert (mips_opts.micromips);
5523         case 't':
5524         case 'w':
5525         case 'E':
5526           INSERT_OPERAND (mips_opts.micromips, RT, insn, va_arg (args, int));
5527           continue;
5528
5529         case 'c':
5530           INSERT_OPERAND (mips_opts.micromips, CODE, insn, va_arg (args, int));
5531           continue;
5532
5533         case 'W':
5534           gas_assert (!mips_opts.micromips);
5535         case 'T':
5536           INSERT_OPERAND (mips_opts.micromips, FT, insn, va_arg (args, int));
5537           continue;
5538
5539         case 'G':
5540           if (mips_opts.micromips)
5541             INSERT_OPERAND (1, RS, insn, va_arg (args, int));
5542           else
5543             INSERT_OPERAND (0, RD, insn, va_arg (args, int));
5544           continue;
5545
5546         case 'K':
5547           gas_assert (!mips_opts.micromips);
5548         case 'd':
5549           INSERT_OPERAND (mips_opts.micromips, RD, insn, va_arg (args, int));
5550           continue;
5551
5552         case 'U':
5553           gas_assert (!mips_opts.micromips);
5554           {
5555             int tmp = va_arg (args, int);
5556
5557             INSERT_OPERAND (0, RT, insn, tmp);
5558             INSERT_OPERAND (0, RD, insn, tmp);
5559           }
5560           continue;
5561
5562         case 'V':
5563         case 'S':
5564           gas_assert (!mips_opts.micromips);
5565           INSERT_OPERAND (0, FS, insn, va_arg (args, int));
5566           continue;
5567
5568         case 'z':
5569           continue;
5570
5571         case '<':
5572           INSERT_OPERAND (mips_opts.micromips,
5573                           SHAMT, insn, va_arg (args, int));
5574           continue;
5575
5576         case 'D':
5577           gas_assert (!mips_opts.micromips);
5578           INSERT_OPERAND (0, FD, insn, va_arg (args, int));
5579           continue;
5580
5581         case 'B':
5582           gas_assert (!mips_opts.micromips);
5583           INSERT_OPERAND (0, CODE20, insn, va_arg (args, int));
5584           continue;
5585
5586         case 'J':
5587           gas_assert (!mips_opts.micromips);
5588           INSERT_OPERAND (0, CODE19, insn, va_arg (args, int));
5589           continue;
5590
5591         case 'q':
5592           gas_assert (!mips_opts.micromips);
5593           INSERT_OPERAND (0, CODE2, insn, va_arg (args, int));
5594           continue;
5595
5596         case 'b':
5597         case 's':
5598         case 'r':
5599         case 'v':
5600           INSERT_OPERAND (mips_opts.micromips, RS, insn, va_arg (args, int));
5601           continue;
5602
5603         case 'i':
5604         case 'j':
5605           macro_read_relocs (&args, r);
5606           gas_assert (*r == BFD_RELOC_GPREL16
5607                       || *r == BFD_RELOC_MIPS_HIGHER
5608                       || *r == BFD_RELOC_HI16_S
5609                       || *r == BFD_RELOC_LO16
5610                       || *r == BFD_RELOC_MIPS_GOT_OFST);
5611           continue;
5612
5613         case 'o':
5614           macro_read_relocs (&args, r);
5615           continue;
5616
5617         case 'u':
5618           macro_read_relocs (&args, r);
5619           gas_assert (ep != NULL
5620                       && (ep->X_op == O_constant
5621                           || (ep->X_op == O_symbol
5622                               && (*r == BFD_RELOC_MIPS_HIGHEST
5623                                   || *r == BFD_RELOC_HI16_S
5624                                   || *r == BFD_RELOC_HI16
5625                                   || *r == BFD_RELOC_GPREL16
5626                                   || *r == BFD_RELOC_MIPS_GOT_HI16
5627                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
5628           continue;
5629
5630         case 'p':
5631           gas_assert (ep != NULL);
5632
5633           /*
5634            * This allows macro() to pass an immediate expression for
5635            * creating short branches without creating a symbol.
5636            *
5637            * We don't allow branch relaxation for these branches, as
5638            * they should only appear in ".set nomacro" anyway.
5639            */
5640           if (ep->X_op == O_constant)
5641             {
5642               /* For microMIPS we always use relocations for branches.
5643                  So we should not resolve immediate values.  */
5644               gas_assert (!mips_opts.micromips);
5645
5646               if ((ep->X_add_number & 3) != 0)
5647                 as_bad (_("branch to misaligned address (0x%lx)"),
5648                         (unsigned long) ep->X_add_number);
5649               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
5650                 as_bad (_("branch address range overflow (0x%lx)"),
5651                         (unsigned long) ep->X_add_number);
5652               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
5653               ep = NULL;
5654             }
5655           else
5656             *r = BFD_RELOC_16_PCREL_S2;
5657           continue;
5658
5659         case 'a':
5660           gas_assert (ep != NULL);
5661           *r = BFD_RELOC_MIPS_JMP;
5662           continue;
5663
5664         case 'C':
5665           gas_assert (!mips_opts.micromips);
5666           INSERT_OPERAND (0, COPZ, insn, va_arg (args, int));
5667           continue;
5668
5669         case 'k':
5670           INSERT_OPERAND (mips_opts.micromips,
5671                           CACHE, insn, va_arg (args, int));
5672           continue;
5673
5674         case '|':
5675           gas_assert (mips_opts.micromips);
5676           INSERT_OPERAND (1, TRAP, insn, va_arg (args, int));
5677           continue;
5678
5679         case '.':
5680           gas_assert (mips_opts.micromips);
5681           INSERT_OPERAND (1, OFFSET10, insn, va_arg (args, int));
5682           continue;
5683
5684         case '\\':
5685           INSERT_OPERAND (mips_opts.micromips,
5686                           3BITPOS, insn, va_arg (args, int));
5687           continue;
5688
5689         case '~':
5690           INSERT_OPERAND (mips_opts.micromips,
5691                           OFFSET12, insn, va_arg (args, int));
5692           continue;
5693
5694         case 'N':
5695           gas_assert (mips_opts.micromips);
5696           INSERT_OPERAND (1, BCC, insn, va_arg (args, int));
5697           continue;
5698
5699         case 'm':       /* Opcode extension character.  */
5700           gas_assert (mips_opts.micromips);
5701           switch (*fmt++)
5702             {
5703             case 'j':
5704               INSERT_OPERAND (1, MJ, insn, va_arg (args, int));
5705               break;
5706
5707             case 'p':
5708               INSERT_OPERAND (1, MP, insn, va_arg (args, int));
5709               break;
5710
5711             case 'F':
5712               INSERT_OPERAND (1, IMMF, insn, va_arg (args, int));
5713               break;
5714
5715             default:
5716               abort ();
5717             }
5718           continue;
5719
5720         default:
5721           abort ();
5722         }
5723       break;
5724     }
5725   va_end (args);
5726   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5727
5728   append_insn (&insn, ep, r, TRUE);
5729 }
5730
5731 static void
5732 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
5733                     va_list *args)
5734 {
5735   struct mips_opcode *mo;
5736   struct mips_cl_insn insn;
5737   bfd_reloc_code_real_type r[3]
5738     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
5739
5740   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
5741   gas_assert (mo);
5742   gas_assert (strcmp (name, mo->name) == 0);
5743
5744   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
5745     {
5746       ++mo;
5747       gas_assert (mo->name);
5748       gas_assert (strcmp (name, mo->name) == 0);
5749     }
5750
5751   create_insn (&insn, mo);
5752   for (;;)
5753     {
5754       int c;
5755
5756       c = *fmt++;
5757       switch (c)
5758         {
5759         case '\0':
5760           break;
5761
5762         case ',':
5763         case '(':
5764         case ')':
5765           continue;
5766
5767         case 'y':
5768         case 'w':
5769           MIPS16_INSERT_OPERAND (RY, insn, va_arg (*args, int));
5770           continue;
5771
5772         case 'x':
5773         case 'v':
5774           MIPS16_INSERT_OPERAND (RX, insn, va_arg (*args, int));
5775           continue;
5776
5777         case 'z':
5778           MIPS16_INSERT_OPERAND (RZ, insn, va_arg (*args, int));
5779           continue;
5780
5781         case 'Z':
5782           MIPS16_INSERT_OPERAND (MOVE32Z, insn, va_arg (*args, int));
5783           continue;
5784
5785         case '0':
5786         case 'S':
5787         case 'P':
5788         case 'R':
5789           continue;
5790
5791         case 'X':
5792           MIPS16_INSERT_OPERAND (REGR32, insn, va_arg (*args, int));
5793           continue;
5794
5795         case '<':
5796         case '>':
5797         case '4':
5798         case '5':
5799         case 'H':
5800         case 'W':
5801         case 'D':
5802         case 'j':
5803         case '8':
5804         case 'V':
5805         case 'C':
5806         case 'U':
5807         case 'k':
5808         case 'K':
5809         case 'p':
5810         case 'q':
5811           {
5812             offsetT value;
5813
5814             gas_assert (ep != NULL);
5815
5816             if (ep->X_op != O_constant)
5817               *r = (int) BFD_RELOC_UNUSED + c;
5818             else if (calculate_reloc (*r, ep->X_add_number, &value))
5819               {
5820                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
5821                 ep = NULL;
5822                 *r = BFD_RELOC_UNUSED;
5823               }
5824           }
5825           continue;
5826
5827         case '6':
5828           MIPS16_INSERT_OPERAND (IMM6, insn, va_arg (*args, int));
5829           continue;
5830         }
5831
5832       break;
5833     }
5834
5835   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
5836
5837   append_insn (&insn, ep, r, TRUE);
5838 }
5839
5840 /*
5841  * Sign-extend 32-bit mode constants that have bit 31 set and all
5842  * higher bits unset.
5843  */
5844 static void
5845 normalize_constant_expr (expressionS *ex)
5846 {
5847   if (ex->X_op == O_constant
5848       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5849     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5850                         - 0x80000000);
5851 }
5852
5853 /*
5854  * Sign-extend 32-bit mode address offsets that have bit 31 set and
5855  * all higher bits unset.
5856  */
5857 static void
5858 normalize_address_expr (expressionS *ex)
5859 {
5860   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
5861         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
5862       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
5863     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
5864                         - 0x80000000);
5865 }
5866
5867 /*
5868  * Generate a "jalr" instruction with a relocation hint to the called
5869  * function.  This occurs in NewABI PIC code.
5870  */
5871 static void
5872 macro_build_jalr (expressionS *ep, int cprestore)
5873 {
5874   static const bfd_reloc_code_real_type jalr_relocs[2]
5875     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
5876   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
5877   const char *jalr;
5878   char *f = NULL;
5879
5880   if (MIPS_JALR_HINT_P (ep))
5881     {
5882       frag_grow (8);
5883       f = frag_more (0);
5884     }
5885   if (mips_opts.micromips)
5886     {
5887       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
5888               ? "jalr" : "jalrs");
5889       if (MIPS_JALR_HINT_P (ep)
5890           || mips_opts.insn32
5891           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
5892         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
5893       else
5894         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
5895     }
5896   else
5897     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
5898   if (MIPS_JALR_HINT_P (ep))
5899     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
5900 }
5901
5902 /*
5903  * Generate a "lui" instruction.
5904  */
5905 static void
5906 macro_build_lui (expressionS *ep, int regnum)
5907 {
5908   gas_assert (! mips_opts.mips16);
5909
5910   if (ep->X_op != O_constant)
5911     {
5912       gas_assert (ep->X_op == O_symbol);
5913       /* _gp_disp is a special case, used from s_cpload.
5914          __gnu_local_gp is used if mips_no_shared.  */
5915       gas_assert (mips_pic == NO_PIC
5916               || (! HAVE_NEWABI
5917                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
5918               || (! mips_in_shared
5919                   && strcmp (S_GET_NAME (ep->X_add_symbol),
5920                              "__gnu_local_gp") == 0));
5921     }
5922
5923   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
5924 }
5925
5926 /* Generate a sequence of instructions to do a load or store from a constant
5927    offset off of a base register (breg) into/from a target register (treg),
5928    using AT if necessary.  */
5929 static void
5930 macro_build_ldst_constoffset (expressionS *ep, const char *op,
5931                               int treg, int breg, int dbl)
5932 {
5933   gas_assert (ep->X_op == O_constant);
5934
5935   /* Sign-extending 32-bit constants makes their handling easier.  */
5936   if (!dbl)
5937     normalize_constant_expr (ep);
5938
5939   /* Right now, this routine can only handle signed 32-bit constants.  */
5940   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
5941     as_warn (_("operand overflow"));
5942
5943   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
5944     {
5945       /* Signed 16-bit offset will fit in the op.  Easy!  */
5946       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
5947     }
5948   else
5949     {
5950       /* 32-bit offset, need multiple instructions and AT, like:
5951            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
5952            addu     $tempreg,$tempreg,$breg
5953            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
5954          to handle the complete offset.  */
5955       macro_build_lui (ep, AT);
5956       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
5957       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
5958
5959       if (!mips_opts.at)
5960         as_bad (_("Macro used $at after \".set noat\""));
5961     }
5962 }
5963
5964 /*                      set_at()
5965  * Generates code to set the $at register to true (one)
5966  * if reg is less than the immediate expression.
5967  */
5968 static void
5969 set_at (int reg, int unsignedp)
5970 {
5971   if (imm_expr.X_op == O_constant
5972       && imm_expr.X_add_number >= -0x8000
5973       && imm_expr.X_add_number < 0x8000)
5974     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
5975                  AT, reg, BFD_RELOC_LO16);
5976   else
5977     {
5978       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
5979       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
5980     }
5981 }
5982
5983 /* Warn if an expression is not a constant.  */
5984
5985 static void
5986 check_absolute_expr (struct mips_cl_insn *ip, expressionS *ex)
5987 {
5988   if (ex->X_op == O_big)
5989     as_bad (_("unsupported large constant"));
5990   else if (ex->X_op != O_constant)
5991     as_bad (_("Instruction %s requires absolute expression"),
5992             ip->insn_mo->name);
5993
5994   if (HAVE_32BIT_GPRS)
5995     normalize_constant_expr (ex);
5996 }
5997
5998 /* Count the leading zeroes by performing a binary chop. This is a
5999    bulky bit of source, but performance is a LOT better for the
6000    majority of values than a simple loop to count the bits:
6001        for (lcnt = 0; (lcnt < 32); lcnt++)
6002          if ((v) & (1 << (31 - lcnt)))
6003            break;
6004   However it is not code size friendly, and the gain will drop a bit
6005   on certain cached systems.
6006 */
6007 #define COUNT_TOP_ZEROES(v)             \
6008   (((v) & ~0xffff) == 0                 \
6009    ? ((v) & ~0xff) == 0                 \
6010      ? ((v) & ~0xf) == 0                \
6011        ? ((v) & ~0x3) == 0              \
6012          ? ((v) & ~0x1) == 0            \
6013            ? !(v)                       \
6014              ? 32                       \
6015              : 31                       \
6016            : 30                         \
6017          : ((v) & ~0x7) == 0            \
6018            ? 29                         \
6019            : 28                         \
6020        : ((v) & ~0x3f) == 0             \
6021          ? ((v) & ~0x1f) == 0           \
6022            ? 27                         \
6023            : 26                         \
6024          : ((v) & ~0x7f) == 0           \
6025            ? 25                         \
6026            : 24                         \
6027      : ((v) & ~0xfff) == 0              \
6028        ? ((v) & ~0x3ff) == 0            \
6029          ? ((v) & ~0x1ff) == 0          \
6030            ? 23                         \
6031            : 22                         \
6032          : ((v) & ~0x7ff) == 0          \
6033            ? 21                         \
6034            : 20                         \
6035        : ((v) & ~0x3fff) == 0           \
6036          ? ((v) & ~0x1fff) == 0         \
6037            ? 19                         \
6038            : 18                         \
6039          : ((v) & ~0x7fff) == 0         \
6040            ? 17                         \
6041            : 16                         \
6042    : ((v) & ~0xffffff) == 0             \
6043      ? ((v) & ~0xfffff) == 0            \
6044        ? ((v) & ~0x3ffff) == 0          \
6045          ? ((v) & ~0x1ffff) == 0        \
6046            ? 15                         \
6047            : 14                         \
6048          : ((v) & ~0x7ffff) == 0        \
6049            ? 13                         \
6050            : 12                         \
6051        : ((v) & ~0x3fffff) == 0         \
6052          ? ((v) & ~0x1fffff) == 0       \
6053            ? 11                         \
6054            : 10                         \
6055          : ((v) & ~0x7fffff) == 0       \
6056            ? 9                          \
6057            : 8                          \
6058      : ((v) & ~0xfffffff) == 0          \
6059        ? ((v) & ~0x3ffffff) == 0        \
6060          ? ((v) & ~0x1ffffff) == 0      \
6061            ? 7                          \
6062            : 6                          \
6063          : ((v) & ~0x7ffffff) == 0      \
6064            ? 5                          \
6065            : 4                          \
6066        : ((v) & ~0x3fffffff) == 0       \
6067          ? ((v) & ~0x1fffffff) == 0     \
6068            ? 3                          \
6069            : 2                          \
6070          : ((v) & ~0x7fffffff) == 0     \
6071            ? 1                          \
6072            : 0)
6073
6074 /*                      load_register()
6075  *  This routine generates the least number of instructions necessary to load
6076  *  an absolute expression value into a register.
6077  */
6078 static void
6079 load_register (int reg, expressionS *ep, int dbl)
6080 {
6081   int freg;
6082   expressionS hi32, lo32;
6083
6084   if (ep->X_op != O_big)
6085     {
6086       gas_assert (ep->X_op == O_constant);
6087
6088       /* Sign-extending 32-bit constants makes their handling easier.  */
6089       if (!dbl)
6090         normalize_constant_expr (ep);
6091
6092       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
6093         {
6094           /* We can handle 16 bit signed values with an addiu to
6095              $zero.  No need to ever use daddiu here, since $zero and
6096              the result are always correct in 32 bit mode.  */
6097           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6098           return;
6099         }
6100       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
6101         {
6102           /* We can handle 16 bit unsigned values with an ori to
6103              $zero.  */
6104           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6105           return;
6106         }
6107       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
6108         {
6109           /* 32 bit values require an lui.  */
6110           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6111           if ((ep->X_add_number & 0xffff) != 0)
6112             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6113           return;
6114         }
6115     }
6116
6117   /* The value is larger than 32 bits.  */
6118
6119   if (!dbl || HAVE_32BIT_GPRS)
6120     {
6121       char value[32];
6122
6123       sprintf_vma (value, ep->X_add_number);
6124       as_bad (_("Number (0x%s) larger than 32 bits"), value);
6125       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6126       return;
6127     }
6128
6129   if (ep->X_op != O_big)
6130     {
6131       hi32 = *ep;
6132       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6133       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
6134       hi32.X_add_number &= 0xffffffff;
6135       lo32 = *ep;
6136       lo32.X_add_number &= 0xffffffff;
6137     }
6138   else
6139     {
6140       gas_assert (ep->X_add_number > 2);
6141       if (ep->X_add_number == 3)
6142         generic_bignum[3] = 0;
6143       else if (ep->X_add_number > 4)
6144         as_bad (_("Number larger than 64 bits"));
6145       lo32.X_op = O_constant;
6146       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
6147       hi32.X_op = O_constant;
6148       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
6149     }
6150
6151   if (hi32.X_add_number == 0)
6152     freg = 0;
6153   else
6154     {
6155       int shift, bit;
6156       unsigned long hi, lo;
6157
6158       if (hi32.X_add_number == (offsetT) 0xffffffff)
6159         {
6160           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
6161             {
6162               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6163               return;
6164             }
6165           if (lo32.X_add_number & 0x80000000)
6166             {
6167               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6168               if (lo32.X_add_number & 0xffff)
6169                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
6170               return;
6171             }
6172         }
6173
6174       /* Check for 16bit shifted constant.  We know that hi32 is
6175          non-zero, so start the mask on the first bit of the hi32
6176          value.  */
6177       shift = 17;
6178       do
6179         {
6180           unsigned long himask, lomask;
6181
6182           if (shift < 32)
6183             {
6184               himask = 0xffff >> (32 - shift);
6185               lomask = (0xffff << shift) & 0xffffffff;
6186             }
6187           else
6188             {
6189               himask = 0xffff << (shift - 32);
6190               lomask = 0;
6191             }
6192           if ((hi32.X_add_number & ~(offsetT) himask) == 0
6193               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
6194             {
6195               expressionS tmp;
6196
6197               tmp.X_op = O_constant;
6198               if (shift < 32)
6199                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
6200                                     | (lo32.X_add_number >> shift));
6201               else
6202                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
6203               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
6204               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6205                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6206               return;
6207             }
6208           ++shift;
6209         }
6210       while (shift <= (64 - 16));
6211
6212       /* Find the bit number of the lowest one bit, and store the
6213          shifted value in hi/lo.  */
6214       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
6215       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
6216       if (lo != 0)
6217         {
6218           bit = 0;
6219           while ((lo & 1) == 0)
6220             {
6221               lo >>= 1;
6222               ++bit;
6223             }
6224           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
6225           hi >>= bit;
6226         }
6227       else
6228         {
6229           bit = 32;
6230           while ((hi & 1) == 0)
6231             {
6232               hi >>= 1;
6233               ++bit;
6234             }
6235           lo = hi;
6236           hi = 0;
6237         }
6238
6239       /* Optimize if the shifted value is a (power of 2) - 1.  */
6240       if ((hi == 0 && ((lo + 1) & lo) == 0)
6241           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
6242         {
6243           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
6244           if (shift != 0)
6245             {
6246               expressionS tmp;
6247
6248               /* This instruction will set the register to be all
6249                  ones.  */
6250               tmp.X_op = O_constant;
6251               tmp.X_add_number = (offsetT) -1;
6252               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
6253               if (bit != 0)
6254                 {
6255                   bit += shift;
6256                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
6257                                reg, reg, (bit >= 32) ? bit - 32 : bit);
6258                 }
6259               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
6260                            reg, reg, (shift >= 32) ? shift - 32 : shift);
6261               return;
6262             }
6263         }
6264
6265       /* Sign extend hi32 before calling load_register, because we can
6266          generally get better code when we load a sign extended value.  */
6267       if ((hi32.X_add_number & 0x80000000) != 0)
6268         hi32.X_add_number |= ~(offsetT) 0xffffffff;
6269       load_register (reg, &hi32, 0);
6270       freg = reg;
6271     }
6272   if ((lo32.X_add_number & 0xffff0000) == 0)
6273     {
6274       if (freg != 0)
6275         {
6276           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
6277           freg = reg;
6278         }
6279     }
6280   else
6281     {
6282       expressionS mid16;
6283
6284       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
6285         {
6286           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
6287           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
6288           return;
6289         }
6290
6291       if (freg != 0)
6292         {
6293           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
6294           freg = reg;
6295         }
6296       mid16 = lo32;
6297       mid16.X_add_number >>= 16;
6298       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6299       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6300       freg = reg;
6301     }
6302   if ((lo32.X_add_number & 0xffff) != 0)
6303     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
6304 }
6305
6306 static inline void
6307 load_delay_nop (void)
6308 {
6309   if (!gpr_interlocks)
6310     macro_build (NULL, "nop", "");
6311 }
6312
6313 /* Load an address into a register.  */
6314
6315 static void
6316 load_address (int reg, expressionS *ep, int *used_at)
6317 {
6318   if (ep->X_op != O_constant
6319       && ep->X_op != O_symbol)
6320     {
6321       as_bad (_("expression too complex"));
6322       ep->X_op = O_constant;
6323     }
6324
6325   if (ep->X_op == O_constant)
6326     {
6327       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
6328       return;
6329     }
6330
6331   if (mips_pic == NO_PIC)
6332     {
6333       /* If this is a reference to a GP relative symbol, we want
6334            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
6335          Otherwise we want
6336            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
6337            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6338          If we have an addend, we always use the latter form.
6339
6340          With 64bit address space and a usable $at we want
6341            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6342            lui          $at,<sym>               (BFD_RELOC_HI16_S)
6343            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6344            daddiu       $at,<sym>               (BFD_RELOC_LO16)
6345            dsll32       $reg,0
6346            daddu        $reg,$reg,$at
6347
6348          If $at is already in use, we use a path which is suboptimal
6349          on superscalar processors.
6350            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
6351            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
6352            dsll         $reg,16
6353            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
6354            dsll         $reg,16
6355            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
6356
6357          For GP relative symbols in 64bit address space we can use
6358          the same sequence as in 32bit address space.  */
6359       if (HAVE_64BIT_SYMBOLS)
6360         {
6361           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6362               && !nopic_need_relax (ep->X_add_symbol, 1))
6363             {
6364               relax_start (ep->X_add_symbol);
6365               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6366                            mips_gp_register, BFD_RELOC_GPREL16);
6367               relax_switch ();
6368             }
6369
6370           if (*used_at == 0 && mips_opts.at)
6371             {
6372               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6373               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
6374               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6375                            BFD_RELOC_MIPS_HIGHER);
6376               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
6377               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
6378               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
6379               *used_at = 1;
6380             }
6381           else
6382             {
6383               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
6384               macro_build (ep, "daddiu", "t,r,j", reg, reg,
6385                            BFD_RELOC_MIPS_HIGHER);
6386               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6387               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
6388               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
6389               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
6390             }
6391
6392           if (mips_relax.sequence)
6393             relax_end ();
6394         }
6395       else
6396         {
6397           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
6398               && !nopic_need_relax (ep->X_add_symbol, 1))
6399             {
6400               relax_start (ep->X_add_symbol);
6401               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
6402                            mips_gp_register, BFD_RELOC_GPREL16);
6403               relax_switch ();
6404             }
6405           macro_build_lui (ep, reg);
6406           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
6407                        reg, reg, BFD_RELOC_LO16);
6408           if (mips_relax.sequence)
6409             relax_end ();
6410         }
6411     }
6412   else if (!mips_big_got)
6413     {
6414       expressionS ex;
6415
6416       /* If this is a reference to an external symbol, we want
6417            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6418          Otherwise we want
6419            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6420            nop
6421            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6422          If there is a constant, it must be added in after.
6423
6424          If we have NewABI, we want
6425            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
6426          unless we're referencing a global symbol with a non-zero
6427          offset, in which case cst must be added separately.  */
6428       if (HAVE_NEWABI)
6429         {
6430           if (ep->X_add_number)
6431             {
6432               ex.X_add_number = ep->X_add_number;
6433               ep->X_add_number = 0;
6434               relax_start (ep->X_add_symbol);
6435               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6436                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6437               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6438                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6439               ex.X_op = O_constant;
6440               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6441                            reg, reg, BFD_RELOC_LO16);
6442               ep->X_add_number = ex.X_add_number;
6443               relax_switch ();
6444             }
6445           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6446                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
6447           if (mips_relax.sequence)
6448             relax_end ();
6449         }
6450       else
6451         {
6452           ex.X_add_number = ep->X_add_number;
6453           ep->X_add_number = 0;
6454           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6455                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6456           load_delay_nop ();
6457           relax_start (ep->X_add_symbol);
6458           relax_switch ();
6459           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6460                        BFD_RELOC_LO16);
6461           relax_end ();
6462
6463           if (ex.X_add_number != 0)
6464             {
6465               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6466                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6467               ex.X_op = O_constant;
6468               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
6469                            reg, reg, BFD_RELOC_LO16);
6470             }
6471         }
6472     }
6473   else if (mips_big_got)
6474     {
6475       expressionS ex;
6476
6477       /* This is the large GOT case.  If this is a reference to an
6478          external symbol, we want
6479            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
6480            addu         $reg,$reg,$gp
6481            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
6482
6483          Otherwise, for a reference to a local symbol in old ABI, we want
6484            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
6485            nop
6486            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
6487          If there is a constant, it must be added in after.
6488
6489          In the NewABI, for local symbols, with or without offsets, we want:
6490            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
6491            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
6492       */
6493       if (HAVE_NEWABI)
6494         {
6495           ex.X_add_number = ep->X_add_number;
6496           ep->X_add_number = 0;
6497           relax_start (ep->X_add_symbol);
6498           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6499           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6500                        reg, reg, mips_gp_register);
6501           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6502                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6503           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6504             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6505           else if (ex.X_add_number)
6506             {
6507               ex.X_op = O_constant;
6508               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6509                            BFD_RELOC_LO16);
6510             }
6511
6512           ep->X_add_number = ex.X_add_number;
6513           relax_switch ();
6514           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6515                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
6516           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6517                        BFD_RELOC_MIPS_GOT_OFST);
6518           relax_end ();
6519         }
6520       else
6521         {
6522           ex.X_add_number = ep->X_add_number;
6523           ep->X_add_number = 0;
6524           relax_start (ep->X_add_symbol);
6525           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
6526           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
6527                        reg, reg, mips_gp_register);
6528           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
6529                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
6530           relax_switch ();
6531           if (reg_needs_delay (mips_gp_register))
6532             {
6533               /* We need a nop before loading from $gp.  This special
6534                  check is required because the lui which starts the main
6535                  instruction stream does not refer to $gp, and so will not
6536                  insert the nop which may be required.  */
6537               macro_build (NULL, "nop", "");
6538             }
6539           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
6540                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
6541           load_delay_nop ();
6542           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6543                        BFD_RELOC_LO16);
6544           relax_end ();
6545
6546           if (ex.X_add_number != 0)
6547             {
6548               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
6549                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
6550               ex.X_op = O_constant;
6551               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
6552                            BFD_RELOC_LO16);
6553             }
6554         }
6555     }
6556   else
6557     abort ();
6558
6559   if (!mips_opts.at && *used_at == 1)
6560     as_bad (_("Macro used $at after \".set noat\""));
6561 }
6562
6563 /* Move the contents of register SOURCE into register DEST.  */
6564
6565 static void
6566 move_register (int dest, int source)
6567 {
6568   /* Prefer to use a 16-bit microMIPS instruction unless the previous
6569      instruction specifically requires a 32-bit one.  */
6570   if (mips_opts.micromips
6571       && !mips_opts.insn32
6572       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
6573     macro_build (NULL, "move", "mp,mj", dest, source);
6574   else
6575     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
6576                  dest, source, 0);
6577 }
6578
6579 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
6580    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
6581    The two alternatives are:
6582
6583    Global symbol                Local sybmol
6584    -------------                ------------
6585    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
6586    ...                          ...
6587    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
6588
6589    load_got_offset emits the first instruction and add_got_offset
6590    emits the second for a 16-bit offset or add_got_offset_hilo emits
6591    a sequence to add a 32-bit offset using a scratch register.  */
6592
6593 static void
6594 load_got_offset (int dest, expressionS *local)
6595 {
6596   expressionS global;
6597
6598   global = *local;
6599   global.X_add_number = 0;
6600
6601   relax_start (local->X_add_symbol);
6602   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6603                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6604   relax_switch ();
6605   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
6606                BFD_RELOC_MIPS_GOT16, mips_gp_register);
6607   relax_end ();
6608 }
6609
6610 static void
6611 add_got_offset (int dest, expressionS *local)
6612 {
6613   expressionS global;
6614
6615   global.X_op = O_constant;
6616   global.X_op_symbol = NULL;
6617   global.X_add_symbol = NULL;
6618   global.X_add_number = local->X_add_number;
6619
6620   relax_start (local->X_add_symbol);
6621   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
6622                dest, dest, BFD_RELOC_LO16);
6623   relax_switch ();
6624   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
6625   relax_end ();
6626 }
6627
6628 static void
6629 add_got_offset_hilo (int dest, expressionS *local, int tmp)
6630 {
6631   expressionS global;
6632   int hold_mips_optimize;
6633
6634   global.X_op = O_constant;
6635   global.X_op_symbol = NULL;
6636   global.X_add_symbol = NULL;
6637   global.X_add_number = local->X_add_number;
6638
6639   relax_start (local->X_add_symbol);
6640   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
6641   relax_switch ();
6642   /* Set mips_optimize around the lui instruction to avoid
6643      inserting an unnecessary nop after the lw.  */
6644   hold_mips_optimize = mips_optimize;
6645   mips_optimize = 2;
6646   macro_build_lui (&global, tmp);
6647   mips_optimize = hold_mips_optimize;
6648   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
6649   relax_end ();
6650
6651   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
6652 }
6653
6654 /* Emit a sequence of instructions to emulate a branch likely operation.
6655    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
6656    is its complementing branch with the original condition negated.
6657    CALL is set if the original branch specified the link operation.
6658    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
6659
6660    Code like this is produced in the noreorder mode:
6661
6662         BRNEG   <args>, 1f
6663          nop
6664         b       <sym>
6665          delay slot (executed only if branch taken)
6666     1:
6667
6668    or, if CALL is set:
6669
6670         BRNEG   <args>, 1f
6671          nop
6672         bal     <sym>
6673          delay slot (executed only if branch taken)
6674     1:
6675
6676    In the reorder mode the delay slot would be filled with a nop anyway,
6677    so code produced is simply:
6678
6679         BR      <args>, <sym>
6680          nop
6681
6682    This function is used when producing code for the microMIPS ASE that
6683    does not implement branch likely instructions in hardware.  */
6684
6685 static void
6686 macro_build_branch_likely (const char *br, const char *brneg,
6687                            int call, expressionS *ep, const char *fmt,
6688                            unsigned int sreg, unsigned int treg)
6689 {
6690   int noreorder = mips_opts.noreorder;
6691   expressionS expr1;
6692
6693   gas_assert (mips_opts.micromips);
6694   start_noreorder ();
6695   if (noreorder)
6696     {
6697       micromips_label_expr (&expr1);
6698       macro_build (&expr1, brneg, fmt, sreg, treg);
6699       macro_build (NULL, "nop", "");
6700       macro_build (ep, call ? "bal" : "b", "p");
6701
6702       /* Set to true so that append_insn adds a label.  */
6703       emit_branch_likely_macro = TRUE;
6704     }
6705   else
6706     {
6707       macro_build (ep, br, fmt, sreg, treg);
6708       macro_build (NULL, "nop", "");
6709     }
6710   end_noreorder ();
6711 }
6712
6713 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
6714    the condition code tested.  EP specifies the branch target.  */
6715
6716 static void
6717 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
6718 {
6719   const int call = 0;
6720   const char *brneg;
6721   const char *br;
6722
6723   switch (type)
6724     {
6725     case M_BC1FL:
6726       br = "bc1f";
6727       brneg = "bc1t";
6728       break;
6729     case M_BC1TL:
6730       br = "bc1t";
6731       brneg = "bc1f";
6732       break;
6733     case M_BC2FL:
6734       br = "bc2f";
6735       brneg = "bc2t";
6736       break;
6737     case M_BC2TL:
6738       br = "bc2t";
6739       brneg = "bc2f";
6740       break;
6741     default:
6742       abort ();
6743     }
6744   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
6745 }
6746
6747 /* Emit a two-argument branch macro specified by TYPE, using SREG as
6748    the register tested.  EP specifies the branch target.  */
6749
6750 static void
6751 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
6752 {
6753   const char *brneg = NULL;
6754   const char *br;
6755   int call = 0;
6756
6757   switch (type)
6758     {
6759     case M_BGEZ:
6760       br = "bgez";
6761       break;
6762     case M_BGEZL:
6763       br = mips_opts.micromips ? "bgez" : "bgezl";
6764       brneg = "bltz";
6765       break;
6766     case M_BGEZALL:
6767       gas_assert (mips_opts.micromips);
6768       br = mips_opts.insn32 ? "bgezal" : "bgezals";
6769       brneg = "bltz";
6770       call = 1;
6771       break;
6772     case M_BGTZ:
6773       br = "bgtz";
6774       break;
6775     case M_BGTZL:
6776       br = mips_opts.micromips ? "bgtz" : "bgtzl";
6777       brneg = "blez";
6778       break;
6779     case M_BLEZ:
6780       br = "blez";
6781       break;
6782     case M_BLEZL:
6783       br = mips_opts.micromips ? "blez" : "blezl";
6784       brneg = "bgtz";
6785       break;
6786     case M_BLTZ:
6787       br = "bltz";
6788       break;
6789     case M_BLTZL:
6790       br = mips_opts.micromips ? "bltz" : "bltzl";
6791       brneg = "bgez";
6792       break;
6793     case M_BLTZALL:
6794       gas_assert (mips_opts.micromips);
6795       br = mips_opts.insn32 ? "bltzal" : "bltzals";
6796       brneg = "bgez";
6797       call = 1;
6798       break;
6799     default:
6800       abort ();
6801     }
6802   if (mips_opts.micromips && brneg)
6803     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
6804   else
6805     macro_build (ep, br, "s,p", sreg);
6806 }
6807
6808 /* Emit a three-argument branch macro specified by TYPE, using SREG and
6809    TREG as the registers tested.  EP specifies the branch target.  */
6810
6811 static void
6812 macro_build_branch_rsrt (int type, expressionS *ep,
6813                          unsigned int sreg, unsigned int treg)
6814 {
6815   const char *brneg = NULL;
6816   const int call = 0;
6817   const char *br;
6818
6819   switch (type)
6820     {
6821     case M_BEQ:
6822     case M_BEQ_I:
6823       br = "beq";
6824       break;
6825     case M_BEQL:
6826     case M_BEQL_I:
6827       br = mips_opts.micromips ? "beq" : "beql";
6828       brneg = "bne";
6829       break;
6830     case M_BNE:
6831     case M_BNE_I:
6832       br = "bne";
6833       break;
6834     case M_BNEL:
6835     case M_BNEL_I:
6836       br = mips_opts.micromips ? "bne" : "bnel";
6837       brneg = "beq";
6838       break;
6839     default:
6840       abort ();
6841     }
6842   if (mips_opts.micromips && brneg)
6843     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
6844   else
6845     macro_build (ep, br, "s,t,p", sreg, treg);
6846 }
6847
6848 /* Return the high part that should be loaded in order to make the low
6849    part of VALUE accessible using an offset of OFFBITS bits.  */
6850
6851 static offsetT
6852 offset_high_part (offsetT value, unsigned int offbits)
6853 {
6854   offsetT bias;
6855   addressT low_mask;
6856
6857   if (offbits == 0)
6858     return value;
6859   bias = 1 << (offbits - 1);
6860   low_mask = bias * 2 - 1;
6861   return (value + bias) & ~low_mask;
6862 }
6863
6864 /* Return true if the value stored in offset_expr and offset_reloc
6865    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
6866    amount that the caller wants to add without inducing overflow
6867    and ALIGN is the known alignment of the value in bytes.  */
6868
6869 static bfd_boolean
6870 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
6871 {
6872   if (offbits == 16)
6873     {
6874       /* Accept any relocation operator if overflow isn't a concern.  */
6875       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
6876         return TRUE;
6877
6878       /* These relocations are guaranteed not to overflow in correct links.  */
6879       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
6880           || gprel16_reloc_p (*offset_reloc))
6881         return TRUE;
6882     }
6883   if (offset_expr.X_op == O_constant
6884       && offset_high_part (offset_expr.X_add_number, offbits) == 0
6885       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
6886     return TRUE;
6887   return FALSE;
6888 }
6889
6890 /*
6891  *                      Build macros
6892  *   This routine implements the seemingly endless macro or synthesized
6893  * instructions and addressing modes in the mips assembly language. Many
6894  * of these macros are simple and are similar to each other. These could
6895  * probably be handled by some kind of table or grammar approach instead of
6896  * this verbose method. Others are not simple macros but are more like
6897  * optimizing code generation.
6898  *   One interesting optimization is when several store macros appear
6899  * consecutively that would load AT with the upper half of the same address.
6900  * The ensuing load upper instructions are ommited. This implies some kind
6901  * of global optimization. We currently only optimize within a single macro.
6902  *   For many of the load and store macros if the address is specified as a
6903  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
6904  * first load register 'at' with zero and use it as the base register. The
6905  * mips assembler simply uses register $zero. Just one tiny optimization
6906  * we're missing.
6907  */
6908 static void
6909 macro (struct mips_cl_insn *ip, char *str)
6910 {
6911   unsigned int treg, sreg, dreg, breg;
6912   unsigned int tempreg;
6913   int mask;
6914   int used_at = 0;
6915   expressionS label_expr;
6916   expressionS expr1;
6917   expressionS *ep;
6918   const char *s;
6919   const char *s2;
6920   const char *fmt;
6921   int likely = 0;
6922   int coproc = 0;
6923   int offbits = 16;
6924   int call = 0;
6925   int jals = 0;
6926   int dbl = 0;
6927   int imm = 0;
6928   int ust = 0;
6929   int lp = 0;
6930   bfd_boolean large_offset;
6931   int off;
6932   int hold_mips_optimize;
6933   unsigned int align;
6934
6935   gas_assert (! mips_opts.mips16);
6936
6937   treg = EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
6938   dreg = EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
6939   sreg = breg = EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
6940   mask = ip->insn_mo->mask;
6941
6942   label_expr.X_op = O_constant;
6943   label_expr.X_op_symbol = NULL;
6944   label_expr.X_add_symbol = NULL;
6945   label_expr.X_add_number = 0;
6946
6947   expr1.X_op = O_constant;
6948   expr1.X_op_symbol = NULL;
6949   expr1.X_add_symbol = NULL;
6950   expr1.X_add_number = 1;
6951   align = 1;
6952
6953   switch (mask)
6954     {
6955     case M_DABS:
6956       dbl = 1;
6957     case M_ABS:
6958       /*    bgez    $a0,1f
6959             move    v0,$a0
6960             sub     v0,$zero,$a0
6961          1:
6962        */
6963
6964       start_noreorder ();
6965
6966       if (mips_opts.micromips)
6967         micromips_label_expr (&label_expr);
6968       else
6969         label_expr.X_add_number = 8;
6970       macro_build (&label_expr, "bgez", "s,p", sreg);
6971       if (dreg == sreg)
6972         macro_build (NULL, "nop", "");
6973       else
6974         move_register (dreg, sreg);
6975       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", dreg, 0, sreg);
6976       if (mips_opts.micromips)
6977         micromips_add_label ();
6978
6979       end_noreorder ();
6980       break;
6981
6982     case M_ADD_I:
6983       s = "addi";
6984       s2 = "add";
6985       goto do_addi;
6986     case M_ADDU_I:
6987       s = "addiu";
6988       s2 = "addu";
6989       goto do_addi;
6990     case M_DADD_I:
6991       dbl = 1;
6992       s = "daddi";
6993       s2 = "dadd";
6994       if (!mips_opts.micromips)
6995         goto do_addi;
6996       if (imm_expr.X_op == O_constant
6997           && imm_expr.X_add_number >= -0x200
6998           && imm_expr.X_add_number < 0x200)
6999         {
7000           macro_build (NULL, s, "t,r,.", treg, sreg, imm_expr.X_add_number);
7001           break;
7002         }
7003       goto do_addi_i;
7004     case M_DADDU_I:
7005       dbl = 1;
7006       s = "daddiu";
7007       s2 = "daddu";
7008     do_addi:
7009       if (imm_expr.X_op == O_constant
7010           && imm_expr.X_add_number >= -0x8000
7011           && imm_expr.X_add_number < 0x8000)
7012         {
7013           macro_build (&imm_expr, s, "t,r,j", treg, sreg, BFD_RELOC_LO16);
7014           break;
7015         }
7016     do_addi_i:
7017       used_at = 1;
7018       load_register (AT, &imm_expr, dbl);
7019       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7020       break;
7021
7022     case M_AND_I:
7023       s = "andi";
7024       s2 = "and";
7025       goto do_bit;
7026     case M_OR_I:
7027       s = "ori";
7028       s2 = "or";
7029       goto do_bit;
7030     case M_NOR_I:
7031       s = "";
7032       s2 = "nor";
7033       goto do_bit;
7034     case M_XOR_I:
7035       s = "xori";
7036       s2 = "xor";
7037     do_bit:
7038       if (imm_expr.X_op == O_constant
7039           && imm_expr.X_add_number >= 0
7040           && imm_expr.X_add_number < 0x10000)
7041         {
7042           if (mask != M_NOR_I)
7043             macro_build (&imm_expr, s, "t,r,i", treg, sreg, BFD_RELOC_LO16);
7044           else
7045             {
7046               macro_build (&imm_expr, "ori", "t,r,i",
7047                            treg, sreg, BFD_RELOC_LO16);
7048               macro_build (NULL, "nor", "d,v,t", treg, treg, 0);
7049             }
7050           break;
7051         }
7052
7053       used_at = 1;
7054       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
7055       macro_build (NULL, s2, "d,v,t", treg, sreg, AT);
7056       break;
7057
7058     case M_BALIGN:
7059       switch (imm_expr.X_add_number)
7060         {
7061         case 0:
7062           macro_build (NULL, "nop", "");
7063           break;
7064         case 2:
7065           macro_build (NULL, "packrl.ph", "d,s,t", treg, treg, sreg);
7066           break;
7067         case 1:
7068         case 3:
7069           macro_build (NULL, "balign", "t,s,2", treg, sreg,
7070                        (int) imm_expr.X_add_number);
7071           break;
7072         default:
7073           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
7074                   (unsigned long) imm_expr.X_add_number);
7075           break;
7076         }
7077       break;
7078
7079     case M_BC1FL:
7080     case M_BC1TL:
7081     case M_BC2FL:
7082     case M_BC2TL:
7083       gas_assert (mips_opts.micromips);
7084       macro_build_branch_ccl (mask, &offset_expr,
7085                               EXTRACT_OPERAND (1, BCC, *ip));
7086       break;
7087
7088     case M_BEQ_I:
7089     case M_BEQL_I:
7090     case M_BNE_I:
7091     case M_BNEL_I:
7092       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7093         treg = 0;
7094       else
7095         {
7096           treg = AT;
7097           used_at = 1;
7098           load_register (treg, &imm_expr, HAVE_64BIT_GPRS);
7099         }
7100       /* Fall through.  */
7101     case M_BEQL:
7102     case M_BNEL:
7103       macro_build_branch_rsrt (mask, &offset_expr, sreg, treg);
7104       break;
7105
7106     case M_BGEL:
7107       likely = 1;
7108     case M_BGE:
7109       if (treg == 0)
7110         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, sreg);
7111       else if (sreg == 0)
7112         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, treg);
7113       else
7114         {
7115           used_at = 1;
7116           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7117           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7118                                    &offset_expr, AT, ZERO);
7119         }
7120       break;
7121
7122     case M_BGEZL:
7123     case M_BGEZALL:
7124     case M_BGTZL:
7125     case M_BLEZL:
7126     case M_BLTZL:
7127     case M_BLTZALL:
7128       macro_build_branch_rs (mask, &offset_expr, sreg);
7129       break;
7130
7131     case M_BGTL_I:
7132       likely = 1;
7133     case M_BGT_I:
7134       /* Check for > max integer.  */
7135       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7136         {
7137         do_false:
7138           /* Result is always false.  */
7139           if (! likely)
7140             macro_build (NULL, "nop", "");
7141           else
7142             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
7143           break;
7144         }
7145       if (imm_expr.X_op != O_constant)
7146         as_bad (_("Unsupported large constant"));
7147       ++imm_expr.X_add_number;
7148       /* FALLTHROUGH */
7149     case M_BGE_I:
7150     case M_BGEL_I:
7151       if (mask == M_BGEL_I)
7152         likely = 1;
7153       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7154         {
7155           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
7156                                  &offset_expr, sreg);
7157           break;
7158         }
7159       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7160         {
7161           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
7162                                  &offset_expr, sreg);
7163           break;
7164         }
7165       if (imm_expr.X_op == O_constant && imm_expr.X_add_number <= GPR_SMIN)
7166         {
7167         do_true:
7168           /* result is always true */
7169           as_warn (_("Branch %s is always true"), ip->insn_mo->name);
7170           macro_build (&offset_expr, "b", "p");
7171           break;
7172         }
7173       used_at = 1;
7174       set_at (sreg, 0);
7175       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7176                                &offset_expr, AT, ZERO);
7177       break;
7178
7179     case M_BGEUL:
7180       likely = 1;
7181     case M_BGEU:
7182       if (treg == 0)
7183         goto do_true;
7184       else if (sreg == 0)
7185         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7186                                  &offset_expr, ZERO, treg);
7187       else
7188         {
7189           used_at = 1;
7190           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7191           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7192                                    &offset_expr, AT, ZERO);
7193         }
7194       break;
7195
7196     case M_BGTUL_I:
7197       likely = 1;
7198     case M_BGTU_I:
7199       if (sreg == 0
7200           || (HAVE_32BIT_GPRS
7201               && imm_expr.X_op == O_constant
7202               && imm_expr.X_add_number == -1))
7203         goto do_false;
7204       if (imm_expr.X_op != O_constant)
7205         as_bad (_("Unsupported large constant"));
7206       ++imm_expr.X_add_number;
7207       /* FALLTHROUGH */
7208     case M_BGEU_I:
7209     case M_BGEUL_I:
7210       if (mask == M_BGEUL_I)
7211         likely = 1;
7212       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7213         goto do_true;
7214       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7215         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7216                                  &offset_expr, sreg, ZERO);
7217       else
7218         {
7219           used_at = 1;
7220           set_at (sreg, 1);
7221           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7222                                    &offset_expr, AT, ZERO);
7223         }
7224       break;
7225
7226     case M_BGTL:
7227       likely = 1;
7228     case M_BGT:
7229       if (treg == 0)
7230         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, sreg);
7231       else if (sreg == 0)
7232         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, treg);
7233       else
7234         {
7235           used_at = 1;
7236           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7237           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7238                                    &offset_expr, AT, ZERO);
7239         }
7240       break;
7241
7242     case M_BGTUL:
7243       likely = 1;
7244     case M_BGTU:
7245       if (treg == 0)
7246         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7247                                  &offset_expr, sreg, ZERO);
7248       else if (sreg == 0)
7249         goto do_false;
7250       else
7251         {
7252           used_at = 1;
7253           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7254           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7255                                    &offset_expr, AT, ZERO);
7256         }
7257       break;
7258
7259     case M_BLEL:
7260       likely = 1;
7261     case M_BLE:
7262       if (treg == 0)
7263         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7264       else if (sreg == 0)
7265         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, treg);
7266       else
7267         {
7268           used_at = 1;
7269           macro_build (NULL, "slt", "d,v,t", AT, treg, sreg);
7270           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7271                                    &offset_expr, AT, ZERO);
7272         }
7273       break;
7274
7275     case M_BLEL_I:
7276       likely = 1;
7277     case M_BLE_I:
7278       if (imm_expr.X_op == O_constant && imm_expr.X_add_number >= GPR_SMAX)
7279         goto do_true;
7280       if (imm_expr.X_op != O_constant)
7281         as_bad (_("Unsupported large constant"));
7282       ++imm_expr.X_add_number;
7283       /* FALLTHROUGH */
7284     case M_BLT_I:
7285     case M_BLTL_I:
7286       if (mask == M_BLTL_I)
7287         likely = 1;
7288       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7289         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7290       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7291         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, sreg);
7292       else
7293         {
7294           used_at = 1;
7295           set_at (sreg, 0);
7296           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7297                                    &offset_expr, AT, ZERO);
7298         }
7299       break;
7300
7301     case M_BLEUL:
7302       likely = 1;
7303     case M_BLEU:
7304       if (treg == 0)
7305         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7306                                  &offset_expr, sreg, ZERO);
7307       else if (sreg == 0)
7308         goto do_true;
7309       else
7310         {
7311           used_at = 1;
7312           macro_build (NULL, "sltu", "d,v,t", AT, treg, sreg);
7313           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7314                                    &offset_expr, AT, ZERO);
7315         }
7316       break;
7317
7318     case M_BLEUL_I:
7319       likely = 1;
7320     case M_BLEU_I:
7321       if (sreg == 0
7322           || (HAVE_32BIT_GPRS
7323               && imm_expr.X_op == O_constant
7324               && imm_expr.X_add_number == -1))
7325         goto do_true;
7326       if (imm_expr.X_op != O_constant)
7327         as_bad (_("Unsupported large constant"));
7328       ++imm_expr.X_add_number;
7329       /* FALLTHROUGH */
7330     case M_BLTU_I:
7331     case M_BLTUL_I:
7332       if (mask == M_BLTUL_I)
7333         likely = 1;
7334       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7335         goto do_false;
7336       else if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7337         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
7338                                  &offset_expr, sreg, ZERO);
7339       else
7340         {
7341           used_at = 1;
7342           set_at (sreg, 1);
7343           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7344                                    &offset_expr, AT, ZERO);
7345         }
7346       break;
7347
7348     case M_BLTL:
7349       likely = 1;
7350     case M_BLT:
7351       if (treg == 0)
7352         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, sreg);
7353       else if (sreg == 0)
7354         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, treg);
7355       else
7356         {
7357           used_at = 1;
7358           macro_build (NULL, "slt", "d,v,t", AT, sreg, treg);
7359           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7360                                    &offset_expr, AT, ZERO);
7361         }
7362       break;
7363
7364     case M_BLTUL:
7365       likely = 1;
7366     case M_BLTU:
7367       if (treg == 0)
7368         goto do_false;
7369       else if (sreg == 0)
7370         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7371                                  &offset_expr, ZERO, treg);
7372       else
7373         {
7374           used_at = 1;
7375           macro_build (NULL, "sltu", "d,v,t", AT, sreg, treg);
7376           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
7377                                    &offset_expr, AT, ZERO);
7378         }
7379       break;
7380
7381     case M_DEXT:
7382       {
7383         /* Use unsigned arithmetic.  */
7384         addressT pos;
7385         addressT size;
7386
7387         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7388           {
7389             as_bad (_("Unsupported large constant"));
7390             pos = size = 1;
7391           }
7392         else
7393           {
7394             pos = imm_expr.X_add_number;
7395             size = imm2_expr.X_add_number;
7396           }
7397
7398         if (pos > 63)
7399           {
7400             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7401             pos = 1;
7402           }
7403         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7404           {
7405             as_bad (_("Improper extract size (%lu, position %lu)"),
7406                     (unsigned long) size, (unsigned long) pos);
7407             size = 1;
7408           }
7409
7410         if (size <= 32 && pos < 32)
7411           {
7412             s = "dext";
7413             fmt = "t,r,+A,+C";
7414           }
7415         else if (size <= 32)
7416           {
7417             s = "dextu";
7418             fmt = "t,r,+E,+H";
7419           }
7420         else
7421           {
7422             s = "dextm";
7423             fmt = "t,r,+A,+G";
7424           }
7425         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7426                      (int) (size - 1));
7427       }
7428       break;
7429
7430     case M_DINS:
7431       {
7432         /* Use unsigned arithmetic.  */
7433         addressT pos;
7434         addressT size;
7435
7436         if (imm_expr.X_op != O_constant || imm2_expr.X_op != O_constant)
7437           {
7438             as_bad (_("Unsupported large constant"));
7439             pos = size = 1;
7440           }
7441         else
7442           {
7443             pos = imm_expr.X_add_number;
7444             size = imm2_expr.X_add_number;
7445           }
7446
7447         if (pos > 63)
7448           {
7449             as_bad (_("Improper position (%lu)"), (unsigned long) pos);
7450             pos = 1;
7451           }
7452         if (size == 0 || size > 64 || (pos + size - 1) > 63)
7453           {
7454             as_bad (_("Improper insert size (%lu, position %lu)"),
7455                     (unsigned long) size, (unsigned long) pos);
7456             size = 1;
7457           }
7458
7459         if (pos < 32 && (pos + size - 1) < 32)
7460           {
7461             s = "dins";
7462             fmt = "t,r,+A,+B";
7463           }
7464         else if (pos >= 32)
7465           {
7466             s = "dinsu";
7467             fmt = "t,r,+E,+F";
7468           }
7469         else
7470           {
7471             s = "dinsm";
7472             fmt = "t,r,+A,+F";
7473           }
7474         macro_build ((expressionS *) NULL, s, fmt, treg, sreg, (int) pos,
7475                      (int) (pos + size - 1));
7476       }
7477       break;
7478
7479     case M_DDIV_3:
7480       dbl = 1;
7481     case M_DIV_3:
7482       s = "mflo";
7483       goto do_div3;
7484     case M_DREM_3:
7485       dbl = 1;
7486     case M_REM_3:
7487       s = "mfhi";
7488     do_div3:
7489       if (treg == 0)
7490         {
7491           as_warn (_("Divide by zero."));
7492           if (mips_trap)
7493             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7494           else
7495             macro_build (NULL, "break", BRK_FMT, 7);
7496           break;
7497         }
7498
7499       start_noreorder ();
7500       if (mips_trap)
7501         {
7502           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7503           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7504         }
7505       else
7506         {
7507           if (mips_opts.micromips)
7508             micromips_label_expr (&label_expr);
7509           else
7510             label_expr.X_add_number = 8;
7511           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7512           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", sreg, treg);
7513           macro_build (NULL, "break", BRK_FMT, 7);
7514           if (mips_opts.micromips)
7515             micromips_add_label ();
7516         }
7517       expr1.X_add_number = -1;
7518       used_at = 1;
7519       load_register (AT, &expr1, dbl);
7520       if (mips_opts.micromips)
7521         micromips_label_expr (&label_expr);
7522       else
7523         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
7524       macro_build (&label_expr, "bne", "s,t,p", treg, AT);
7525       if (dbl)
7526         {
7527           expr1.X_add_number = 1;
7528           load_register (AT, &expr1, dbl);
7529           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
7530         }
7531       else
7532         {
7533           expr1.X_add_number = 0x80000000;
7534           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
7535         }
7536       if (mips_trap)
7537         {
7538           macro_build (NULL, "teq", TRAP_FMT, sreg, AT, 6);
7539           /* We want to close the noreorder block as soon as possible, so
7540              that later insns are available for delay slot filling.  */
7541           end_noreorder ();
7542         }
7543       else
7544         {
7545           if (mips_opts.micromips)
7546             micromips_label_expr (&label_expr);
7547           else
7548             label_expr.X_add_number = 8;
7549           macro_build (&label_expr, "bne", "s,t,p", sreg, AT);
7550           macro_build (NULL, "nop", "");
7551
7552           /* We want to close the noreorder block as soon as possible, so
7553              that later insns are available for delay slot filling.  */
7554           end_noreorder ();
7555
7556           macro_build (NULL, "break", BRK_FMT, 6);
7557         }
7558       if (mips_opts.micromips)
7559         micromips_add_label ();
7560       macro_build (NULL, s, MFHL_FMT, dreg);
7561       break;
7562
7563     case M_DIV_3I:
7564       s = "div";
7565       s2 = "mflo";
7566       goto do_divi;
7567     case M_DIVU_3I:
7568       s = "divu";
7569       s2 = "mflo";
7570       goto do_divi;
7571     case M_REM_3I:
7572       s = "div";
7573       s2 = "mfhi";
7574       goto do_divi;
7575     case M_REMU_3I:
7576       s = "divu";
7577       s2 = "mfhi";
7578       goto do_divi;
7579     case M_DDIV_3I:
7580       dbl = 1;
7581       s = "ddiv";
7582       s2 = "mflo";
7583       goto do_divi;
7584     case M_DDIVU_3I:
7585       dbl = 1;
7586       s = "ddivu";
7587       s2 = "mflo";
7588       goto do_divi;
7589     case M_DREM_3I:
7590       dbl = 1;
7591       s = "ddiv";
7592       s2 = "mfhi";
7593       goto do_divi;
7594     case M_DREMU_3I:
7595       dbl = 1;
7596       s = "ddivu";
7597       s2 = "mfhi";
7598     do_divi:
7599       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
7600         {
7601           as_warn (_("Divide by zero."));
7602           if (mips_trap)
7603             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
7604           else
7605             macro_build (NULL, "break", BRK_FMT, 7);
7606           break;
7607         }
7608       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 1)
7609         {
7610           if (strcmp (s2, "mflo") == 0)
7611             move_register (dreg, sreg);
7612           else
7613             move_register (dreg, ZERO);
7614           break;
7615         }
7616       if (imm_expr.X_op == O_constant
7617           && imm_expr.X_add_number == -1
7618           && s[strlen (s) - 1] != 'u')
7619         {
7620           if (strcmp (s2, "mflo") == 0)
7621             {
7622               macro_build (NULL, dbl ? "dneg" : "neg", "d,w", dreg, sreg);
7623             }
7624           else
7625             move_register (dreg, ZERO);
7626           break;
7627         }
7628
7629       used_at = 1;
7630       load_register (AT, &imm_expr, dbl);
7631       macro_build (NULL, s, "z,s,t", sreg, AT);
7632       macro_build (NULL, s2, MFHL_FMT, dreg);
7633       break;
7634
7635     case M_DIVU_3:
7636       s = "divu";
7637       s2 = "mflo";
7638       goto do_divu3;
7639     case M_REMU_3:
7640       s = "divu";
7641       s2 = "mfhi";
7642       goto do_divu3;
7643     case M_DDIVU_3:
7644       s = "ddivu";
7645       s2 = "mflo";
7646       goto do_divu3;
7647     case M_DREMU_3:
7648       s = "ddivu";
7649       s2 = "mfhi";
7650     do_divu3:
7651       start_noreorder ();
7652       if (mips_trap)
7653         {
7654           macro_build (NULL, "teq", TRAP_FMT, treg, ZERO, 7);
7655           macro_build (NULL, s, "z,s,t", sreg, treg);
7656           /* We want to close the noreorder block as soon as possible, so
7657              that later insns are available for delay slot filling.  */
7658           end_noreorder ();
7659         }
7660       else
7661         {
7662           if (mips_opts.micromips)
7663             micromips_label_expr (&label_expr);
7664           else
7665             label_expr.X_add_number = 8;
7666           macro_build (&label_expr, "bne", "s,t,p", treg, ZERO);
7667           macro_build (NULL, s, "z,s,t", sreg, treg);
7668
7669           /* We want to close the noreorder block as soon as possible, so
7670              that later insns are available for delay slot filling.  */
7671           end_noreorder ();
7672           macro_build (NULL, "break", BRK_FMT, 7);
7673           if (mips_opts.micromips)
7674             micromips_add_label ();
7675         }
7676       macro_build (NULL, s2, MFHL_FMT, dreg);
7677       break;
7678
7679     case M_DLCA_AB:
7680       dbl = 1;
7681     case M_LCA_AB:
7682       call = 1;
7683       goto do_la;
7684     case M_DLA_AB:
7685       dbl = 1;
7686     case M_LA_AB:
7687     do_la:
7688       /* Load the address of a symbol into a register.  If breg is not
7689          zero, we then add a base register to it.  */
7690
7691       if (dbl && HAVE_32BIT_GPRS)
7692         as_warn (_("dla used to load 32-bit register"));
7693
7694       if (!dbl && HAVE_64BIT_OBJECTS)
7695         as_warn (_("la used to load 64-bit address"));
7696
7697       if (small_offset_p (0, align, 16))
7698         {
7699           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", treg, breg,
7700                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
7701           break;
7702         }
7703
7704       if (mips_opts.at && (treg == breg))
7705         {
7706           tempreg = AT;
7707           used_at = 1;
7708         }
7709       else
7710         {
7711           tempreg = treg;
7712         }
7713
7714       if (offset_expr.X_op != O_symbol
7715           && offset_expr.X_op != O_constant)
7716         {
7717           as_bad (_("Expression too complex"));
7718           offset_expr.X_op = O_constant;
7719         }
7720
7721       if (offset_expr.X_op == O_constant)
7722         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
7723       else if (mips_pic == NO_PIC)
7724         {
7725           /* If this is a reference to a GP relative symbol, we want
7726                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
7727              Otherwise we want
7728                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
7729                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7730              If we have a constant, we need two instructions anyhow,
7731              so we may as well always use the latter form.
7732
7733              With 64bit address space and a usable $at we want
7734                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7735                lui      $at,<sym>               (BFD_RELOC_HI16_S)
7736                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7737                daddiu   $at,<sym>               (BFD_RELOC_LO16)
7738                dsll32   $tempreg,0
7739                daddu    $tempreg,$tempreg,$at
7740
7741              If $at is already in use, we use a path which is suboptimal
7742              on superscalar processors.
7743                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
7744                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
7745                dsll     $tempreg,16
7746                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
7747                dsll     $tempreg,16
7748                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
7749
7750              For GP relative symbols in 64bit address space we can use
7751              the same sequence as in 32bit address space.  */
7752           if (HAVE_64BIT_SYMBOLS)
7753             {
7754               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7755                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7756                 {
7757                   relax_start (offset_expr.X_add_symbol);
7758                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7759                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7760                   relax_switch ();
7761                 }
7762
7763               if (used_at == 0 && mips_opts.at)
7764                 {
7765                   macro_build (&offset_expr, "lui", LUI_FMT,
7766                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7767                   macro_build (&offset_expr, "lui", LUI_FMT,
7768                                AT, BFD_RELOC_HI16_S);
7769                   macro_build (&offset_expr, "daddiu", "t,r,j",
7770                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7771                   macro_build (&offset_expr, "daddiu", "t,r,j",
7772                                AT, AT, BFD_RELOC_LO16);
7773                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
7774                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
7775                   used_at = 1;
7776                 }
7777               else
7778                 {
7779                   macro_build (&offset_expr, "lui", LUI_FMT,
7780                                tempreg, BFD_RELOC_MIPS_HIGHEST);
7781                   macro_build (&offset_expr, "daddiu", "t,r,j",
7782                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
7783                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7784                   macro_build (&offset_expr, "daddiu", "t,r,j",
7785                                tempreg, tempreg, BFD_RELOC_HI16_S);
7786                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
7787                   macro_build (&offset_expr, "daddiu", "t,r,j",
7788                                tempreg, tempreg, BFD_RELOC_LO16);
7789                 }
7790
7791               if (mips_relax.sequence)
7792                 relax_end ();
7793             }
7794           else
7795             {
7796               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
7797                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
7798                 {
7799                   relax_start (offset_expr.X_add_symbol);
7800                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7801                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
7802                   relax_switch ();
7803                 }
7804               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
7805                 as_bad (_("Offset too large"));
7806               macro_build_lui (&offset_expr, tempreg);
7807               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7808                            tempreg, tempreg, BFD_RELOC_LO16);
7809               if (mips_relax.sequence)
7810                 relax_end ();
7811             }
7812         }
7813       else if (!mips_big_got && !HAVE_NEWABI)
7814         {
7815           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
7816
7817           /* If this is a reference to an external symbol, and there
7818              is no constant, we want
7819                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7820              or for lca or if tempreg is PIC_CALL_REG
7821                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7822              For a local symbol, we want
7823                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7824                nop
7825                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
7826
7827              If we have a small constant, and this is a reference to
7828              an external symbol, we want
7829                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7830                nop
7831                addiu    $tempreg,$tempreg,<constant>
7832              For a local symbol, we want the same instruction
7833              sequence, but we output a BFD_RELOC_LO16 reloc on the
7834              addiu instruction.
7835
7836              If we have a large constant, and this is a reference to
7837              an external symbol, we want
7838                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
7839                lui      $at,<hiconstant>
7840                addiu    $at,$at,<loconstant>
7841                addu     $tempreg,$tempreg,$at
7842              For a local symbol, we want the same instruction
7843              sequence, but we output a BFD_RELOC_LO16 reloc on the
7844              addiu instruction.
7845            */
7846
7847           if (offset_expr.X_add_number == 0)
7848             {
7849               if (mips_pic == SVR4_PIC
7850                   && breg == 0
7851                   && (call || tempreg == PIC_CALL_REG))
7852                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
7853
7854               relax_start (offset_expr.X_add_symbol);
7855               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7856                            lw_reloc_type, mips_gp_register);
7857               if (breg != 0)
7858                 {
7859                   /* We're going to put in an addu instruction using
7860                      tempreg, so we may as well insert the nop right
7861                      now.  */
7862                   load_delay_nop ();
7863                 }
7864               relax_switch ();
7865               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
7866                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
7867               load_delay_nop ();
7868               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
7869                            tempreg, tempreg, BFD_RELOC_LO16);
7870               relax_end ();
7871               /* FIXME: If breg == 0, and the next instruction uses
7872                  $tempreg, then if this variant case is used an extra
7873                  nop will be generated.  */
7874             }
7875           else if (offset_expr.X_add_number >= -0x8000
7876                    && offset_expr.X_add_number < 0x8000)
7877             {
7878               load_got_offset (tempreg, &offset_expr);
7879               load_delay_nop ();
7880               add_got_offset (tempreg, &offset_expr);
7881             }
7882           else
7883             {
7884               expr1.X_add_number = offset_expr.X_add_number;
7885               offset_expr.X_add_number =
7886                 SEXT_16BIT (offset_expr.X_add_number);
7887               load_got_offset (tempreg, &offset_expr);
7888               offset_expr.X_add_number = expr1.X_add_number;
7889               /* If we are going to add in a base register, and the
7890                  target register and the base register are the same,
7891                  then we are using AT as a temporary register.  Since
7892                  we want to load the constant into AT, we add our
7893                  current AT (from the global offset table) and the
7894                  register into the register now, and pretend we were
7895                  not using a base register.  */
7896               if (breg == treg)
7897                 {
7898                   load_delay_nop ();
7899                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7900                                treg, AT, breg);
7901                   breg = 0;
7902                   tempreg = treg;
7903                 }
7904               add_got_offset_hilo (tempreg, &offset_expr, AT);
7905               used_at = 1;
7906             }
7907         }
7908       else if (!mips_big_got && HAVE_NEWABI)
7909         {
7910           int add_breg_early = 0;
7911
7912           /* If this is a reference to an external, and there is no
7913              constant, or local symbol (*), with or without a
7914              constant, we want
7915                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7916              or for lca or if tempreg is PIC_CALL_REG
7917                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
7918
7919              If we have a small constant, and this is a reference to
7920              an external symbol, we want
7921                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7922                addiu    $tempreg,$tempreg,<constant>
7923
7924              If we have a large constant, and this is a reference to
7925              an external symbol, we want
7926                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
7927                lui      $at,<hiconstant>
7928                addiu    $at,$at,<loconstant>
7929                addu     $tempreg,$tempreg,$at
7930
7931              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
7932              local symbols, even though it introduces an additional
7933              instruction.  */
7934
7935           if (offset_expr.X_add_number)
7936             {
7937               expr1.X_add_number = offset_expr.X_add_number;
7938               offset_expr.X_add_number = 0;
7939
7940               relax_start (offset_expr.X_add_symbol);
7941               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7942                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7943
7944               if (expr1.X_add_number >= -0x8000
7945                   && expr1.X_add_number < 0x8000)
7946                 {
7947                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
7948                                tempreg, tempreg, BFD_RELOC_LO16);
7949                 }
7950               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
7951                 {
7952                   /* If we are going to add in a base register, and the
7953                      target register and the base register are the same,
7954                      then we are using AT as a temporary register.  Since
7955                      we want to load the constant into AT, we add our
7956                      current AT (from the global offset table) and the
7957                      register into the register now, and pretend we were
7958                      not using a base register.  */
7959                   if (breg != treg)
7960                     dreg = tempreg;
7961                   else
7962                     {
7963                       gas_assert (tempreg == AT);
7964                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7965                                    treg, AT, breg);
7966                       dreg = treg;
7967                       add_breg_early = 1;
7968                     }
7969
7970                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
7971                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7972                                dreg, dreg, AT);
7973
7974                   used_at = 1;
7975                 }
7976               else
7977                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
7978
7979               relax_switch ();
7980               offset_expr.X_add_number = expr1.X_add_number;
7981
7982               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7983                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
7984               if (add_breg_early)
7985                 {
7986                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
7987                                treg, tempreg, breg);
7988                   breg = 0;
7989                   tempreg = treg;
7990                 }
7991               relax_end ();
7992             }
7993           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
7994             {
7995               relax_start (offset_expr.X_add_symbol);
7996               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
7997                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
7998               relax_switch ();
7999               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8000                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8001               relax_end ();
8002             }
8003           else
8004             {
8005               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8006                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8007             }
8008         }
8009       else if (mips_big_got && !HAVE_NEWABI)
8010         {
8011           int gpdelay;
8012           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8013           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8014           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
8015
8016           /* This is the large GOT case.  If this is a reference to an
8017              external symbol, and there is no constant, we want
8018                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8019                addu     $tempreg,$tempreg,$gp
8020                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8021              or for lca or if tempreg is PIC_CALL_REG
8022                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8023                addu     $tempreg,$tempreg,$gp
8024                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8025              For a local symbol, we want
8026                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8027                nop
8028                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
8029
8030              If we have a small constant, and this is a reference to
8031              an external symbol, we want
8032                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8033                addu     $tempreg,$tempreg,$gp
8034                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8035                nop
8036                addiu    $tempreg,$tempreg,<constant>
8037              For a local symbol, we want
8038                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8039                nop
8040                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
8041
8042              If we have a large constant, and this is a reference to
8043              an external symbol, we want
8044                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8045                addu     $tempreg,$tempreg,$gp
8046                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8047                lui      $at,<hiconstant>
8048                addiu    $at,$at,<loconstant>
8049                addu     $tempreg,$tempreg,$at
8050              For a local symbol, we want
8051                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
8052                lui      $at,<hiconstant>
8053                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
8054                addu     $tempreg,$tempreg,$at
8055           */
8056
8057           expr1.X_add_number = offset_expr.X_add_number;
8058           offset_expr.X_add_number = 0;
8059           relax_start (offset_expr.X_add_symbol);
8060           gpdelay = reg_needs_delay (mips_gp_register);
8061           if (expr1.X_add_number == 0 && breg == 0
8062               && (call || tempreg == PIC_CALL_REG))
8063             {
8064               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8065               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8066             }
8067           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8068           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8069                        tempreg, tempreg, mips_gp_register);
8070           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8071                        tempreg, lw_reloc_type, tempreg);
8072           if (expr1.X_add_number == 0)
8073             {
8074               if (breg != 0)
8075                 {
8076                   /* We're going to put in an addu instruction using
8077                      tempreg, so we may as well insert the nop right
8078                      now.  */
8079                   load_delay_nop ();
8080                 }
8081             }
8082           else if (expr1.X_add_number >= -0x8000
8083                    && expr1.X_add_number < 0x8000)
8084             {
8085               load_delay_nop ();
8086               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8087                            tempreg, tempreg, BFD_RELOC_LO16);
8088             }
8089           else
8090             {
8091               /* If we are going to add in a base register, and the
8092                  target register and the base register are the same,
8093                  then we are using AT as a temporary register.  Since
8094                  we want to load the constant into AT, we add our
8095                  current AT (from the global offset table) and the
8096                  register into the register now, and pretend we were
8097                  not using a base register.  */
8098               if (breg != treg)
8099                 dreg = tempreg;
8100               else
8101                 {
8102                   gas_assert (tempreg == AT);
8103                   load_delay_nop ();
8104                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8105                                treg, AT, breg);
8106                   dreg = treg;
8107                 }
8108
8109               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8110               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8111
8112               used_at = 1;
8113             }
8114           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
8115           relax_switch ();
8116
8117           if (gpdelay)
8118             {
8119               /* This is needed because this instruction uses $gp, but
8120                  the first instruction on the main stream does not.  */
8121               macro_build (NULL, "nop", "");
8122             }
8123
8124           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8125                        local_reloc_type, mips_gp_register);
8126           if (expr1.X_add_number >= -0x8000
8127               && expr1.X_add_number < 0x8000)
8128             {
8129               load_delay_nop ();
8130               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8131                            tempreg, tempreg, BFD_RELOC_LO16);
8132               /* FIXME: If add_number is 0, and there was no base
8133                  register, the external symbol case ended with a load,
8134                  so if the symbol turns out to not be external, and
8135                  the next instruction uses tempreg, an unnecessary nop
8136                  will be inserted.  */
8137             }
8138           else
8139             {
8140               if (breg == treg)
8141                 {
8142                   /* We must add in the base register now, as in the
8143                      external symbol case.  */
8144                   gas_assert (tempreg == AT);
8145                   load_delay_nop ();
8146                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8147                                treg, AT, breg);
8148                   tempreg = treg;
8149                   /* We set breg to 0 because we have arranged to add
8150                      it in in both cases.  */
8151                   breg = 0;
8152                 }
8153
8154               macro_build_lui (&expr1, AT);
8155               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8156                            AT, AT, BFD_RELOC_LO16);
8157               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8158                            tempreg, tempreg, AT);
8159               used_at = 1;
8160             }
8161           relax_end ();
8162         }
8163       else if (mips_big_got && HAVE_NEWABI)
8164         {
8165           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
8166           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
8167           int add_breg_early = 0;
8168
8169           /* This is the large GOT case.  If this is a reference to an
8170              external symbol, and there is no constant, we want
8171                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8172                add      $tempreg,$tempreg,$gp
8173                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8174              or for lca or if tempreg is PIC_CALL_REG
8175                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
8176                add      $tempreg,$tempreg,$gp
8177                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
8178
8179              If we have a small constant, and this is a reference to
8180              an external symbol, we want
8181                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8182                add      $tempreg,$tempreg,$gp
8183                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8184                addi     $tempreg,$tempreg,<constant>
8185
8186              If we have a large constant, and this is a reference to
8187              an external symbol, we want
8188                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
8189                addu     $tempreg,$tempreg,$gp
8190                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
8191                lui      $at,<hiconstant>
8192                addi     $at,$at,<loconstant>
8193                add      $tempreg,$tempreg,$at
8194
8195              If we have NewABI, and we know it's a local symbol, we want
8196                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8197                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8198              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
8199
8200           relax_start (offset_expr.X_add_symbol);
8201
8202           expr1.X_add_number = offset_expr.X_add_number;
8203           offset_expr.X_add_number = 0;
8204
8205           if (expr1.X_add_number == 0 && breg == 0
8206               && (call || tempreg == PIC_CALL_REG))
8207             {
8208               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
8209               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
8210             }
8211           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
8212           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8213                        tempreg, tempreg, mips_gp_register);
8214           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8215                        tempreg, lw_reloc_type, tempreg);
8216
8217           if (expr1.X_add_number == 0)
8218             ;
8219           else if (expr1.X_add_number >= -0x8000
8220                    && expr1.X_add_number < 0x8000)
8221             {
8222               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
8223                            tempreg, tempreg, BFD_RELOC_LO16);
8224             }
8225           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
8226             {
8227               /* If we are going to add in a base register, and the
8228                  target register and the base register are the same,
8229                  then we are using AT as a temporary register.  Since
8230                  we want to load the constant into AT, we add our
8231                  current AT (from the global offset table) and the
8232                  register into the register now, and pretend we were
8233                  not using a base register.  */
8234               if (breg != treg)
8235                 dreg = tempreg;
8236               else
8237                 {
8238                   gas_assert (tempreg == AT);
8239                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8240                                treg, AT, breg);
8241                   dreg = treg;
8242                   add_breg_early = 1;
8243                 }
8244
8245               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
8246               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
8247
8248               used_at = 1;
8249             }
8250           else
8251             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
8252
8253           relax_switch ();
8254           offset_expr.X_add_number = expr1.X_add_number;
8255           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
8256                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8257           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
8258                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
8259           if (add_breg_early)
8260             {
8261               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8262                            treg, tempreg, breg);
8263               breg = 0;
8264               tempreg = treg;
8265             }
8266           relax_end ();
8267         }
8268       else
8269         abort ();
8270
8271       if (breg != 0)
8272         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", treg, tempreg, breg);
8273       break;
8274
8275     case M_MSGSND:
8276       gas_assert (!mips_opts.micromips);
8277       macro_build (NULL, "c2", "C", (treg << 16) | 0x01);
8278       break;
8279
8280     case M_MSGLD:
8281       gas_assert (!mips_opts.micromips);
8282       macro_build (NULL, "c2", "C", 0x02);
8283       break;
8284
8285     case M_MSGLD_T:
8286       gas_assert (!mips_opts.micromips);
8287       macro_build (NULL, "c2", "C", (treg << 16) | 0x02);
8288       break;
8289
8290     case M_MSGWAIT:
8291       gas_assert (!mips_opts.micromips);
8292       macro_build (NULL, "c2", "C", 3);
8293       break;
8294
8295     case M_MSGWAIT_T:
8296       gas_assert (!mips_opts.micromips);
8297       macro_build (NULL, "c2", "C", (treg << 16) | 0x03);
8298       break;
8299
8300     case M_J_A:
8301       /* The j instruction may not be used in PIC code, since it
8302          requires an absolute address.  We convert it to a b
8303          instruction.  */
8304       if (mips_pic == NO_PIC)
8305         macro_build (&offset_expr, "j", "a");
8306       else
8307         macro_build (&offset_expr, "b", "p");
8308       break;
8309
8310       /* The jal instructions must be handled as macros because when
8311          generating PIC code they expand to multi-instruction
8312          sequences.  Normally they are simple instructions.  */
8313     case M_JALS_1:
8314       dreg = RA;
8315       /* Fall through.  */
8316     case M_JALS_2:
8317       gas_assert (mips_opts.micromips);
8318       if (mips_opts.insn32)
8319         {
8320           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
8321           break;
8322         }
8323       jals = 1;
8324       goto jal;
8325     case M_JAL_1:
8326       dreg = RA;
8327       /* Fall through.  */
8328     case M_JAL_2:
8329     jal:
8330       if (mips_pic == NO_PIC)
8331         {
8332           s = jals ? "jalrs" : "jalr";
8333           if (mips_opts.micromips
8334               && !mips_opts.insn32
8335               && dreg == RA
8336               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8337             macro_build (NULL, s, "mj", sreg);
8338           else
8339             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8340         }
8341       else
8342         {
8343           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
8344                            && mips_cprestore_offset >= 0);
8345
8346           if (sreg != PIC_CALL_REG)
8347             as_warn (_("MIPS PIC call to register other than $25"));
8348
8349           s = ((mips_opts.micromips
8350                 && !mips_opts.insn32
8351                 && (!mips_opts.noreorder || cprestore))
8352                ? "jalrs" : "jalr");
8353           if (mips_opts.micromips
8354               && !mips_opts.insn32
8355               && dreg == RA
8356               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8357             macro_build (NULL, s, "mj", sreg);
8358           else
8359             macro_build (NULL, s, JALR_FMT, dreg, sreg);
8360           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
8361             {
8362               if (mips_cprestore_offset < 0)
8363                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8364               else
8365                 {
8366                   if (!mips_frame_reg_valid)
8367                     {
8368                       as_warn (_("No .frame pseudo-op used in PIC code"));
8369                       /* Quiet this warning.  */
8370                       mips_frame_reg_valid = 1;
8371                     }
8372                   if (!mips_cprestore_valid)
8373                     {
8374                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8375                       /* Quiet this warning.  */
8376                       mips_cprestore_valid = 1;
8377                     }
8378                   if (mips_opts.noreorder)
8379                     macro_build (NULL, "nop", "");
8380                   expr1.X_add_number = mips_cprestore_offset;
8381                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8382                                                 mips_gp_register,
8383                                                 mips_frame_reg,
8384                                                 HAVE_64BIT_ADDRESSES);
8385                 }
8386             }
8387         }
8388
8389       break;
8390
8391     case M_JALS_A:
8392       gas_assert (mips_opts.micromips);
8393       if (mips_opts.insn32)
8394         {
8395           as_bad (_("Opcode not supported in the `insn32' mode `%s'"), str);
8396           break;
8397         }
8398       jals = 1;
8399       /* Fall through.  */
8400     case M_JAL_A:
8401       if (mips_pic == NO_PIC)
8402         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
8403       else if (mips_pic == SVR4_PIC)
8404         {
8405           /* If this is a reference to an external symbol, and we are
8406              using a small GOT, we want
8407                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
8408                nop
8409                jalr     $ra,$25
8410                nop
8411                lw       $gp,cprestore($sp)
8412              The cprestore value is set using the .cprestore
8413              pseudo-op.  If we are using a big GOT, we want
8414                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
8415                addu     $25,$25,$gp
8416                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
8417                nop
8418                jalr     $ra,$25
8419                nop
8420                lw       $gp,cprestore($sp)
8421              If the symbol is not external, we want
8422                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
8423                nop
8424                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
8425                jalr     $ra,$25
8426                nop
8427                lw $gp,cprestore($sp)
8428
8429              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
8430              sequences above, minus nops, unless the symbol is local,
8431              which enables us to use GOT_PAGE/GOT_OFST (big got) or
8432              GOT_DISP.  */
8433           if (HAVE_NEWABI)
8434             {
8435               if (!mips_big_got)
8436                 {
8437                   relax_start (offset_expr.X_add_symbol);
8438                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8439                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8440                                mips_gp_register);
8441                   relax_switch ();
8442                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8443                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
8444                                mips_gp_register);
8445                   relax_end ();
8446                 }
8447               else
8448                 {
8449                   relax_start (offset_expr.X_add_symbol);
8450                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8451                                BFD_RELOC_MIPS_CALL_HI16);
8452                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8453                                PIC_CALL_REG, mips_gp_register);
8454                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8455                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8456                                PIC_CALL_REG);
8457                   relax_switch ();
8458                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8459                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
8460                                mips_gp_register);
8461                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8462                                PIC_CALL_REG, PIC_CALL_REG,
8463                                BFD_RELOC_MIPS_GOT_OFST);
8464                   relax_end ();
8465                 }
8466
8467               macro_build_jalr (&offset_expr, 0);
8468             }
8469           else
8470             {
8471               relax_start (offset_expr.X_add_symbol);
8472               if (!mips_big_got)
8473                 {
8474                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8475                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
8476                                mips_gp_register);
8477                   load_delay_nop ();
8478                   relax_switch ();
8479                 }
8480               else
8481                 {
8482                   int gpdelay;
8483
8484                   gpdelay = reg_needs_delay (mips_gp_register);
8485                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
8486                                BFD_RELOC_MIPS_CALL_HI16);
8487                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
8488                                PIC_CALL_REG, mips_gp_register);
8489                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8490                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
8491                                PIC_CALL_REG);
8492                   load_delay_nop ();
8493                   relax_switch ();
8494                   if (gpdelay)
8495                     macro_build (NULL, "nop", "");
8496                 }
8497               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
8498                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
8499                            mips_gp_register);
8500               load_delay_nop ();
8501               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8502                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
8503               relax_end ();
8504               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
8505
8506               if (mips_cprestore_offset < 0)
8507                 as_warn (_("No .cprestore pseudo-op used in PIC code"));
8508               else
8509                 {
8510                   if (!mips_frame_reg_valid)
8511                     {
8512                       as_warn (_("No .frame pseudo-op used in PIC code"));
8513                       /* Quiet this warning.  */
8514                       mips_frame_reg_valid = 1;
8515                     }
8516                   if (!mips_cprestore_valid)
8517                     {
8518                       as_warn (_("No .cprestore pseudo-op used in PIC code"));
8519                       /* Quiet this warning.  */
8520                       mips_cprestore_valid = 1;
8521                     }
8522                   if (mips_opts.noreorder)
8523                     macro_build (NULL, "nop", "");
8524                   expr1.X_add_number = mips_cprestore_offset;
8525                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
8526                                                 mips_gp_register,
8527                                                 mips_frame_reg,
8528                                                 HAVE_64BIT_ADDRESSES);
8529                 }
8530             }
8531         }
8532       else if (mips_pic == VXWORKS_PIC)
8533         as_bad (_("Non-PIC jump used in PIC library"));
8534       else
8535         abort ();
8536
8537       break;
8538
8539     case M_LBUE_AB:
8540       s = "lbue";
8541       fmt = "t,+j(b)";
8542       offbits = 9;
8543       goto ld_st;
8544     case M_LHUE_AB:
8545       s = "lhue";
8546       fmt = "t,+j(b)";
8547       offbits = 9;
8548       goto ld_st;
8549     case M_LBE_AB:
8550       s = "lbe";
8551       fmt = "t,+j(b)";
8552       offbits = 9;
8553       goto ld_st;
8554     case M_LHE_AB:
8555       s = "lhe";
8556       fmt = "t,+j(b)";
8557       offbits = 9;
8558       goto ld_st;
8559     case M_LLE_AB:
8560       s = "lle";
8561       fmt = "t,+j(b)";
8562       offbits = 9;
8563       goto ld_st;
8564     case M_LWE_AB:
8565       s = "lwe";
8566       fmt = "t,+j(b)";
8567       offbits = 9;
8568       goto ld_st;
8569     case M_LWLE_AB:
8570       s = "lwle";
8571       fmt = "t,+j(b)";
8572       offbits = 9;
8573       goto ld_st;
8574     case M_LWRE_AB:
8575       s = "lwre";
8576       fmt = "t,+j(b)";
8577       offbits = 9;
8578       goto ld_st;
8579     case M_SBE_AB:
8580       s = "sbe";
8581       fmt = "t,+j(b)";
8582       offbits = 9;
8583       goto ld_st;
8584     case M_SCE_AB:
8585       s = "sce";
8586       fmt = "t,+j(b)";
8587       offbits = 9;
8588       goto ld_st;
8589     case M_SHE_AB:
8590       s = "she";
8591       fmt = "t,+j(b)";
8592       offbits = 9;
8593       goto ld_st;
8594     case M_SWE_AB:
8595       s = "swe";
8596       fmt = "t,+j(b)";
8597       offbits = 9;
8598       goto ld_st;
8599     case M_SWLE_AB:
8600       s = "swle";
8601       fmt = "t,+j(b)";
8602       offbits = 9;
8603       goto ld_st;
8604     case M_SWRE_AB:
8605       s = "swre";
8606       fmt = "t,+j(b)";
8607       offbits = 9;
8608       goto ld_st;
8609     case M_ACLR_AB:
8610       s = "aclr";
8611       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8612       fmt = "\\,~(b)";
8613       offbits = 12;
8614       goto ld_st;
8615     case M_ASET_AB:
8616       s = "aset";
8617       treg = EXTRACT_OPERAND (mips_opts.micromips, 3BITPOS, *ip);
8618       fmt = "\\,~(b)";
8619       offbits = 12;
8620       goto ld_st;
8621     case M_LB_AB:
8622       s = "lb";
8623       fmt = "t,o(b)";
8624       goto ld;
8625     case M_LBU_AB:
8626       s = "lbu";
8627       fmt = "t,o(b)";
8628       goto ld;
8629     case M_LH_AB:
8630       s = "lh";
8631       fmt = "t,o(b)";
8632       goto ld;
8633     case M_LHU_AB:
8634       s = "lhu";
8635       fmt = "t,o(b)";
8636       goto ld;
8637     case M_LW_AB:
8638       s = "lw";
8639       fmt = "t,o(b)";
8640       goto ld;
8641     case M_LWC0_AB:
8642       gas_assert (!mips_opts.micromips);
8643       s = "lwc0";
8644       fmt = "E,o(b)";
8645       /* Itbl support may require additional care here.  */
8646       coproc = 1;
8647       goto ld_st;
8648     case M_LWC1_AB:
8649       s = "lwc1";
8650       fmt = "T,o(b)";
8651       /* Itbl support may require additional care here.  */
8652       coproc = 1;
8653       goto ld_st;
8654     case M_LWC2_AB:
8655       s = "lwc2";
8656       fmt = COP12_FMT;
8657       offbits = (mips_opts.micromips ? 12 : 16);
8658       /* Itbl support may require additional care here.  */
8659       coproc = 1;
8660       goto ld_st;
8661     case M_LWC3_AB:
8662       gas_assert (!mips_opts.micromips);
8663       s = "lwc3";
8664       fmt = "E,o(b)";
8665       /* Itbl support may require additional care here.  */
8666       coproc = 1;
8667       goto ld_st;
8668     case M_LWL_AB:
8669       s = "lwl";
8670       fmt = MEM12_FMT;
8671       offbits = (mips_opts.micromips ? 12 : 16);
8672       goto ld_st;
8673     case M_LWR_AB:
8674       s = "lwr";
8675       fmt = MEM12_FMT;
8676       offbits = (mips_opts.micromips ? 12 : 16);
8677       goto ld_st;
8678     case M_LDC1_AB:
8679       s = "ldc1";
8680       fmt = "T,o(b)";
8681       /* Itbl support may require additional care here.  */
8682       coproc = 1;
8683       goto ld_st;
8684     case M_LDC2_AB:
8685       s = "ldc2";
8686       fmt = COP12_FMT;
8687       offbits = (mips_opts.micromips ? 12 : 16);
8688       /* Itbl support may require additional care here.  */
8689       coproc = 1;
8690       goto ld_st;
8691     case M_LQC2_AB:
8692       s = "lqc2";
8693       fmt = "E,o(b)";
8694       /* Itbl support may require additional care here.  */
8695       coproc = 1;
8696       goto ld_st;
8697     case M_LDC3_AB:
8698       s = "ldc3";
8699       fmt = "E,o(b)";
8700       /* Itbl support may require additional care here.  */
8701       coproc = 1;
8702       goto ld_st;
8703     case M_LDL_AB:
8704       s = "ldl";
8705       fmt = MEM12_FMT;
8706       offbits = (mips_opts.micromips ? 12 : 16);
8707       goto ld_st;
8708     case M_LDR_AB:
8709       s = "ldr";
8710       fmt = MEM12_FMT;
8711       offbits = (mips_opts.micromips ? 12 : 16);
8712       goto ld_st;
8713     case M_LL_AB:
8714       s = "ll";
8715       fmt = MEM12_FMT;
8716       offbits = (mips_opts.micromips ? 12 : 16);
8717       goto ld;
8718     case M_LLD_AB:
8719       s = "lld";
8720       fmt = MEM12_FMT;
8721       offbits = (mips_opts.micromips ? 12 : 16);
8722       goto ld;
8723     case M_LWU_AB:
8724       s = "lwu";
8725       fmt = MEM12_FMT;
8726       offbits = (mips_opts.micromips ? 12 : 16);
8727       goto ld;
8728     case M_LWP_AB:
8729       gas_assert (mips_opts.micromips);
8730       s = "lwp";
8731       fmt = "t,~(b)";
8732       offbits = 12;
8733       lp = 1;
8734       goto ld;
8735     case M_LDP_AB:
8736       gas_assert (mips_opts.micromips);
8737       s = "ldp";
8738       fmt = "t,~(b)";
8739       offbits = 12;
8740       lp = 1;
8741       goto ld;
8742     case M_LWM_AB:
8743       gas_assert (mips_opts.micromips);
8744       s = "lwm";
8745       fmt = "n,~(b)";
8746       offbits = 12;
8747       goto ld_st;
8748     case M_LDM_AB:
8749       gas_assert (mips_opts.micromips);
8750       s = "ldm";
8751       fmt = "n,~(b)";
8752       offbits = 12;
8753       goto ld_st;
8754
8755     ld:
8756       /* We don't want to use $0 as tempreg.  */
8757       if (breg == treg + lp || treg + lp == ZERO)
8758         goto ld_st;
8759       else
8760         tempreg = treg + lp;
8761       goto ld_noat;
8762
8763     case M_SB_AB:
8764       s = "sb";
8765       fmt = "t,o(b)";
8766       goto ld_st;
8767     case M_SH_AB:
8768       s = "sh";
8769       fmt = "t,o(b)";
8770       goto ld_st;
8771     case M_SW_AB:
8772       s = "sw";
8773       fmt = "t,o(b)";
8774       goto ld_st;
8775     case M_SWC0_AB:
8776       gas_assert (!mips_opts.micromips);
8777       s = "swc0";
8778       fmt = "E,o(b)";
8779       /* Itbl support may require additional care here.  */
8780       coproc = 1;
8781       goto ld_st;
8782     case M_SWC1_AB:
8783       s = "swc1";
8784       fmt = "T,o(b)";
8785       /* Itbl support may require additional care here.  */
8786       coproc = 1;
8787       goto ld_st;
8788     case M_SWC2_AB:
8789       s = "swc2";
8790       fmt = COP12_FMT;
8791       offbits = (mips_opts.micromips ? 12 : 16);
8792       /* Itbl support may require additional care here.  */
8793       coproc = 1;
8794       goto ld_st;
8795     case M_SWC3_AB:
8796       gas_assert (!mips_opts.micromips);
8797       s = "swc3";
8798       fmt = "E,o(b)";
8799       /* Itbl support may require additional care here.  */
8800       coproc = 1;
8801       goto ld_st;
8802     case M_SWL_AB:
8803       s = "swl";
8804       fmt = MEM12_FMT;
8805       offbits = (mips_opts.micromips ? 12 : 16);
8806       goto ld_st;
8807     case M_SWR_AB:
8808       s = "swr";
8809       fmt = MEM12_FMT;
8810       offbits = (mips_opts.micromips ? 12 : 16);
8811       goto ld_st;
8812     case M_SC_AB:
8813       s = "sc";
8814       fmt = MEM12_FMT;
8815       offbits = (mips_opts.micromips ? 12 : 16);
8816       goto ld_st;
8817     case M_SCD_AB:
8818       s = "scd";
8819       fmt = MEM12_FMT;
8820       offbits = (mips_opts.micromips ? 12 : 16);
8821       goto ld_st;
8822     case M_CACHE_AB:
8823       s = "cache";
8824       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
8825       offbits = (mips_opts.micromips ? 12 : 16);
8826       goto ld_st;
8827     case M_CACHEE_AB:
8828       s = "cachee";
8829       fmt = "k,+j(b)";
8830       offbits = 9;
8831       goto ld_st;
8832     case M_PREF_AB:
8833       s = "pref";
8834       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
8835       offbits = (mips_opts.micromips ? 12 : 16);
8836       goto ld_st;
8837     case M_PREFE_AB:
8838       s = "prefe";
8839       fmt = "k,+j(b)";
8840       offbits = 9;
8841       goto ld_st;
8842     case M_SDC1_AB:
8843       s = "sdc1";
8844       fmt = "T,o(b)";
8845       coproc = 1;
8846       /* Itbl support may require additional care here.  */
8847       goto ld_st;
8848     case M_SDC2_AB:
8849       s = "sdc2";
8850       fmt = COP12_FMT;
8851       offbits = (mips_opts.micromips ? 12 : 16);
8852       /* Itbl support may require additional care here.  */
8853       coproc = 1;
8854       goto ld_st;
8855     case M_SQC2_AB:
8856       s = "sqc2";
8857       fmt = "E,o(b)";
8858       /* Itbl support may require additional care here.  */
8859       coproc = 1;
8860       goto ld_st;
8861     case M_SDC3_AB:
8862       gas_assert (!mips_opts.micromips);
8863       s = "sdc3";
8864       fmt = "E,o(b)";
8865       /* Itbl support may require additional care here.  */
8866       coproc = 1;
8867       goto ld_st;
8868     case M_SDL_AB:
8869       s = "sdl";
8870       fmt = MEM12_FMT;
8871       offbits = (mips_opts.micromips ? 12 : 16);
8872       goto ld_st;
8873     case M_SDR_AB:
8874       s = "sdr";
8875       fmt = MEM12_FMT;
8876       offbits = (mips_opts.micromips ? 12 : 16);
8877       goto ld_st;
8878     case M_SWP_AB:
8879       gas_assert (mips_opts.micromips);
8880       s = "swp";
8881       fmt = "t,~(b)";
8882       offbits = 12;
8883       goto ld_st;
8884     case M_SDP_AB:
8885       gas_assert (mips_opts.micromips);
8886       s = "sdp";
8887       fmt = "t,~(b)";
8888       offbits = 12;
8889       goto ld_st;
8890     case M_SWM_AB:
8891       gas_assert (mips_opts.micromips);
8892       s = "swm";
8893       fmt = "n,~(b)";
8894       offbits = 12;
8895       goto ld_st;
8896     case M_SDM_AB:
8897       gas_assert (mips_opts.micromips);
8898       s = "sdm";
8899       fmt = "n,~(b)";
8900       offbits = 12;
8901
8902     ld_st:
8903       tempreg = AT;
8904     ld_noat:
8905       if (small_offset_p (0, align, 16))
8906         {
8907           /* The first case exists for M_LD_AB and M_SD_AB, which are
8908              macros for o32 but which should act like normal instructions
8909              otherwise.  */
8910           if (offbits == 16)
8911             macro_build (&offset_expr, s, fmt, treg, -1, offset_reloc[0],
8912                          offset_reloc[1], offset_reloc[2], breg);
8913           else if (small_offset_p (0, align, offbits))
8914             {
8915               if (offbits == 0)
8916                 macro_build (NULL, s, fmt, treg, breg);
8917               else
8918                 macro_build (NULL, s, fmt, treg,
8919                              (int) offset_expr.X_add_number, breg);
8920             }
8921           else
8922             {
8923               if (tempreg == AT)
8924                 used_at = 1;
8925               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
8926                            tempreg, breg, -1, offset_reloc[0],
8927                            offset_reloc[1], offset_reloc[2]);
8928               if (offbits == 0)
8929                 macro_build (NULL, s, fmt, treg, tempreg);
8930               else
8931                 macro_build (NULL, s, fmt, treg, 0, tempreg);
8932             }
8933           break;
8934         }
8935
8936       if (tempreg == AT)
8937         used_at = 1;
8938
8939       if (offset_expr.X_op != O_constant
8940           && offset_expr.X_op != O_symbol)
8941         {
8942           as_bad (_("Expression too complex"));
8943           offset_expr.X_op = O_constant;
8944         }
8945
8946       if (HAVE_32BIT_ADDRESSES
8947           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
8948         {
8949           char value [32];
8950
8951           sprintf_vma (value, offset_expr.X_add_number);
8952           as_bad (_("Number (0x%s) larger than 32 bits"), value);
8953         }
8954
8955       /* A constant expression in PIC code can be handled just as it
8956          is in non PIC code.  */
8957       if (offset_expr.X_op == O_constant)
8958         {
8959           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
8960                                                  offbits == 0 ? 16 : offbits);
8961           offset_expr.X_add_number -= expr1.X_add_number;
8962
8963           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
8964           if (breg != 0)
8965             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8966                          tempreg, tempreg, breg);
8967           if (offbits == 0)
8968             {
8969               if (offset_expr.X_add_number != 0)
8970                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
8971                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
8972               macro_build (NULL, s, fmt, treg, tempreg);
8973             }
8974           else if (offbits == 16)
8975             macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16, tempreg);
8976           else
8977             macro_build (NULL, s, fmt, treg,
8978                          (int) offset_expr.X_add_number, tempreg);
8979         }
8980       else if (offbits != 16)
8981         {
8982           /* The offset field is too narrow to be used for a low-part
8983              relocation, so load the whole address into the auxillary
8984              register.  */
8985           load_address (tempreg, &offset_expr, &used_at);
8986           if (breg != 0)
8987             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8988                          tempreg, tempreg, breg);
8989           if (offbits == 0)
8990             macro_build (NULL, s, fmt, treg, tempreg);
8991           else
8992             macro_build (NULL, s, fmt, treg, 0, tempreg);
8993         }
8994       else if (mips_pic == NO_PIC)
8995         {
8996           /* If this is a reference to a GP relative symbol, and there
8997              is no base register, we want
8998                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
8999              Otherwise, if there is no base register, we want
9000                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9001                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9002              If we have a constant, we need two instructions anyhow,
9003              so we always use the latter form.
9004
9005              If we have a base register, and this is a reference to a
9006              GP relative symbol, we want
9007                addu     $tempreg,$breg,$gp
9008                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_GPREL16)
9009              Otherwise we want
9010                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9011                addu     $tempreg,$tempreg,$breg
9012                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9013              With a constant we always use the latter case.
9014
9015              With 64bit address space and no base register and $at usable,
9016              we want
9017                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9018                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9019                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9020                dsll32   $tempreg,0
9021                daddu    $tempreg,$at
9022                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9023              If we have a base register, we want
9024                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9025                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9026                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9027                daddu    $at,$breg
9028                dsll32   $tempreg,0
9029                daddu    $tempreg,$at
9030                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9031
9032              Without $at we can't generate the optimal path for superscalar
9033              processors here since this would require two temporary registers.
9034                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9035                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9036                dsll     $tempreg,16
9037                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9038                dsll     $tempreg,16
9039                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9040              If we have a base register, we want
9041                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9042                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9043                dsll     $tempreg,16
9044                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9045                dsll     $tempreg,16
9046                daddu    $tempreg,$tempreg,$breg
9047                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_LO16)
9048
9049              For GP relative symbols in 64bit address space we can use
9050              the same sequence as in 32bit address space.  */
9051           if (HAVE_64BIT_SYMBOLS)
9052             {
9053               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9054                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9055                 {
9056                   relax_start (offset_expr.X_add_symbol);
9057                   if (breg == 0)
9058                     {
9059                       macro_build (&offset_expr, s, fmt, treg,
9060                                    BFD_RELOC_GPREL16, mips_gp_register);
9061                     }
9062                   else
9063                     {
9064                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9065                                    tempreg, breg, mips_gp_register);
9066                       macro_build (&offset_expr, s, fmt, treg,
9067                                    BFD_RELOC_GPREL16, tempreg);
9068                     }
9069                   relax_switch ();
9070                 }
9071
9072               if (used_at == 0 && mips_opts.at)
9073                 {
9074                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9075                                BFD_RELOC_MIPS_HIGHEST);
9076                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
9077                                BFD_RELOC_HI16_S);
9078                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9079                                tempreg, BFD_RELOC_MIPS_HIGHER);
9080                   if (breg != 0)
9081                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
9082                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9083                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9084                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_LO16,
9085                                tempreg);
9086                   used_at = 1;
9087                 }
9088               else
9089                 {
9090                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9091                                BFD_RELOC_MIPS_HIGHEST);
9092                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9093                                tempreg, BFD_RELOC_MIPS_HIGHER);
9094                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9095                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
9096                                tempreg, BFD_RELOC_HI16_S);
9097                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9098                   if (breg != 0)
9099                     macro_build (NULL, "daddu", "d,v,t",
9100                                  tempreg, tempreg, breg);
9101                   macro_build (&offset_expr, s, fmt, treg,
9102                                BFD_RELOC_LO16, tempreg);
9103                 }
9104
9105               if (mips_relax.sequence)
9106                 relax_end ();
9107               break;
9108             }
9109
9110           if (breg == 0)
9111             {
9112               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9113                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9114                 {
9115                   relax_start (offset_expr.X_add_symbol);
9116                   macro_build (&offset_expr, s, fmt, treg, BFD_RELOC_GPREL16,
9117                                mips_gp_register);
9118                   relax_switch ();
9119                 }
9120               macro_build_lui (&offset_expr, tempreg);
9121               macro_build (&offset_expr, s, fmt, treg,
9122                            BFD_RELOC_LO16, tempreg);
9123               if (mips_relax.sequence)
9124                 relax_end ();
9125             }
9126           else
9127             {
9128               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9129                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9130                 {
9131                   relax_start (offset_expr.X_add_symbol);
9132                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9133                                tempreg, breg, mips_gp_register);
9134                   macro_build (&offset_expr, s, fmt, treg,
9135                                BFD_RELOC_GPREL16, tempreg);
9136                   relax_switch ();
9137                 }
9138               macro_build_lui (&offset_expr, tempreg);
9139               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9140                            tempreg, tempreg, breg);
9141               macro_build (&offset_expr, s, fmt, treg,
9142                            BFD_RELOC_LO16, tempreg);
9143               if (mips_relax.sequence)
9144                 relax_end ();
9145             }
9146         }
9147       else if (!mips_big_got)
9148         {
9149           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9150
9151           /* If this is a reference to an external symbol, we want
9152                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9153                nop
9154                <op>     $treg,0($tempreg)
9155              Otherwise we want
9156                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9157                nop
9158                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9159                <op>     $treg,0($tempreg)
9160
9161              For NewABI, we want
9162                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9163                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
9164
9165              If there is a base register, we add it to $tempreg before
9166              the <op>.  If there is a constant, we stick it in the
9167              <op> instruction.  We don't handle constants larger than
9168              16 bits, because we have no way to load the upper 16 bits
9169              (actually, we could handle them for the subset of cases
9170              in which we are not using $at).  */
9171           gas_assert (offset_expr.X_op == O_symbol);
9172           if (HAVE_NEWABI)
9173             {
9174               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9175                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9176               if (breg != 0)
9177                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9178                              tempreg, tempreg, breg);
9179               macro_build (&offset_expr, s, fmt, treg,
9180                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
9181               break;
9182             }
9183           expr1.X_add_number = offset_expr.X_add_number;
9184           offset_expr.X_add_number = 0;
9185           if (expr1.X_add_number < -0x8000
9186               || expr1.X_add_number >= 0x8000)
9187             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9188           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9189                        lw_reloc_type, mips_gp_register);
9190           load_delay_nop ();
9191           relax_start (offset_expr.X_add_symbol);
9192           relax_switch ();
9193           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9194                        tempreg, BFD_RELOC_LO16);
9195           relax_end ();
9196           if (breg != 0)
9197             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9198                          tempreg, tempreg, breg);
9199           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9200         }
9201       else if (mips_big_got && !HAVE_NEWABI)
9202         {
9203           int gpdelay;
9204
9205           /* If this is a reference to an external symbol, we want
9206                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9207                addu     $tempreg,$tempreg,$gp
9208                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9209                <op>     $treg,0($tempreg)
9210              Otherwise we want
9211                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9212                nop
9213                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9214                <op>     $treg,0($tempreg)
9215              If there is a base register, we add it to $tempreg before
9216              the <op>.  If there is a constant, we stick it in the
9217              <op> instruction.  We don't handle constants larger than
9218              16 bits, because we have no way to load the upper 16 bits
9219              (actually, we could handle them for the subset of cases
9220              in which we are not using $at).  */
9221           gas_assert (offset_expr.X_op == O_symbol);
9222           expr1.X_add_number = offset_expr.X_add_number;
9223           offset_expr.X_add_number = 0;
9224           if (expr1.X_add_number < -0x8000
9225               || expr1.X_add_number >= 0x8000)
9226             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9227           gpdelay = reg_needs_delay (mips_gp_register);
9228           relax_start (offset_expr.X_add_symbol);
9229           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9230                        BFD_RELOC_MIPS_GOT_HI16);
9231           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9232                        mips_gp_register);
9233           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9234                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9235           relax_switch ();
9236           if (gpdelay)
9237             macro_build (NULL, "nop", "");
9238           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9239                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9240           load_delay_nop ();
9241           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
9242                        tempreg, BFD_RELOC_LO16);
9243           relax_end ();
9244
9245           if (breg != 0)
9246             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9247                          tempreg, tempreg, breg);
9248           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9249         }
9250       else if (mips_big_got && HAVE_NEWABI)
9251         {
9252           /* If this is a reference to an external symbol, we want
9253                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9254                add      $tempreg,$tempreg,$gp
9255                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
9256                <op>     $treg,<ofst>($tempreg)
9257              Otherwise, for local symbols, we want:
9258                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
9259                <op>     $treg,<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
9260           gas_assert (offset_expr.X_op == O_symbol);
9261           expr1.X_add_number = offset_expr.X_add_number;
9262           offset_expr.X_add_number = 0;
9263           if (expr1.X_add_number < -0x8000
9264               || expr1.X_add_number >= 0x8000)
9265             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9266           relax_start (offset_expr.X_add_symbol);
9267           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
9268                        BFD_RELOC_MIPS_GOT_HI16);
9269           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
9270                        mips_gp_register);
9271           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9272                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
9273           if (breg != 0)
9274             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9275                          tempreg, tempreg, breg);
9276           macro_build (&expr1, s, fmt, treg, BFD_RELOC_LO16, tempreg);
9277
9278           relax_switch ();
9279           offset_expr.X_add_number = expr1.X_add_number;
9280           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9281                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9282           if (breg != 0)
9283             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9284                          tempreg, tempreg, breg);
9285           macro_build (&offset_expr, s, fmt, treg,
9286                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
9287           relax_end ();
9288         }
9289       else
9290         abort ();
9291
9292       break;
9293
9294     case M_JRADDIUSP:
9295       gas_assert (mips_opts.micromips);
9296       gas_assert (mips_opts.insn32);
9297       start_noreorder ();
9298       macro_build (NULL, "jr", "s", RA);
9299       expr1.X_add_number = EXTRACT_OPERAND (1, IMMP, *ip) << 2;
9300       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
9301       end_noreorder ();
9302       break;
9303
9304     case M_JRC:
9305       gas_assert (mips_opts.micromips);
9306       gas_assert (mips_opts.insn32);
9307       macro_build (NULL, "jr", "s", sreg);
9308       if (mips_opts.noreorder)
9309         macro_build (NULL, "nop", "");
9310       break;
9311
9312     case M_LI:
9313     case M_LI_S:
9314       load_register (treg, &imm_expr, 0);
9315       break;
9316
9317     case M_DLI:
9318       load_register (treg, &imm_expr, 1);
9319       break;
9320
9321     case M_LI_SS:
9322       if (imm_expr.X_op == O_constant)
9323         {
9324           used_at = 1;
9325           load_register (AT, &imm_expr, 0);
9326           macro_build (NULL, "mtc1", "t,G", AT, treg);
9327           break;
9328         }
9329       else
9330         {
9331           gas_assert (offset_expr.X_op == O_symbol
9332                       && strcmp (segment_name (S_GET_SEGMENT
9333                                                (offset_expr.X_add_symbol)),
9334                                  ".lit4") == 0
9335                       && offset_expr.X_add_number == 0);
9336           macro_build (&offset_expr, "lwc1", "T,o(b)", treg,
9337                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
9338           break;
9339         }
9340
9341     case M_LI_D:
9342       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
9343          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
9344          order 32 bits of the value and the low order 32 bits are either
9345          zero or in OFFSET_EXPR.  */
9346       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9347         {
9348           if (HAVE_64BIT_GPRS)
9349             load_register (treg, &imm_expr, 1);
9350           else
9351             {
9352               int hreg, lreg;
9353
9354               if (target_big_endian)
9355                 {
9356                   hreg = treg;
9357                   lreg = treg + 1;
9358                 }
9359               else
9360                 {
9361                   hreg = treg + 1;
9362                   lreg = treg;
9363                 }
9364
9365               if (hreg <= 31)
9366                 load_register (hreg, &imm_expr, 0);
9367               if (lreg <= 31)
9368                 {
9369                   if (offset_expr.X_op == O_absent)
9370                     move_register (lreg, 0);
9371                   else
9372                     {
9373                       gas_assert (offset_expr.X_op == O_constant);
9374                       load_register (lreg, &offset_expr, 0);
9375                     }
9376                 }
9377             }
9378           break;
9379         }
9380
9381       /* We know that sym is in the .rdata section.  First we get the
9382          upper 16 bits of the address.  */
9383       if (mips_pic == NO_PIC)
9384         {
9385           macro_build_lui (&offset_expr, AT);
9386           used_at = 1;
9387         }
9388       else
9389         {
9390           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9391                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9392           used_at = 1;
9393         }
9394
9395       /* Now we load the register(s).  */
9396       if (HAVE_64BIT_GPRS)
9397         {
9398           used_at = 1;
9399           macro_build (&offset_expr, "ld", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9400         }
9401       else
9402         {
9403           used_at = 1;
9404           macro_build (&offset_expr, "lw", "t,o(b)", treg, BFD_RELOC_LO16, AT);
9405           if (treg != RA)
9406             {
9407               /* FIXME: How in the world do we deal with the possible
9408                  overflow here?  */
9409               offset_expr.X_add_number += 4;
9410               macro_build (&offset_expr, "lw", "t,o(b)",
9411                            treg + 1, BFD_RELOC_LO16, AT);
9412             }
9413         }
9414       break;
9415
9416     case M_LI_DD:
9417       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
9418          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
9419          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
9420          the value and the low order 32 bits are either zero or in
9421          OFFSET_EXPR.  */
9422       if (imm_expr.X_op == O_constant || imm_expr.X_op == O_big)
9423         {
9424           used_at = 1;
9425           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
9426           if (HAVE_64BIT_FPRS)
9427             {
9428               gas_assert (HAVE_64BIT_GPRS);
9429               macro_build (NULL, "dmtc1", "t,S", AT, treg);
9430             }
9431           else
9432             {
9433               macro_build (NULL, "mtc1", "t,G", AT, treg + 1);
9434               if (offset_expr.X_op == O_absent)
9435                 macro_build (NULL, "mtc1", "t,G", 0, treg);
9436               else
9437                 {
9438                   gas_assert (offset_expr.X_op == O_constant);
9439                   load_register (AT, &offset_expr, 0);
9440                   macro_build (NULL, "mtc1", "t,G", AT, treg);
9441                 }
9442             }
9443           break;
9444         }
9445
9446       gas_assert (offset_expr.X_op == O_symbol
9447                   && offset_expr.X_add_number == 0);
9448       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
9449       if (strcmp (s, ".lit8") == 0)
9450         {
9451           breg = mips_gp_register;
9452           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
9453           offset_reloc[1] = BFD_RELOC_UNUSED;
9454           offset_reloc[2] = BFD_RELOC_UNUSED;
9455         }
9456       else
9457         {
9458           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
9459           used_at = 1;
9460           if (mips_pic != NO_PIC)
9461             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9462                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
9463           else
9464             {
9465               /* FIXME: This won't work for a 64 bit address.  */
9466               macro_build_lui (&offset_expr, AT);
9467             }
9468
9469           breg = AT;
9470           offset_reloc[0] = BFD_RELOC_LO16;
9471           offset_reloc[1] = BFD_RELOC_UNUSED;
9472           offset_reloc[2] = BFD_RELOC_UNUSED;
9473         }
9474       align = 8;
9475       /* Fall through */
9476
9477     case M_L_DAB:
9478       /*
9479        * The MIPS assembler seems to check for X_add_number not
9480        * being double aligned and generating:
9481        *        lui     at,%hi(foo+1)
9482        *        addu    at,at,v1
9483        *        addiu   at,at,%lo(foo+1)
9484        *        lwc1    f2,0(at)
9485        *        lwc1    f3,4(at)
9486        * But, the resulting address is the same after relocation so why
9487        * generate the extra instruction?
9488        */
9489       /* Itbl support may require additional care here.  */
9490       coproc = 1;
9491       fmt = "T,o(b)";
9492       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9493         {
9494           s = "ldc1";
9495           goto ld_st;
9496         }
9497       s = "lwc1";
9498       goto ldd_std;
9499
9500     case M_S_DAB:
9501       gas_assert (!mips_opts.micromips);
9502       /* Itbl support may require additional care here.  */
9503       coproc = 1;
9504       fmt = "T,o(b)";
9505       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
9506         {
9507           s = "sdc1";
9508           goto ld_st;
9509         }
9510       s = "swc1";
9511       goto ldd_std;
9512
9513     case M_LQ_AB:
9514       fmt = "t,o(b)";
9515       s = "lq";
9516       goto ld;
9517
9518     case M_SQ_AB:
9519       fmt = "t,o(b)";
9520       s = "sq";
9521       goto ld_st;
9522
9523     case M_LD_AB:
9524       fmt = "t,o(b)";
9525       if (HAVE_64BIT_GPRS)
9526         {
9527           s = "ld";
9528           goto ld;
9529         }
9530       s = "lw";
9531       goto ldd_std;
9532
9533     case M_SD_AB:
9534       fmt = "t,o(b)";
9535       if (HAVE_64BIT_GPRS)
9536         {
9537           s = "sd";
9538           goto ld_st;
9539         }
9540       s = "sw";
9541
9542     ldd_std:
9543       /* Even on a big endian machine $fn comes before $fn+1.  We have
9544          to adjust when loading from memory.  We set coproc if we must
9545          load $fn+1 first.  */
9546       /* Itbl support may require additional care here.  */
9547       if (!target_big_endian)
9548         coproc = 0;
9549
9550       if (small_offset_p (0, align, 16))
9551         {
9552           ep = &offset_expr;
9553           if (!small_offset_p (4, align, 16))
9554             {
9555               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
9556                            -1, offset_reloc[0], offset_reloc[1],
9557                            offset_reloc[2]);
9558               expr1.X_add_number = 0;
9559               ep = &expr1;
9560               breg = AT;
9561               used_at = 1;
9562               offset_reloc[0] = BFD_RELOC_LO16;
9563               offset_reloc[1] = BFD_RELOC_UNUSED;
9564               offset_reloc[2] = BFD_RELOC_UNUSED;
9565             }
9566           if (strcmp (s, "lw") == 0 && treg == breg)
9567             {
9568               ep->X_add_number += 4;
9569               macro_build (ep, s, fmt, treg + 1, -1, offset_reloc[0],
9570                            offset_reloc[1], offset_reloc[2], breg);
9571               ep->X_add_number -= 4;
9572               macro_build (ep, s, fmt, treg, -1, offset_reloc[0],
9573                            offset_reloc[1], offset_reloc[2], breg);
9574             }
9575           else
9576             {
9577               macro_build (ep, s, fmt, coproc ? treg + 1 : treg, -1,
9578                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
9579                            breg);
9580               ep->X_add_number += 4;
9581               macro_build (ep, s, fmt, coproc ? treg : treg + 1, -1,
9582                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
9583                            breg);
9584             }
9585           break;
9586         }
9587
9588       if (offset_expr.X_op != O_symbol
9589           && offset_expr.X_op != O_constant)
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       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
9605         {
9606           /* If this is a reference to a GP relative symbol, we want
9607                <op>     $treg,<sym>($gp)        (BFD_RELOC_GPREL16)
9608                <op>     $treg+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
9609              If we have a base register, we use this
9610                addu     $at,$breg,$gp
9611                <op>     $treg,<sym>($at)        (BFD_RELOC_GPREL16)
9612                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
9613              If this is not a GP relative symbol, we want
9614                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9615                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9616                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9617              If there is a base register, we add it to $at after the
9618              lui instruction.  If there is a constant, we always use
9619              the last case.  */
9620           if (offset_expr.X_op == O_symbol
9621               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9622               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9623             {
9624               relax_start (offset_expr.X_add_symbol);
9625               if (breg == 0)
9626                 {
9627                   tempreg = mips_gp_register;
9628                 }
9629               else
9630                 {
9631                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9632                                AT, breg, mips_gp_register);
9633                   tempreg = AT;
9634                   used_at = 1;
9635                 }
9636
9637               /* Itbl support may require additional care here.  */
9638               macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9639                            BFD_RELOC_GPREL16, tempreg);
9640               offset_expr.X_add_number += 4;
9641
9642               /* Set mips_optimize to 2 to avoid inserting an
9643                  undesired nop.  */
9644               hold_mips_optimize = mips_optimize;
9645               mips_optimize = 2;
9646               /* Itbl support may require additional care here.  */
9647               macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9648                            BFD_RELOC_GPREL16, tempreg);
9649               mips_optimize = hold_mips_optimize;
9650
9651               relax_switch ();
9652
9653               offset_expr.X_add_number -= 4;
9654             }
9655           used_at = 1;
9656           if (offset_high_part (offset_expr.X_add_number, 16)
9657               != offset_high_part (offset_expr.X_add_number + 4, 16))
9658             {
9659               load_address (AT, &offset_expr, &used_at);
9660               offset_expr.X_op = O_constant;
9661               offset_expr.X_add_number = 0;
9662             }
9663           else
9664             macro_build_lui (&offset_expr, AT);
9665           if (breg != 0)
9666             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9667           /* Itbl support may require additional care here.  */
9668           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9669                        BFD_RELOC_LO16, AT);
9670           /* FIXME: How do we handle overflow here?  */
9671           offset_expr.X_add_number += 4;
9672           /* Itbl support may require additional care here.  */
9673           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9674                        BFD_RELOC_LO16, AT);
9675           if (mips_relax.sequence)
9676             relax_end ();
9677         }
9678       else if (!mips_big_got)
9679         {
9680           /* If this is a reference to an external symbol, we want
9681                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9682                nop
9683                <op>     $treg,0($at)
9684                <op>     $treg+1,4($at)
9685              Otherwise we want
9686                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9687                nop
9688                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9689                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9690              If there is a base register we add it to $at before the
9691              lwc1 instructions.  If there is a constant we include it
9692              in the lwc1 instructions.  */
9693           used_at = 1;
9694           expr1.X_add_number = offset_expr.X_add_number;
9695           if (expr1.X_add_number < -0x8000
9696               || expr1.X_add_number >= 0x8000 - 4)
9697             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9698           load_got_offset (AT, &offset_expr);
9699           load_delay_nop ();
9700           if (breg != 0)
9701             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9702
9703           /* Set mips_optimize to 2 to avoid inserting an undesired
9704              nop.  */
9705           hold_mips_optimize = mips_optimize;
9706           mips_optimize = 2;
9707
9708           /* Itbl support may require additional care here.  */
9709           relax_start (offset_expr.X_add_symbol);
9710           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9711                        BFD_RELOC_LO16, AT);
9712           expr1.X_add_number += 4;
9713           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9714                        BFD_RELOC_LO16, AT);
9715           relax_switch ();
9716           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9717                        BFD_RELOC_LO16, AT);
9718           offset_expr.X_add_number += 4;
9719           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9720                        BFD_RELOC_LO16, AT);
9721           relax_end ();
9722
9723           mips_optimize = hold_mips_optimize;
9724         }
9725       else if (mips_big_got)
9726         {
9727           int gpdelay;
9728
9729           /* If this is a reference to an external symbol, we want
9730                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
9731                addu     $at,$at,$gp
9732                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
9733                nop
9734                <op>     $treg,0($at)
9735                <op>     $treg+1,4($at)
9736              Otherwise we want
9737                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
9738                nop
9739                <op>     $treg,<sym>($at)        (BFD_RELOC_LO16)
9740                <op>     $treg+1,<sym>+4($at)    (BFD_RELOC_LO16)
9741              If there is a base register we add it to $at before the
9742              lwc1 instructions.  If there is a constant we include it
9743              in the lwc1 instructions.  */
9744           used_at = 1;
9745           expr1.X_add_number = offset_expr.X_add_number;
9746           offset_expr.X_add_number = 0;
9747           if (expr1.X_add_number < -0x8000
9748               || expr1.X_add_number >= 0x8000 - 4)
9749             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9750           gpdelay = reg_needs_delay (mips_gp_register);
9751           relax_start (offset_expr.X_add_symbol);
9752           macro_build (&offset_expr, "lui", LUI_FMT,
9753                        AT, BFD_RELOC_MIPS_GOT_HI16);
9754           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9755                        AT, AT, mips_gp_register);
9756           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9757                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
9758           load_delay_nop ();
9759           if (breg != 0)
9760             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9761           /* Itbl support may require additional care here.  */
9762           macro_build (&expr1, s, fmt, coproc ? treg + 1 : treg,
9763                        BFD_RELOC_LO16, AT);
9764           expr1.X_add_number += 4;
9765
9766           /* Set mips_optimize to 2 to avoid inserting an undesired
9767              nop.  */
9768           hold_mips_optimize = mips_optimize;
9769           mips_optimize = 2;
9770           /* Itbl support may require additional care here.  */
9771           macro_build (&expr1, s, fmt, coproc ? treg : treg + 1,
9772                        BFD_RELOC_LO16, AT);
9773           mips_optimize = hold_mips_optimize;
9774           expr1.X_add_number -= 4;
9775
9776           relax_switch ();
9777           offset_expr.X_add_number = expr1.X_add_number;
9778           if (gpdelay)
9779             macro_build (NULL, "nop", "");
9780           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
9781                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9782           load_delay_nop ();
9783           if (breg != 0)
9784             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
9785           /* Itbl support may require additional care here.  */
9786           macro_build (&offset_expr, s, fmt, coproc ? treg + 1 : treg,
9787                        BFD_RELOC_LO16, AT);
9788           offset_expr.X_add_number += 4;
9789
9790           /* Set mips_optimize to 2 to avoid inserting an undesired
9791              nop.  */
9792           hold_mips_optimize = mips_optimize;
9793           mips_optimize = 2;
9794           /* Itbl support may require additional care here.  */
9795           macro_build (&offset_expr, s, fmt, coproc ? treg : treg + 1,
9796                        BFD_RELOC_LO16, AT);
9797           mips_optimize = hold_mips_optimize;
9798           relax_end ();
9799         }
9800       else
9801         abort ();
9802
9803       break;
9804         
9805     case M_SAA_AB:
9806       s = "saa";
9807       offbits = 0;
9808       fmt = "t,(b)";
9809       goto ld_st;
9810     case M_SAAD_AB:
9811       s = "saad";
9812       offbits = 0;
9813       fmt = "t,(b)";
9814       goto ld_st;
9815
9816    /* New code added to support COPZ instructions.
9817       This code builds table entries out of the macros in mip_opcodes.
9818       R4000 uses interlocks to handle coproc delays.
9819       Other chips (like the R3000) require nops to be inserted for delays.
9820
9821       FIXME: Currently, we require that the user handle delays.
9822       In order to fill delay slots for non-interlocked chips,
9823       we must have a way to specify delays based on the coprocessor.
9824       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
9825       What are the side-effects of the cop instruction?
9826       What cache support might we have and what are its effects?
9827       Both coprocessor & memory require delays. how long???
9828       What registers are read/set/modified?
9829
9830       If an itbl is provided to interpret cop instructions,
9831       this knowledge can be encoded in the itbl spec.  */
9832
9833     case M_COP0:
9834       s = "c0";
9835       goto copz;
9836     case M_COP1:
9837       s = "c1";
9838       goto copz;
9839     case M_COP2:
9840       s = "c2";
9841       goto copz;
9842     case M_COP3:
9843       s = "c3";
9844     copz:
9845       gas_assert (!mips_opts.micromips);
9846       /* For now we just do C (same as Cz).  The parameter will be
9847          stored in insn_opcode by mips_ip.  */
9848       macro_build (NULL, s, "C", (int) ip->insn_opcode);
9849       break;
9850
9851     case M_MOVE:
9852       move_register (dreg, sreg);
9853       break;
9854
9855     case M_MOVEP:
9856       gas_assert (mips_opts.micromips);
9857       gas_assert (mips_opts.insn32);
9858       dreg = micromips_to_32_reg_h_map1[EXTRACT_OPERAND (1, MH, *ip)];
9859       breg = micromips_to_32_reg_h_map2[EXTRACT_OPERAND (1, MH, *ip)];
9860       sreg = micromips_to_32_reg_m_map[EXTRACT_OPERAND (1, MM, *ip)];
9861       treg = micromips_to_32_reg_n_map[EXTRACT_OPERAND (1, MN, *ip)];
9862       move_register (dreg, sreg);
9863       move_register (breg, treg);
9864       break;
9865
9866     case M_DMUL:
9867       dbl = 1;
9868     case M_MUL:
9869       if (mips_opts.arch == CPU_R5900)
9870         {
9871           macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", dreg, sreg, treg);
9872         }
9873       else
9874         {
9875       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", sreg, treg);
9876       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9877         }
9878       break;
9879
9880     case M_DMUL_I:
9881       dbl = 1;
9882     case M_MUL_I:
9883       /* The MIPS assembler some times generates shifts and adds.  I'm
9884          not trying to be that fancy. GCC should do this for us
9885          anyway.  */
9886       used_at = 1;
9887       load_register (AT, &imm_expr, dbl);
9888       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, AT);
9889       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9890       break;
9891
9892     case M_DMULO_I:
9893       dbl = 1;
9894     case M_MULO_I:
9895       imm = 1;
9896       goto do_mulo;
9897
9898     case M_DMULO:
9899       dbl = 1;
9900     case M_MULO:
9901     do_mulo:
9902       start_noreorder ();
9903       used_at = 1;
9904       if (imm)
9905         load_register (AT, &imm_expr, dbl);
9906       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", sreg, imm ? AT : treg);
9907       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9908       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, dreg, dreg, RA);
9909       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9910       if (mips_trap)
9911         macro_build (NULL, "tne", TRAP_FMT, dreg, AT, 6);
9912       else
9913         {
9914           if (mips_opts.micromips)
9915             micromips_label_expr (&label_expr);
9916           else
9917             label_expr.X_add_number = 8;
9918           macro_build (&label_expr, "beq", "s,t,p", dreg, AT);
9919           macro_build (NULL, "nop", "");
9920           macro_build (NULL, "break", BRK_FMT, 6);
9921           if (mips_opts.micromips)
9922             micromips_add_label ();
9923         }
9924       end_noreorder ();
9925       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9926       break;
9927
9928     case M_DMULOU_I:
9929       dbl = 1;
9930     case M_MULOU_I:
9931       imm = 1;
9932       goto do_mulou;
9933
9934     case M_DMULOU:
9935       dbl = 1;
9936     case M_MULOU:
9937     do_mulou:
9938       start_noreorder ();
9939       used_at = 1;
9940       if (imm)
9941         load_register (AT, &imm_expr, dbl);
9942       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
9943                    sreg, imm ? AT : treg);
9944       macro_build (NULL, "mfhi", MFHL_FMT, AT);
9945       macro_build (NULL, "mflo", MFHL_FMT, dreg);
9946       if (mips_trap)
9947         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
9948       else
9949         {
9950           if (mips_opts.micromips)
9951             micromips_label_expr (&label_expr);
9952           else
9953             label_expr.X_add_number = 8;
9954           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
9955           macro_build (NULL, "nop", "");
9956           macro_build (NULL, "break", BRK_FMT, 6);
9957           if (mips_opts.micromips)
9958             micromips_add_label ();
9959         }
9960       end_noreorder ();
9961       break;
9962
9963     case M_DROL:
9964       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
9965         {
9966           if (dreg == sreg)
9967             {
9968               tempreg = AT;
9969               used_at = 1;
9970             }
9971           else
9972             {
9973               tempreg = dreg;
9974             }
9975           macro_build (NULL, "dnegu", "d,w", tempreg, treg);
9976           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, tempreg);
9977           break;
9978         }
9979       used_at = 1;
9980       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
9981       macro_build (NULL, "dsrlv", "d,t,s", AT, sreg, AT);
9982       macro_build (NULL, "dsllv", "d,t,s", dreg, sreg, treg);
9983       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
9984       break;
9985
9986     case M_ROL:
9987       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
9988         {
9989           if (dreg == sreg)
9990             {
9991               tempreg = AT;
9992               used_at = 1;
9993             }
9994           else
9995             {
9996               tempreg = dreg;
9997             }
9998           macro_build (NULL, "negu", "d,w", tempreg, treg);
9999           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, tempreg);
10000           break;
10001         }
10002       used_at = 1;
10003       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10004       macro_build (NULL, "srlv", "d,t,s", AT, sreg, AT);
10005       macro_build (NULL, "sllv", "d,t,s", dreg, sreg, treg);
10006       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10007       break;
10008
10009     case M_DROL_I:
10010       {
10011         unsigned int rot;
10012         char *l;
10013         char *rr;
10014
10015         if (imm_expr.X_op != O_constant)
10016           as_bad (_("Improper rotate count"));
10017         rot = imm_expr.X_add_number & 0x3f;
10018         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10019           {
10020             rot = (64 - rot) & 0x3f;
10021             if (rot >= 32)
10022               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10023             else
10024               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10025             break;
10026           }
10027         if (rot == 0)
10028           {
10029             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10030             break;
10031           }
10032         l = (rot < 0x20) ? "dsll" : "dsll32";
10033         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
10034         rot &= 0x1f;
10035         used_at = 1;
10036         macro_build (NULL, l, SHFT_FMT, AT, sreg, rot);
10037         macro_build (NULL, rr, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10038         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10039       }
10040       break;
10041
10042     case M_ROL_I:
10043       {
10044         unsigned int rot;
10045
10046         if (imm_expr.X_op != O_constant)
10047           as_bad (_("Improper rotate count"));
10048         rot = imm_expr.X_add_number & 0x1f;
10049         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10050           {
10051             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, (32 - rot) & 0x1f);
10052             break;
10053           }
10054         if (rot == 0)
10055           {
10056             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10057             break;
10058           }
10059         used_at = 1;
10060         macro_build (NULL, "sll", SHFT_FMT, AT, sreg, rot);
10061         macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10062         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10063       }
10064       break;
10065
10066     case M_DROR:
10067       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10068         {
10069           macro_build (NULL, "drorv", "d,t,s", dreg, sreg, treg);
10070           break;
10071         }
10072       used_at = 1;
10073       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, treg);
10074       macro_build (NULL, "dsllv", "d,t,s", AT, sreg, AT);
10075       macro_build (NULL, "dsrlv", "d,t,s", dreg, sreg, treg);
10076       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10077       break;
10078
10079     case M_ROR:
10080       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10081         {
10082           macro_build (NULL, "rorv", "d,t,s", dreg, sreg, treg);
10083           break;
10084         }
10085       used_at = 1;
10086       macro_build (NULL, "subu", "d,v,t", AT, ZERO, treg);
10087       macro_build (NULL, "sllv", "d,t,s", AT, sreg, AT);
10088       macro_build (NULL, "srlv", "d,t,s", dreg, sreg, treg);
10089       macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10090       break;
10091
10092     case M_DROR_I:
10093       {
10094         unsigned int rot;
10095         char *l;
10096         char *rr;
10097
10098         if (imm_expr.X_op != O_constant)
10099           as_bad (_("Improper rotate count"));
10100         rot = imm_expr.X_add_number & 0x3f;
10101         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
10102           {
10103             if (rot >= 32)
10104               macro_build (NULL, "dror32", SHFT_FMT, dreg, sreg, rot - 32);
10105             else
10106               macro_build (NULL, "dror", SHFT_FMT, dreg, sreg, rot);
10107             break;
10108           }
10109         if (rot == 0)
10110           {
10111             macro_build (NULL, "dsrl", SHFT_FMT, dreg, sreg, 0);
10112             break;
10113           }
10114         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
10115         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
10116         rot &= 0x1f;
10117         used_at = 1;
10118         macro_build (NULL, rr, SHFT_FMT, AT, sreg, rot);
10119         macro_build (NULL, l, SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10120         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10121       }
10122       break;
10123
10124     case M_ROR_I:
10125       {
10126         unsigned int rot;
10127
10128         if (imm_expr.X_op != O_constant)
10129           as_bad (_("Improper rotate count"));
10130         rot = imm_expr.X_add_number & 0x1f;
10131         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
10132           {
10133             macro_build (NULL, "ror", SHFT_FMT, dreg, sreg, rot);
10134             break;
10135           }
10136         if (rot == 0)
10137           {
10138             macro_build (NULL, "srl", SHFT_FMT, dreg, sreg, 0);
10139             break;
10140           }
10141         used_at = 1;
10142         macro_build (NULL, "srl", SHFT_FMT, AT, sreg, rot);
10143         macro_build (NULL, "sll", SHFT_FMT, dreg, sreg, (0x20 - rot) & 0x1f);
10144         macro_build (NULL, "or", "d,v,t", dreg, dreg, AT);
10145       }
10146       break;
10147
10148     case M_SEQ:
10149       if (sreg == 0)
10150         macro_build (&expr1, "sltiu", "t,r,j", dreg, treg, BFD_RELOC_LO16);
10151       else if (treg == 0)
10152         macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10153       else
10154         {
10155           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10156           macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10157         }
10158       break;
10159
10160     case M_SEQ_I:
10161       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10162         {
10163           macro_build (&expr1, "sltiu", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10164           break;
10165         }
10166       if (sreg == 0)
10167         {
10168           as_warn (_("Instruction %s: result is always false"),
10169                    ip->insn_mo->name);
10170           move_register (dreg, 0);
10171           break;
10172         }
10173       if (CPU_HAS_SEQ (mips_opts.arch)
10174           && -512 <= imm_expr.X_add_number
10175           && imm_expr.X_add_number < 512)
10176         {
10177           macro_build (NULL, "seqi", "t,r,+Q", dreg, sreg,
10178                        (int) imm_expr.X_add_number);
10179           break;
10180         }
10181       if (imm_expr.X_op == O_constant
10182           && imm_expr.X_add_number >= 0
10183           && imm_expr.X_add_number < 0x10000)
10184         {
10185           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10186         }
10187       else if (imm_expr.X_op == O_constant
10188                && imm_expr.X_add_number > -0x8000
10189                && imm_expr.X_add_number < 0)
10190         {
10191           imm_expr.X_add_number = -imm_expr.X_add_number;
10192           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10193                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10194         }
10195       else if (CPU_HAS_SEQ (mips_opts.arch))
10196         {
10197           used_at = 1;
10198           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10199           macro_build (NULL, "seq", "d,v,t", dreg, sreg, AT);
10200           break;
10201         }
10202       else
10203         {
10204           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10205           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10206           used_at = 1;
10207         }
10208       macro_build (&expr1, "sltiu", "t,r,j", dreg, dreg, BFD_RELOC_LO16);
10209       break;
10210
10211     case M_SGE:         /* sreg >= treg <==> not (sreg < treg) */
10212       s = "slt";
10213       goto sge;
10214     case M_SGEU:
10215       s = "sltu";
10216     sge:
10217       macro_build (NULL, s, "d,v,t", dreg, sreg, treg);
10218       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10219       break;
10220
10221     case M_SGE_I:               /* sreg >= I <==> not (sreg < I) */
10222     case M_SGEU_I:
10223       if (imm_expr.X_op == O_constant
10224           && imm_expr.X_add_number >= -0x8000
10225           && imm_expr.X_add_number < 0x8000)
10226         {
10227           macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
10228                        dreg, sreg, BFD_RELOC_LO16);
10229         }
10230       else
10231         {
10232           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10233           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
10234                        dreg, sreg, AT);
10235           used_at = 1;
10236         }
10237       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10238       break;
10239
10240     case M_SGT:         /* sreg > treg  <==>  treg < sreg */
10241       s = "slt";
10242       goto sgt;
10243     case M_SGTU:
10244       s = "sltu";
10245     sgt:
10246       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10247       break;
10248
10249     case M_SGT_I:               /* sreg > I  <==>  I < sreg */
10250       s = "slt";
10251       goto sgti;
10252     case M_SGTU_I:
10253       s = "sltu";
10254     sgti:
10255       used_at = 1;
10256       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10257       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10258       break;
10259
10260     case M_SLE: /* sreg <= treg  <==>  treg >= sreg  <==>  not (treg < sreg) */
10261       s = "slt";
10262       goto sle;
10263     case M_SLEU:
10264       s = "sltu";
10265     sle:
10266       macro_build (NULL, s, "d,v,t", dreg, treg, sreg);
10267       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10268       break;
10269
10270     case M_SLE_I:       /* sreg <= I <==> I >= sreg <==> not (I < sreg) */
10271       s = "slt";
10272       goto slei;
10273     case M_SLEU_I:
10274       s = "sltu";
10275     slei:
10276       used_at = 1;
10277       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10278       macro_build (NULL, s, "d,v,t", dreg, AT, sreg);
10279       macro_build (&expr1, "xori", "t,r,i", dreg, dreg, BFD_RELOC_LO16);
10280       break;
10281
10282     case M_SLT_I:
10283       if (imm_expr.X_op == O_constant
10284           && imm_expr.X_add_number >= -0x8000
10285           && imm_expr.X_add_number < 0x8000)
10286         {
10287           macro_build (&imm_expr, "slti", "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10288           break;
10289         }
10290       used_at = 1;
10291       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10292       macro_build (NULL, "slt", "d,v,t", dreg, sreg, AT);
10293       break;
10294
10295     case M_SLTU_I:
10296       if (imm_expr.X_op == O_constant
10297           && imm_expr.X_add_number >= -0x8000
10298           && imm_expr.X_add_number < 0x8000)
10299         {
10300           macro_build (&imm_expr, "sltiu", "t,r,j", dreg, sreg,
10301                        BFD_RELOC_LO16);
10302           break;
10303         }
10304       used_at = 1;
10305       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10306       macro_build (NULL, "sltu", "d,v,t", dreg, sreg, AT);
10307       break;
10308
10309     case M_SNE:
10310       if (sreg == 0)
10311         macro_build (NULL, "sltu", "d,v,t", dreg, 0, treg);
10312       else if (treg == 0)
10313         macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10314       else
10315         {
10316           macro_build (NULL, "xor", "d,v,t", dreg, sreg, treg);
10317           macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10318         }
10319       break;
10320
10321     case M_SNE_I:
10322       if (imm_expr.X_op == O_constant && imm_expr.X_add_number == 0)
10323         {
10324           macro_build (NULL, "sltu", "d,v,t", dreg, 0, sreg);
10325           break;
10326         }
10327       if (sreg == 0)
10328         {
10329           as_warn (_("Instruction %s: result is always true"),
10330                    ip->insn_mo->name);
10331           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
10332                        dreg, 0, BFD_RELOC_LO16);
10333           break;
10334         }
10335       if (CPU_HAS_SEQ (mips_opts.arch)
10336           && -512 <= imm_expr.X_add_number
10337           && imm_expr.X_add_number < 512)
10338         {
10339           macro_build (NULL, "snei", "t,r,+Q", dreg, sreg,
10340                        (int) imm_expr.X_add_number);
10341           break;
10342         }
10343       if (imm_expr.X_op == O_constant
10344           && imm_expr.X_add_number >= 0
10345           && imm_expr.X_add_number < 0x10000)
10346         {
10347           macro_build (&imm_expr, "xori", "t,r,i", dreg, sreg, BFD_RELOC_LO16);
10348         }
10349       else if (imm_expr.X_op == O_constant
10350                && imm_expr.X_add_number > -0x8000
10351                && imm_expr.X_add_number < 0)
10352         {
10353           imm_expr.X_add_number = -imm_expr.X_add_number;
10354           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
10355                        "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10356         }
10357       else if (CPU_HAS_SEQ (mips_opts.arch))
10358         {
10359           used_at = 1;
10360           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10361           macro_build (NULL, "sne", "d,v,t", dreg, sreg, AT);
10362           break;
10363         }
10364       else
10365         {
10366           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10367           macro_build (NULL, "xor", "d,v,t", dreg, sreg, AT);
10368           used_at = 1;
10369         }
10370       macro_build (NULL, "sltu", "d,v,t", dreg, 0, dreg);
10371       break;
10372
10373     case M_SUB_I:
10374       s = "addi";
10375       s2 = "sub";
10376       goto do_subi;
10377     case M_SUBU_I:
10378       s = "addiu";
10379       s2 = "subu";
10380       goto do_subi;
10381     case M_DSUB_I:
10382       dbl = 1;
10383       s = "daddi";
10384       s2 = "dsub";
10385       if (!mips_opts.micromips)
10386         goto do_subi;
10387       if (imm_expr.X_op == O_constant
10388           && imm_expr.X_add_number > -0x200
10389           && imm_expr.X_add_number <= 0x200)
10390         {
10391           macro_build (NULL, s, "t,r,.", dreg, sreg, -imm_expr.X_add_number);
10392           break;
10393         }
10394       goto do_subi_i;
10395     case M_DSUBU_I:
10396       dbl = 1;
10397       s = "daddiu";
10398       s2 = "dsubu";
10399     do_subi:
10400       if (imm_expr.X_op == O_constant
10401           && imm_expr.X_add_number > -0x8000
10402           && imm_expr.X_add_number <= 0x8000)
10403         {
10404           imm_expr.X_add_number = -imm_expr.X_add_number;
10405           macro_build (&imm_expr, s, "t,r,j", dreg, sreg, BFD_RELOC_LO16);
10406           break;
10407         }
10408     do_subi_i:
10409       used_at = 1;
10410       load_register (AT, &imm_expr, dbl);
10411       macro_build (NULL, s2, "d,v,t", dreg, sreg, AT);
10412       break;
10413
10414     case M_TEQ_I:
10415       s = "teq";
10416       goto trap;
10417     case M_TGE_I:
10418       s = "tge";
10419       goto trap;
10420     case M_TGEU_I:
10421       s = "tgeu";
10422       goto trap;
10423     case M_TLT_I:
10424       s = "tlt";
10425       goto trap;
10426     case M_TLTU_I:
10427       s = "tltu";
10428       goto trap;
10429     case M_TNE_I:
10430       s = "tne";
10431     trap:
10432       used_at = 1;
10433       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
10434       macro_build (NULL, s, "s,t", sreg, AT);
10435       break;
10436
10437     case M_TRUNCWS:
10438     case M_TRUNCWD:
10439       gas_assert (!mips_opts.micromips);
10440       gas_assert (mips_opts.isa == ISA_MIPS1);
10441       used_at = 1;
10442       sreg = (ip->insn_opcode >> 11) & 0x1f;    /* floating reg */
10443       dreg = (ip->insn_opcode >> 06) & 0x1f;    /* floating reg */
10444
10445       /*
10446        * Is the double cfc1 instruction a bug in the mips assembler;
10447        * or is there a reason for it?
10448        */
10449       start_noreorder ();
10450       macro_build (NULL, "cfc1", "t,G", treg, RA);
10451       macro_build (NULL, "cfc1", "t,G", treg, RA);
10452       macro_build (NULL, "nop", "");
10453       expr1.X_add_number = 3;
10454       macro_build (&expr1, "ori", "t,r,i", AT, treg, BFD_RELOC_LO16);
10455       expr1.X_add_number = 2;
10456       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
10457       macro_build (NULL, "ctc1", "t,G", AT, RA);
10458       macro_build (NULL, "nop", "");
10459       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
10460                    dreg, sreg);
10461       macro_build (NULL, "ctc1", "t,G", treg, RA);
10462       macro_build (NULL, "nop", "");
10463       end_noreorder ();
10464       break;
10465
10466     case M_ULH_AB:
10467       s = "lb";
10468       s2 = "lbu";
10469       off = 1;
10470       goto uld_st;
10471     case M_ULHU_AB:
10472       s = "lbu";
10473       s2 = "lbu";
10474       off = 1;
10475       goto uld_st;
10476     case M_ULW_AB:
10477       s = "lwl";
10478       s2 = "lwr";
10479       offbits = (mips_opts.micromips ? 12 : 16);
10480       off = 3;
10481       goto uld_st;
10482     case M_ULD_AB:
10483       s = "ldl";
10484       s2 = "ldr";
10485       offbits = (mips_opts.micromips ? 12 : 16);
10486       off = 7;
10487       goto uld_st;
10488     case M_USH_AB:
10489       s = "sb";
10490       s2 = "sb";
10491       off = 1;
10492       ust = 1;
10493       goto uld_st;
10494     case M_USW_AB:
10495       s = "swl";
10496       s2 = "swr";
10497       offbits = (mips_opts.micromips ? 12 : 16);
10498       off = 3;
10499       ust = 1;
10500       goto uld_st;
10501     case M_USD_AB:
10502       s = "sdl";
10503       s2 = "sdr";
10504       offbits = (mips_opts.micromips ? 12 : 16);
10505       off = 7;
10506       ust = 1;
10507
10508     uld_st:
10509       large_offset = !small_offset_p (off, align, offbits);
10510       ep = &offset_expr;
10511       expr1.X_add_number = 0;
10512       if (large_offset)
10513         {
10514           used_at = 1;
10515           tempreg = AT;
10516           if (small_offset_p (0, align, 16))
10517             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
10518                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10519           else
10520             {
10521               load_address (tempreg, ep, &used_at);
10522               if (breg != 0)
10523                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10524                              tempreg, tempreg, breg);
10525             }
10526           offset_reloc[0] = BFD_RELOC_LO16;
10527           offset_reloc[1] = BFD_RELOC_UNUSED;
10528           offset_reloc[2] = BFD_RELOC_UNUSED;
10529           breg = tempreg;
10530           tempreg = treg;
10531           ep = &expr1;
10532         }
10533       else if (!ust && treg == breg)
10534         {
10535           used_at = 1;
10536           tempreg = AT;
10537         }
10538       else
10539         tempreg = treg;
10540
10541       if (off == 1)
10542         goto ulh_sh;
10543
10544       if (!target_big_endian)
10545         ep->X_add_number += off;
10546       if (offbits == 12)
10547         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
10548       else
10549         macro_build (ep, s, "t,o(b)", tempreg, -1,
10550                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10551
10552       if (!target_big_endian)
10553         ep->X_add_number -= off;
10554       else
10555         ep->X_add_number += off;
10556       if (offbits == 12)
10557         macro_build (NULL, s2, "t,~(b)",
10558                      tempreg, (int) ep->X_add_number, breg);
10559       else
10560         macro_build (ep, s2, "t,o(b)", tempreg, -1,
10561                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10562
10563       /* If necessary, move the result in tempreg to the final destination.  */
10564       if (!ust && treg != tempreg)
10565         {
10566           /* Protect second load's delay slot.  */
10567           load_delay_nop ();
10568           move_register (treg, tempreg);
10569         }
10570       break;
10571
10572     ulh_sh:
10573       used_at = 1;
10574       if (target_big_endian == ust)
10575         ep->X_add_number += off;
10576       tempreg = ust || large_offset ? treg : AT;
10577       macro_build (ep, s, "t,o(b)", tempreg, -1,
10578                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10579
10580       /* For halfword transfers we need a temporary register to shuffle
10581          bytes.  Unfortunately for M_USH_A we have none available before
10582          the next store as AT holds the base address.  We deal with this
10583          case by clobbering TREG and then restoring it as with ULH.  */
10584       tempreg = ust == large_offset ? treg : AT;
10585       if (ust)
10586         macro_build (NULL, "srl", SHFT_FMT, tempreg, treg, 8);
10587
10588       if (target_big_endian == ust)
10589         ep->X_add_number -= off;
10590       else
10591         ep->X_add_number += off;
10592       macro_build (ep, s2, "t,o(b)", tempreg, -1,
10593                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
10594
10595       /* For M_USH_A re-retrieve the LSB.  */
10596       if (ust && large_offset)
10597         {
10598           if (target_big_endian)
10599             ep->X_add_number += off;
10600           else
10601             ep->X_add_number -= off;
10602           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
10603                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
10604         }
10605       /* For ULH and M_USH_A OR the LSB in.  */
10606       if (!ust || large_offset)
10607         {
10608           tempreg = !large_offset ? AT : treg;
10609           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
10610           macro_build (NULL, "or", "d,v,t", treg, treg, AT);
10611         }
10612       break;
10613
10614     default:
10615       /* FIXME: Check if this is one of the itbl macros, since they
10616          are added dynamically.  */
10617       as_bad (_("Macro %s not implemented yet"), ip->insn_mo->name);
10618       break;
10619     }
10620   if (!mips_opts.at && used_at)
10621     as_bad (_("Macro used $at after \".set noat\""));
10622 }
10623
10624 /* Implement macros in mips16 mode.  */
10625
10626 static void
10627 mips16_macro (struct mips_cl_insn *ip)
10628 {
10629   int mask;
10630   int xreg, yreg, zreg, tmp;
10631   expressionS expr1;
10632   int dbl;
10633   const char *s, *s2, *s3;
10634
10635   mask = ip->insn_mo->mask;
10636
10637   xreg = MIPS16_EXTRACT_OPERAND (RX, *ip);
10638   yreg = MIPS16_EXTRACT_OPERAND (RY, *ip);
10639   zreg = MIPS16_EXTRACT_OPERAND (RZ, *ip);
10640
10641   expr1.X_op = O_constant;
10642   expr1.X_op_symbol = NULL;
10643   expr1.X_add_symbol = NULL;
10644   expr1.X_add_number = 1;
10645
10646   dbl = 0;
10647
10648   switch (mask)
10649     {
10650     default:
10651       abort ();
10652
10653     case M_DDIV_3:
10654       dbl = 1;
10655     case M_DIV_3:
10656       s = "mflo";
10657       goto do_div3;
10658     case M_DREM_3:
10659       dbl = 1;
10660     case M_REM_3:
10661       s = "mfhi";
10662     do_div3:
10663       start_noreorder ();
10664       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", xreg, yreg);
10665       expr1.X_add_number = 2;
10666       macro_build (&expr1, "bnez", "x,p", yreg);
10667       macro_build (NULL, "break", "6", 7);
10668
10669       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
10670          since that causes an overflow.  We should do that as well,
10671          but I don't see how to do the comparisons without a temporary
10672          register.  */
10673       end_noreorder ();
10674       macro_build (NULL, s, "x", zreg);
10675       break;
10676
10677     case M_DIVU_3:
10678       s = "divu";
10679       s2 = "mflo";
10680       goto do_divu3;
10681     case M_REMU_3:
10682       s = "divu";
10683       s2 = "mfhi";
10684       goto do_divu3;
10685     case M_DDIVU_3:
10686       s = "ddivu";
10687       s2 = "mflo";
10688       goto do_divu3;
10689     case M_DREMU_3:
10690       s = "ddivu";
10691       s2 = "mfhi";
10692     do_divu3:
10693       start_noreorder ();
10694       macro_build (NULL, s, "0,x,y", xreg, yreg);
10695       expr1.X_add_number = 2;
10696       macro_build (&expr1, "bnez", "x,p", yreg);
10697       macro_build (NULL, "break", "6", 7);
10698       end_noreorder ();
10699       macro_build (NULL, s2, "x", zreg);
10700       break;
10701
10702     case M_DMUL:
10703       dbl = 1;
10704     case M_MUL:
10705       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", xreg, yreg);
10706       macro_build (NULL, "mflo", "x", zreg);
10707       break;
10708
10709     case M_DSUBU_I:
10710       dbl = 1;
10711       goto do_subu;
10712     case M_SUBU_I:
10713     do_subu:
10714       if (imm_expr.X_op != O_constant)
10715         as_bad (_("Unsupported large constant"));
10716       imm_expr.X_add_number = -imm_expr.X_add_number;
10717       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", yreg, xreg);
10718       break;
10719
10720     case M_SUBU_I_2:
10721       if (imm_expr.X_op != O_constant)
10722         as_bad (_("Unsupported large constant"));
10723       imm_expr.X_add_number = -imm_expr.X_add_number;
10724       macro_build (&imm_expr, "addiu", "x,k", xreg);
10725       break;
10726
10727     case M_DSUBU_I_2:
10728       if (imm_expr.X_op != O_constant)
10729         as_bad (_("Unsupported large constant"));
10730       imm_expr.X_add_number = -imm_expr.X_add_number;
10731       macro_build (&imm_expr, "daddiu", "y,j", yreg);
10732       break;
10733
10734     case M_BEQ:
10735       s = "cmp";
10736       s2 = "bteqz";
10737       goto do_branch;
10738     case M_BNE:
10739       s = "cmp";
10740       s2 = "btnez";
10741       goto do_branch;
10742     case M_BLT:
10743       s = "slt";
10744       s2 = "btnez";
10745       goto do_branch;
10746     case M_BLTU:
10747       s = "sltu";
10748       s2 = "btnez";
10749       goto do_branch;
10750     case M_BLE:
10751       s = "slt";
10752       s2 = "bteqz";
10753       goto do_reverse_branch;
10754     case M_BLEU:
10755       s = "sltu";
10756       s2 = "bteqz";
10757       goto do_reverse_branch;
10758     case M_BGE:
10759       s = "slt";
10760       s2 = "bteqz";
10761       goto do_branch;
10762     case M_BGEU:
10763       s = "sltu";
10764       s2 = "bteqz";
10765       goto do_branch;
10766     case M_BGT:
10767       s = "slt";
10768       s2 = "btnez";
10769       goto do_reverse_branch;
10770     case M_BGTU:
10771       s = "sltu";
10772       s2 = "btnez";
10773
10774     do_reverse_branch:
10775       tmp = xreg;
10776       xreg = yreg;
10777       yreg = tmp;
10778
10779     do_branch:
10780       macro_build (NULL, s, "x,y", xreg, yreg);
10781       macro_build (&offset_expr, s2, "p");
10782       break;
10783
10784     case M_BEQ_I:
10785       s = "cmpi";
10786       s2 = "bteqz";
10787       s3 = "x,U";
10788       goto do_branch_i;
10789     case M_BNE_I:
10790       s = "cmpi";
10791       s2 = "btnez";
10792       s3 = "x,U";
10793       goto do_branch_i;
10794     case M_BLT_I:
10795       s = "slti";
10796       s2 = "btnez";
10797       s3 = "x,8";
10798       goto do_branch_i;
10799     case M_BLTU_I:
10800       s = "sltiu";
10801       s2 = "btnez";
10802       s3 = "x,8";
10803       goto do_branch_i;
10804     case M_BLE_I:
10805       s = "slti";
10806       s2 = "btnez";
10807       s3 = "x,8";
10808       goto do_addone_branch_i;
10809     case M_BLEU_I:
10810       s = "sltiu";
10811       s2 = "btnez";
10812       s3 = "x,8";
10813       goto do_addone_branch_i;
10814     case M_BGE_I:
10815       s = "slti";
10816       s2 = "bteqz";
10817       s3 = "x,8";
10818       goto do_branch_i;
10819     case M_BGEU_I:
10820       s = "sltiu";
10821       s2 = "bteqz";
10822       s3 = "x,8";
10823       goto do_branch_i;
10824     case M_BGT_I:
10825       s = "slti";
10826       s2 = "bteqz";
10827       s3 = "x,8";
10828       goto do_addone_branch_i;
10829     case M_BGTU_I:
10830       s = "sltiu";
10831       s2 = "bteqz";
10832       s3 = "x,8";
10833
10834     do_addone_branch_i:
10835       if (imm_expr.X_op != O_constant)
10836         as_bad (_("Unsupported large constant"));
10837       ++imm_expr.X_add_number;
10838
10839     do_branch_i:
10840       macro_build (&imm_expr, s, s3, xreg);
10841       macro_build (&offset_expr, s2, "p");
10842       break;
10843
10844     case M_ABS:
10845       expr1.X_add_number = 0;
10846       macro_build (&expr1, "slti", "x,8", yreg);
10847       if (xreg != yreg)
10848         move_register (xreg, yreg);
10849       expr1.X_add_number = 2;
10850       macro_build (&expr1, "bteqz", "p");
10851       macro_build (NULL, "neg", "x,w", xreg, xreg);
10852     }
10853 }
10854
10855 /* UDI immediates.  */
10856 struct mips_immed {
10857   char          type;
10858   unsigned int  shift;
10859   unsigned long mask;
10860   const char *  desc;
10861 };
10862
10863 static const struct mips_immed mips_immed[] = {
10864   { '1',        OP_SH_UDI1,     OP_MASK_UDI1,           0},
10865   { '2',        OP_SH_UDI2,     OP_MASK_UDI2,           0},
10866   { '3',        OP_SH_UDI3,     OP_MASK_UDI3,           0},
10867   { '4',        OP_SH_UDI4,     OP_MASK_UDI4,           0},
10868   { 0,0,0,0 }
10869 };
10870
10871 /* Check whether an odd floating-point register is allowed.  */
10872 static int
10873 mips_oddfpreg_ok (const struct mips_opcode *insn, int argnum)
10874 {
10875   const char *s = insn->name;
10876
10877   if (insn->pinfo == INSN_MACRO)
10878     /* Let a macro pass, we'll catch it later when it is expanded.  */
10879     return 1;
10880
10881   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || (mips_opts.arch == CPU_R5900))
10882     {
10883       /* Allow odd registers for single-precision ops.  */
10884       switch (insn->pinfo & (FP_S | FP_D))
10885         {
10886         case FP_S:
10887         case 0:
10888           return 1;     /* both single precision - ok */
10889         case FP_D:
10890           return 0;     /* both double precision - fail */
10891         default:
10892           break;
10893         }
10894
10895       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
10896       s = strchr (insn->name, '.');
10897       if (argnum == 2)
10898         s = s != NULL ? strchr (s + 1, '.') : NULL;
10899       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
10900     } 
10901
10902   /* Single-precision coprocessor loads and moves are OK too.  */
10903   if ((insn->pinfo & FP_S)
10904       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
10905                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
10906     return 1;
10907
10908   return 0;
10909 }
10910
10911 /* Check if EXPR is a constant between MIN (inclusive) and MAX (exclusive)
10912    taking bits from BIT up.  */
10913 static int
10914 expr_const_in_range (expressionS *ep, offsetT min, offsetT max, int bit)
10915 {
10916   return (ep->X_op == O_constant
10917           && (ep->X_add_number & ((1 << bit) - 1)) == 0
10918           && ep->X_add_number >= min << bit
10919           && ep->X_add_number < max << bit);
10920 }
10921
10922 /* Assemble an instruction into its binary format.  If the instruction
10923    is a macro, set imm_expr, imm2_expr and offset_expr to the values
10924    associated with "I", "+I" and "A" operands respectively.  Otherwise
10925    store the value of the relocatable field (if any) in offset_expr.
10926    In both cases set offset_reloc to the relocation operators applied
10927    to offset_expr.  */
10928
10929 static void
10930 mips_ip (char *str, struct mips_cl_insn *ip)
10931 {
10932   bfd_boolean wrong_delay_slot_insns = FALSE;
10933   bfd_boolean need_delay_slot_ok = TRUE;
10934   struct mips_opcode *firstinsn = NULL;
10935   const struct mips_opcode *past;
10936   struct hash_control *hash;
10937   char *s;
10938   const char *args;
10939   char c = 0;
10940   struct mips_opcode *insn;
10941   char *argsStart;
10942   unsigned int regno, regno2;
10943   unsigned int lastregno;
10944   unsigned int destregno = 0;
10945   unsigned int lastpos = 0;
10946   unsigned int limlo, limhi;
10947   int sizelo;
10948   char *s_reset;
10949   offsetT min_range, max_range;
10950   long opend;
10951   char *name;
10952   int argnum;
10953   unsigned int rtype;
10954   char *dot;
10955   long end;
10956
10957   insn_error = NULL;
10958
10959   if (mips_opts.micromips)
10960     {
10961       hash = micromips_op_hash;
10962       past = &micromips_opcodes[bfd_micromips_num_opcodes];
10963     }
10964   else
10965     {
10966       hash = op_hash;
10967       past = &mips_opcodes[NUMOPCODES];
10968     }
10969   forced_insn_length = 0;
10970   insn = NULL;
10971
10972   /* We first try to match an instruction up to a space or to the end.  */
10973   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
10974     continue;
10975
10976   /* Make a copy of the instruction so that we can fiddle with it.  */
10977   name = alloca (end + 1);
10978   memcpy (name, str, end);
10979   name[end] = '\0';
10980
10981   for (;;)
10982     {
10983       insn = (struct mips_opcode *) hash_find (hash, name);
10984
10985       if (insn != NULL || !mips_opts.micromips)
10986         break;
10987       if (forced_insn_length)
10988         break;
10989
10990       /* See if there's an instruction size override suffix,
10991          either `16' or `32', at the end of the mnemonic proper,
10992          that defines the operation, i.e. before the first `.'
10993          character if any.  Strip it and retry.  */
10994       dot = strchr (name, '.');
10995       opend = dot != NULL ? dot - name : end;
10996       if (opend < 3)
10997         break;
10998       if (name[opend - 2] == '1' && name[opend - 1] == '6')
10999         forced_insn_length = 2;
11000       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
11001         forced_insn_length = 4;
11002       else
11003         break;
11004       memcpy (name + opend - 2, name + opend, end - opend + 1);
11005     }
11006   if (insn == NULL)
11007     {
11008       insn_error = _("Unrecognized opcode");
11009       return;
11010     }
11011
11012   /* For microMIPS instructions placed in a fixed-length branch delay slot
11013      we make up to two passes over the relevant fragment of the opcode
11014      table.  First we try instructions that meet the delay slot's length
11015      requirement.  If none matched, then we retry with the remaining ones
11016      and if one matches, then we use it and then issue an appropriate
11017      warning later on.  */
11018   argsStart = s = str + end;
11019   for (;;)
11020     {
11021       bfd_boolean delay_slot_ok;
11022       bfd_boolean size_ok;
11023       bfd_boolean ok;
11024
11025       gas_assert (strcmp (insn->name, name) == 0);
11026
11027       ok = is_opcode_valid (insn);
11028       size_ok = is_size_valid (insn);
11029       delay_slot_ok = is_delay_slot_valid (insn);
11030       if (!delay_slot_ok && !wrong_delay_slot_insns)
11031         {
11032           firstinsn = insn;
11033           wrong_delay_slot_insns = TRUE;
11034         }
11035       if (!ok || !size_ok || delay_slot_ok != need_delay_slot_ok)
11036         {
11037           static char buf[256];
11038
11039           if (insn + 1 < past && strcmp (insn->name, insn[1].name) == 0)
11040             {
11041               ++insn;
11042               continue;
11043             }
11044           if (wrong_delay_slot_insns && need_delay_slot_ok)
11045             {
11046               gas_assert (firstinsn);
11047               need_delay_slot_ok = FALSE;
11048               past = insn + 1;
11049               insn = firstinsn;
11050               continue;
11051             }
11052
11053           if (insn_error)
11054             return;
11055
11056           if (!ok)
11057             sprintf (buf, _("Opcode not supported on this processor: %s (%s)"),
11058                      mips_cpu_info_from_arch (mips_opts.arch)->name,
11059                      mips_cpu_info_from_isa (mips_opts.isa)->name);
11060           else if (mips_opts.insn32)
11061             sprintf (buf, _("Opcode not supported in the `insn32' mode"));
11062           else
11063             sprintf (buf, _("Unrecognized %u-bit version of microMIPS opcode"),
11064                      8 * forced_insn_length);
11065           insn_error = buf;
11066
11067           return;
11068         }
11069
11070       imm_expr.X_op = O_absent;
11071       imm2_expr.X_op = O_absent;
11072       offset_expr.X_op = O_absent;
11073       offset_reloc[0] = BFD_RELOC_UNUSED;
11074       offset_reloc[1] = BFD_RELOC_UNUSED;
11075       offset_reloc[2] = BFD_RELOC_UNUSED;
11076
11077       create_insn (ip, insn);
11078       insn_error = NULL;
11079       argnum = 1;
11080       lastregno = 0xffffffff;
11081       for (args = insn->args;; ++args)
11082         {
11083           int is_mdmx;
11084
11085           s += strspn (s, " \t");
11086           is_mdmx = 0;
11087           switch (*args)
11088             {
11089             case '\0':          /* end of args */
11090               if (*s == '\0')
11091                 return;
11092               break;
11093
11094             case '2':
11095               /* DSP 2-bit unsigned immediate in bit 11 (for standard MIPS
11096                  code) or 14 (for microMIPS code).  */
11097               my_getExpression (&imm_expr, s);
11098               check_absolute_expr (ip, &imm_expr);
11099               if ((unsigned long) imm_expr.X_add_number != 1
11100                   && (unsigned long) imm_expr.X_add_number != 3)
11101                 {
11102                   as_bad (_("BALIGN immediate not 1 or 3 (%lu)"),
11103                           (unsigned long) imm_expr.X_add_number);
11104                 }
11105               INSERT_OPERAND (mips_opts.micromips,
11106                               BP, *ip, imm_expr.X_add_number);
11107               imm_expr.X_op = O_absent;
11108               s = expr_end;
11109               continue;
11110
11111             case '3':
11112               /* DSP 3-bit unsigned immediate in bit 21 (for standard MIPS
11113                  code) or 13 (for microMIPS code).  */
11114               {
11115                 unsigned long mask = (mips_opts.micromips
11116                                       ? MICROMIPSOP_MASK_SA3 : OP_MASK_SA3);
11117
11118                 my_getExpression (&imm_expr, s);
11119                 check_absolute_expr (ip, &imm_expr);
11120                 if ((unsigned long) imm_expr.X_add_number > mask)
11121                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11122                           mask, (unsigned long) imm_expr.X_add_number);
11123                 INSERT_OPERAND (mips_opts.micromips,
11124                                 SA3, *ip, imm_expr.X_add_number);
11125                 imm_expr.X_op = O_absent;
11126                 s = expr_end;
11127               }
11128               continue;
11129
11130             case '4':
11131               /* DSP 4-bit unsigned immediate in bit 21 (for standard MIPS
11132                  code) or 12 (for microMIPS code).  */
11133               {
11134                 unsigned long mask = (mips_opts.micromips
11135                                       ? MICROMIPSOP_MASK_SA4 : OP_MASK_SA4);
11136
11137                 my_getExpression (&imm_expr, s);
11138                 check_absolute_expr (ip, &imm_expr);
11139                 if ((unsigned long) imm_expr.X_add_number > mask)
11140                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11141                           mask, (unsigned long) imm_expr.X_add_number);
11142                 INSERT_OPERAND (mips_opts.micromips,
11143                                 SA4, *ip, imm_expr.X_add_number);
11144                 imm_expr.X_op = O_absent;
11145                 s = expr_end;
11146               }
11147               continue;
11148
11149             case '5':
11150               /* DSP 8-bit unsigned immediate in bit 16 (for standard MIPS
11151                  code) or 13 (for microMIPS code).  */
11152               {
11153                 unsigned long mask = (mips_opts.micromips
11154                                       ? MICROMIPSOP_MASK_IMM8 : OP_MASK_IMM8);
11155
11156                 my_getExpression (&imm_expr, s);
11157                 check_absolute_expr (ip, &imm_expr);
11158                 if ((unsigned long) imm_expr.X_add_number > mask)
11159                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11160                           mask, (unsigned long) imm_expr.X_add_number);
11161                 INSERT_OPERAND (mips_opts.micromips,
11162                                 IMM8, *ip, imm_expr.X_add_number);
11163                 imm_expr.X_op = O_absent;
11164                 s = expr_end;
11165               }
11166               continue;
11167
11168             case '6':
11169               /* DSP 5-bit unsigned immediate in bit 21 (for standard MIPS
11170                  code) or 16 (for microMIPS code).  */
11171               {
11172                 unsigned long mask = (mips_opts.micromips
11173                                       ? MICROMIPSOP_MASK_RS : OP_MASK_RS);
11174
11175                 my_getExpression (&imm_expr, s);
11176                 check_absolute_expr (ip, &imm_expr);
11177                 if ((unsigned long) imm_expr.X_add_number > mask)
11178                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11179                           mask, (unsigned long) imm_expr.X_add_number);
11180                 INSERT_OPERAND (mips_opts.micromips,
11181                                 RS, *ip, imm_expr.X_add_number);
11182                 imm_expr.X_op = O_absent;
11183                 s = expr_end;
11184               }
11185               continue;
11186
11187             case '7':
11188               /* Four DSP accumulators in bit 11 (for standard MIPS code)
11189                  or 14 (for microMIPS code).  */
11190               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11191                   && s[3] >= '0' && s[3] <= '3')
11192                 {
11193                   regno = s[3] - '0';
11194                   s += 4;
11195                   INSERT_OPERAND (mips_opts.micromips, DSPACC, *ip, regno);
11196                   continue;
11197                 }
11198               else
11199                 as_bad (_("Invalid dsp acc register"));
11200               break;
11201
11202             case '8':
11203               /* DSP 6-bit unsigned immediate in bit 11 (for standard MIPS
11204                  code) or 14 (for microMIPS code).  */
11205               {
11206                 unsigned long mask = (mips_opts.micromips
11207                                       ? MICROMIPSOP_MASK_WRDSP
11208                                       : OP_MASK_WRDSP);
11209
11210                 my_getExpression (&imm_expr, s);
11211                 check_absolute_expr (ip, &imm_expr);
11212                 if ((unsigned long) imm_expr.X_add_number > mask)
11213                   as_bad (_("DSP immediate not in range 0..%lu (%lu)"),
11214                           mask, (unsigned long) imm_expr.X_add_number);
11215                 INSERT_OPERAND (mips_opts.micromips,
11216                                 WRDSP, *ip, imm_expr.X_add_number);
11217                 imm_expr.X_op = O_absent;
11218                 s = expr_end;
11219               }
11220               continue;
11221
11222             case '9': /* Four DSP accumulators in bits 21,22.  */
11223               gas_assert (!mips_opts.micromips);
11224               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c'
11225                   && s[3] >= '0' && s[3] <= '3')
11226                 {
11227                   regno = s[3] - '0';
11228                   s += 4;
11229                   INSERT_OPERAND (0, DSPACC_S, *ip, regno);
11230                   continue;
11231                 }
11232               else
11233                 as_bad (_("Invalid dsp acc register"));
11234               break;
11235
11236             case '0':
11237               /* DSP 6-bit signed immediate in bit 20 (for standard MIPS
11238                  code) or 16 (for microMIPS code).  */
11239               {
11240                 long mask = (mips_opts.micromips
11241                              ? MICROMIPSOP_MASK_DSPSFT : OP_MASK_DSPSFT);
11242
11243                 my_getExpression (&imm_expr, s);
11244                 check_absolute_expr (ip, &imm_expr);
11245                 min_range = -((mask + 1) >> 1);
11246                 max_range = ((mask + 1) >> 1) - 1;
11247                 if (imm_expr.X_add_number < min_range
11248                     || imm_expr.X_add_number > max_range)
11249                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11250                           (long) min_range, (long) max_range,
11251                           (long) imm_expr.X_add_number);
11252                 INSERT_OPERAND (mips_opts.micromips,
11253                                 DSPSFT, *ip, imm_expr.X_add_number);
11254                 imm_expr.X_op = O_absent;
11255                 s = expr_end;
11256               }
11257               continue;
11258
11259             case '\'': /* DSP 6-bit unsigned immediate in bit 16.  */
11260               gas_assert (!mips_opts.micromips);
11261               my_getExpression (&imm_expr, s);
11262               check_absolute_expr (ip, &imm_expr);
11263               if (imm_expr.X_add_number & ~OP_MASK_RDDSP)
11264                 {
11265                   as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11266                           OP_MASK_RDDSP,
11267                           (unsigned long) imm_expr.X_add_number);
11268                 }
11269               INSERT_OPERAND (0, RDDSP, *ip, imm_expr.X_add_number);
11270               imm_expr.X_op = O_absent;
11271               s = expr_end;
11272               continue;
11273
11274             case ':': /* DSP 7-bit signed immediate in bit 19.  */
11275               gas_assert (!mips_opts.micromips);
11276               my_getExpression (&imm_expr, s);
11277               check_absolute_expr (ip, &imm_expr);
11278               min_range = -((OP_MASK_DSPSFT_7 + 1) >> 1);
11279               max_range = ((OP_MASK_DSPSFT_7 + 1) >> 1) - 1;
11280               if (imm_expr.X_add_number < min_range ||
11281                   imm_expr.X_add_number > max_range)
11282                 {
11283                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11284                           (long) min_range, (long) max_range,
11285                           (long) imm_expr.X_add_number);
11286                 }
11287               INSERT_OPERAND (0, DSPSFT_7, *ip, imm_expr.X_add_number);
11288               imm_expr.X_op = O_absent;
11289               s = expr_end;
11290               continue;
11291
11292             case '@': /* DSP 10-bit signed immediate in bit 16.  */
11293               {
11294                 long mask = (mips_opts.micromips
11295                              ? MICROMIPSOP_MASK_IMM10 : OP_MASK_IMM10);
11296
11297                 my_getExpression (&imm_expr, s);
11298                 check_absolute_expr (ip, &imm_expr);
11299                 min_range = -((mask + 1) >> 1);
11300                 max_range = ((mask + 1) >> 1) - 1;
11301                 if (imm_expr.X_add_number < min_range
11302                     || imm_expr.X_add_number > max_range)
11303                   as_bad (_("DSP immediate not in range %ld..%ld (%ld)"),
11304                           (long) min_range, (long) max_range,
11305                           (long) imm_expr.X_add_number);
11306                 INSERT_OPERAND (mips_opts.micromips,
11307                                 IMM10, *ip, imm_expr.X_add_number);
11308                 imm_expr.X_op = O_absent;
11309                 s = expr_end;
11310               }
11311               continue;
11312
11313             case '^': /* DSP 5-bit unsigned immediate in bit 11.  */
11314               gas_assert (mips_opts.micromips);
11315               my_getExpression (&imm_expr, s);
11316               check_absolute_expr (ip, &imm_expr);
11317               if (imm_expr.X_add_number & ~MICROMIPSOP_MASK_RD)
11318                 as_bad (_("DSP immediate not in range 0..%d (%lu)"),
11319                         MICROMIPSOP_MASK_RD,
11320                         (unsigned long) imm_expr.X_add_number);
11321               INSERT_OPERAND (1, RD, *ip, imm_expr.X_add_number);
11322               imm_expr.X_op = O_absent;
11323               s = expr_end;
11324               continue;
11325
11326             case '!': /* MT usermode flag bit.  */
11327               gas_assert (!mips_opts.micromips);
11328               my_getExpression (&imm_expr, s);
11329               check_absolute_expr (ip, &imm_expr);
11330               if (imm_expr.X_add_number & ~OP_MASK_MT_U)
11331                 as_bad (_("MT usermode bit not 0 or 1 (%lu)"),
11332                         (unsigned long) imm_expr.X_add_number);
11333               INSERT_OPERAND (0, MT_U, *ip, imm_expr.X_add_number);
11334               imm_expr.X_op = O_absent;
11335               s = expr_end;
11336               continue;
11337
11338             case '$': /* MT load high flag bit.  */
11339               gas_assert (!mips_opts.micromips);
11340               my_getExpression (&imm_expr, s);
11341               check_absolute_expr (ip, &imm_expr);
11342               if (imm_expr.X_add_number & ~OP_MASK_MT_H)
11343                 as_bad (_("MT load high bit not 0 or 1 (%lu)"),
11344                         (unsigned long) imm_expr.X_add_number);
11345               INSERT_OPERAND (0, MT_H, *ip, imm_expr.X_add_number);
11346               imm_expr.X_op = O_absent;
11347               s = expr_end;
11348               continue;
11349
11350             case '*': /* Four DSP accumulators in bits 18,19.  */
11351               gas_assert (!mips_opts.micromips);
11352               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11353                   s[3] >= '0' && s[3] <= '3')
11354                 {
11355                   regno = s[3] - '0';
11356                   s += 4;
11357                   INSERT_OPERAND (0, MTACC_T, *ip, regno);
11358                   continue;
11359                 }
11360               else
11361                 as_bad (_("Invalid dsp/smartmips acc register"));
11362               break;
11363
11364             case '&': /* Four DSP accumulators in bits 13,14.  */
11365               gas_assert (!mips_opts.micromips);
11366               if (s[0] == '$' && s[1] == 'a' && s[2] == 'c' &&
11367                   s[3] >= '0' && s[3] <= '3')
11368                 {
11369                   regno = s[3] - '0';
11370                   s += 4;
11371                   INSERT_OPERAND (0, MTACC_D, *ip, regno);
11372                   continue;
11373                 }
11374               else
11375                 as_bad (_("Invalid dsp/smartmips acc register"));
11376               break;
11377
11378             case '\\':          /* 3-bit bit position.  */
11379               {
11380                 unsigned long mask = (mips_opts.micromips
11381                                       ? MICROMIPSOP_MASK_3BITPOS
11382                                       : OP_MASK_3BITPOS);
11383
11384                 my_getExpression (&imm_expr, s);
11385                 check_absolute_expr (ip, &imm_expr);
11386                 if ((unsigned long) imm_expr.X_add_number > mask)
11387                   as_warn (_("Bit position for %s not in range 0..%lu (%lu)"),
11388                            ip->insn_mo->name,
11389                            mask, (unsigned long) imm_expr.X_add_number);
11390                 INSERT_OPERAND (mips_opts.micromips,
11391                                 3BITPOS, *ip, imm_expr.X_add_number);
11392                 imm_expr.X_op = O_absent;
11393                 s = expr_end;
11394               }
11395               continue;
11396
11397             case ',':
11398               ++argnum;
11399               if (*s++ == *args)
11400                 continue;
11401               s--;
11402               switch (*++args)
11403                 {
11404                 case 'r':
11405                 case 'v':
11406                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
11407                   continue;
11408
11409                 case 'w':
11410                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
11411                   continue;
11412
11413                 case 'W':
11414                   gas_assert (!mips_opts.micromips);
11415                   INSERT_OPERAND (0, FT, *ip, lastregno);
11416                   continue;
11417
11418                 case 'V':
11419                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
11420                   continue;
11421                 }
11422               break;
11423
11424             case '(':
11425               /* Handle optional base register.
11426                  Either the base register is omitted or
11427                  we must have a left paren.  */
11428               /* This is dependent on the next operand specifier
11429                  is a base register specification.  */
11430               gas_assert (args[1] == 'b'
11431                           || (mips_opts.micromips
11432                               && args[1] == 'm'
11433                               && (args[2] == 'l' || args[2] == 'n'
11434                                   || args[2] == 's' || args[2] == 'a')));
11435               if (*s == '\0' && args[1] == 'b')
11436                 return;
11437               /* Fall through.  */
11438
11439             case ')':           /* These must match exactly.  */
11440               if (*s++ == *args)
11441                 continue;
11442               break;
11443
11444             case '+':           /* Opcode extension character.  */
11445               switch (*++args)
11446                 {
11447                 case '1':       /* UDI immediates.  */
11448                 case '2':
11449                 case '3':
11450                 case '4':
11451                   gas_assert (!mips_opts.micromips);
11452                   {
11453                     const struct mips_immed *imm = mips_immed;
11454
11455                     while (imm->type && imm->type != *args)
11456                       ++imm;
11457                     if (! imm->type)
11458                       abort ();
11459                     my_getExpression (&imm_expr, s);
11460                     check_absolute_expr (ip, &imm_expr);
11461                     if ((unsigned long) imm_expr.X_add_number & ~imm->mask)
11462                       {
11463                         as_warn (_("Illegal %s number (%lu, 0x%lx)"),
11464                                  imm->desc ? imm->desc : ip->insn_mo->name,
11465                                  (unsigned long) imm_expr.X_add_number,
11466                                  (unsigned long) imm_expr.X_add_number);
11467                         imm_expr.X_add_number &= imm->mask;
11468                       }
11469                     ip->insn_opcode |= ((unsigned long) imm_expr.X_add_number
11470                                         << imm->shift);
11471                     imm_expr.X_op = O_absent;
11472                     s = expr_end;
11473                   }
11474                   continue;
11475
11476                 case 'J':               /* 10-bit hypcall code.  */
11477                   gas_assert (!mips_opts.micromips);
11478                   {
11479                     unsigned long mask = OP_MASK_CODE10;
11480
11481                     my_getExpression (&imm_expr, s);
11482                     check_absolute_expr (ip, &imm_expr);
11483                     if ((unsigned long) imm_expr.X_add_number > mask)
11484                       as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11485                                ip->insn_mo->name,
11486                                mask, (unsigned long) imm_expr.X_add_number);
11487                     INSERT_OPERAND (0, CODE10, *ip, imm_expr.X_add_number);
11488                     imm_expr.X_op = O_absent;
11489                     s = expr_end;
11490                   }
11491                   continue;
11492
11493                 case 'A':               /* ins/ext position, becomes LSB.  */
11494                   limlo = 0;
11495                   limhi = 31;
11496                   goto do_lsb;
11497                 case 'E':
11498                   limlo = 32;
11499                   limhi = 63;
11500                   goto do_lsb;
11501                 do_lsb:
11502                   my_getExpression (&imm_expr, s);
11503                   check_absolute_expr (ip, &imm_expr);
11504                   if ((unsigned long) imm_expr.X_add_number < limlo
11505                       || (unsigned long) imm_expr.X_add_number > limhi)
11506                     {
11507                       as_bad (_("Improper position (%lu)"),
11508                               (unsigned long) imm_expr.X_add_number);
11509                       imm_expr.X_add_number = limlo;
11510                     }
11511                   lastpos = imm_expr.X_add_number;
11512                   INSERT_OPERAND (mips_opts.micromips,
11513                                   EXTLSB, *ip, imm_expr.X_add_number);
11514                   imm_expr.X_op = O_absent;
11515                   s = expr_end;
11516                   continue;
11517
11518                 case 'B':               /* ins size, becomes MSB.  */
11519                   limlo = 1;
11520                   limhi = 32;
11521                   goto do_msb;
11522                 case 'F':
11523                   limlo = 33;
11524                   limhi = 64;
11525                   goto do_msb;
11526                 do_msb:
11527                   my_getExpression (&imm_expr, s);
11528                   check_absolute_expr (ip, &imm_expr);
11529                   /* Check for negative input so that small negative numbers
11530                      will not succeed incorrectly.  The checks against
11531                      (pos+size) transitively check "size" itself,
11532                      assuming that "pos" is reasonable.  */
11533                   if ((long) imm_expr.X_add_number < 0
11534                       || ((unsigned long) imm_expr.X_add_number
11535                           + lastpos) < limlo
11536                       || ((unsigned long) imm_expr.X_add_number
11537                           + lastpos) > limhi)
11538                     {
11539                       as_bad (_("Improper insert size (%lu, position %lu)"),
11540                               (unsigned long) imm_expr.X_add_number,
11541                               (unsigned long) lastpos);
11542                       imm_expr.X_add_number = limlo - lastpos;
11543                     }
11544                   INSERT_OPERAND (mips_opts.micromips, INSMSB, *ip,
11545                                   lastpos + imm_expr.X_add_number - 1);
11546                   imm_expr.X_op = O_absent;
11547                   s = expr_end;
11548                   continue;
11549
11550                 case 'C':               /* ext size, becomes MSBD.  */
11551                   limlo = 1;
11552                   limhi = 32;
11553                   sizelo = 1;
11554                   goto do_msbd;
11555                 case 'G':
11556                   limlo = 33;
11557                   limhi = 64;
11558                   sizelo = 33;
11559                   goto do_msbd;
11560                 case 'H':
11561                   limlo = 33;
11562                   limhi = 64;
11563                   sizelo = 1;
11564                   goto do_msbd;
11565                 do_msbd:
11566                   my_getExpression (&imm_expr, s);
11567                   check_absolute_expr (ip, &imm_expr);
11568                   /* The checks against (pos+size) don't transitively check
11569                      "size" itself, assuming that "pos" is reasonable.
11570                      We also need to check the lower bound of "size".  */
11571                   if ((long) imm_expr.X_add_number < sizelo
11572                       || ((unsigned long) imm_expr.X_add_number
11573                           + lastpos) < limlo
11574                       || ((unsigned long) imm_expr.X_add_number
11575                           + lastpos) > limhi)
11576                     {
11577                       as_bad (_("Improper extract size (%lu, position %lu)"),
11578                               (unsigned long) imm_expr.X_add_number,
11579                               (unsigned long) lastpos);
11580                       imm_expr.X_add_number = limlo - lastpos;
11581                     }
11582                   INSERT_OPERAND (mips_opts.micromips,
11583                                   EXTMSBD, *ip, imm_expr.X_add_number - 1);
11584                   imm_expr.X_op = O_absent;
11585                   s = expr_end;
11586                   continue;
11587
11588                 case 'I':
11589                   /* "+I" is like "I", except that imm2_expr is used.  */
11590                   my_getExpression (&imm2_expr, s);
11591                   if (imm2_expr.X_op != O_big
11592                       && imm2_expr.X_op != O_constant)
11593                   insn_error = _("absolute expression required");
11594                   if (HAVE_32BIT_GPRS)
11595                     normalize_constant_expr (&imm2_expr);
11596                   s = expr_end;
11597                   continue;
11598
11599                 case 't': /* Coprocessor register number.  */
11600                   gas_assert (!mips_opts.micromips);
11601                   if (s[0] == '$' && ISDIGIT (s[1]))
11602                     {
11603                       ++s;
11604                       regno = 0;
11605                       do
11606                         {
11607                           regno *= 10;
11608                           regno += *s - '0';
11609                           ++s;
11610                         }
11611                       while (ISDIGIT (*s));
11612                       if (regno > 31)
11613                         as_bad (_("Invalid register number (%d)"), regno);
11614                       else
11615                         {
11616                           INSERT_OPERAND (0, RT, *ip, regno);
11617                           continue;
11618                         }
11619                     }
11620                   else
11621                     as_bad (_("Invalid coprocessor 0 register number"));
11622                   break;
11623
11624                 case 'x':
11625                   /* bbit[01] and bbit[01]32 bit index.  Give error if index
11626                      is not in the valid range.  */
11627                   gas_assert (!mips_opts.micromips);
11628                   my_getExpression (&imm_expr, s);
11629                   check_absolute_expr (ip, &imm_expr);
11630                   if ((unsigned) imm_expr.X_add_number > 31)
11631                     {
11632                       as_bad (_("Improper bit index (%lu)"),
11633                               (unsigned long) imm_expr.X_add_number);
11634                       imm_expr.X_add_number = 0;
11635                     }
11636                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number);
11637                   imm_expr.X_op = O_absent;
11638                   s = expr_end;
11639                   continue;
11640
11641                 case 'X':
11642                   /* bbit[01] bit index when bbit is used but we generate
11643                      bbit[01]32 because the index is over 32.  Move to the
11644                      next candidate if index is not in the valid range.  */
11645                   gas_assert (!mips_opts.micromips);
11646                   my_getExpression (&imm_expr, s);
11647                   check_absolute_expr (ip, &imm_expr);
11648                   if ((unsigned) imm_expr.X_add_number < 32
11649                       || (unsigned) imm_expr.X_add_number > 63)
11650                     break;
11651                   INSERT_OPERAND (0, BBITIND, *ip, imm_expr.X_add_number - 32);
11652                   imm_expr.X_op = O_absent;
11653                   s = expr_end;
11654                   continue;
11655
11656                 case 'p':
11657                   /* cins, cins32, exts and exts32 position field.  Give error
11658                      if it's not in the valid range.  */
11659                   gas_assert (!mips_opts.micromips);
11660                   my_getExpression (&imm_expr, s);
11661                   check_absolute_expr (ip, &imm_expr);
11662                   if ((unsigned) imm_expr.X_add_number > 31)
11663                     {
11664                       as_bad (_("Improper position (%lu)"),
11665                               (unsigned long) imm_expr.X_add_number);
11666                       imm_expr.X_add_number = 0;
11667                     }
11668                   lastpos = imm_expr.X_add_number;
11669                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number);
11670                   imm_expr.X_op = O_absent;
11671                   s = expr_end;
11672                   continue;
11673
11674                 case 'P':
11675                   /* cins, cins32, exts and exts32 position field.  Move to
11676                      the next candidate if it's not in the valid range.  */
11677                   gas_assert (!mips_opts.micromips);
11678                   my_getExpression (&imm_expr, s);
11679                   check_absolute_expr (ip, &imm_expr);
11680                   if ((unsigned) imm_expr.X_add_number < 32
11681                       || (unsigned) imm_expr.X_add_number > 63)
11682                     break;
11683                   lastpos = imm_expr.X_add_number;
11684                   INSERT_OPERAND (0, CINSPOS, *ip, imm_expr.X_add_number - 32);
11685                   imm_expr.X_op = O_absent;
11686                   s = expr_end;
11687                   continue;
11688
11689                 case 's':
11690                   /* cins32 and exts32 length-minus-one field.  */
11691                   gas_assert (!mips_opts.micromips);
11692                   my_getExpression (&imm_expr, s);
11693                   check_absolute_expr (ip, &imm_expr);
11694                   if ((unsigned long) imm_expr.X_add_number > 31
11695                       || (unsigned long) imm_expr.X_add_number + lastpos > 31)
11696                     {
11697                       as_bad (_("Improper size (%lu)"),
11698                               (unsigned long) imm_expr.X_add_number);
11699                       imm_expr.X_add_number = 0;
11700                     }
11701                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11702                   imm_expr.X_op = O_absent;
11703                   s = expr_end;
11704                   continue;
11705
11706                 case 'S':
11707                   /* cins/exts length-minus-one field.  */
11708                   gas_assert (!mips_opts.micromips);
11709                   my_getExpression (&imm_expr, s);
11710                   check_absolute_expr (ip, &imm_expr);
11711                   if ((unsigned long) imm_expr.X_add_number > 31
11712                       || (unsigned long) imm_expr.X_add_number + lastpos > 63)
11713                     {
11714                       as_bad (_("Improper size (%lu)"),
11715                               (unsigned long) imm_expr.X_add_number);
11716                       imm_expr.X_add_number = 0;
11717                     }
11718                   INSERT_OPERAND (0, CINSLM1, *ip, imm_expr.X_add_number);
11719                   imm_expr.X_op = O_absent;
11720                   s = expr_end;
11721                   continue;
11722
11723                 case 'Q':
11724                   /* seqi/snei immediate field.  */
11725                   gas_assert (!mips_opts.micromips);
11726                   my_getExpression (&imm_expr, s);
11727                   check_absolute_expr (ip, &imm_expr);
11728                   if ((long) imm_expr.X_add_number < -512
11729                       || (long) imm_expr.X_add_number >= 512)
11730                     {
11731                       as_bad (_("Improper immediate (%ld)"),
11732                                (long) imm_expr.X_add_number);
11733                       imm_expr.X_add_number = 0;
11734                     }
11735                   INSERT_OPERAND (0, SEQI, *ip, imm_expr.X_add_number);
11736                   imm_expr.X_op = O_absent;
11737                   s = expr_end;
11738                   continue;
11739
11740                 case 'a': /* 8-bit signed offset in bit 6 */
11741                   gas_assert (!mips_opts.micromips);
11742                   my_getExpression (&imm_expr, s);
11743                   check_absolute_expr (ip, &imm_expr);
11744                   min_range = -((OP_MASK_OFFSET_A + 1) >> 1);
11745                   max_range = ((OP_MASK_OFFSET_A + 1) >> 1) - 1;
11746                   if (imm_expr.X_add_number < min_range
11747                       || imm_expr.X_add_number > max_range)
11748                     {
11749                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11750                               (long) min_range, (long) max_range,
11751                               (long) imm_expr.X_add_number);
11752                     }
11753                   INSERT_OPERAND (0, OFFSET_A, *ip, imm_expr.X_add_number);
11754                   imm_expr.X_op = O_absent;
11755                   s = expr_end;
11756                   continue;
11757
11758                 case 'b': /* 8-bit signed offset in bit 3 */
11759                   gas_assert (!mips_opts.micromips);
11760                   my_getExpression (&imm_expr, s);
11761                   check_absolute_expr (ip, &imm_expr);
11762                   min_range = -((OP_MASK_OFFSET_B + 1) >> 1);
11763                   max_range = ((OP_MASK_OFFSET_B + 1) >> 1) - 1;
11764                   if (imm_expr.X_add_number < min_range
11765                       || imm_expr.X_add_number > max_range)
11766                     {
11767                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11768                               (long) min_range, (long) max_range,
11769                               (long) imm_expr.X_add_number);
11770                     }
11771                   INSERT_OPERAND (0, OFFSET_B, *ip, imm_expr.X_add_number);
11772                   imm_expr.X_op = O_absent;
11773                   s = expr_end;
11774                   continue;
11775
11776                 case 'c': /* 9-bit signed offset in bit 6 */
11777                   gas_assert (!mips_opts.micromips);
11778                   my_getExpression (&imm_expr, s);
11779                   check_absolute_expr (ip, &imm_expr);
11780                   min_range = -((OP_MASK_OFFSET_C + 1) >> 1);
11781                   max_range = ((OP_MASK_OFFSET_C + 1) >> 1) - 1;
11782                   /* We check the offset range before adjusted.  */
11783                   min_range <<= 4;
11784                   max_range <<= 4;
11785                   if (imm_expr.X_add_number < min_range
11786                       || imm_expr.X_add_number > max_range)
11787                     {
11788                       as_bad (_("Offset not in range %ld..%ld (%ld)"),
11789                               (long) min_range, (long) max_range,
11790                               (long) imm_expr.X_add_number);
11791                     }
11792                   if (imm_expr.X_add_number & 0xf)
11793                     {
11794                       as_bad (_("Offset not 16 bytes alignment (%ld)"),
11795                               (long) imm_expr.X_add_number);
11796                     }
11797                   /* Right shift 4 bits to adjust the offset operand.  */
11798                   INSERT_OPERAND (0, OFFSET_C, *ip,
11799                                   imm_expr.X_add_number >> 4);
11800                   imm_expr.X_op = O_absent;
11801                   s = expr_end;
11802                   continue;
11803
11804                 case 'z':
11805                   gas_assert (!mips_opts.micromips);
11806                   if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
11807                     break;
11808                   if (regno == AT && mips_opts.at)
11809                     {
11810                       if (mips_opts.at == ATREG)
11811                         as_warn (_("used $at without \".set noat\""));
11812                       else
11813                         as_warn (_("used $%u with \".set at=$%u\""),
11814                                  regno, mips_opts.at);
11815                     }
11816                   INSERT_OPERAND (0, RZ, *ip, regno);
11817                   continue;
11818
11819                 case 'Z':
11820                   gas_assert (!mips_opts.micromips);
11821                   if (!reg_lookup (&s, RTYPE_FPU, &regno))
11822                     break;
11823                   INSERT_OPERAND (0, FZ, *ip, regno);
11824                   continue;
11825
11826                 case 'i':
11827                   goto jump;
11828
11829                 case 'j':
11830                   {
11831                     int shift = 8;
11832                     size_t i;
11833                     bfd_reloc_code_real_type r[3];
11834
11835                     /* Check whether there is only a single bracketed expression
11836                        left.  If so, it must be the base register and the
11837                        constant must be zero.  */
11838                     if (*s == '(' && strchr (s + 1, '(') == 0)
11839                       continue;
11840
11841                     /* If this value won't fit into the offset, then go find
11842                        a macro that will generate a 16- or 32-bit offset code
11843                        pattern.  */
11844                     i = my_getSmallExpression (&imm_expr, r, s);
11845                     if ((i == 0 && (imm_expr.X_op != O_constant
11846                                     || imm_expr.X_add_number >= 1 << shift
11847                                     || imm_expr.X_add_number < -1 << shift))
11848                         || i > 0)
11849                       {
11850                         imm_expr.X_op = O_absent;
11851                         break;
11852                       }
11853                     INSERT_OPERAND (mips_opts.micromips, EVAOFFSET, *ip,
11854                                     imm_expr.X_add_number);
11855                     imm_expr.X_op = O_absent;
11856                     s = expr_end;
11857                   }
11858                   continue;
11859
11860                 default:
11861                   as_bad (_("Internal error: bad %s opcode "
11862                             "(unknown extension operand type `+%c'): %s %s"),
11863                           mips_opts.micromips ? "microMIPS" : "MIPS",
11864                           *args, insn->name, insn->args);
11865                   /* Further processing is fruitless.  */
11866                   return;
11867                 }
11868               break;
11869
11870             case '.':           /* 10-bit offset.  */
11871               gas_assert (mips_opts.micromips);
11872             case '~':           /* 12-bit offset.  */
11873               {
11874                 int shift = *args == '.' ? 9 : 11;
11875                 size_t i;
11876                 bfd_reloc_code_real_type r[3];
11877
11878                 /* Check whether there is only a single bracketed expression
11879                    left.  If so, it must be the base register and the
11880                    constant must be zero.  */
11881                 if (*s == '(' && strchr (s + 1, '(') == 0)
11882                   continue;
11883
11884                 /* If this value won't fit into the offset, then go find
11885                    a macro that will generate a 16- or 32-bit offset code
11886                    pattern.  */
11887                 i = my_getSmallExpression (&imm_expr, r, s);
11888                 if ((i == 0 && (imm_expr.X_op != O_constant
11889                                 || imm_expr.X_add_number >= 1 << shift
11890                                 || imm_expr.X_add_number < -1 << shift))
11891                     || i > 0)
11892                   {
11893                     imm_expr.X_op = O_absent;
11894                     break;
11895                   }
11896                 if (shift == 9)
11897                   INSERT_OPERAND (1, OFFSET10, *ip, imm_expr.X_add_number);
11898                 else
11899                   INSERT_OPERAND (mips_opts.micromips,
11900                                   OFFSET12, *ip, imm_expr.X_add_number);
11901                 imm_expr.X_op = O_absent;
11902                 s = expr_end;
11903               }
11904               continue;
11905
11906             case '<':           /* must be at least one digit */
11907               /*
11908                * According to the manual, if the shift amount is greater
11909                * than 31 or less than 0, then the shift amount should be
11910                * mod 32.  In reality the mips assembler issues an error.
11911                * We issue a warning and mask out all but the low 5 bits.
11912                */
11913               my_getExpression (&imm_expr, s);
11914               check_absolute_expr (ip, &imm_expr);
11915               if ((unsigned long) imm_expr.X_add_number > 31)
11916                 as_warn (_("Improper shift amount (%lu)"),
11917                          (unsigned long) imm_expr.X_add_number);
11918               INSERT_OPERAND (mips_opts.micromips,
11919                               SHAMT, *ip, imm_expr.X_add_number);
11920               imm_expr.X_op = O_absent;
11921               s = expr_end;
11922               continue;
11923
11924             case '>':           /* shift amount minus 32 */
11925               my_getExpression (&imm_expr, s);
11926               check_absolute_expr (ip, &imm_expr);
11927               if ((unsigned long) imm_expr.X_add_number < 32
11928                   || (unsigned long) imm_expr.X_add_number > 63)
11929                 break;
11930               INSERT_OPERAND (mips_opts.micromips,
11931                               SHAMT, *ip, imm_expr.X_add_number - 32);
11932               imm_expr.X_op = O_absent;
11933               s = expr_end;
11934               continue;
11935
11936             case 'k':           /* CACHE code.  */
11937             case 'h':           /* PREFX code.  */
11938             case '1':           /* SYNC type.  */
11939               my_getExpression (&imm_expr, s);
11940               check_absolute_expr (ip, &imm_expr);
11941               if ((unsigned long) imm_expr.X_add_number > 31)
11942                 as_warn (_("Invalid value for `%s' (%lu)"),
11943                          ip->insn_mo->name,
11944                          (unsigned long) imm_expr.X_add_number);
11945               switch (*args)
11946                 {
11947                 case 'k':
11948                   if (mips_fix_cn63xxp1
11949                       && !mips_opts.micromips
11950                       && strcmp ("pref", insn->name) == 0)
11951                     switch (imm_expr.X_add_number)
11952                       {
11953                       case 5:
11954                       case 25:
11955                       case 26:
11956                       case 27:
11957                       case 28:
11958                       case 29:
11959                       case 30:
11960                       case 31:  /* These are ok.  */
11961                         break;
11962
11963                       default:  /* The rest must be changed to 28.  */
11964                         imm_expr.X_add_number = 28;
11965                         break;
11966                       }
11967                   INSERT_OPERAND (mips_opts.micromips,
11968                                   CACHE, *ip, imm_expr.X_add_number);
11969                   break;
11970                 case 'h':
11971                   INSERT_OPERAND (mips_opts.micromips,
11972                                   PREFX, *ip, imm_expr.X_add_number);
11973                   break;
11974                 case '1':
11975                   INSERT_OPERAND (mips_opts.micromips,
11976                                   STYPE, *ip, imm_expr.X_add_number);
11977                   break;
11978                 }
11979               imm_expr.X_op = O_absent;
11980               s = expr_end;
11981               continue;
11982
11983             case 'c':           /* BREAK code.  */
11984               {
11985                 unsigned long mask = (mips_opts.micromips
11986                                       ? MICROMIPSOP_MASK_CODE
11987                                       : OP_MASK_CODE);
11988
11989                 my_getExpression (&imm_expr, s);
11990                 check_absolute_expr (ip, &imm_expr);
11991                 if ((unsigned long) imm_expr.X_add_number > mask)
11992                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
11993                            ip->insn_mo->name,
11994                            mask, (unsigned long) imm_expr.X_add_number);
11995                 INSERT_OPERAND (mips_opts.micromips,
11996                                 CODE, *ip, imm_expr.X_add_number);
11997                 imm_expr.X_op = O_absent;
11998                 s = expr_end;
11999               }
12000               continue;
12001
12002             case 'q':           /* Lower BREAK code.  */
12003               {
12004                 unsigned long mask = (mips_opts.micromips
12005                                       ? MICROMIPSOP_MASK_CODE2
12006                                       : OP_MASK_CODE2);
12007
12008                 my_getExpression (&imm_expr, s);
12009                 check_absolute_expr (ip, &imm_expr);
12010                 if ((unsigned long) imm_expr.X_add_number > mask)
12011                   as_warn (_("Lower code for %s not in range 0..%lu (%lu)"),
12012                            ip->insn_mo->name,
12013                            mask, (unsigned long) imm_expr.X_add_number);
12014                 INSERT_OPERAND (mips_opts.micromips,
12015                                 CODE2, *ip, imm_expr.X_add_number);
12016                 imm_expr.X_op = O_absent;
12017                 s = expr_end;
12018               }
12019               continue;
12020
12021             case 'B':           /* 20- or 10-bit syscall/break/wait code.  */
12022               {
12023                 unsigned long mask = (mips_opts.micromips
12024                                       ? MICROMIPSOP_MASK_CODE10
12025                                       : OP_MASK_CODE20);
12026
12027                 my_getExpression (&imm_expr, s);
12028                 check_absolute_expr (ip, &imm_expr);
12029                 if ((unsigned long) imm_expr.X_add_number > mask)
12030                   as_warn (_("Code for %s not in range 0..%lu (%lu)"),
12031                            ip->insn_mo->name,
12032                            mask, (unsigned long) imm_expr.X_add_number);
12033                 if (mips_opts.micromips)
12034                   INSERT_OPERAND (1, CODE10, *ip, imm_expr.X_add_number);
12035                 else
12036                   INSERT_OPERAND (0, CODE20, *ip, imm_expr.X_add_number);
12037                 imm_expr.X_op = O_absent;
12038                 s = expr_end;
12039               }
12040               continue;
12041
12042             case 'C':           /* 25- or 23-bit coprocessor code.  */
12043               {
12044                 unsigned long mask = (mips_opts.micromips
12045                                       ? MICROMIPSOP_MASK_COPZ
12046                                       : OP_MASK_COPZ);
12047
12048                 my_getExpression (&imm_expr, s);
12049                 check_absolute_expr (ip, &imm_expr);
12050                 if ((unsigned long) imm_expr.X_add_number > mask)
12051                   as_warn (_("Coproccesor code > %u bits (%lu)"),
12052                            mips_opts.micromips ? 23U : 25U,
12053                            (unsigned long) imm_expr.X_add_number);
12054                 INSERT_OPERAND (mips_opts.micromips,
12055                                 COPZ, *ip, imm_expr.X_add_number);
12056                 imm_expr.X_op = O_absent;
12057                 s = expr_end;
12058               }
12059               continue;
12060
12061             case 'J':           /* 19-bit WAIT code.  */
12062               gas_assert (!mips_opts.micromips);
12063               my_getExpression (&imm_expr, s);
12064               check_absolute_expr (ip, &imm_expr);
12065               if ((unsigned long) imm_expr.X_add_number > OP_MASK_CODE19)
12066                 {
12067                   as_warn (_("Illegal 19-bit code (%lu)"),
12068                            (unsigned long) imm_expr.X_add_number);
12069                   imm_expr.X_add_number &= OP_MASK_CODE19;
12070                 }
12071               INSERT_OPERAND (0, CODE19, *ip, imm_expr.X_add_number);
12072               imm_expr.X_op = O_absent;
12073               s = expr_end;
12074               continue;
12075
12076             case 'P':           /* Performance register.  */
12077               gas_assert (!mips_opts.micromips);
12078               my_getExpression (&imm_expr, s);
12079               check_absolute_expr (ip, &imm_expr);
12080               if (imm_expr.X_add_number != 0 && imm_expr.X_add_number != 1)
12081                 as_warn (_("Invalid performance register (%lu)"),
12082                          (unsigned long) imm_expr.X_add_number);
12083               if (imm_expr.X_add_number != 0 && mips_opts.arch == CPU_R5900
12084                 && (!strcmp(insn->name,"mfps") || !strcmp(insn->name,"mtps")))
12085                 as_warn (_("Invalid performance register (%lu)"),
12086                   (unsigned long) imm_expr.X_add_number);
12087               INSERT_OPERAND (0, PERFREG, *ip, imm_expr.X_add_number);
12088               imm_expr.X_op = O_absent;
12089               s = expr_end;
12090               continue;
12091
12092             case 'G':           /* Coprocessor destination register.  */
12093               {
12094                 unsigned long opcode = ip->insn_opcode;
12095                 unsigned long mask;
12096                 unsigned int types;
12097                 int cop0;
12098
12099                 if (mips_opts.micromips)
12100                   {
12101                     mask = ~((MICROMIPSOP_MASK_RT << MICROMIPSOP_SH_RT)
12102                              | (MICROMIPSOP_MASK_RS << MICROMIPSOP_SH_RS)
12103                              | (MICROMIPSOP_MASK_SEL << MICROMIPSOP_SH_SEL));
12104                     opcode &= mask;
12105                     switch (opcode)
12106                       {
12107                       case 0x000000fc:                          /* mfc0  */
12108                       case 0x000002fc:                          /* mtc0  */
12109                       case 0x580000fc:                          /* dmfc0 */
12110                       case 0x580002fc:                          /* dmtc0 */
12111                         cop0 = 1;
12112                         break;
12113                       default:
12114                         cop0 = 0;
12115                         break;
12116                       }
12117                   }
12118                 else
12119                   {
12120                     opcode = (opcode >> OP_SH_OP) & OP_MASK_OP;
12121                     cop0 = opcode == OP_OP_COP0;
12122                   }
12123                 types = RTYPE_NUM | (cop0 ? RTYPE_CP0 : RTYPE_GP);
12124                 ok = reg_lookup (&s, types, &regno);
12125                 if (mips_opts.micromips)
12126                   INSERT_OPERAND (1, RS, *ip, regno);
12127                 else
12128                   INSERT_OPERAND (0, RD, *ip, regno);
12129                 if (ok)
12130                   {
12131                     lastregno = regno;
12132                     continue;
12133                   }
12134               }
12135               break;
12136
12137             case 'y':           /* ALNV.PS source register.  */
12138               gas_assert (mips_opts.micromips);
12139               goto do_reg;
12140             case 'x':           /* Ignore register name.  */
12141             case 'U':           /* Destination register (CLO/CLZ).  */
12142             case 'g':           /* Coprocessor destination register.  */
12143               gas_assert (!mips_opts.micromips);
12144             case 'b':           /* Base register.  */
12145             case 'd':           /* Destination register.  */
12146             case 's':           /* Source register.  */
12147             case 't':           /* Target register.  */
12148             case 'r':           /* Both target and source.  */
12149             case 'v':           /* Both dest and source.  */
12150             case 'w':           /* Both dest and target.  */
12151             case 'E':           /* Coprocessor target register.  */
12152             case 'K':           /* RDHWR destination register.  */
12153             case 'z':           /* Must be zero register.  */
12154             do_reg:
12155               s_reset = s;
12156               if (*args == 'E' || *args == 'K')
12157                 ok = reg_lookup (&s, RTYPE_NUM, &regno);
12158               else
12159                 {
12160                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12161                   if (regno == AT && mips_opts.at)
12162                     {
12163                       if (mips_opts.at == ATREG)
12164                         as_warn (_("Used $at without \".set noat\""));
12165                       else
12166                         as_warn (_("Used $%u with \".set at=$%u\""),
12167                                  regno, mips_opts.at);
12168                     }
12169                 }
12170               if (ok)
12171                 {
12172                   c = *args;
12173                   if (*s == ' ')
12174                     ++s;
12175                   if (args[1] != *s)
12176                     {
12177                       if (c == 'r' || c == 'v' || c == 'w')
12178                         {
12179                           regno = lastregno;
12180                           s = s_reset;
12181                           ++args;
12182                         }
12183                     }
12184                   /* 'z' only matches $0.  */
12185                   if (c == 'z' && regno != 0)
12186                     break;
12187
12188                   if (c == 's' && !strncmp (ip->insn_mo->name, "jalr", 4))
12189                     {
12190                       if (regno == lastregno)
12191                         {
12192                           insn_error
12193                             = _("Source and destination must be different");
12194                           continue;
12195                         }
12196                       if (regno == 31 && lastregno == 0xffffffff)
12197                         {
12198                           insn_error
12199                             = _("A destination register must be supplied");
12200                           continue;
12201                         }
12202                     }
12203                   /* Now that we have assembled one operand, we use the args
12204                      string to figure out where it goes in the instruction.  */
12205                   switch (c)
12206                     {
12207                     case 'r':
12208                     case 's':
12209                     case 'v':
12210                     case 'b':
12211                       INSERT_OPERAND (mips_opts.micromips, RS, *ip, regno);
12212                       break;
12213
12214                     case 'K':
12215                       if (mips_opts.micromips)
12216                         INSERT_OPERAND (1, RS, *ip, regno);
12217                       else
12218                         INSERT_OPERAND (0, RD, *ip, regno);
12219                       break;
12220
12221                     case 'd':
12222                     case 'g':
12223                       INSERT_OPERAND (mips_opts.micromips, RD, *ip, regno);
12224                       break;
12225
12226                     case 'U':
12227                       gas_assert (!mips_opts.micromips);
12228                       INSERT_OPERAND (0, RD, *ip, regno);
12229                       INSERT_OPERAND (0, RT, *ip, regno);
12230                       break;
12231
12232                     case 'w':
12233                     case 't':
12234                     case 'E':
12235                       INSERT_OPERAND (mips_opts.micromips, RT, *ip, regno);
12236                       break;
12237
12238                     case 'y':
12239                       gas_assert (mips_opts.micromips);
12240                       INSERT_OPERAND (1, RS3, *ip, regno);
12241                       break;
12242
12243                     case 'x':
12244                       /* This case exists because on the r3000 trunc
12245                          expands into a macro which requires a gp
12246                          register.  On the r6000 or r4000 it is
12247                          assembled into a single instruction which
12248                          ignores the register.  Thus the insn version
12249                          is MIPS_ISA2 and uses 'x', and the macro
12250                          version is MIPS_ISA1 and uses 't'.  */
12251                       break;
12252
12253                     case 'z':
12254                       /* This case is for the div instruction, which
12255                          acts differently if the destination argument
12256                          is $0.  This only matches $0, and is checked
12257                          outside the switch.  */
12258                       break;
12259                     }
12260                   lastregno = regno;
12261                   continue;
12262                 }
12263               switch (*args++)
12264                 {
12265                 case 'r':
12266                 case 'v':
12267                   INSERT_OPERAND (mips_opts.micromips, RS, *ip, lastregno);
12268                   continue;
12269
12270                 case 'w':
12271                   INSERT_OPERAND (mips_opts.micromips, RT, *ip, lastregno);
12272                   continue;
12273                 }
12274               break;
12275
12276             case 'O':           /* MDMX alignment immediate constant.  */
12277               gas_assert (!mips_opts.micromips);
12278               my_getExpression (&imm_expr, s);
12279               check_absolute_expr (ip, &imm_expr);
12280               if ((unsigned long) imm_expr.X_add_number > OP_MASK_ALN)
12281                 as_warn (_("Improper align amount (%ld), using low bits"),
12282                          (long) imm_expr.X_add_number);
12283               INSERT_OPERAND (0, ALN, *ip, imm_expr.X_add_number);
12284               imm_expr.X_op = O_absent;
12285               s = expr_end;
12286               continue;
12287
12288             case 'Q':           /* MDMX vector, element sel, or const.  */
12289               if (s[0] != '$')
12290                 {
12291                   /* MDMX Immediate.  */
12292                   gas_assert (!mips_opts.micromips);
12293                   my_getExpression (&imm_expr, s);
12294                   check_absolute_expr (ip, &imm_expr);
12295                   if ((unsigned long) imm_expr.X_add_number > OP_MASK_FT)
12296                     as_warn (_("Invalid MDMX Immediate (%ld)"),
12297                              (long) imm_expr.X_add_number);
12298                   INSERT_OPERAND (0, FT, *ip, imm_expr.X_add_number);
12299                   if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12300                     ip->insn_opcode |= MDMX_FMTSEL_IMM_QH << OP_SH_VSEL;
12301                   else
12302                     ip->insn_opcode |= MDMX_FMTSEL_IMM_OB << OP_SH_VSEL;
12303                   imm_expr.X_op = O_absent;
12304                   s = expr_end;
12305                   continue;
12306                 }
12307               /* Not MDMX Immediate.  Fall through.  */
12308             case 'X':           /* MDMX destination register.  */
12309             case 'Y':           /* MDMX source register.  */
12310             case 'Z':           /* MDMX target register.  */
12311               is_mdmx = !(insn->membership & INSN_5400);
12312             case 'W':
12313               gas_assert (!mips_opts.micromips);
12314             case 'D':           /* Floating point destination register.  */
12315             case 'S':           /* Floating point source register.  */
12316             case 'T':           /* Floating point target register.  */
12317             case 'R':           /* Floating point source register.  */
12318             case 'V':
12319               rtype = RTYPE_FPU;
12320               if (is_mdmx
12321                   || ((mips_opts.ase & ASE_MDMX)
12322                       && (ip->insn_mo->pinfo & FP_D)
12323                       && (ip->insn_mo->pinfo & (INSN_COPROC_MOVE_DELAY
12324                                                 | INSN_COPROC_MEMORY_DELAY
12325                                                 | INSN_LOAD_COPROC_DELAY
12326                                                 | INSN_LOAD_MEMORY_DELAY
12327                                                 | INSN_STORE_MEMORY))))
12328                 rtype |= RTYPE_VEC;
12329               s_reset = s;
12330               if (reg_lookup (&s, rtype, &regno))
12331                 {
12332                   if ((regno & 1) != 0
12333                       && HAVE_32BIT_FPRS
12334                       && !mips_oddfpreg_ok (ip->insn_mo, argnum))
12335                     as_warn (_("Float register should be even, was %d"),
12336                              regno);
12337
12338                   c = *args;
12339                   if (*s == ' ')
12340                     ++s;
12341                   if (args[1] != *s)
12342                     {
12343                       if (c == 'V' || c == 'W')
12344                         {
12345                           regno = lastregno;
12346                           s = s_reset;
12347                           ++args;
12348                         }
12349                     }
12350                   switch (c)
12351                     {
12352                     case 'D':
12353                     case 'X':
12354                       INSERT_OPERAND (mips_opts.micromips, FD, *ip, regno);
12355                       break;
12356
12357                     case 'V':
12358                     case 'S':
12359                     case 'Y':
12360                       INSERT_OPERAND (mips_opts.micromips, FS, *ip, regno);
12361                       break;
12362
12363                     case 'Q':
12364                       /* This is like 'Z', but also needs to fix the MDMX
12365                          vector/scalar select bits.  Note that the
12366                          scalar immediate case is handled above.  */
12367                       if ((ip->insn_mo->membership & INSN_5400)
12368                           && strcmp (insn->name, "rzu.ob") == 0)
12369                         as_bad (_("Operand %d of `%s' must be an immediate"),
12370                                 argnum, ip->insn_mo->name);
12371
12372                       if (*s == '[')
12373                         {
12374                           int is_qh = (ip->insn_opcode & (1 << OP_SH_VSEL));
12375                           int max_el = (is_qh ? 3 : 7);
12376                           s++;
12377                           my_getExpression(&imm_expr, s);
12378                           check_absolute_expr (ip, &imm_expr);
12379                           s = expr_end;
12380                           if (imm_expr.X_add_number > max_el)
12381                             as_bad (_("Bad element selector %ld"),
12382                                     (long) imm_expr.X_add_number);
12383                           imm_expr.X_add_number &= max_el;
12384                           ip->insn_opcode |= (imm_expr.X_add_number
12385                                               << (OP_SH_VSEL +
12386                                                   (is_qh ? 2 : 1)));
12387                           imm_expr.X_op = O_absent;
12388                           if (*s != ']')
12389                             as_warn (_("Expecting ']' found '%s'"), s);
12390                           else
12391                             s++;
12392                         }
12393                       else
12394                         {
12395                           if ((ip->insn_mo->membership & INSN_5400)
12396                               && (strcmp (insn->name, "sll.ob") == 0
12397                                   || strcmp (insn->name, "srl.ob") == 0))
12398                             as_bad (_("Operand %d of `%s' must be scalar"),
12399                                     argnum, ip->insn_mo->name);
12400
12401                           if (ip->insn_opcode & (OP_MASK_VSEL << OP_SH_VSEL))
12402                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_QH
12403                                                 << OP_SH_VSEL);
12404                           else
12405                             ip->insn_opcode |= (MDMX_FMTSEL_VEC_OB <<
12406                                                 OP_SH_VSEL);
12407                         }
12408                       /* Fall through.  */
12409                     case 'W':
12410                     case 'T':
12411                     case 'Z':
12412                       INSERT_OPERAND (mips_opts.micromips, FT, *ip, regno);
12413                       break;
12414
12415                     case 'R':
12416                       INSERT_OPERAND (mips_opts.micromips, FR, *ip, regno);
12417                       break;
12418                     }
12419                   lastregno = regno;
12420                   continue;
12421                 }
12422
12423               switch (*args++)
12424                 {
12425                 case 'V':
12426                   INSERT_OPERAND (mips_opts.micromips, FS, *ip, lastregno);
12427                   continue;
12428
12429                 case 'W':
12430                   INSERT_OPERAND (mips_opts.micromips, FT, *ip, lastregno);
12431                   continue;
12432                 }
12433               break;
12434
12435             case 'I':
12436               my_getExpression (&imm_expr, s);
12437               if (imm_expr.X_op != O_big
12438                   && imm_expr.X_op != O_constant)
12439                 insn_error = _("absolute expression required");
12440               if (HAVE_32BIT_GPRS)
12441                 normalize_constant_expr (&imm_expr);
12442               s = expr_end;
12443               continue;
12444
12445             case 'A':
12446               my_getSmallExpression (&offset_expr, offset_reloc, s);
12447               if (offset_expr.X_op == O_register)
12448                 {
12449                   /* Assume that the offset has been elided and that what
12450                      we saw was a base register.  The match will fail later
12451                      if that assumption turns out to be wrong.  */
12452                   offset_expr.X_op = O_constant;
12453                   offset_expr.X_add_number = 0;
12454                 }
12455               else
12456                 {
12457                   normalize_address_expr (&offset_expr);
12458                   s = expr_end;
12459                 }
12460               continue;
12461
12462             case 'F':
12463             case 'L':
12464             case 'f':
12465             case 'l':
12466               {
12467                 int f64;
12468                 int using_gprs;
12469                 char *save_in;
12470                 char *err;
12471                 unsigned char temp[8];
12472                 int len;
12473                 unsigned int length;
12474                 segT seg;
12475                 subsegT subseg;
12476                 char *p;
12477
12478                 /* These only appear as the last operand in an
12479                    instruction, and every instruction that accepts
12480                    them in any variant accepts them in all variants.
12481                    This means we don't have to worry about backing out
12482                    any changes if the instruction does not match.
12483
12484                    The difference between them is the size of the
12485                    floating point constant and where it goes.  For 'F'
12486                    and 'L' the constant is 64 bits; for 'f' and 'l' it
12487                    is 32 bits.  Where the constant is placed is based
12488                    on how the MIPS assembler does things:
12489                     F -- .rdata
12490                     L -- .lit8
12491                     f -- immediate value
12492                     l -- .lit4
12493
12494                     The .lit4 and .lit8 sections are only used if
12495                     permitted by the -G argument.
12496
12497                     The code below needs to know whether the target register
12498                     is 32 or 64 bits wide.  It relies on the fact 'f' and
12499                     'F' are used with GPR-based instructions and 'l' and
12500                     'L' are used with FPR-based instructions.  */
12501
12502                 f64 = *args == 'F' || *args == 'L';
12503                 using_gprs = *args == 'F' || *args == 'f';
12504
12505                 save_in = input_line_pointer;
12506                 input_line_pointer = s;
12507                 err = md_atof (f64 ? 'd' : 'f', (char *) temp, &len);
12508                 length = len;
12509                 s = input_line_pointer;
12510                 input_line_pointer = save_in;
12511                 if (err != NULL && *err != '\0')
12512                   {
12513                     as_bad (_("Bad floating point constant: %s"), err);
12514                     memset (temp, '\0', sizeof temp);
12515                     length = f64 ? 8 : 4;
12516                   }
12517
12518                 gas_assert (length == (unsigned) (f64 ? 8 : 4));
12519
12520                 if (*args == 'f'
12521                     || (*args == 'l'
12522                         && (g_switch_value < 4
12523                             || (temp[0] == 0 && temp[1] == 0)
12524                             || (temp[2] == 0 && temp[3] == 0))))
12525                   {
12526                     imm_expr.X_op = O_constant;
12527                     if (!target_big_endian)
12528                       imm_expr.X_add_number = bfd_getl32 (temp);
12529                     else
12530                       imm_expr.X_add_number = bfd_getb32 (temp);
12531                   }
12532                 else if (length > 4
12533                          && !mips_disable_float_construction
12534                          /* Constants can only be constructed in GPRs and
12535                             copied to FPRs if the GPRs are at least as wide
12536                             as the FPRs.  Force the constant into memory if
12537                             we are using 64-bit FPRs but the GPRs are only
12538                             32 bits wide.  */
12539                          && (using_gprs
12540                              || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
12541                          && ((temp[0] == 0 && temp[1] == 0)
12542                              || (temp[2] == 0 && temp[3] == 0))
12543                          && ((temp[4] == 0 && temp[5] == 0)
12544                              || (temp[6] == 0 && temp[7] == 0)))
12545                   {
12546                     /* The value is simple enough to load with a couple of
12547                        instructions.  If using 32-bit registers, set
12548                        imm_expr to the high order 32 bits and offset_expr to
12549                        the low order 32 bits.  Otherwise, set imm_expr to
12550                        the entire 64 bit constant.  */
12551                     if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
12552                       {
12553                         imm_expr.X_op = O_constant;
12554                         offset_expr.X_op = O_constant;
12555                         if (!target_big_endian)
12556                           {
12557                             imm_expr.X_add_number = bfd_getl32 (temp + 4);
12558                             offset_expr.X_add_number = bfd_getl32 (temp);
12559                           }
12560                         else
12561                           {
12562                             imm_expr.X_add_number = bfd_getb32 (temp);
12563                             offset_expr.X_add_number = bfd_getb32 (temp + 4);
12564                           }
12565                         if (offset_expr.X_add_number == 0)
12566                           offset_expr.X_op = O_absent;
12567                       }
12568                     else
12569                       {
12570                         imm_expr.X_op = O_constant;
12571                         if (!target_big_endian)
12572                           imm_expr.X_add_number = bfd_getl64 (temp);
12573                         else
12574                           imm_expr.X_add_number = bfd_getb64 (temp);
12575                       }
12576                   }
12577                 else
12578                   {
12579                     const char *newname;
12580                     segT new_seg;
12581
12582                     /* Switch to the right section.  */
12583                     seg = now_seg;
12584                     subseg = now_subseg;
12585                     switch (*args)
12586                       {
12587                       default: /* unused default case avoids warnings.  */
12588                       case 'L':
12589                         newname = RDATA_SECTION_NAME;
12590                         if (g_switch_value >= 8)
12591                           newname = ".lit8";
12592                         break;
12593                       case 'F':
12594                         newname = RDATA_SECTION_NAME;
12595                         break;
12596                       case 'l':
12597                         gas_assert (g_switch_value >= 4);
12598                         newname = ".lit4";
12599                         break;
12600                       }
12601                     new_seg = subseg_new (newname, (subsegT) 0);
12602                     bfd_set_section_flags (stdoutput, new_seg,
12603                                            (SEC_ALLOC
12604                                             | SEC_LOAD
12605                                             | SEC_READONLY
12606                                             | SEC_DATA));
12607                     frag_align (*args == 'l' ? 2 : 3, 0, 0);
12608                     if (strncmp (TARGET_OS, "elf", 3) != 0)
12609                       record_alignment (new_seg, 4);
12610                     else
12611                       record_alignment (new_seg, *args == 'l' ? 2 : 3);
12612                     if (seg == now_seg)
12613                       as_bad (_("Can't use floating point insn in this section"));
12614
12615                     /* Set the argument to the current address in the
12616                        section.  */
12617                     offset_expr.X_op = O_symbol;
12618                     offset_expr.X_add_symbol = symbol_temp_new_now ();
12619                     offset_expr.X_add_number = 0;
12620
12621                     /* Put the floating point number into the section.  */
12622                     p = frag_more ((int) length);
12623                     memcpy (p, temp, length);
12624
12625                     /* Switch back to the original section.  */
12626                     subseg_set (seg, subseg);
12627                   }
12628               }
12629               continue;
12630
12631             case 'i':           /* 16-bit unsigned immediate.  */
12632             case 'j':           /* 16-bit signed immediate.  */
12633               *offset_reloc = BFD_RELOC_LO16;
12634               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0)
12635                 {
12636                   int more;
12637                   offsetT minval, maxval;
12638
12639                   more = (insn + 1 < past
12640                           && strcmp (insn->name, insn[1].name) == 0);
12641
12642                   /* For compatibility with older assemblers, we accept
12643                      0x8000-0xffff as signed 16-bit numbers when only
12644                      signed numbers are allowed.  */
12645                   if (*args == 'i')
12646                     minval = 0, maxval = 0xffff;
12647                   else if (more)
12648                     minval = -0x8000, maxval = 0x7fff;
12649                   else
12650                     minval = -0x8000, maxval = 0xffff;
12651
12652                   if (offset_expr.X_op != O_constant
12653                       || offset_expr.X_add_number < minval
12654                       || offset_expr.X_add_number > maxval)
12655                     {
12656                       if (more)
12657                         break;
12658                       if (offset_expr.X_op == O_constant
12659                           || offset_expr.X_op == O_big)
12660                         as_bad (_("Expression out of range"));
12661                     }
12662                 }
12663               s = expr_end;
12664               continue;
12665
12666             case 'o':           /* 16-bit offset.  */
12667               offset_reloc[0] = BFD_RELOC_LO16;
12668               offset_reloc[1] = BFD_RELOC_UNUSED;
12669               offset_reloc[2] = BFD_RELOC_UNUSED;
12670
12671               /* Check whether there is only a single bracketed expression
12672                  left.  If so, it must be the base register and the
12673                  constant must be zero.  */
12674               if (*s == '(' && strchr (s + 1, '(') == 0)
12675                 {
12676                   offset_expr.X_op = O_constant;
12677                   offset_expr.X_add_number = 0;
12678                   continue;
12679                 }
12680
12681               /* If this value won't fit into a 16 bit offset, then go
12682                  find a macro that will generate the 32 bit offset
12683                  code pattern.  */
12684               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12685                   && (offset_expr.X_op != O_constant
12686                       || offset_expr.X_add_number >= 0x8000
12687                       || offset_expr.X_add_number < -0x8000))
12688                 break;
12689
12690               s = expr_end;
12691               continue;
12692
12693             case 'p':           /* PC-relative offset.  */
12694               *offset_reloc = BFD_RELOC_16_PCREL_S2;
12695               my_getExpression (&offset_expr, s);
12696               s = expr_end;
12697               continue;
12698
12699             case 'u':           /* Upper 16 bits.  */
12700               *offset_reloc = BFD_RELOC_LO16;
12701               if (my_getSmallExpression (&offset_expr, offset_reloc, s) == 0
12702                   && offset_expr.X_op == O_constant
12703                   && (offset_expr.X_add_number < 0
12704                       || offset_expr.X_add_number >= 0x10000))
12705                 as_bad (_("lui expression (%lu) not in range 0..65535"),
12706                         (unsigned long) offset_expr.X_add_number);
12707               s = expr_end;
12708               continue;
12709
12710             case 'a':           /* 26-bit address.  */
12711             jump:
12712               *offset_reloc = BFD_RELOC_MIPS_JMP;
12713               my_getExpression (&offset_expr, s);
12714               s = expr_end;
12715               continue;
12716
12717             case 'N':           /* 3-bit branch condition code.  */
12718             case 'M':           /* 3-bit compare condition code.  */
12719               rtype = RTYPE_CCC;
12720               if (ip->insn_mo->pinfo & (FP_D | FP_S))
12721                 rtype |= RTYPE_FCC;
12722               if (!reg_lookup (&s, rtype, &regno))
12723                 break;
12724               if ((strcmp (str + strlen (str) - 3, ".ps") == 0
12725                    || strcmp (str + strlen (str) - 5, "any2f") == 0
12726                    || strcmp (str + strlen (str) - 5, "any2t") == 0)
12727                   && (regno & 1) != 0)
12728                 as_warn (_("Condition code register should be even for %s, "
12729                            "was %d"),
12730                          str, regno);
12731               if ((strcmp (str + strlen (str) - 5, "any4f") == 0
12732                    || strcmp (str + strlen (str) - 5, "any4t") == 0)
12733                   && (regno & 3) != 0)
12734                 as_warn (_("Condition code register should be 0 or 4 for %s, "
12735                            "was %d"),
12736                          str, regno);
12737               if (*args == 'N')
12738                 INSERT_OPERAND (mips_opts.micromips, BCC, *ip, regno);
12739               else
12740                 INSERT_OPERAND (mips_opts.micromips, CCC, *ip, regno);
12741               continue;
12742
12743             case 'H':
12744               if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
12745                 s += 2;
12746               if (ISDIGIT (*s))
12747                 {
12748                   c = 0;
12749                   do
12750                     {
12751                       c *= 10;
12752                       c += *s - '0';
12753                       ++s;
12754                     }
12755                   while (ISDIGIT (*s));
12756                 }
12757               else
12758                 c = 8; /* Invalid sel value.  */
12759
12760               if (c > 7)
12761                 as_bad (_("Invalid coprocessor sub-selection value (0-7)"));
12762               INSERT_OPERAND (mips_opts.micromips, SEL, *ip, c);
12763               continue;
12764
12765             case 'e':
12766               gas_assert (!mips_opts.micromips);
12767               /* Must be at least one digit.  */
12768               my_getExpression (&imm_expr, s);
12769               check_absolute_expr (ip, &imm_expr);
12770
12771               if ((unsigned long) imm_expr.X_add_number
12772                   > (unsigned long) OP_MASK_VECBYTE)
12773                 {
12774                   as_bad (_("bad byte vector index (%ld)"),
12775                            (long) imm_expr.X_add_number);
12776                   imm_expr.X_add_number = 0;
12777                 }
12778
12779               INSERT_OPERAND (0, VECBYTE, *ip, imm_expr.X_add_number);
12780               imm_expr.X_op = O_absent;
12781               s = expr_end;
12782               continue;
12783
12784             case '%':
12785               gas_assert (!mips_opts.micromips);
12786               my_getExpression (&imm_expr, s);
12787               check_absolute_expr (ip, &imm_expr);
12788
12789               if ((unsigned long) imm_expr.X_add_number
12790                   > (unsigned long) OP_MASK_VECALIGN)
12791                 {
12792                   as_bad (_("bad byte vector index (%ld)"),
12793                            (long) imm_expr.X_add_number);
12794                   imm_expr.X_add_number = 0;
12795                 }
12796
12797               INSERT_OPERAND (0, VECALIGN, *ip, imm_expr.X_add_number);
12798               imm_expr.X_op = O_absent;
12799               s = expr_end;
12800               continue;
12801
12802             case 'm':           /* Opcode extension character.  */
12803               gas_assert (mips_opts.micromips);
12804               c = *++args;
12805               switch (c)
12806                 {
12807                 case 'r':
12808                   if (strncmp (s, "$pc", 3) == 0)
12809                     {
12810                       s += 3;
12811                       continue;
12812                     }
12813                   break;
12814
12815                 case 'a':
12816                 case 'b':
12817                 case 'c':
12818                 case 'd':
12819                 case 'e':
12820                 case 'f':
12821                 case 'g':
12822                 case 'h':
12823                 case 'j':
12824                 case 'l':
12825                 case 'm':
12826                 case 'n':
12827                 case 'p':
12828                 case 'q':
12829                 case 's':
12830                 case 't':
12831                 case 'x':
12832                 case 'y':
12833                 case 'z':
12834                   s_reset = s;
12835                   ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno);
12836                   if (regno == AT && mips_opts.at)
12837                     {
12838                       if (mips_opts.at == ATREG)
12839                         as_warn (_("Used $at without \".set noat\""));
12840                       else
12841                         as_warn (_("Used $%u with \".set at=$%u\""),
12842                                  regno, mips_opts.at);
12843                     }
12844                   if (!ok)
12845                     {
12846                       if (c == 'c')
12847                         {
12848                           gas_assert (args[1] == ',');
12849                           regno = lastregno;
12850                           ++args;
12851                         }
12852                       else if (c == 't')
12853                         {
12854                           gas_assert (args[1] == ',');
12855                           ++args;
12856                           continue;                     /* Nothing to do.  */
12857                         }
12858                       else
12859                         break;
12860                     }
12861
12862                   if (c == 'j' && !strncmp (ip->insn_mo->name, "jalr", 4))
12863                     {
12864                       if (regno == lastregno)
12865                         {
12866                           insn_error
12867                             = _("Source and destination must be different");
12868                           continue;
12869                         }
12870                       if (regno == 31 && lastregno == 0xffffffff)
12871                         {
12872                           insn_error
12873                             = _("A destination register must be supplied");
12874                           continue;
12875                         }
12876                     }
12877
12878                   if (*s == ' ')
12879                     ++s;
12880                   if (args[1] != *s)
12881                     {
12882                       if (c == 'e')
12883                         {
12884                           gas_assert (args[1] == ',');
12885                           regno = lastregno;
12886                           s = s_reset;
12887                           ++args;
12888                         }
12889                       else if (c == 't')
12890                         {
12891                           gas_assert (args[1] == ',');
12892                           s = s_reset;
12893                           ++args;
12894                           continue;                     /* Nothing to do.  */
12895                         }
12896                     }
12897
12898                   /* Make sure regno is the same as lastregno.  */
12899                   if (c == 't' && regno != lastregno)
12900                     break;
12901
12902                   /* Make sure regno is the same as destregno.  */
12903                   if (c == 'x' && regno != destregno)
12904                     break;
12905
12906                   /* We need to save regno, before regno maps to the
12907                      microMIPS register encoding.  */
12908                   lastregno = regno;
12909
12910                   if (c == 'f')
12911                     destregno = regno;
12912
12913                   switch (c)
12914                     {
12915                       case 'a':
12916                         if (regno != GP)
12917                           regno = ILLEGAL_REG;
12918                         break;
12919
12920                       case 'b':
12921                         regno = mips32_to_micromips_reg_b_map[regno];
12922                         break;
12923
12924                       case 'c':
12925                         regno = mips32_to_micromips_reg_c_map[regno];
12926                         break;
12927
12928                       case 'd':
12929                         regno = mips32_to_micromips_reg_d_map[regno];
12930                         break;
12931
12932                       case 'e':
12933                         regno = mips32_to_micromips_reg_e_map[regno];
12934                         break;
12935
12936                       case 'f':
12937                         regno = mips32_to_micromips_reg_f_map[regno];
12938                         break;
12939
12940                       case 'g':
12941                         regno = mips32_to_micromips_reg_g_map[regno];
12942                         break;
12943
12944                       case 'h':
12945                         s += strspn (s, " \t");
12946                         if (*s != ',')
12947                           {
12948                             regno = ILLEGAL_REG;
12949                             break;
12950                           }
12951                         ++s;
12952                         s += strspn (s, " \t");
12953                         ok = reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno2);
12954                         if (!ok)
12955                           {
12956                             regno = ILLEGAL_REG;
12957                             break;
12958                           }
12959                         if (regno2 == AT && mips_opts.at)
12960                           {
12961                             if (mips_opts.at == ATREG)
12962                               as_warn (_("Used $at without \".set noat\""));
12963                             else
12964                               as_warn (_("Used $%u with \".set at=$%u\""),
12965                                        regno2, mips_opts.at);
12966                           }
12967                         regno = (mips_lookup_reg_pair
12968                                  (regno, regno2,
12969                                   micromips_to_32_reg_h_map1,
12970                                   micromips_to_32_reg_h_map2, 8));
12971                         break;
12972
12973                       case 'l':
12974                         regno = mips32_to_micromips_reg_l_map[regno];
12975                         break;
12976
12977                       case 'm':
12978                         regno = mips32_to_micromips_reg_m_map[regno];
12979                         break;
12980
12981                       case 'n':
12982                         regno = mips32_to_micromips_reg_n_map[regno];
12983                         break;
12984
12985                       case 'q':
12986                         regno = mips32_to_micromips_reg_q_map[regno];
12987                         break;
12988
12989                       case 's':
12990                         if (regno != SP)
12991                           regno = ILLEGAL_REG;
12992                         break;
12993
12994                       case 'y':
12995                         if (regno != 31)
12996                           regno = ILLEGAL_REG;
12997                         break;
12998
12999                       case 'z':
13000                         if (regno != ZERO)
13001                           regno = ILLEGAL_REG;
13002                         break;
13003
13004                       case 'j': /* Do nothing.  */
13005                       case 'p':
13006                       case 't':
13007                       case 'x':
13008                         break;
13009
13010                       default:
13011                         abort ();
13012                     }
13013
13014                   if (regno == ILLEGAL_REG)
13015                     break;
13016
13017                   switch (c)
13018                     {
13019                       case 'b':
13020                         INSERT_OPERAND (1, MB, *ip, regno);
13021                         break;
13022
13023                       case 'c':
13024                         INSERT_OPERAND (1, MC, *ip, regno);
13025                         break;
13026
13027                       case 'd':
13028                         INSERT_OPERAND (1, MD, *ip, regno);
13029                         break;
13030
13031                       case 'e':
13032                         INSERT_OPERAND (1, ME, *ip, regno);
13033                         break;
13034
13035                       case 'f':
13036                         INSERT_OPERAND (1, MF, *ip, regno);
13037                         break;
13038
13039                       case 'g':
13040                         INSERT_OPERAND (1, MG, *ip, regno);
13041                         break;
13042
13043                       case 'h':
13044                         INSERT_OPERAND (1, MH, *ip, regno);
13045                         break;
13046
13047                       case 'j':
13048                         INSERT_OPERAND (1, MJ, *ip, regno);
13049                         break;
13050
13051                       case 'l':
13052                         INSERT_OPERAND (1, ML, *ip, regno);
13053                         break;
13054
13055                       case 'm':
13056                         INSERT_OPERAND (1, MM, *ip, regno);
13057                         break;
13058
13059                       case 'n':
13060                         INSERT_OPERAND (1, MN, *ip, regno);
13061                         break;
13062
13063                       case 'p':
13064                         INSERT_OPERAND (1, MP, *ip, regno);
13065                         break;
13066
13067                       case 'q':
13068                         INSERT_OPERAND (1, MQ, *ip, regno);
13069                         break;
13070
13071                       case 'a': /* Do nothing.  */
13072                       case 's': /* Do nothing.  */
13073                       case 't': /* Do nothing.  */
13074                       case 'x': /* Do nothing.  */
13075                       case 'y': /* Do nothing.  */
13076                       case 'z': /* Do nothing.  */
13077                         break;
13078
13079                       default:
13080                         abort ();
13081                     }
13082                   continue;
13083
13084                 case 'A':
13085                   {
13086                     bfd_reloc_code_real_type r[3];
13087                     expressionS ep;
13088                     int imm;
13089
13090                     /* Check whether there is only a single bracketed
13091                        expression left.  If so, it must be the base register
13092                        and the constant must be zero.  */
13093                     if (*s == '(' && strchr (s + 1, '(') == 0)
13094                       {
13095                         INSERT_OPERAND (1, IMMA, *ip, 0);
13096                         continue;
13097                       }
13098
13099                     if (my_getSmallExpression (&ep, r, s) > 0
13100                         || !expr_const_in_range (&ep, -64, 64, 2))
13101                       break;
13102
13103                     imm = ep.X_add_number >> 2;
13104                     INSERT_OPERAND (1, IMMA, *ip, imm);
13105                   }
13106                   s = expr_end;
13107                   continue;
13108
13109                 case 'B':
13110                   {
13111                     bfd_reloc_code_real_type r[3];
13112                     expressionS ep;
13113                     int imm;
13114
13115                     if (my_getSmallExpression (&ep, r, s) > 0
13116                         || ep.X_op != O_constant)
13117                       break;
13118
13119                     for (imm = 0; imm < 8; imm++)
13120                       if (micromips_imm_b_map[imm] == ep.X_add_number)
13121                         break;
13122                     if (imm >= 8)
13123                       break;
13124
13125                     INSERT_OPERAND (1, IMMB, *ip, imm);
13126                   }
13127                   s = expr_end;
13128                   continue;
13129
13130                 case 'C':
13131                   {
13132                     bfd_reloc_code_real_type r[3];
13133                     expressionS ep;
13134                     int imm;
13135
13136                     if (my_getSmallExpression (&ep, r, s) > 0
13137                         || ep.X_op != O_constant)
13138                       break;
13139
13140                     for (imm = 0; imm < 16; imm++)
13141                       if (micromips_imm_c_map[imm] == ep.X_add_number)
13142                         break;
13143                     if (imm >= 16)
13144                       break;
13145
13146                     INSERT_OPERAND (1, IMMC, *ip, imm);
13147                   }
13148                   s = expr_end;
13149                   continue;
13150
13151                 case 'D':       /* pc relative offset */
13152                 case 'E':       /* pc relative offset */
13153                   my_getExpression (&offset_expr, s);
13154                   if (offset_expr.X_op == O_register)
13155                     break;
13156
13157                   if (!forced_insn_length)
13158                     *offset_reloc = (int) BFD_RELOC_UNUSED + c;
13159                   else if (c == 'D')
13160                     *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
13161                   else
13162                     *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
13163                   s = expr_end;
13164                   continue;
13165
13166                 case 'F':
13167                   {
13168                     bfd_reloc_code_real_type r[3];
13169                     expressionS ep;
13170                     int imm;
13171
13172                     if (my_getSmallExpression (&ep, r, s) > 0
13173                         || !expr_const_in_range (&ep, 0, 16, 0))
13174                       break;
13175
13176                     imm = ep.X_add_number;
13177                     INSERT_OPERAND (1, IMMF, *ip, imm);
13178                   }
13179                   s = expr_end;
13180                   continue;
13181
13182                 case 'G':
13183                   {
13184                     bfd_reloc_code_real_type r[3];
13185                     expressionS ep;
13186                     int imm;
13187
13188                     /* Check whether there is only a single bracketed
13189                        expression left.  If so, it must be the base register
13190                        and the constant must be zero.  */
13191                     if (*s == '(' && strchr (s + 1, '(') == 0)
13192                       {
13193                         INSERT_OPERAND (1, IMMG, *ip, 0);
13194                         continue;
13195                       }
13196
13197                     if (my_getSmallExpression (&ep, r, s) > 0
13198                         || !expr_const_in_range (&ep, -1, 15, 0))
13199                       break;
13200
13201                     imm = ep.X_add_number & 15;
13202                     INSERT_OPERAND (1, IMMG, *ip, imm);
13203                   }
13204                   s = expr_end;
13205                   continue;
13206
13207                 case 'H':
13208                   {
13209                     bfd_reloc_code_real_type r[3];
13210                     expressionS ep;
13211                     int imm;
13212
13213                     /* Check whether there is only a single bracketed
13214                        expression left.  If so, it must be the base register
13215                        and the constant must be zero.  */
13216                     if (*s == '(' && strchr (s + 1, '(') == 0)
13217                       {
13218                         INSERT_OPERAND (1, IMMH, *ip, 0);
13219                         continue;
13220                       }
13221
13222                     if (my_getSmallExpression (&ep, r, s) > 0
13223                         || !expr_const_in_range (&ep, 0, 16, 1))
13224                       break;
13225
13226                     imm = ep.X_add_number >> 1;
13227                     INSERT_OPERAND (1, IMMH, *ip, imm);
13228                   }
13229                   s = expr_end;
13230                   continue;
13231
13232                 case 'I':
13233                   {
13234                     bfd_reloc_code_real_type r[3];
13235                     expressionS ep;
13236                     int imm;
13237
13238                     if (my_getSmallExpression (&ep, r, s) > 0
13239                         || !expr_const_in_range (&ep, -1, 127, 0))
13240                       break;
13241
13242                     imm = ep.X_add_number & 127;
13243                     INSERT_OPERAND (1, IMMI, *ip, imm);
13244                   }
13245                   s = expr_end;
13246                   continue;
13247
13248                 case 'J':
13249                   {
13250                     bfd_reloc_code_real_type r[3];
13251                     expressionS ep;
13252                     int imm;
13253
13254                     /* Check whether there is only a single bracketed
13255                        expression left.  If so, it must be the base register
13256                        and the constant must be zero.  */
13257                     if (*s == '(' && strchr (s + 1, '(') == 0)
13258                       {
13259                         INSERT_OPERAND (1, IMMJ, *ip, 0);
13260                         continue;
13261                       }
13262
13263                     if (my_getSmallExpression (&ep, r, s) > 0
13264                         || !expr_const_in_range (&ep, 0, 16, 2))
13265                       break;
13266
13267                     imm = ep.X_add_number >> 2;
13268                     INSERT_OPERAND (1, IMMJ, *ip, imm);
13269                   }
13270                   s = expr_end;
13271                   continue;
13272
13273                 case 'L':
13274                   {
13275                     bfd_reloc_code_real_type r[3];
13276                     expressionS ep;
13277                     int imm;
13278
13279                     /* Check whether there is only a single bracketed
13280                        expression left.  If so, it must be the base register
13281                        and the constant must be zero.  */
13282                     if (*s == '(' && strchr (s + 1, '(') == 0)
13283                       {
13284                         INSERT_OPERAND (1, IMML, *ip, 0);
13285                         continue;
13286                       }
13287
13288                     if (my_getSmallExpression (&ep, r, s) > 0
13289                         || !expr_const_in_range (&ep, 0, 16, 0))
13290                       break;
13291
13292                     imm = ep.X_add_number;
13293                     INSERT_OPERAND (1, IMML, *ip, imm);
13294                   }
13295                   s = expr_end;
13296                   continue;
13297
13298                 case 'M':
13299                   {
13300                     bfd_reloc_code_real_type r[3];
13301                     expressionS ep;
13302                     int imm;
13303
13304                     if (my_getSmallExpression (&ep, r, s) > 0
13305                         || !expr_const_in_range (&ep, 1, 9, 0))
13306                       break;
13307
13308                     imm = ep.X_add_number & 7;
13309                     INSERT_OPERAND (1, IMMM, *ip, imm);
13310                   }
13311                   s = expr_end;
13312                   continue;
13313
13314                 case 'N':       /* Register list for lwm and swm.  */
13315                   {
13316                     /* A comma-separated list of registers and/or
13317                        dash-separated contiguous ranges including
13318                        both ra and a set of one or more registers
13319                        starting at s0 up to s3 which have to be
13320                        consecutive, e.g.:
13321
13322                        s0, ra
13323                        s0, s1, ra, s2, s3
13324                        s0-s2, ra
13325
13326                        and any permutations of these.  */
13327                     unsigned int reglist;
13328                     int imm;
13329
13330                     if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13331                       break;
13332
13333                     if ((reglist & 0xfff1ffff) != 0x80010000)
13334                       break;
13335
13336                     reglist = (reglist >> 17) & 7;
13337                     reglist += 1;
13338                     if ((reglist & -reglist) != reglist)
13339                       break;
13340
13341                     imm = ffs (reglist) - 1;
13342                     INSERT_OPERAND (1, IMMN, *ip, imm);
13343                   }
13344                   continue;
13345
13346                 case 'O':       /* sdbbp 4-bit code.  */
13347                   {
13348                     bfd_reloc_code_real_type r[3];
13349                     expressionS ep;
13350                     int imm;
13351
13352                     if (my_getSmallExpression (&ep, r, s) > 0
13353                         || !expr_const_in_range (&ep, 0, 16, 0))
13354                       break;
13355
13356                     imm = ep.X_add_number;
13357                     INSERT_OPERAND (1, IMMO, *ip, imm);
13358                   }
13359                   s = expr_end;
13360                   continue;
13361
13362                 case 'P':
13363                   {
13364                     bfd_reloc_code_real_type r[3];
13365                     expressionS ep;
13366                     int imm;
13367
13368                     if (my_getSmallExpression (&ep, r, s) > 0
13369                         || !expr_const_in_range (&ep, 0, 32, 2))
13370                       break;
13371
13372                     imm = ep.X_add_number >> 2;
13373                     INSERT_OPERAND (1, IMMP, *ip, imm);
13374                   }
13375                   s = expr_end;
13376                   continue;
13377
13378                 case 'Q':
13379                   {
13380                     bfd_reloc_code_real_type r[3];
13381                     expressionS ep;
13382                     int imm;
13383
13384                     if (my_getSmallExpression (&ep, r, s) > 0
13385                         || !expr_const_in_range (&ep, -0x400000, 0x400000, 2))
13386                       break;
13387
13388                     imm = ep.X_add_number >> 2;
13389                     INSERT_OPERAND (1, IMMQ, *ip, imm);
13390                   }
13391                   s = expr_end;
13392                   continue;
13393
13394                 case 'U':
13395                   {
13396                     bfd_reloc_code_real_type r[3];
13397                     expressionS ep;
13398                     int imm;
13399
13400                     /* Check whether there is only a single bracketed
13401                        expression left.  If so, it must be the base register
13402                        and the constant must be zero.  */
13403                     if (*s == '(' && strchr (s + 1, '(') == 0)
13404                       {
13405                         INSERT_OPERAND (1, IMMU, *ip, 0);
13406                         continue;
13407                       }
13408
13409                     if (my_getSmallExpression (&ep, r, s) > 0
13410                         || !expr_const_in_range (&ep, 0, 32, 2))
13411                       break;
13412
13413                     imm = ep.X_add_number >> 2;
13414                     INSERT_OPERAND (1, IMMU, *ip, imm);
13415                   }
13416                   s = expr_end;
13417                   continue;
13418
13419                 case 'W':
13420                   {
13421                     bfd_reloc_code_real_type r[3];
13422                     expressionS ep;
13423                     int imm;
13424
13425                     if (my_getSmallExpression (&ep, r, s) > 0
13426                         || !expr_const_in_range (&ep, 0, 64, 2))
13427                       break;
13428
13429                     imm = ep.X_add_number >> 2;
13430                     INSERT_OPERAND (1, IMMW, *ip, imm);
13431                   }
13432                   s = expr_end;
13433                   continue;
13434
13435                 case 'X':
13436                   {
13437                     bfd_reloc_code_real_type r[3];
13438                     expressionS ep;
13439                     int imm;
13440
13441                     if (my_getSmallExpression (&ep, r, s) > 0
13442                         || !expr_const_in_range (&ep, -8, 8, 0))
13443                       break;
13444
13445                     imm = ep.X_add_number;
13446                     INSERT_OPERAND (1, IMMX, *ip, imm);
13447                   }
13448                   s = expr_end;
13449                   continue;
13450
13451                 case 'Y':
13452                   {
13453                     bfd_reloc_code_real_type r[3];
13454                     expressionS ep;
13455                     int imm;
13456
13457                     if (my_getSmallExpression (&ep, r, s) > 0
13458                         || expr_const_in_range (&ep, -2, 2, 2)
13459                         || !expr_const_in_range (&ep, -258, 258, 2))
13460                       break;
13461
13462                     imm = ep.X_add_number >> 2;
13463                     imm = ((imm >> 1) & ~0xff) | (imm & 0xff);
13464                     INSERT_OPERAND (1, IMMY, *ip, imm);
13465                   }
13466                   s = expr_end;
13467                   continue;
13468
13469                 case 'Z':
13470                   {
13471                     bfd_reloc_code_real_type r[3];
13472                     expressionS ep;
13473
13474                     if (my_getSmallExpression (&ep, r, s) > 0
13475                         || !expr_const_in_range (&ep, 0, 1, 0))
13476                       break;
13477                   }
13478                   s = expr_end;
13479                   continue;
13480
13481                 default:
13482                   as_bad (_("Internal error: bad microMIPS opcode "
13483                             "(unknown extension operand type `m%c'): %s %s"),
13484                           *args, insn->name, insn->args);
13485                   /* Further processing is fruitless.  */
13486                   return;
13487                 }
13488               break;
13489
13490             case 'n':           /* Register list for 32-bit lwm and swm.  */
13491               gas_assert (mips_opts.micromips);
13492               {
13493                 /* A comma-separated list of registers and/or
13494                    dash-separated contiguous ranges including
13495                    at least one of ra and a set of one or more
13496                    registers starting at s0 up to s7 and then
13497                    s8 which have to be consecutive, e.g.:
13498
13499                    ra
13500                    s0
13501                    ra, s0, s1, s2
13502                    s0-s8
13503                    s0-s5, ra
13504
13505                    and any permutations of these.  */
13506                 unsigned int reglist;
13507                 int imm;
13508                 int ra;
13509
13510                 if (!reglist_lookup (&s, RTYPE_NUM | RTYPE_GP, &reglist))
13511                   break;
13512
13513                 if ((reglist & 0x3f00ffff) != 0)
13514                   break;
13515
13516                 ra = (reglist >> 27) & 0x10;
13517                 reglist = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
13518                 reglist += 1;
13519                 if ((reglist & -reglist) != reglist)
13520                   break;
13521
13522                 imm = (ffs (reglist) - 1) | ra;
13523                 INSERT_OPERAND (1, RT, *ip, imm);
13524                 imm_expr.X_op = O_absent;
13525               }
13526               continue;
13527
13528             case '|':           /* 4-bit trap code.  */
13529               gas_assert (mips_opts.micromips);
13530               my_getExpression (&imm_expr, s);
13531               check_absolute_expr (ip, &imm_expr);
13532               if ((unsigned long) imm_expr.X_add_number
13533                   > MICROMIPSOP_MASK_TRAP)
13534                 as_bad (_("Trap code (%lu) for %s not in 0..15 range"),
13535                         (unsigned long) imm_expr.X_add_number,
13536                         ip->insn_mo->name);
13537               INSERT_OPERAND (1, TRAP, *ip, imm_expr.X_add_number);
13538               imm_expr.X_op = O_absent;
13539               s = expr_end;
13540               continue;
13541
13542             default:
13543               as_bad (_("Bad char = '%c'\n"), *args);
13544               abort ();
13545             }
13546           break;
13547         }
13548       /* Args don't match.  */
13549       s = argsStart;
13550       insn_error = _("Illegal operands");
13551       if (insn + 1 < past && !strcmp (insn->name, insn[1].name))
13552         {
13553           ++insn;
13554           continue;
13555         }
13556       else if (wrong_delay_slot_insns && need_delay_slot_ok)
13557         {
13558           gas_assert (firstinsn);
13559           need_delay_slot_ok = FALSE;
13560           past = insn + 1;
13561           insn = firstinsn;
13562           continue;
13563         }
13564       return;
13565     }
13566 }
13567
13568 #define SKIP_SPACE_TABS(S) { while (*(S) == ' ' || *(S) == '\t') ++(S); }
13569
13570 /* As for mips_ip, but used when assembling MIPS16 code.
13571    Also set forced_insn_length to the resulting instruction size in
13572    bytes if the user explicitly requested a small or extended instruction.  */
13573
13574 static void
13575 mips16_ip (char *str, struct mips_cl_insn *ip)
13576 {
13577   char *s;
13578   const char *args;
13579   struct mips_opcode *insn;
13580   char *argsstart;
13581   unsigned int regno;
13582   unsigned int lastregno = 0;
13583   char *s_reset;
13584   size_t i;
13585
13586   insn_error = NULL;
13587
13588   forced_insn_length = 0;
13589
13590   for (s = str; ISLOWER (*s); ++s)
13591     ;
13592   switch (*s)
13593     {
13594     case '\0':
13595       break;
13596
13597     case ' ':
13598       *s++ = '\0';
13599       break;
13600
13601     case '.':
13602       if (s[1] == 't' && s[2] == ' ')
13603         {
13604           *s = '\0';
13605           forced_insn_length = 2;
13606           s += 3;
13607           break;
13608         }
13609       else if (s[1] == 'e' && s[2] == ' ')
13610         {
13611           *s = '\0';
13612           forced_insn_length = 4;
13613           s += 3;
13614           break;
13615         }
13616       /* Fall through.  */
13617     default:
13618       insn_error = _("unknown opcode");
13619       return;
13620     }
13621
13622   if (mips_opts.noautoextend && !forced_insn_length)
13623     forced_insn_length = 2;
13624
13625   if ((insn = (struct mips_opcode *) hash_find (mips16_op_hash, str)) == NULL)
13626     {
13627       insn_error = _("unrecognized opcode");
13628       return;
13629     }
13630
13631   argsstart = s;
13632   for (;;)
13633     {
13634       bfd_boolean ok;
13635       char relax_char;
13636
13637       gas_assert (strcmp (insn->name, str) == 0);
13638
13639       ok = is_opcode_valid_16 (insn);
13640       if (! ok)
13641         {
13642           if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes]
13643               && strcmp (insn->name, insn[1].name) == 0)
13644             {
13645               ++insn;
13646               continue;
13647             }
13648           else
13649             {
13650               if (!insn_error)
13651                 {
13652                   static char buf[100];
13653                   sprintf (buf,
13654                            _("Opcode not supported on this processor: %s (%s)"),
13655                            mips_cpu_info_from_arch (mips_opts.arch)->name,
13656                            mips_cpu_info_from_isa (mips_opts.isa)->name);
13657                   insn_error = buf;
13658                 }
13659               return;
13660             }
13661         }
13662
13663       create_insn (ip, insn);
13664       imm_expr.X_op = O_absent;
13665       imm2_expr.X_op = O_absent;
13666       offset_expr.X_op = O_absent;
13667       offset_reloc[0] = BFD_RELOC_UNUSED;
13668       offset_reloc[1] = BFD_RELOC_UNUSED;
13669       offset_reloc[2] = BFD_RELOC_UNUSED;
13670       relax_char = 0;
13671       for (args = insn->args; 1; ++args)
13672         {
13673           int c;
13674
13675           if (*s == ' ')
13676             ++s;
13677
13678           /* In this switch statement we call break if we did not find
13679              a match, continue if we did find a match, or return if we
13680              are done.  */
13681
13682           c = *args;
13683           switch (c)
13684             {
13685             case '\0':
13686               if (*s == '\0')
13687                 {
13688                   offsetT value;
13689
13690                   /* Stuff the immediate value in now, if we can.  */
13691                   if (insn->pinfo == INSN_MACRO)
13692                     {
13693                       gas_assert (relax_char == 0);
13694                       gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
13695                     }
13696                   else if (relax_char
13697                            && offset_expr.X_op == O_constant
13698                            && calculate_reloc (*offset_reloc,
13699                                                offset_expr.X_add_number,
13700                                                &value))
13701                     {
13702                       mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
13703                                     forced_insn_length, &ip->insn_opcode);
13704                       offset_expr.X_op = O_absent;
13705                       *offset_reloc = BFD_RELOC_UNUSED;
13706                     }
13707                   else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
13708                     {
13709                       if (forced_insn_length == 2)
13710                         as_bad (_("invalid unextended operand value"));
13711                       forced_insn_length = 4;
13712                       ip->insn_opcode |= MIPS16_EXTEND;
13713                     }
13714                   else if (relax_char)
13715                     *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
13716
13717                   return;
13718                 }
13719               break;
13720
13721             case ',':
13722               if (*s++ == c)
13723                 continue;
13724               s--;
13725               switch (*++args)
13726                 {
13727                 case 'v':
13728                   MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13729                   continue;
13730                 case 'w':
13731                   MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13732                   continue;
13733                 }
13734               break;
13735
13736             case '(':
13737             case ')':
13738               if (*s++ == c)
13739                 continue;
13740               break;
13741
13742             case 'v':
13743             case 'w':
13744               if (s[0] != '$')
13745                 {
13746                   if (c == 'v')
13747                     MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13748                   else
13749                     MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13750                   ++args;
13751                   continue;
13752                 }
13753               /* Fall through.  */
13754             case 'x':
13755             case 'y':
13756             case 'z':
13757             case 'Z':
13758             case '0':
13759             case 'S':
13760             case 'R':
13761             case 'X':
13762             case 'Y':
13763               s_reset = s;
13764               if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &regno))
13765                 {
13766                   if (c == 'v' || c == 'w')
13767                     {
13768                       if (c == 'v')
13769                         MIPS16_INSERT_OPERAND (RX, *ip, lastregno);
13770                       else
13771                         MIPS16_INSERT_OPERAND (RY, *ip, lastregno);
13772                       ++args;
13773                       continue;
13774                     }
13775                   break;
13776                 }
13777
13778               if (*s == ' ')
13779                 ++s;
13780               if (args[1] != *s)
13781                 {
13782                   if (c == 'v' || c == 'w')
13783                     {
13784                       regno = mips16_to_32_reg_map[lastregno];
13785                       s = s_reset;
13786                       ++args;
13787                     }
13788                 }
13789
13790               switch (c)
13791                 {
13792                 case 'x':
13793                 case 'y':
13794                 case 'z':
13795                 case 'v':
13796                 case 'w':
13797                 case 'Z':
13798                   regno = mips32_to_16_reg_map[regno];
13799                   break;
13800
13801                 case '0':
13802                   if (regno != 0)
13803                     regno = ILLEGAL_REG;
13804                   break;
13805
13806                 case 'S':
13807                   if (regno != SP)
13808                     regno = ILLEGAL_REG;
13809                   break;
13810
13811                 case 'R':
13812                   if (regno != RA)
13813                     regno = ILLEGAL_REG;
13814                   break;
13815
13816                 case 'X':
13817                 case 'Y':
13818                   if (regno == AT && mips_opts.at)
13819                     {
13820                       if (mips_opts.at == ATREG)
13821                         as_warn (_("used $at without \".set noat\""));
13822                       else
13823                         as_warn (_("used $%u with \".set at=$%u\""),
13824                                  regno, mips_opts.at);
13825                     }
13826                   break;
13827
13828                 default:
13829                   abort ();
13830                 }
13831
13832               if (regno == ILLEGAL_REG)
13833                 break;
13834
13835               switch (c)
13836                 {
13837                 case 'x':
13838                 case 'v':
13839                   MIPS16_INSERT_OPERAND (RX, *ip, regno);
13840                   break;
13841                 case 'y':
13842                 case 'w':
13843                   MIPS16_INSERT_OPERAND (RY, *ip, regno);
13844                   break;
13845                 case 'z':
13846                   MIPS16_INSERT_OPERAND (RZ, *ip, regno);
13847                   break;
13848                 case 'Z':
13849                   MIPS16_INSERT_OPERAND (MOVE32Z, *ip, regno);
13850                 case '0':
13851                 case 'S':
13852                 case 'R':
13853                   break;
13854                 case 'X':
13855                   MIPS16_INSERT_OPERAND (REGR32, *ip, regno);
13856                   break;
13857                 case 'Y':
13858                   regno = ((regno & 7) << 2) | ((regno & 0x18) >> 3);
13859                   MIPS16_INSERT_OPERAND (REG32R, *ip, regno);
13860                   break;
13861                 default:
13862                   abort ();
13863                 }
13864
13865               lastregno = regno;
13866               continue;
13867
13868             case 'P':
13869               if (strncmp (s, "$pc", 3) == 0)
13870                 {
13871                   s += 3;
13872                   continue;
13873                 }
13874               break;
13875
13876             case '5':
13877             case 'H':
13878             case 'W':
13879             case 'D':
13880             case 'j':
13881             case 'V':
13882             case 'C':
13883             case 'U':
13884             case 'k':
13885             case 'K':
13886               i = my_getSmallExpression (&offset_expr, offset_reloc, s);
13887               if (i > 0)
13888                 {
13889                   relax_char = c;
13890                   s = expr_end;
13891                   continue;
13892                 }
13893               *offset_reloc = BFD_RELOC_UNUSED;
13894               /* Fall through.  */
13895             case '<':
13896             case '>':
13897             case '[':
13898             case ']':
13899             case '4':
13900             case '8':
13901               my_getExpression (&offset_expr, s);
13902               if (offset_expr.X_op == O_register)
13903                 {
13904                   /* What we thought was an expression turned out to
13905                      be a register.  */
13906
13907                   if (s[0] == '(' && args[1] == '(')
13908                     {
13909                       /* It looks like the expression was omitted
13910                          before a register indirection, which means
13911                          that the expression is implicitly zero.  We
13912                          still set up offset_expr, so that we handle
13913                          explicit extensions correctly.  */
13914                       offset_expr.X_op = O_constant;
13915                       offset_expr.X_add_number = 0;
13916                       relax_char = c;
13917                       continue;
13918                     }
13919
13920                   break;
13921                 }
13922
13923               /* We need to relax this instruction.  */
13924               relax_char = c;
13925               s = expr_end;
13926               continue;
13927
13928             case 'p':
13929             case 'q':
13930             case 'A':
13931             case 'B':
13932             case 'E':
13933               /* We use offset_reloc rather than imm_reloc for the PC
13934                  relative operands.  This lets macros with both
13935                  immediate and address operands work correctly.  */
13936               my_getExpression (&offset_expr, s);
13937
13938               if (offset_expr.X_op == O_register)
13939                 break;
13940
13941               /* We need to relax this instruction.  */
13942               relax_char = c;
13943               s = expr_end;
13944               continue;
13945
13946             case '6':           /* break code */
13947               my_getExpression (&imm_expr, s);
13948               check_absolute_expr (ip, &imm_expr);
13949               if ((unsigned long) imm_expr.X_add_number > 63)
13950                 as_warn (_("Invalid value for `%s' (%lu)"),
13951                          ip->insn_mo->name,
13952                          (unsigned long) imm_expr.X_add_number);
13953               MIPS16_INSERT_OPERAND (IMM6, *ip, imm_expr.X_add_number);
13954               imm_expr.X_op = O_absent;
13955               s = expr_end;
13956               continue;
13957
13958             case 'I':
13959               my_getExpression (&imm_expr, s);
13960               if (imm_expr.X_op != O_big
13961                   && imm_expr.X_op != O_constant)
13962                 insn_error = _("absolute expression required");
13963               if (HAVE_32BIT_GPRS)
13964                 normalize_constant_expr (&imm_expr);
13965               s = expr_end;
13966               continue;
13967
13968             case 'a':           /* 26 bit address */
13969             case 'i':
13970               my_getExpression (&offset_expr, s);
13971               s = expr_end;
13972               *offset_reloc = BFD_RELOC_MIPS16_JMP;
13973               ip->insn_opcode <<= 16;
13974               continue;
13975
13976             case 'l':           /* register list for entry macro */
13977             case 'L':           /* register list for exit macro */
13978               {
13979                 int mask;
13980
13981                 if (c == 'l')
13982                   mask = 0;
13983                 else
13984                   mask = 7 << 3;
13985                 while (*s != '\0')
13986                   {
13987                     unsigned int freg, reg1, reg2;
13988
13989                     while (*s == ' ' || *s == ',')
13990                       ++s;
13991                     if (reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
13992                       freg = 0;
13993                     else if (reg_lookup (&s, RTYPE_FPU, &reg1))
13994                       freg = 1;
13995                     else
13996                       {
13997                         as_bad (_("can't parse register list"));
13998                         break;
13999                       }
14000                     if (*s == ' ')
14001                       ++s;
14002                     if (*s != '-')
14003                       reg2 = reg1;
14004                     else
14005                       {
14006                         ++s;
14007                         if (!reg_lookup (&s, freg ? RTYPE_FPU 
14008                                          : (RTYPE_GP | RTYPE_NUM), &reg2))
14009                           {
14010                             as_bad (_("invalid register list"));
14011                             break;
14012                           }
14013                       }
14014                     if (freg && reg1 == 0 && reg2 == 0 && c == 'L')
14015                       {
14016                         mask &= ~ (7 << 3);
14017                         mask |= 5 << 3;
14018                       }
14019                     else if (freg && reg1 == 0 && reg2 == 1 && c == 'L')
14020                       {
14021                         mask &= ~ (7 << 3);
14022                         mask |= 6 << 3;
14023                       }
14024                     else if (reg1 == 4 && reg2 >= 4 && reg2 <= 7 && c != 'L')
14025                       mask |= (reg2 - 3) << 3;
14026                     else if (reg1 == 16 && reg2 >= 16 && reg2 <= 17)
14027                       mask |= (reg2 - 15) << 1;
14028                     else if (reg1 == RA && reg2 == RA)
14029                       mask |= 1;
14030                     else
14031                       {
14032                         as_bad (_("invalid register list"));
14033                         break;
14034                       }
14035                   }
14036                 /* The mask is filled in in the opcode table for the
14037                    benefit of the disassembler.  We remove it before
14038                    applying the actual mask.  */
14039                 ip->insn_opcode &= ~ ((7 << 3) << MIPS16OP_SH_IMM6);
14040                 ip->insn_opcode |= mask << MIPS16OP_SH_IMM6;
14041               }
14042             continue;
14043
14044             case 'm':           /* Register list for save insn.  */
14045             case 'M':           /* Register list for restore insn.  */
14046               {
14047                 int opcode = ip->insn_opcode;
14048                 int framesz = 0, seen_framesz = 0;
14049                 int nargs = 0, statics = 0, sregs = 0;
14050
14051                 while (*s != '\0')
14052                   {
14053                     unsigned int reg1, reg2;
14054
14055                     SKIP_SPACE_TABS (s);
14056                     while (*s == ',')
14057                       ++s;
14058                     SKIP_SPACE_TABS (s);
14059
14060                     my_getExpression (&imm_expr, s);
14061                     if (imm_expr.X_op == O_constant)
14062                       {
14063                         /* Handle the frame size.  */
14064                         if (seen_framesz)
14065                           {
14066                             as_bad (_("more than one frame size in list"));
14067                             break;
14068                           }
14069                         seen_framesz = 1;
14070                         framesz = imm_expr.X_add_number;
14071                         imm_expr.X_op = O_absent;
14072                         s = expr_end;
14073                         continue;
14074                       }
14075
14076                     if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg1))
14077                       {
14078                         as_bad (_("can't parse register list"));
14079                         break;
14080                       }
14081
14082                     while (*s == ' ')
14083                       ++s;
14084
14085                     if (*s != '-')
14086                       reg2 = reg1;
14087                     else
14088                       {
14089                         ++s;
14090                         if (! reg_lookup (&s, RTYPE_GP | RTYPE_NUM, &reg2)
14091                             || reg2 < reg1)
14092                           {
14093                             as_bad (_("can't parse register list"));
14094                             break;
14095                           }
14096                       }
14097
14098                     while (reg1 <= reg2)
14099                       {
14100                         if (reg1 >= 4 && reg1 <= 7)
14101                           {
14102                             if (!seen_framesz)
14103                                 /* args $a0-$a3 */
14104                                 nargs |= 1 << (reg1 - 4);
14105                             else
14106                                 /* statics $a0-$a3 */
14107                                 statics |= 1 << (reg1 - 4);
14108                           }
14109                         else if ((reg1 >= 16 && reg1 <= 23) || reg1 == 30)
14110                           {
14111                             /* $s0-$s8 */
14112                             sregs |= 1 << ((reg1 == 30) ? 8 : (reg1 - 16));
14113                           }
14114                         else if (reg1 == 31)
14115                           {
14116                             /* Add $ra to insn.  */
14117                             opcode |= 0x40;
14118                           }
14119                         else
14120                           {
14121                             as_bad (_("unexpected register in list"));
14122                             break;
14123                           }
14124                         if (++reg1 == 24)
14125                           reg1 = 30;
14126                       }
14127                   }
14128
14129                 /* Encode args/statics combination.  */
14130                 if (nargs & statics)
14131                   as_bad (_("arg/static registers overlap"));
14132                 else if (nargs == 0xf)
14133                   /* All $a0-$a3 are args.  */
14134                   opcode |= MIPS16_ALL_ARGS << 16;
14135                 else if (statics == 0xf)
14136                   /* All $a0-$a3 are statics.  */
14137                   opcode |= MIPS16_ALL_STATICS << 16;
14138                 else 
14139                   {
14140                     int narg = 0, nstat = 0;
14141
14142                     /* Count arg registers.  */
14143                     while (nargs & 0x1)
14144                       {
14145                         nargs >>= 1;
14146                         narg++;
14147                       }
14148                     if (nargs != 0)
14149                       as_bad (_("invalid arg register list"));
14150
14151                     /* Count static registers.  */
14152                     while (statics & 0x8)
14153                       {
14154                         statics = (statics << 1) & 0xf;
14155                         nstat++;
14156                       }
14157                     if (statics != 0) 
14158                       as_bad (_("invalid static register list"));
14159
14160                     /* Encode args/statics.  */
14161                     opcode |= ((narg << 2) | nstat) << 16;
14162                   }
14163
14164                 /* Encode $s0/$s1.  */
14165                 if (sregs & (1 << 0))           /* $s0 */
14166                   opcode |= 0x20;
14167                 if (sregs & (1 << 1))           /* $s1 */
14168                   opcode |= 0x10;
14169                 sregs >>= 2;
14170
14171                 if (sregs != 0)
14172                   {
14173                     /* Count regs $s2-$s8.  */
14174                     int nsreg = 0;
14175                     while (sregs & 1)
14176                       {
14177                         sregs >>= 1;
14178                         nsreg++;
14179                       }
14180                     if (sregs != 0)
14181                       as_bad (_("invalid static register list"));
14182                     /* Encode $s2-$s8. */
14183                     opcode |= nsreg << 24;
14184                   }
14185
14186                 /* Encode frame size.  */
14187                 if (!seen_framesz)
14188                   as_bad (_("missing frame size"));
14189                 else if ((framesz & 7) != 0 || framesz < 0
14190                          || framesz > 0xff * 8)
14191                   as_bad (_("invalid frame size"));
14192                 else if (framesz != 128 || (opcode >> 16) != 0)
14193                   {
14194                     framesz /= 8;
14195                     opcode |= (((framesz & 0xf0) << 16)
14196                              | (framesz & 0x0f));
14197                   }
14198
14199                 /* Finally build the instruction.  */
14200                 if ((opcode >> 16) != 0 || framesz == 0)
14201                   opcode |= MIPS16_EXTEND;
14202                 ip->insn_opcode = opcode;
14203               }
14204             continue;
14205
14206             case 'e':           /* extend code */
14207               my_getExpression (&imm_expr, s);
14208               check_absolute_expr (ip, &imm_expr);
14209               if ((unsigned long) imm_expr.X_add_number > 0x7ff)
14210                 {
14211                   as_warn (_("Invalid value for `%s' (%lu)"),
14212                            ip->insn_mo->name,
14213                            (unsigned long) imm_expr.X_add_number);
14214                   imm_expr.X_add_number &= 0x7ff;
14215                 }
14216               ip->insn_opcode |= imm_expr.X_add_number;
14217               imm_expr.X_op = O_absent;
14218               s = expr_end;
14219               continue;
14220
14221             default:
14222               abort ();
14223             }
14224           break;
14225         }
14226
14227       /* Args don't match.  */
14228       if (insn + 1 < &mips16_opcodes[bfd_mips16_num_opcodes] &&
14229           strcmp (insn->name, insn[1].name) == 0)
14230         {
14231           ++insn;
14232           s = argsstart;
14233           continue;
14234         }
14235
14236       insn_error = _("illegal operands");
14237
14238       return;
14239     }
14240 }
14241
14242 /* This structure holds information we know about a mips16 immediate
14243    argument type.  */
14244
14245 struct mips16_immed_operand
14246 {
14247   /* The type code used in the argument string in the opcode table.  */
14248   int type;
14249   /* The number of bits in the short form of the opcode.  */
14250   int nbits;
14251   /* The number of bits in the extended form of the opcode.  */
14252   int extbits;
14253   /* The amount by which the short form is shifted when it is used;
14254      for example, the sw instruction has a shift count of 2.  */
14255   int shift;
14256   /* The amount by which the short form is shifted when it is stored
14257      into the instruction code.  */
14258   int op_shift;
14259   /* Non-zero if the short form is unsigned.  */
14260   int unsp;
14261   /* Non-zero if the extended form is unsigned.  */
14262   int extu;
14263   /* Non-zero if the value is PC relative.  */
14264   int pcrel;
14265 };
14266
14267 /* The mips16 immediate operand types.  */
14268
14269 static const struct mips16_immed_operand mips16_immed_operands[] =
14270 {
14271   { '<',  3,  5, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14272   { '>',  3,  5, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14273   { '[',  3,  6, 0, MIPS16OP_SH_RZ,   1, 1, 0 },
14274   { ']',  3,  6, 0, MIPS16OP_SH_RX,   1, 1, 0 },
14275   { '4',  4, 15, 0, MIPS16OP_SH_IMM4, 0, 0, 0 },
14276   { '5',  5, 16, 0, MIPS16OP_SH_IMM5, 1, 0, 0 },
14277   { 'H',  5, 16, 1, MIPS16OP_SH_IMM5, 1, 0, 0 },
14278   { 'W',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 0 },
14279   { 'D',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 0 },
14280   { 'j',  5, 16, 0, MIPS16OP_SH_IMM5, 0, 0, 0 },
14281   { '8',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 0, 0 },
14282   { 'V',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 0 },
14283   { 'C',  8, 16, 3, MIPS16OP_SH_IMM8, 1, 0, 0 },
14284   { 'U',  8, 16, 0, MIPS16OP_SH_IMM8, 1, 1, 0 },
14285   { 'k',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 0 },
14286   { 'K',  8, 16, 3, MIPS16OP_SH_IMM8, 0, 0, 0 },
14287   { 'p',  8, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14288   { 'q', 11, 16, 0, MIPS16OP_SH_IMM8, 0, 0, 1 },
14289   { 'A',  8, 16, 2, MIPS16OP_SH_IMM8, 1, 0, 1 },
14290   { 'B',  5, 16, 3, MIPS16OP_SH_IMM5, 1, 0, 1 },
14291   { 'E',  5, 16, 2, MIPS16OP_SH_IMM5, 1, 0, 1 }
14292 };
14293
14294 #define MIPS16_NUM_IMMED \
14295   (sizeof mips16_immed_operands / sizeof mips16_immed_operands[0])
14296
14297 /* Marshal immediate value VAL for an extended MIPS16 instruction.
14298    NBITS is the number of significant bits in VAL.  */
14299
14300 static unsigned long
14301 mips16_immed_extend (offsetT val, unsigned int nbits)
14302 {
14303   int extval;
14304   if (nbits == 16)
14305     {
14306       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
14307       val &= 0x1f;
14308     }
14309   else if (nbits == 15)
14310     {
14311       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
14312       val &= 0xf;
14313     }
14314   else
14315     {
14316       extval = ((val & 0x1f) << 6) | (val & 0x20);
14317       val = 0;
14318     }
14319   return (extval << 16) | val;
14320 }
14321
14322 /* Install immediate value VAL into MIPS16 instruction *INSN,
14323    extending it if necessary.  The instruction in *INSN may
14324    already be extended.
14325
14326    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
14327    if none.  In the former case, VAL is a 16-bit number with no
14328    defined signedness.
14329
14330    TYPE is the type of the immediate field.  USER_INSN_LENGTH
14331    is the length that the user requested, or 0 if none.  */
14332
14333 static void
14334 mips16_immed (char *file, unsigned int line, int type,
14335               bfd_reloc_code_real_type reloc, offsetT val,
14336               unsigned int user_insn_length, unsigned long *insn)
14337 {
14338   const struct mips16_immed_operand *op;
14339   int mintiny, maxtiny;
14340
14341   op = mips16_immed_operands;
14342   while (op->type != type)
14343     {
14344       ++op;
14345       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
14346     }
14347
14348   if (op->unsp)
14349     {
14350       if (type == '<' || type == '>' || type == '[' || type == ']')
14351         {
14352           mintiny = 1;
14353           maxtiny = 1 << op->nbits;
14354         }
14355       else
14356         {
14357           mintiny = 0;
14358           maxtiny = (1 << op->nbits) - 1;
14359         }
14360       if (reloc != BFD_RELOC_UNUSED)
14361         val &= 0xffff;
14362     }
14363   else
14364     {
14365       mintiny = - (1 << (op->nbits - 1));
14366       maxtiny = (1 << (op->nbits - 1)) - 1;
14367       if (reloc != BFD_RELOC_UNUSED)
14368         val = SEXT_16BIT (val);
14369     }
14370
14371   /* Branch offsets have an implicit 0 in the lowest bit.  */
14372   if (type == 'p' || type == 'q')
14373     val /= 2;
14374
14375   if ((val & ((1 << op->shift) - 1)) != 0
14376       || val < (mintiny << op->shift)
14377       || val > (maxtiny << op->shift))
14378     {
14379       /* We need an extended instruction.  */
14380       if (user_insn_length == 2)
14381         as_bad_where (file, line, _("invalid unextended operand value"));
14382       else
14383         *insn |= MIPS16_EXTEND;
14384     }
14385   else if (user_insn_length == 4)
14386     {
14387       /* The operand doesn't force an unextended instruction to be extended.
14388          Warn if the user wanted an extended instruction anyway.  */
14389       *insn |= MIPS16_EXTEND;
14390       as_warn_where (file, line,
14391                      _("extended operand requested but not required"));
14392     }
14393
14394   if (mips16_opcode_length (*insn) == 2)
14395     {
14396       int insnval;
14397
14398       insnval = ((val >> op->shift) & ((1 << op->nbits) - 1));
14399       insnval <<= op->op_shift;
14400       *insn |= insnval;
14401     }
14402   else
14403     {
14404       long minext, maxext;
14405
14406       if (reloc == BFD_RELOC_UNUSED)
14407         {
14408           if (op->extu)
14409             {
14410               minext = 0;
14411               maxext = (1 << op->extbits) - 1;
14412             }
14413           else
14414             {
14415               minext = - (1 << (op->extbits - 1));
14416               maxext = (1 << (op->extbits - 1)) - 1;
14417             }
14418           if (val < minext || val > maxext)
14419             as_bad_where (file, line,
14420                           _("operand value out of range for instruction"));
14421         }
14422
14423       *insn |= mips16_immed_extend (val, op->extbits);
14424     }
14425 }
14426 \f
14427 struct percent_op_match
14428 {
14429   const char *str;
14430   bfd_reloc_code_real_type reloc;
14431 };
14432
14433 static const struct percent_op_match mips_percent_op[] =
14434 {
14435   {"%lo", BFD_RELOC_LO16},
14436   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
14437   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
14438   {"%call16", BFD_RELOC_MIPS_CALL16},
14439   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
14440   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
14441   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
14442   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
14443   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
14444   {"%got", BFD_RELOC_MIPS_GOT16},
14445   {"%gp_rel", BFD_RELOC_GPREL16},
14446   {"%half", BFD_RELOC_16},
14447   {"%highest", BFD_RELOC_MIPS_HIGHEST},
14448   {"%higher", BFD_RELOC_MIPS_HIGHER},
14449   {"%neg", BFD_RELOC_MIPS_SUB},
14450   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
14451   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
14452   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
14453   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
14454   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
14455   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
14456   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
14457   {"%hi", BFD_RELOC_HI16_S}
14458 };
14459
14460 static const struct percent_op_match mips16_percent_op[] =
14461 {
14462   {"%lo", BFD_RELOC_MIPS16_LO16},
14463   {"%gprel", BFD_RELOC_MIPS16_GPREL},
14464   {"%got", BFD_RELOC_MIPS16_GOT16},
14465   {"%call16", BFD_RELOC_MIPS16_CALL16},
14466   {"%hi", BFD_RELOC_MIPS16_HI16_S},
14467   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
14468   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
14469   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
14470   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
14471   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
14472   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
14473   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
14474 };
14475
14476
14477 /* Return true if *STR points to a relocation operator.  When returning true,
14478    move *STR over the operator and store its relocation code in *RELOC.
14479    Leave both *STR and *RELOC alone when returning false.  */
14480
14481 static bfd_boolean
14482 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
14483 {
14484   const struct percent_op_match *percent_op;
14485   size_t limit, i;
14486
14487   if (mips_opts.mips16)
14488     {
14489       percent_op = mips16_percent_op;
14490       limit = ARRAY_SIZE (mips16_percent_op);
14491     }
14492   else
14493     {
14494       percent_op = mips_percent_op;
14495       limit = ARRAY_SIZE (mips_percent_op);
14496     }
14497
14498   for (i = 0; i < limit; i++)
14499     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
14500       {
14501         int len = strlen (percent_op[i].str);
14502
14503         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
14504           continue;
14505
14506         *str += strlen (percent_op[i].str);
14507         *reloc = percent_op[i].reloc;
14508
14509         /* Check whether the output BFD supports this relocation.
14510            If not, issue an error and fall back on something safe.  */
14511         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
14512           {
14513             as_bad (_("relocation %s isn't supported by the current ABI"),
14514                     percent_op[i].str);
14515             *reloc = BFD_RELOC_UNUSED;
14516           }
14517         return TRUE;
14518       }
14519   return FALSE;
14520 }
14521
14522
14523 /* Parse string STR as a 16-bit relocatable operand.  Store the
14524    expression in *EP and the relocations in the array starting
14525    at RELOC.  Return the number of relocation operators used.
14526
14527    On exit, EXPR_END points to the first character after the expression.  */
14528
14529 static size_t
14530 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
14531                        char *str)
14532 {
14533   bfd_reloc_code_real_type reversed_reloc[3];
14534   size_t reloc_index, i;
14535   int crux_depth, str_depth;
14536   char *crux;
14537
14538   /* Search for the start of the main expression, recoding relocations
14539      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
14540      of the main expression and with CRUX_DEPTH containing the number
14541      of open brackets at that point.  */
14542   reloc_index = -1;
14543   str_depth = 0;
14544   do
14545     {
14546       reloc_index++;
14547       crux = str;
14548       crux_depth = str_depth;
14549
14550       /* Skip over whitespace and brackets, keeping count of the number
14551          of brackets.  */
14552       while (*str == ' ' || *str == '\t' || *str == '(')
14553         if (*str++ == '(')
14554           str_depth++;
14555     }
14556   while (*str == '%'
14557          && reloc_index < (HAVE_NEWABI ? 3 : 1)
14558          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14559
14560   my_getExpression (ep, crux);
14561   str = expr_end;
14562
14563   /* Match every open bracket.  */
14564   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14565     if (*str++ == ')')
14566       crux_depth--;
14567
14568   if (crux_depth > 0)
14569     as_bad (_("unclosed '('"));
14570
14571   expr_end = str;
14572
14573   if (reloc_index != 0)
14574     {
14575       prev_reloc_op_frag = frag_now;
14576       for (i = 0; i < reloc_index; i++)
14577         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14578     }
14579
14580   return reloc_index;
14581 }
14582
14583 static void
14584 my_getExpression (expressionS *ep, char *str)
14585 {
14586   char *save_in;
14587
14588   save_in = input_line_pointer;
14589   input_line_pointer = str;
14590   expression (ep);
14591   expr_end = input_line_pointer;
14592   input_line_pointer = save_in;
14593 }
14594
14595 char *
14596 md_atof (int type, char *litP, int *sizeP)
14597 {
14598   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14599 }
14600
14601 void
14602 md_number_to_chars (char *buf, valueT val, int n)
14603 {
14604   if (target_big_endian)
14605     number_to_chars_bigendian (buf, val, n);
14606   else
14607     number_to_chars_littleendian (buf, val, n);
14608 }
14609 \f
14610 static int support_64bit_objects(void)
14611 {
14612   const char **list, **l;
14613   int yes;
14614
14615   list = bfd_target_list ();
14616   for (l = list; *l != NULL; l++)
14617     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14618         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14619       break;
14620   yes = (*l != NULL);
14621   free (list);
14622   return yes;
14623 }
14624
14625 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14626    NEW_VALUE.  Warn if another value was already specified.  Note:
14627    we have to defer parsing the -march and -mtune arguments in order
14628    to handle 'from-abi' correctly, since the ABI might be specified
14629    in a later argument.  */
14630
14631 static void
14632 mips_set_option_string (const char **string_ptr, const char *new_value)
14633 {
14634   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14635     as_warn (_("A different %s was already specified, is now %s"),
14636              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14637              new_value);
14638
14639   *string_ptr = new_value;
14640 }
14641
14642 int
14643 md_parse_option (int c, char *arg)
14644 {
14645   unsigned int i;
14646
14647   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14648     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14649       {
14650         file_ase_explicit |= mips_set_ase (&mips_ases[i],
14651                                            c == mips_ases[i].option_on);
14652         return 1;
14653       }
14654
14655   switch (c)
14656     {
14657     case OPTION_CONSTRUCT_FLOATS:
14658       mips_disable_float_construction = 0;
14659       break;
14660
14661     case OPTION_NO_CONSTRUCT_FLOATS:
14662       mips_disable_float_construction = 1;
14663       break;
14664
14665     case OPTION_TRAP:
14666       mips_trap = 1;
14667       break;
14668
14669     case OPTION_BREAK:
14670       mips_trap = 0;
14671       break;
14672
14673     case OPTION_EB:
14674       target_big_endian = 1;
14675       break;
14676
14677     case OPTION_EL:
14678       target_big_endian = 0;
14679       break;
14680
14681     case 'O':
14682       if (arg == NULL)
14683         mips_optimize = 1;
14684       else if (arg[0] == '0')
14685         mips_optimize = 0;
14686       else if (arg[0] == '1')
14687         mips_optimize = 1;
14688       else
14689         mips_optimize = 2;
14690       break;
14691
14692     case 'g':
14693       if (arg == NULL)
14694         mips_debug = 2;
14695       else
14696         mips_debug = atoi (arg);
14697       break;
14698
14699     case OPTION_MIPS1:
14700       file_mips_isa = ISA_MIPS1;
14701       break;
14702
14703     case OPTION_MIPS2:
14704       file_mips_isa = ISA_MIPS2;
14705       break;
14706
14707     case OPTION_MIPS3:
14708       file_mips_isa = ISA_MIPS3;
14709       break;
14710
14711     case OPTION_MIPS4:
14712       file_mips_isa = ISA_MIPS4;
14713       break;
14714
14715     case OPTION_MIPS5:
14716       file_mips_isa = ISA_MIPS5;
14717       break;
14718
14719     case OPTION_MIPS32:
14720       file_mips_isa = ISA_MIPS32;
14721       break;
14722
14723     case OPTION_MIPS32R2:
14724       file_mips_isa = ISA_MIPS32R2;
14725       break;
14726
14727     case OPTION_MIPS64R2:
14728       file_mips_isa = ISA_MIPS64R2;
14729       break;
14730
14731     case OPTION_MIPS64:
14732       file_mips_isa = ISA_MIPS64;
14733       break;
14734
14735     case OPTION_MTUNE:
14736       mips_set_option_string (&mips_tune_string, arg);
14737       break;
14738
14739     case OPTION_MARCH:
14740       mips_set_option_string (&mips_arch_string, arg);
14741       break;
14742
14743     case OPTION_M4650:
14744       mips_set_option_string (&mips_arch_string, "4650");
14745       mips_set_option_string (&mips_tune_string, "4650");
14746       break;
14747
14748     case OPTION_NO_M4650:
14749       break;
14750
14751     case OPTION_M4010:
14752       mips_set_option_string (&mips_arch_string, "4010");
14753       mips_set_option_string (&mips_tune_string, "4010");
14754       break;
14755
14756     case OPTION_NO_M4010:
14757       break;
14758
14759     case OPTION_M4100:
14760       mips_set_option_string (&mips_arch_string, "4100");
14761       mips_set_option_string (&mips_tune_string, "4100");
14762       break;
14763
14764     case OPTION_NO_M4100:
14765       break;
14766
14767     case OPTION_M3900:
14768       mips_set_option_string (&mips_arch_string, "3900");
14769       mips_set_option_string (&mips_tune_string, "3900");
14770       break;
14771
14772     case OPTION_NO_M3900:
14773       break;
14774
14775     case OPTION_MICROMIPS:
14776       if (mips_opts.mips16 == 1)
14777         {
14778           as_bad (_("-mmicromips cannot be used with -mips16"));
14779           return 0;
14780         }
14781       mips_opts.micromips = 1;
14782       mips_no_prev_insn ();
14783       break;
14784
14785     case OPTION_NO_MICROMIPS:
14786       mips_opts.micromips = 0;
14787       mips_no_prev_insn ();
14788       break;
14789
14790     case OPTION_MIPS16:
14791       if (mips_opts.micromips == 1)
14792         {
14793           as_bad (_("-mips16 cannot be used with -micromips"));
14794           return 0;
14795         }
14796       mips_opts.mips16 = 1;
14797       mips_no_prev_insn ();
14798       break;
14799
14800     case OPTION_NO_MIPS16:
14801       mips_opts.mips16 = 0;
14802       mips_no_prev_insn ();
14803       break;
14804
14805     case OPTION_FIX_24K:
14806       mips_fix_24k = 1;
14807       break;
14808
14809     case OPTION_NO_FIX_24K:
14810       mips_fix_24k = 0;
14811       break;
14812
14813     case OPTION_FIX_LOONGSON2F_JUMP:
14814       mips_fix_loongson2f_jump = TRUE;
14815       break;
14816
14817     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14818       mips_fix_loongson2f_jump = FALSE;
14819       break;
14820
14821     case OPTION_FIX_LOONGSON2F_NOP:
14822       mips_fix_loongson2f_nop = TRUE;
14823       break;
14824
14825     case OPTION_NO_FIX_LOONGSON2F_NOP:
14826       mips_fix_loongson2f_nop = FALSE;
14827       break;
14828
14829     case OPTION_FIX_VR4120:
14830       mips_fix_vr4120 = 1;
14831       break;
14832
14833     case OPTION_NO_FIX_VR4120:
14834       mips_fix_vr4120 = 0;
14835       break;
14836
14837     case OPTION_FIX_VR4130:
14838       mips_fix_vr4130 = 1;
14839       break;
14840
14841     case OPTION_NO_FIX_VR4130:
14842       mips_fix_vr4130 = 0;
14843       break;
14844
14845     case OPTION_FIX_CN63XXP1:
14846       mips_fix_cn63xxp1 = TRUE;
14847       break;
14848
14849     case OPTION_NO_FIX_CN63XXP1:
14850       mips_fix_cn63xxp1 = FALSE;
14851       break;
14852
14853     case OPTION_RELAX_BRANCH:
14854       mips_relax_branch = 1;
14855       break;
14856
14857     case OPTION_NO_RELAX_BRANCH:
14858       mips_relax_branch = 0;
14859       break;
14860
14861     case OPTION_INSN32:
14862       mips_opts.insn32 = TRUE;
14863       break;
14864
14865     case OPTION_NO_INSN32:
14866       mips_opts.insn32 = FALSE;
14867       break;
14868
14869     case OPTION_MSHARED:
14870       mips_in_shared = TRUE;
14871       break;
14872
14873     case OPTION_MNO_SHARED:
14874       mips_in_shared = FALSE;
14875       break;
14876
14877     case OPTION_MSYM32:
14878       mips_opts.sym32 = TRUE;
14879       break;
14880
14881     case OPTION_MNO_SYM32:
14882       mips_opts.sym32 = FALSE;
14883       break;
14884
14885       /* When generating ELF code, we permit -KPIC and -call_shared to
14886          select SVR4_PIC, and -non_shared to select no PIC.  This is
14887          intended to be compatible with Irix 5.  */
14888     case OPTION_CALL_SHARED:
14889       mips_pic = SVR4_PIC;
14890       mips_abicalls = TRUE;
14891       break;
14892
14893     case OPTION_CALL_NONPIC:
14894       mips_pic = NO_PIC;
14895       mips_abicalls = TRUE;
14896       break;
14897
14898     case OPTION_NON_SHARED:
14899       mips_pic = NO_PIC;
14900       mips_abicalls = FALSE;
14901       break;
14902
14903       /* The -xgot option tells the assembler to use 32 bit offsets
14904          when accessing the got in SVR4_PIC mode.  It is for Irix
14905          compatibility.  */
14906     case OPTION_XGOT:
14907       mips_big_got = 1;
14908       break;
14909
14910     case 'G':
14911       g_switch_value = atoi (arg);
14912       g_switch_seen = 1;
14913       break;
14914
14915       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14916          and -mabi=64.  */
14917     case OPTION_32:
14918       mips_abi = O32_ABI;
14919       break;
14920
14921     case OPTION_N32:
14922       mips_abi = N32_ABI;
14923       break;
14924
14925     case OPTION_64:
14926       mips_abi = N64_ABI;
14927       if (!support_64bit_objects())
14928         as_fatal (_("No compiled in support for 64 bit object file format"));
14929       break;
14930
14931     case OPTION_GP32:
14932       file_mips_gp32 = 1;
14933       break;
14934
14935     case OPTION_GP64:
14936       file_mips_gp32 = 0;
14937       break;
14938
14939     case OPTION_FP32:
14940       file_mips_fp32 = 1;
14941       break;
14942
14943     case OPTION_FP64:
14944       file_mips_fp32 = 0;
14945       break;
14946
14947     case OPTION_SINGLE_FLOAT:
14948       file_mips_single_float = 1;
14949       break;
14950
14951     case OPTION_DOUBLE_FLOAT:
14952       file_mips_single_float = 0;
14953       break;
14954
14955     case OPTION_SOFT_FLOAT:
14956       file_mips_soft_float = 1;
14957       break;
14958
14959     case OPTION_HARD_FLOAT:
14960       file_mips_soft_float = 0;
14961       break;
14962
14963     case OPTION_MABI:
14964       if (strcmp (arg, "32") == 0)
14965         mips_abi = O32_ABI;
14966       else if (strcmp (arg, "o64") == 0)
14967         mips_abi = O64_ABI;
14968       else if (strcmp (arg, "n32") == 0)
14969         mips_abi = N32_ABI;
14970       else if (strcmp (arg, "64") == 0)
14971         {
14972           mips_abi = N64_ABI;
14973           if (! support_64bit_objects())
14974             as_fatal (_("No compiled in support for 64 bit object file "
14975                         "format"));
14976         }
14977       else if (strcmp (arg, "eabi") == 0)
14978         mips_abi = EABI_ABI;
14979       else
14980         {
14981           as_fatal (_("invalid abi -mabi=%s"), arg);
14982           return 0;
14983         }
14984       break;
14985
14986     case OPTION_M7000_HILO_FIX:
14987       mips_7000_hilo_fix = TRUE;
14988       break;
14989
14990     case OPTION_MNO_7000_HILO_FIX:
14991       mips_7000_hilo_fix = FALSE;
14992       break;
14993
14994     case OPTION_MDEBUG:
14995       mips_flag_mdebug = TRUE;
14996       break;
14997
14998     case OPTION_NO_MDEBUG:
14999       mips_flag_mdebug = FALSE;
15000       break;
15001
15002     case OPTION_PDR:
15003       mips_flag_pdr = TRUE;
15004       break;
15005
15006     case OPTION_NO_PDR:
15007       mips_flag_pdr = FALSE;
15008       break;
15009
15010     case OPTION_MVXWORKS_PIC:
15011       mips_pic = VXWORKS_PIC;
15012       break;
15013
15014     case OPTION_NAN:
15015       if (strcmp (arg, "2008") == 0)
15016         mips_flag_nan2008 = TRUE;
15017       else if (strcmp (arg, "legacy") == 0)
15018         mips_flag_nan2008 = FALSE;
15019       else
15020         {
15021           as_fatal (_("Invalid NaN setting -mnan=%s"), arg);
15022           return 0;
15023         }
15024       break;
15025
15026     default:
15027       return 0;
15028     }
15029
15030     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
15031
15032   return 1;
15033 }
15034 \f
15035 /* Set up globals to generate code for the ISA or processor
15036    described by INFO.  */
15037
15038 static void
15039 mips_set_architecture (const struct mips_cpu_info *info)
15040 {
15041   if (info != 0)
15042     {
15043       file_mips_arch = info->cpu;
15044       mips_opts.arch = info->cpu;
15045       mips_opts.isa = info->isa;
15046     }
15047 }
15048
15049
15050 /* Likewise for tuning.  */
15051
15052 static void
15053 mips_set_tune (const struct mips_cpu_info *info)
15054 {
15055   if (info != 0)
15056     mips_tune = info->cpu;
15057 }
15058
15059
15060 void
15061 mips_after_parse_args (void)
15062 {
15063   const struct mips_cpu_info *arch_info = 0;
15064   const struct mips_cpu_info *tune_info = 0;
15065
15066   /* GP relative stuff not working for PE */
15067   if (strncmp (TARGET_OS, "pe", 2) == 0)
15068     {
15069       if (g_switch_seen && g_switch_value != 0)
15070         as_bad (_("-G not supported in this configuration."));
15071       g_switch_value = 0;
15072     }
15073
15074   if (mips_abi == NO_ABI)
15075     mips_abi = MIPS_DEFAULT_ABI;
15076
15077   /* The following code determines the architecture and register size.
15078      Similar code was added to GCC 3.3 (see override_options() in
15079      config/mips/mips.c).  The GAS and GCC code should be kept in sync
15080      as much as possible.  */
15081
15082   if (mips_arch_string != 0)
15083     arch_info = mips_parse_cpu ("-march", mips_arch_string);
15084
15085   if (file_mips_isa != ISA_UNKNOWN)
15086     {
15087       /* Handle -mipsN.  At this point, file_mips_isa contains the
15088          ISA level specified by -mipsN, while arch_info->isa contains
15089          the -march selection (if any).  */
15090       if (arch_info != 0)
15091         {
15092           /* -march takes precedence over -mipsN, since it is more descriptive.
15093              There's no harm in specifying both as long as the ISA levels
15094              are the same.  */
15095           if (file_mips_isa != arch_info->isa)
15096             as_bad (_("-%s conflicts with the other architecture options, which imply -%s"),
15097                     mips_cpu_info_from_isa (file_mips_isa)->name,
15098                     mips_cpu_info_from_isa (arch_info->isa)->name);
15099         }
15100       else
15101         arch_info = mips_cpu_info_from_isa (file_mips_isa);
15102     }
15103
15104   if (arch_info == 0)
15105     {
15106       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
15107       gas_assert (arch_info);
15108     }
15109
15110   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
15111     as_bad (_("-march=%s is not compatible with the selected ABI"),
15112             arch_info->name);
15113
15114   mips_set_architecture (arch_info);
15115
15116   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
15117   if (mips_tune_string != 0)
15118     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
15119
15120   if (tune_info == 0)
15121     mips_set_tune (arch_info);
15122   else
15123     mips_set_tune (tune_info);
15124
15125   if (file_mips_gp32 >= 0)
15126     {
15127       /* The user specified the size of the integer registers.  Make sure
15128          it agrees with the ABI and ISA.  */
15129       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
15130         as_bad (_("-mgp64 used with a 32-bit processor"));
15131       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
15132         as_bad (_("-mgp32 used with a 64-bit ABI"));
15133       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
15134         as_bad (_("-mgp64 used with a 32-bit ABI"));
15135     }
15136   else
15137     {
15138       /* Infer the integer register size from the ABI and processor.
15139          Restrict ourselves to 32-bit registers if that's all the
15140          processor has, or if the ABI cannot handle 64-bit registers.  */
15141       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
15142                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
15143     }
15144
15145   switch (file_mips_fp32)
15146     {
15147     default:
15148     case -1:
15149       /* No user specified float register size.
15150          ??? GAS treats single-float processors as though they had 64-bit
15151          float registers (although it complains when double-precision
15152          instructions are used).  As things stand, saying they have 32-bit
15153          registers would lead to spurious "register must be even" messages.
15154          So here we assume float registers are never smaller than the
15155          integer ones.  */
15156       if (file_mips_gp32 == 0)
15157         /* 64-bit integer registers implies 64-bit float registers.  */
15158         file_mips_fp32 = 0;
15159       else if ((mips_opts.ase & FP64_ASES)
15160                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
15161         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
15162         file_mips_fp32 = 0;
15163       else
15164         /* 32-bit float registers.  */
15165         file_mips_fp32 = 1;
15166       break;
15167
15168     /* The user specified the size of the float registers.  Check if it
15169        agrees with the ABI and ISA.  */
15170     case 0:
15171       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15172         as_bad (_("-mfp64 used with a 32-bit fpu"));
15173       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
15174                && !ISA_HAS_MXHC1 (mips_opts.isa))
15175         as_warn (_("-mfp64 used with a 32-bit ABI"));
15176       break;
15177     case 1:
15178       if (ABI_NEEDS_64BIT_REGS (mips_abi))
15179         as_warn (_("-mfp32 used with a 64-bit ABI"));
15180       break;
15181     }
15182
15183   /* End of GCC-shared inference code.  */
15184
15185   /* This flag is set when we have a 64-bit capable CPU but use only
15186      32-bit wide registers.  Note that EABI does not use it.  */
15187   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
15188       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
15189           || mips_abi == O32_ABI))
15190     mips_32bitmode = 1;
15191
15192   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
15193     as_bad (_("trap exception not supported at ISA 1"));
15194
15195   /* If the selected architecture includes support for ASEs, enable
15196      generation of code for them.  */
15197   if (mips_opts.mips16 == -1)
15198     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
15199   if (mips_opts.micromips == -1)
15200     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
15201
15202   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
15203      ASEs from being selected implicitly.  */
15204   if (file_mips_fp32 == 1)
15205     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
15206
15207   /* If the user didn't explicitly select or deselect a particular ASE,
15208      use the default setting for the CPU.  */
15209   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
15210
15211   file_mips_isa = mips_opts.isa;
15212   file_ase = mips_opts.ase;
15213   mips_opts.gp32 = file_mips_gp32;
15214   mips_opts.fp32 = file_mips_fp32;
15215   mips_opts.soft_float = file_mips_soft_float;
15216   mips_opts.single_float = file_mips_single_float;
15217
15218   mips_check_isa_supports_ases ();
15219
15220   if (mips_flag_mdebug < 0)
15221     mips_flag_mdebug = 0;
15222 }
15223 \f
15224 void
15225 mips_init_after_args (void)
15226 {
15227   /* initialize opcodes */
15228   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
15229   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
15230 }
15231
15232 long
15233 md_pcrel_from (fixS *fixP)
15234 {
15235   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
15236   switch (fixP->fx_r_type)
15237     {
15238     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15239     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15240       /* Return the address of the delay slot.  */
15241       return addr + 2;
15242
15243     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15244     case BFD_RELOC_MICROMIPS_JMP:
15245     case BFD_RELOC_16_PCREL_S2:
15246     case BFD_RELOC_MIPS_JMP:
15247       /* Return the address of the delay slot.  */
15248       return addr + 4;
15249
15250     case BFD_RELOC_32_PCREL:
15251       return addr;
15252
15253     default:
15254       /* We have no relocation type for PC relative MIPS16 instructions.  */
15255       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
15256         as_bad_where (fixP->fx_file, fixP->fx_line,
15257                       _("PC relative MIPS16 instruction references a different section"));
15258       return addr;
15259     }
15260 }
15261
15262 /* This is called before the symbol table is processed.  In order to
15263    work with gcc when using mips-tfile, we must keep all local labels.
15264    However, in other cases, we want to discard them.  If we were
15265    called with -g, but we didn't see any debugging information, it may
15266    mean that gcc is smuggling debugging information through to
15267    mips-tfile, in which case we must generate all local labels.  */
15268
15269 void
15270 mips_frob_file_before_adjust (void)
15271 {
15272 #ifndef NO_ECOFF_DEBUGGING
15273   if (ECOFF_DEBUGGING
15274       && mips_debug != 0
15275       && ! ecoff_debugging_seen)
15276     flag_keep_locals = 1;
15277 #endif
15278 }
15279
15280 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
15281    the corresponding LO16 reloc.  This is called before md_apply_fix and
15282    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
15283    relocation operators.
15284
15285    For our purposes, a %lo() expression matches a %got() or %hi()
15286    expression if:
15287
15288       (a) it refers to the same symbol; and
15289       (b) the offset applied in the %lo() expression is no lower than
15290           the offset applied in the %got() or %hi().
15291
15292    (b) allows us to cope with code like:
15293
15294         lui     $4,%hi(foo)
15295         lh      $4,%lo(foo+2)($4)
15296
15297    ...which is legal on RELA targets, and has a well-defined behaviour
15298    if the user knows that adding 2 to "foo" will not induce a carry to
15299    the high 16 bits.
15300
15301    When several %lo()s match a particular %got() or %hi(), we use the
15302    following rules to distinguish them:
15303
15304      (1) %lo()s with smaller offsets are a better match than %lo()s with
15305          higher offsets.
15306
15307      (2) %lo()s with no matching %got() or %hi() are better than those
15308          that already have a matching %got() or %hi().
15309
15310      (3) later %lo()s are better than earlier %lo()s.
15311
15312    These rules are applied in order.
15313
15314    (1) means, among other things, that %lo()s with identical offsets are
15315    chosen if they exist.
15316
15317    (2) means that we won't associate several high-part relocations with
15318    the same low-part relocation unless there's no alternative.  Having
15319    several high parts for the same low part is a GNU extension; this rule
15320    allows careful users to avoid it.
15321
15322    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
15323    with the last high-part relocation being at the front of the list.
15324    It therefore makes sense to choose the last matching low-part
15325    relocation, all other things being equal.  It's also easier
15326    to code that way.  */
15327
15328 void
15329 mips_frob_file (void)
15330 {
15331   struct mips_hi_fixup *l;
15332   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
15333
15334   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
15335     {
15336       segment_info_type *seginfo;
15337       bfd_boolean matched_lo_p;
15338       fixS **hi_pos, **lo_pos, **pos;
15339
15340       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
15341
15342       /* If a GOT16 relocation turns out to be against a global symbol,
15343          there isn't supposed to be a matching LO.  Ignore %gots against
15344          constants; we'll report an error for those later.  */
15345       if (got16_reloc_p (l->fixp->fx_r_type)
15346           && !(l->fixp->fx_addsy
15347                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
15348         continue;
15349
15350       /* Check quickly whether the next fixup happens to be a matching %lo.  */
15351       if (fixup_has_matching_lo_p (l->fixp))
15352         continue;
15353
15354       seginfo = seg_info (l->seg);
15355
15356       /* Set HI_POS to the position of this relocation in the chain.
15357          Set LO_POS to the position of the chosen low-part relocation.
15358          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
15359          relocation that matches an immediately-preceding high-part
15360          relocation.  */
15361       hi_pos = NULL;
15362       lo_pos = NULL;
15363       matched_lo_p = FALSE;
15364       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
15365
15366       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
15367         {
15368           if (*pos == l->fixp)
15369             hi_pos = pos;
15370
15371           if ((*pos)->fx_r_type == looking_for_rtype
15372               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
15373               && (*pos)->fx_offset >= l->fixp->fx_offset
15374               && (lo_pos == NULL
15375                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
15376                   || (!matched_lo_p
15377                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
15378             lo_pos = pos;
15379
15380           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
15381                           && fixup_has_matching_lo_p (*pos));
15382         }
15383
15384       /* If we found a match, remove the high-part relocation from its
15385          current position and insert it before the low-part relocation.
15386          Make the offsets match so that fixup_has_matching_lo_p()
15387          will return true.
15388
15389          We don't warn about unmatched high-part relocations since some
15390          versions of gcc have been known to emit dead "lui ...%hi(...)"
15391          instructions.  */
15392       if (lo_pos != NULL)
15393         {
15394           l->fixp->fx_offset = (*lo_pos)->fx_offset;
15395           if (l->fixp->fx_next != *lo_pos)
15396             {
15397               *hi_pos = l->fixp->fx_next;
15398               l->fixp->fx_next = *lo_pos;
15399               *lo_pos = l->fixp;
15400             }
15401         }
15402     }
15403 }
15404
15405 int
15406 mips_force_relocation (fixS *fixp)
15407 {
15408   if (generic_force_reloc (fixp))
15409     return 1;
15410
15411   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
15412      so that the linker relaxation can update targets.  */
15413   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15414       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15415       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
15416     return 1;
15417
15418   return 0;
15419 }
15420
15421 /* Read the instruction associated with RELOC from BUF.  */
15422
15423 static unsigned int
15424 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
15425 {
15426   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15427     return read_compressed_insn (buf, 4);
15428   else
15429     return read_insn (buf);
15430 }
15431
15432 /* Write instruction INSN to BUF, given that it has been relocated
15433    by RELOC.  */
15434
15435 static void
15436 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
15437                   unsigned long insn)
15438 {
15439   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
15440     write_compressed_insn (buf, insn, 4);
15441   else
15442     write_insn (buf, insn);
15443 }
15444
15445 /* Apply a fixup to the object file.  */
15446
15447 void
15448 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15449 {
15450   char *buf;
15451   unsigned long insn;
15452   reloc_howto_type *howto;
15453
15454   /* We ignore generic BFD relocations we don't know about.  */
15455   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15456   if (! howto)
15457     return;
15458
15459   gas_assert (fixP->fx_size == 2
15460               || fixP->fx_size == 4
15461               || fixP->fx_r_type == BFD_RELOC_16
15462               || fixP->fx_r_type == BFD_RELOC_64
15463               || fixP->fx_r_type == BFD_RELOC_CTOR
15464               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15465               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15466               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15467               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15468               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
15469
15470   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15471
15472   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
15473               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
15474               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
15475               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
15476               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
15477
15478   /* Don't treat parts of a composite relocation as done.  There are two
15479      reasons for this:
15480
15481      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15482          should nevertheless be emitted if the first part is.
15483
15484      (2) In normal usage, composite relocations are never assembly-time
15485          constants.  The easiest way of dealing with the pathological
15486          exceptions is to generate a relocation against STN_UNDEF and
15487          leave everything up to the linker.  */
15488   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15489     fixP->fx_done = 1;
15490
15491   switch (fixP->fx_r_type)
15492     {
15493     case BFD_RELOC_MIPS_TLS_GD:
15494     case BFD_RELOC_MIPS_TLS_LDM:
15495     case BFD_RELOC_MIPS_TLS_DTPREL32:
15496     case BFD_RELOC_MIPS_TLS_DTPREL64:
15497     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15498     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15499     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15500     case BFD_RELOC_MIPS_TLS_TPREL32:
15501     case BFD_RELOC_MIPS_TLS_TPREL64:
15502     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15503     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15504     case BFD_RELOC_MICROMIPS_TLS_GD:
15505     case BFD_RELOC_MICROMIPS_TLS_LDM:
15506     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15507     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15508     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15509     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15510     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15511     case BFD_RELOC_MIPS16_TLS_GD:
15512     case BFD_RELOC_MIPS16_TLS_LDM:
15513     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15514     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15515     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15516     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15517     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15518       if (!fixP->fx_addsy)
15519         {
15520           as_bad_where (fixP->fx_file, fixP->fx_line,
15521                         _("TLS relocation against a constant"));
15522           break;
15523         }
15524       S_SET_THREAD_LOCAL (fixP->fx_addsy);
15525       /* fall through */
15526
15527     case BFD_RELOC_MIPS_JMP:
15528     case BFD_RELOC_MIPS_SHIFT5:
15529     case BFD_RELOC_MIPS_SHIFT6:
15530     case BFD_RELOC_MIPS_GOT_DISP:
15531     case BFD_RELOC_MIPS_GOT_PAGE:
15532     case BFD_RELOC_MIPS_GOT_OFST:
15533     case BFD_RELOC_MIPS_SUB:
15534     case BFD_RELOC_MIPS_INSERT_A:
15535     case BFD_RELOC_MIPS_INSERT_B:
15536     case BFD_RELOC_MIPS_DELETE:
15537     case BFD_RELOC_MIPS_HIGHEST:
15538     case BFD_RELOC_MIPS_HIGHER:
15539     case BFD_RELOC_MIPS_SCN_DISP:
15540     case BFD_RELOC_MIPS_REL16:
15541     case BFD_RELOC_MIPS_RELGOT:
15542     case BFD_RELOC_MIPS_JALR:
15543     case BFD_RELOC_HI16:
15544     case BFD_RELOC_HI16_S:
15545     case BFD_RELOC_LO16:
15546     case BFD_RELOC_GPREL16:
15547     case BFD_RELOC_MIPS_LITERAL:
15548     case BFD_RELOC_MIPS_CALL16:
15549     case BFD_RELOC_MIPS_GOT16:
15550     case BFD_RELOC_GPREL32:
15551     case BFD_RELOC_MIPS_GOT_HI16:
15552     case BFD_RELOC_MIPS_GOT_LO16:
15553     case BFD_RELOC_MIPS_CALL_HI16:
15554     case BFD_RELOC_MIPS_CALL_LO16:
15555     case BFD_RELOC_MIPS16_GPREL:
15556     case BFD_RELOC_MIPS16_GOT16:
15557     case BFD_RELOC_MIPS16_CALL16:
15558     case BFD_RELOC_MIPS16_HI16:
15559     case BFD_RELOC_MIPS16_HI16_S:
15560     case BFD_RELOC_MIPS16_LO16:
15561     case BFD_RELOC_MIPS16_JMP:
15562     case BFD_RELOC_MICROMIPS_JMP:
15563     case BFD_RELOC_MICROMIPS_GOT_DISP:
15564     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15565     case BFD_RELOC_MICROMIPS_GOT_OFST:
15566     case BFD_RELOC_MICROMIPS_SUB:
15567     case BFD_RELOC_MICROMIPS_HIGHEST:
15568     case BFD_RELOC_MICROMIPS_HIGHER:
15569     case BFD_RELOC_MICROMIPS_SCN_DISP:
15570     case BFD_RELOC_MICROMIPS_JALR:
15571     case BFD_RELOC_MICROMIPS_HI16:
15572     case BFD_RELOC_MICROMIPS_HI16_S:
15573     case BFD_RELOC_MICROMIPS_LO16:
15574     case BFD_RELOC_MICROMIPS_GPREL16:
15575     case BFD_RELOC_MICROMIPS_LITERAL:
15576     case BFD_RELOC_MICROMIPS_CALL16:
15577     case BFD_RELOC_MICROMIPS_GOT16:
15578     case BFD_RELOC_MICROMIPS_GOT_HI16:
15579     case BFD_RELOC_MICROMIPS_GOT_LO16:
15580     case BFD_RELOC_MICROMIPS_CALL_HI16:
15581     case BFD_RELOC_MICROMIPS_CALL_LO16:
15582     case BFD_RELOC_MIPS_EH:
15583       if (fixP->fx_done)
15584         {
15585           offsetT value;
15586
15587           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15588             {
15589               insn = read_reloc_insn (buf, fixP->fx_r_type);
15590               if (mips16_reloc_p (fixP->fx_r_type))
15591                 insn |= mips16_immed_extend (value, 16);
15592               else
15593                 insn |= (value & 0xffff);
15594               write_reloc_insn (buf, fixP->fx_r_type, insn);
15595             }
15596           else
15597             as_bad_where (fixP->fx_file, fixP->fx_line,
15598                           _("Unsupported constant in relocation"));
15599         }
15600       break;
15601
15602     case BFD_RELOC_64:
15603       /* This is handled like BFD_RELOC_32, but we output a sign
15604          extended value if we are only 32 bits.  */
15605       if (fixP->fx_done)
15606         {
15607           if (8 <= sizeof (valueT))
15608             md_number_to_chars (buf, *valP, 8);
15609           else
15610             {
15611               valueT hiv;
15612
15613               if ((*valP & 0x80000000) != 0)
15614                 hiv = 0xffffffff;
15615               else
15616                 hiv = 0;
15617               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15618               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15619             }
15620         }
15621       break;
15622
15623     case BFD_RELOC_RVA:
15624     case BFD_RELOC_32:
15625     case BFD_RELOC_32_PCREL:
15626     case BFD_RELOC_16:
15627       /* If we are deleting this reloc entry, we must fill in the
15628          value now.  This can happen if we have a .word which is not
15629          resolved when it appears but is later defined.  */
15630       if (fixP->fx_done)
15631         md_number_to_chars (buf, *valP, fixP->fx_size);
15632       break;
15633
15634     case BFD_RELOC_16_PCREL_S2:
15635       if ((*valP & 0x3) != 0)
15636         as_bad_where (fixP->fx_file, fixP->fx_line,
15637                       _("Branch to misaligned address (%lx)"), (long) *valP);
15638
15639       /* We need to save the bits in the instruction since fixup_segment()
15640          might be deleting the relocation entry (i.e., a branch within
15641          the current segment).  */
15642       if (! fixP->fx_done)
15643         break;
15644
15645       /* Update old instruction data.  */
15646       insn = read_insn (buf);
15647
15648       if (*valP + 0x20000 <= 0x3ffff)
15649         {
15650           insn |= (*valP >> 2) & 0xffff;
15651           write_insn (buf, insn);
15652         }
15653       else if (mips_pic == NO_PIC
15654                && fixP->fx_done
15655                && fixP->fx_frag->fr_address >= text_section->vma
15656                && (fixP->fx_frag->fr_address
15657                    < text_section->vma + bfd_get_section_size (text_section))
15658                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15659                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15660                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15661         {
15662           /* The branch offset is too large.  If this is an
15663              unconditional branch, and we are not generating PIC code,
15664              we can convert it to an absolute jump instruction.  */
15665           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15666             insn = 0x0c000000;  /* jal */
15667           else
15668             insn = 0x08000000;  /* j */
15669           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15670           fixP->fx_done = 0;
15671           fixP->fx_addsy = section_symbol (text_section);
15672           *valP += md_pcrel_from (fixP);
15673           write_insn (buf, insn);
15674         }
15675       else
15676         {
15677           /* If we got here, we have branch-relaxation disabled,
15678              and there's nothing we can do to fix this instruction
15679              without turning it into a longer sequence.  */
15680           as_bad_where (fixP->fx_file, fixP->fx_line,
15681                         _("Branch out of range"));
15682         }
15683       break;
15684
15685     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15686     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15687     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15688       /* We adjust the offset back to even.  */
15689       if ((*valP & 0x1) != 0)
15690         --(*valP);
15691
15692       if (! fixP->fx_done)
15693         break;
15694
15695       /* Should never visit here, because we keep the relocation.  */
15696       abort ();
15697       break;
15698
15699     case BFD_RELOC_VTABLE_INHERIT:
15700       fixP->fx_done = 0;
15701       if (fixP->fx_addsy
15702           && !S_IS_DEFINED (fixP->fx_addsy)
15703           && !S_IS_WEAK (fixP->fx_addsy))
15704         S_SET_WEAK (fixP->fx_addsy);
15705       break;
15706
15707     case BFD_RELOC_VTABLE_ENTRY:
15708       fixP->fx_done = 0;
15709       break;
15710
15711     default:
15712       abort ();
15713     }
15714
15715   /* Remember value for tc_gen_reloc.  */
15716   fixP->fx_addnumber = *valP;
15717 }
15718
15719 static symbolS *
15720 get_symbol (void)
15721 {
15722   int c;
15723   char *name;
15724   symbolS *p;
15725
15726   name = input_line_pointer;
15727   c = get_symbol_end ();
15728   p = (symbolS *) symbol_find_or_make (name);
15729   *input_line_pointer = c;
15730   return p;
15731 }
15732
15733 /* Align the current frag to a given power of two.  If a particular
15734    fill byte should be used, FILL points to an integer that contains
15735    that byte, otherwise FILL is null.
15736
15737    This function used to have the comment:
15738
15739       The MIPS assembler also automatically adjusts any preceding label.
15740
15741    The implementation therefore applied the adjustment to a maximum of
15742    one label.  However, other label adjustments are applied to batches
15743    of labels, and adjusting just one caused problems when new labels
15744    were added for the sake of debugging or unwind information.
15745    We therefore adjust all preceding labels (given as LABELS) instead.  */
15746
15747 static void
15748 mips_align (int to, int *fill, struct insn_label_list *labels)
15749 {
15750   mips_emit_delays ();
15751   mips_record_compressed_mode ();
15752   if (fill == NULL && subseg_text_p (now_seg))
15753     frag_align_code (to, 0);
15754   else
15755     frag_align (to, fill ? *fill : 0, 0);
15756   record_alignment (now_seg, to);
15757   mips_move_labels (labels, FALSE);
15758 }
15759
15760 /* Align to a given power of two.  .align 0 turns off the automatic
15761    alignment used by the data creating pseudo-ops.  */
15762
15763 static void
15764 s_align (int x ATTRIBUTE_UNUSED)
15765 {
15766   int temp, fill_value, *fill_ptr;
15767   long max_alignment = 28;
15768
15769   /* o Note that the assembler pulls down any immediately preceding label
15770        to the aligned address.
15771      o It's not documented but auto alignment is reinstated by
15772        a .align pseudo instruction.
15773      o Note also that after auto alignment is turned off the mips assembler
15774        issues an error on attempt to assemble an improperly aligned data item.
15775        We don't.  */
15776
15777   temp = get_absolute_expression ();
15778   if (temp > max_alignment)
15779     as_bad (_("Alignment too large: %d. assumed."), temp = max_alignment);
15780   else if (temp < 0)
15781     {
15782       as_warn (_("Alignment negative: 0 assumed."));
15783       temp = 0;
15784     }
15785   if (*input_line_pointer == ',')
15786     {
15787       ++input_line_pointer;
15788       fill_value = get_absolute_expression ();
15789       fill_ptr = &fill_value;
15790     }
15791   else
15792     fill_ptr = 0;
15793   if (temp)
15794     {
15795       segment_info_type *si = seg_info (now_seg);
15796       struct insn_label_list *l = si->label_list;
15797       /* Auto alignment should be switched on by next section change.  */
15798       auto_align = 1;
15799       mips_align (temp, fill_ptr, l);
15800     }
15801   else
15802     {
15803       auto_align = 0;
15804     }
15805
15806   demand_empty_rest_of_line ();
15807 }
15808
15809 static void
15810 s_change_sec (int sec)
15811 {
15812   segT seg;
15813
15814   /* The ELF backend needs to know that we are changing sections, so
15815      that .previous works correctly.  We could do something like check
15816      for an obj_section_change_hook macro, but that might be confusing
15817      as it would not be appropriate to use it in the section changing
15818      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15819      This should be cleaner, somehow.  */
15820   obj_elf_section_change_hook ();
15821
15822   mips_emit_delays ();
15823
15824   switch (sec)
15825     {
15826     case 't':
15827       s_text (0);
15828       break;
15829     case 'd':
15830       s_data (0);
15831       break;
15832     case 'b':
15833       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15834       demand_empty_rest_of_line ();
15835       break;
15836
15837     case 'r':
15838       seg = subseg_new (RDATA_SECTION_NAME,
15839                         (subsegT) get_absolute_expression ());
15840       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15841                                               | SEC_READONLY | SEC_RELOC
15842                                               | SEC_DATA));
15843       if (strncmp (TARGET_OS, "elf", 3) != 0)
15844         record_alignment (seg, 4);
15845       demand_empty_rest_of_line ();
15846       break;
15847
15848     case 's':
15849       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15850       bfd_set_section_flags (stdoutput, seg,
15851                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15852       if (strncmp (TARGET_OS, "elf", 3) != 0)
15853         record_alignment (seg, 4);
15854       demand_empty_rest_of_line ();
15855       break;
15856
15857     case 'B':
15858       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15859       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15860       if (strncmp (TARGET_OS, "elf", 3) != 0)
15861         record_alignment (seg, 4);
15862       demand_empty_rest_of_line ();
15863       break;
15864     }
15865
15866   auto_align = 1;
15867 }
15868
15869 void
15870 s_change_section (int ignore ATTRIBUTE_UNUSED)
15871 {
15872   char *section_name;
15873   char c;
15874   char next_c = 0;
15875   int section_type;
15876   int section_flag;
15877   int section_entry_size;
15878   int section_alignment;
15879
15880   section_name = input_line_pointer;
15881   c = get_symbol_end ();
15882   if (c)
15883     next_c = *(input_line_pointer + 1);
15884
15885   /* Do we have .section Name<,"flags">?  */
15886   if (c != ',' || (c == ',' && next_c == '"'))
15887     {
15888       /* just after name is now '\0'.  */
15889       *input_line_pointer = c;
15890       input_line_pointer = section_name;
15891       obj_elf_section (ignore);
15892       return;
15893     }
15894   input_line_pointer++;
15895
15896   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15897   if (c == ',')
15898     section_type = get_absolute_expression ();
15899   else
15900     section_type = 0;
15901   if (*input_line_pointer++ == ',')
15902     section_flag = get_absolute_expression ();
15903   else
15904     section_flag = 0;
15905   if (*input_line_pointer++ == ',')
15906     section_entry_size = get_absolute_expression ();
15907   else
15908     section_entry_size = 0;
15909   if (*input_line_pointer++ == ',')
15910     section_alignment = get_absolute_expression ();
15911   else
15912     section_alignment = 0;
15913   /* FIXME: really ignore?  */
15914   (void) section_alignment;
15915
15916   section_name = xstrdup (section_name);
15917
15918   /* When using the generic form of .section (as implemented by obj-elf.c),
15919      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15920      traditionally had to fall back on the more common @progbits instead.
15921
15922      There's nothing really harmful in this, since bfd will correct
15923      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15924      means that, for backwards compatibility, the special_section entries
15925      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15926
15927      Even so, we shouldn't force users of the MIPS .section syntax to
15928      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15929      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15930      generic type-checking code.  */
15931   if (section_type == SHT_MIPS_DWARF)
15932     section_type = SHT_PROGBITS;
15933
15934   obj_elf_change_section (section_name, section_type, section_flag,
15935                           section_entry_size, 0, 0, 0);
15936
15937   if (now_seg->name != section_name)
15938     free (section_name);
15939 }
15940
15941 void
15942 mips_enable_auto_align (void)
15943 {
15944   auto_align = 1;
15945 }
15946
15947 static void
15948 s_cons (int log_size)
15949 {
15950   segment_info_type *si = seg_info (now_seg);
15951   struct insn_label_list *l = si->label_list;
15952
15953   mips_emit_delays ();
15954   if (log_size > 0 && auto_align)
15955     mips_align (log_size, 0, l);
15956   cons (1 << log_size);
15957   mips_clear_insn_labels ();
15958 }
15959
15960 static void
15961 s_float_cons (int type)
15962 {
15963   segment_info_type *si = seg_info (now_seg);
15964   struct insn_label_list *l = si->label_list;
15965
15966   mips_emit_delays ();
15967
15968   if (auto_align)
15969     {
15970       if (type == 'd')
15971         mips_align (3, 0, l);
15972       else
15973         mips_align (2, 0, l);
15974     }
15975
15976   float_cons (type);
15977   mips_clear_insn_labels ();
15978 }
15979
15980 /* Handle .globl.  We need to override it because on Irix 5 you are
15981    permitted to say
15982        .globl foo .text
15983    where foo is an undefined symbol, to mean that foo should be
15984    considered to be the address of a function.  */
15985
15986 static void
15987 s_mips_globl (int x ATTRIBUTE_UNUSED)
15988 {
15989   char *name;
15990   int c;
15991   symbolS *symbolP;
15992   flagword flag;
15993
15994   do
15995     {
15996       name = input_line_pointer;
15997       c = get_symbol_end ();
15998       symbolP = symbol_find_or_make (name);
15999       S_SET_EXTERNAL (symbolP);
16000
16001       *input_line_pointer = c;
16002       SKIP_WHITESPACE ();
16003
16004       /* On Irix 5, every global symbol that is not explicitly labelled as
16005          being a function is apparently labelled as being an object.  */
16006       flag = BSF_OBJECT;
16007
16008       if (!is_end_of_line[(unsigned char) *input_line_pointer]
16009           && (*input_line_pointer != ','))
16010         {
16011           char *secname;
16012           asection *sec;
16013
16014           secname = input_line_pointer;
16015           c = get_symbol_end ();
16016           sec = bfd_get_section_by_name (stdoutput, secname);
16017           if (sec == NULL)
16018             as_bad (_("%s: no such section"), secname);
16019           *input_line_pointer = c;
16020
16021           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
16022             flag = BSF_FUNCTION;
16023         }
16024
16025       symbol_get_bfdsym (symbolP)->flags |= flag;
16026
16027       c = *input_line_pointer;
16028       if (c == ',')
16029         {
16030           input_line_pointer++;
16031           SKIP_WHITESPACE ();
16032           if (is_end_of_line[(unsigned char) *input_line_pointer])
16033             c = '\n';
16034         }
16035     }
16036   while (c == ',');
16037
16038   demand_empty_rest_of_line ();
16039 }
16040
16041 static void
16042 s_option (int x ATTRIBUTE_UNUSED)
16043 {
16044   char *opt;
16045   char c;
16046
16047   opt = input_line_pointer;
16048   c = get_symbol_end ();
16049
16050   if (*opt == 'O')
16051     {
16052       /* FIXME: What does this mean?  */
16053     }
16054   else if (strncmp (opt, "pic", 3) == 0)
16055     {
16056       int i;
16057
16058       i = atoi (opt + 3);
16059       if (i == 0)
16060         mips_pic = NO_PIC;
16061       else if (i == 2)
16062         {
16063           mips_pic = SVR4_PIC;
16064           mips_abicalls = TRUE;
16065         }
16066       else
16067         as_bad (_(".option pic%d not supported"), i);
16068
16069       if (mips_pic == SVR4_PIC)
16070         {
16071           if (g_switch_seen && g_switch_value != 0)
16072             as_warn (_("-G may not be used with SVR4 PIC code"));
16073           g_switch_value = 0;
16074           bfd_set_gp_size (stdoutput, 0);
16075         }
16076     }
16077   else
16078     as_warn (_("Unrecognized option \"%s\""), opt);
16079
16080   *input_line_pointer = c;
16081   demand_empty_rest_of_line ();
16082 }
16083
16084 /* This structure is used to hold a stack of .set values.  */
16085
16086 struct mips_option_stack
16087 {
16088   struct mips_option_stack *next;
16089   struct mips_set_options options;
16090 };
16091
16092 static struct mips_option_stack *mips_opts_stack;
16093
16094 /* Handle the .set pseudo-op.  */
16095
16096 static void
16097 s_mipsset (int x ATTRIBUTE_UNUSED)
16098 {
16099   char *name = input_line_pointer, ch;
16100   const struct mips_ase *ase;
16101
16102   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16103     ++input_line_pointer;
16104   ch = *input_line_pointer;
16105   *input_line_pointer = '\0';
16106
16107   if (strcmp (name, "reorder") == 0)
16108     {
16109       if (mips_opts.noreorder)
16110         end_noreorder ();
16111     }
16112   else if (strcmp (name, "noreorder") == 0)
16113     {
16114       if (!mips_opts.noreorder)
16115         start_noreorder ();
16116     }
16117   else if (strncmp (name, "at=", 3) == 0)
16118     {
16119       char *s = name + 3;
16120
16121       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
16122         as_bad (_("Unrecognized register name `%s'"), s);
16123     }
16124   else if (strcmp (name, "at") == 0)
16125     {
16126       mips_opts.at = ATREG;
16127     }
16128   else if (strcmp (name, "noat") == 0)
16129     {
16130       mips_opts.at = ZERO;
16131     }
16132   else if (strcmp (name, "macro") == 0)
16133     {
16134       mips_opts.warn_about_macros = 0;
16135     }
16136   else if (strcmp (name, "nomacro") == 0)
16137     {
16138       if (mips_opts.noreorder == 0)
16139         as_bad (_("`noreorder' must be set before `nomacro'"));
16140       mips_opts.warn_about_macros = 1;
16141     }
16142   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
16143     {
16144       mips_opts.nomove = 0;
16145     }
16146   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
16147     {
16148       mips_opts.nomove = 1;
16149     }
16150   else if (strcmp (name, "bopt") == 0)
16151     {
16152       mips_opts.nobopt = 0;
16153     }
16154   else if (strcmp (name, "nobopt") == 0)
16155     {
16156       mips_opts.nobopt = 1;
16157     }
16158   else if (strcmp (name, "gp=default") == 0)
16159     mips_opts.gp32 = file_mips_gp32;
16160   else if (strcmp (name, "gp=32") == 0)
16161     mips_opts.gp32 = 1;
16162   else if (strcmp (name, "gp=64") == 0)
16163     {
16164       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
16165         as_warn (_("%s isa does not support 64-bit registers"),
16166                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16167       mips_opts.gp32 = 0;
16168     }
16169   else if (strcmp (name, "fp=default") == 0)
16170     mips_opts.fp32 = file_mips_fp32;
16171   else if (strcmp (name, "fp=32") == 0)
16172     mips_opts.fp32 = 1;
16173   else if (strcmp (name, "fp=64") == 0)
16174     {
16175       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
16176         as_warn (_("%s isa does not support 64-bit floating point registers"),
16177                  mips_cpu_info_from_isa (mips_opts.isa)->name);
16178       mips_opts.fp32 = 0;
16179     }
16180   else if (strcmp (name, "softfloat") == 0)
16181     mips_opts.soft_float = 1;
16182   else if (strcmp (name, "hardfloat") == 0)
16183     mips_opts.soft_float = 0;
16184   else if (strcmp (name, "singlefloat") == 0)
16185     mips_opts.single_float = 1;
16186   else if (strcmp (name, "doublefloat") == 0)
16187     mips_opts.single_float = 0;
16188   else if (strcmp (name, "mips16") == 0
16189            || strcmp (name, "MIPS-16") == 0)
16190     {
16191       if (mips_opts.micromips == 1)
16192         as_fatal (_("`mips16' cannot be used with `micromips'"));
16193       mips_opts.mips16 = 1;
16194     }
16195   else if (strcmp (name, "nomips16") == 0
16196            || strcmp (name, "noMIPS-16") == 0)
16197     mips_opts.mips16 = 0;
16198   else if (strcmp (name, "micromips") == 0)
16199     {
16200       if (mips_opts.mips16 == 1)
16201         as_fatal (_("`micromips' cannot be used with `mips16'"));
16202       mips_opts.micromips = 1;
16203     }
16204   else if (strcmp (name, "nomicromips") == 0)
16205     mips_opts.micromips = 0;
16206   else if (name[0] == 'n'
16207            && name[1] == 'o'
16208            && (ase = mips_lookup_ase (name + 2)))
16209     mips_set_ase (ase, FALSE);
16210   else if ((ase = mips_lookup_ase (name)))
16211     mips_set_ase (ase, TRUE);
16212   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
16213     {
16214       int reset = 0;
16215
16216       /* Permit the user to change the ISA and architecture on the fly.
16217          Needless to say, misuse can cause serious problems.  */
16218       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16219         {
16220           reset = 1;
16221           mips_opts.isa = file_mips_isa;
16222           mips_opts.arch = file_mips_arch;
16223         }
16224       else if (strncmp (name, "arch=", 5) == 0)
16225         {
16226           const struct mips_cpu_info *p;
16227
16228           p = mips_parse_cpu("internal use", name + 5);
16229           if (!p)
16230             as_bad (_("unknown architecture %s"), name + 5);
16231           else
16232             {
16233               mips_opts.arch = p->cpu;
16234               mips_opts.isa = p->isa;
16235             }
16236         }
16237       else if (strncmp (name, "mips", 4) == 0)
16238         {
16239           const struct mips_cpu_info *p;
16240
16241           p = mips_parse_cpu("internal use", name);
16242           if (!p)
16243             as_bad (_("unknown ISA level %s"), name + 4);
16244           else
16245             {
16246               mips_opts.arch = p->cpu;
16247               mips_opts.isa = p->isa;
16248             }
16249         }
16250       else
16251         as_bad (_("unknown ISA or architecture %s"), name);
16252
16253       switch (mips_opts.isa)
16254         {
16255         case  0:
16256           break;
16257         case ISA_MIPS1:
16258         case ISA_MIPS2:
16259         case ISA_MIPS32:
16260         case ISA_MIPS32R2:
16261           mips_opts.gp32 = 1;
16262           mips_opts.fp32 = 1;
16263           break;
16264         case ISA_MIPS3:
16265         case ISA_MIPS4:
16266         case ISA_MIPS5:
16267         case ISA_MIPS64:
16268         case ISA_MIPS64R2:
16269           mips_opts.gp32 = 0;
16270           if (mips_opts.arch == CPU_R5900)
16271             {
16272                 mips_opts.fp32 = 1;
16273             }
16274           else
16275             {
16276           mips_opts.fp32 = 0;
16277             }
16278           break;
16279         default:
16280           as_bad (_("unknown ISA level %s"), name + 4);
16281           break;
16282         }
16283       if (reset)
16284         {
16285           mips_opts.gp32 = file_mips_gp32;
16286           mips_opts.fp32 = file_mips_fp32;
16287         }
16288     }
16289   else if (strcmp (name, "autoextend") == 0)
16290     mips_opts.noautoextend = 0;
16291   else if (strcmp (name, "noautoextend") == 0)
16292     mips_opts.noautoextend = 1;
16293   else if (strcmp (name, "insn32") == 0)
16294     mips_opts.insn32 = TRUE;
16295   else if (strcmp (name, "noinsn32") == 0)
16296     mips_opts.insn32 = FALSE;
16297   else if (strcmp (name, "push") == 0)
16298     {
16299       struct mips_option_stack *s;
16300
16301       s = (struct mips_option_stack *) xmalloc (sizeof *s);
16302       s->next = mips_opts_stack;
16303       s->options = mips_opts;
16304       mips_opts_stack = s;
16305     }
16306   else if (strcmp (name, "pop") == 0)
16307     {
16308       struct mips_option_stack *s;
16309
16310       s = mips_opts_stack;
16311       if (s == NULL)
16312         as_bad (_(".set pop with no .set push"));
16313       else
16314         {
16315           /* If we're changing the reorder mode we need to handle
16316              delay slots correctly.  */
16317           if (s->options.noreorder && ! mips_opts.noreorder)
16318             start_noreorder ();
16319           else if (! s->options.noreorder && mips_opts.noreorder)
16320             end_noreorder ();
16321
16322           mips_opts = s->options;
16323           mips_opts_stack = s->next;
16324           free (s);
16325         }
16326     }
16327   else if (strcmp (name, "sym32") == 0)
16328     mips_opts.sym32 = TRUE;
16329   else if (strcmp (name, "nosym32") == 0)
16330     mips_opts.sym32 = FALSE;
16331   else if (strchr (name, ','))
16332     {
16333       /* Generic ".set" directive; use the generic handler.  */
16334       *input_line_pointer = ch;
16335       input_line_pointer = name;
16336       s_set (0);
16337       return;
16338     }
16339   else
16340     {
16341       as_warn (_("Tried to set unrecognized symbol: %s\n"), name);
16342     }
16343   mips_check_isa_supports_ases ();
16344   *input_line_pointer = ch;
16345   demand_empty_rest_of_line ();
16346 }
16347
16348 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16349    .option pic2.  It means to generate SVR4 PIC calls.  */
16350
16351 static void
16352 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16353 {
16354   mips_pic = SVR4_PIC;
16355   mips_abicalls = TRUE;
16356
16357   if (g_switch_seen && g_switch_value != 0)
16358     as_warn (_("-G may not be used with SVR4 PIC code"));
16359   g_switch_value = 0;
16360
16361   bfd_set_gp_size (stdoutput, 0);
16362   demand_empty_rest_of_line ();
16363 }
16364
16365 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16366    PIC code.  It sets the $gp register for the function based on the
16367    function address, which is in the register named in the argument.
16368    This uses a relocation against _gp_disp, which is handled specially
16369    by the linker.  The result is:
16370         lui     $gp,%hi(_gp_disp)
16371         addiu   $gp,$gp,%lo(_gp_disp)
16372         addu    $gp,$gp,.cpload argument
16373    The .cpload argument is normally $25 == $t9.
16374
16375    The -mno-shared option changes this to:
16376         lui     $gp,%hi(__gnu_local_gp)
16377         addiu   $gp,$gp,%lo(__gnu_local_gp)
16378    and the argument is ignored.  This saves an instruction, but the
16379    resulting code is not position independent; it uses an absolute
16380    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16381    can go into an ordinary executable, but not into a shared library.  */
16382
16383 static void
16384 s_cpload (int ignore ATTRIBUTE_UNUSED)
16385 {
16386   expressionS ex;
16387   int reg;
16388   int in_shared;
16389
16390   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16391      .cpload is ignored.  */
16392   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16393     {
16394       s_ignore (0);
16395       return;
16396     }
16397
16398   if (mips_opts.mips16)
16399     {
16400       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16401       ignore_rest_of_line ();
16402       return;
16403     }
16404
16405   /* .cpload should be in a .set noreorder section.  */
16406   if (mips_opts.noreorder == 0)
16407     as_warn (_(".cpload not in noreorder section"));
16408
16409   reg = tc_get_register (0);
16410
16411   /* If we need to produce a 64-bit address, we are better off using
16412      the default instruction sequence.  */
16413   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16414
16415   ex.X_op = O_symbol;
16416   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16417                                          "__gnu_local_gp");
16418   ex.X_op_symbol = NULL;
16419   ex.X_add_number = 0;
16420
16421   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16422   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16423
16424   mips_mark_labels ();
16425   mips_assembling_insn = TRUE;
16426
16427   macro_start ();
16428   macro_build_lui (&ex, mips_gp_register);
16429   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16430                mips_gp_register, BFD_RELOC_LO16);
16431   if (in_shared)
16432     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16433                  mips_gp_register, reg);
16434   macro_end ();
16435
16436   mips_assembling_insn = FALSE;
16437   demand_empty_rest_of_line ();
16438 }
16439
16440 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16441      .cpsetup $reg1, offset|$reg2, label
16442
16443    If offset is given, this results in:
16444      sd         $gp, offset($sp)
16445      lui        $gp, %hi(%neg(%gp_rel(label)))
16446      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16447      daddu      $gp, $gp, $reg1
16448
16449    If $reg2 is given, this results in:
16450      daddu      $reg2, $gp, $0
16451      lui        $gp, %hi(%neg(%gp_rel(label)))
16452      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16453      daddu      $gp, $gp, $reg1
16454    $reg1 is normally $25 == $t9.
16455
16456    The -mno-shared option replaces the last three instructions with
16457         lui     $gp,%hi(_gp)
16458         addiu   $gp,$gp,%lo(_gp)  */
16459
16460 static void
16461 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16462 {
16463   expressionS ex_off;
16464   expressionS ex_sym;
16465   int reg1;
16466
16467   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16468      We also need NewABI support.  */
16469   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16470     {
16471       s_ignore (0);
16472       return;
16473     }
16474
16475   if (mips_opts.mips16)
16476     {
16477       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16478       ignore_rest_of_line ();
16479       return;
16480     }
16481
16482   reg1 = tc_get_register (0);
16483   SKIP_WHITESPACE ();
16484   if (*input_line_pointer != ',')
16485     {
16486       as_bad (_("missing argument separator ',' for .cpsetup"));
16487       return;
16488     }
16489   else
16490     ++input_line_pointer;
16491   SKIP_WHITESPACE ();
16492   if (*input_line_pointer == '$')
16493     {
16494       mips_cpreturn_register = tc_get_register (0);
16495       mips_cpreturn_offset = -1;
16496     }
16497   else
16498     {
16499       mips_cpreturn_offset = get_absolute_expression ();
16500       mips_cpreturn_register = -1;
16501     }
16502   SKIP_WHITESPACE ();
16503   if (*input_line_pointer != ',')
16504     {
16505       as_bad (_("missing argument separator ',' for .cpsetup"));
16506       return;
16507     }
16508   else
16509     ++input_line_pointer;
16510   SKIP_WHITESPACE ();
16511   expression (&ex_sym);
16512
16513   mips_mark_labels ();
16514   mips_assembling_insn = TRUE;
16515
16516   macro_start ();
16517   if (mips_cpreturn_register == -1)
16518     {
16519       ex_off.X_op = O_constant;
16520       ex_off.X_add_symbol = NULL;
16521       ex_off.X_op_symbol = NULL;
16522       ex_off.X_add_number = mips_cpreturn_offset;
16523
16524       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16525                    BFD_RELOC_LO16, SP);
16526     }
16527   else
16528     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
16529                  mips_gp_register, 0);
16530
16531   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16532     {
16533       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16534                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16535                    BFD_RELOC_HI16_S);
16536
16537       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16538                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16539                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16540
16541       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16542                    mips_gp_register, reg1);
16543     }
16544   else
16545     {
16546       expressionS ex;
16547
16548       ex.X_op = O_symbol;
16549       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16550       ex.X_op_symbol = NULL;
16551       ex.X_add_number = 0;
16552
16553       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16554       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16555
16556       macro_build_lui (&ex, mips_gp_register);
16557       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16558                    mips_gp_register, BFD_RELOC_LO16);
16559     }
16560
16561   macro_end ();
16562
16563   mips_assembling_insn = FALSE;
16564   demand_empty_rest_of_line ();
16565 }
16566
16567 static void
16568 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16569 {
16570   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16571      .cplocal is ignored.  */
16572   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16573     {
16574       s_ignore (0);
16575       return;
16576     }
16577
16578   if (mips_opts.mips16)
16579     {
16580       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16581       ignore_rest_of_line ();
16582       return;
16583     }
16584
16585   mips_gp_register = tc_get_register (0);
16586   demand_empty_rest_of_line ();
16587 }
16588
16589 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16590    offset from $sp.  The offset is remembered, and after making a PIC
16591    call $gp is restored from that location.  */
16592
16593 static void
16594 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16595 {
16596   expressionS ex;
16597
16598   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16599      .cprestore is ignored.  */
16600   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16601     {
16602       s_ignore (0);
16603       return;
16604     }
16605
16606   if (mips_opts.mips16)
16607     {
16608       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16609       ignore_rest_of_line ();
16610       return;
16611     }
16612
16613   mips_cprestore_offset = get_absolute_expression ();
16614   mips_cprestore_valid = 1;
16615
16616   ex.X_op = O_constant;
16617   ex.X_add_symbol = NULL;
16618   ex.X_op_symbol = NULL;
16619   ex.X_add_number = mips_cprestore_offset;
16620
16621   mips_mark_labels ();
16622   mips_assembling_insn = TRUE;
16623
16624   macro_start ();
16625   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16626                                 SP, HAVE_64BIT_ADDRESSES);
16627   macro_end ();
16628
16629   mips_assembling_insn = FALSE;
16630   demand_empty_rest_of_line ();
16631 }
16632
16633 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16634    was given in the preceding .cpsetup, it results in:
16635      ld         $gp, offset($sp)
16636
16637    If a register $reg2 was given there, it results in:
16638      daddu      $gp, $reg2, $0  */
16639
16640 static void
16641 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16642 {
16643   expressionS ex;
16644
16645   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16646      We also need NewABI support.  */
16647   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16648     {
16649       s_ignore (0);
16650       return;
16651     }
16652
16653   if (mips_opts.mips16)
16654     {
16655       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16656       ignore_rest_of_line ();
16657       return;
16658     }
16659
16660   mips_mark_labels ();
16661   mips_assembling_insn = TRUE;
16662
16663   macro_start ();
16664   if (mips_cpreturn_register == -1)
16665     {
16666       ex.X_op = O_constant;
16667       ex.X_add_symbol = NULL;
16668       ex.X_op_symbol = NULL;
16669       ex.X_add_number = mips_cpreturn_offset;
16670
16671       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16672     }
16673   else
16674     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
16675                  mips_cpreturn_register, 0);
16676   macro_end ();
16677
16678   mips_assembling_insn = FALSE;
16679   demand_empty_rest_of_line ();
16680 }
16681
16682 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16683    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16684    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16685    debug information or MIPS16 TLS.  */
16686
16687 static void
16688 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16689                      bfd_reloc_code_real_type rtype)
16690 {
16691   expressionS ex;
16692   char *p;
16693
16694   expression (&ex);
16695
16696   if (ex.X_op != O_symbol)
16697     {
16698       as_bad (_("Unsupported use of %s"), dirstr);
16699       ignore_rest_of_line ();
16700     }
16701
16702   p = frag_more (bytes);
16703   md_number_to_chars (p, 0, bytes);
16704   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16705   demand_empty_rest_of_line ();
16706   mips_clear_insn_labels ();
16707 }
16708
16709 /* Handle .dtprelword.  */
16710
16711 static void
16712 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16713 {
16714   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16715 }
16716
16717 /* Handle .dtpreldword.  */
16718
16719 static void
16720 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16721 {
16722   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16723 }
16724
16725 /* Handle .tprelword.  */
16726
16727 static void
16728 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16729 {
16730   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16731 }
16732
16733 /* Handle .tpreldword.  */
16734
16735 static void
16736 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16737 {
16738   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16739 }
16740
16741 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16742    code.  It sets the offset to use in gp_rel relocations.  */
16743
16744 static void
16745 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16746 {
16747   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16748      We also need NewABI support.  */
16749   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16750     {
16751       s_ignore (0);
16752       return;
16753     }
16754
16755   mips_gprel_offset = get_absolute_expression ();
16756
16757   demand_empty_rest_of_line ();
16758 }
16759
16760 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16761    code.  It generates a 32 bit GP relative reloc.  */
16762
16763 static void
16764 s_gpword (int ignore ATTRIBUTE_UNUSED)
16765 {
16766   segment_info_type *si;
16767   struct insn_label_list *l;
16768   expressionS ex;
16769   char *p;
16770
16771   /* When not generating PIC code, this is treated as .word.  */
16772   if (mips_pic != SVR4_PIC)
16773     {
16774       s_cons (2);
16775       return;
16776     }
16777
16778   si = seg_info (now_seg);
16779   l = si->label_list;
16780   mips_emit_delays ();
16781   if (auto_align)
16782     mips_align (2, 0, l);
16783
16784   expression (&ex);
16785   mips_clear_insn_labels ();
16786
16787   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16788     {
16789       as_bad (_("Unsupported use of .gpword"));
16790       ignore_rest_of_line ();
16791     }
16792
16793   p = frag_more (4);
16794   md_number_to_chars (p, 0, 4);
16795   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16796                BFD_RELOC_GPREL32);
16797
16798   demand_empty_rest_of_line ();
16799 }
16800
16801 static void
16802 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16803 {
16804   segment_info_type *si;
16805   struct insn_label_list *l;
16806   expressionS ex;
16807   char *p;
16808
16809   /* When not generating PIC code, this is treated as .dword.  */
16810   if (mips_pic != SVR4_PIC)
16811     {
16812       s_cons (3);
16813       return;
16814     }
16815
16816   si = seg_info (now_seg);
16817   l = si->label_list;
16818   mips_emit_delays ();
16819   if (auto_align)
16820     mips_align (3, 0, l);
16821
16822   expression (&ex);
16823   mips_clear_insn_labels ();
16824
16825   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16826     {
16827       as_bad (_("Unsupported use of .gpdword"));
16828       ignore_rest_of_line ();
16829     }
16830
16831   p = frag_more (8);
16832   md_number_to_chars (p, 0, 8);
16833   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16834                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16835
16836   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16837   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16838            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16839
16840   demand_empty_rest_of_line ();
16841 }
16842
16843 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
16844    tables.  It generates a R_MIPS_EH reloc.  */
16845
16846 static void
16847 s_ehword (int ignore ATTRIBUTE_UNUSED)
16848 {
16849   expressionS ex;
16850   char *p;
16851
16852   mips_emit_delays ();
16853
16854   expression (&ex);
16855   mips_clear_insn_labels ();
16856
16857   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16858     {
16859       as_bad (_("Unsupported use of .ehword"));
16860       ignore_rest_of_line ();
16861     }
16862
16863   p = frag_more (4);
16864   md_number_to_chars (p, 0, 4);
16865   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16866                BFD_RELOC_MIPS_EH);
16867
16868   demand_empty_rest_of_line ();
16869 }
16870
16871 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16872    tables in SVR4 PIC code.  */
16873
16874 static void
16875 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16876 {
16877   int reg;
16878
16879   /* This is ignored when not generating SVR4 PIC code.  */
16880   if (mips_pic != SVR4_PIC)
16881     {
16882       s_ignore (0);
16883       return;
16884     }
16885
16886   mips_mark_labels ();
16887   mips_assembling_insn = TRUE;
16888
16889   /* Add $gp to the register named as an argument.  */
16890   macro_start ();
16891   reg = tc_get_register (0);
16892   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16893   macro_end ();
16894
16895   mips_assembling_insn = FALSE;
16896   demand_empty_rest_of_line ();
16897 }
16898
16899 /* Handle the .insn pseudo-op.  This marks instruction labels in
16900    mips16/micromips mode.  This permits the linker to handle them specially,
16901    such as generating jalx instructions when needed.  We also make
16902    them odd for the duration of the assembly, in order to generate the
16903    right sort of code.  We will make them even in the adjust_symtab
16904    routine, while leaving them marked.  This is convenient for the
16905    debugger and the disassembler.  The linker knows to make them odd
16906    again.  */
16907
16908 static void
16909 s_insn (int ignore ATTRIBUTE_UNUSED)
16910 {
16911   mips_mark_labels ();
16912
16913   demand_empty_rest_of_line ();
16914 }
16915
16916 /* Handle the .nan pseudo-op.  */
16917
16918 static void
16919 s_nan (int ignore ATTRIBUTE_UNUSED)
16920 {
16921   static const char str_legacy[] = "legacy";
16922   static const char str_2008[] = "2008";
16923   size_t i;
16924
16925   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16926
16927   if (i == sizeof (str_2008) - 1
16928       && memcmp (input_line_pointer, str_2008, i) == 0)
16929     mips_flag_nan2008 = TRUE;
16930   else if (i == sizeof (str_legacy) - 1
16931            && memcmp (input_line_pointer, str_legacy, i) == 0)
16932     mips_flag_nan2008 = FALSE;
16933   else
16934     as_bad (_("Bad .nan directive"));
16935
16936   input_line_pointer += i;
16937   demand_empty_rest_of_line ();
16938 }
16939
16940 /* Handle a .stab[snd] directive.  Ideally these directives would be
16941    implemented in a transparent way, so that removing them would not
16942    have any effect on the generated instructions.  However, s_stab
16943    internally changes the section, so in practice we need to decide
16944    now whether the preceding label marks compressed code.  We do not
16945    support changing the compression mode of a label after a .stab*
16946    directive, such as in:
16947
16948    foo:
16949         .stabs ...
16950         .set mips16
16951
16952    so the current mode wins.  */
16953
16954 static void
16955 s_mips_stab (int type)
16956 {
16957   mips_mark_labels ();
16958   s_stab (type);
16959 }
16960
16961 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16962
16963 static void
16964 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16965 {
16966   char *name;
16967   int c;
16968   symbolS *symbolP;
16969   expressionS exp;
16970
16971   name = input_line_pointer;
16972   c = get_symbol_end ();
16973   symbolP = symbol_find_or_make (name);
16974   S_SET_WEAK (symbolP);
16975   *input_line_pointer = c;
16976
16977   SKIP_WHITESPACE ();
16978
16979   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16980     {
16981       if (S_IS_DEFINED (symbolP))
16982         {
16983           as_bad (_("ignoring attempt to redefine symbol %s"),
16984                   S_GET_NAME (symbolP));
16985           ignore_rest_of_line ();
16986           return;
16987         }
16988
16989       if (*input_line_pointer == ',')
16990         {
16991           ++input_line_pointer;
16992           SKIP_WHITESPACE ();
16993         }
16994
16995       expression (&exp);
16996       if (exp.X_op != O_symbol)
16997         {
16998           as_bad (_("bad .weakext directive"));
16999           ignore_rest_of_line ();
17000           return;
17001         }
17002       symbol_set_value_expression (symbolP, &exp);
17003     }
17004
17005   demand_empty_rest_of_line ();
17006 }
17007
17008 /* Parse a register string into a number.  Called from the ECOFF code
17009    to parse .frame.  The argument is non-zero if this is the frame
17010    register, so that we can record it in mips_frame_reg.  */
17011
17012 int
17013 tc_get_register (int frame)
17014 {
17015   unsigned int reg;
17016
17017   SKIP_WHITESPACE ();
17018   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
17019     reg = 0;
17020   if (frame)
17021     {
17022       mips_frame_reg = reg != 0 ? reg : SP;
17023       mips_frame_reg_valid = 1;
17024       mips_cprestore_valid = 0;
17025     }
17026   return reg;
17027 }
17028
17029 valueT
17030 md_section_align (asection *seg, valueT addr)
17031 {
17032   int align = bfd_get_section_alignment (stdoutput, seg);
17033
17034   /* We don't need to align ELF sections to the full alignment.
17035      However, Irix 5 may prefer that we align them at least to a 16
17036      byte boundary.  We don't bother to align the sections if we
17037      are targeted for an embedded system.  */
17038   if (strncmp (TARGET_OS, "elf", 3) == 0)
17039     return addr;
17040   if (align > 4)
17041     align = 4;
17042
17043   return ((addr + (1 << align) - 1) & (-1 << align));
17044 }
17045
17046 /* Utility routine, called from above as well.  If called while the
17047    input file is still being read, it's only an approximation.  (For
17048    example, a symbol may later become defined which appeared to be
17049    undefined earlier.)  */
17050
17051 static int
17052 nopic_need_relax (symbolS *sym, int before_relaxing)
17053 {
17054   if (sym == 0)
17055     return 0;
17056
17057   if (g_switch_value > 0)
17058     {
17059       const char *symname;
17060       int change;
17061
17062       /* Find out whether this symbol can be referenced off the $gp
17063          register.  It can be if it is smaller than the -G size or if
17064          it is in the .sdata or .sbss section.  Certain symbols can
17065          not be referenced off the $gp, although it appears as though
17066          they can.  */
17067       symname = S_GET_NAME (sym);
17068       if (symname != (const char *) NULL
17069           && (strcmp (symname, "eprol") == 0
17070               || strcmp (symname, "etext") == 0
17071               || strcmp (symname, "_gp") == 0
17072               || strcmp (symname, "edata") == 0
17073               || strcmp (symname, "_fbss") == 0
17074               || strcmp (symname, "_fdata") == 0
17075               || strcmp (symname, "_ftext") == 0
17076               || strcmp (symname, "end") == 0
17077               || strcmp (symname, "_gp_disp") == 0))
17078         change = 1;
17079       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
17080                && (0
17081 #ifndef NO_ECOFF_DEBUGGING
17082                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
17083                        && (symbol_get_obj (sym)->ecoff_extern_size
17084                            <= g_switch_value))
17085 #endif
17086                    /* We must defer this decision until after the whole
17087                       file has been read, since there might be a .extern
17088                       after the first use of this symbol.  */
17089                    || (before_relaxing
17090 #ifndef NO_ECOFF_DEBUGGING
17091                        && symbol_get_obj (sym)->ecoff_extern_size == 0
17092 #endif
17093                        && S_GET_VALUE (sym) == 0)
17094                    || (S_GET_VALUE (sym) != 0
17095                        && S_GET_VALUE (sym) <= g_switch_value)))
17096         change = 0;
17097       else
17098         {
17099           const char *segname;
17100
17101           segname = segment_name (S_GET_SEGMENT (sym));
17102           gas_assert (strcmp (segname, ".lit8") != 0
17103                   && strcmp (segname, ".lit4") != 0);
17104           change = (strcmp (segname, ".sdata") != 0
17105                     && strcmp (segname, ".sbss") != 0
17106                     && strncmp (segname, ".sdata.", 7) != 0
17107                     && strncmp (segname, ".sbss.", 6) != 0
17108                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
17109                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
17110         }
17111       return change;
17112     }
17113   else
17114     /* We are not optimizing for the $gp register.  */
17115     return 1;
17116 }
17117
17118
17119 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
17120
17121 static bfd_boolean
17122 pic_need_relax (symbolS *sym, asection *segtype)
17123 {
17124   asection *symsec;
17125
17126   /* Handle the case of a symbol equated to another symbol.  */
17127   while (symbol_equated_reloc_p (sym))
17128     {
17129       symbolS *n;
17130
17131       /* It's possible to get a loop here in a badly written program.  */
17132       n = symbol_get_value_expression (sym)->X_add_symbol;
17133       if (n == sym)
17134         break;
17135       sym = n;
17136     }
17137
17138   if (symbol_section_p (sym))
17139     return TRUE;
17140
17141   symsec = S_GET_SEGMENT (sym);
17142
17143   /* This must duplicate the test in adjust_reloc_syms.  */
17144   return (!bfd_is_und_section (symsec)
17145           && !bfd_is_abs_section (symsec)
17146           && !bfd_is_com_section (symsec)
17147           && !s_is_linkonce (sym, segtype)
17148           /* A global or weak symbol is treated as external.  */
17149           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
17150 }
17151
17152
17153 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
17154    extended opcode.  SEC is the section the frag is in.  */
17155
17156 static int
17157 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
17158 {
17159   int type;
17160   const struct mips16_immed_operand *op;
17161   offsetT val;
17162   int mintiny, maxtiny;
17163   segT symsec;
17164   fragS *sym_frag;
17165
17166   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17167     return 0;
17168   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17169     return 1;
17170
17171   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17172   op = mips16_immed_operands;
17173   while (op->type != type)
17174     {
17175       ++op;
17176       gas_assert (op < mips16_immed_operands + MIPS16_NUM_IMMED);
17177     }
17178
17179   if (op->unsp)
17180     {
17181       if (type == '<' || type == '>' || type == '[' || type == ']')
17182         {
17183           mintiny = 1;
17184           maxtiny = 1 << op->nbits;
17185         }
17186       else
17187         {
17188           mintiny = 0;
17189           maxtiny = (1 << op->nbits) - 1;
17190         }
17191     }
17192   else
17193     {
17194       mintiny = - (1 << (op->nbits - 1));
17195       maxtiny = (1 << (op->nbits - 1)) - 1;
17196     }
17197
17198   sym_frag = symbol_get_frag (fragp->fr_symbol);
17199   val = S_GET_VALUE (fragp->fr_symbol);
17200   symsec = S_GET_SEGMENT (fragp->fr_symbol);
17201
17202   if (op->pcrel)
17203     {
17204       addressT addr;
17205
17206       /* We won't have the section when we are called from
17207          mips_relax_frag.  However, we will always have been called
17208          from md_estimate_size_before_relax first.  If this is a
17209          branch to a different section, we mark it as such.  If SEC is
17210          NULL, and the frag is not marked, then it must be a branch to
17211          the same section.  */
17212       if (sec == NULL)
17213         {
17214           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17215             return 1;
17216         }
17217       else
17218         {
17219           /* Must have been called from md_estimate_size_before_relax.  */
17220           if (symsec != sec)
17221             {
17222               fragp->fr_subtype =
17223                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17224
17225               /* FIXME: We should support this, and let the linker
17226                  catch branches and loads that are out of range.  */
17227               as_bad_where (fragp->fr_file, fragp->fr_line,
17228                             _("unsupported PC relative reference to different section"));
17229
17230               return 1;
17231             }
17232           if (fragp != sym_frag && sym_frag->fr_address == 0)
17233             /* Assume non-extended on the first relaxation pass.
17234                The address we have calculated will be bogus if this is
17235                a forward branch to another frag, as the forward frag
17236                will have fr_address == 0.  */
17237             return 0;
17238         }
17239
17240       /* In this case, we know for sure that the symbol fragment is in
17241          the same section.  If the relax_marker of the symbol fragment
17242          differs from the relax_marker of this fragment, we have not
17243          yet adjusted the symbol fragment fr_address.  We want to add
17244          in STRETCH in order to get a better estimate of the address.
17245          This particularly matters because of the shift bits.  */
17246       if (stretch != 0
17247           && sym_frag->relax_marker != fragp->relax_marker)
17248         {
17249           fragS *f;
17250
17251           /* Adjust stretch for any alignment frag.  Note that if have
17252              been expanding the earlier code, the symbol may be
17253              defined in what appears to be an earlier frag.  FIXME:
17254              This doesn't handle the fr_subtype field, which specifies
17255              a maximum number of bytes to skip when doing an
17256              alignment.  */
17257           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17258             {
17259               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17260                 {
17261                   if (stretch < 0)
17262                     stretch = - ((- stretch)
17263                                  & ~ ((1 << (int) f->fr_offset) - 1));
17264                   else
17265                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17266                   if (stretch == 0)
17267                     break;
17268                 }
17269             }
17270           if (f != NULL)
17271             val += stretch;
17272         }
17273
17274       addr = fragp->fr_address + fragp->fr_fix;
17275
17276       /* The base address rules are complicated.  The base address of
17277          a branch is the following instruction.  The base address of a
17278          PC relative load or add is the instruction itself, but if it
17279          is in a delay slot (in which case it can not be extended) use
17280          the address of the instruction whose delay slot it is in.  */
17281       if (type == 'p' || type == 'q')
17282         {
17283           addr += 2;
17284
17285           /* If we are currently assuming that this frag should be
17286              extended, then, the current address is two bytes
17287              higher.  */
17288           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17289             addr += 2;
17290
17291           /* Ignore the low bit in the target, since it will be set
17292              for a text label.  */
17293           if ((val & 1) != 0)
17294             --val;
17295         }
17296       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17297         addr -= 4;
17298       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17299         addr -= 2;
17300
17301       val -= addr & ~ ((1 << op->shift) - 1);
17302
17303       /* Branch offsets have an implicit 0 in the lowest bit.  */
17304       if (type == 'p' || type == 'q')
17305         val /= 2;
17306
17307       /* If any of the shifted bits are set, we must use an extended
17308          opcode.  If the address depends on the size of this
17309          instruction, this can lead to a loop, so we arrange to always
17310          use an extended opcode.  We only check this when we are in
17311          the main relaxation loop, when SEC is NULL.  */
17312       if ((val & ((1 << op->shift) - 1)) != 0 && sec == NULL)
17313         {
17314           fragp->fr_subtype =
17315             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17316           return 1;
17317         }
17318
17319       /* If we are about to mark a frag as extended because the value
17320          is precisely maxtiny + 1, then there is a chance of an
17321          infinite loop as in the following code:
17322              la $4,foo
17323              .skip      1020
17324              .align     2
17325            foo:
17326          In this case when the la is extended, foo is 0x3fc bytes
17327          away, so the la can be shrunk, but then foo is 0x400 away, so
17328          the la must be extended.  To avoid this loop, we mark the
17329          frag as extended if it was small, and is about to become
17330          extended with a value of maxtiny + 1.  */
17331       if (val == ((maxtiny + 1) << op->shift)
17332           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
17333           && sec == NULL)
17334         {
17335           fragp->fr_subtype =
17336             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17337           return 1;
17338         }
17339     }
17340   else if (symsec != absolute_section && sec != NULL)
17341     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
17342
17343   if ((val & ((1 << op->shift) - 1)) != 0
17344       || val < (mintiny << op->shift)
17345       || val > (maxtiny << op->shift))
17346     return 1;
17347   else
17348     return 0;
17349 }
17350
17351 /* Compute the length of a branch sequence, and adjust the
17352    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17353    worst-case length is computed, with UPDATE being used to indicate
17354    whether an unconditional (-1), branch-likely (+1) or regular (0)
17355    branch is to be computed.  */
17356 static int
17357 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17358 {
17359   bfd_boolean toofar;
17360   int length;
17361
17362   if (fragp
17363       && S_IS_DEFINED (fragp->fr_symbol)
17364       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17365     {
17366       addressT addr;
17367       offsetT val;
17368
17369       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17370
17371       addr = fragp->fr_address + fragp->fr_fix + 4;
17372
17373       val -= addr;
17374
17375       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17376     }
17377   else if (fragp)
17378     /* If the symbol is not defined or it's in a different segment,
17379        assume the user knows what's going on and emit a short
17380        branch.  */
17381     toofar = FALSE;
17382   else
17383     toofar = TRUE;
17384
17385   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17386     fragp->fr_subtype
17387       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17388                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17389                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17390                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17391                              toofar);
17392
17393   length = 4;
17394   if (toofar)
17395     {
17396       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17397         length += 8;
17398
17399       if (mips_pic != NO_PIC)
17400         {
17401           /* Additional space for PIC loading of target address.  */
17402           length += 8;
17403           if (mips_opts.isa == ISA_MIPS1)
17404             /* Additional space for $at-stabilizing nop.  */
17405             length += 4;
17406         }
17407
17408       /* If branch is conditional.  */
17409       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17410         length += 8;
17411     }
17412
17413   return length;
17414 }
17415
17416 /* Compute the length of a branch sequence, and adjust the
17417    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17418    worst-case length is computed, with UPDATE being used to indicate
17419    whether an unconditional (-1), or regular (0) branch is to be
17420    computed.  */
17421
17422 static int
17423 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17424 {
17425   bfd_boolean toofar;
17426   int length;
17427
17428   if (fragp
17429       && S_IS_DEFINED (fragp->fr_symbol)
17430       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17431     {
17432       addressT addr;
17433       offsetT val;
17434
17435       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17436       /* Ignore the low bit in the target, since it will be set
17437          for a text label.  */
17438       if ((val & 1) != 0)
17439         --val;
17440
17441       addr = fragp->fr_address + fragp->fr_fix + 4;
17442
17443       val -= addr;
17444
17445       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17446     }
17447   else if (fragp)
17448     /* If the symbol is not defined or it's in a different segment,
17449        assume the user knows what's going on and emit a short
17450        branch.  */
17451     toofar = FALSE;
17452   else
17453     toofar = TRUE;
17454
17455   if (fragp && update
17456       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17457     fragp->fr_subtype = (toofar
17458                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17459                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17460
17461   length = 4;
17462   if (toofar)
17463     {
17464       bfd_boolean compact_known = fragp != NULL;
17465       bfd_boolean compact = FALSE;
17466       bfd_boolean uncond;
17467
17468       if (compact_known)
17469         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17470       if (fragp)
17471         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17472       else
17473         uncond = update < 0;
17474
17475       /* If label is out of range, we turn branch <br>:
17476
17477                 <br>    label                   # 4 bytes
17478             0:
17479
17480          into:
17481
17482                 j       label                   # 4 bytes
17483                 nop                             # 2 bytes if compact && !PIC
17484             0:
17485        */
17486       if (mips_pic == NO_PIC && (!compact_known || compact))
17487         length += 2;
17488
17489       /* If assembling PIC code, we further turn:
17490
17491                         j       label                   # 4 bytes
17492
17493          into:
17494
17495                         lw/ld   at, %got(label)(gp)     # 4 bytes
17496                         d/addiu at, %lo(label)          # 4 bytes
17497                         jr/c    at                      # 2 bytes
17498        */
17499       if (mips_pic != NO_PIC)
17500         length += 6;
17501
17502       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17503
17504                         <brneg> 0f                      # 4 bytes
17505                         nop                             # 2 bytes if !compact
17506        */
17507       if (!uncond)
17508         length += (compact_known && compact) ? 4 : 6;
17509     }
17510
17511   return length;
17512 }
17513
17514 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17515    bit accordingly.  */
17516
17517 static int
17518 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17519 {
17520   bfd_boolean toofar;
17521
17522   if (fragp
17523       && S_IS_DEFINED (fragp->fr_symbol)
17524       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17525     {
17526       addressT addr;
17527       offsetT val;
17528       int type;
17529
17530       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17531       /* Ignore the low bit in the target, since it will be set
17532          for a text label.  */
17533       if ((val & 1) != 0)
17534         --val;
17535
17536       /* Assume this is a 2-byte branch.  */
17537       addr = fragp->fr_address + fragp->fr_fix + 2;
17538
17539       /* We try to avoid the infinite loop by not adding 2 more bytes for
17540          long branches.  */
17541
17542       val -= addr;
17543
17544       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17545       if (type == 'D')
17546         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17547       else if (type == 'E')
17548         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17549       else
17550         abort ();
17551     }
17552   else
17553     /* If the symbol is not defined or it's in a different segment,
17554        we emit a normal 32-bit branch.  */
17555     toofar = TRUE;
17556
17557   if (fragp && update
17558       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17559     fragp->fr_subtype
17560       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17561                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17562
17563   if (toofar)
17564     return 4;
17565
17566   return 2;
17567 }
17568
17569 /* Estimate the size of a frag before relaxing.  Unless this is the
17570    mips16, we are not really relaxing here, and the final size is
17571    encoded in the subtype information.  For the mips16, we have to
17572    decide whether we are using an extended opcode or not.  */
17573
17574 int
17575 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17576 {
17577   int change;
17578
17579   if (RELAX_BRANCH_P (fragp->fr_subtype))
17580     {
17581
17582       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17583
17584       return fragp->fr_var;
17585     }
17586
17587   if (RELAX_MIPS16_P (fragp->fr_subtype))
17588     /* We don't want to modify the EXTENDED bit here; it might get us
17589        into infinite loops.  We change it only in mips_relax_frag().  */
17590     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17591
17592   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17593     {
17594       int length = 4;
17595
17596       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17597         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17598       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17599         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17600       fragp->fr_var = length;
17601
17602       return length;
17603     }
17604
17605   if (mips_pic == NO_PIC)
17606     change = nopic_need_relax (fragp->fr_symbol, 0);
17607   else if (mips_pic == SVR4_PIC)
17608     change = pic_need_relax (fragp->fr_symbol, segtype);
17609   else if (mips_pic == VXWORKS_PIC)
17610     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17611     change = 0;
17612   else
17613     abort ();
17614
17615   if (change)
17616     {
17617       fragp->fr_subtype |= RELAX_USE_SECOND;
17618       return -RELAX_FIRST (fragp->fr_subtype);
17619     }
17620   else
17621     return -RELAX_SECOND (fragp->fr_subtype);
17622 }
17623
17624 /* This is called to see whether a reloc against a defined symbol
17625    should be converted into a reloc against a section.  */
17626
17627 int
17628 mips_fix_adjustable (fixS *fixp)
17629 {
17630   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17631       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17632     return 0;
17633
17634   if (fixp->fx_addsy == NULL)
17635     return 1;
17636
17637   /* If symbol SYM is in a mergeable section, relocations of the form
17638      SYM + 0 can usually be made section-relative.  The mergeable data
17639      is then identified by the section offset rather than by the symbol.
17640
17641      However, if we're generating REL LO16 relocations, the offset is split
17642      between the LO16 and parterning high part relocation.  The linker will
17643      need to recalculate the complete offset in order to correctly identify
17644      the merge data.
17645
17646      The linker has traditionally not looked for the parterning high part
17647      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17648      placed anywhere.  Rather than break backwards compatibility by changing
17649      this, it seems better not to force the issue, and instead keep the
17650      original symbol.  This will work with either linker behavior.  */
17651   if ((lo16_reloc_p (fixp->fx_r_type)
17652        || reloc_needs_lo_p (fixp->fx_r_type))
17653       && HAVE_IN_PLACE_ADDENDS
17654       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17655     return 0;
17656
17657   /* There is no place to store an in-place offset for JALR relocations.
17658      Likewise an in-range offset of limited PC-relative relocations may
17659      overflow the in-place relocatable field if recalculated against the
17660      start address of the symbol's containing section.  */
17661   if (HAVE_IN_PLACE_ADDENDS
17662       && (limited_pcrel_reloc_p (fixp->fx_r_type)
17663           || jalr_reloc_p (fixp->fx_r_type)))
17664     return 0;
17665
17666   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17667      to a floating-point stub.  The same is true for non-R_MIPS16_26
17668      relocations against MIPS16 functions; in this case, the stub becomes
17669      the function's canonical address.
17670
17671      Floating-point stubs are stored in unique .mips16.call.* or
17672      .mips16.fn.* sections.  If a stub T for function F is in section S,
17673      the first relocation in section S must be against F; this is how the
17674      linker determines the target function.  All relocations that might
17675      resolve to T must also be against F.  We therefore have the following
17676      restrictions, which are given in an intentionally-redundant way:
17677
17678        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17679           symbols.
17680
17681        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17682           if that stub might be used.
17683
17684        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17685           symbols.
17686
17687        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17688           that stub might be used.
17689
17690      There is a further restriction:
17691
17692        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17693           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
17694           targets with in-place addends; the relocation field cannot
17695           encode the low bit.
17696
17697      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17698      against a MIPS16 symbol.  We deal with (5) by by not reducing any
17699      such relocations on REL targets.
17700
17701      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17702      relocation against some symbol R, no relocation against R may be
17703      reduced.  (Note that this deals with (2) as well as (1) because
17704      relocations against global symbols will never be reduced on ELF
17705      targets.)  This approach is a little simpler than trying to detect
17706      stub sections, and gives the "all or nothing" per-symbol consistency
17707      that we have for MIPS16 symbols.  */
17708   if (fixp->fx_subsy == NULL
17709       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17710           || *symbol_get_tc (fixp->fx_addsy)
17711           || (HAVE_IN_PLACE_ADDENDS
17712               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17713               && jmp_reloc_p (fixp->fx_r_type))))
17714     return 0;
17715
17716   return 1;
17717 }
17718
17719 /* Translate internal representation of relocation info to BFD target
17720    format.  */
17721
17722 arelent **
17723 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17724 {
17725   static arelent *retval[4];
17726   arelent *reloc;
17727   bfd_reloc_code_real_type code;
17728
17729   memset (retval, 0, sizeof(retval));
17730   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
17731   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
17732   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17733   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17734
17735   if (fixp->fx_pcrel)
17736     {
17737       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17738                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17739                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17740                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17741                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
17742
17743       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17744          Relocations want only the symbol offset.  */
17745       reloc->addend = fixp->fx_addnumber + reloc->address;
17746     }
17747   else
17748     reloc->addend = fixp->fx_addnumber;
17749
17750   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17751      entry to be used in the relocation's section offset.  */
17752   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17753     {
17754       reloc->address = reloc->addend;
17755       reloc->addend = 0;
17756     }
17757
17758   code = fixp->fx_r_type;
17759
17760   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17761   if (reloc->howto == NULL)
17762     {
17763       as_bad_where (fixp->fx_file, fixp->fx_line,
17764                     _("Can not represent %s relocation in this object file format"),
17765                     bfd_get_reloc_code_name (code));
17766       retval[0] = NULL;
17767     }
17768
17769   return retval;
17770 }
17771
17772 /* Relax a machine dependent frag.  This returns the amount by which
17773    the current size of the frag should change.  */
17774
17775 int
17776 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17777 {
17778   if (RELAX_BRANCH_P (fragp->fr_subtype))
17779     {
17780       offsetT old_var = fragp->fr_var;
17781
17782       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17783
17784       return fragp->fr_var - old_var;
17785     }
17786
17787   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17788     {
17789       offsetT old_var = fragp->fr_var;
17790       offsetT new_var = 4;
17791
17792       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17793         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17794       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17795         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17796       fragp->fr_var = new_var;
17797
17798       return new_var - old_var;
17799     }
17800
17801   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17802     return 0;
17803
17804   if (mips16_extended_frag (fragp, NULL, stretch))
17805     {
17806       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17807         return 0;
17808       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17809       return 2;
17810     }
17811   else
17812     {
17813       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17814         return 0;
17815       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17816       return -2;
17817     }
17818
17819   return 0;
17820 }
17821
17822 /* Convert a machine dependent frag.  */
17823
17824 void
17825 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17826 {
17827   if (RELAX_BRANCH_P (fragp->fr_subtype))
17828     {
17829       char *buf;
17830       unsigned long insn;
17831       expressionS exp;
17832       fixS *fixp;
17833
17834       buf = fragp->fr_literal + fragp->fr_fix;
17835       insn = read_insn (buf);
17836
17837       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17838         {
17839           /* We generate a fixup instead of applying it right now
17840              because, if there are linker relaxations, we're going to
17841              need the relocations.  */
17842           exp.X_op = O_symbol;
17843           exp.X_add_symbol = fragp->fr_symbol;
17844           exp.X_add_number = fragp->fr_offset;
17845
17846           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17847                               BFD_RELOC_16_PCREL_S2);
17848           fixp->fx_file = fragp->fr_file;
17849           fixp->fx_line = fragp->fr_line;
17850
17851           buf = write_insn (buf, insn);
17852         }
17853       else
17854         {
17855           int i;
17856
17857           as_warn_where (fragp->fr_file, fragp->fr_line,
17858                          _("Relaxed out-of-range branch into a jump"));
17859
17860           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17861             goto uncond;
17862
17863           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17864             {
17865               /* Reverse the branch.  */
17866               switch ((insn >> 28) & 0xf)
17867                 {
17868                 case 4:
17869                   /* bc[0-3][tf]l? instructions can have the condition
17870                      reversed by tweaking a single TF bit, and their
17871                      opcodes all have 0x4???????.  */
17872                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
17873                   insn ^= 0x00010000;
17874                   break;
17875
17876                 case 0:
17877                   /* bltz       0x04000000      bgez    0x04010000
17878                      bltzal     0x04100000      bgezal  0x04110000  */
17879                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17880                   insn ^= 0x00010000;
17881                   break;
17882
17883                 case 1:
17884                   /* beq        0x10000000      bne     0x14000000
17885                      blez       0x18000000      bgtz    0x1c000000  */
17886                   insn ^= 0x04000000;
17887                   break;
17888
17889                 default:
17890                   abort ();
17891                 }
17892             }
17893
17894           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17895             {
17896               /* Clear the and-link bit.  */
17897               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17898
17899               /* bltzal         0x04100000      bgezal  0x04110000
17900                  bltzall        0x04120000      bgezall 0x04130000  */
17901               insn &= ~0x00100000;
17902             }
17903
17904           /* Branch over the branch (if the branch was likely) or the
17905              full jump (not likely case).  Compute the offset from the
17906              current instruction to branch to.  */
17907           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17908             i = 16;
17909           else
17910             {
17911               /* How many bytes in instructions we've already emitted?  */
17912               i = buf - fragp->fr_literal - fragp->fr_fix;
17913               /* How many bytes in instructions from here to the end?  */
17914               i = fragp->fr_var - i;
17915             }
17916           /* Convert to instruction count.  */
17917           i >>= 2;
17918           /* Branch counts from the next instruction.  */
17919           i--;
17920           insn |= i;
17921           /* Branch over the jump.  */
17922           buf = write_insn (buf, insn);
17923
17924           /* nop */
17925           buf = write_insn (buf, 0);
17926
17927           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17928             {
17929               /* beql $0, $0, 2f */
17930               insn = 0x50000000;
17931               /* Compute the PC offset from the current instruction to
17932                  the end of the variable frag.  */
17933               /* How many bytes in instructions we've already emitted?  */
17934               i = buf - fragp->fr_literal - fragp->fr_fix;
17935               /* How many bytes in instructions from here to the end?  */
17936               i = fragp->fr_var - i;
17937               /* Convert to instruction count.  */
17938               i >>= 2;
17939               /* Don't decrement i, because we want to branch over the
17940                  delay slot.  */
17941               insn |= i;
17942
17943               buf = write_insn (buf, insn);
17944               buf = write_insn (buf, 0);
17945             }
17946
17947         uncond:
17948           if (mips_pic == NO_PIC)
17949             {
17950               /* j or jal.  */
17951               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17952                       ? 0x0c000000 : 0x08000000);
17953               exp.X_op = O_symbol;
17954               exp.X_add_symbol = fragp->fr_symbol;
17955               exp.X_add_number = fragp->fr_offset;
17956
17957               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17958                                   FALSE, BFD_RELOC_MIPS_JMP);
17959               fixp->fx_file = fragp->fr_file;
17960               fixp->fx_line = fragp->fr_line;
17961
17962               buf = write_insn (buf, insn);
17963             }
17964           else
17965             {
17966               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17967
17968               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17969               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17970               insn |= at << OP_SH_RT;
17971               exp.X_op = O_symbol;
17972               exp.X_add_symbol = fragp->fr_symbol;
17973               exp.X_add_number = fragp->fr_offset;
17974
17975               if (fragp->fr_offset)
17976                 {
17977                   exp.X_add_symbol = make_expr_symbol (&exp);
17978                   exp.X_add_number = 0;
17979                 }
17980
17981               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17982                                   FALSE, BFD_RELOC_MIPS_GOT16);
17983               fixp->fx_file = fragp->fr_file;
17984               fixp->fx_line = fragp->fr_line;
17985
17986               buf = write_insn (buf, insn);
17987
17988               if (mips_opts.isa == ISA_MIPS1)
17989                 /* nop */
17990                 buf = write_insn (buf, 0);
17991
17992               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17993               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17994               insn |= at << OP_SH_RS | at << OP_SH_RT;
17995
17996               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17997                                   FALSE, BFD_RELOC_LO16);
17998               fixp->fx_file = fragp->fr_file;
17999               fixp->fx_line = fragp->fr_line;
18000
18001               buf = write_insn (buf, insn);
18002
18003               /* j(al)r $at.  */
18004               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
18005                 insn = 0x0000f809;
18006               else
18007                 insn = 0x00000008;
18008               insn |= at << OP_SH_RS;
18009
18010               buf = write_insn (buf, insn);
18011             }
18012         }
18013
18014       fragp->fr_fix += fragp->fr_var;
18015       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18016       return;
18017     }
18018
18019   /* Relax microMIPS branches.  */
18020   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
18021     {
18022       char *buf = fragp->fr_literal + fragp->fr_fix;
18023       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
18024       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
18025       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
18026       bfd_boolean short_ds;
18027       unsigned long insn;
18028       expressionS exp;
18029       fixS *fixp;
18030
18031       exp.X_op = O_symbol;
18032       exp.X_add_symbol = fragp->fr_symbol;
18033       exp.X_add_number = fragp->fr_offset;
18034
18035       fragp->fr_fix += fragp->fr_var;
18036
18037       /* Handle 16-bit branches that fit or are forced to fit.  */
18038       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
18039         {
18040           /* We generate a fixup instead of applying it right now,
18041              because if there is linker relaxation, we're going to
18042              need the relocations.  */
18043           if (type == 'D')
18044             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18045                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
18046           else if (type == 'E')
18047             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
18048                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
18049           else
18050             abort ();
18051
18052           fixp->fx_file = fragp->fr_file;
18053           fixp->fx_line = fragp->fr_line;
18054
18055           /* These relocations can have an addend that won't fit in
18056              2 octets.  */
18057           fixp->fx_no_overflow = 1;
18058
18059           return;
18060         }
18061
18062       /* Handle 32-bit branches that fit or are forced to fit.  */
18063       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18064           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18065         {
18066           /* We generate a fixup instead of applying it right now,
18067              because if there is linker relaxation, we're going to
18068              need the relocations.  */
18069           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
18070                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
18071           fixp->fx_file = fragp->fr_file;
18072           fixp->fx_line = fragp->fr_line;
18073
18074           if (type == 0)
18075             return;
18076         }
18077
18078       /* Relax 16-bit branches to 32-bit branches.  */
18079       if (type != 0)
18080         {
18081           insn = read_compressed_insn (buf, 2);
18082
18083           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
18084             insn = 0x94000000;                          /* beq  */
18085           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
18086             {
18087               unsigned long regno;
18088
18089               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
18090               regno = micromips_to_32_reg_d_map [regno];
18091               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
18092               insn |= regno << MICROMIPSOP_SH_RS;
18093             }
18094           else
18095             abort ();
18096
18097           /* Nothing else to do, just write it out.  */
18098           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
18099               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
18100             {
18101               buf = write_compressed_insn (buf, insn, 4);
18102               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18103               return;
18104             }
18105         }
18106       else
18107         insn = read_compressed_insn (buf, 4);
18108
18109       /* Relax 32-bit branches to a sequence of instructions.  */
18110       as_warn_where (fragp->fr_file, fragp->fr_line,
18111                      _("Relaxed out-of-range branch into a jump"));
18112
18113       /* Set the short-delay-slot bit.  */
18114       short_ds = al && (insn & 0x02000000) != 0;
18115
18116       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
18117         {
18118           symbolS *l;
18119
18120           /* Reverse the branch.  */
18121           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
18122               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
18123             insn ^= 0x20000000;
18124           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
18125                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
18126                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
18127                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
18128                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
18129                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
18130                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
18131                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
18132                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
18133                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
18134             insn ^= 0x00400000;
18135           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
18136                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
18137                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
18138                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
18139             insn ^= 0x00200000;
18140           else
18141             abort ();
18142
18143           if (al)
18144             {
18145               /* Clear the and-link and short-delay-slot bits.  */
18146               gas_assert ((insn & 0xfda00000) == 0x40200000);
18147
18148               /* bltzal  0x40200000     bgezal  0x40600000  */
18149               /* bltzals 0x42200000     bgezals 0x42600000  */
18150               insn &= ~0x02200000;
18151             }
18152
18153           /* Make a label at the end for use with the branch.  */
18154           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
18155           micromips_label_inc ();
18156           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
18157
18158           /* Refer to it.  */
18159           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
18160                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
18161           fixp->fx_file = fragp->fr_file;
18162           fixp->fx_line = fragp->fr_line;
18163
18164           /* Branch over the jump.  */
18165           buf = write_compressed_insn (buf, insn, 4);
18166           if (!compact)
18167             /* nop */
18168             buf = write_compressed_insn (buf, 0x0c00, 2);
18169         }
18170
18171       if (mips_pic == NO_PIC)
18172         {
18173           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
18174
18175           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
18176           insn = al ? jal : 0xd4000000;
18177
18178           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18179                               BFD_RELOC_MICROMIPS_JMP);
18180           fixp->fx_file = fragp->fr_file;
18181           fixp->fx_line = fragp->fr_line;
18182
18183           buf = write_compressed_insn (buf, insn, 4);
18184           if (compact)
18185             /* nop */
18186             buf = write_compressed_insn (buf, 0x0c00, 2);
18187         }
18188       else
18189         {
18190           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18191           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18192           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18193
18194           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18195           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18196           insn |= at << MICROMIPSOP_SH_RT;
18197
18198           if (exp.X_add_number)
18199             {
18200               exp.X_add_symbol = make_expr_symbol (&exp);
18201               exp.X_add_number = 0;
18202             }
18203
18204           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18205                               BFD_RELOC_MICROMIPS_GOT16);
18206           fixp->fx_file = fragp->fr_file;
18207           fixp->fx_line = fragp->fr_line;
18208
18209           buf = write_compressed_insn (buf, insn, 4);
18210
18211           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18212           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18213           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18214
18215           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18216                               BFD_RELOC_MICROMIPS_LO16);
18217           fixp->fx_file = fragp->fr_file;
18218           fixp->fx_line = fragp->fr_line;
18219
18220           buf = write_compressed_insn (buf, insn, 4);
18221
18222           /* jr/jrc/jalr/jalrs $at  */
18223           insn = al ? jalr : jr;
18224           insn |= at << MICROMIPSOP_SH_MJ;
18225
18226           buf = write_compressed_insn (buf, insn, 2);
18227         }
18228
18229       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18230       return;
18231     }
18232
18233   if (RELAX_MIPS16_P (fragp->fr_subtype))
18234     {
18235       int type;
18236       const struct mips16_immed_operand *op;
18237       offsetT val;
18238       char *buf;
18239       unsigned int user_length, length;
18240       unsigned long insn;
18241       bfd_boolean ext;
18242
18243       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18244       op = mips16_immed_operands;
18245       while (op->type != type)
18246         ++op;
18247
18248       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18249       val = resolve_symbol_value (fragp->fr_symbol);
18250       if (op->pcrel)
18251         {
18252           addressT addr;
18253
18254           addr = fragp->fr_address + fragp->fr_fix;
18255
18256           /* The rules for the base address of a PC relative reloc are
18257              complicated; see mips16_extended_frag.  */
18258           if (type == 'p' || type == 'q')
18259             {
18260               addr += 2;
18261               if (ext)
18262                 addr += 2;
18263               /* Ignore the low bit in the target, since it will be
18264                  set for a text label.  */
18265               if ((val & 1) != 0)
18266                 --val;
18267             }
18268           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18269             addr -= 4;
18270           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18271             addr -= 2;
18272
18273           addr &= ~ (addressT) ((1 << op->shift) - 1);
18274           val -= addr;
18275
18276           /* Make sure the section winds up with the alignment we have
18277              assumed.  */
18278           if (op->shift > 0)
18279             record_alignment (asec, op->shift);
18280         }
18281
18282       if (ext
18283           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18284               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18285         as_warn_where (fragp->fr_file, fragp->fr_line,
18286                        _("extended instruction in delay slot"));
18287
18288       buf = fragp->fr_literal + fragp->fr_fix;
18289
18290       insn = read_compressed_insn (buf, 2);
18291       if (ext)
18292         insn |= MIPS16_EXTEND;
18293
18294       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18295         user_length = 4;
18296       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18297         user_length = 2;
18298       else
18299         user_length = 0;
18300
18301       mips16_immed (fragp->fr_file, fragp->fr_line, type,
18302                     BFD_RELOC_UNUSED, val, user_length, &insn);
18303
18304       length = (ext ? 4 : 2);
18305       gas_assert (mips16_opcode_length (insn) == length);
18306       write_compressed_insn (buf, insn, length);
18307       fragp->fr_fix += length;
18308     }
18309   else
18310     {
18311       relax_substateT subtype = fragp->fr_subtype;
18312       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18313       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18314       int first, second;
18315       fixS *fixp;
18316
18317       first = RELAX_FIRST (subtype);
18318       second = RELAX_SECOND (subtype);
18319       fixp = (fixS *) fragp->fr_opcode;
18320
18321       /* If the delay slot chosen does not match the size of the instruction,
18322          then emit a warning.  */
18323       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18324            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18325         {
18326           relax_substateT s;
18327           const char *msg;
18328
18329           s = subtype & (RELAX_DELAY_SLOT_16BIT
18330                          | RELAX_DELAY_SLOT_SIZE_FIRST
18331                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18332           msg = macro_warning (s);
18333           if (msg != NULL)
18334             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18335           subtype &= ~s;
18336         }
18337
18338       /* Possibly emit a warning if we've chosen the longer option.  */
18339       if (use_second == second_longer)
18340         {
18341           relax_substateT s;
18342           const char *msg;
18343
18344           s = (subtype
18345                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18346           msg = macro_warning (s);
18347           if (msg != NULL)
18348             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18349           subtype &= ~s;
18350         }
18351
18352       /* Go through all the fixups for the first sequence.  Disable them
18353          (by marking them as done) if we're going to use the second
18354          sequence instead.  */
18355       while (fixp
18356              && fixp->fx_frag == fragp
18357              && fixp->fx_where < fragp->fr_fix - second)
18358         {
18359           if (subtype & RELAX_USE_SECOND)
18360             fixp->fx_done = 1;
18361           fixp = fixp->fx_next;
18362         }
18363
18364       /* Go through the fixups for the second sequence.  Disable them if
18365          we're going to use the first sequence, otherwise adjust their
18366          addresses to account for the relaxation.  */
18367       while (fixp && fixp->fx_frag == fragp)
18368         {
18369           if (subtype & RELAX_USE_SECOND)
18370             fixp->fx_where -= first;
18371           else
18372             fixp->fx_done = 1;
18373           fixp = fixp->fx_next;
18374         }
18375
18376       /* Now modify the frag contents.  */
18377       if (subtype & RELAX_USE_SECOND)
18378         {
18379           char *start;
18380
18381           start = fragp->fr_literal + fragp->fr_fix - first - second;
18382           memmove (start, start + first, second);
18383           fragp->fr_fix -= first;
18384         }
18385       else
18386         fragp->fr_fix -= second;
18387     }
18388 }
18389
18390 /* This function is called after the relocs have been generated.
18391    We've been storing mips16 text labels as odd.  Here we convert them
18392    back to even for the convenience of the debugger.  */
18393
18394 void
18395 mips_frob_file_after_relocs (void)
18396 {
18397   asymbol **syms;
18398   unsigned int count, i;
18399
18400   syms = bfd_get_outsymbols (stdoutput);
18401   count = bfd_get_symcount (stdoutput);
18402   for (i = 0; i < count; i++, syms++)
18403     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18404         && ((*syms)->value & 1) != 0)
18405       {
18406         (*syms)->value &= ~1;
18407         /* If the symbol has an odd size, it was probably computed
18408            incorrectly, so adjust that as well.  */
18409         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18410           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18411       }
18412 }
18413
18414 /* This function is called whenever a label is defined, including fake
18415    labels instantiated off the dot special symbol.  It is used when
18416    handling branch delays; if a branch has a label, we assume we cannot
18417    move it.  This also bumps the value of the symbol by 1 in compressed
18418    code.  */
18419
18420 static void
18421 mips_record_label (symbolS *sym)
18422 {
18423   segment_info_type *si = seg_info (now_seg);
18424   struct insn_label_list *l;
18425
18426   if (free_insn_labels == NULL)
18427     l = (struct insn_label_list *) xmalloc (sizeof *l);
18428   else
18429     {
18430       l = free_insn_labels;
18431       free_insn_labels = l->next;
18432     }
18433
18434   l->label = sym;
18435   l->next = si->label_list;
18436   si->label_list = l;
18437 }
18438
18439 /* This function is called as tc_frob_label() whenever a label is defined
18440    and adds a DWARF-2 record we only want for true labels.  */
18441
18442 void
18443 mips_define_label (symbolS *sym)
18444 {
18445   mips_record_label (sym);
18446   dwarf2_emit_label (sym);
18447 }
18448
18449 /* This function is called by tc_new_dot_label whenever a new dot symbol
18450    is defined.  */
18451
18452 void
18453 mips_add_dot_label (symbolS *sym)
18454 {
18455   mips_record_label (sym);
18456   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18457     mips_compressed_mark_label (sym);
18458 }
18459 \f
18460 /* Some special processing for a MIPS ELF file.  */
18461
18462 void
18463 mips_elf_final_processing (void)
18464 {
18465   /* Write out the register information.  */
18466   if (mips_abi != N64_ABI)
18467     {
18468       Elf32_RegInfo s;
18469
18470       s.ri_gprmask = mips_gprmask;
18471       s.ri_cprmask[0] = mips_cprmask[0];
18472       s.ri_cprmask[1] = mips_cprmask[1];
18473       s.ri_cprmask[2] = mips_cprmask[2];
18474       s.ri_cprmask[3] = mips_cprmask[3];
18475       /* The gp_value field is set by the MIPS ELF backend.  */
18476
18477       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18478                                        ((Elf32_External_RegInfo *)
18479                                         mips_regmask_frag));
18480     }
18481   else
18482     {
18483       Elf64_Internal_RegInfo s;
18484
18485       s.ri_gprmask = mips_gprmask;
18486       s.ri_pad = 0;
18487       s.ri_cprmask[0] = mips_cprmask[0];
18488       s.ri_cprmask[1] = mips_cprmask[1];
18489       s.ri_cprmask[2] = mips_cprmask[2];
18490       s.ri_cprmask[3] = mips_cprmask[3];
18491       /* The gp_value field is set by the MIPS ELF backend.  */
18492
18493       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18494                                        ((Elf64_External_RegInfo *)
18495                                         mips_regmask_frag));
18496     }
18497
18498   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18499      sort of BFD interface for this.  */
18500   if (mips_any_noreorder)
18501     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18502   if (mips_pic != NO_PIC)
18503     {
18504       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18505       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18506     }
18507   if (mips_abicalls)
18508     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18509
18510   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
18511      defined at present; this might need to change in future.  */
18512   if (file_ase_mips16)
18513     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18514   if (file_ase_micromips)
18515     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18516   if (file_ase & ASE_MDMX)
18517     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18518
18519   /* Set the MIPS ELF ABI flags.  */
18520   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18521     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18522   else if (mips_abi == O64_ABI)
18523     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18524   else if (mips_abi == EABI_ABI)
18525     {
18526       if (!file_mips_gp32)
18527         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18528       else
18529         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18530     }
18531   else if (mips_abi == N32_ABI)
18532     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18533
18534   /* Nothing to do for N64_ABI.  */
18535
18536   if (mips_32bitmode)
18537     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18538
18539   if (mips_flag_nan2008)
18540     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
18541
18542 #if 0 /* XXX FIXME */
18543   /* 32 bit code with 64 bit FP registers.  */
18544   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
18545     elf_elfheader (stdoutput)->e_flags |= ???;
18546 #endif
18547 }
18548 \f
18549 typedef struct proc {
18550   symbolS *func_sym;
18551   symbolS *func_end_sym;
18552   unsigned long reg_mask;
18553   unsigned long reg_offset;
18554   unsigned long fpreg_mask;
18555   unsigned long fpreg_offset;
18556   unsigned long frame_offset;
18557   unsigned long frame_reg;
18558   unsigned long pc_reg;
18559 } procS;
18560
18561 static procS cur_proc;
18562 static procS *cur_proc_ptr;
18563 static int numprocs;
18564
18565 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18566    as "2", and a normal nop as "0".  */
18567
18568 #define NOP_OPCODE_MIPS         0
18569 #define NOP_OPCODE_MIPS16       1
18570 #define NOP_OPCODE_MICROMIPS    2
18571
18572 char
18573 mips_nop_opcode (void)
18574 {
18575   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18576     return NOP_OPCODE_MICROMIPS;
18577   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18578     return NOP_OPCODE_MIPS16;
18579   else
18580     return NOP_OPCODE_MIPS;
18581 }
18582
18583 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18584    32-bit microMIPS NOPs here (if applicable).  */
18585
18586 void
18587 mips_handle_align (fragS *fragp)
18588 {
18589   char nop_opcode;
18590   char *p;
18591   int bytes, size, excess;
18592   valueT opcode;
18593
18594   if (fragp->fr_type != rs_align_code)
18595     return;
18596
18597   p = fragp->fr_literal + fragp->fr_fix;
18598   nop_opcode = *p;
18599   switch (nop_opcode)
18600     {
18601     case NOP_OPCODE_MICROMIPS:
18602       opcode = micromips_nop32_insn.insn_opcode;
18603       size = 4;
18604       break;
18605     case NOP_OPCODE_MIPS16:
18606       opcode = mips16_nop_insn.insn_opcode;
18607       size = 2;
18608       break;
18609     case NOP_OPCODE_MIPS:
18610     default:
18611       opcode = nop_insn.insn_opcode;
18612       size = 4;
18613       break;
18614     }
18615
18616   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18617   excess = bytes % size;
18618
18619   /* Handle the leading part if we're not inserting a whole number of
18620      instructions, and make it the end of the fixed part of the frag.
18621      Try to fit in a short microMIPS NOP if applicable and possible,
18622      and use zeroes otherwise.  */
18623   gas_assert (excess < 4);
18624   fragp->fr_fix += excess;
18625   switch (excess)
18626     {
18627     case 3:
18628       *p++ = '\0';
18629       /* Fall through.  */
18630     case 2:
18631       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
18632         {
18633           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
18634           break;
18635         }
18636       *p++ = '\0';
18637       /* Fall through.  */
18638     case 1:
18639       *p++ = '\0';
18640       /* Fall through.  */
18641     case 0:
18642       break;
18643     }
18644
18645   md_number_to_chars (p, opcode, size);
18646   fragp->fr_var = size;
18647 }
18648
18649 static void
18650 md_obj_begin (void)
18651 {
18652 }
18653
18654 static void
18655 md_obj_end (void)
18656 {
18657   /* Check for premature end, nesting errors, etc.  */
18658   if (cur_proc_ptr)
18659     as_warn (_("missing .end at end of assembly"));
18660 }
18661
18662 static long
18663 get_number (void)
18664 {
18665   int negative = 0;
18666   long val = 0;
18667
18668   if (*input_line_pointer == '-')
18669     {
18670       ++input_line_pointer;
18671       negative = 1;
18672     }
18673   if (!ISDIGIT (*input_line_pointer))
18674     as_bad (_("expected simple number"));
18675   if (input_line_pointer[0] == '0')
18676     {
18677       if (input_line_pointer[1] == 'x')
18678         {
18679           input_line_pointer += 2;
18680           while (ISXDIGIT (*input_line_pointer))
18681             {
18682               val <<= 4;
18683               val |= hex_value (*input_line_pointer++);
18684             }
18685           return negative ? -val : val;
18686         }
18687       else
18688         {
18689           ++input_line_pointer;
18690           while (ISDIGIT (*input_line_pointer))
18691             {
18692               val <<= 3;
18693               val |= *input_line_pointer++ - '0';
18694             }
18695           return negative ? -val : val;
18696         }
18697     }
18698   if (!ISDIGIT (*input_line_pointer))
18699     {
18700       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18701               *input_line_pointer, *input_line_pointer);
18702       as_warn (_("invalid number"));
18703       return -1;
18704     }
18705   while (ISDIGIT (*input_line_pointer))
18706     {
18707       val *= 10;
18708       val += *input_line_pointer++ - '0';
18709     }
18710   return negative ? -val : val;
18711 }
18712
18713 /* The .file directive; just like the usual .file directive, but there
18714    is an initial number which is the ECOFF file index.  In the non-ECOFF
18715    case .file implies DWARF-2.  */
18716
18717 static void
18718 s_mips_file (int x ATTRIBUTE_UNUSED)
18719 {
18720   static int first_file_directive = 0;
18721
18722   if (ECOFF_DEBUGGING)
18723     {
18724       get_number ();
18725       s_app_file (0);
18726     }
18727   else
18728     {
18729       char *filename;
18730
18731       filename = dwarf2_directive_file (0);
18732
18733       /* Versions of GCC up to 3.1 start files with a ".file"
18734          directive even for stabs output.  Make sure that this
18735          ".file" is handled.  Note that you need a version of GCC
18736          after 3.1 in order to support DWARF-2 on MIPS.  */
18737       if (filename != NULL && ! first_file_directive)
18738         {
18739           (void) new_logical_line (filename, -1);
18740           s_app_file_string (filename, 0);
18741         }
18742       first_file_directive = 1;
18743     }
18744 }
18745
18746 /* The .loc directive, implying DWARF-2.  */
18747
18748 static void
18749 s_mips_loc (int x ATTRIBUTE_UNUSED)
18750 {
18751   if (!ECOFF_DEBUGGING)
18752     dwarf2_directive_loc (0);
18753 }
18754
18755 /* The .end directive.  */
18756
18757 static void
18758 s_mips_end (int x ATTRIBUTE_UNUSED)
18759 {
18760   symbolS *p;
18761
18762   /* Following functions need their own .frame and .cprestore directives.  */
18763   mips_frame_reg_valid = 0;
18764   mips_cprestore_valid = 0;
18765
18766   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18767     {
18768       p = get_symbol ();
18769       demand_empty_rest_of_line ();
18770     }
18771   else
18772     p = NULL;
18773
18774   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18775     as_warn (_(".end not in text section"));
18776
18777   if (!cur_proc_ptr)
18778     {
18779       as_warn (_(".end directive without a preceding .ent directive."));
18780       demand_empty_rest_of_line ();
18781       return;
18782     }
18783
18784   if (p != NULL)
18785     {
18786       gas_assert (S_GET_NAME (p));
18787       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18788         as_warn (_(".end symbol does not match .ent symbol."));
18789
18790       if (debug_type == DEBUG_STABS)
18791         stabs_generate_asm_endfunc (S_GET_NAME (p),
18792                                     S_GET_NAME (p));
18793     }
18794   else
18795     as_warn (_(".end directive missing or unknown symbol"));
18796
18797   /* Create an expression to calculate the size of the function.  */
18798   if (p && cur_proc_ptr)
18799     {
18800       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18801       expressionS *exp = xmalloc (sizeof (expressionS));
18802
18803       obj->size = exp;
18804       exp->X_op = O_subtract;
18805       exp->X_add_symbol = symbol_temp_new_now ();
18806       exp->X_op_symbol = p;
18807       exp->X_add_number = 0;
18808
18809       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18810     }
18811
18812   /* Generate a .pdr section.  */
18813   if (!ECOFF_DEBUGGING && mips_flag_pdr)
18814     {
18815       segT saved_seg = now_seg;
18816       subsegT saved_subseg = now_subseg;
18817       expressionS exp;
18818       char *fragp;
18819
18820 #ifdef md_flush_pending_output
18821       md_flush_pending_output ();
18822 #endif
18823
18824       gas_assert (pdr_seg);
18825       subseg_set (pdr_seg, 0);
18826
18827       /* Write the symbol.  */
18828       exp.X_op = O_symbol;
18829       exp.X_add_symbol = p;
18830       exp.X_add_number = 0;
18831       emit_expr (&exp, 4);
18832
18833       fragp = frag_more (7 * 4);
18834
18835       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18836       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18837       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18838       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18839       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18840       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18841       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18842
18843       subseg_set (saved_seg, saved_subseg);
18844     }
18845
18846   cur_proc_ptr = NULL;
18847 }
18848
18849 /* The .aent and .ent directives.  */
18850
18851 static void
18852 s_mips_ent (int aent)
18853 {
18854   symbolS *symbolP;
18855
18856   symbolP = get_symbol ();
18857   if (*input_line_pointer == ',')
18858     ++input_line_pointer;
18859   SKIP_WHITESPACE ();
18860   if (ISDIGIT (*input_line_pointer)
18861       || *input_line_pointer == '-')
18862     get_number ();
18863
18864   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18865     as_warn (_(".ent or .aent not in text section."));
18866
18867   if (!aent && cur_proc_ptr)
18868     as_warn (_("missing .end"));
18869
18870   if (!aent)
18871     {
18872       /* This function needs its own .frame and .cprestore directives.  */
18873       mips_frame_reg_valid = 0;
18874       mips_cprestore_valid = 0;
18875
18876       cur_proc_ptr = &cur_proc;
18877       memset (cur_proc_ptr, '\0', sizeof (procS));
18878
18879       cur_proc_ptr->func_sym = symbolP;
18880
18881       ++numprocs;
18882
18883       if (debug_type == DEBUG_STABS)
18884         stabs_generate_asm_func (S_GET_NAME (symbolP),
18885                                  S_GET_NAME (symbolP));
18886     }
18887
18888   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18889
18890   demand_empty_rest_of_line ();
18891 }
18892
18893 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18894    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18895    s_mips_frame is used so that we can set the PDR information correctly.
18896    We can't use the ecoff routines because they make reference to the ecoff
18897    symbol table (in the mdebug section).  */
18898
18899 static void
18900 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18901 {
18902   if (ECOFF_DEBUGGING)
18903     s_ignore (ignore);
18904   else
18905     {
18906       long val;
18907
18908       if (cur_proc_ptr == (procS *) NULL)
18909         {
18910           as_warn (_(".frame outside of .ent"));
18911           demand_empty_rest_of_line ();
18912           return;
18913         }
18914
18915       cur_proc_ptr->frame_reg = tc_get_register (1);
18916
18917       SKIP_WHITESPACE ();
18918       if (*input_line_pointer++ != ','
18919           || get_absolute_expression_and_terminator (&val) != ',')
18920         {
18921           as_warn (_("Bad .frame directive"));
18922           --input_line_pointer;
18923           demand_empty_rest_of_line ();
18924           return;
18925         }
18926
18927       cur_proc_ptr->frame_offset = val;
18928       cur_proc_ptr->pc_reg = tc_get_register (0);
18929
18930       demand_empty_rest_of_line ();
18931     }
18932 }
18933
18934 /* The .fmask and .mask directives. If the mdebug section is present
18935    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18936    embedded targets, s_mips_mask is used so that we can set the PDR
18937    information correctly. We can't use the ecoff routines because they
18938    make reference to the ecoff symbol table (in the mdebug section).  */
18939
18940 static void
18941 s_mips_mask (int reg_type)
18942 {
18943   if (ECOFF_DEBUGGING)
18944     s_ignore (reg_type);
18945   else
18946     {
18947       long mask, off;
18948
18949       if (cur_proc_ptr == (procS *) NULL)
18950         {
18951           as_warn (_(".mask/.fmask outside of .ent"));
18952           demand_empty_rest_of_line ();
18953           return;
18954         }
18955
18956       if (get_absolute_expression_and_terminator (&mask) != ',')
18957         {
18958           as_warn (_("Bad .mask/.fmask directive"));
18959           --input_line_pointer;
18960           demand_empty_rest_of_line ();
18961           return;
18962         }
18963
18964       off = get_absolute_expression ();
18965
18966       if (reg_type == 'F')
18967         {
18968           cur_proc_ptr->fpreg_mask = mask;
18969           cur_proc_ptr->fpreg_offset = off;
18970         }
18971       else
18972         {
18973           cur_proc_ptr->reg_mask = mask;
18974           cur_proc_ptr->reg_offset = off;
18975         }
18976
18977       demand_empty_rest_of_line ();
18978     }
18979 }
18980
18981 /* A table describing all the processors gas knows about.  Names are
18982    matched in the order listed.
18983
18984    To ease comparison, please keep this table in the same order as
18985    gcc's mips_cpu_info_table[].  */
18986 static const struct mips_cpu_info mips_cpu_info_table[] =
18987 {
18988   /* Entries for generic ISAs */
18989   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
18990   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
18991   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
18992   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
18993   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
18994   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
18995   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
18996   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
18997   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
18998
18999   /* MIPS I */
19000   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19001   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
19002   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
19003
19004   /* MIPS II */
19005   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
19006
19007   /* MIPS III */
19008   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
19009   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
19010   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
19011   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19012   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19013   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
19014   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
19015   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
19016   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
19017   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19018   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19019   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19020   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19021   /* ST Microelectronics Loongson 2E and 2F cores */
19022   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19023   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19024
19025   /* MIPS IV */
19026   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19027   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19028   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19029   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19030   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19031   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19032   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19033   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19034   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19035   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19036   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19037   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19038   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19039   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19040   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19041
19042   /* MIPS 32 */
19043   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19044   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19045   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19046   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19047
19048   /* MIPS 32 Release 2 */
19049   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19050   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19051   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19052   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19053   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19054   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19055   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19056   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19057   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19058                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19059   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19060                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19061   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19062   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19063   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19064   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19065   /* Deprecated forms of the above.  */
19066   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19067   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19068   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19069   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19070   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19071   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19072   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19073   /* Deprecated forms of the above.  */
19074   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19075   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19076   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19077   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19078   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19079   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19080   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19081   /* Deprecated forms of the above.  */
19082   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19083   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19084   /* 34Kn is a 34kc without DSP.  */
19085   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19086   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19087   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19088   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19089   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19090   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19091   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19092   /* Deprecated forms of the above.  */
19093   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19094   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19095   /* 1004K cores are multiprocessor versions of the 34K.  */
19096   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19097   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19098   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19099   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19100
19101   /* MIPS 64 */
19102   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19103   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19104   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19105   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19106
19107   /* Broadcom SB-1 CPU core */
19108   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19109   /* Broadcom SB-1A CPU core */
19110   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19111   
19112   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
19113
19114   /* MIPS 64 Release 2 */
19115
19116   /* Cavium Networks Octeon CPU core */
19117   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19118   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19119   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19120
19121   /* RMI Xlr */
19122   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19123
19124   /* Broadcom XLP.
19125      XLP is mostly like XLR, with the prominent exception that it is
19126      MIPS64R2 rather than MIPS64.  */
19127   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19128
19129   /* End marker */
19130   { NULL, 0, 0, 0, 0 }
19131 };
19132
19133
19134 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19135    with a final "000" replaced by "k".  Ignore case.
19136
19137    Note: this function is shared between GCC and GAS.  */
19138
19139 static bfd_boolean
19140 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19141 {
19142   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19143     given++, canonical++;
19144
19145   return ((*given == 0 && *canonical == 0)
19146           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19147 }
19148
19149
19150 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19151    CPU name.  We've traditionally allowed a lot of variation here.
19152
19153    Note: this function is shared between GCC and GAS.  */
19154
19155 static bfd_boolean
19156 mips_matching_cpu_name_p (const char *canonical, const char *given)
19157 {
19158   /* First see if the name matches exactly, or with a final "000"
19159      turned into "k".  */
19160   if (mips_strict_matching_cpu_name_p (canonical, given))
19161     return TRUE;
19162
19163   /* If not, try comparing based on numerical designation alone.
19164      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19165   if (TOLOWER (*given) == 'r')
19166     given++;
19167   if (!ISDIGIT (*given))
19168     return FALSE;
19169
19170   /* Skip over some well-known prefixes in the canonical name,
19171      hoping to find a number there too.  */
19172   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19173     canonical += 2;
19174   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19175     canonical += 2;
19176   else if (TOLOWER (canonical[0]) == 'r')
19177     canonical += 1;
19178
19179   return mips_strict_matching_cpu_name_p (canonical, given);
19180 }
19181
19182
19183 /* Parse an option that takes the name of a processor as its argument.
19184    OPTION is the name of the option and CPU_STRING is the argument.
19185    Return the corresponding processor enumeration if the CPU_STRING is
19186    recognized, otherwise report an error and return null.
19187
19188    A similar function exists in GCC.  */
19189
19190 static const struct mips_cpu_info *
19191 mips_parse_cpu (const char *option, const char *cpu_string)
19192 {
19193   const struct mips_cpu_info *p;
19194
19195   /* 'from-abi' selects the most compatible architecture for the given
19196      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19197      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19198      version.  Look first at the -mgp options, if given, otherwise base
19199      the choice on MIPS_DEFAULT_64BIT.
19200
19201      Treat NO_ABI like the EABIs.  One reason to do this is that the
19202      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19203      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19204      'mips64', just as we did in the days before 'from-abi'.  */
19205   if (strcasecmp (cpu_string, "from-abi") == 0)
19206     {
19207       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19208         return mips_cpu_info_from_isa (ISA_MIPS1);
19209
19210       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19211         return mips_cpu_info_from_isa (ISA_MIPS3);
19212
19213       if (file_mips_gp32 >= 0)
19214         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
19215
19216       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19217                                      ? ISA_MIPS3
19218                                      : ISA_MIPS1);
19219     }
19220
19221   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19222   if (strcasecmp (cpu_string, "default") == 0)
19223     return 0;
19224
19225   for (p = mips_cpu_info_table; p->name != 0; p++)
19226     if (mips_matching_cpu_name_p (p->name, cpu_string))
19227       return p;
19228
19229   as_bad (_("Bad value (%s) for %s"), cpu_string, option);
19230   return 0;
19231 }
19232
19233 /* Return the canonical processor information for ISA (a member of the
19234    ISA_MIPS* enumeration).  */
19235
19236 static const struct mips_cpu_info *
19237 mips_cpu_info_from_isa (int isa)
19238 {
19239   int i;
19240
19241   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19242     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19243         && isa == mips_cpu_info_table[i].isa)
19244       return (&mips_cpu_info_table[i]);
19245
19246   return NULL;
19247 }
19248
19249 static const struct mips_cpu_info *
19250 mips_cpu_info_from_arch (int arch)
19251 {
19252   int i;
19253
19254   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19255     if (arch == mips_cpu_info_table[i].cpu)
19256       return (&mips_cpu_info_table[i]);
19257
19258   return NULL;
19259 }
19260 \f
19261 static void
19262 show (FILE *stream, const char *string, int *col_p, int *first_p)
19263 {
19264   if (*first_p)
19265     {
19266       fprintf (stream, "%24s", "");
19267       *col_p = 24;
19268     }
19269   else
19270     {
19271       fprintf (stream, ", ");
19272       *col_p += 2;
19273     }
19274
19275   if (*col_p + strlen (string) > 72)
19276     {
19277       fprintf (stream, "\n%24s", "");
19278       *col_p = 24;
19279     }
19280
19281   fprintf (stream, "%s", string);
19282   *col_p += strlen (string);
19283
19284   *first_p = 0;
19285 }
19286
19287 void
19288 md_show_usage (FILE *stream)
19289 {
19290   int column, first;
19291   size_t i;
19292
19293   fprintf (stream, _("\
19294 MIPS options:\n\
19295 -EB                     generate big endian output\n\
19296 -EL                     generate little endian output\n\
19297 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19298 -G NUM                  allow referencing objects up to NUM bytes\n\
19299                         implicitly with the gp register [default 8]\n"));
19300   fprintf (stream, _("\
19301 -mips1                  generate MIPS ISA I instructions\n\
19302 -mips2                  generate MIPS ISA II instructions\n\
19303 -mips3                  generate MIPS ISA III instructions\n\
19304 -mips4                  generate MIPS ISA IV instructions\n\
19305 -mips5                  generate MIPS ISA V instructions\n\
19306 -mips32                 generate MIPS32 ISA instructions\n\
19307 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19308 -mips64                 generate MIPS64 ISA instructions\n\
19309 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19310 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19311
19312   first = 1;
19313
19314   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19315     show (stream, mips_cpu_info_table[i].name, &column, &first);
19316   show (stream, "from-abi", &column, &first);
19317   fputc ('\n', stream);
19318
19319   fprintf (stream, _("\
19320 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19321 -no-mCPU                don't generate code specific to CPU.\n\
19322                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19323
19324   first = 1;
19325
19326   show (stream, "3900", &column, &first);
19327   show (stream, "4010", &column, &first);
19328   show (stream, "4100", &column, &first);
19329   show (stream, "4650", &column, &first);
19330   fputc ('\n', stream);
19331
19332   fprintf (stream, _("\
19333 -mips16                 generate mips16 instructions\n\
19334 -no-mips16              do not generate mips16 instructions\n"));
19335   fprintf (stream, _("\
19336 -mmicromips             generate microMIPS instructions\n\
19337 -mno-micromips          do not generate microMIPS instructions\n"));
19338   fprintf (stream, _("\
19339 -msmartmips             generate smartmips instructions\n\
19340 -mno-smartmips          do not generate smartmips instructions\n"));  
19341   fprintf (stream, _("\
19342 -mdsp                   generate DSP instructions\n\
19343 -mno-dsp                do not generate DSP instructions\n"));
19344   fprintf (stream, _("\
19345 -mdspr2                 generate DSP R2 instructions\n\
19346 -mno-dspr2              do not generate DSP R2 instructions\n"));
19347   fprintf (stream, _("\
19348 -mmt                    generate MT instructions\n\
19349 -mno-mt                 do not generate MT instructions\n"));
19350   fprintf (stream, _("\
19351 -mmcu                   generate MCU instructions\n\
19352 -mno-mcu                do not generate MCU instructions\n"));
19353   fprintf (stream, _("\
19354 -mvirt                  generate Virtualization instructions\n\
19355 -mno-virt               do not generate Virtualization instructions\n"));
19356   fprintf (stream, _("\
19357 -minsn32                only generate 32-bit microMIPS instructions\n\
19358 -mno-insn32             generate all microMIPS instructions\n"));
19359   fprintf (stream, _("\
19360 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19361 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19362 -mfix-vr4120            work around certain VR4120 errata\n\
19363 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19364 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19365 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19366 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19367 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19368 -msym32                 assume all symbols have 32-bit values\n\
19369 -O0                     remove unneeded NOPs, do not swap branches\n\
19370 -O                      remove unneeded NOPs and swap branches\n\
19371 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19372 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19373   fprintf (stream, _("\
19374 -mhard-float            allow floating-point instructions\n\
19375 -msoft-float            do not allow floating-point instructions\n\
19376 -msingle-float          only allow 32-bit floating-point operations\n\
19377 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19378 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19379 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19380 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19381
19382   first = 1;
19383
19384   show (stream, "legacy", &column, &first);
19385   show (stream, "2008", &column, &first);
19386
19387   fputc ('\n', stream);
19388
19389   fprintf (stream, _("\
19390 -KPIC, -call_shared     generate SVR4 position independent code\n\
19391 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19392 -mvxworks-pic           generate VxWorks position independent code\n\
19393 -non_shared             do not generate code that can operate with DSOs\n\
19394 -xgot                   assume a 32 bit GOT\n\
19395 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19396 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19397                         position dependent (non shared) code\n\
19398 -mabi=ABI               create ABI conformant object file for:\n"));
19399
19400   first = 1;
19401
19402   show (stream, "32", &column, &first);
19403   show (stream, "o64", &column, &first);
19404   show (stream, "n32", &column, &first);
19405   show (stream, "64", &column, &first);
19406   show (stream, "eabi", &column, &first);
19407
19408   fputc ('\n', stream);
19409
19410   fprintf (stream, _("\
19411 -32                     create o32 ABI object file (default)\n\
19412 -n32                    create n32 ABI object file\n\
19413 -64                     create 64 ABI object file\n"));
19414 }
19415
19416 #ifdef TE_IRIX
19417 enum dwarf2_format
19418 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19419 {
19420   if (HAVE_64BIT_SYMBOLS)
19421     return dwarf2_format_64bit_irix;
19422   else
19423     return dwarf2_format_32bit;
19424 }
19425 #endif
19426
19427 int
19428 mips_dwarf2_addr_size (void)
19429 {
19430   if (HAVE_64BIT_OBJECTS)
19431     return 8;
19432   else
19433     return 4;
19434 }
19435
19436 /* Standard calling conventions leave the CFA at SP on entry.  */
19437 void
19438 mips_cfi_frame_initial_instructions (void)
19439 {
19440   cfi_add_CFA_def_cfa_register (SP);
19441 }
19442
19443 int
19444 tc_mips_regname_to_dw2regnum (char *regname)
19445 {
19446   unsigned int regnum = -1;
19447   unsigned int reg;
19448
19449   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19450     regnum = reg;
19451
19452   return regnum;
19453 }