bfd/
[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 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92
93 #define ZERO 0
94 #define ATREG 1
95 #define S0  16
96 #define S7  23
97 #define TREG 24
98 #define PIC_CALL_REG 25
99 #define KT0 26
100 #define KT1 27
101 #define GP  28
102 #define SP  29
103 #define FP  30
104 #define RA  31
105
106 #define ILLEGAL_REG (32)
107
108 #define AT  mips_opts.at
109
110 extern int target_big_endian;
111
112 /* The name of the readonly data section.  */
113 #define RDATA_SECTION_NAME ".rodata"
114
115 /* Ways in which an instruction can be "appended" to the output.  */
116 enum append_method {
117   /* Just add it normally.  */
118   APPEND_ADD,
119
120   /* Add it normally and then add a nop.  */
121   APPEND_ADD_WITH_NOP,
122
123   /* Turn an instruction with a delay slot into a "compact" version.  */
124   APPEND_ADD_COMPACT,
125
126   /* Insert the instruction before the last one.  */
127   APPEND_SWAP
128 };
129
130 /* Information about an instruction, including its format, operands
131    and fixups.  */
132 struct mips_cl_insn
133 {
134   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
135   const struct mips_opcode *insn_mo;
136
137   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
138      a copy of INSN_MO->match with the operands filled in.  If we have
139      decided to use an extended MIPS16 instruction, this includes the
140      extension.  */
141   unsigned long insn_opcode;
142
143   /* The frag that contains the instruction.  */
144   struct frag *frag;
145
146   /* The offset into FRAG of the first instruction byte.  */
147   long where;
148
149   /* The relocs associated with the instruction, if any.  */
150   fixS *fixp[3];
151
152   /* True if this entry cannot be moved from its current position.  */
153   unsigned int fixed_p : 1;
154
155   /* True if this instruction occurred in a .set noreorder block.  */
156   unsigned int noreorder_p : 1;
157
158   /* True for mips16 instructions that jump to an absolute address.  */
159   unsigned int mips16_absolute_jump_p : 1;
160
161   /* True if this instruction is complete.  */
162   unsigned int complete_p : 1;
163
164   /* True if this instruction is cleared from history by unconditional
165      branch.  */
166   unsigned int cleared_p : 1;
167 };
168
169 /* The ABI to use.  */
170 enum mips_abi_level
171 {
172   NO_ABI = 0,
173   O32_ABI,
174   O64_ABI,
175   N32_ABI,
176   N64_ABI,
177   EABI_ABI
178 };
179
180 /* MIPS ABI we are using for this output file.  */
181 static enum mips_abi_level mips_abi = NO_ABI;
182
183 /* Whether or not we have code that can call pic code.  */
184 int mips_abicalls = FALSE;
185
186 /* Whether or not we have code which can be put into a shared
187    library.  */
188 static bfd_boolean mips_in_shared = TRUE;
189
190 /* This is the set of options which may be modified by the .set
191    pseudo-op.  We use a struct so that .set push and .set pop are more
192    reliable.  */
193
194 struct mips_set_options
195 {
196   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
197      if it has not been initialized.  Changed by `.set mipsN', and the
198      -mipsN command line option, and the default CPU.  */
199   int isa;
200   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
201      <asename>', by command line options, and based on the default
202      architecture.  */
203   int ase;
204   /* Whether we are assembling for the mips16 processor.  0 if we are
205      not, 1 if we are, and -1 if the value has not been initialized.
206      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
207      -nomips16 command line options, and the default CPU.  */
208   int mips16;
209   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
210      1 if we are, and -1 if the value has not been initialized.  Changed
211      by `.set micromips' and `.set nomicromips', and the -mmicromips
212      and -mno-micromips command line options, and the default CPU.  */
213   int micromips;
214   /* Non-zero if we should not reorder instructions.  Changed by `.set
215      reorder' and `.set noreorder'.  */
216   int noreorder;
217   /* Non-zero if we should not permit the register designated "assembler
218      temporary" to be used in instructions.  The value is the register
219      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
220      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
221   unsigned int at;
222   /* Non-zero if we should warn when a macro instruction expands into
223      more than one machine instruction.  Changed by `.set nomacro' and
224      `.set macro'.  */
225   int warn_about_macros;
226   /* Non-zero if we should not move instructions.  Changed by `.set
227      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
228   int nomove;
229   /* Non-zero if we should not optimize branches by moving the target
230      of the branch into the delay slot.  Actually, we don't perform
231      this optimization anyhow.  Changed by `.set bopt' and `.set
232      nobopt'.  */
233   int nobopt;
234   /* Non-zero if we should not autoextend mips16 instructions.
235      Changed by `.set autoextend' and `.set noautoextend'.  */
236   int noautoextend;
237   /* True if we should only emit 32-bit microMIPS instructions.
238      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
239      and -mno-insn32 command line options.  */
240   bfd_boolean insn32;
241   /* Restrict general purpose registers and floating point registers
242      to 32 bit.  This is initially determined when -mgp32 or -mfp32
243      is passed but can changed if the assembler code uses .set mipsN.  */
244   int gp32;
245   int fp32;
246   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
247      command line option, and the default CPU.  */
248   int arch;
249   /* True if ".set sym32" is in effect.  */
250   bfd_boolean sym32;
251   /* True if floating-point operations are not allowed.  Changed by .set
252      softfloat or .set hardfloat, by command line options -msoft-float or
253      -mhard-float.  The default is false.  */
254   bfd_boolean soft_float;
255
256   /* True if only single-precision floating-point operations are allowed.
257      Changed by .set singlefloat or .set doublefloat, command-line options
258      -msingle-float or -mdouble-float.  The default is false.  */
259   bfd_boolean single_float;
260 };
261
262 /* This is the struct we use to hold the current set of options.  Note
263    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
264    -1 to indicate that they have not been initialized.  */
265
266 /* True if -mgp32 was passed.  */
267 static int file_mips_gp32 = -1;
268
269 /* True if -mfp32 was passed.  */
270 static int file_mips_fp32 = -1;
271
272 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
273 static int file_mips_soft_float = 0;
274
275 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
276 static int file_mips_single_float = 0;
277
278 /* True if -mnan=2008, false if -mnan=legacy.  */
279 static bfd_boolean mips_flag_nan2008 = FALSE;
280
281 static struct mips_set_options mips_opts =
282 {
283   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
284   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
285   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
286   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
287   /* soft_float */ FALSE, /* single_float */ FALSE
288 };
289
290 /* The set of ASEs that were selected on the command line, either
291    explicitly via ASE options or implicitly through things like -march.  */
292 static unsigned int file_ase;
293
294 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
295 static unsigned int file_ase_explicit;
296
297 /* These variables are filled in with the masks of registers used.
298    The object format code reads them and puts them in the appropriate
299    place.  */
300 unsigned long mips_gprmask;
301 unsigned long mips_cprmask[4];
302
303 /* MIPS ISA we are using for this output file.  */
304 static int file_mips_isa = ISA_UNKNOWN;
305
306 /* True if any MIPS16 code was produced.  */
307 static int file_ase_mips16;
308
309 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
310                               || mips_opts.isa == ISA_MIPS32R2          \
311                               || mips_opts.isa == ISA_MIPS64            \
312                               || mips_opts.isa == ISA_MIPS64R2)
313
314 /* True if any microMIPS code was produced.  */
315 static int file_ase_micromips;
316
317 /* True if we want to create R_MIPS_JALR for jalr $25.  */
318 #ifdef TE_IRIX
319 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
320 #else
321 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
322    because there's no place for any addend, the only acceptable
323    expression is a bare symbol.  */
324 #define MIPS_JALR_HINT_P(EXPR) \
325   (!HAVE_IN_PLACE_ADDENDS \
326    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
327 #endif
328
329 /* The argument of the -march= flag.  The architecture we are assembling.  */
330 static int file_mips_arch = CPU_UNKNOWN;
331 static const char *mips_arch_string;
332
333 /* The argument of the -mtune= flag.  The architecture for which we
334    are optimizing.  */
335 static int mips_tune = CPU_UNKNOWN;
336 static const char *mips_tune_string;
337
338 /* True when generating 32-bit code for a 64-bit processor.  */
339 static int mips_32bitmode = 0;
340
341 /* True if the given ABI requires 32-bit registers.  */
342 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
343
344 /* Likewise 64-bit registers.  */
345 #define ABI_NEEDS_64BIT_REGS(ABI)       \
346   ((ABI) == N32_ABI                     \
347    || (ABI) == N64_ABI                  \
348    || (ABI) == O64_ABI)
349
350 /*  Return true if ISA supports 64 bit wide gp registers.  */
351 #define ISA_HAS_64BIT_REGS(ISA)         \
352   ((ISA) == ISA_MIPS3                   \
353    || (ISA) == ISA_MIPS4                \
354    || (ISA) == ISA_MIPS5                \
355    || (ISA) == ISA_MIPS64               \
356    || (ISA) == ISA_MIPS64R2)
357
358 /*  Return true if ISA supports 64 bit wide float registers.  */
359 #define ISA_HAS_64BIT_FPRS(ISA)         \
360   ((ISA) == ISA_MIPS3                   \
361    || (ISA) == ISA_MIPS4                \
362    || (ISA) == ISA_MIPS5                \
363    || (ISA) == ISA_MIPS32R2             \
364    || (ISA) == ISA_MIPS64               \
365    || (ISA) == ISA_MIPS64R2)
366
367 /* Return true if ISA supports 64-bit right rotate (dror et al.)
368    instructions.  */
369 #define ISA_HAS_DROR(ISA)               \
370   ((ISA) == ISA_MIPS64R2                \
371    || (mips_opts.micromips              \
372        && ISA_HAS_64BIT_REGS (ISA))     \
373    )
374
375 /* Return true if ISA supports 32-bit right rotate (ror et al.)
376    instructions.  */
377 #define ISA_HAS_ROR(ISA)                \
378   ((ISA) == ISA_MIPS32R2                \
379    || (ISA) == ISA_MIPS64R2             \
380    || (mips_opts.ase & ASE_SMARTMIPS)   \
381    || mips_opts.micromips               \
382    )
383
384 /* Return true if ISA supports single-precision floats in odd registers.  */
385 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
386   ((ISA) == ISA_MIPS32                  \
387    || (ISA) == ISA_MIPS32R2             \
388    || (ISA) == ISA_MIPS64               \
389    || (ISA) == ISA_MIPS64R2)
390
391 /* Return true if ISA supports move to/from high part of a 64-bit
392    floating-point register. */
393 #define ISA_HAS_MXHC1(ISA)              \
394   ((ISA) == ISA_MIPS32R2                \
395    || (ISA) == ISA_MIPS64R2)
396
397 #define HAVE_32BIT_GPRS                            \
398     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
399
400 #define HAVE_32BIT_FPRS                            \
401     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
402
403 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
404 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
405
406 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
407
408 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
409
410 /* True if relocations are stored in-place.  */
411 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
412
413 /* The ABI-derived address size.  */
414 #define HAVE_64BIT_ADDRESSES \
415   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
416 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
417
418 /* The size of symbolic constants (i.e., expressions of the form
419    "SYMBOL" or "SYMBOL + OFFSET").  */
420 #define HAVE_32BIT_SYMBOLS \
421   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
422 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
423
424 /* Addresses are loaded in different ways, depending on the address size
425    in use.  The n32 ABI Documentation also mandates the use of additions
426    with overflow checking, but existing implementations don't follow it.  */
427 #define ADDRESS_ADD_INSN                                                \
428    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
429
430 #define ADDRESS_ADDI_INSN                                               \
431    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
432
433 #define ADDRESS_LOAD_INSN                                               \
434    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
435
436 #define ADDRESS_STORE_INSN                                              \
437    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
438
439 /* Return true if the given CPU supports the MIPS16 ASE.  */
440 #define CPU_HAS_MIPS16(cpu)                                             \
441    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
442     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
443
444 /* Return true if the given CPU supports the microMIPS ASE.  */
445 #define CPU_HAS_MICROMIPS(cpu)  0
446
447 /* True if CPU has a dror instruction.  */
448 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
449
450 /* True if CPU has a ror instruction.  */
451 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
452
453 /* True if CPU is in the Octeon family */
454 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
455
456 /* True if CPU has seq/sne and seqi/snei instructions.  */
457 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
458
459 /* True, if CPU has support for ldc1 and sdc1. */
460 #define CPU_HAS_LDC1_SDC1(CPU)  \
461    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
462
463 /* True if mflo and mfhi can be immediately followed by instructions
464    which write to the HI and LO registers.
465
466    According to MIPS specifications, MIPS ISAs I, II, and III need
467    (at least) two instructions between the reads of HI/LO and
468    instructions which write them, and later ISAs do not.  Contradicting
469    the MIPS specifications, some MIPS IV processor user manuals (e.g.
470    the UM for the NEC Vr5000) document needing the instructions between
471    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
472    MIPS64 and later ISAs to have the interlocks, plus any specific
473    earlier-ISA CPUs for which CPU documentation declares that the
474    instructions are really interlocked.  */
475 #define hilo_interlocks \
476   (mips_opts.isa == ISA_MIPS32                        \
477    || mips_opts.isa == ISA_MIPS32R2                   \
478    || mips_opts.isa == ISA_MIPS64                     \
479    || mips_opts.isa == ISA_MIPS64R2                   \
480    || mips_opts.arch == CPU_R4010                     \
481    || mips_opts.arch == CPU_R5900                     \
482    || mips_opts.arch == CPU_R10000                    \
483    || mips_opts.arch == CPU_R12000                    \
484    || mips_opts.arch == CPU_R14000                    \
485    || mips_opts.arch == CPU_R16000                    \
486    || mips_opts.arch == CPU_RM7000                    \
487    || mips_opts.arch == CPU_VR5500                    \
488    || mips_opts.micromips                             \
489    )
490
491 /* Whether the processor uses hardware interlocks to protect reads
492    from the GPRs after they are loaded from memory, and thus does not
493    require nops to be inserted.  This applies to instructions marked
494    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
495    level I and microMIPS mode instructions are always interlocked.  */
496 #define gpr_interlocks                                \
497   (mips_opts.isa != ISA_MIPS1                         \
498    || mips_opts.arch == CPU_R3900                     \
499    || mips_opts.arch == CPU_R5900                     \
500    || mips_opts.micromips                             \
501    )
502
503 /* Whether the processor uses hardware interlocks to avoid delays
504    required by coprocessor instructions, and thus does not require
505    nops to be inserted.  This applies to instructions marked
506    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
507    between instructions marked INSN_WRITE_COND_CODE and ones marked
508    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
509    levels I, II, and III and microMIPS mode instructions are always
510    interlocked.  */
511 /* Itbl support may require additional care here.  */
512 #define cop_interlocks                                \
513   ((mips_opts.isa != ISA_MIPS1                        \
514     && mips_opts.isa != ISA_MIPS2                     \
515     && mips_opts.isa != ISA_MIPS3)                    \
516    || mips_opts.arch == CPU_R4300                     \
517    || mips_opts.micromips                             \
518    )
519
520 /* Whether the processor uses hardware interlocks to protect reads
521    from coprocessor registers after they are loaded from memory, and
522    thus does not require nops to be inserted.  This applies to
523    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
524    requires at MIPS ISA level I and microMIPS mode instructions are
525    always interlocked.  */
526 #define cop_mem_interlocks                            \
527   (mips_opts.isa != ISA_MIPS1                         \
528    || mips_opts.micromips                             \
529    )
530
531 /* Is this a mfhi or mflo instruction?  */
532 #define MF_HILO_INSN(PINFO) \
533   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
534
535 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
536    has been selected.  This implies, in particular, that addresses of text
537    labels have their LSB set.  */
538 #define HAVE_CODE_COMPRESSION                                           \
539   ((mips_opts.mips16 | mips_opts.micromips) != 0)
540
541 /* The minimum and maximum signed values that can be stored in a GPR.  */
542 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
543 #define GPR_SMIN (-GPR_SMAX - 1)
544
545 /* MIPS PIC level.  */
546
547 enum mips_pic_level mips_pic;
548
549 /* 1 if we should generate 32 bit offsets from the $gp register in
550    SVR4_PIC mode.  Currently has no meaning in other modes.  */
551 static int mips_big_got = 0;
552
553 /* 1 if trap instructions should used for overflow rather than break
554    instructions.  */
555 static int mips_trap = 0;
556
557 /* 1 if double width floating point constants should not be constructed
558    by assembling two single width halves into two single width floating
559    point registers which just happen to alias the double width destination
560    register.  On some architectures this aliasing can be disabled by a bit
561    in the status register, and the setting of this bit cannot be determined
562    automatically at assemble time.  */
563 static int mips_disable_float_construction;
564
565 /* Non-zero if any .set noreorder directives were used.  */
566
567 static int mips_any_noreorder;
568
569 /* Non-zero if nops should be inserted when the register referenced in
570    an mfhi/mflo instruction is read in the next two instructions.  */
571 static int mips_7000_hilo_fix;
572
573 /* The size of objects in the small data section.  */
574 static unsigned int g_switch_value = 8;
575 /* Whether the -G option was used.  */
576 static int g_switch_seen = 0;
577
578 #define N_RMASK 0xc4
579 #define N_VFP   0xd4
580
581 /* If we can determine in advance that GP optimization won't be
582    possible, we can skip the relaxation stuff that tries to produce
583    GP-relative references.  This makes delay slot optimization work
584    better.
585
586    This function can only provide a guess, but it seems to work for
587    gcc output.  It needs to guess right for gcc, otherwise gcc
588    will put what it thinks is a GP-relative instruction in a branch
589    delay slot.
590
591    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
592    fixed it for the non-PIC mode.  KR 95/04/07  */
593 static int nopic_need_relax (symbolS *, int);
594
595 /* handle of the OPCODE hash table */
596 static struct hash_control *op_hash = NULL;
597
598 /* The opcode hash table we use for the mips16.  */
599 static struct hash_control *mips16_op_hash = NULL;
600
601 /* The opcode hash table we use for the microMIPS ASE.  */
602 static struct hash_control *micromips_op_hash = NULL;
603
604 /* This array holds the chars that always start a comment.  If the
605     pre-processor is disabled, these aren't very useful */
606 const char comment_chars[] = "#";
607
608 /* This array holds the chars that only start a comment at the beginning of
609    a line.  If the line seems to have the form '# 123 filename'
610    .line and .file directives will appear in the pre-processed output */
611 /* Note that input_file.c hand checks for '#' at the beginning of the
612    first line of the input file.  This is because the compiler outputs
613    #NO_APP at the beginning of its output.  */
614 /* Also note that C style comments are always supported.  */
615 const char line_comment_chars[] = "#";
616
617 /* This array holds machine specific line separator characters.  */
618 const char line_separator_chars[] = ";";
619
620 /* Chars that can be used to separate mant from exp in floating point nums */
621 const char EXP_CHARS[] = "eE";
622
623 /* Chars that mean this number is a floating point constant */
624 /* As in 0f12.456 */
625 /* or    0d1.2345e12 */
626 const char FLT_CHARS[] = "rRsSfFdDxXpP";
627
628 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
629    changed in read.c .  Ideally it shouldn't have to know about it at all,
630    but nothing is ideal around here.
631  */
632
633 /* Types of printf format used for instruction-related error messages.
634    "I" means int ("%d") and "S" means string ("%s"). */
635 enum mips_insn_error_format {
636   ERR_FMT_PLAIN,
637   ERR_FMT_I,
638   ERR_FMT_SS,
639 };
640
641 /* Information about an error that was found while assembling the current
642    instruction.  */
643 struct mips_insn_error {
644   /* We sometimes need to match an instruction against more than one
645      opcode table entry.  Errors found during this matching are reported
646      against a particular syntactic argument rather than against the
647      instruction as a whole.  We grade these messages so that errors
648      against argument N have a greater priority than an error against
649      any argument < N, since the former implies that arguments up to N
650      were acceptable and that the opcode entry was therefore a closer match.
651      If several matches report an error against the same argument,
652      we only use that error if it is the same in all cases.
653
654      min_argnum is the minimum argument number for which an error message
655      should be accepted.  It is 0 if MSG is against the instruction as
656      a whole.  */
657   int min_argnum;
658
659   /* The printf()-style message, including its format and arguments.  */
660   enum mips_insn_error_format format;
661   const char *msg;
662   union {
663     int i;
664     const char *ss[2];
665   } u;
666 };
667
668 /* The error that should be reported for the current instruction.  */
669 static struct mips_insn_error insn_error;
670
671 static int auto_align = 1;
672
673 /* When outputting SVR4 PIC code, the assembler needs to know the
674    offset in the stack frame from which to restore the $gp register.
675    This is set by the .cprestore pseudo-op, and saved in this
676    variable.  */
677 static offsetT mips_cprestore_offset = -1;
678
679 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
680    more optimizations, it can use a register value instead of a memory-saved
681    offset and even an other register than $gp as global pointer.  */
682 static offsetT mips_cpreturn_offset = -1;
683 static int mips_cpreturn_register = -1;
684 static int mips_gp_register = GP;
685 static int mips_gprel_offset = 0;
686
687 /* Whether mips_cprestore_offset has been set in the current function
688    (or whether it has already been warned about, if not).  */
689 static int mips_cprestore_valid = 0;
690
691 /* This is the register which holds the stack frame, as set by the
692    .frame pseudo-op.  This is needed to implement .cprestore.  */
693 static int mips_frame_reg = SP;
694
695 /* Whether mips_frame_reg has been set in the current function
696    (or whether it has already been warned about, if not).  */
697 static int mips_frame_reg_valid = 0;
698
699 /* To output NOP instructions correctly, we need to keep information
700    about the previous two instructions.  */
701
702 /* Whether we are optimizing.  The default value of 2 means to remove
703    unneeded NOPs and swap branch instructions when possible.  A value
704    of 1 means to not swap branches.  A value of 0 means to always
705    insert NOPs.  */
706 static int mips_optimize = 2;
707
708 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
709    equivalent to seeing no -g option at all.  */
710 static int mips_debug = 0;
711
712 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
713 #define MAX_VR4130_NOPS 4
714
715 /* The maximum number of NOPs needed to fill delay slots.  */
716 #define MAX_DELAY_NOPS 2
717
718 /* The maximum number of NOPs needed for any purpose.  */
719 #define MAX_NOPS 4
720
721 /* A list of previous instructions, with index 0 being the most recent.
722    We need to look back MAX_NOPS instructions when filling delay slots
723    or working around processor errata.  We need to look back one
724    instruction further if we're thinking about using history[0] to
725    fill a branch delay slot.  */
726 static struct mips_cl_insn history[1 + MAX_NOPS];
727
728 /* Arrays of operands for each instruction.  */
729 #define MAX_OPERANDS 6
730 struct mips_operand_array {
731   const struct mips_operand *operand[MAX_OPERANDS];
732 };
733 static struct mips_operand_array *mips_operands;
734 static struct mips_operand_array *mips16_operands;
735 static struct mips_operand_array *micromips_operands;
736
737 /* Nop instructions used by emit_nop.  */
738 static struct mips_cl_insn nop_insn;
739 static struct mips_cl_insn mips16_nop_insn;
740 static struct mips_cl_insn micromips_nop16_insn;
741 static struct mips_cl_insn micromips_nop32_insn;
742
743 /* The appropriate nop for the current mode.  */
744 #define NOP_INSN (mips_opts.mips16                                      \
745                   ? &mips16_nop_insn                                    \
746                   : (mips_opts.micromips                                \
747                      ? (mips_opts.insn32                                \
748                         ? &micromips_nop32_insn                         \
749                         : &micromips_nop16_insn)                        \
750                      : &nop_insn))
751
752 /* The size of NOP_INSN in bytes.  */
753 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
754                         || (mips_opts.micromips && !mips_opts.insn32))  \
755                        ? 2 : 4)
756
757 /* If this is set, it points to a frag holding nop instructions which
758    were inserted before the start of a noreorder section.  If those
759    nops turn out to be unnecessary, the size of the frag can be
760    decreased.  */
761 static fragS *prev_nop_frag;
762
763 /* The number of nop instructions we created in prev_nop_frag.  */
764 static int prev_nop_frag_holds;
765
766 /* The number of nop instructions that we know we need in
767    prev_nop_frag.  */
768 static int prev_nop_frag_required;
769
770 /* The number of instructions we've seen since prev_nop_frag.  */
771 static int prev_nop_frag_since;
772
773 /* Relocations against symbols are sometimes done in two parts, with a HI
774    relocation and a LO relocation.  Each relocation has only 16 bits of
775    space to store an addend.  This means that in order for the linker to
776    handle carries correctly, it must be able to locate both the HI and
777    the LO relocation.  This means that the relocations must appear in
778    order in the relocation table.
779
780    In order to implement this, we keep track of each unmatched HI
781    relocation.  We then sort them so that they immediately precede the
782    corresponding LO relocation.  */
783
784 struct mips_hi_fixup
785 {
786   /* Next HI fixup.  */
787   struct mips_hi_fixup *next;
788   /* This fixup.  */
789   fixS *fixp;
790   /* The section this fixup is in.  */
791   segT seg;
792 };
793
794 /* The list of unmatched HI relocs.  */
795
796 static struct mips_hi_fixup *mips_hi_fixup_list;
797
798 /* The frag containing the last explicit relocation operator.
799    Null if explicit relocations have not been used.  */
800
801 static fragS *prev_reloc_op_frag;
802
803 /* Map mips16 register numbers to normal MIPS register numbers.  */
804
805 static const unsigned int mips16_to_32_reg_map[] =
806 {
807   16, 17, 2, 3, 4, 5, 6, 7
808 };
809
810 /* Map microMIPS register numbers to normal MIPS register numbers.  */
811
812 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
813
814 /* The microMIPS registers with type h.  */
815 static const unsigned int micromips_to_32_reg_h_map1[] =
816 {
817   5, 5, 6, 4, 4, 4, 4, 4
818 };
819 static const unsigned int micromips_to_32_reg_h_map2[] =
820 {
821   6, 7, 7, 21, 22, 5, 6, 7
822 };
823
824 /* The microMIPS registers with type m.  */
825 static const unsigned int micromips_to_32_reg_m_map[] =
826 {
827   0, 17, 2, 3, 16, 18, 19, 20
828 };
829
830 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
831
832 /* Classifies the kind of instructions we're interested in when
833    implementing -mfix-vr4120.  */
834 enum fix_vr4120_class
835 {
836   FIX_VR4120_MACC,
837   FIX_VR4120_DMACC,
838   FIX_VR4120_MULT,
839   FIX_VR4120_DMULT,
840   FIX_VR4120_DIV,
841   FIX_VR4120_MTHILO,
842   NUM_FIX_VR4120_CLASSES
843 };
844
845 /* ...likewise -mfix-loongson2f-jump.  */
846 static bfd_boolean mips_fix_loongson2f_jump;
847
848 /* ...likewise -mfix-loongson2f-nop.  */
849 static bfd_boolean mips_fix_loongson2f_nop;
850
851 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
852 static bfd_boolean mips_fix_loongson2f;
853
854 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
855    there must be at least one other instruction between an instruction
856    of type X and an instruction of type Y.  */
857 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
858
859 /* True if -mfix-vr4120 is in force.  */
860 static int mips_fix_vr4120;
861
862 /* ...likewise -mfix-vr4130.  */
863 static int mips_fix_vr4130;
864
865 /* ...likewise -mfix-24k.  */
866 static int mips_fix_24k;
867
868 /* ...likewise -mfix-rm7000  */
869 static int mips_fix_rm7000;
870
871 /* ...likewise -mfix-cn63xxp1 */
872 static bfd_boolean mips_fix_cn63xxp1;
873
874 /* We don't relax branches by default, since this causes us to expand
875    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
876    fail to compute the offset before expanding the macro to the most
877    efficient expansion.  */
878
879 static int mips_relax_branch;
880 \f
881 /* The expansion of many macros depends on the type of symbol that
882    they refer to.  For example, when generating position-dependent code,
883    a macro that refers to a symbol may have two different expansions,
884    one which uses GP-relative addresses and one which uses absolute
885    addresses.  When generating SVR4-style PIC, a macro may have
886    different expansions for local and global symbols.
887
888    We handle these situations by generating both sequences and putting
889    them in variant frags.  In position-dependent code, the first sequence
890    will be the GP-relative one and the second sequence will be the
891    absolute one.  In SVR4 PIC, the first sequence will be for global
892    symbols and the second will be for local symbols.
893
894    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
895    SECOND are the lengths of the two sequences in bytes.  These fields
896    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
897    the subtype has the following flags:
898
899    RELAX_USE_SECOND
900         Set if it has been decided that we should use the second
901         sequence instead of the first.
902
903    RELAX_SECOND_LONGER
904         Set in the first variant frag if the macro's second implementation
905         is longer than its first.  This refers to the macro as a whole,
906         not an individual relaxation.
907
908    RELAX_NOMACRO
909         Set in the first variant frag if the macro appeared in a .set nomacro
910         block and if one alternative requires a warning but the other does not.
911
912    RELAX_DELAY_SLOT
913         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
914         delay slot.
915
916    RELAX_DELAY_SLOT_16BIT
917         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
918         16-bit instruction.
919
920    RELAX_DELAY_SLOT_SIZE_FIRST
921         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
922         the macro is of the wrong size for the branch delay slot.
923
924    RELAX_DELAY_SLOT_SIZE_SECOND
925         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
926         the macro is of the wrong size for the branch delay slot.
927
928    The frag's "opcode" points to the first fixup for relaxable code.
929
930    Relaxable macros are generated using a sequence such as:
931
932       relax_start (SYMBOL);
933       ... generate first expansion ...
934       relax_switch ();
935       ... generate second expansion ...
936       relax_end ();
937
938    The code and fixups for the unwanted alternative are discarded
939    by md_convert_frag.  */
940 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
941
942 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
943 #define RELAX_SECOND(X) ((X) & 0xff)
944 #define RELAX_USE_SECOND 0x10000
945 #define RELAX_SECOND_LONGER 0x20000
946 #define RELAX_NOMACRO 0x40000
947 #define RELAX_DELAY_SLOT 0x80000
948 #define RELAX_DELAY_SLOT_16BIT 0x100000
949 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
950 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
951
952 /* Branch without likely bit.  If label is out of range, we turn:
953
954         beq reg1, reg2, label
955         delay slot
956
957    into
958
959         bne reg1, reg2, 0f
960         nop
961         j label
962      0: delay slot
963
964    with the following opcode replacements:
965
966         beq <-> bne
967         blez <-> bgtz
968         bltz <-> bgez
969         bc1f <-> bc1t
970
971         bltzal <-> bgezal  (with jal label instead of j label)
972
973    Even though keeping the delay slot instruction in the delay slot of
974    the branch would be more efficient, it would be very tricky to do
975    correctly, because we'd have to introduce a variable frag *after*
976    the delay slot instruction, and expand that instead.  Let's do it
977    the easy way for now, even if the branch-not-taken case now costs
978    one additional instruction.  Out-of-range branches are not supposed
979    to be common, anyway.
980
981    Branch likely.  If label is out of range, we turn:
982
983         beql reg1, reg2, label
984         delay slot (annulled if branch not taken)
985
986    into
987
988         beql reg1, reg2, 1f
989         nop
990         beql $0, $0, 2f
991         nop
992      1: j[al] label
993         delay slot (executed only if branch taken)
994      2:
995
996    It would be possible to generate a shorter sequence by losing the
997    likely bit, generating something like:
998
999         bne reg1, reg2, 0f
1000         nop
1001         j[al] label
1002         delay slot (executed only if branch taken)
1003      0:
1004
1005         beql -> bne
1006         bnel -> beq
1007         blezl -> bgtz
1008         bgtzl -> blez
1009         bltzl -> bgez
1010         bgezl -> bltz
1011         bc1fl -> bc1t
1012         bc1tl -> bc1f
1013
1014         bltzall -> bgezal  (with jal label instead of j label)
1015         bgezall -> bltzal  (ditto)
1016
1017
1018    but it's not clear that it would actually improve performance.  */
1019 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1020   ((relax_substateT)                                            \
1021    (0xc0000000                                                  \
1022     | ((at) & 0x1f)                                             \
1023     | ((toofar) ? 0x20 : 0)                                     \
1024     | ((link) ? 0x40 : 0)                                       \
1025     | ((likely) ? 0x80 : 0)                                     \
1026     | ((uncond) ? 0x100 : 0)))
1027 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1028 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1029 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1030 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1031 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1032 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1033
1034 /* For mips16 code, we use an entirely different form of relaxation.
1035    mips16 supports two versions of most instructions which take
1036    immediate values: a small one which takes some small value, and a
1037    larger one which takes a 16 bit value.  Since branches also follow
1038    this pattern, relaxing these values is required.
1039
1040    We can assemble both mips16 and normal MIPS code in a single
1041    object.  Therefore, we need to support this type of relaxation at
1042    the same time that we support the relaxation described above.  We
1043    use the high bit of the subtype field to distinguish these cases.
1044
1045    The information we store for this type of relaxation is the
1046    argument code found in the opcode file for this relocation, whether
1047    the user explicitly requested a small or extended form, and whether
1048    the relocation is in a jump or jal delay slot.  That tells us the
1049    size of the value, and how it should be stored.  We also store
1050    whether the fragment is considered to be extended or not.  We also
1051    store whether this is known to be a branch to a different section,
1052    whether we have tried to relax this frag yet, and whether we have
1053    ever extended a PC relative fragment because of a shift count.  */
1054 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1055   (0x80000000                                                   \
1056    | ((type) & 0xff)                                            \
1057    | ((small) ? 0x100 : 0)                                      \
1058    | ((ext) ? 0x200 : 0)                                        \
1059    | ((dslot) ? 0x400 : 0)                                      \
1060    | ((jal_dslot) ? 0x800 : 0))
1061 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1062 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1063 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1064 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1065 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1066 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1067 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1068 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1069 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1070 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1071 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1072 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1073
1074 /* For microMIPS code, we use relaxation similar to one we use for
1075    MIPS16 code.  Some instructions that take immediate values support
1076    two encodings: a small one which takes some small value, and a
1077    larger one which takes a 16 bit value.  As some branches also follow
1078    this pattern, relaxing these values is required.
1079
1080    We can assemble both microMIPS and normal MIPS code in a single
1081    object.  Therefore, we need to support this type of relaxation at
1082    the same time that we support the relaxation described above.  We
1083    use one of the high bits of the subtype field to distinguish these
1084    cases.
1085
1086    The information we store for this type of relaxation is the argument
1087    code found in the opcode file for this relocation, the register
1088    selected as the assembler temporary, whether the branch is
1089    unconditional, whether it is compact, whether it stores the link
1090    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1091    branches to a sequence of instructions is enabled, and whether the
1092    displacement of a branch is too large to fit as an immediate argument
1093    of a 16-bit and a 32-bit branch, respectively.  */
1094 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1095                                relax32, toofar16, toofar32)     \
1096   (0x40000000                                                   \
1097    | ((type) & 0xff)                                            \
1098    | (((at) & 0x1f) << 8)                                       \
1099    | ((uncond) ? 0x2000 : 0)                                    \
1100    | ((compact) ? 0x4000 : 0)                                   \
1101    | ((link) ? 0x8000 : 0)                                      \
1102    | ((relax32) ? 0x10000 : 0)                                  \
1103    | ((toofar16) ? 0x20000 : 0)                                 \
1104    | ((toofar32) ? 0x40000 : 0))
1105 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1106 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1107 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1108 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1109 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1110 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1111 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1112
1113 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1114 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1115 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1116 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1117 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1118 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1119
1120 /* Sign-extend 16-bit value X.  */
1121 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1122
1123 /* Is the given value a sign-extended 32-bit value?  */
1124 #define IS_SEXT_32BIT_NUM(x)                                            \
1125   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1126    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1127
1128 /* Is the given value a sign-extended 16-bit value?  */
1129 #define IS_SEXT_16BIT_NUM(x)                                            \
1130   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1131    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1132
1133 /* Is the given value a sign-extended 12-bit value?  */
1134 #define IS_SEXT_12BIT_NUM(x)                                            \
1135   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1136
1137 /* Is the given value a sign-extended 9-bit value?  */
1138 #define IS_SEXT_9BIT_NUM(x)                                             \
1139   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1140
1141 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1142 #define IS_ZEXT_32BIT_NUM(x)                                            \
1143   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1144    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1145
1146 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1147    SHIFT places.  */
1148 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1149   (((STRUCT) >> (SHIFT)) & (MASK))
1150
1151 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1152 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1153   (!(MICROMIPS) \
1154    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1155    : EXTRACT_BITS ((INSN).insn_opcode, \
1156                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1157 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1158   EXTRACT_BITS ((INSN).insn_opcode, \
1159                 MIPS16OP_MASK_##FIELD, \
1160                 MIPS16OP_SH_##FIELD)
1161
1162 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1163 #define MIPS16_EXTEND (0xf000U << 16)
1164 \f
1165 /* Whether or not we are emitting a branch-likely macro.  */
1166 static bfd_boolean emit_branch_likely_macro = FALSE;
1167
1168 /* Global variables used when generating relaxable macros.  See the
1169    comment above RELAX_ENCODE for more details about how relaxation
1170    is used.  */
1171 static struct {
1172   /* 0 if we're not emitting a relaxable macro.
1173      1 if we're emitting the first of the two relaxation alternatives.
1174      2 if we're emitting the second alternative.  */
1175   int sequence;
1176
1177   /* The first relaxable fixup in the current frag.  (In other words,
1178      the first fixup that refers to relaxable code.)  */
1179   fixS *first_fixup;
1180
1181   /* sizes[0] says how many bytes of the first alternative are stored in
1182      the current frag.  Likewise sizes[1] for the second alternative.  */
1183   unsigned int sizes[2];
1184
1185   /* The symbol on which the choice of sequence depends.  */
1186   symbolS *symbol;
1187 } mips_relax;
1188 \f
1189 /* Global variables used to decide whether a macro needs a warning.  */
1190 static struct {
1191   /* True if the macro is in a branch delay slot.  */
1192   bfd_boolean delay_slot_p;
1193
1194   /* Set to the length in bytes required if the macro is in a delay slot
1195      that requires a specific length of instruction, otherwise zero.  */
1196   unsigned int delay_slot_length;
1197
1198   /* For relaxable macros, sizes[0] is the length of the first alternative
1199      in bytes and sizes[1] is the length of the second alternative.
1200      For non-relaxable macros, both elements give the length of the
1201      macro in bytes.  */
1202   unsigned int sizes[2];
1203
1204   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1205      instruction of the first alternative in bytes and first_insn_sizes[1]
1206      is the length of the first instruction of the second alternative.
1207      For non-relaxable macros, both elements give the length of the first
1208      instruction in bytes.
1209
1210      Set to zero if we haven't yet seen the first instruction.  */
1211   unsigned int first_insn_sizes[2];
1212
1213   /* For relaxable macros, insns[0] is the number of instructions for the
1214      first alternative and insns[1] is the number of instructions for the
1215      second alternative.
1216
1217      For non-relaxable macros, both elements give the number of
1218      instructions for the macro.  */
1219   unsigned int insns[2];
1220
1221   /* The first variant frag for this macro.  */
1222   fragS *first_frag;
1223 } mips_macro_warning;
1224 \f
1225 /* Prototypes for static functions.  */
1226
1227 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1228
1229 static void append_insn
1230   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1231    bfd_boolean expansionp);
1232 static void mips_no_prev_insn (void);
1233 static void macro_build (expressionS *, const char *, const char *, ...);
1234 static void mips16_macro_build
1235   (expressionS *, const char *, const char *, va_list *);
1236 static void load_register (int, expressionS *, int);
1237 static void macro_start (void);
1238 static void macro_end (void);
1239 static void macro (struct mips_cl_insn *ip, char *str);
1240 static void mips16_macro (struct mips_cl_insn * ip);
1241 static void mips_ip (char *str, struct mips_cl_insn * ip);
1242 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1243 static void mips16_immed
1244   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1245    unsigned int, unsigned long *);
1246 static size_t my_getSmallExpression
1247   (expressionS *, bfd_reloc_code_real_type *, char *);
1248 static void my_getExpression (expressionS *, char *);
1249 static void s_align (int);
1250 static void s_change_sec (int);
1251 static void s_change_section (int);
1252 static void s_cons (int);
1253 static void s_float_cons (int);
1254 static void s_mips_globl (int);
1255 static void s_option (int);
1256 static void s_mipsset (int);
1257 static void s_abicalls (int);
1258 static void s_cpload (int);
1259 static void s_cpsetup (int);
1260 static void s_cplocal (int);
1261 static void s_cprestore (int);
1262 static void s_cpreturn (int);
1263 static void s_dtprelword (int);
1264 static void s_dtpreldword (int);
1265 static void s_tprelword (int);
1266 static void s_tpreldword (int);
1267 static void s_gpvalue (int);
1268 static void s_gpword (int);
1269 static void s_gpdword (int);
1270 static void s_ehword (int);
1271 static void s_cpadd (int);
1272 static void s_insn (int);
1273 static void s_nan (int);
1274 static void md_obj_begin (void);
1275 static void md_obj_end (void);
1276 static void s_mips_ent (int);
1277 static void s_mips_end (int);
1278 static void s_mips_frame (int);
1279 static void s_mips_mask (int reg_type);
1280 static void s_mips_stab (int);
1281 static void s_mips_weakext (int);
1282 static void s_mips_file (int);
1283 static void s_mips_loc (int);
1284 static bfd_boolean pic_need_relax (symbolS *, asection *);
1285 static int relaxed_branch_length (fragS *, asection *, int);
1286 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1287 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1288
1289 /* Table and functions used to map between CPU/ISA names, and
1290    ISA levels, and CPU numbers.  */
1291
1292 struct mips_cpu_info
1293 {
1294   const char *name;           /* CPU or ISA name.  */
1295   int flags;                  /* MIPS_CPU_* flags.  */
1296   int ase;                    /* Set of ASEs implemented by the CPU.  */
1297   int isa;                    /* ISA level.  */
1298   int cpu;                    /* CPU number (default CPU if ISA).  */
1299 };
1300
1301 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1302
1303 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1304 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1305 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1306 \f
1307 /* Command-line options.  */
1308 const char *md_shortopts = "O::g::G:";
1309
1310 enum options
1311   {
1312     OPTION_MARCH = OPTION_MD_BASE,
1313     OPTION_MTUNE,
1314     OPTION_MIPS1,
1315     OPTION_MIPS2,
1316     OPTION_MIPS3,
1317     OPTION_MIPS4,
1318     OPTION_MIPS5,
1319     OPTION_MIPS32,
1320     OPTION_MIPS64,
1321     OPTION_MIPS32R2,
1322     OPTION_MIPS64R2,
1323     OPTION_MIPS16,
1324     OPTION_NO_MIPS16,
1325     OPTION_MIPS3D,
1326     OPTION_NO_MIPS3D,
1327     OPTION_MDMX,
1328     OPTION_NO_MDMX,
1329     OPTION_DSP,
1330     OPTION_NO_DSP,
1331     OPTION_MT,
1332     OPTION_NO_MT,
1333     OPTION_VIRT,
1334     OPTION_NO_VIRT,
1335     OPTION_MSA,
1336     OPTION_NO_MSA,
1337     OPTION_SMARTMIPS,
1338     OPTION_NO_SMARTMIPS,
1339     OPTION_DSPR2,
1340     OPTION_NO_DSPR2,
1341     OPTION_EVA,
1342     OPTION_NO_EVA,
1343     OPTION_MICROMIPS,
1344     OPTION_NO_MICROMIPS,
1345     OPTION_MCU,
1346     OPTION_NO_MCU,
1347     OPTION_COMPAT_ARCH_BASE,
1348     OPTION_M4650,
1349     OPTION_NO_M4650,
1350     OPTION_M4010,
1351     OPTION_NO_M4010,
1352     OPTION_M4100,
1353     OPTION_NO_M4100,
1354     OPTION_M3900,
1355     OPTION_NO_M3900,
1356     OPTION_M7000_HILO_FIX,
1357     OPTION_MNO_7000_HILO_FIX,
1358     OPTION_FIX_24K,
1359     OPTION_NO_FIX_24K,
1360     OPTION_FIX_RM7000,
1361     OPTION_NO_FIX_RM7000,
1362     OPTION_FIX_LOONGSON2F_JUMP,
1363     OPTION_NO_FIX_LOONGSON2F_JUMP,
1364     OPTION_FIX_LOONGSON2F_NOP,
1365     OPTION_NO_FIX_LOONGSON2F_NOP,
1366     OPTION_FIX_VR4120,
1367     OPTION_NO_FIX_VR4120,
1368     OPTION_FIX_VR4130,
1369     OPTION_NO_FIX_VR4130,
1370     OPTION_FIX_CN63XXP1,
1371     OPTION_NO_FIX_CN63XXP1,
1372     OPTION_TRAP,
1373     OPTION_BREAK,
1374     OPTION_EB,
1375     OPTION_EL,
1376     OPTION_FP32,
1377     OPTION_GP32,
1378     OPTION_CONSTRUCT_FLOATS,
1379     OPTION_NO_CONSTRUCT_FLOATS,
1380     OPTION_FP64,
1381     OPTION_GP64,
1382     OPTION_RELAX_BRANCH,
1383     OPTION_NO_RELAX_BRANCH,
1384     OPTION_INSN32,
1385     OPTION_NO_INSN32,
1386     OPTION_MSHARED,
1387     OPTION_MNO_SHARED,
1388     OPTION_MSYM32,
1389     OPTION_MNO_SYM32,
1390     OPTION_SOFT_FLOAT,
1391     OPTION_HARD_FLOAT,
1392     OPTION_SINGLE_FLOAT,
1393     OPTION_DOUBLE_FLOAT,
1394     OPTION_32,
1395     OPTION_CALL_SHARED,
1396     OPTION_CALL_NONPIC,
1397     OPTION_NON_SHARED,
1398     OPTION_XGOT,
1399     OPTION_MABI,
1400     OPTION_N32,
1401     OPTION_64,
1402     OPTION_MDEBUG,
1403     OPTION_NO_MDEBUG,
1404     OPTION_PDR,
1405     OPTION_NO_PDR,
1406     OPTION_MVXWORKS_PIC,
1407     OPTION_NAN,
1408     OPTION_END_OF_ENUM
1409   };
1410
1411 struct option md_longopts[] =
1412 {
1413   /* Options which specify architecture.  */
1414   {"march", required_argument, NULL, OPTION_MARCH},
1415   {"mtune", required_argument, NULL, OPTION_MTUNE},
1416   {"mips0", no_argument, NULL, OPTION_MIPS1},
1417   {"mips1", no_argument, NULL, OPTION_MIPS1},
1418   {"mips2", no_argument, NULL, OPTION_MIPS2},
1419   {"mips3", no_argument, NULL, OPTION_MIPS3},
1420   {"mips4", no_argument, NULL, OPTION_MIPS4},
1421   {"mips5", no_argument, NULL, OPTION_MIPS5},
1422   {"mips32", no_argument, NULL, OPTION_MIPS32},
1423   {"mips64", no_argument, NULL, OPTION_MIPS64},
1424   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1425   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1426
1427   /* Options which specify Application Specific Extensions (ASEs).  */
1428   {"mips16", no_argument, NULL, OPTION_MIPS16},
1429   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1430   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1431   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1432   {"mdmx", no_argument, NULL, OPTION_MDMX},
1433   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1434   {"mdsp", no_argument, NULL, OPTION_DSP},
1435   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1436   {"mmt", no_argument, NULL, OPTION_MT},
1437   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1438   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1439   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1440   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1441   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1442   {"meva", no_argument, NULL, OPTION_EVA},
1443   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1444   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1445   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1446   {"mmcu", no_argument, NULL, OPTION_MCU},
1447   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1448   {"mvirt", no_argument, NULL, OPTION_VIRT},
1449   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1450   {"mmsa", no_argument, NULL, OPTION_MSA},
1451   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1452
1453   /* Old-style architecture options.  Don't add more of these.  */
1454   {"m4650", no_argument, NULL, OPTION_M4650},
1455   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1456   {"m4010", no_argument, NULL, OPTION_M4010},
1457   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1458   {"m4100", no_argument, NULL, OPTION_M4100},
1459   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1460   {"m3900", no_argument, NULL, OPTION_M3900},
1461   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1462
1463   /* Options which enable bug fixes.  */
1464   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1465   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1466   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1467   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1468   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1469   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1470   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1471   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1472   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1473   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1474   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1475   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1476   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1477   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1478   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1479   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1480   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1481
1482   /* Miscellaneous options.  */
1483   {"trap", no_argument, NULL, OPTION_TRAP},
1484   {"no-break", no_argument, NULL, OPTION_TRAP},
1485   {"break", no_argument, NULL, OPTION_BREAK},
1486   {"no-trap", no_argument, NULL, OPTION_BREAK},
1487   {"EB", no_argument, NULL, OPTION_EB},
1488   {"EL", no_argument, NULL, OPTION_EL},
1489   {"mfp32", no_argument, NULL, OPTION_FP32},
1490   {"mgp32", no_argument, NULL, OPTION_GP32},
1491   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1492   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1493   {"mfp64", no_argument, NULL, OPTION_FP64},
1494   {"mgp64", no_argument, NULL, OPTION_GP64},
1495   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1496   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1497   {"minsn32", no_argument, NULL, OPTION_INSN32},
1498   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1499   {"mshared", no_argument, NULL, OPTION_MSHARED},
1500   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1501   {"msym32", no_argument, NULL, OPTION_MSYM32},
1502   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1503   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1504   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1505   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1506   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1507
1508   /* Strictly speaking this next option is ELF specific,
1509      but we allow it for other ports as well in order to
1510      make testing easier.  */
1511   {"32", no_argument, NULL, OPTION_32},
1512
1513   /* ELF-specific options.  */
1514   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1515   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1516   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1517   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1518   {"xgot", no_argument, NULL, OPTION_XGOT},
1519   {"mabi", required_argument, NULL, OPTION_MABI},
1520   {"n32", no_argument, NULL, OPTION_N32},
1521   {"64", no_argument, NULL, OPTION_64},
1522   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1523   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1524   {"mpdr", no_argument, NULL, OPTION_PDR},
1525   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1526   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1527   {"mnan", required_argument, NULL, OPTION_NAN},
1528
1529   {NULL, no_argument, NULL, 0}
1530 };
1531 size_t md_longopts_size = sizeof (md_longopts);
1532 \f
1533 /* Information about either an Application Specific Extension or an
1534    optional architecture feature that, for simplicity, we treat in the
1535    same way as an ASE.  */
1536 struct mips_ase
1537 {
1538   /* The name of the ASE, used in both the command-line and .set options.  */
1539   const char *name;
1540
1541   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1542      and 64-bit architectures, the flags here refer to the subset that
1543      is available on both.  */
1544   unsigned int flags;
1545
1546   /* The ASE_* flag used for instructions that are available on 64-bit
1547      architectures but that are not included in FLAGS.  */
1548   unsigned int flags64;
1549
1550   /* The command-line options that turn the ASE on and off.  */
1551   int option_on;
1552   int option_off;
1553
1554   /* The minimum required architecture revisions for MIPS32, MIPS64,
1555      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1556   int mips32_rev;
1557   int mips64_rev;
1558   int micromips32_rev;
1559   int micromips64_rev;
1560 };
1561
1562 /* A table of all supported ASEs.  */
1563 static const struct mips_ase mips_ases[] = {
1564   { "dsp", ASE_DSP, ASE_DSP64,
1565     OPTION_DSP, OPTION_NO_DSP,
1566     2, 2, 2, 2 },
1567
1568   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1569     OPTION_DSPR2, OPTION_NO_DSPR2,
1570     2, 2, 2, 2 },
1571
1572   { "eva", ASE_EVA, 0,
1573     OPTION_EVA, OPTION_NO_EVA,
1574     2, 2, 2, 2 },
1575
1576   { "mcu", ASE_MCU, 0,
1577     OPTION_MCU, OPTION_NO_MCU,
1578     2, 2, 2, 2 },
1579
1580   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1581   { "mdmx", ASE_MDMX, 0,
1582     OPTION_MDMX, OPTION_NO_MDMX,
1583     -1, 1, -1, -1 },
1584
1585   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1586   { "mips3d", ASE_MIPS3D, 0,
1587     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1588     2, 1, -1, -1 },
1589
1590   { "mt", ASE_MT, 0,
1591     OPTION_MT, OPTION_NO_MT,
1592     2, 2, -1, -1 },
1593
1594   { "smartmips", ASE_SMARTMIPS, 0,
1595     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1596     1, -1, -1, -1 },
1597
1598   { "virt", ASE_VIRT, ASE_VIRT64,
1599     OPTION_VIRT, OPTION_NO_VIRT,
1600     2, 2, 2, 2 },
1601
1602   { "msa", ASE_MSA, ASE_MSA64,
1603     OPTION_MSA, OPTION_NO_MSA,
1604     2, 2, 2, 2 }
1605 };
1606
1607 /* The set of ASEs that require -mfp64.  */
1608 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1609
1610 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1611 static const unsigned int mips_ase_groups[] = {
1612   ASE_DSP | ASE_DSPR2
1613 };
1614 \f
1615 /* Pseudo-op table.
1616
1617    The following pseudo-ops from the Kane and Heinrich MIPS book
1618    should be defined here, but are currently unsupported: .alias,
1619    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1620
1621    The following pseudo-ops from the Kane and Heinrich MIPS book are
1622    specific to the type of debugging information being generated, and
1623    should be defined by the object format: .aent, .begin, .bend,
1624    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1625    .vreg.
1626
1627    The following pseudo-ops from the Kane and Heinrich MIPS book are
1628    not MIPS CPU specific, but are also not specific to the object file
1629    format.  This file is probably the best place to define them, but
1630    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1631
1632 static const pseudo_typeS mips_pseudo_table[] =
1633 {
1634   /* MIPS specific pseudo-ops.  */
1635   {"option", s_option, 0},
1636   {"set", s_mipsset, 0},
1637   {"rdata", s_change_sec, 'r'},
1638   {"sdata", s_change_sec, 's'},
1639   {"livereg", s_ignore, 0},
1640   {"abicalls", s_abicalls, 0},
1641   {"cpload", s_cpload, 0},
1642   {"cpsetup", s_cpsetup, 0},
1643   {"cplocal", s_cplocal, 0},
1644   {"cprestore", s_cprestore, 0},
1645   {"cpreturn", s_cpreturn, 0},
1646   {"dtprelword", s_dtprelword, 0},
1647   {"dtpreldword", s_dtpreldword, 0},
1648   {"tprelword", s_tprelword, 0},
1649   {"tpreldword", s_tpreldword, 0},
1650   {"gpvalue", s_gpvalue, 0},
1651   {"gpword", s_gpword, 0},
1652   {"gpdword", s_gpdword, 0},
1653   {"ehword", s_ehword, 0},
1654   {"cpadd", s_cpadd, 0},
1655   {"insn", s_insn, 0},
1656   {"nan", s_nan, 0},
1657
1658   /* Relatively generic pseudo-ops that happen to be used on MIPS
1659      chips.  */
1660   {"asciiz", stringer, 8 + 1},
1661   {"bss", s_change_sec, 'b'},
1662   {"err", s_err, 0},
1663   {"half", s_cons, 1},
1664   {"dword", s_cons, 3},
1665   {"weakext", s_mips_weakext, 0},
1666   {"origin", s_org, 0},
1667   {"repeat", s_rept, 0},
1668
1669   /* For MIPS this is non-standard, but we define it for consistency.  */
1670   {"sbss", s_change_sec, 'B'},
1671
1672   /* These pseudo-ops are defined in read.c, but must be overridden
1673      here for one reason or another.  */
1674   {"align", s_align, 0},
1675   {"byte", s_cons, 0},
1676   {"data", s_change_sec, 'd'},
1677   {"double", s_float_cons, 'd'},
1678   {"float", s_float_cons, 'f'},
1679   {"globl", s_mips_globl, 0},
1680   {"global", s_mips_globl, 0},
1681   {"hword", s_cons, 1},
1682   {"int", s_cons, 2},
1683   {"long", s_cons, 2},
1684   {"octa", s_cons, 4},
1685   {"quad", s_cons, 3},
1686   {"section", s_change_section, 0},
1687   {"short", s_cons, 1},
1688   {"single", s_float_cons, 'f'},
1689   {"stabd", s_mips_stab, 'd'},
1690   {"stabn", s_mips_stab, 'n'},
1691   {"stabs", s_mips_stab, 's'},
1692   {"text", s_change_sec, 't'},
1693   {"word", s_cons, 2},
1694
1695   { "extern", ecoff_directive_extern, 0},
1696
1697   { NULL, NULL, 0 },
1698 };
1699
1700 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1701 {
1702   /* These pseudo-ops should be defined by the object file format.
1703      However, a.out doesn't support them, so we have versions here.  */
1704   {"aent", s_mips_ent, 1},
1705   {"bgnb", s_ignore, 0},
1706   {"end", s_mips_end, 0},
1707   {"endb", s_ignore, 0},
1708   {"ent", s_mips_ent, 0},
1709   {"file", s_mips_file, 0},
1710   {"fmask", s_mips_mask, 'F'},
1711   {"frame", s_mips_frame, 0},
1712   {"loc", s_mips_loc, 0},
1713   {"mask", s_mips_mask, 'R'},
1714   {"verstamp", s_ignore, 0},
1715   { NULL, NULL, 0 },
1716 };
1717
1718 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1719    purpose of the `.dc.a' internal pseudo-op.  */
1720
1721 int
1722 mips_address_bytes (void)
1723 {
1724   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1725 }
1726
1727 extern void pop_insert (const pseudo_typeS *);
1728
1729 void
1730 mips_pop_insert (void)
1731 {
1732   pop_insert (mips_pseudo_table);
1733   if (! ECOFF_DEBUGGING)
1734     pop_insert (mips_nonecoff_pseudo_table);
1735 }
1736 \f
1737 /* Symbols labelling the current insn.  */
1738
1739 struct insn_label_list
1740 {
1741   struct insn_label_list *next;
1742   symbolS *label;
1743 };
1744
1745 static struct insn_label_list *free_insn_labels;
1746 #define label_list tc_segment_info_data.labels
1747
1748 static void mips_clear_insn_labels (void);
1749 static void mips_mark_labels (void);
1750 static void mips_compressed_mark_labels (void);
1751
1752 static inline void
1753 mips_clear_insn_labels (void)
1754 {
1755   register struct insn_label_list **pl;
1756   segment_info_type *si;
1757
1758   if (now_seg)
1759     {
1760       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1761         ;
1762       
1763       si = seg_info (now_seg);
1764       *pl = si->label_list;
1765       si->label_list = NULL;
1766     }
1767 }
1768
1769 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1770
1771 static inline void
1772 mips_mark_labels (void)
1773 {
1774   if (HAVE_CODE_COMPRESSION)
1775     mips_compressed_mark_labels ();
1776 }
1777 \f
1778 static char *expr_end;
1779
1780 /* An expression in a macro instruction.  This is set by mips_ip and
1781    mips16_ip and when populated is always an O_constant.  */
1782
1783 static expressionS imm_expr;
1784
1785 /* The relocatable field in an instruction and the relocs associated
1786    with it.  These variables are used for instructions like LUI and
1787    JAL as well as true offsets.  They are also used for address
1788    operands in macros.  */
1789
1790 static expressionS offset_expr;
1791 static bfd_reloc_code_real_type offset_reloc[3]
1792   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1793
1794 /* This is set to the resulting size of the instruction to be produced
1795    by mips16_ip if an explicit extension is used or by mips_ip if an
1796    explicit size is supplied.  */
1797
1798 static unsigned int forced_insn_length;
1799
1800 /* True if we are assembling an instruction.  All dot symbols defined during
1801    this time should be treated as code labels.  */
1802
1803 static bfd_boolean mips_assembling_insn;
1804
1805 /* The pdr segment for per procedure frame/regmask info.  Not used for
1806    ECOFF debugging.  */
1807
1808 static segT pdr_seg;
1809
1810 /* The default target format to use.  */
1811
1812 #if defined (TE_FreeBSD)
1813 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1814 #elif defined (TE_TMIPS)
1815 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1816 #else
1817 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1818 #endif
1819
1820 const char *
1821 mips_target_format (void)
1822 {
1823   switch (OUTPUT_FLAVOR)
1824     {
1825     case bfd_target_elf_flavour:
1826 #ifdef TE_VXWORKS
1827       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1828         return (target_big_endian
1829                 ? "elf32-bigmips-vxworks"
1830                 : "elf32-littlemips-vxworks");
1831 #endif
1832       return (target_big_endian
1833               ? (HAVE_64BIT_OBJECTS
1834                  ? ELF_TARGET ("elf64-", "big")
1835                  : (HAVE_NEWABI
1836                     ? ELF_TARGET ("elf32-n", "big")
1837                     : ELF_TARGET ("elf32-", "big")))
1838               : (HAVE_64BIT_OBJECTS
1839                  ? ELF_TARGET ("elf64-", "little")
1840                  : (HAVE_NEWABI
1841                     ? ELF_TARGET ("elf32-n", "little")
1842                     : ELF_TARGET ("elf32-", "little"))));
1843     default:
1844       abort ();
1845       return NULL;
1846     }
1847 }
1848
1849 /* Return the ISA revision that is currently in use, or 0 if we are
1850    generating code for MIPS V or below.  */
1851
1852 static int
1853 mips_isa_rev (void)
1854 {
1855   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1856     return 2;
1857
1858   /* microMIPS implies revision 2 or above.  */
1859   if (mips_opts.micromips)
1860     return 2;
1861
1862   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1863     return 1;
1864
1865   return 0;
1866 }
1867
1868 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1869
1870 static unsigned int
1871 mips_ase_mask (unsigned int flags)
1872 {
1873   unsigned int i;
1874
1875   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1876     if (flags & mips_ase_groups[i])
1877       flags |= mips_ase_groups[i];
1878   return flags;
1879 }
1880
1881 /* Check whether the current ISA supports ASE.  Issue a warning if
1882    appropriate.  */
1883
1884 static void
1885 mips_check_isa_supports_ase (const struct mips_ase *ase)
1886 {
1887   const char *base;
1888   int min_rev, size;
1889   static unsigned int warned_isa;
1890   static unsigned int warned_fp32;
1891
1892   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1893     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1894   else
1895     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1896   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1897       && (warned_isa & ase->flags) != ase->flags)
1898     {
1899       warned_isa |= ase->flags;
1900       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1901       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1902       if (min_rev < 0)
1903         as_warn (_("the %d-bit %s architecture does not support the"
1904                    " `%s' extension"), size, base, ase->name);
1905       else
1906         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1907                  ase->name, base, size, min_rev);
1908     }
1909   if ((ase->flags & FP64_ASES)
1910       && mips_opts.fp32
1911       && (warned_fp32 & ase->flags) != ase->flags)
1912     {
1913       warned_fp32 |= ase->flags;
1914       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1915     }
1916 }
1917
1918 /* Check all enabled ASEs to see whether they are supported by the
1919    chosen architecture.  */
1920
1921 static void
1922 mips_check_isa_supports_ases (void)
1923 {
1924   unsigned int i, mask;
1925
1926   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1927     {
1928       mask = mips_ase_mask (mips_ases[i].flags);
1929       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1930         mips_check_isa_supports_ase (&mips_ases[i]);
1931     }
1932 }
1933
1934 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1935    that were affected.  */
1936
1937 static unsigned int
1938 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1939 {
1940   unsigned int mask;
1941
1942   mask = mips_ase_mask (ase->flags);
1943   mips_opts.ase &= ~mask;
1944   if (enabled_p)
1945     mips_opts.ase |= ase->flags;
1946   return mask;
1947 }
1948
1949 /* Return the ASE called NAME, or null if none.  */
1950
1951 static const struct mips_ase *
1952 mips_lookup_ase (const char *name)
1953 {
1954   unsigned int i;
1955
1956   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1957     if (strcmp (name, mips_ases[i].name) == 0)
1958       return &mips_ases[i];
1959   return NULL;
1960 }
1961
1962 /* Return the length of a microMIPS instruction in bytes.  If bits of
1963    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1964    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1965    major opcode) will require further modifications to the opcode
1966    table.  */
1967
1968 static inline unsigned int
1969 micromips_insn_length (const struct mips_opcode *mo)
1970 {
1971   return (mo->mask >> 16) == 0 ? 2 : 4;
1972 }
1973
1974 /* Return the length of MIPS16 instruction OPCODE.  */
1975
1976 static inline unsigned int
1977 mips16_opcode_length (unsigned long opcode)
1978 {
1979   return (opcode >> 16) == 0 ? 2 : 4;
1980 }
1981
1982 /* Return the length of instruction INSN.  */
1983
1984 static inline unsigned int
1985 insn_length (const struct mips_cl_insn *insn)
1986 {
1987   if (mips_opts.micromips)
1988     return micromips_insn_length (insn->insn_mo);
1989   else if (mips_opts.mips16)
1990     return mips16_opcode_length (insn->insn_opcode);
1991   else
1992     return 4;
1993 }
1994
1995 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1996
1997 static void
1998 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1999 {
2000   size_t i;
2001
2002   insn->insn_mo = mo;
2003   insn->insn_opcode = mo->match;
2004   insn->frag = NULL;
2005   insn->where = 0;
2006   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2007     insn->fixp[i] = NULL;
2008   insn->fixed_p = (mips_opts.noreorder > 0);
2009   insn->noreorder_p = (mips_opts.noreorder > 0);
2010   insn->mips16_absolute_jump_p = 0;
2011   insn->complete_p = 0;
2012   insn->cleared_p = 0;
2013 }
2014
2015 /* Get a list of all the operands in INSN.  */
2016
2017 static const struct mips_operand_array *
2018 insn_operands (const struct mips_cl_insn *insn)
2019 {
2020   if (insn->insn_mo >= &mips_opcodes[0]
2021       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2022     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2023
2024   if (insn->insn_mo >= &mips16_opcodes[0]
2025       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2026     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2027
2028   if (insn->insn_mo >= &micromips_opcodes[0]
2029       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2030     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2031
2032   abort ();
2033 }
2034
2035 /* Get a description of operand OPNO of INSN.  */
2036
2037 static const struct mips_operand *
2038 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2039 {
2040   const struct mips_operand_array *operands;
2041
2042   operands = insn_operands (insn);
2043   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2044     abort ();
2045   return operands->operand[opno];
2046 }
2047
2048 /* Install UVAL as the value of OPERAND in INSN.  */
2049
2050 static inline void
2051 insn_insert_operand (struct mips_cl_insn *insn,
2052                      const struct mips_operand *operand, unsigned int uval)
2053 {
2054   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2055 }
2056
2057 /* Extract the value of OPERAND from INSN.  */
2058
2059 static inline unsigned
2060 insn_extract_operand (const struct mips_cl_insn *insn,
2061                       const struct mips_operand *operand)
2062 {
2063   return mips_extract_operand (operand, insn->insn_opcode);
2064 }
2065
2066 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2067
2068 static void
2069 mips_record_compressed_mode (void)
2070 {
2071   segment_info_type *si;
2072
2073   si = seg_info (now_seg);
2074   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2075     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2076   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2077     si->tc_segment_info_data.micromips = mips_opts.micromips;
2078 }
2079
2080 /* Read a standard MIPS instruction from BUF.  */
2081
2082 static unsigned long
2083 read_insn (char *buf)
2084 {
2085   if (target_big_endian)
2086     return bfd_getb32 ((bfd_byte *) buf);
2087   else
2088     return bfd_getl32 ((bfd_byte *) buf);
2089 }
2090
2091 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2092    the next byte.  */
2093
2094 static char *
2095 write_insn (char *buf, unsigned int insn)
2096 {
2097   md_number_to_chars (buf, insn, 4);
2098   return buf + 4;
2099 }
2100
2101 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2102    has length LENGTH.  */
2103
2104 static unsigned long
2105 read_compressed_insn (char *buf, unsigned int length)
2106 {
2107   unsigned long insn;
2108   unsigned int i;
2109
2110   insn = 0;
2111   for (i = 0; i < length; i += 2)
2112     {
2113       insn <<= 16;
2114       if (target_big_endian)
2115         insn |= bfd_getb16 ((char *) buf);
2116       else
2117         insn |= bfd_getl16 ((char *) buf);
2118       buf += 2;
2119     }
2120   return insn;
2121 }
2122
2123 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2124    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2125
2126 static char *
2127 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2128 {
2129   unsigned int i;
2130
2131   for (i = 0; i < length; i += 2)
2132     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2133   return buf + length;
2134 }
2135
2136 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2137
2138 static void
2139 install_insn (const struct mips_cl_insn *insn)
2140 {
2141   char *f = insn->frag->fr_literal + insn->where;
2142   if (HAVE_CODE_COMPRESSION)
2143     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2144   else
2145     write_insn (f, insn->insn_opcode);
2146   mips_record_compressed_mode ();
2147 }
2148
2149 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2150    and install the opcode in the new location.  */
2151
2152 static void
2153 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2154 {
2155   size_t i;
2156
2157   insn->frag = frag;
2158   insn->where = where;
2159   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2160     if (insn->fixp[i] != NULL)
2161       {
2162         insn->fixp[i]->fx_frag = frag;
2163         insn->fixp[i]->fx_where = where;
2164       }
2165   install_insn (insn);
2166 }
2167
2168 /* Add INSN to the end of the output.  */
2169
2170 static void
2171 add_fixed_insn (struct mips_cl_insn *insn)
2172 {
2173   char *f = frag_more (insn_length (insn));
2174   move_insn (insn, frag_now, f - frag_now->fr_literal);
2175 }
2176
2177 /* Start a variant frag and move INSN to the start of the variant part,
2178    marking it as fixed.  The other arguments are as for frag_var.  */
2179
2180 static void
2181 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2182                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2183 {
2184   frag_grow (max_chars);
2185   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2186   insn->fixed_p = 1;
2187   frag_var (rs_machine_dependent, max_chars, var,
2188             subtype, symbol, offset, NULL);
2189 }
2190
2191 /* Insert N copies of INSN into the history buffer, starting at
2192    position FIRST.  Neither FIRST nor N need to be clipped.  */
2193
2194 static void
2195 insert_into_history (unsigned int first, unsigned int n,
2196                      const struct mips_cl_insn *insn)
2197 {
2198   if (mips_relax.sequence != 2)
2199     {
2200       unsigned int i;
2201
2202       for (i = ARRAY_SIZE (history); i-- > first;)
2203         if (i >= first + n)
2204           history[i] = history[i - n];
2205         else
2206           history[i] = *insn;
2207     }
2208 }
2209
2210 /* Clear the error in insn_error.  */
2211
2212 static void
2213 clear_insn_error (void)
2214 {
2215   memset (&insn_error, 0, sizeof (insn_error));
2216 }
2217
2218 /* Possibly record error message MSG for the current instruction.
2219    If the error is about a particular argument, ARGNUM is the 1-based
2220    number of that argument, otherwise it is 0.  FORMAT is the format
2221    of MSG.  Return true if MSG was used, false if the current message
2222    was kept.  */
2223
2224 static bfd_boolean
2225 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2226                        const char *msg)
2227 {
2228   if (argnum == 0)
2229     {
2230       /* Give priority to errors against specific arguments, and to
2231          the first whole-instruction message.  */
2232       if (insn_error.msg)
2233         return FALSE;
2234     }
2235   else
2236     {
2237       /* Keep insn_error if it is against a later argument.  */
2238       if (argnum < insn_error.min_argnum)
2239         return FALSE;
2240
2241       /* If both errors are against the same argument but are different,
2242          give up on reporting a specific error for this argument.
2243          See the comment about mips_insn_error for details.  */
2244       if (argnum == insn_error.min_argnum
2245           && insn_error.msg
2246           && strcmp (insn_error.msg, msg) != 0)
2247         {
2248           insn_error.msg = 0;
2249           insn_error.min_argnum += 1;
2250           return FALSE;
2251         }
2252     }
2253   insn_error.min_argnum = argnum;
2254   insn_error.format = format;
2255   insn_error.msg = msg;
2256   return TRUE;
2257 }
2258
2259 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2260    as for set_insn_error_format.  */
2261
2262 static void
2263 set_insn_error (int argnum, const char *msg)
2264 {
2265   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2266 }
2267
2268 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2269    as for set_insn_error_format.  */
2270
2271 static void
2272 set_insn_error_i (int argnum, const char *msg, int i)
2273 {
2274   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2275     insn_error.u.i = i;
2276 }
2277
2278 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2279    are as for set_insn_error_format.  */
2280
2281 static void
2282 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2283 {
2284   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2285     {
2286       insn_error.u.ss[0] = s1;
2287       insn_error.u.ss[1] = s2;
2288     }
2289 }
2290
2291 /* Report the error in insn_error, which is against assembly code STR.  */
2292
2293 static void
2294 report_insn_error (const char *str)
2295 {
2296   const char *msg;
2297
2298   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2299   switch (insn_error.format)
2300     {
2301     case ERR_FMT_PLAIN:
2302       as_bad (msg, str);
2303       break;
2304
2305     case ERR_FMT_I:
2306       as_bad (msg, insn_error.u.i, str);
2307       break;
2308
2309     case ERR_FMT_SS:
2310       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2311       break;
2312     }
2313 }
2314
2315 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2316    the idea is to make it obvious at a glance that each errata is
2317    included.  */
2318
2319 static void
2320 init_vr4120_conflicts (void)
2321 {
2322 #define CONFLICT(FIRST, SECOND) \
2323     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2324
2325   /* Errata 21 - [D]DIV[U] after [D]MACC */
2326   CONFLICT (MACC, DIV);
2327   CONFLICT (DMACC, DIV);
2328
2329   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2330   CONFLICT (DMULT, DMULT);
2331   CONFLICT (DMULT, DMACC);
2332   CONFLICT (DMACC, DMULT);
2333   CONFLICT (DMACC, DMACC);
2334
2335   /* Errata 24 - MT{LO,HI} after [D]MACC */
2336   CONFLICT (MACC, MTHILO);
2337   CONFLICT (DMACC, MTHILO);
2338
2339   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2340      instruction is executed immediately after a MACC or DMACC
2341      instruction, the result of [either instruction] is incorrect."  */
2342   CONFLICT (MACC, MULT);
2343   CONFLICT (MACC, DMULT);
2344   CONFLICT (DMACC, MULT);
2345   CONFLICT (DMACC, DMULT);
2346
2347   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2348      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2349      DDIV or DDIVU instruction, the result of the MACC or
2350      DMACC instruction is incorrect.".  */
2351   CONFLICT (DMULT, MACC);
2352   CONFLICT (DMULT, DMACC);
2353   CONFLICT (DIV, MACC);
2354   CONFLICT (DIV, DMACC);
2355
2356 #undef CONFLICT
2357 }
2358
2359 struct regname {
2360   const char *name;
2361   unsigned int num;
2362 };
2363
2364 #define RNUM_MASK       0x00000ff
2365 #define RTYPE_MASK      0x0ffff00
2366 #define RTYPE_NUM       0x0000100
2367 #define RTYPE_FPU       0x0000200
2368 #define RTYPE_FCC       0x0000400
2369 #define RTYPE_VEC       0x0000800
2370 #define RTYPE_GP        0x0001000
2371 #define RTYPE_CP0       0x0002000
2372 #define RTYPE_PC        0x0004000
2373 #define RTYPE_ACC       0x0008000
2374 #define RTYPE_CCC       0x0010000
2375 #define RTYPE_VI        0x0020000
2376 #define RTYPE_VF        0x0040000
2377 #define RTYPE_R5900_I   0x0080000
2378 #define RTYPE_R5900_Q   0x0100000
2379 #define RTYPE_R5900_R   0x0200000
2380 #define RTYPE_R5900_ACC 0x0400000
2381 #define RTYPE_MSA       0x0800000
2382 #define RWARN           0x8000000
2383
2384 #define GENERIC_REGISTER_NUMBERS \
2385     {"$0",      RTYPE_NUM | 0},  \
2386     {"$1",      RTYPE_NUM | 1},  \
2387     {"$2",      RTYPE_NUM | 2},  \
2388     {"$3",      RTYPE_NUM | 3},  \
2389     {"$4",      RTYPE_NUM | 4},  \
2390     {"$5",      RTYPE_NUM | 5},  \
2391     {"$6",      RTYPE_NUM | 6},  \
2392     {"$7",      RTYPE_NUM | 7},  \
2393     {"$8",      RTYPE_NUM | 8},  \
2394     {"$9",      RTYPE_NUM | 9},  \
2395     {"$10",     RTYPE_NUM | 10}, \
2396     {"$11",     RTYPE_NUM | 11}, \
2397     {"$12",     RTYPE_NUM | 12}, \
2398     {"$13",     RTYPE_NUM | 13}, \
2399     {"$14",     RTYPE_NUM | 14}, \
2400     {"$15",     RTYPE_NUM | 15}, \
2401     {"$16",     RTYPE_NUM | 16}, \
2402     {"$17",     RTYPE_NUM | 17}, \
2403     {"$18",     RTYPE_NUM | 18}, \
2404     {"$19",     RTYPE_NUM | 19}, \
2405     {"$20",     RTYPE_NUM | 20}, \
2406     {"$21",     RTYPE_NUM | 21}, \
2407     {"$22",     RTYPE_NUM | 22}, \
2408     {"$23",     RTYPE_NUM | 23}, \
2409     {"$24",     RTYPE_NUM | 24}, \
2410     {"$25",     RTYPE_NUM | 25}, \
2411     {"$26",     RTYPE_NUM | 26}, \
2412     {"$27",     RTYPE_NUM | 27}, \
2413     {"$28",     RTYPE_NUM | 28}, \
2414     {"$29",     RTYPE_NUM | 29}, \
2415     {"$30",     RTYPE_NUM | 30}, \
2416     {"$31",     RTYPE_NUM | 31} 
2417
2418 #define FPU_REGISTER_NAMES       \
2419     {"$f0",     RTYPE_FPU | 0},  \
2420     {"$f1",     RTYPE_FPU | 1},  \
2421     {"$f2",     RTYPE_FPU | 2},  \
2422     {"$f3",     RTYPE_FPU | 3},  \
2423     {"$f4",     RTYPE_FPU | 4},  \
2424     {"$f5",     RTYPE_FPU | 5},  \
2425     {"$f6",     RTYPE_FPU | 6},  \
2426     {"$f7",     RTYPE_FPU | 7},  \
2427     {"$f8",     RTYPE_FPU | 8},  \
2428     {"$f9",     RTYPE_FPU | 9},  \
2429     {"$f10",    RTYPE_FPU | 10}, \
2430     {"$f11",    RTYPE_FPU | 11}, \
2431     {"$f12",    RTYPE_FPU | 12}, \
2432     {"$f13",    RTYPE_FPU | 13}, \
2433     {"$f14",    RTYPE_FPU | 14}, \
2434     {"$f15",    RTYPE_FPU | 15}, \
2435     {"$f16",    RTYPE_FPU | 16}, \
2436     {"$f17",    RTYPE_FPU | 17}, \
2437     {"$f18",    RTYPE_FPU | 18}, \
2438     {"$f19",    RTYPE_FPU | 19}, \
2439     {"$f20",    RTYPE_FPU | 20}, \
2440     {"$f21",    RTYPE_FPU | 21}, \
2441     {"$f22",    RTYPE_FPU | 22}, \
2442     {"$f23",    RTYPE_FPU | 23}, \
2443     {"$f24",    RTYPE_FPU | 24}, \
2444     {"$f25",    RTYPE_FPU | 25}, \
2445     {"$f26",    RTYPE_FPU | 26}, \
2446     {"$f27",    RTYPE_FPU | 27}, \
2447     {"$f28",    RTYPE_FPU | 28}, \
2448     {"$f29",    RTYPE_FPU | 29}, \
2449     {"$f30",    RTYPE_FPU | 30}, \
2450     {"$f31",    RTYPE_FPU | 31}
2451
2452 #define FPU_CONDITION_CODE_NAMES \
2453     {"$fcc0",   RTYPE_FCC | 0},  \
2454     {"$fcc1",   RTYPE_FCC | 1},  \
2455     {"$fcc2",   RTYPE_FCC | 2},  \
2456     {"$fcc3",   RTYPE_FCC | 3},  \
2457     {"$fcc4",   RTYPE_FCC | 4},  \
2458     {"$fcc5",   RTYPE_FCC | 5},  \
2459     {"$fcc6",   RTYPE_FCC | 6},  \
2460     {"$fcc7",   RTYPE_FCC | 7}
2461
2462 #define COPROC_CONDITION_CODE_NAMES         \
2463     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2464     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2465     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2466     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2467     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2468     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2469     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2470     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2471
2472 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2473     {"$a4",     RTYPE_GP | 8},  \
2474     {"$a5",     RTYPE_GP | 9},  \
2475     {"$a6",     RTYPE_GP | 10}, \
2476     {"$a7",     RTYPE_GP | 11}, \
2477     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2478     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2479     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2480     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2481     {"$t0",     RTYPE_GP | 12}, \
2482     {"$t1",     RTYPE_GP | 13}, \
2483     {"$t2",     RTYPE_GP | 14}, \
2484     {"$t3",     RTYPE_GP | 15}
2485
2486 #define O32_SYMBOLIC_REGISTER_NAMES \
2487     {"$t0",     RTYPE_GP | 8},  \
2488     {"$t1",     RTYPE_GP | 9},  \
2489     {"$t2",     RTYPE_GP | 10}, \
2490     {"$t3",     RTYPE_GP | 11}, \
2491     {"$t4",     RTYPE_GP | 12}, \
2492     {"$t5",     RTYPE_GP | 13}, \
2493     {"$t6",     RTYPE_GP | 14}, \
2494     {"$t7",     RTYPE_GP | 15}, \
2495     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2496     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2497     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2498     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2499
2500 /* Remaining symbolic register names */
2501 #define SYMBOLIC_REGISTER_NAMES \
2502     {"$zero",   RTYPE_GP | 0},  \
2503     {"$at",     RTYPE_GP | 1},  \
2504     {"$AT",     RTYPE_GP | 1},  \
2505     {"$v0",     RTYPE_GP | 2},  \
2506     {"$v1",     RTYPE_GP | 3},  \
2507     {"$a0",     RTYPE_GP | 4},  \
2508     {"$a1",     RTYPE_GP | 5},  \
2509     {"$a2",     RTYPE_GP | 6},  \
2510     {"$a3",     RTYPE_GP | 7},  \
2511     {"$s0",     RTYPE_GP | 16}, \
2512     {"$s1",     RTYPE_GP | 17}, \
2513     {"$s2",     RTYPE_GP | 18}, \
2514     {"$s3",     RTYPE_GP | 19}, \
2515     {"$s4",     RTYPE_GP | 20}, \
2516     {"$s5",     RTYPE_GP | 21}, \
2517     {"$s6",     RTYPE_GP | 22}, \
2518     {"$s7",     RTYPE_GP | 23}, \
2519     {"$t8",     RTYPE_GP | 24}, \
2520     {"$t9",     RTYPE_GP | 25}, \
2521     {"$k0",     RTYPE_GP | 26}, \
2522     {"$kt0",    RTYPE_GP | 26}, \
2523     {"$k1",     RTYPE_GP | 27}, \
2524     {"$kt1",    RTYPE_GP | 27}, \
2525     {"$gp",     RTYPE_GP | 28}, \
2526     {"$sp",     RTYPE_GP | 29}, \
2527     {"$s8",     RTYPE_GP | 30}, \
2528     {"$fp",     RTYPE_GP | 30}, \
2529     {"$ra",     RTYPE_GP | 31}
2530
2531 #define MIPS16_SPECIAL_REGISTER_NAMES \
2532     {"$pc",     RTYPE_PC | 0}
2533
2534 #define MDMX_VECTOR_REGISTER_NAMES \
2535     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2536     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2537     {"$v2",     RTYPE_VEC | 2},  \
2538     {"$v3",     RTYPE_VEC | 3},  \
2539     {"$v4",     RTYPE_VEC | 4},  \
2540     {"$v5",     RTYPE_VEC | 5},  \
2541     {"$v6",     RTYPE_VEC | 6},  \
2542     {"$v7",     RTYPE_VEC | 7},  \
2543     {"$v8",     RTYPE_VEC | 8},  \
2544     {"$v9",     RTYPE_VEC | 9},  \
2545     {"$v10",    RTYPE_VEC | 10}, \
2546     {"$v11",    RTYPE_VEC | 11}, \
2547     {"$v12",    RTYPE_VEC | 12}, \
2548     {"$v13",    RTYPE_VEC | 13}, \
2549     {"$v14",    RTYPE_VEC | 14}, \
2550     {"$v15",    RTYPE_VEC | 15}, \
2551     {"$v16",    RTYPE_VEC | 16}, \
2552     {"$v17",    RTYPE_VEC | 17}, \
2553     {"$v18",    RTYPE_VEC | 18}, \
2554     {"$v19",    RTYPE_VEC | 19}, \
2555     {"$v20",    RTYPE_VEC | 20}, \
2556     {"$v21",    RTYPE_VEC | 21}, \
2557     {"$v22",    RTYPE_VEC | 22}, \
2558     {"$v23",    RTYPE_VEC | 23}, \
2559     {"$v24",    RTYPE_VEC | 24}, \
2560     {"$v25",    RTYPE_VEC | 25}, \
2561     {"$v26",    RTYPE_VEC | 26}, \
2562     {"$v27",    RTYPE_VEC | 27}, \
2563     {"$v28",    RTYPE_VEC | 28}, \
2564     {"$v29",    RTYPE_VEC | 29}, \
2565     {"$v30",    RTYPE_VEC | 30}, \
2566     {"$v31",    RTYPE_VEC | 31}
2567
2568 #define R5900_I_NAMES \
2569     {"$I",      RTYPE_R5900_I | 0}
2570
2571 #define R5900_Q_NAMES \
2572     {"$Q",      RTYPE_R5900_Q | 0}
2573
2574 #define R5900_R_NAMES \
2575     {"$R",      RTYPE_R5900_R | 0}
2576
2577 #define R5900_ACC_NAMES \
2578     {"$ACC",    RTYPE_R5900_ACC | 0 }
2579
2580 #define MIPS_DSP_ACCUMULATOR_NAMES \
2581     {"$ac0",    RTYPE_ACC | 0}, \
2582     {"$ac1",    RTYPE_ACC | 1}, \
2583     {"$ac2",    RTYPE_ACC | 2}, \
2584     {"$ac3",    RTYPE_ACC | 3}
2585
2586 static const struct regname reg_names[] = {
2587   GENERIC_REGISTER_NUMBERS,
2588   FPU_REGISTER_NAMES,
2589   FPU_CONDITION_CODE_NAMES,
2590   COPROC_CONDITION_CODE_NAMES,
2591
2592   /* The $txx registers depends on the abi,
2593      these will be added later into the symbol table from
2594      one of the tables below once mips_abi is set after 
2595      parsing of arguments from the command line. */
2596   SYMBOLIC_REGISTER_NAMES,
2597
2598   MIPS16_SPECIAL_REGISTER_NAMES,
2599   MDMX_VECTOR_REGISTER_NAMES,
2600   R5900_I_NAMES,
2601   R5900_Q_NAMES,
2602   R5900_R_NAMES,
2603   R5900_ACC_NAMES,
2604   MIPS_DSP_ACCUMULATOR_NAMES,
2605   {0, 0}
2606 };
2607
2608 static const struct regname reg_names_o32[] = {
2609   O32_SYMBOLIC_REGISTER_NAMES,
2610   {0, 0}
2611 };
2612
2613 static const struct regname reg_names_n32n64[] = {
2614   N32N64_SYMBOLIC_REGISTER_NAMES,
2615   {0, 0}
2616 };
2617
2618 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2619    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2620    of these register symbols, return the associated vector register,
2621    otherwise return SYMVAL itself.  */
2622
2623 static unsigned int
2624 mips_prefer_vec_regno (unsigned int symval)
2625 {
2626   if ((symval & -2) == (RTYPE_GP | 2))
2627     return RTYPE_VEC | (symval & 1);
2628   return symval;
2629 }
2630
2631 /* Return true if string [S, E) is a valid register name, storing its
2632    symbol value in *SYMVAL_PTR if so.  */
2633
2634 static bfd_boolean
2635 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2636 {
2637   char save_c;
2638   symbolS *symbol;
2639
2640   /* Terminate name.  */
2641   save_c = *e;
2642   *e = '\0';
2643
2644   /* Look up the name.  */
2645   symbol = symbol_find (s);
2646   *e = save_c;
2647
2648   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2649     return FALSE;
2650
2651   *symval_ptr = S_GET_VALUE (symbol);
2652   return TRUE;
2653 }
2654
2655 /* Return true if the string at *SPTR is a valid register name.  Allow it
2656    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2657    is nonnull.
2658
2659    When returning true, move *SPTR past the register, store the
2660    register's symbol value in *SYMVAL_PTR and the channel mask in
2661    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2662    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2663    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2664
2665 static bfd_boolean
2666 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2667                      unsigned int *channels_ptr)
2668 {
2669   char *s, *e, *m;
2670   const char *q;
2671   unsigned int channels, symval, bit;
2672
2673   /* Find end of name.  */
2674   s = e = *sptr;
2675   if (is_name_beginner (*e))
2676     ++e;
2677   while (is_part_of_name (*e))
2678     ++e;
2679
2680   channels = 0;
2681   if (!mips_parse_register_1 (s, e, &symval))
2682     {
2683       if (!channels_ptr)
2684         return FALSE;
2685
2686       /* Eat characters from the end of the string that are valid
2687          channel suffixes.  The preceding register must be $ACC or
2688          end with a digit, so there is no ambiguity.  */
2689       bit = 1;
2690       m = e;
2691       for (q = "wzyx"; *q; q++, bit <<= 1)
2692         if (m > s && m[-1] == *q)
2693           {
2694             --m;
2695             channels |= bit;
2696           }
2697
2698       if (channels == 0
2699           || !mips_parse_register_1 (s, m, &symval)
2700           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2701         return FALSE;
2702     }
2703
2704   *sptr = e;
2705   *symval_ptr = symval;
2706   if (channels_ptr)
2707     *channels_ptr = channels;
2708   return TRUE;
2709 }
2710
2711 /* Check if SPTR points at a valid register specifier according to TYPES.
2712    If so, then return 1, advance S to consume the specifier and store
2713    the register's number in REGNOP, otherwise return 0.  */
2714
2715 static int
2716 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2717 {
2718   unsigned int regno;
2719
2720   if (mips_parse_register (s, &regno, NULL))
2721     {
2722       if (types & RTYPE_VEC)
2723         regno = mips_prefer_vec_regno (regno);
2724       if (regno & types)
2725         regno &= RNUM_MASK;
2726       else
2727         regno = ~0;
2728     }
2729   else
2730     {
2731       if (types & RWARN)
2732         as_warn (_("unrecognized register name `%s'"), *s);
2733       regno = ~0;
2734     }
2735   if (regnop)
2736     *regnop = regno;
2737   return regno <= RNUM_MASK;
2738 }
2739
2740 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2741    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2742
2743 static char *
2744 mips_parse_vu0_channels (char *s, unsigned int *channels)
2745 {
2746   unsigned int i;
2747
2748   *channels = 0;
2749   for (i = 0; i < 4; i++)
2750     if (*s == "xyzw"[i])
2751       {
2752         *channels |= 1 << (3 - i);
2753         ++s;
2754       }
2755   return s;
2756 }
2757
2758 /* Token types for parsed operand lists.  */
2759 enum mips_operand_token_type {
2760   /* A plain register, e.g. $f2.  */
2761   OT_REG,
2762
2763   /* A 4-bit XYZW channel mask.  */
2764   OT_CHANNELS,
2765
2766   /* A constant vector index, e.g. [1].  */
2767   OT_INTEGER_INDEX,
2768
2769   /* A register vector index, e.g. [$2].  */
2770   OT_REG_INDEX,
2771
2772   /* A continuous range of registers, e.g. $s0-$s4.  */
2773   OT_REG_RANGE,
2774
2775   /* A (possibly relocated) expression.  */
2776   OT_INTEGER,
2777
2778   /* A floating-point value.  */
2779   OT_FLOAT,
2780
2781   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2782      before OT_REGs.  */
2783   OT_CHAR,
2784
2785   /* A doubled character, either "--" or "++".  */
2786   OT_DOUBLE_CHAR,
2787
2788   /* The end of the operand list.  */
2789   OT_END
2790 };
2791
2792 /* A parsed operand token.  */
2793 struct mips_operand_token
2794 {
2795   /* The type of token.  */
2796   enum mips_operand_token_type type;
2797   union
2798   {
2799     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2800     unsigned int regno;
2801
2802     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2803     unsigned int channels;
2804
2805     /* The integer value of an OT_INTEGER_INDEX.  */
2806     addressT index;
2807
2808     /* The two register symbol values involved in an OT_REG_RANGE.  */
2809     struct {
2810       unsigned int regno1;
2811       unsigned int regno2;
2812     } reg_range;
2813
2814     /* The value of an OT_INTEGER.  The value is represented as an
2815        expression and the relocation operators that were applied to
2816        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2817        relocation operators were used.  */
2818     struct {
2819       expressionS value;
2820       bfd_reloc_code_real_type relocs[3];
2821     } integer;
2822
2823     /* The binary data for an OT_FLOAT constant, and the number of bytes
2824        in the constant.  */
2825     struct {
2826       unsigned char data[8];
2827       int length;
2828     } flt;
2829
2830     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2831     char ch;
2832   } u;
2833 };
2834
2835 /* An obstack used to construct lists of mips_operand_tokens.  */
2836 static struct obstack mips_operand_tokens;
2837
2838 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2839
2840 static void
2841 mips_add_token (struct mips_operand_token *token,
2842                 enum mips_operand_token_type type)
2843 {
2844   token->type = type;
2845   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2846 }
2847
2848 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2849    and OT_REG tokens for them if so, and return a pointer to the first
2850    unconsumed character.  Return null otherwise.  */
2851
2852 static char *
2853 mips_parse_base_start (char *s)
2854 {
2855   struct mips_operand_token token;
2856   unsigned int regno, channels;
2857   bfd_boolean decrement_p;
2858
2859   if (*s != '(')
2860     return 0;
2861
2862   ++s;
2863   SKIP_SPACE_TABS (s);
2864
2865   /* Only match "--" as part of a base expression.  In other contexts "--X"
2866      is a double negative.  */
2867   decrement_p = (s[0] == '-' && s[1] == '-');
2868   if (decrement_p)
2869     {
2870       s += 2;
2871       SKIP_SPACE_TABS (s);
2872     }
2873
2874   /* Allow a channel specifier because that leads to better error messages
2875      than treating something like "$vf0x++" as an expression.  */
2876   if (!mips_parse_register (&s, &regno, &channels))
2877     return 0;
2878
2879   token.u.ch = '(';
2880   mips_add_token (&token, OT_CHAR);
2881
2882   if (decrement_p)
2883     {
2884       token.u.ch = '-';
2885       mips_add_token (&token, OT_DOUBLE_CHAR);
2886     }
2887
2888   token.u.regno = regno;
2889   mips_add_token (&token, OT_REG);
2890
2891   if (channels)
2892     {
2893       token.u.channels = channels;
2894       mips_add_token (&token, OT_CHANNELS);
2895     }
2896
2897   /* For consistency, only match "++" as part of base expressions too.  */
2898   SKIP_SPACE_TABS (s);
2899   if (s[0] == '+' && s[1] == '+')
2900     {
2901       s += 2;
2902       token.u.ch = '+';
2903       mips_add_token (&token, OT_DOUBLE_CHAR);
2904     }
2905
2906   return s;
2907 }
2908
2909 /* Parse one or more tokens from S.  Return a pointer to the first
2910    unconsumed character on success.  Return null if an error was found
2911    and store the error text in insn_error.  FLOAT_FORMAT is as for
2912    mips_parse_arguments.  */
2913
2914 static char *
2915 mips_parse_argument_token (char *s, char float_format)
2916 {
2917   char *end, *save_in, *err;
2918   unsigned int regno1, regno2, channels;
2919   struct mips_operand_token token;
2920
2921   /* First look for "($reg", since we want to treat that as an
2922      OT_CHAR and OT_REG rather than an expression.  */
2923   end = mips_parse_base_start (s);
2924   if (end)
2925     return end;
2926
2927   /* Handle other characters that end up as OT_CHARs.  */
2928   if (*s == ')' || *s == ',')
2929     {
2930       token.u.ch = *s;
2931       mips_add_token (&token, OT_CHAR);
2932       ++s;
2933       return s;
2934     }
2935
2936   /* Handle tokens that start with a register.  */
2937   if (mips_parse_register (&s, &regno1, &channels))
2938     {
2939       if (channels)
2940         {
2941           /* A register and a VU0 channel suffix.  */
2942           token.u.regno = regno1;
2943           mips_add_token (&token, OT_REG);
2944
2945           token.u.channels = channels;
2946           mips_add_token (&token, OT_CHANNELS);
2947           return s;
2948         }
2949
2950       SKIP_SPACE_TABS (s);
2951       if (*s == '-')
2952         {
2953           /* A register range.  */
2954           ++s;
2955           SKIP_SPACE_TABS (s);
2956           if (!mips_parse_register (&s, &regno2, NULL))
2957             {
2958               set_insn_error (0, _("invalid register range"));
2959               return 0;
2960             }
2961
2962           token.u.reg_range.regno1 = regno1;
2963           token.u.reg_range.regno2 = regno2;
2964           mips_add_token (&token, OT_REG_RANGE);
2965           return s;
2966         }
2967
2968       /* Add the register itself.  */
2969       token.u.regno = regno1;
2970       mips_add_token (&token, OT_REG);
2971
2972       /* Check for a vector index.  */
2973       if (*s == '[')
2974         {
2975           ++s;
2976           SKIP_SPACE_TABS (s);
2977           if (mips_parse_register (&s, &token.u.regno, NULL))
2978             mips_add_token (&token, OT_REG_INDEX);
2979           else
2980             {
2981               expressionS element;
2982
2983               my_getExpression (&element, s);
2984               if (element.X_op != O_constant)
2985                 {
2986                   set_insn_error (0, _("vector element must be constant"));
2987                   return 0;
2988                 }
2989               s = expr_end;
2990               token.u.index = element.X_add_number;
2991               mips_add_token (&token, OT_INTEGER_INDEX);
2992             }
2993           SKIP_SPACE_TABS (s);
2994           if (*s != ']')
2995             {
2996               set_insn_error (0, _("missing `]'"));
2997               return 0;
2998             }
2999           ++s;
3000         }
3001       return s;
3002     }
3003
3004   if (float_format)
3005     {
3006       /* First try to treat expressions as floats.  */
3007       save_in = input_line_pointer;
3008       input_line_pointer = s;
3009       err = md_atof (float_format, (char *) token.u.flt.data,
3010                      &token.u.flt.length);
3011       end = input_line_pointer;
3012       input_line_pointer = save_in;
3013       if (err && *err)
3014         {
3015           set_insn_error (0, err);
3016           return 0;
3017         }
3018       if (s != end)
3019         {
3020           mips_add_token (&token, OT_FLOAT);
3021           return end;
3022         }
3023     }
3024
3025   /* Treat everything else as an integer expression.  */
3026   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3027   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3028   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3029   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3030   s = expr_end;
3031   mips_add_token (&token, OT_INTEGER);
3032   return s;
3033 }
3034
3035 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3036    if expressions should be treated as 32-bit floating-point constants,
3037    'd' if they should be treated as 64-bit floating-point constants,
3038    or 0 if they should be treated as integer expressions (the usual case).
3039
3040    Return a list of tokens on success, otherwise return 0.  The caller
3041    must obstack_free the list after use.  */
3042
3043 static struct mips_operand_token *
3044 mips_parse_arguments (char *s, char float_format)
3045 {
3046   struct mips_operand_token token;
3047
3048   SKIP_SPACE_TABS (s);
3049   while (*s)
3050     {
3051       s = mips_parse_argument_token (s, float_format);
3052       if (!s)
3053         {
3054           obstack_free (&mips_operand_tokens,
3055                         obstack_finish (&mips_operand_tokens));
3056           return 0;
3057         }
3058       SKIP_SPACE_TABS (s);
3059     }
3060   mips_add_token (&token, OT_END);
3061   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3062 }
3063
3064 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3065    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3066
3067 static bfd_boolean
3068 is_opcode_valid (const struct mips_opcode *mo)
3069 {
3070   int isa = mips_opts.isa;
3071   int ase = mips_opts.ase;
3072   int fp_s, fp_d;
3073   unsigned int i;
3074
3075   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3076     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3077       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3078         ase |= mips_ases[i].flags64;
3079
3080   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3081     return FALSE;
3082
3083   /* Check whether the instruction or macro requires single-precision or
3084      double-precision floating-point support.  Note that this information is
3085      stored differently in the opcode table for insns and macros.  */
3086   if (mo->pinfo == INSN_MACRO)
3087     {
3088       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3089       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3090     }
3091   else
3092     {
3093       fp_s = mo->pinfo & FP_S;
3094       fp_d = mo->pinfo & FP_D;
3095     }
3096
3097   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3098     return FALSE;
3099
3100   if (fp_s && mips_opts.soft_float)
3101     return FALSE;
3102
3103   return TRUE;
3104 }
3105
3106 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3107    selected ISA and architecture.  */
3108
3109 static bfd_boolean
3110 is_opcode_valid_16 (const struct mips_opcode *mo)
3111 {
3112   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3113 }
3114
3115 /* Return TRUE if the size of the microMIPS opcode MO matches one
3116    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3117
3118 static bfd_boolean
3119 is_size_valid (const struct mips_opcode *mo)
3120 {
3121   if (!mips_opts.micromips)
3122     return TRUE;
3123
3124   if (mips_opts.insn32)
3125     {
3126       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3127         return FALSE;
3128       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3129         return FALSE;
3130     }
3131   if (!forced_insn_length)
3132     return TRUE;
3133   if (mo->pinfo == INSN_MACRO)
3134     return FALSE;
3135   return forced_insn_length == micromips_insn_length (mo);
3136 }
3137
3138 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3139    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3140
3141    We don't accept macros in 16-bit delay slots to avoid a case where
3142    a macro expansion fails because it relies on a preceding 32-bit real
3143    instruction to have matched and does not handle the operands correctly.
3144    The only macros that may expand to 16-bit instructions are JAL that
3145    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3146    and BGT (that likewise cannot be placed in a delay slot) that decay to
3147    a NOP.  In all these cases the macros precede any corresponding real
3148    instruction definitions in the opcode table, so they will match in the
3149    second pass where the size of the delay slot is ignored and therefore
3150    produce correct code.  */
3151
3152 static bfd_boolean
3153 is_delay_slot_valid (const struct mips_opcode *mo)
3154 {
3155   if (!mips_opts.micromips)
3156     return TRUE;
3157
3158   if (mo->pinfo == INSN_MACRO)
3159     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3160   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3161       && micromips_insn_length (mo) != 4)
3162     return FALSE;
3163   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3164       && micromips_insn_length (mo) != 2)
3165     return FALSE;
3166
3167   return TRUE;
3168 }
3169
3170 /* For consistency checking, verify that all bits of OPCODE are specified
3171    either by the match/mask part of the instruction definition, or by the
3172    operand list.  Also build up a list of operands in OPERANDS.
3173
3174    INSN_BITS says which bits of the instruction are significant.
3175    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3176    provides the mips_operand description of each operand.  DECODE_OPERAND
3177    is null for MIPS16 instructions.  */
3178
3179 static int
3180 validate_mips_insn (const struct mips_opcode *opcode,
3181                     unsigned long insn_bits,
3182                     const struct mips_operand *(*decode_operand) (const char *),
3183                     struct mips_operand_array *operands)
3184 {
3185   const char *s;
3186   unsigned long used_bits, doubled, undefined, opno, mask;
3187   const struct mips_operand *operand;
3188
3189   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3190   if ((mask & opcode->match) != opcode->match)
3191     {
3192       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3193               opcode->name, opcode->args);
3194       return 0;
3195     }
3196   used_bits = 0;
3197   opno = 0;
3198   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3199     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3200   for (s = opcode->args; *s; ++s)
3201     switch (*s)
3202       {
3203       case ',':
3204       case '(':
3205       case ')':
3206         break;
3207
3208       case '#':
3209         s++;
3210         break;
3211
3212       default:
3213         if (!decode_operand)
3214           operand = decode_mips16_operand (*s, FALSE);
3215         else
3216           operand = decode_operand (s);
3217         if (!operand && opcode->pinfo != INSN_MACRO)
3218           {
3219             as_bad (_("internal: unknown operand type: %s %s"),
3220                     opcode->name, opcode->args);
3221             return 0;
3222           }
3223         gas_assert (opno < MAX_OPERANDS);
3224         operands->operand[opno] = operand;
3225         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3226           {
3227             used_bits = mips_insert_operand (operand, used_bits, -1);
3228             if (operand->type == OP_MDMX_IMM_REG)
3229               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3230                  has separate entries for each format.  */
3231               used_bits &= ~(1 << (operand->lsb + 5));
3232             if (operand->type == OP_ENTRY_EXIT_LIST)
3233               used_bits &= ~(mask & 0x700);
3234           }
3235         /* Skip prefix characters.  */
3236         if (decode_operand && (*s == '+' || *s == 'm'))
3237           ++s;
3238         opno += 1;
3239         break;
3240       }
3241   doubled = used_bits & mask & insn_bits;
3242   if (doubled)
3243     {
3244       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3245                 " %s %s"), doubled, opcode->name, opcode->args);
3246       return 0;
3247     }
3248   used_bits |= mask;
3249   undefined = ~used_bits & insn_bits;
3250   if (opcode->pinfo != INSN_MACRO && undefined)
3251     {
3252       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3253               undefined, opcode->name, opcode->args);
3254       return 0;
3255     }
3256   used_bits &= ~insn_bits;
3257   if (used_bits)
3258     {
3259       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3260               used_bits, opcode->name, opcode->args);
3261       return 0;
3262     }
3263   return 1;
3264 }
3265
3266 /* The MIPS16 version of validate_mips_insn.  */
3267
3268 static int
3269 validate_mips16_insn (const struct mips_opcode *opcode,
3270                       struct mips_operand_array *operands)
3271 {
3272   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3273     {
3274       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3275          instruction.  Use TMP to describe the full instruction.  */
3276       struct mips_opcode tmp;
3277
3278       tmp = *opcode;
3279       tmp.match <<= 16;
3280       tmp.mask <<= 16;
3281       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3282     }
3283   return validate_mips_insn (opcode, 0xffff, 0, operands);
3284 }
3285
3286 /* The microMIPS version of validate_mips_insn.  */
3287
3288 static int
3289 validate_micromips_insn (const struct mips_opcode *opc,
3290                          struct mips_operand_array *operands)
3291 {
3292   unsigned long insn_bits;
3293   unsigned long major;
3294   unsigned int length;
3295
3296   if (opc->pinfo == INSN_MACRO)
3297     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3298                                operands);
3299
3300   length = micromips_insn_length (opc);
3301   if (length != 2 && length != 4)
3302     {
3303       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3304                 "%s %s"), length, opc->name, opc->args);
3305       return 0;
3306     }
3307   major = opc->match >> (10 + 8 * (length - 2));
3308   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3309       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3310     {
3311       as_bad (_("internal error: bad microMIPS opcode "
3312                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3313       return 0;
3314     }
3315
3316   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3317   insn_bits = 1 << 4 * length;
3318   insn_bits <<= 4 * length;
3319   insn_bits -= 1;
3320   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3321                              operands);
3322 }
3323
3324 /* This function is called once, at assembler startup time.  It should set up
3325    all the tables, etc. that the MD part of the assembler will need.  */
3326
3327 void
3328 md_begin (void)
3329 {
3330   const char *retval = NULL;
3331   int i = 0;
3332   int broken = 0;
3333
3334   if (mips_pic != NO_PIC)
3335     {
3336       if (g_switch_seen && g_switch_value != 0)
3337         as_bad (_("-G may not be used in position-independent code"));
3338       g_switch_value = 0;
3339     }
3340
3341   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3342     as_warn (_("could not set architecture and machine"));
3343
3344   op_hash = hash_new ();
3345
3346   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3347   for (i = 0; i < NUMOPCODES;)
3348     {
3349       const char *name = mips_opcodes[i].name;
3350
3351       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3352       if (retval != NULL)
3353         {
3354           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3355                    mips_opcodes[i].name, retval);
3356           /* Probably a memory allocation problem?  Give up now.  */
3357           as_fatal (_("broken assembler, no assembly attempted"));
3358         }
3359       do
3360         {
3361           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3362                                    decode_mips_operand, &mips_operands[i]))
3363             broken = 1;
3364           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3365             {
3366               create_insn (&nop_insn, mips_opcodes + i);
3367               if (mips_fix_loongson2f_nop)
3368                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3369               nop_insn.fixed_p = 1;
3370             }
3371           ++i;
3372         }
3373       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3374     }
3375
3376   mips16_op_hash = hash_new ();
3377   mips16_operands = XCNEWVEC (struct mips_operand_array,
3378                               bfd_mips16_num_opcodes);
3379
3380   i = 0;
3381   while (i < bfd_mips16_num_opcodes)
3382     {
3383       const char *name = mips16_opcodes[i].name;
3384
3385       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3386       if (retval != NULL)
3387         as_fatal (_("internal: can't hash `%s': %s"),
3388                   mips16_opcodes[i].name, retval);
3389       do
3390         {
3391           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3392             broken = 1;
3393           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3394             {
3395               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3396               mips16_nop_insn.fixed_p = 1;
3397             }
3398           ++i;
3399         }
3400       while (i < bfd_mips16_num_opcodes
3401              && strcmp (mips16_opcodes[i].name, name) == 0);
3402     }
3403
3404   micromips_op_hash = hash_new ();
3405   micromips_operands = XCNEWVEC (struct mips_operand_array,
3406                                  bfd_micromips_num_opcodes);
3407
3408   i = 0;
3409   while (i < bfd_micromips_num_opcodes)
3410     {
3411       const char *name = micromips_opcodes[i].name;
3412
3413       retval = hash_insert (micromips_op_hash, name,
3414                             (void *) &micromips_opcodes[i]);
3415       if (retval != NULL)
3416         as_fatal (_("internal: can't hash `%s': %s"),
3417                   micromips_opcodes[i].name, retval);
3418       do
3419         {
3420           struct mips_cl_insn *micromips_nop_insn;
3421
3422           if (!validate_micromips_insn (&micromips_opcodes[i],
3423                                         &micromips_operands[i]))
3424             broken = 1;
3425
3426           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3427             {
3428               if (micromips_insn_length (micromips_opcodes + i) == 2)
3429                 micromips_nop_insn = &micromips_nop16_insn;
3430               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3431                 micromips_nop_insn = &micromips_nop32_insn;
3432               else
3433                 continue;
3434
3435               if (micromips_nop_insn->insn_mo == NULL
3436                   && strcmp (name, "nop") == 0)
3437                 {
3438                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3439                   micromips_nop_insn->fixed_p = 1;
3440                 }
3441             }
3442         }
3443       while (++i < bfd_micromips_num_opcodes
3444              && strcmp (micromips_opcodes[i].name, name) == 0);
3445     }
3446
3447   if (broken)
3448     as_fatal (_("broken assembler, no assembly attempted"));
3449
3450   /* We add all the general register names to the symbol table.  This
3451      helps us detect invalid uses of them.  */
3452   for (i = 0; reg_names[i].name; i++) 
3453     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3454                                      reg_names[i].num, /* & RNUM_MASK, */
3455                                      &zero_address_frag));
3456   if (HAVE_NEWABI)
3457     for (i = 0; reg_names_n32n64[i].name; i++) 
3458       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3459                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3460                                        &zero_address_frag));
3461   else
3462     for (i = 0; reg_names_o32[i].name; i++) 
3463       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3464                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3465                                        &zero_address_frag));
3466
3467   for (i = 0; i < 32; i++)
3468     {
3469       char regname[7];
3470
3471       /* R5900 VU0 floating-point register.  */
3472       regname[sizeof (rename) - 1] = 0;
3473       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3474       symbol_table_insert (symbol_new (regname, reg_section,
3475                                        RTYPE_VF | i, &zero_address_frag));
3476
3477       /* R5900 VU0 integer register.  */
3478       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3479       symbol_table_insert (symbol_new (regname, reg_section,
3480                                        RTYPE_VI | i, &zero_address_frag));
3481
3482       /* MSA register.  */
3483       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3484       symbol_table_insert (symbol_new (regname, reg_section,
3485                                        RTYPE_MSA | i, &zero_address_frag));
3486     }
3487
3488   obstack_init (&mips_operand_tokens);
3489
3490   mips_no_prev_insn ();
3491
3492   mips_gprmask = 0;
3493   mips_cprmask[0] = 0;
3494   mips_cprmask[1] = 0;
3495   mips_cprmask[2] = 0;
3496   mips_cprmask[3] = 0;
3497
3498   /* set the default alignment for the text section (2**2) */
3499   record_alignment (text_section, 2);
3500
3501   bfd_set_gp_size (stdoutput, g_switch_value);
3502
3503   /* On a native system other than VxWorks, sections must be aligned
3504      to 16 byte boundaries.  When configured for an embedded ELF
3505      target, we don't bother.  */
3506   if (strncmp (TARGET_OS, "elf", 3) != 0
3507       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3508     {
3509       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3510       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3511       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3512     }
3513
3514   /* Create a .reginfo section for register masks and a .mdebug
3515      section for debugging information.  */
3516   {
3517     segT seg;
3518     subsegT subseg;
3519     flagword flags;
3520     segT sec;
3521
3522     seg = now_seg;
3523     subseg = now_subseg;
3524
3525     /* The ABI says this section should be loaded so that the
3526        running program can access it.  However, we don't load it
3527        if we are configured for an embedded target */
3528     flags = SEC_READONLY | SEC_DATA;
3529     if (strncmp (TARGET_OS, "elf", 3) != 0)
3530       flags |= SEC_ALLOC | SEC_LOAD;
3531
3532     if (mips_abi != N64_ABI)
3533       {
3534         sec = subseg_new (".reginfo", (subsegT) 0);
3535
3536         bfd_set_section_flags (stdoutput, sec, flags);
3537         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3538
3539         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3540       }
3541     else
3542       {
3543         /* The 64-bit ABI uses a .MIPS.options section rather than
3544            .reginfo section.  */
3545         sec = subseg_new (".MIPS.options", (subsegT) 0);
3546         bfd_set_section_flags (stdoutput, sec, flags);
3547         bfd_set_section_alignment (stdoutput, sec, 3);
3548
3549         /* Set up the option header.  */
3550         {
3551           Elf_Internal_Options opthdr;
3552           char *f;
3553
3554           opthdr.kind = ODK_REGINFO;
3555           opthdr.size = (sizeof (Elf_External_Options)
3556                          + sizeof (Elf64_External_RegInfo));
3557           opthdr.section = 0;
3558           opthdr.info = 0;
3559           f = frag_more (sizeof (Elf_External_Options));
3560           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3561                                          (Elf_External_Options *) f);
3562
3563           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3564         }
3565       }
3566
3567     if (ECOFF_DEBUGGING)
3568       {
3569         sec = subseg_new (".mdebug", (subsegT) 0);
3570         (void) bfd_set_section_flags (stdoutput, sec,
3571                                       SEC_HAS_CONTENTS | SEC_READONLY);
3572         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3573       }
3574     else if (mips_flag_pdr)
3575       {
3576         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3577         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3578                                       SEC_READONLY | SEC_RELOC
3579                                       | SEC_DEBUGGING);
3580         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3581       }
3582
3583     subseg_set (seg, subseg);
3584   }
3585
3586   if (! ECOFF_DEBUGGING)
3587     md_obj_begin ();
3588
3589   if (mips_fix_vr4120)
3590     init_vr4120_conflicts ();
3591 }
3592
3593 void
3594 md_mips_end (void)
3595 {
3596   mips_emit_delays ();
3597   if (! ECOFF_DEBUGGING)
3598     md_obj_end ();
3599 }
3600
3601 void
3602 md_assemble (char *str)
3603 {
3604   struct mips_cl_insn insn;
3605   bfd_reloc_code_real_type unused_reloc[3]
3606     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3607
3608   imm_expr.X_op = O_absent;
3609   offset_expr.X_op = O_absent;
3610   offset_reloc[0] = BFD_RELOC_UNUSED;
3611   offset_reloc[1] = BFD_RELOC_UNUSED;
3612   offset_reloc[2] = BFD_RELOC_UNUSED;
3613
3614   mips_mark_labels ();
3615   mips_assembling_insn = TRUE;
3616   clear_insn_error ();
3617
3618   if (mips_opts.mips16)
3619     mips16_ip (str, &insn);
3620   else
3621     {
3622       mips_ip (str, &insn);
3623       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3624             str, insn.insn_opcode));
3625     }
3626
3627   if (insn_error.msg)
3628     report_insn_error (str);
3629   else if (insn.insn_mo->pinfo == INSN_MACRO)
3630     {
3631       macro_start ();
3632       if (mips_opts.mips16)
3633         mips16_macro (&insn);
3634       else
3635         macro (&insn, str);
3636       macro_end ();
3637     }
3638   else
3639     {
3640       if (offset_expr.X_op != O_absent)
3641         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3642       else
3643         append_insn (&insn, NULL, unused_reloc, FALSE);
3644     }
3645
3646   mips_assembling_insn = FALSE;
3647 }
3648
3649 /* Convenience functions for abstracting away the differences between
3650    MIPS16 and non-MIPS16 relocations.  */
3651
3652 static inline bfd_boolean
3653 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3654 {
3655   switch (reloc)
3656     {
3657     case BFD_RELOC_MIPS16_JMP:
3658     case BFD_RELOC_MIPS16_GPREL:
3659     case BFD_RELOC_MIPS16_GOT16:
3660     case BFD_RELOC_MIPS16_CALL16:
3661     case BFD_RELOC_MIPS16_HI16_S:
3662     case BFD_RELOC_MIPS16_HI16:
3663     case BFD_RELOC_MIPS16_LO16:
3664       return TRUE;
3665
3666     default:
3667       return FALSE;
3668     }
3669 }
3670
3671 static inline bfd_boolean
3672 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3673 {
3674   switch (reloc)
3675     {
3676     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3677     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3678     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3679     case BFD_RELOC_MICROMIPS_GPREL16:
3680     case BFD_RELOC_MICROMIPS_JMP:
3681     case BFD_RELOC_MICROMIPS_HI16:
3682     case BFD_RELOC_MICROMIPS_HI16_S:
3683     case BFD_RELOC_MICROMIPS_LO16:
3684     case BFD_RELOC_MICROMIPS_LITERAL:
3685     case BFD_RELOC_MICROMIPS_GOT16:
3686     case BFD_RELOC_MICROMIPS_CALL16:
3687     case BFD_RELOC_MICROMIPS_GOT_HI16:
3688     case BFD_RELOC_MICROMIPS_GOT_LO16:
3689     case BFD_RELOC_MICROMIPS_CALL_HI16:
3690     case BFD_RELOC_MICROMIPS_CALL_LO16:
3691     case BFD_RELOC_MICROMIPS_SUB:
3692     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3693     case BFD_RELOC_MICROMIPS_GOT_OFST:
3694     case BFD_RELOC_MICROMIPS_GOT_DISP:
3695     case BFD_RELOC_MICROMIPS_HIGHEST:
3696     case BFD_RELOC_MICROMIPS_HIGHER:
3697     case BFD_RELOC_MICROMIPS_SCN_DISP:
3698     case BFD_RELOC_MICROMIPS_JALR:
3699       return TRUE;
3700
3701     default:
3702       return FALSE;
3703     }
3704 }
3705
3706 static inline bfd_boolean
3707 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3708 {
3709   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3710 }
3711
3712 static inline bfd_boolean
3713 got16_reloc_p (bfd_reloc_code_real_type reloc)
3714 {
3715   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3716           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3717 }
3718
3719 static inline bfd_boolean
3720 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3721 {
3722   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3723           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3724 }
3725
3726 static inline bfd_boolean
3727 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3728 {
3729   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3730           || reloc == BFD_RELOC_MICROMIPS_LO16);
3731 }
3732
3733 static inline bfd_boolean
3734 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3735 {
3736   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3737 }
3738
3739 static inline bfd_boolean
3740 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3741 {
3742   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3743           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3744 }
3745
3746 /* Return true if RELOC is a PC-relative relocation that does not have
3747    full address range.  */
3748
3749 static inline bfd_boolean
3750 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3751 {
3752   switch (reloc)
3753     {
3754     case BFD_RELOC_16_PCREL_S2:
3755     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3756     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3757     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3758       return TRUE;
3759
3760     case BFD_RELOC_32_PCREL:
3761       return HAVE_64BIT_ADDRESSES;
3762
3763     default:
3764       return FALSE;
3765     }
3766 }
3767
3768 /* Return true if the given relocation might need a matching %lo().
3769    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3770    need a matching %lo() when applied to local symbols.  */
3771
3772 static inline bfd_boolean
3773 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3774 {
3775   return (HAVE_IN_PLACE_ADDENDS
3776           && (hi16_reloc_p (reloc)
3777               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3778                  all GOT16 relocations evaluate to "G".  */
3779               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3780 }
3781
3782 /* Return the type of %lo() reloc needed by RELOC, given that
3783    reloc_needs_lo_p.  */
3784
3785 static inline bfd_reloc_code_real_type
3786 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3787 {
3788   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3789           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3790              : BFD_RELOC_LO16));
3791 }
3792
3793 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3794    relocation.  */
3795
3796 static inline bfd_boolean
3797 fixup_has_matching_lo_p (fixS *fixp)
3798 {
3799   return (fixp->fx_next != NULL
3800           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3801           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3802           && fixp->fx_offset == fixp->fx_next->fx_offset);
3803 }
3804
3805 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3806    says whether the labels refer to text or data.  */
3807
3808 static void
3809 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3810 {
3811   struct insn_label_list *l;
3812   valueT val;
3813
3814   for (l = labels; l != NULL; l = l->next)
3815     {
3816       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3817       symbol_set_frag (l->label, frag_now);
3818       val = (valueT) frag_now_fix ();
3819       /* MIPS16/microMIPS text labels are stored as odd.  */
3820       if (text_p && HAVE_CODE_COMPRESSION)
3821         ++val;
3822       S_SET_VALUE (l->label, val);
3823     }
3824 }
3825
3826 /* Move all labels in insn_labels to the current insertion point
3827    and treat them as text labels.  */
3828
3829 static void
3830 mips_move_text_labels (void)
3831 {
3832   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3833 }
3834
3835 static bfd_boolean
3836 s_is_linkonce (symbolS *sym, segT from_seg)
3837 {
3838   bfd_boolean linkonce = FALSE;
3839   segT symseg = S_GET_SEGMENT (sym);
3840
3841   if (symseg != from_seg && !S_IS_LOCAL (sym))
3842     {
3843       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3844         linkonce = TRUE;
3845       /* The GNU toolchain uses an extension for ELF: a section
3846          beginning with the magic string .gnu.linkonce is a
3847          linkonce section.  */
3848       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3849                    sizeof ".gnu.linkonce" - 1) == 0)
3850         linkonce = TRUE;
3851     }
3852   return linkonce;
3853 }
3854
3855 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3856    linker to handle them specially, such as generating jalx instructions
3857    when needed.  We also make them odd for the duration of the assembly,
3858    in order to generate the right sort of code.  We will make them even
3859    in the adjust_symtab routine, while leaving them marked.  This is
3860    convenient for the debugger and the disassembler.  The linker knows
3861    to make them odd again.  */
3862
3863 static void
3864 mips_compressed_mark_label (symbolS *label)
3865 {
3866   gas_assert (HAVE_CODE_COMPRESSION);
3867
3868   if (mips_opts.mips16)
3869     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3870   else
3871     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3872   if ((S_GET_VALUE (label) & 1) == 0
3873       /* Don't adjust the address if the label is global or weak, or
3874          in a link-once section, since we'll be emitting symbol reloc
3875          references to it which will be patched up by the linker, and
3876          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3877       && !S_IS_WEAK (label)
3878       && !S_IS_EXTERNAL (label)
3879       && !s_is_linkonce (label, now_seg))
3880     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3881 }
3882
3883 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3884
3885 static void
3886 mips_compressed_mark_labels (void)
3887 {
3888   struct insn_label_list *l;
3889
3890   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3891     mips_compressed_mark_label (l->label);
3892 }
3893
3894 /* End the current frag.  Make it a variant frag and record the
3895    relaxation info.  */
3896
3897 static void
3898 relax_close_frag (void)
3899 {
3900   mips_macro_warning.first_frag = frag_now;
3901   frag_var (rs_machine_dependent, 0, 0,
3902             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3903             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3904
3905   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3906   mips_relax.first_fixup = 0;
3907 }
3908
3909 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3910    See the comment above RELAX_ENCODE for more details.  */
3911
3912 static void
3913 relax_start (symbolS *symbol)
3914 {
3915   gas_assert (mips_relax.sequence == 0);
3916   mips_relax.sequence = 1;
3917   mips_relax.symbol = symbol;
3918 }
3919
3920 /* Start generating the second version of a relaxable sequence.
3921    See the comment above RELAX_ENCODE for more details.  */
3922
3923 static void
3924 relax_switch (void)
3925 {
3926   gas_assert (mips_relax.sequence == 1);
3927   mips_relax.sequence = 2;
3928 }
3929
3930 /* End the current relaxable sequence.  */
3931
3932 static void
3933 relax_end (void)
3934 {
3935   gas_assert (mips_relax.sequence == 2);
3936   relax_close_frag ();
3937   mips_relax.sequence = 0;
3938 }
3939
3940 /* Return true if IP is a delayed branch or jump.  */
3941
3942 static inline bfd_boolean
3943 delayed_branch_p (const struct mips_cl_insn *ip)
3944 {
3945   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3946                                 | INSN_COND_BRANCH_DELAY
3947                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3948 }
3949
3950 /* Return true if IP is a compact branch or jump.  */
3951
3952 static inline bfd_boolean
3953 compact_branch_p (const struct mips_cl_insn *ip)
3954 {
3955   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3956                                  | INSN2_COND_BRANCH)) != 0;
3957 }
3958
3959 /* Return true if IP is an unconditional branch or jump.  */
3960
3961 static inline bfd_boolean
3962 uncond_branch_p (const struct mips_cl_insn *ip)
3963 {
3964   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3965           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3966 }
3967
3968 /* Return true if IP is a branch-likely instruction.  */
3969
3970 static inline bfd_boolean
3971 branch_likely_p (const struct mips_cl_insn *ip)
3972 {
3973   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3974 }
3975
3976 /* Return the type of nop that should be used to fill the delay slot
3977    of delayed branch IP.  */
3978
3979 static struct mips_cl_insn *
3980 get_delay_slot_nop (const struct mips_cl_insn *ip)
3981 {
3982   if (mips_opts.micromips
3983       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3984     return &micromips_nop32_insn;
3985   return NOP_INSN;
3986 }
3987
3988 /* Return a mask that has bit N set if OPCODE reads the register(s)
3989    in operand N.  */
3990
3991 static unsigned int
3992 insn_read_mask (const struct mips_opcode *opcode)
3993 {
3994   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3995 }
3996
3997 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3998    in operand N.  */
3999
4000 static unsigned int
4001 insn_write_mask (const struct mips_opcode *opcode)
4002 {
4003   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4004 }
4005
4006 /* Return a mask of the registers specified by operand OPERAND of INSN.
4007    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4008    is set.  */
4009
4010 static unsigned int
4011 operand_reg_mask (const struct mips_cl_insn *insn,
4012                   const struct mips_operand *operand,
4013                   unsigned int type_mask)
4014 {
4015   unsigned int uval, vsel;
4016
4017   switch (operand->type)
4018     {
4019     case OP_INT:
4020     case OP_MAPPED_INT:
4021     case OP_MSB:
4022     case OP_PCREL:
4023     case OP_PERF_REG:
4024     case OP_ADDIUSP_INT:
4025     case OP_ENTRY_EXIT_LIST:
4026     case OP_REPEAT_DEST_REG:
4027     case OP_REPEAT_PREV_REG:
4028     case OP_PC:
4029     case OP_VU0_SUFFIX:
4030     case OP_VU0_MATCH_SUFFIX:
4031     case OP_IMM_INDEX:
4032       abort ();
4033
4034     case OP_REG:
4035     case OP_OPTIONAL_REG:
4036       {
4037         const struct mips_reg_operand *reg_op;
4038
4039         reg_op = (const struct mips_reg_operand *) operand;
4040         if (!(type_mask & (1 << reg_op->reg_type)))
4041           return 0;
4042         uval = insn_extract_operand (insn, operand);
4043         return 1 << mips_decode_reg_operand (reg_op, uval);
4044       }
4045
4046     case OP_REG_PAIR:
4047       {
4048         const struct mips_reg_pair_operand *pair_op;
4049
4050         pair_op = (const struct mips_reg_pair_operand *) operand;
4051         if (!(type_mask & (1 << pair_op->reg_type)))
4052           return 0;
4053         uval = insn_extract_operand (insn, operand);
4054         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4055       }
4056
4057     case OP_CLO_CLZ_DEST:
4058       if (!(type_mask & (1 << OP_REG_GP)))
4059         return 0;
4060       uval = insn_extract_operand (insn, operand);
4061       return (1 << (uval & 31)) | (1 << (uval >> 5));
4062
4063     case OP_LWM_SWM_LIST:
4064       abort ();
4065
4066     case OP_SAVE_RESTORE_LIST:
4067       abort ();
4068
4069     case OP_MDMX_IMM_REG:
4070       if (!(type_mask & (1 << OP_REG_VEC)))
4071         return 0;
4072       uval = insn_extract_operand (insn, operand);
4073       vsel = uval >> 5;
4074       if ((vsel & 0x18) == 0x18)
4075         return 0;
4076       return 1 << (uval & 31);
4077
4078     case OP_REG_INDEX:
4079       if (!(type_mask & (1 << OP_REG_GP)))
4080         return 0;
4081       return 1 << insn_extract_operand (insn, operand);
4082     }
4083   abort ();
4084 }
4085
4086 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4087    where bit N of OPNO_MASK is set if operand N should be included.
4088    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4089    is set.  */
4090
4091 static unsigned int
4092 insn_reg_mask (const struct mips_cl_insn *insn,
4093                unsigned int type_mask, unsigned int opno_mask)
4094 {
4095   unsigned int opno, reg_mask;
4096
4097   opno = 0;
4098   reg_mask = 0;
4099   while (opno_mask != 0)
4100     {
4101       if (opno_mask & 1)
4102         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4103       opno_mask >>= 1;
4104       opno += 1;
4105     }
4106   return reg_mask;
4107 }
4108
4109 /* Return the mask of core registers that IP reads.  */
4110
4111 static unsigned int
4112 gpr_read_mask (const struct mips_cl_insn *ip)
4113 {
4114   unsigned long pinfo, pinfo2;
4115   unsigned int mask;
4116
4117   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4118   pinfo = ip->insn_mo->pinfo;
4119   pinfo2 = ip->insn_mo->pinfo2;
4120   if (pinfo & INSN_UDI)
4121     {
4122       /* UDI instructions have traditionally been assumed to read RS
4123          and RT.  */
4124       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4125       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4126     }
4127   if (pinfo & INSN_READ_GPR_24)
4128     mask |= 1 << 24;
4129   if (pinfo2 & INSN2_READ_GPR_16)
4130     mask |= 1 << 16;
4131   if (pinfo2 & INSN2_READ_SP)
4132     mask |= 1 << SP;
4133   if (pinfo2 & INSN2_READ_GPR_31)
4134     mask |= 1 << 31;
4135   /* Don't include register 0.  */
4136   return mask & ~1;
4137 }
4138
4139 /* Return the mask of core registers that IP writes.  */
4140
4141 static unsigned int
4142 gpr_write_mask (const struct mips_cl_insn *ip)
4143 {
4144   unsigned long pinfo, pinfo2;
4145   unsigned int mask;
4146
4147   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4148   pinfo = ip->insn_mo->pinfo;
4149   pinfo2 = ip->insn_mo->pinfo2;
4150   if (pinfo & INSN_WRITE_GPR_24)
4151     mask |= 1 << 24;
4152   if (pinfo & INSN_WRITE_GPR_31)
4153     mask |= 1 << 31;
4154   if (pinfo & INSN_UDI)
4155     /* UDI instructions have traditionally been assumed to write to RD.  */
4156     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4157   if (pinfo2 & INSN2_WRITE_SP)
4158     mask |= 1 << SP;
4159   /* Don't include register 0.  */
4160   return mask & ~1;
4161 }
4162
4163 /* Return the mask of floating-point registers that IP reads.  */
4164
4165 static unsigned int
4166 fpr_read_mask (const struct mips_cl_insn *ip)
4167 {
4168   unsigned long pinfo;
4169   unsigned int mask;
4170
4171   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4172                              | (1 << OP_REG_MSA)),
4173                         insn_read_mask (ip->insn_mo));
4174   pinfo = ip->insn_mo->pinfo;
4175   /* Conservatively treat all operands to an FP_D instruction are doubles.
4176      (This is overly pessimistic for things like cvt.d.s.)  */
4177   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4178     mask |= mask << 1;
4179   return mask;
4180 }
4181
4182 /* Return the mask of floating-point registers that IP writes.  */
4183
4184 static unsigned int
4185 fpr_write_mask (const struct mips_cl_insn *ip)
4186 {
4187   unsigned long pinfo;
4188   unsigned int mask;
4189
4190   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4191                              | (1 << OP_REG_MSA)),
4192                         insn_write_mask (ip->insn_mo));
4193   pinfo = ip->insn_mo->pinfo;
4194   /* Conservatively treat all operands to an FP_D instruction are doubles.
4195      (This is overly pessimistic for things like cvt.s.d.)  */
4196   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4197     mask |= mask << 1;
4198   return mask;
4199 }
4200
4201 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4202    Check whether that is allowed.  */
4203
4204 static bfd_boolean
4205 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4206 {
4207   const char *s = insn->name;
4208
4209   if (insn->pinfo == INSN_MACRO)
4210     /* Let a macro pass, we'll catch it later when it is expanded.  */
4211     return TRUE;
4212
4213   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4214     {
4215       /* Allow odd registers for single-precision ops.  */
4216       switch (insn->pinfo & (FP_S | FP_D))
4217         {
4218         case FP_S:
4219         case 0:
4220           return TRUE;
4221         case FP_D:
4222           return FALSE;
4223         default:
4224           break;
4225         }
4226
4227       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4228       s = strchr (insn->name, '.');
4229       if (s != NULL && opnum == 2)
4230         s = strchr (s + 1, '.');
4231       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4232     }
4233
4234   /* Single-precision coprocessor loads and moves are OK too.  */
4235   if ((insn->pinfo & FP_S)
4236       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4237                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4238     return TRUE;
4239
4240   return FALSE;
4241 }
4242
4243 /* Information about an instruction argument that we're trying to match.  */
4244 struct mips_arg_info
4245 {
4246   /* The instruction so far.  */
4247   struct mips_cl_insn *insn;
4248
4249   /* The first unconsumed operand token.  */
4250   struct mips_operand_token *token;
4251
4252   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4253   int opnum;
4254
4255   /* The 1-based argument number, for error reporting.  This does not
4256      count elided optional registers, etc..  */
4257   int argnum;
4258
4259   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4260   unsigned int last_regno;
4261
4262   /* If the first operand was an OP_REG, this is the register that it
4263      specified, otherwise it is ILLEGAL_REG.  */
4264   unsigned int dest_regno;
4265
4266   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4267      where it gives the lsb position.  */
4268   unsigned int last_op_int;
4269
4270   /* If true, match routines should assume that no later instruction
4271      alternative matches and should therefore be as accomodating as
4272      possible.  Match routines should not report errors if something
4273      is only invalid for !LAX_MATCH.  */
4274   bfd_boolean lax_match;
4275
4276   /* True if a reference to the current AT register was seen.  */
4277   bfd_boolean seen_at;
4278 };
4279
4280 /* Record that the argument is out of range.  */
4281
4282 static void
4283 match_out_of_range (struct mips_arg_info *arg)
4284 {
4285   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4286 }
4287
4288 /* Record that the argument isn't constant but needs to be.  */
4289
4290 static void
4291 match_not_constant (struct mips_arg_info *arg)
4292 {
4293   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4294                     arg->argnum);
4295 }
4296
4297 /* Try to match an OT_CHAR token for character CH.  Consume the token
4298    and return true on success, otherwise return false.  */
4299
4300 static bfd_boolean
4301 match_char (struct mips_arg_info *arg, char ch)
4302 {
4303   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4304     {
4305       ++arg->token;
4306       if (ch == ',')
4307         arg->argnum += 1;
4308       return TRUE;
4309     }
4310   return FALSE;
4311 }
4312
4313 /* Try to get an expression from the next tokens in ARG.  Consume the
4314    tokens and return true on success, storing the expression value in
4315    VALUE and relocation types in R.  */
4316
4317 static bfd_boolean
4318 match_expression (struct mips_arg_info *arg, expressionS *value,
4319                   bfd_reloc_code_real_type *r)
4320 {
4321   /* If the next token is a '(' that was parsed as being part of a base
4322      expression, assume we have an elided offset.  The later match will fail
4323      if this turns out to be wrong.  */
4324   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4325     {
4326       value->X_op = O_constant;
4327       value->X_add_number = 0;
4328       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4329       return TRUE;
4330     }
4331
4332   /* Reject register-based expressions such as "0+$2" and "(($2))".
4333      For plain registers the default error seems more appropriate.  */
4334   if (arg->token->type == OT_INTEGER
4335       && arg->token->u.integer.value.X_op == O_register)
4336     {
4337       set_insn_error (arg->argnum, _("register value used as expression"));
4338       return FALSE;
4339     }
4340
4341   if (arg->token->type == OT_INTEGER)
4342     {
4343       *value = arg->token->u.integer.value;
4344       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4345       ++arg->token;
4346       return TRUE;
4347     }
4348
4349   set_insn_error_i
4350     (arg->argnum, _("operand %d must be an immediate expression"),
4351      arg->argnum);
4352   return FALSE;
4353 }
4354
4355 /* Try to get a constant expression from the next tokens in ARG.  Consume
4356    the tokens and return return true on success, storing the constant value
4357    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4358    error.  */
4359
4360 static bfd_boolean
4361 match_const_int (struct mips_arg_info *arg, offsetT *value)
4362 {
4363   expressionS ex;
4364   bfd_reloc_code_real_type r[3];
4365
4366   if (!match_expression (arg, &ex, r))
4367     return FALSE;
4368
4369   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4370     *value = ex.X_add_number;
4371   else
4372     {
4373       match_not_constant (arg);
4374       return FALSE;
4375     }
4376   return TRUE;
4377 }
4378
4379 /* Return the RTYPE_* flags for a register operand of type TYPE that
4380    appears in instruction OPCODE.  */
4381
4382 static unsigned int
4383 convert_reg_type (const struct mips_opcode *opcode,
4384                   enum mips_reg_operand_type type)
4385 {
4386   switch (type)
4387     {
4388     case OP_REG_GP:
4389       return RTYPE_NUM | RTYPE_GP;
4390
4391     case OP_REG_FP:
4392       /* Allow vector register names for MDMX if the instruction is a 64-bit
4393          FPR load, store or move (including moves to and from GPRs).  */
4394       if ((mips_opts.ase & ASE_MDMX)
4395           && (opcode->pinfo & FP_D)
4396           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4397                                | INSN_COPROC_MEMORY_DELAY
4398                                | INSN_LOAD_COPROC_DELAY
4399                                | INSN_LOAD_MEMORY
4400                                | INSN_STORE_MEMORY)))
4401         return RTYPE_FPU | RTYPE_VEC;
4402       return RTYPE_FPU;
4403
4404     case OP_REG_CCC:
4405       if (opcode->pinfo & (FP_D | FP_S))
4406         return RTYPE_CCC | RTYPE_FCC;
4407       return RTYPE_CCC;
4408
4409     case OP_REG_VEC:
4410       if (opcode->membership & INSN_5400)
4411         return RTYPE_FPU;
4412       return RTYPE_FPU | RTYPE_VEC;
4413
4414     case OP_REG_ACC:
4415       return RTYPE_ACC;
4416
4417     case OP_REG_COPRO:
4418       if (opcode->name[strlen (opcode->name) - 1] == '0')
4419         return RTYPE_NUM | RTYPE_CP0;
4420       return RTYPE_NUM;
4421
4422     case OP_REG_HW:
4423       return RTYPE_NUM;
4424
4425     case OP_REG_VI:
4426       return RTYPE_NUM | RTYPE_VI;
4427
4428     case OP_REG_VF:
4429       return RTYPE_NUM | RTYPE_VF;
4430
4431     case OP_REG_R5900_I:
4432       return RTYPE_R5900_I;
4433
4434     case OP_REG_R5900_Q:
4435       return RTYPE_R5900_Q;
4436
4437     case OP_REG_R5900_R:
4438       return RTYPE_R5900_R;
4439
4440     case OP_REG_R5900_ACC:
4441       return RTYPE_R5900_ACC;
4442
4443     case OP_REG_MSA:
4444       return RTYPE_MSA;
4445
4446     case OP_REG_MSA_CTRL:
4447       return RTYPE_NUM;
4448     }
4449   abort ();
4450 }
4451
4452 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4453
4454 static void
4455 check_regno (struct mips_arg_info *arg,
4456              enum mips_reg_operand_type type, unsigned int regno)
4457 {
4458   if (AT && type == OP_REG_GP && regno == AT)
4459     arg->seen_at = TRUE;
4460
4461   if (type == OP_REG_FP
4462       && (regno & 1) != 0
4463       && HAVE_32BIT_FPRS
4464       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4465     as_warn (_("float register should be even, was %d"), regno);
4466
4467   if (type == OP_REG_CCC)
4468     {
4469       const char *name;
4470       size_t length;
4471
4472       name = arg->insn->insn_mo->name;
4473       length = strlen (name);
4474       if ((regno & 1) != 0
4475           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4476               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4477         as_warn (_("condition code register should be even for %s, was %d"),
4478                  name, regno);
4479
4480       if ((regno & 3) != 0
4481           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4482         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4483                  name, regno);
4484     }
4485 }
4486
4487 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4488    a register of type TYPE.  Return true on success, storing the register
4489    number in *REGNO and warning about any dubious uses.  */
4490
4491 static bfd_boolean
4492 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4493              unsigned int symval, unsigned int *regno)
4494 {
4495   if (type == OP_REG_VEC)
4496     symval = mips_prefer_vec_regno (symval);
4497   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4498     return FALSE;
4499
4500   *regno = symval & RNUM_MASK;
4501   check_regno (arg, type, *regno);
4502   return TRUE;
4503 }
4504
4505 /* Try to interpret the next token in ARG as a register of type TYPE.
4506    Consume the token and return true on success, storing the register
4507    number in *REGNO.  Return false on failure.  */
4508
4509 static bfd_boolean
4510 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4511            unsigned int *regno)
4512 {
4513   if (arg->token->type == OT_REG
4514       && match_regno (arg, type, arg->token->u.regno, regno))
4515     {
4516       ++arg->token;
4517       return TRUE;
4518     }
4519   return FALSE;
4520 }
4521
4522 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4523    Consume the token and return true on success, storing the register numbers
4524    in *REGNO1 and *REGNO2.  Return false on failure.  */
4525
4526 static bfd_boolean
4527 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4528                  unsigned int *regno1, unsigned int *regno2)
4529 {
4530   if (match_reg (arg, type, regno1))
4531     {
4532       *regno2 = *regno1;
4533       return TRUE;
4534     }
4535   if (arg->token->type == OT_REG_RANGE
4536       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4537       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4538       && *regno1 <= *regno2)
4539     {
4540       ++arg->token;
4541       return TRUE;
4542     }
4543   return FALSE;
4544 }
4545
4546 /* OP_INT matcher.  */
4547
4548 static bfd_boolean
4549 match_int_operand (struct mips_arg_info *arg,
4550                    const struct mips_operand *operand_base)
4551 {
4552   const struct mips_int_operand *operand;
4553   unsigned int uval;
4554   int min_val, max_val, factor;
4555   offsetT sval;
4556
4557   operand = (const struct mips_int_operand *) operand_base;
4558   factor = 1 << operand->shift;
4559   min_val = mips_int_operand_min (operand);
4560   max_val = mips_int_operand_max (operand);
4561
4562   if (operand_base->lsb == 0
4563       && operand_base->size == 16
4564       && operand->shift == 0
4565       && operand->bias == 0
4566       && (operand->max_val == 32767 || operand->max_val == 65535))
4567     {
4568       /* The operand can be relocated.  */
4569       if (!match_expression (arg, &offset_expr, offset_reloc))
4570         return FALSE;
4571
4572       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4573         /* Relocation operators were used.  Accept the arguent and
4574            leave the relocation value in offset_expr and offset_relocs
4575            for the caller to process.  */
4576         return TRUE;
4577
4578       if (offset_expr.X_op != O_constant)
4579         {
4580           /* Accept non-constant operands if no later alternative matches,
4581              leaving it for the caller to process.  */
4582           if (!arg->lax_match)
4583             return FALSE;
4584           offset_reloc[0] = BFD_RELOC_LO16;
4585           return TRUE;
4586         }
4587
4588       /* Clear the global state; we're going to install the operand
4589          ourselves.  */
4590       sval = offset_expr.X_add_number;
4591       offset_expr.X_op = O_absent;
4592
4593       /* For compatibility with older assemblers, we accept
4594          0x8000-0xffff as signed 16-bit numbers when only
4595          signed numbers are allowed.  */
4596       if (sval > max_val)
4597         {
4598           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4599           if (!arg->lax_match && sval <= max_val)
4600             return FALSE;
4601         }
4602     }
4603   else
4604     {
4605       if (!match_const_int (arg, &sval))
4606         return FALSE;
4607     }
4608
4609   arg->last_op_int = sval;
4610
4611   if (sval < min_val || sval > max_val || sval % factor)
4612     {
4613       match_out_of_range (arg);
4614       return FALSE;
4615     }
4616
4617   uval = (unsigned int) sval >> operand->shift;
4618   uval -= operand->bias;
4619
4620   /* Handle -mfix-cn63xxp1.  */
4621   if (arg->opnum == 1
4622       && mips_fix_cn63xxp1
4623       && !mips_opts.micromips
4624       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4625     switch (uval)
4626       {
4627       case 5:
4628       case 25:
4629       case 26:
4630       case 27:
4631       case 28:
4632       case 29:
4633       case 30:
4634       case 31:
4635         /* These are ok.  */
4636         break;
4637
4638       default:
4639         /* The rest must be changed to 28.  */
4640         uval = 28;
4641         break;
4642       }
4643
4644   insn_insert_operand (arg->insn, operand_base, uval);
4645   return TRUE;
4646 }
4647
4648 /* OP_MAPPED_INT matcher.  */
4649
4650 static bfd_boolean
4651 match_mapped_int_operand (struct mips_arg_info *arg,
4652                           const struct mips_operand *operand_base)
4653 {
4654   const struct mips_mapped_int_operand *operand;
4655   unsigned int uval, num_vals;
4656   offsetT sval;
4657
4658   operand = (const struct mips_mapped_int_operand *) operand_base;
4659   if (!match_const_int (arg, &sval))
4660     return FALSE;
4661
4662   num_vals = 1 << operand_base->size;
4663   for (uval = 0; uval < num_vals; uval++)
4664     if (operand->int_map[uval] == sval)
4665       break;
4666   if (uval == num_vals)
4667     {
4668       match_out_of_range (arg);
4669       return FALSE;
4670     }
4671
4672   insn_insert_operand (arg->insn, operand_base, uval);
4673   return TRUE;
4674 }
4675
4676 /* OP_MSB matcher.  */
4677
4678 static bfd_boolean
4679 match_msb_operand (struct mips_arg_info *arg,
4680                    const struct mips_operand *operand_base)
4681 {
4682   const struct mips_msb_operand *operand;
4683   int min_val, max_val, max_high;
4684   offsetT size, sval, high;
4685
4686   operand = (const struct mips_msb_operand *) operand_base;
4687   min_val = operand->bias;
4688   max_val = min_val + (1 << operand_base->size) - 1;
4689   max_high = operand->opsize;
4690
4691   if (!match_const_int (arg, &size))
4692     return FALSE;
4693
4694   high = size + arg->last_op_int;
4695   sval = operand->add_lsb ? high : size;
4696
4697   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4698     {
4699       match_out_of_range (arg);
4700       return FALSE;
4701     }
4702   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4703   return TRUE;
4704 }
4705
4706 /* OP_REG matcher.  */
4707
4708 static bfd_boolean
4709 match_reg_operand (struct mips_arg_info *arg,
4710                    const struct mips_operand *operand_base)
4711 {
4712   const struct mips_reg_operand *operand;
4713   unsigned int regno, uval, num_vals;
4714
4715   operand = (const struct mips_reg_operand *) operand_base;
4716   if (!match_reg (arg, operand->reg_type, &regno))
4717     return FALSE;
4718
4719   if (operand->reg_map)
4720     {
4721       num_vals = 1 << operand->root.size;
4722       for (uval = 0; uval < num_vals; uval++)
4723         if (operand->reg_map[uval] == regno)
4724           break;
4725       if (num_vals == uval)
4726         return FALSE;
4727     }
4728   else
4729     uval = regno;
4730
4731   arg->last_regno = regno;
4732   if (arg->opnum == 1)
4733     arg->dest_regno = regno;
4734   insn_insert_operand (arg->insn, operand_base, uval);
4735   return TRUE;
4736 }
4737
4738 /* OP_REG_PAIR matcher.  */
4739
4740 static bfd_boolean
4741 match_reg_pair_operand (struct mips_arg_info *arg,
4742                         const struct mips_operand *operand_base)
4743 {
4744   const struct mips_reg_pair_operand *operand;
4745   unsigned int regno1, regno2, uval, num_vals;
4746
4747   operand = (const struct mips_reg_pair_operand *) operand_base;
4748   if (!match_reg (arg, operand->reg_type, &regno1)
4749       || !match_char (arg, ',')
4750       || !match_reg (arg, operand->reg_type, &regno2))
4751     return FALSE;
4752
4753   num_vals = 1 << operand_base->size;
4754   for (uval = 0; uval < num_vals; uval++)
4755     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4756       break;
4757   if (uval == num_vals)
4758     return FALSE;
4759
4760   insn_insert_operand (arg->insn, operand_base, uval);
4761   return TRUE;
4762 }
4763
4764 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4765
4766 static bfd_boolean
4767 match_pcrel_operand (struct mips_arg_info *arg)
4768 {
4769   bfd_reloc_code_real_type r[3];
4770
4771   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4772 }
4773
4774 /* OP_PERF_REG matcher.  */
4775
4776 static bfd_boolean
4777 match_perf_reg_operand (struct mips_arg_info *arg,
4778                         const struct mips_operand *operand)
4779 {
4780   offsetT sval;
4781
4782   if (!match_const_int (arg, &sval))
4783     return FALSE;
4784
4785   if (sval != 0
4786       && (sval != 1
4787           || (mips_opts.arch == CPU_R5900
4788               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4789                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4790     {
4791       set_insn_error (arg->argnum, _("invalid performance register"));
4792       return FALSE;
4793     }
4794
4795   insn_insert_operand (arg->insn, operand, sval);
4796   return TRUE;
4797 }
4798
4799 /* OP_ADDIUSP matcher.  */
4800
4801 static bfd_boolean
4802 match_addiusp_operand (struct mips_arg_info *arg,
4803                        const struct mips_operand *operand)
4804 {
4805   offsetT sval;
4806   unsigned int uval;
4807
4808   if (!match_const_int (arg, &sval))
4809     return FALSE;
4810
4811   if (sval % 4)
4812     {
4813       match_out_of_range (arg);
4814       return FALSE;
4815     }
4816
4817   sval /= 4;
4818   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4819     {
4820       match_out_of_range (arg);
4821       return FALSE;
4822     }
4823
4824   uval = (unsigned int) sval;
4825   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4826   insn_insert_operand (arg->insn, operand, uval);
4827   return TRUE;
4828 }
4829
4830 /* OP_CLO_CLZ_DEST matcher.  */
4831
4832 static bfd_boolean
4833 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4834                             const struct mips_operand *operand)
4835 {
4836   unsigned int regno;
4837
4838   if (!match_reg (arg, OP_REG_GP, &regno))
4839     return FALSE;
4840
4841   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4842   return TRUE;
4843 }
4844
4845 /* OP_LWM_SWM_LIST matcher.  */
4846
4847 static bfd_boolean
4848 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4849                             const struct mips_operand *operand)
4850 {
4851   unsigned int reglist, sregs, ra, regno1, regno2;
4852   struct mips_arg_info reset;
4853
4854   reglist = 0;
4855   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4856     return FALSE;
4857   do
4858     {
4859       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4860         {
4861           reglist |= 1 << FP;
4862           regno2 = S7;
4863         }
4864       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4865       reset = *arg;
4866     }
4867   while (match_char (arg, ',')
4868          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4869   *arg = reset;
4870
4871   if (operand->size == 2)
4872     {
4873       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4874
4875          s0, ra
4876          s0, s1, ra, s2, s3
4877          s0-s2, ra
4878
4879          and any permutations of these.  */
4880       if ((reglist & 0xfff1ffff) != 0x80010000)
4881         return FALSE;
4882
4883       sregs = (reglist >> 17) & 7;
4884       ra = 0;
4885     }
4886   else
4887     {
4888       /* The list must include at least one of ra and s0-sN,
4889          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4890          which are $23 and $30 respectively.)  E.g.:
4891
4892          ra
4893          s0
4894          ra, s0, s1, s2
4895          s0-s8
4896          s0-s5, ra
4897
4898          and any permutations of these.  */
4899       if ((reglist & 0x3f00ffff) != 0)
4900         return FALSE;
4901
4902       ra = (reglist >> 27) & 0x10;
4903       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4904     }
4905   sregs += 1;
4906   if ((sregs & -sregs) != sregs)
4907     return FALSE;
4908
4909   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4910   return TRUE;
4911 }
4912
4913 /* OP_ENTRY_EXIT_LIST matcher.  */
4914
4915 static unsigned int
4916 match_entry_exit_operand (struct mips_arg_info *arg,
4917                           const struct mips_operand *operand)
4918 {
4919   unsigned int mask;
4920   bfd_boolean is_exit;
4921
4922   /* The format is the same for both ENTRY and EXIT, but the constraints
4923      are different.  */
4924   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4925   mask = (is_exit ? 7 << 3 : 0);
4926   do
4927     {
4928       unsigned int regno1, regno2;
4929       bfd_boolean is_freg;
4930
4931       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4932         is_freg = FALSE;
4933       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4934         is_freg = TRUE;
4935       else
4936         return FALSE;
4937
4938       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4939         {
4940           mask &= ~(7 << 3);
4941           mask |= (5 + regno2) << 3;
4942         }
4943       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4944         mask |= (regno2 - 3) << 3;
4945       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4946         mask |= (regno2 - 15) << 1;
4947       else if (regno1 == RA && regno2 == RA)
4948         mask |= 1;
4949       else
4950         return FALSE;
4951     }
4952   while (match_char (arg, ','));
4953
4954   insn_insert_operand (arg->insn, operand, mask);
4955   return TRUE;
4956 }
4957
4958 /* OP_SAVE_RESTORE_LIST matcher.  */
4959
4960 static bfd_boolean
4961 match_save_restore_list_operand (struct mips_arg_info *arg)
4962 {
4963   unsigned int opcode, args, statics, sregs;
4964   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4965   offsetT frame_size;
4966
4967   opcode = arg->insn->insn_opcode;
4968   frame_size = 0;
4969   num_frame_sizes = 0;
4970   args = 0;
4971   statics = 0;
4972   sregs = 0;
4973   do
4974     {
4975       unsigned int regno1, regno2;
4976
4977       if (arg->token->type == OT_INTEGER)
4978         {
4979           /* Handle the frame size.  */
4980           if (!match_const_int (arg, &frame_size))
4981             return FALSE;
4982           num_frame_sizes += 1;
4983         }
4984       else
4985         {
4986           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4987             return FALSE;
4988
4989           while (regno1 <= regno2)
4990             {
4991               if (regno1 >= 4 && regno1 <= 7)
4992                 {
4993                   if (num_frame_sizes == 0)
4994                     /* args $a0-$a3 */
4995                     args |= 1 << (regno1 - 4);
4996                   else
4997                     /* statics $a0-$a3 */
4998                     statics |= 1 << (regno1 - 4);
4999                 }
5000               else if (regno1 >= 16 && regno1 <= 23)
5001                 /* $s0-$s7 */
5002                 sregs |= 1 << (regno1 - 16);
5003               else if (regno1 == 30)
5004                 /* $s8 */
5005                 sregs |= 1 << 8;
5006               else if (regno1 == 31)
5007                 /* Add $ra to insn.  */
5008                 opcode |= 0x40;
5009               else
5010                 return FALSE;
5011               regno1 += 1;
5012               if (regno1 == 24)
5013                 regno1 = 30;
5014             }
5015         }
5016     }
5017   while (match_char (arg, ','));
5018
5019   /* Encode args/statics combination.  */
5020   if (args & statics)
5021     return FALSE;
5022   else if (args == 0xf)
5023     /* All $a0-$a3 are args.  */
5024     opcode |= MIPS16_ALL_ARGS << 16;
5025   else if (statics == 0xf)
5026     /* All $a0-$a3 are statics.  */
5027     opcode |= MIPS16_ALL_STATICS << 16;
5028   else
5029     {
5030       /* Count arg registers.  */
5031       num_args = 0;
5032       while (args & 0x1)
5033         {
5034           args >>= 1;
5035           num_args += 1;
5036         }
5037       if (args != 0)
5038         return FALSE;
5039
5040       /* Count static registers.  */
5041       num_statics = 0;
5042       while (statics & 0x8)
5043         {
5044           statics = (statics << 1) & 0xf;
5045           num_statics += 1;
5046         }
5047       if (statics != 0)
5048         return FALSE;
5049
5050       /* Encode args/statics.  */
5051       opcode |= ((num_args << 2) | num_statics) << 16;
5052     }
5053
5054   /* Encode $s0/$s1.  */
5055   if (sregs & (1 << 0))         /* $s0 */
5056     opcode |= 0x20;
5057   if (sregs & (1 << 1))         /* $s1 */
5058     opcode |= 0x10;
5059   sregs >>= 2;
5060
5061   /* Encode $s2-$s8. */
5062   num_sregs = 0;
5063   while (sregs & 1)
5064     {
5065       sregs >>= 1;
5066       num_sregs += 1;
5067     }
5068   if (sregs != 0)
5069     return FALSE;
5070   opcode |= num_sregs << 24;
5071
5072   /* Encode frame size.  */
5073   if (num_frame_sizes == 0)
5074     {
5075       set_insn_error (arg->argnum, _("missing frame size"));
5076       return FALSE;
5077     }
5078   if (num_frame_sizes > 1)
5079     {
5080       set_insn_error (arg->argnum, _("frame size specified twice"));
5081       return FALSE;
5082     }
5083   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5084     {
5085       set_insn_error (arg->argnum, _("invalid frame size"));
5086       return FALSE;
5087     }
5088   if (frame_size != 128 || (opcode >> 16) != 0)
5089     {
5090       frame_size /= 8;
5091       opcode |= (((frame_size & 0xf0) << 16)
5092                  | (frame_size & 0x0f));
5093     }
5094
5095   /* Finally build the instruction.  */
5096   if ((opcode >> 16) != 0 || frame_size == 0)
5097     opcode |= MIPS16_EXTEND;
5098   arg->insn->insn_opcode = opcode;
5099   return TRUE;
5100 }
5101
5102 /* OP_MDMX_IMM_REG matcher.  */
5103
5104 static bfd_boolean
5105 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5106                             const struct mips_operand *operand)
5107 {
5108   unsigned int regno, uval;
5109   bfd_boolean is_qh;
5110   const struct mips_opcode *opcode;
5111
5112   /* The mips_opcode records whether this is an octobyte or quadhalf
5113      instruction.  Start out with that bit in place.  */
5114   opcode = arg->insn->insn_mo;
5115   uval = mips_extract_operand (operand, opcode->match);
5116   is_qh = (uval != 0);
5117
5118   if (arg->token->type == OT_REG)
5119     {
5120       if ((opcode->membership & INSN_5400)
5121           && strcmp (opcode->name, "rzu.ob") == 0)
5122         {
5123           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5124                             arg->argnum);
5125           return FALSE;
5126         }
5127
5128       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5129         return FALSE;
5130       ++arg->token;
5131
5132       /* Check whether this is a vector register or a broadcast of
5133          a single element.  */
5134       if (arg->token->type == OT_INTEGER_INDEX)
5135         {
5136           if (arg->token->u.index > (is_qh ? 3 : 7))
5137             {
5138               set_insn_error (arg->argnum, _("invalid element selector"));
5139               return FALSE;
5140             }
5141           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5142           ++arg->token;
5143         }
5144       else
5145         {
5146           /* A full vector.  */
5147           if ((opcode->membership & INSN_5400)
5148               && (strcmp (opcode->name, "sll.ob") == 0
5149                   || strcmp (opcode->name, "srl.ob") == 0))
5150             {
5151               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5152                                 arg->argnum);
5153               return FALSE;
5154             }
5155
5156           if (is_qh)
5157             uval |= MDMX_FMTSEL_VEC_QH << 5;
5158           else
5159             uval |= MDMX_FMTSEL_VEC_OB << 5;
5160         }
5161       uval |= regno;
5162     }
5163   else
5164     {
5165       offsetT sval;
5166
5167       if (!match_const_int (arg, &sval))
5168         return FALSE;
5169       if (sval < 0 || sval > 31)
5170         {
5171           match_out_of_range (arg);
5172           return FALSE;
5173         }
5174       uval |= (sval & 31);
5175       if (is_qh)
5176         uval |= MDMX_FMTSEL_IMM_QH << 5;
5177       else
5178         uval |= MDMX_FMTSEL_IMM_OB << 5;
5179     }
5180   insn_insert_operand (arg->insn, operand, uval);
5181   return TRUE;
5182 }
5183
5184 /* OP_IMM_INDEX matcher.  */
5185
5186 static bfd_boolean
5187 match_imm_index_operand (struct mips_arg_info *arg,
5188                          const struct mips_operand *operand)
5189 {
5190   unsigned int max_val;
5191
5192   if (arg->token->type != OT_INTEGER_INDEX)
5193     return FALSE;
5194
5195   max_val = (1 << operand->size) - 1;
5196   if (arg->token->u.index > max_val)
5197     {
5198       match_out_of_range (arg);
5199       return FALSE;
5200     }
5201   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5202   ++arg->token;
5203   return TRUE;
5204 }
5205
5206 /* OP_REG_INDEX matcher.  */
5207
5208 static bfd_boolean
5209 match_reg_index_operand (struct mips_arg_info *arg,
5210                          const struct mips_operand *operand)
5211 {
5212   unsigned int regno;
5213
5214   if (arg->token->type != OT_REG_INDEX)
5215     return FALSE;
5216
5217   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5218     return FALSE;
5219
5220   insn_insert_operand (arg->insn, operand, regno);
5221   ++arg->token;
5222   return TRUE;
5223 }
5224
5225 /* OP_PC matcher.  */
5226
5227 static bfd_boolean
5228 match_pc_operand (struct mips_arg_info *arg)
5229 {
5230   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5231     {
5232       ++arg->token;
5233       return TRUE;
5234     }
5235   return FALSE;
5236 }
5237
5238 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5239    register that we need to match.  */
5240
5241 static bfd_boolean
5242 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5243 {
5244   unsigned int regno;
5245
5246   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5247 }
5248
5249 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5250    the length of the value in bytes (4 for float, 8 for double) and
5251    USING_GPRS says whether the destination is a GPR rather than an FPR.
5252
5253    Return the constant in IMM and OFFSET as follows:
5254
5255    - If the constant should be loaded via memory, set IMM to O_absent and
5256      OFFSET to the memory address.
5257
5258    - Otherwise, if the constant should be loaded into two 32-bit registers,
5259      set IMM to the O_constant to load into the high register and OFFSET
5260      to the corresponding value for the low register.
5261
5262    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5263
5264    These constants only appear as the last operand in an instruction,
5265    and every instruction that accepts them in any variant accepts them
5266    in all variants.  This means we don't have to worry about backing out
5267    any changes if the instruction does not match.  We just match
5268    unconditionally and report an error if the constant is invalid.  */
5269
5270 static bfd_boolean
5271 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5272                       expressionS *offset, int length, bfd_boolean using_gprs)
5273 {
5274   char *p;
5275   segT seg, new_seg;
5276   subsegT subseg;
5277   const char *newname;
5278   unsigned char *data;
5279
5280   /* Where the constant is placed is based on how the MIPS assembler
5281      does things:
5282
5283      length == 4 && using_gprs  -- immediate value only
5284      length == 8 && using_gprs  -- .rdata or immediate value
5285      length == 4 && !using_gprs -- .lit4 or immediate value
5286      length == 8 && !using_gprs -- .lit8 or immediate value
5287
5288      The .lit4 and .lit8 sections are only used if permitted by the
5289      -G argument.  */
5290   if (arg->token->type != OT_FLOAT)
5291     {
5292       set_insn_error (arg->argnum, _("floating-point expression required"));
5293       return FALSE;
5294     }
5295
5296   gas_assert (arg->token->u.flt.length == length);
5297   data = arg->token->u.flt.data;
5298   ++arg->token;
5299
5300   /* Handle 32-bit constants for which an immediate value is best.  */
5301   if (length == 4
5302       && (using_gprs
5303           || g_switch_value < 4
5304           || (data[0] == 0 && data[1] == 0)
5305           || (data[2] == 0 && data[3] == 0)))
5306     {
5307       imm->X_op = O_constant;
5308       if (!target_big_endian)
5309         imm->X_add_number = bfd_getl32 (data);
5310       else
5311         imm->X_add_number = bfd_getb32 (data);
5312       offset->X_op = O_absent;
5313       return TRUE;
5314     }
5315
5316   /* Handle 64-bit constants for which an immediate value is best.  */
5317   if (length == 8
5318       && !mips_disable_float_construction
5319       /* Constants can only be constructed in GPRs and copied
5320          to FPRs if the GPRs are at least as wide as the FPRs.
5321          Force the constant into memory if we are using 64-bit FPRs
5322          but the GPRs are only 32 bits wide.  */
5323       /* ??? No longer true with the addition of MTHC1, but this
5324          is legacy code...  */
5325       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5326       && ((data[0] == 0 && data[1] == 0)
5327           || (data[2] == 0 && data[3] == 0))
5328       && ((data[4] == 0 && data[5] == 0)
5329           || (data[6] == 0 && data[7] == 0)))
5330     {
5331       /* The value is simple enough to load with a couple of instructions.
5332          If using 32-bit registers, set IMM to the high order 32 bits and
5333          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5334          64 bit constant.  */
5335       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5336         {
5337           imm->X_op = O_constant;
5338           offset->X_op = O_constant;
5339           if (!target_big_endian)
5340             {
5341               imm->X_add_number = bfd_getl32 (data + 4);
5342               offset->X_add_number = bfd_getl32 (data);
5343             }
5344           else
5345             {
5346               imm->X_add_number = bfd_getb32 (data);
5347               offset->X_add_number = bfd_getb32 (data + 4);
5348             }
5349           if (offset->X_add_number == 0)
5350             offset->X_op = O_absent;
5351         }
5352       else
5353         {
5354           imm->X_op = O_constant;
5355           if (!target_big_endian)
5356             imm->X_add_number = bfd_getl64 (data);
5357           else
5358             imm->X_add_number = bfd_getb64 (data);
5359           offset->X_op = O_absent;
5360         }
5361       return TRUE;
5362     }
5363
5364   /* Switch to the right section.  */
5365   seg = now_seg;
5366   subseg = now_subseg;
5367   if (length == 4)
5368     {
5369       gas_assert (!using_gprs && g_switch_value >= 4);
5370       newname = ".lit4";
5371     }
5372   else
5373     {
5374       if (using_gprs || g_switch_value < 8)
5375         newname = RDATA_SECTION_NAME;
5376       else
5377         newname = ".lit8";
5378     }
5379
5380   new_seg = subseg_new (newname, (subsegT) 0);
5381   bfd_set_section_flags (stdoutput, new_seg,
5382                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5383   frag_align (length == 4 ? 2 : 3, 0, 0);
5384   if (strncmp (TARGET_OS, "elf", 3) != 0)
5385     record_alignment (new_seg, 4);
5386   else
5387     record_alignment (new_seg, length == 4 ? 2 : 3);
5388   if (seg == now_seg)
5389     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5390
5391   /* Set the argument to the current address in the section.  */
5392   imm->X_op = O_absent;
5393   offset->X_op = O_symbol;
5394   offset->X_add_symbol = symbol_temp_new_now ();
5395   offset->X_add_number = 0;
5396
5397   /* Put the floating point number into the section.  */
5398   p = frag_more (length);
5399   memcpy (p, data, length);
5400
5401   /* Switch back to the original section.  */
5402   subseg_set (seg, subseg);
5403   return TRUE;
5404 }
5405
5406 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5407    them.  */
5408
5409 static bfd_boolean
5410 match_vu0_suffix_operand (struct mips_arg_info *arg,
5411                           const struct mips_operand *operand,
5412                           bfd_boolean match_p)
5413 {
5414   unsigned int uval;
5415
5416   /* The operand can be an XYZW mask or a single 2-bit channel index
5417      (with X being 0).  */
5418   gas_assert (operand->size == 2 || operand->size == 4);
5419
5420   /* The suffix can be omitted when it is already part of the opcode.  */
5421   if (arg->token->type != OT_CHANNELS)
5422     return match_p;
5423
5424   uval = arg->token->u.channels;
5425   if (operand->size == 2)
5426     {
5427       /* Check that a single bit is set and convert it into a 2-bit index.  */
5428       if ((uval & -uval) != uval)
5429         return FALSE;
5430       uval = 4 - ffs (uval);
5431     }
5432
5433   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5434     return FALSE;
5435
5436   ++arg->token;
5437   if (!match_p)
5438     insn_insert_operand (arg->insn, operand, uval);
5439   return TRUE;
5440 }
5441
5442 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5443    of the argument text if the match is successful, otherwise return null.  */
5444
5445 static bfd_boolean
5446 match_operand (struct mips_arg_info *arg,
5447                const struct mips_operand *operand)
5448 {
5449   switch (operand->type)
5450     {
5451     case OP_INT:
5452       return match_int_operand (arg, operand);
5453
5454     case OP_MAPPED_INT:
5455       return match_mapped_int_operand (arg, operand);
5456
5457     case OP_MSB:
5458       return match_msb_operand (arg, operand);
5459
5460     case OP_REG:
5461     case OP_OPTIONAL_REG:
5462       return match_reg_operand (arg, operand);
5463
5464     case OP_REG_PAIR:
5465       return match_reg_pair_operand (arg, operand);
5466
5467     case OP_PCREL:
5468       return match_pcrel_operand (arg);
5469
5470     case OP_PERF_REG:
5471       return match_perf_reg_operand (arg, operand);
5472
5473     case OP_ADDIUSP_INT:
5474       return match_addiusp_operand (arg, operand);
5475
5476     case OP_CLO_CLZ_DEST:
5477       return match_clo_clz_dest_operand (arg, operand);
5478
5479     case OP_LWM_SWM_LIST:
5480       return match_lwm_swm_list_operand (arg, operand);
5481
5482     case OP_ENTRY_EXIT_LIST:
5483       return match_entry_exit_operand (arg, operand);
5484
5485     case OP_SAVE_RESTORE_LIST:
5486       return match_save_restore_list_operand (arg);
5487
5488     case OP_MDMX_IMM_REG:
5489       return match_mdmx_imm_reg_operand (arg, operand);
5490
5491     case OP_REPEAT_DEST_REG:
5492       return match_tied_reg_operand (arg, arg->dest_regno);
5493
5494     case OP_REPEAT_PREV_REG:
5495       return match_tied_reg_operand (arg, arg->last_regno);
5496
5497     case OP_PC:
5498       return match_pc_operand (arg);
5499
5500     case OP_VU0_SUFFIX:
5501       return match_vu0_suffix_operand (arg, operand, FALSE);
5502
5503     case OP_VU0_MATCH_SUFFIX:
5504       return match_vu0_suffix_operand (arg, operand, TRUE);
5505
5506     case OP_IMM_INDEX:
5507       return match_imm_index_operand (arg, operand);
5508
5509     case OP_REG_INDEX:
5510       return match_reg_index_operand (arg, operand);
5511     }
5512   abort ();
5513 }
5514
5515 /* ARG is the state after successfully matching an instruction.
5516    Issue any queued-up warnings.  */
5517
5518 static void
5519 check_completed_insn (struct mips_arg_info *arg)
5520 {
5521   if (arg->seen_at)
5522     {
5523       if (AT == ATREG)
5524         as_warn (_("used $at without \".set noat\""));
5525       else
5526         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5527     }
5528 }
5529
5530 /* Return true if modifying general-purpose register REG needs a delay.  */
5531
5532 static bfd_boolean
5533 reg_needs_delay (unsigned int reg)
5534 {
5535   unsigned long prev_pinfo;
5536
5537   prev_pinfo = history[0].insn_mo->pinfo;
5538   if (!mips_opts.noreorder
5539       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5540           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5541       && (gpr_write_mask (&history[0]) & (1 << reg)))
5542     return TRUE;
5543
5544   return FALSE;
5545 }
5546
5547 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5548    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5549    by VR4120 errata.  */
5550
5551 static unsigned int
5552 classify_vr4120_insn (const char *name)
5553 {
5554   if (strncmp (name, "macc", 4) == 0)
5555     return FIX_VR4120_MACC;
5556   if (strncmp (name, "dmacc", 5) == 0)
5557     return FIX_VR4120_DMACC;
5558   if (strncmp (name, "mult", 4) == 0)
5559     return FIX_VR4120_MULT;
5560   if (strncmp (name, "dmult", 5) == 0)
5561     return FIX_VR4120_DMULT;
5562   if (strstr (name, "div"))
5563     return FIX_VR4120_DIV;
5564   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5565     return FIX_VR4120_MTHILO;
5566   return NUM_FIX_VR4120_CLASSES;
5567 }
5568
5569 #define INSN_ERET       0x42000018
5570 #define INSN_DERET      0x4200001f
5571 #define INSN_DMULT      0x1c
5572 #define INSN_DMULTU     0x1d
5573
5574 /* Return the number of instructions that must separate INSN1 and INSN2,
5575    where INSN1 is the earlier instruction.  Return the worst-case value
5576    for any INSN2 if INSN2 is null.  */
5577
5578 static unsigned int
5579 insns_between (const struct mips_cl_insn *insn1,
5580                const struct mips_cl_insn *insn2)
5581 {
5582   unsigned long pinfo1, pinfo2;
5583   unsigned int mask;
5584
5585   /* If INFO2 is null, pessimistically assume that all flags are set for
5586      the second instruction.  */
5587   pinfo1 = insn1->insn_mo->pinfo;
5588   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5589
5590   /* For most targets, write-after-read dependencies on the HI and LO
5591      registers must be separated by at least two instructions.  */
5592   if (!hilo_interlocks)
5593     {
5594       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5595         return 2;
5596       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5597         return 2;
5598     }
5599
5600   /* If we're working around r7000 errata, there must be two instructions
5601      between an mfhi or mflo and any instruction that uses the result.  */
5602   if (mips_7000_hilo_fix
5603       && !mips_opts.micromips
5604       && MF_HILO_INSN (pinfo1)
5605       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5606     return 2;
5607
5608   /* If we're working around 24K errata, one instruction is required
5609      if an ERET or DERET is followed by a branch instruction.  */
5610   if (mips_fix_24k && !mips_opts.micromips)
5611     {
5612       if (insn1->insn_opcode == INSN_ERET
5613           || insn1->insn_opcode == INSN_DERET)
5614         {
5615           if (insn2 == NULL
5616               || insn2->insn_opcode == INSN_ERET
5617               || insn2->insn_opcode == INSN_DERET
5618               || delayed_branch_p (insn2))
5619             return 1;
5620         }
5621     }
5622
5623   /* If we're working around PMC RM7000 errata, there must be three
5624      nops between a dmult and a load instruction.  */
5625   if (mips_fix_rm7000 && !mips_opts.micromips)
5626     {
5627       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5628           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5629         {
5630           if (pinfo2 & INSN_LOAD_MEMORY)
5631            return 3;
5632         }
5633     }
5634
5635   /* If working around VR4120 errata, check for combinations that need
5636      a single intervening instruction.  */
5637   if (mips_fix_vr4120 && !mips_opts.micromips)
5638     {
5639       unsigned int class1, class2;
5640
5641       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5642       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5643         {
5644           if (insn2 == NULL)
5645             return 1;
5646           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5647           if (vr4120_conflicts[class1] & (1 << class2))
5648             return 1;
5649         }
5650     }
5651
5652   if (!HAVE_CODE_COMPRESSION)
5653     {
5654       /* Check for GPR or coprocessor load delays.  All such delays
5655          are on the RT register.  */
5656       /* Itbl support may require additional care here.  */
5657       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5658           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5659         {
5660           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5661             return 1;
5662         }
5663
5664       /* Check for generic coprocessor hazards.
5665
5666          This case is not handled very well.  There is no special
5667          knowledge of CP0 handling, and the coprocessors other than
5668          the floating point unit are not distinguished at all.  */
5669       /* Itbl support may require additional care here. FIXME!
5670          Need to modify this to include knowledge about
5671          user specified delays!  */
5672       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5673                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5674         {
5675           /* Handle cases where INSN1 writes to a known general coprocessor
5676              register.  There must be a one instruction delay before INSN2
5677              if INSN2 reads that register, otherwise no delay is needed.  */
5678           mask = fpr_write_mask (insn1);
5679           if (mask != 0)
5680             {
5681               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5682                 return 1;
5683             }
5684           else
5685             {
5686               /* Read-after-write dependencies on the control registers
5687                  require a two-instruction gap.  */
5688               if ((pinfo1 & INSN_WRITE_COND_CODE)
5689                   && (pinfo2 & INSN_READ_COND_CODE))
5690                 return 2;
5691
5692               /* We don't know exactly what INSN1 does.  If INSN2 is
5693                  also a coprocessor instruction, assume there must be
5694                  a one instruction gap.  */
5695               if (pinfo2 & INSN_COP)
5696                 return 1;
5697             }
5698         }
5699
5700       /* Check for read-after-write dependencies on the coprocessor
5701          control registers in cases where INSN1 does not need a general
5702          coprocessor delay.  This means that INSN1 is a floating point
5703          comparison instruction.  */
5704       /* Itbl support may require additional care here.  */
5705       else if (!cop_interlocks
5706                && (pinfo1 & INSN_WRITE_COND_CODE)
5707                && (pinfo2 & INSN_READ_COND_CODE))
5708         return 1;
5709     }
5710
5711   return 0;
5712 }
5713
5714 /* Return the number of nops that would be needed to work around the
5715    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5716    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5717    that are contained within the first IGNORE instructions of HIST.  */
5718
5719 static int
5720 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5721                  const struct mips_cl_insn *insn)
5722 {
5723   int i, j;
5724   unsigned int mask;
5725
5726   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5727      are not affected by the errata.  */
5728   if (insn != 0
5729       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5730           || strcmp (insn->insn_mo->name, "mtlo") == 0
5731           || strcmp (insn->insn_mo->name, "mthi") == 0))
5732     return 0;
5733
5734   /* Search for the first MFLO or MFHI.  */
5735   for (i = 0; i < MAX_VR4130_NOPS; i++)
5736     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5737       {
5738         /* Extract the destination register.  */
5739         mask = gpr_write_mask (&hist[i]);
5740
5741         /* No nops are needed if INSN reads that register.  */
5742         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5743           return 0;
5744
5745         /* ...or if any of the intervening instructions do.  */
5746         for (j = 0; j < i; j++)
5747           if (gpr_read_mask (&hist[j]) & mask)
5748             return 0;
5749
5750         if (i >= ignore)
5751           return MAX_VR4130_NOPS - i;
5752       }
5753   return 0;
5754 }
5755
5756 #define BASE_REG_EQ(INSN1, INSN2)       \
5757   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5758       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5759
5760 /* Return the minimum alignment for this store instruction.  */
5761
5762 static int
5763 fix_24k_align_to (const struct mips_opcode *mo)
5764 {
5765   if (strcmp (mo->name, "sh") == 0)
5766     return 2;
5767
5768   if (strcmp (mo->name, "swc1") == 0
5769       || strcmp (mo->name, "swc2") == 0
5770       || strcmp (mo->name, "sw") == 0
5771       || strcmp (mo->name, "sc") == 0
5772       || strcmp (mo->name, "s.s") == 0)
5773     return 4;
5774
5775   if (strcmp (mo->name, "sdc1") == 0
5776       || strcmp (mo->name, "sdc2") == 0
5777       || strcmp (mo->name, "s.d") == 0)
5778     return 8;
5779
5780   /* sb, swl, swr */
5781   return 1;
5782 }
5783
5784 struct fix_24k_store_info
5785   {
5786     /* Immediate offset, if any, for this store instruction.  */
5787     short off;
5788     /* Alignment required by this store instruction.  */
5789     int align_to;
5790     /* True for register offsets.  */
5791     int register_offset;
5792   };
5793
5794 /* Comparison function used by qsort.  */
5795
5796 static int
5797 fix_24k_sort (const void *a, const void *b)
5798 {
5799   const struct fix_24k_store_info *pos1 = a;
5800   const struct fix_24k_store_info *pos2 = b;
5801
5802   return (pos1->off - pos2->off);
5803 }
5804
5805 /* INSN is a store instruction.  Try to record the store information
5806    in STINFO.  Return false if the information isn't known.  */
5807
5808 static bfd_boolean
5809 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5810                            const struct mips_cl_insn *insn)
5811 {
5812   /* The instruction must have a known offset.  */
5813   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5814     return FALSE;
5815
5816   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5817   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5818   return TRUE;
5819 }
5820
5821 /* Return the number of nops that would be needed to work around the 24k
5822    "lost data on stores during refill" errata if instruction INSN
5823    immediately followed the 2 instructions described by HIST.
5824    Ignore hazards that are contained within the first IGNORE
5825    instructions of HIST.
5826
5827    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5828    for the data cache refills and store data. The following describes
5829    the scenario where the store data could be lost.
5830
5831    * A data cache miss, due to either a load or a store, causing fill
5832      data to be supplied by the memory subsystem
5833    * The first three doublewords of fill data are returned and written
5834      into the cache
5835    * A sequence of four stores occurs in consecutive cycles around the
5836      final doubleword of the fill:
5837    * Store A
5838    * Store B
5839    * Store C
5840    * Zero, One or more instructions
5841    * Store D
5842
5843    The four stores A-D must be to different doublewords of the line that
5844    is being filled. The fourth instruction in the sequence above permits
5845    the fill of the final doubleword to be transferred from the FSB into
5846    the cache. In the sequence above, the stores may be either integer
5847    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5848    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5849    different doublewords on the line. If the floating point unit is
5850    running in 1:2 mode, it is not possible to create the sequence above
5851    using only floating point store instructions.
5852
5853    In this case, the cache line being filled is incorrectly marked
5854    invalid, thereby losing the data from any store to the line that
5855    occurs between the original miss and the completion of the five
5856    cycle sequence shown above.
5857
5858    The workarounds are:
5859
5860    * Run the data cache in write-through mode.
5861    * Insert a non-store instruction between
5862      Store A and Store B or Store B and Store C.  */
5863   
5864 static int
5865 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5866               const struct mips_cl_insn *insn)
5867 {
5868   struct fix_24k_store_info pos[3];
5869   int align, i, base_offset;
5870
5871   if (ignore >= 2)
5872     return 0;
5873
5874   /* If the previous instruction wasn't a store, there's nothing to
5875      worry about.  */
5876   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5877     return 0;
5878
5879   /* If the instructions after the previous one are unknown, we have
5880      to assume the worst.  */
5881   if (!insn)
5882     return 1;
5883
5884   /* Check whether we are dealing with three consecutive stores.  */
5885   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5886       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5887     return 0;
5888
5889   /* If we don't know the relationship between the store addresses,
5890      assume the worst.  */
5891   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5892       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5893     return 1;
5894
5895   if (!fix_24k_record_store_info (&pos[0], insn)
5896       || !fix_24k_record_store_info (&pos[1], &hist[0])
5897       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5898     return 1;
5899
5900   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5901
5902   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5903      X bytes and such that the base register + X is known to be aligned
5904      to align bytes.  */
5905
5906   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5907     align = 8;
5908   else
5909     {
5910       align = pos[0].align_to;
5911       base_offset = pos[0].off;
5912       for (i = 1; i < 3; i++)
5913         if (align < pos[i].align_to)
5914           {
5915             align = pos[i].align_to;
5916             base_offset = pos[i].off;
5917           }
5918       for (i = 0; i < 3; i++)
5919         pos[i].off -= base_offset;
5920     }
5921
5922   pos[0].off &= ~align + 1;
5923   pos[1].off &= ~align + 1;
5924   pos[2].off &= ~align + 1;
5925
5926   /* If any two stores write to the same chunk, they also write to the
5927      same doubleword.  The offsets are still sorted at this point.  */
5928   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5929     return 0;
5930
5931   /* A range of at least 9 bytes is needed for the stores to be in
5932      non-overlapping doublewords.  */
5933   if (pos[2].off - pos[0].off <= 8)
5934     return 0;
5935
5936   if (pos[2].off - pos[1].off >= 24
5937       || pos[1].off - pos[0].off >= 24
5938       || pos[2].off - pos[0].off >= 32)
5939     return 0;
5940
5941   return 1;
5942 }
5943
5944 /* Return the number of nops that would be needed if instruction INSN
5945    immediately followed the MAX_NOPS instructions given by HIST,
5946    where HIST[0] is the most recent instruction.  Ignore hazards
5947    between INSN and the first IGNORE instructions in HIST.
5948
5949    If INSN is null, return the worse-case number of nops for any
5950    instruction.  */
5951
5952 static int
5953 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5954                const struct mips_cl_insn *insn)
5955 {
5956   int i, nops, tmp_nops;
5957
5958   nops = 0;
5959   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5960     {
5961       tmp_nops = insns_between (hist + i, insn) - i;
5962       if (tmp_nops > nops)
5963         nops = tmp_nops;
5964     }
5965
5966   if (mips_fix_vr4130 && !mips_opts.micromips)
5967     {
5968       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5969       if (tmp_nops > nops)
5970         nops = tmp_nops;
5971     }
5972
5973   if (mips_fix_24k && !mips_opts.micromips)
5974     {
5975       tmp_nops = nops_for_24k (ignore, hist, insn);
5976       if (tmp_nops > nops)
5977         nops = tmp_nops;
5978     }
5979
5980   return nops;
5981 }
5982
5983 /* The variable arguments provide NUM_INSNS extra instructions that
5984    might be added to HIST.  Return the largest number of nops that
5985    would be needed after the extended sequence, ignoring hazards
5986    in the first IGNORE instructions.  */
5987
5988 static int
5989 nops_for_sequence (int num_insns, int ignore,
5990                    const struct mips_cl_insn *hist, ...)
5991 {
5992   va_list args;
5993   struct mips_cl_insn buffer[MAX_NOPS];
5994   struct mips_cl_insn *cursor;
5995   int nops;
5996
5997   va_start (args, hist);
5998   cursor = buffer + num_insns;
5999   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6000   while (cursor > buffer)
6001     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6002
6003   nops = nops_for_insn (ignore, buffer, NULL);
6004   va_end (args);
6005   return nops;
6006 }
6007
6008 /* Like nops_for_insn, but if INSN is a branch, take into account the
6009    worst-case delay for the branch target.  */
6010
6011 static int
6012 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6013                          const struct mips_cl_insn *insn)
6014 {
6015   int nops, tmp_nops;
6016
6017   nops = nops_for_insn (ignore, hist, insn);
6018   if (delayed_branch_p (insn))
6019     {
6020       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6021                                     hist, insn, get_delay_slot_nop (insn));
6022       if (tmp_nops > nops)
6023         nops = tmp_nops;
6024     }
6025   else if (compact_branch_p (insn))
6026     {
6027       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6028       if (tmp_nops > nops)
6029         nops = tmp_nops;
6030     }
6031   return nops;
6032 }
6033
6034 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6035
6036 static void
6037 fix_loongson2f_nop (struct mips_cl_insn * ip)
6038 {
6039   gas_assert (!HAVE_CODE_COMPRESSION);
6040   if (strcmp (ip->insn_mo->name, "nop") == 0)
6041     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6042 }
6043
6044 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6045                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6046
6047 static void
6048 fix_loongson2f_jump (struct mips_cl_insn * ip)
6049 {
6050   gas_assert (!HAVE_CODE_COMPRESSION);
6051   if (strcmp (ip->insn_mo->name, "j") == 0
6052       || strcmp (ip->insn_mo->name, "jr") == 0
6053       || strcmp (ip->insn_mo->name, "jalr") == 0)
6054     {
6055       int sreg;
6056       expressionS ep;
6057
6058       if (! mips_opts.at)
6059         return;
6060
6061       sreg = EXTRACT_OPERAND (0, RS, *ip);
6062       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6063         return;
6064
6065       ep.X_op = O_constant;
6066       ep.X_add_number = 0xcfff0000;
6067       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6068       ep.X_add_number = 0xffff;
6069       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6070       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6071     }
6072 }
6073
6074 static void
6075 fix_loongson2f (struct mips_cl_insn * ip)
6076 {
6077   if (mips_fix_loongson2f_nop)
6078     fix_loongson2f_nop (ip);
6079
6080   if (mips_fix_loongson2f_jump)
6081     fix_loongson2f_jump (ip);
6082 }
6083
6084 /* IP is a branch that has a delay slot, and we need to fill it
6085    automatically.   Return true if we can do that by swapping IP
6086    with the previous instruction.
6087    ADDRESS_EXPR is an operand of the instruction to be used with
6088    RELOC_TYPE.  */
6089
6090 static bfd_boolean
6091 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6092                    bfd_reloc_code_real_type *reloc_type)
6093 {
6094   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6095   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6096   unsigned int fpr_read, prev_fpr_write;
6097
6098   /* -O2 and above is required for this optimization.  */
6099   if (mips_optimize < 2)
6100     return FALSE;
6101
6102   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6103   if (mips_opts.nomove)
6104     return FALSE;
6105
6106   /* We can't swap if the previous instruction's position is fixed.  */
6107   if (history[0].fixed_p)
6108     return FALSE;
6109
6110   /* If the previous previous insn was in a .set noreorder, we can't
6111      swap.  Actually, the MIPS assembler will swap in this situation.
6112      However, gcc configured -with-gnu-as will generate code like
6113
6114         .set    noreorder
6115         lw      $4,XXX
6116         .set    reorder
6117         INSN
6118         bne     $4,$0,foo
6119
6120      in which we can not swap the bne and INSN.  If gcc is not configured
6121      -with-gnu-as, it does not output the .set pseudo-ops.  */
6122   if (history[1].noreorder_p)
6123     return FALSE;
6124
6125   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6126      This means that the previous instruction was a 4-byte one anyhow.  */
6127   if (mips_opts.mips16 && history[0].fixp[0])
6128     return FALSE;
6129
6130   /* If the branch is itself the target of a branch, we can not swap.
6131      We cheat on this; all we check for is whether there is a label on
6132      this instruction.  If there are any branches to anything other than
6133      a label, users must use .set noreorder.  */
6134   if (seg_info (now_seg)->label_list)
6135     return FALSE;
6136
6137   /* If the previous instruction is in a variant frag other than this
6138      branch's one, we cannot do the swap.  This does not apply to
6139      MIPS16 code, which uses variant frags for different purposes.  */
6140   if (!mips_opts.mips16
6141       && history[0].frag
6142       && history[0].frag->fr_type == rs_machine_dependent)
6143     return FALSE;
6144
6145   /* We do not swap with instructions that cannot architecturally
6146      be placed in a branch delay slot, such as SYNC or ERET.  We
6147      also refrain from swapping with a trap instruction, since it
6148      complicates trap handlers to have the trap instruction be in
6149      a delay slot.  */
6150   prev_pinfo = history[0].insn_mo->pinfo;
6151   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6152     return FALSE;
6153
6154   /* Check for conflicts between the branch and the instructions
6155      before the candidate delay slot.  */
6156   if (nops_for_insn (0, history + 1, ip) > 0)
6157     return FALSE;
6158
6159   /* Check for conflicts between the swapped sequence and the
6160      target of the branch.  */
6161   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6162     return FALSE;
6163
6164   /* If the branch reads a register that the previous
6165      instruction sets, we can not swap.  */
6166   gpr_read = gpr_read_mask (ip);
6167   prev_gpr_write = gpr_write_mask (&history[0]);
6168   if (gpr_read & prev_gpr_write)
6169     return FALSE;
6170
6171   fpr_read = fpr_read_mask (ip);
6172   prev_fpr_write = fpr_write_mask (&history[0]);
6173   if (fpr_read & prev_fpr_write)
6174     return FALSE;
6175
6176   /* If the branch writes a register that the previous
6177      instruction sets, we can not swap.  */
6178   gpr_write = gpr_write_mask (ip);
6179   if (gpr_write & prev_gpr_write)
6180     return FALSE;
6181
6182   /* If the branch writes a register that the previous
6183      instruction reads, we can not swap.  */
6184   prev_gpr_read = gpr_read_mask (&history[0]);
6185   if (gpr_write & prev_gpr_read)
6186     return FALSE;
6187
6188   /* If one instruction sets a condition code and the
6189      other one uses a condition code, we can not swap.  */
6190   pinfo = ip->insn_mo->pinfo;
6191   if ((pinfo & INSN_READ_COND_CODE)
6192       && (prev_pinfo & INSN_WRITE_COND_CODE))
6193     return FALSE;
6194   if ((pinfo & INSN_WRITE_COND_CODE)
6195       && (prev_pinfo & INSN_READ_COND_CODE))
6196     return FALSE;
6197
6198   /* If the previous instruction uses the PC, we can not swap.  */
6199   prev_pinfo2 = history[0].insn_mo->pinfo2;
6200   if (prev_pinfo2 & INSN2_READ_PC)
6201     return FALSE;
6202
6203   /* If the previous instruction has an incorrect size for a fixed
6204      branch delay slot in microMIPS mode, we cannot swap.  */
6205   pinfo2 = ip->insn_mo->pinfo2;
6206   if (mips_opts.micromips
6207       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6208       && insn_length (history) != 2)
6209     return FALSE;
6210   if (mips_opts.micromips
6211       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6212       && insn_length (history) != 4)
6213     return FALSE;
6214
6215   /* On R5900 short loops need to be fixed by inserting a nop in
6216      the branch delay slots.
6217      A short loop can be terminated too early.  */
6218   if (mips_opts.arch == CPU_R5900
6219       /* Check if instruction has a parameter, ignore "j $31". */
6220       && (address_expr != NULL)
6221       /* Parameter must be 16 bit. */
6222       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6223       /* Branch to same segment. */
6224       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6225       /* Branch to same code fragment. */
6226       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6227       /* Can only calculate branch offset if value is known. */
6228       && symbol_constant_p(address_expr->X_add_symbol)
6229       /* Check if branch is really conditional. */
6230       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6231         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6232         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6233     {
6234       int distance;
6235       /* Check if loop is shorter than 6 instructions including
6236          branch and delay slot.  */
6237       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6238       if (distance <= 20)
6239         {
6240           int i;
6241           int rv;
6242
6243           rv = FALSE;
6244           /* When the loop includes branches or jumps,
6245              it is not a short loop. */
6246           for (i = 0; i < (distance / 4); i++)
6247             {
6248               if ((history[i].cleared_p)
6249                   || delayed_branch_p(&history[i]))
6250                 {
6251                   rv = TRUE;
6252                   break;
6253                 }
6254             }
6255           if (rv == FALSE)
6256             {
6257               /* Insert nop after branch to fix short loop. */
6258               return FALSE;
6259             }
6260         }
6261     }
6262
6263   return TRUE;
6264 }
6265
6266 /* Decide how we should add IP to the instruction stream.
6267    ADDRESS_EXPR is an operand of the instruction to be used with
6268    RELOC_TYPE.  */
6269
6270 static enum append_method
6271 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6272                    bfd_reloc_code_real_type *reloc_type)
6273 {
6274   /* The relaxed version of a macro sequence must be inherently
6275      hazard-free.  */
6276   if (mips_relax.sequence == 2)
6277     return APPEND_ADD;
6278
6279   /* We must not dabble with instructions in a ".set norerorder" block.  */
6280   if (mips_opts.noreorder)
6281     return APPEND_ADD;
6282
6283   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6284   if (delayed_branch_p (ip))
6285     {
6286       if (!branch_likely_p (ip)
6287           && can_swap_branch_p (ip, address_expr, reloc_type))
6288         return APPEND_SWAP;
6289
6290       if (mips_opts.mips16
6291           && ISA_SUPPORTS_MIPS16E
6292           && gpr_read_mask (ip) != 0)
6293         return APPEND_ADD_COMPACT;
6294
6295       return APPEND_ADD_WITH_NOP;
6296     }
6297
6298   return APPEND_ADD;
6299 }
6300
6301 /* IP is a MIPS16 instruction whose opcode we have just changed.
6302    Point IP->insn_mo to the new opcode's definition.  */
6303
6304 static void
6305 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6306 {
6307   const struct mips_opcode *mo, *end;
6308
6309   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6310   for (mo = ip->insn_mo; mo < end; mo++)
6311     if ((ip->insn_opcode & mo->mask) == mo->match)
6312       {
6313         ip->insn_mo = mo;
6314         return;
6315       }
6316   abort ();
6317 }
6318
6319 /* For microMIPS macros, we need to generate a local number label
6320    as the target of branches.  */
6321 #define MICROMIPS_LABEL_CHAR            '\037'
6322 static unsigned long micromips_target_label;
6323 static char micromips_target_name[32];
6324
6325 static char *
6326 micromips_label_name (void)
6327 {
6328   char *p = micromips_target_name;
6329   char symbol_name_temporary[24];
6330   unsigned long l;
6331   int i;
6332
6333   if (*p)
6334     return p;
6335
6336   i = 0;
6337   l = micromips_target_label;
6338 #ifdef LOCAL_LABEL_PREFIX
6339   *p++ = LOCAL_LABEL_PREFIX;
6340 #endif
6341   *p++ = 'L';
6342   *p++ = MICROMIPS_LABEL_CHAR;
6343   do
6344     {
6345       symbol_name_temporary[i++] = l % 10 + '0';
6346       l /= 10;
6347     }
6348   while (l != 0);
6349   while (i > 0)
6350     *p++ = symbol_name_temporary[--i];
6351   *p = '\0';
6352
6353   return micromips_target_name;
6354 }
6355
6356 static void
6357 micromips_label_expr (expressionS *label_expr)
6358 {
6359   label_expr->X_op = O_symbol;
6360   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6361   label_expr->X_add_number = 0;
6362 }
6363
6364 static void
6365 micromips_label_inc (void)
6366 {
6367   micromips_target_label++;
6368   *micromips_target_name = '\0';
6369 }
6370
6371 static void
6372 micromips_add_label (void)
6373 {
6374   symbolS *s;
6375
6376   s = colon (micromips_label_name ());
6377   micromips_label_inc ();
6378   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6379 }
6380
6381 /* If assembling microMIPS code, then return the microMIPS reloc
6382    corresponding to the requested one if any.  Otherwise return
6383    the reloc unchanged.  */
6384
6385 static bfd_reloc_code_real_type
6386 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6387 {
6388   static const bfd_reloc_code_real_type relocs[][2] =
6389     {
6390       /* Keep sorted incrementally by the left-hand key.  */
6391       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6392       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6393       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6394       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6395       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6396       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6397       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6398       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6399       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6400       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6401       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6402       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6403       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6404       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6405       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6406       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6407       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6408       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6409       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6410       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6411       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6412       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6413       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6414       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6415       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6416       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6417       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6418     };
6419   bfd_reloc_code_real_type r;
6420   size_t i;
6421
6422   if (!mips_opts.micromips)
6423     return reloc;
6424   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6425     {
6426       r = relocs[i][0];
6427       if (r > reloc)
6428         return reloc;
6429       if (r == reloc)
6430         return relocs[i][1];
6431     }
6432   return reloc;
6433 }
6434
6435 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6436    Return true on success, storing the resolved value in RESULT.  */
6437
6438 static bfd_boolean
6439 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6440                  offsetT *result)
6441 {
6442   switch (reloc)
6443     {
6444     case BFD_RELOC_MIPS_HIGHEST:
6445     case BFD_RELOC_MICROMIPS_HIGHEST:
6446       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6447       return TRUE;
6448
6449     case BFD_RELOC_MIPS_HIGHER:
6450     case BFD_RELOC_MICROMIPS_HIGHER:
6451       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6452       return TRUE;
6453
6454     case BFD_RELOC_HI16_S:
6455     case BFD_RELOC_MICROMIPS_HI16_S:
6456     case BFD_RELOC_MIPS16_HI16_S:
6457       *result = ((operand + 0x8000) >> 16) & 0xffff;
6458       return TRUE;
6459
6460     case BFD_RELOC_HI16:
6461     case BFD_RELOC_MICROMIPS_HI16:
6462     case BFD_RELOC_MIPS16_HI16:
6463       *result = (operand >> 16) & 0xffff;
6464       return TRUE;
6465
6466     case BFD_RELOC_LO16:
6467     case BFD_RELOC_MICROMIPS_LO16:
6468     case BFD_RELOC_MIPS16_LO16:
6469       *result = operand & 0xffff;
6470       return TRUE;
6471
6472     case BFD_RELOC_UNUSED:
6473       *result = operand;
6474       return TRUE;
6475
6476     default:
6477       return FALSE;
6478     }
6479 }
6480
6481 /* Output an instruction.  IP is the instruction information.
6482    ADDRESS_EXPR is an operand of the instruction to be used with
6483    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6484    a macro expansion.  */
6485
6486 static void
6487 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6488              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6489 {
6490   unsigned long prev_pinfo2, pinfo;
6491   bfd_boolean relaxed_branch = FALSE;
6492   enum append_method method;
6493   bfd_boolean relax32;
6494   int branch_disp;
6495
6496   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6497     fix_loongson2f (ip);
6498
6499   file_ase_mips16 |= mips_opts.mips16;
6500   file_ase_micromips |= mips_opts.micromips;
6501
6502   prev_pinfo2 = history[0].insn_mo->pinfo2;
6503   pinfo = ip->insn_mo->pinfo;
6504
6505   if (mips_opts.micromips
6506       && !expansionp
6507       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6508            && micromips_insn_length (ip->insn_mo) != 2)
6509           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6510               && micromips_insn_length (ip->insn_mo) != 4)))
6511     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6512              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6513
6514   if (address_expr == NULL)
6515     ip->complete_p = 1;
6516   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6517            && reloc_type[1] == BFD_RELOC_UNUSED
6518            && reloc_type[2] == BFD_RELOC_UNUSED
6519            && address_expr->X_op == O_constant)
6520     {
6521       switch (*reloc_type)
6522         {
6523         case BFD_RELOC_MIPS_JMP:
6524           {
6525             int shift;
6526
6527             shift = mips_opts.micromips ? 1 : 2;
6528             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6529               as_bad (_("jump to misaligned address (0x%lx)"),
6530                       (unsigned long) address_expr->X_add_number);
6531             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6532                                 & 0x3ffffff);
6533             ip->complete_p = 1;
6534           }
6535           break;
6536
6537         case BFD_RELOC_MIPS16_JMP:
6538           if ((address_expr->X_add_number & 3) != 0)
6539             as_bad (_("jump to misaligned address (0x%lx)"),
6540                     (unsigned long) address_expr->X_add_number);
6541           ip->insn_opcode |=
6542             (((address_expr->X_add_number & 0x7c0000) << 3)
6543                | ((address_expr->X_add_number & 0xf800000) >> 7)
6544                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6545           ip->complete_p = 1;
6546           break;
6547
6548         case BFD_RELOC_16_PCREL_S2:
6549           {
6550             int shift;
6551
6552             shift = mips_opts.micromips ? 1 : 2;
6553             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6554               as_bad (_("branch to misaligned address (0x%lx)"),
6555                       (unsigned long) address_expr->X_add_number);
6556             if (!mips_relax_branch)
6557               {
6558                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6559                     & ~((1 << (shift + 16)) - 1))
6560                   as_bad (_("branch address range overflow (0x%lx)"),
6561                           (unsigned long) address_expr->X_add_number);
6562                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6563                                     & 0xffff);
6564               }
6565           }
6566           break;
6567
6568         default:
6569           {
6570             offsetT value;
6571
6572             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6573                                  &value))
6574               {
6575                 ip->insn_opcode |= value & 0xffff;
6576                 ip->complete_p = 1;
6577               }
6578           }
6579           break;
6580         }
6581     }
6582
6583   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6584     {
6585       /* There are a lot of optimizations we could do that we don't.
6586          In particular, we do not, in general, reorder instructions.
6587          If you use gcc with optimization, it will reorder
6588          instructions and generally do much more optimization then we
6589          do here; repeating all that work in the assembler would only
6590          benefit hand written assembly code, and does not seem worth
6591          it.  */
6592       int nops = (mips_optimize == 0
6593                   ? nops_for_insn (0, history, NULL)
6594                   : nops_for_insn_or_target (0, history, ip));
6595       if (nops > 0)
6596         {
6597           fragS *old_frag;
6598           unsigned long old_frag_offset;
6599           int i;
6600
6601           old_frag = frag_now;
6602           old_frag_offset = frag_now_fix ();
6603
6604           for (i = 0; i < nops; i++)
6605             add_fixed_insn (NOP_INSN);
6606           insert_into_history (0, nops, NOP_INSN);
6607
6608           if (listing)
6609             {
6610               listing_prev_line ();
6611               /* We may be at the start of a variant frag.  In case we
6612                  are, make sure there is enough space for the frag
6613                  after the frags created by listing_prev_line.  The
6614                  argument to frag_grow here must be at least as large
6615                  as the argument to all other calls to frag_grow in
6616                  this file.  We don't have to worry about being in the
6617                  middle of a variant frag, because the variants insert
6618                  all needed nop instructions themselves.  */
6619               frag_grow (40);
6620             }
6621
6622           mips_move_text_labels ();
6623
6624 #ifndef NO_ECOFF_DEBUGGING
6625           if (ECOFF_DEBUGGING)
6626             ecoff_fix_loc (old_frag, old_frag_offset);
6627 #endif
6628         }
6629     }
6630   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6631     {
6632       int nops;
6633
6634       /* Work out how many nops in prev_nop_frag are needed by IP,
6635          ignoring hazards generated by the first prev_nop_frag_since
6636          instructions.  */
6637       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6638       gas_assert (nops <= prev_nop_frag_holds);
6639
6640       /* Enforce NOPS as a minimum.  */
6641       if (nops > prev_nop_frag_required)
6642         prev_nop_frag_required = nops;
6643
6644       if (prev_nop_frag_holds == prev_nop_frag_required)
6645         {
6646           /* Settle for the current number of nops.  Update the history
6647              accordingly (for the benefit of any future .set reorder code).  */
6648           prev_nop_frag = NULL;
6649           insert_into_history (prev_nop_frag_since,
6650                                prev_nop_frag_holds, NOP_INSN);
6651         }
6652       else
6653         {
6654           /* Allow this instruction to replace one of the nops that was
6655              tentatively added to prev_nop_frag.  */
6656           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6657           prev_nop_frag_holds--;
6658           prev_nop_frag_since++;
6659         }
6660     }
6661
6662   method = get_append_method (ip, address_expr, reloc_type);
6663   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6664
6665   dwarf2_emit_insn (0);
6666   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6667      so "move" the instruction address accordingly.
6668
6669      Also, it doesn't seem appropriate for the assembler to reorder .loc
6670      entries.  If this instruction is a branch that we are going to swap
6671      with the previous instruction, the two instructions should be
6672      treated as a unit, and the debug information for both instructions
6673      should refer to the start of the branch sequence.  Using the
6674      current position is certainly wrong when swapping a 32-bit branch
6675      and a 16-bit delay slot, since the current position would then be
6676      in the middle of a branch.  */
6677   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6678
6679   relax32 = (mips_relax_branch
6680              /* Don't try branch relaxation within .set nomacro, or within
6681                 .set noat if we use $at for PIC computations.  If it turns
6682                 out that the branch was out-of-range, we'll get an error.  */
6683              && !mips_opts.warn_about_macros
6684              && (mips_opts.at || mips_pic == NO_PIC)
6685              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6686                 as they have no complementing branches.  */
6687              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6688
6689   if (!HAVE_CODE_COMPRESSION
6690       && address_expr
6691       && relax32
6692       && *reloc_type == BFD_RELOC_16_PCREL_S2
6693       && delayed_branch_p (ip))
6694     {
6695       relaxed_branch = TRUE;
6696       add_relaxed_insn (ip, (relaxed_branch_length
6697                              (NULL, NULL,
6698                               uncond_branch_p (ip) ? -1
6699                               : branch_likely_p (ip) ? 1
6700                               : 0)), 4,
6701                         RELAX_BRANCH_ENCODE
6702                         (AT,
6703                          uncond_branch_p (ip),
6704                          branch_likely_p (ip),
6705                          pinfo & INSN_WRITE_GPR_31,
6706                          0),
6707                         address_expr->X_add_symbol,
6708                         address_expr->X_add_number);
6709       *reloc_type = BFD_RELOC_UNUSED;
6710     }
6711   else if (mips_opts.micromips
6712            && address_expr
6713            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6714                || *reloc_type > BFD_RELOC_UNUSED)
6715            && (delayed_branch_p (ip) || compact_branch_p (ip))
6716            /* Don't try branch relaxation when users specify
6717               16-bit/32-bit instructions.  */
6718            && !forced_insn_length)
6719     {
6720       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6721       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6722       int uncond = uncond_branch_p (ip) ? -1 : 0;
6723       int compact = compact_branch_p (ip);
6724       int al = pinfo & INSN_WRITE_GPR_31;
6725       int length32;
6726
6727       gas_assert (address_expr != NULL);
6728       gas_assert (!mips_relax.sequence);
6729
6730       relaxed_branch = TRUE;
6731       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6732       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6733                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6734                                                 relax32, 0, 0),
6735                         address_expr->X_add_symbol,
6736                         address_expr->X_add_number);
6737       *reloc_type = BFD_RELOC_UNUSED;
6738     }
6739   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6740     {
6741       /* We need to set up a variant frag.  */
6742       gas_assert (address_expr != NULL);
6743       add_relaxed_insn (ip, 4, 0,
6744                         RELAX_MIPS16_ENCODE
6745                         (*reloc_type - BFD_RELOC_UNUSED,
6746                          forced_insn_length == 2, forced_insn_length == 4,
6747                          delayed_branch_p (&history[0]),
6748                          history[0].mips16_absolute_jump_p),
6749                         make_expr_symbol (address_expr), 0);
6750     }
6751   else if (mips_opts.mips16 && insn_length (ip) == 2)
6752     {
6753       if (!delayed_branch_p (ip))
6754         /* Make sure there is enough room to swap this instruction with
6755            a following jump instruction.  */
6756         frag_grow (6);
6757       add_fixed_insn (ip);
6758     }
6759   else
6760     {
6761       if (mips_opts.mips16
6762           && mips_opts.noreorder
6763           && delayed_branch_p (&history[0]))
6764         as_warn (_("extended instruction in delay slot"));
6765
6766       if (mips_relax.sequence)
6767         {
6768           /* If we've reached the end of this frag, turn it into a variant
6769              frag and record the information for the instructions we've
6770              written so far.  */
6771           if (frag_room () < 4)
6772             relax_close_frag ();
6773           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6774         }
6775
6776       if (mips_relax.sequence != 2)
6777         {
6778           if (mips_macro_warning.first_insn_sizes[0] == 0)
6779             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6780           mips_macro_warning.sizes[0] += insn_length (ip);
6781           mips_macro_warning.insns[0]++;
6782         }
6783       if (mips_relax.sequence != 1)
6784         {
6785           if (mips_macro_warning.first_insn_sizes[1] == 0)
6786             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6787           mips_macro_warning.sizes[1] += insn_length (ip);
6788           mips_macro_warning.insns[1]++;
6789         }
6790
6791       if (mips_opts.mips16)
6792         {
6793           ip->fixed_p = 1;
6794           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6795         }
6796       add_fixed_insn (ip);
6797     }
6798
6799   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6800     {
6801       bfd_reloc_code_real_type final_type[3];
6802       reloc_howto_type *howto0;
6803       reloc_howto_type *howto;
6804       int i;
6805
6806       /* Perform any necessary conversion to microMIPS relocations
6807          and find out how many relocations there actually are.  */
6808       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6809         final_type[i] = micromips_map_reloc (reloc_type[i]);
6810
6811       /* In a compound relocation, it is the final (outermost)
6812          operator that determines the relocated field.  */
6813       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6814       if (!howto)
6815         abort ();
6816
6817       if (i > 1)
6818         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6819       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6820                                  bfd_get_reloc_size (howto),
6821                                  address_expr,
6822                                  howto0 && howto0->pc_relative,
6823                                  final_type[0]);
6824
6825       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6826       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6827         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6828
6829       /* These relocations can have an addend that won't fit in
6830          4 octets for 64bit assembly.  */
6831       if (HAVE_64BIT_GPRS
6832           && ! howto->partial_inplace
6833           && (reloc_type[0] == BFD_RELOC_16
6834               || reloc_type[0] == BFD_RELOC_32
6835               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6836               || reloc_type[0] == BFD_RELOC_GPREL16
6837               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6838               || reloc_type[0] == BFD_RELOC_GPREL32
6839               || reloc_type[0] == BFD_RELOC_64
6840               || reloc_type[0] == BFD_RELOC_CTOR
6841               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6842               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6843               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6844               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6845               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6846               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6847               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6848               || hi16_reloc_p (reloc_type[0])
6849               || lo16_reloc_p (reloc_type[0])))
6850         ip->fixp[0]->fx_no_overflow = 1;
6851
6852       /* These relocations can have an addend that won't fit in 2 octets.  */
6853       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6854           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6855         ip->fixp[0]->fx_no_overflow = 1;
6856
6857       if (mips_relax.sequence)
6858         {
6859           if (mips_relax.first_fixup == 0)
6860             mips_relax.first_fixup = ip->fixp[0];
6861         }
6862       else if (reloc_needs_lo_p (*reloc_type))
6863         {
6864           struct mips_hi_fixup *hi_fixup;
6865
6866           /* Reuse the last entry if it already has a matching %lo.  */
6867           hi_fixup = mips_hi_fixup_list;
6868           if (hi_fixup == 0
6869               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6870             {
6871               hi_fixup = ((struct mips_hi_fixup *)
6872                           xmalloc (sizeof (struct mips_hi_fixup)));
6873               hi_fixup->next = mips_hi_fixup_list;
6874               mips_hi_fixup_list = hi_fixup;
6875             }
6876           hi_fixup->fixp = ip->fixp[0];
6877           hi_fixup->seg = now_seg;
6878         }
6879
6880       /* Add fixups for the second and third relocations, if given.
6881          Note that the ABI allows the second relocation to be
6882          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6883          moment we only use RSS_UNDEF, but we could add support
6884          for the others if it ever becomes necessary.  */
6885       for (i = 1; i < 3; i++)
6886         if (reloc_type[i] != BFD_RELOC_UNUSED)
6887           {
6888             ip->fixp[i] = fix_new (ip->frag, ip->where,
6889                                    ip->fixp[0]->fx_size, NULL, 0,
6890                                    FALSE, final_type[i]);
6891
6892             /* Use fx_tcbit to mark compound relocs.  */
6893             ip->fixp[0]->fx_tcbit = 1;
6894             ip->fixp[i]->fx_tcbit = 1;
6895           }
6896     }
6897   install_insn (ip);
6898
6899   /* Update the register mask information.  */
6900   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6901   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6902
6903   switch (method)
6904     {
6905     case APPEND_ADD:
6906       insert_into_history (0, 1, ip);
6907       break;
6908
6909     case APPEND_ADD_WITH_NOP:
6910       {
6911         struct mips_cl_insn *nop;
6912
6913         insert_into_history (0, 1, ip);
6914         nop = get_delay_slot_nop (ip);
6915         add_fixed_insn (nop);
6916         insert_into_history (0, 1, nop);
6917         if (mips_relax.sequence)
6918           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6919       }
6920       break;
6921
6922     case APPEND_ADD_COMPACT:
6923       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6924       gas_assert (mips_opts.mips16);
6925       ip->insn_opcode |= 0x0080;
6926       find_altered_mips16_opcode (ip);
6927       install_insn (ip);
6928       insert_into_history (0, 1, ip);
6929       break;
6930
6931     case APPEND_SWAP:
6932       {
6933         struct mips_cl_insn delay = history[0];
6934         if (mips_opts.mips16)
6935           {
6936             know (delay.frag == ip->frag);
6937             move_insn (ip, delay.frag, delay.where);
6938             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6939           }
6940         else if (relaxed_branch || delay.frag != ip->frag)
6941           {
6942             /* Add the delay slot instruction to the end of the
6943                current frag and shrink the fixed part of the
6944                original frag.  If the branch occupies the tail of
6945                the latter, move it backwards to cover the gap.  */
6946             delay.frag->fr_fix -= branch_disp;
6947             if (delay.frag == ip->frag)
6948               move_insn (ip, ip->frag, ip->where - branch_disp);
6949             add_fixed_insn (&delay);
6950           }
6951         else
6952           {
6953             move_insn (&delay, ip->frag,
6954                        ip->where - branch_disp + insn_length (ip));
6955             move_insn (ip, history[0].frag, history[0].where);
6956           }
6957         history[0] = *ip;
6958         delay.fixed_p = 1;
6959         insert_into_history (0, 1, &delay);
6960       }
6961       break;
6962     }
6963
6964   /* If we have just completed an unconditional branch, clear the history.  */
6965   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6966       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6967     {
6968       unsigned int i;
6969
6970       mips_no_prev_insn ();
6971
6972       for (i = 0; i < ARRAY_SIZE (history); i++)
6973         history[i].cleared_p = 1;
6974     }
6975
6976   /* We need to emit a label at the end of branch-likely macros.  */
6977   if (emit_branch_likely_macro)
6978     {
6979       emit_branch_likely_macro = FALSE;
6980       micromips_add_label ();
6981     }
6982
6983   /* We just output an insn, so the next one doesn't have a label.  */
6984   mips_clear_insn_labels ();
6985 }
6986
6987 /* Forget that there was any previous instruction or label.
6988    When BRANCH is true, the branch history is also flushed.  */
6989
6990 static void
6991 mips_no_prev_insn (void)
6992 {
6993   prev_nop_frag = NULL;
6994   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6995   mips_clear_insn_labels ();
6996 }
6997
6998 /* This function must be called before we emit something other than
6999    instructions.  It is like mips_no_prev_insn except that it inserts
7000    any NOPS that might be needed by previous instructions.  */
7001
7002 void
7003 mips_emit_delays (void)
7004 {
7005   if (! mips_opts.noreorder)
7006     {
7007       int nops = nops_for_insn (0, history, NULL);
7008       if (nops > 0)
7009         {
7010           while (nops-- > 0)
7011             add_fixed_insn (NOP_INSN);
7012           mips_move_text_labels ();
7013         }
7014     }
7015   mips_no_prev_insn ();
7016 }
7017
7018 /* Start a (possibly nested) noreorder block.  */
7019
7020 static void
7021 start_noreorder (void)
7022 {
7023   if (mips_opts.noreorder == 0)
7024     {
7025       unsigned int i;
7026       int nops;
7027
7028       /* None of the instructions before the .set noreorder can be moved.  */
7029       for (i = 0; i < ARRAY_SIZE (history); i++)
7030         history[i].fixed_p = 1;
7031
7032       /* Insert any nops that might be needed between the .set noreorder
7033          block and the previous instructions.  We will later remove any
7034          nops that turn out not to be needed.  */
7035       nops = nops_for_insn (0, history, NULL);
7036       if (nops > 0)
7037         {
7038           if (mips_optimize != 0)
7039             {
7040               /* Record the frag which holds the nop instructions, so
7041                  that we can remove them if we don't need them.  */
7042               frag_grow (nops * NOP_INSN_SIZE);
7043               prev_nop_frag = frag_now;
7044               prev_nop_frag_holds = nops;
7045               prev_nop_frag_required = 0;
7046               prev_nop_frag_since = 0;
7047             }
7048
7049           for (; nops > 0; --nops)
7050             add_fixed_insn (NOP_INSN);
7051
7052           /* Move on to a new frag, so that it is safe to simply
7053              decrease the size of prev_nop_frag.  */
7054           frag_wane (frag_now);
7055           frag_new (0);
7056           mips_move_text_labels ();
7057         }
7058       mips_mark_labels ();
7059       mips_clear_insn_labels ();
7060     }
7061   mips_opts.noreorder++;
7062   mips_any_noreorder = 1;
7063 }
7064
7065 /* End a nested noreorder block.  */
7066
7067 static void
7068 end_noreorder (void)
7069 {
7070   mips_opts.noreorder--;
7071   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7072     {
7073       /* Commit to inserting prev_nop_frag_required nops and go back to
7074          handling nop insertion the .set reorder way.  */
7075       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7076                                 * NOP_INSN_SIZE);
7077       insert_into_history (prev_nop_frag_since,
7078                            prev_nop_frag_required, NOP_INSN);
7079       prev_nop_frag = NULL;
7080     }
7081 }
7082
7083 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7084    higher bits unset.  */
7085
7086 static void
7087 normalize_constant_expr (expressionS *ex)
7088 {
7089   if (ex->X_op == O_constant
7090       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7091     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7092                         - 0x80000000);
7093 }
7094
7095 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7096    all higher bits unset.  */
7097
7098 static void
7099 normalize_address_expr (expressionS *ex)
7100 {
7101   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7102         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7103       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7104     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7105                         - 0x80000000);
7106 }
7107
7108 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7109    Return true if the match was successful.
7110
7111    OPCODE_EXTRA is a value that should be ORed into the opcode
7112    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7113    there are more alternatives after OPCODE and SOFT_MATCH is
7114    as for mips_arg_info.  */
7115
7116 static bfd_boolean
7117 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7118             struct mips_operand_token *tokens, unsigned int opcode_extra,
7119             bfd_boolean lax_match, bfd_boolean complete_p)
7120 {
7121   const char *args;
7122   struct mips_arg_info arg;
7123   const struct mips_operand *operand;
7124   char c;
7125
7126   imm_expr.X_op = O_absent;
7127   offset_expr.X_op = O_absent;
7128   offset_reloc[0] = BFD_RELOC_UNUSED;
7129   offset_reloc[1] = BFD_RELOC_UNUSED;
7130   offset_reloc[2] = BFD_RELOC_UNUSED;
7131
7132   create_insn (insn, opcode);
7133   /* When no opcode suffix is specified, assume ".xyzw". */
7134   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7135     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7136   else
7137     insn->insn_opcode |= opcode_extra;
7138   memset (&arg, 0, sizeof (arg));
7139   arg.insn = insn;
7140   arg.token = tokens;
7141   arg.argnum = 1;
7142   arg.last_regno = ILLEGAL_REG;
7143   arg.dest_regno = ILLEGAL_REG;
7144   arg.lax_match = lax_match;
7145   for (args = opcode->args;; ++args)
7146     {
7147       if (arg.token->type == OT_END)
7148         {
7149           /* Handle unary instructions in which only one operand is given.
7150              The source is then the same as the destination.  */
7151           if (arg.opnum == 1 && *args == ',')
7152             {
7153               operand = (mips_opts.micromips
7154                          ? decode_micromips_operand (args + 1)
7155                          : decode_mips_operand (args + 1));
7156               if (operand && mips_optional_operand_p (operand))
7157                 {
7158                   arg.token = tokens;
7159                   arg.argnum = 1;
7160                   continue;
7161                 }
7162             }
7163
7164           /* Treat elided base registers as $0.  */
7165           if (strcmp (args, "(b)") == 0)
7166             args += 3;
7167
7168           if (args[0] == '+')
7169             switch (args[1])
7170               {
7171               case 'K':
7172               case 'N':
7173                 /* The register suffix is optional. */
7174                 args += 2;
7175                 break;
7176               }
7177
7178           /* Fail the match if there were too few operands.  */
7179           if (*args)
7180             return FALSE;
7181
7182           /* Successful match.  */
7183           if (!complete_p)
7184             return TRUE;
7185           clear_insn_error ();
7186           if (arg.dest_regno == arg.last_regno
7187               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7188             {
7189               if (arg.opnum == 2)
7190                 set_insn_error
7191                   (0, _("source and destination must be different"));
7192               else if (arg.last_regno == 31)
7193                 set_insn_error
7194                   (0, _("a destination register must be supplied"));
7195             }
7196           else if (arg.last_regno == 31
7197                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7198                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7199             set_insn_error (0, _("the source register must not be $31"));
7200           check_completed_insn (&arg);
7201           return TRUE;
7202         }
7203
7204       /* Fail the match if the line has too many operands.   */
7205       if (*args == 0)
7206         return FALSE;
7207
7208       /* Handle characters that need to match exactly.  */
7209       if (*args == '(' || *args == ')' || *args == ',')
7210         {
7211           if (match_char (&arg, *args))
7212             continue;
7213           return FALSE;
7214         }
7215       if (*args == '#')
7216         {
7217           ++args;
7218           if (arg.token->type == OT_DOUBLE_CHAR
7219               && arg.token->u.ch == *args)
7220             {
7221               ++arg.token;
7222               continue;
7223             }
7224           return FALSE;
7225         }
7226
7227       /* Handle special macro operands.  Work out the properties of
7228          other operands.  */
7229       arg.opnum += 1;
7230       switch (*args)
7231         {
7232         case '+':
7233           switch (args[1])
7234             {
7235             case 'i':
7236               *offset_reloc = BFD_RELOC_MIPS_JMP;
7237               break;
7238             }
7239           break;
7240
7241         case 'I':
7242           if (!match_const_int (&arg, &imm_expr.X_add_number))
7243             return FALSE;
7244           imm_expr.X_op = O_constant;
7245           if (HAVE_32BIT_GPRS)
7246             normalize_constant_expr (&imm_expr);
7247           continue;
7248
7249         case 'A':
7250           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7251             {
7252               /* Assume that the offset has been elided and that what
7253                  we saw was a base register.  The match will fail later
7254                  if that assumption turns out to be wrong.  */
7255               offset_expr.X_op = O_constant;
7256               offset_expr.X_add_number = 0;
7257             }
7258           else
7259             {
7260               if (!match_expression (&arg, &offset_expr, offset_reloc))
7261                 return FALSE;
7262               normalize_address_expr (&offset_expr);
7263             }
7264           continue;
7265
7266         case 'F':
7267           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7268                                      8, TRUE))
7269             return FALSE;
7270           continue;
7271
7272         case 'L':
7273           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7274                                      8, FALSE))
7275             return FALSE;
7276           continue;
7277
7278         case 'f':
7279           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7280                                      4, TRUE))
7281             return FALSE;
7282           continue;
7283
7284         case 'l':
7285           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7286                                      4, FALSE))
7287             return FALSE;
7288           continue;
7289
7290         case 'p':
7291           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7292           break;
7293
7294         case 'a':
7295           *offset_reloc = BFD_RELOC_MIPS_JMP;
7296           break;
7297
7298         case 'm':
7299           gas_assert (mips_opts.micromips);
7300           c = args[1];
7301           switch (c)
7302             {
7303             case 'D':
7304             case 'E':
7305               if (!forced_insn_length)
7306                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7307               else if (c == 'D')
7308                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7309               else
7310                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7311               break;
7312             }
7313           break;
7314         }
7315
7316       operand = (mips_opts.micromips
7317                  ? decode_micromips_operand (args)
7318                  : decode_mips_operand (args));
7319       if (!operand)
7320         abort ();
7321
7322       /* Skip prefixes.  */
7323       if (*args == '+' || *args == 'm')
7324         args++;
7325
7326       if (mips_optional_operand_p (operand)
7327           && args[1] == ','
7328           && (arg.token[0].type != OT_REG
7329               || arg.token[1].type == OT_END))
7330         {
7331           /* Assume that the register has been elided and is the
7332              same as the first operand.  */
7333           arg.token = tokens;
7334           arg.argnum = 1;
7335         }
7336
7337       if (!match_operand (&arg, operand))
7338         return FALSE;
7339     }
7340 }
7341
7342 /* Like match_insn, but for MIPS16.  */
7343
7344 static bfd_boolean
7345 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7346                    struct mips_operand_token *tokens)
7347 {
7348   const char *args;
7349   const struct mips_operand *operand;
7350   const struct mips_operand *ext_operand;
7351   struct mips_arg_info arg;
7352   int relax_char;
7353
7354   create_insn (insn, opcode);
7355   imm_expr.X_op = O_absent;
7356   offset_expr.X_op = O_absent;
7357   offset_reloc[0] = BFD_RELOC_UNUSED;
7358   offset_reloc[1] = BFD_RELOC_UNUSED;
7359   offset_reloc[2] = BFD_RELOC_UNUSED;
7360   relax_char = 0;
7361
7362   memset (&arg, 0, sizeof (arg));
7363   arg.insn = insn;
7364   arg.token = tokens;
7365   arg.argnum = 1;
7366   arg.last_regno = ILLEGAL_REG;
7367   arg.dest_regno = ILLEGAL_REG;
7368   relax_char = 0;
7369   for (args = opcode->args;; ++args)
7370     {
7371       int c;
7372
7373       if (arg.token->type == OT_END)
7374         {
7375           offsetT value;
7376
7377           /* Handle unary instructions in which only one operand is given.
7378              The source is then the same as the destination.  */
7379           if (arg.opnum == 1 && *args == ',')
7380             {
7381               operand = decode_mips16_operand (args[1], FALSE);
7382               if (operand && mips_optional_operand_p (operand))
7383                 {
7384                   arg.token = tokens;
7385                   arg.argnum = 1;
7386                   continue;
7387                 }
7388             }
7389
7390           /* Fail the match if there were too few operands.  */
7391           if (*args)
7392             return FALSE;
7393
7394           /* Successful match.  Stuff the immediate value in now, if
7395              we can.  */
7396           clear_insn_error ();
7397           if (opcode->pinfo == INSN_MACRO)
7398             {
7399               gas_assert (relax_char == 0 || relax_char == 'p');
7400               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7401             }
7402           else if (relax_char
7403                    && offset_expr.X_op == O_constant
7404                    && calculate_reloc (*offset_reloc,
7405                                        offset_expr.X_add_number,
7406                                        &value))
7407             {
7408               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7409                             forced_insn_length, &insn->insn_opcode);
7410               offset_expr.X_op = O_absent;
7411               *offset_reloc = BFD_RELOC_UNUSED;
7412             }
7413           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7414             {
7415               if (forced_insn_length == 2)
7416                 set_insn_error (0, _("invalid unextended operand value"));
7417               forced_insn_length = 4;
7418               insn->insn_opcode |= MIPS16_EXTEND;
7419             }
7420           else if (relax_char)
7421             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7422
7423           check_completed_insn (&arg);
7424           return TRUE;
7425         }
7426
7427       /* Fail the match if the line has too many operands.   */
7428       if (*args == 0)
7429         return FALSE;
7430
7431       /* Handle characters that need to match exactly.  */
7432       if (*args == '(' || *args == ')' || *args == ',')
7433         {
7434           if (match_char (&arg, *args))
7435             continue;
7436           return FALSE;
7437         }
7438
7439       arg.opnum += 1;
7440       c = *args;
7441       switch (c)
7442         {
7443         case 'p':
7444         case 'q':
7445         case 'A':
7446         case 'B':
7447         case 'E':
7448           relax_char = c;
7449           break;
7450
7451         case 'I':
7452           if (!match_const_int (&arg, &imm_expr.X_add_number))
7453             return FALSE;
7454           imm_expr.X_op = O_constant;
7455           if (HAVE_32BIT_GPRS)
7456             normalize_constant_expr (&imm_expr);
7457           continue;
7458
7459         case 'a':
7460         case 'i':
7461           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7462           insn->insn_opcode <<= 16;
7463           break;
7464         }
7465
7466       operand = decode_mips16_operand (c, FALSE);
7467       if (!operand)
7468         abort ();
7469
7470       /* '6' is a special case.  It is used for BREAK and SDBBP,
7471          whose operands are only meaningful to the software that decodes
7472          them.  This means that there is no architectural reason why
7473          they cannot be prefixed by EXTEND, but in practice,
7474          exception handlers will only look at the instruction
7475          itself.  We therefore allow '6' to be extended when
7476          disassembling but not when assembling.  */
7477       if (operand->type != OP_PCREL && c != '6')
7478         {
7479           ext_operand = decode_mips16_operand (c, TRUE);
7480           if (operand != ext_operand)
7481             {
7482               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7483                 {
7484                   offset_expr.X_op = O_constant;
7485                   offset_expr.X_add_number = 0;
7486                   relax_char = c;
7487                   continue;
7488                 }
7489
7490               /* We need the OT_INTEGER check because some MIPS16
7491                  immediate variants are listed before the register ones.  */
7492               if (arg.token->type != OT_INTEGER
7493                   || !match_expression (&arg, &offset_expr, offset_reloc))
7494                 return FALSE;
7495
7496               /* '8' is used for SLTI(U) and has traditionally not
7497                  been allowed to take relocation operators.  */
7498               if (offset_reloc[0] != BFD_RELOC_UNUSED
7499                   && (ext_operand->size != 16 || c == '8'))
7500                 return FALSE;
7501
7502               relax_char = c;
7503               continue;
7504             }
7505         }
7506
7507       if (mips_optional_operand_p (operand)
7508           && args[1] == ','
7509           && (arg.token[0].type != OT_REG
7510               || arg.token[1].type == OT_END))
7511         {
7512           /* Assume that the register has been elided and is the
7513              same as the first operand.  */
7514           arg.token = tokens;
7515           arg.argnum = 1;
7516         }
7517
7518       if (!match_operand (&arg, operand))
7519         return FALSE;
7520     }
7521 }
7522
7523 /* Record that the current instruction is invalid for the current ISA.  */
7524
7525 static void
7526 match_invalid_for_isa (void)
7527 {
7528   set_insn_error_ss
7529     (0, _("opcode not supported on this processor: %s (%s)"),
7530      mips_cpu_info_from_arch (mips_opts.arch)->name,
7531      mips_cpu_info_from_isa (mips_opts.isa)->name);
7532 }
7533
7534 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7535    Return true if a definite match or failure was found, storing any match
7536    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7537    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7538    tried and failed to match under normal conditions and now want to try a
7539    more relaxed match.  */
7540
7541 static bfd_boolean
7542 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7543              const struct mips_opcode *past, struct mips_operand_token *tokens,
7544              int opcode_extra, bfd_boolean lax_match)
7545 {
7546   const struct mips_opcode *opcode;
7547   const struct mips_opcode *invalid_delay_slot;
7548   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7549
7550   /* Search for a match, ignoring alternatives that don't satisfy the
7551      current ISA or forced_length.  */
7552   invalid_delay_slot = 0;
7553   seen_valid_for_isa = FALSE;
7554   seen_valid_for_size = FALSE;
7555   opcode = first;
7556   do
7557     {
7558       gas_assert (strcmp (opcode->name, first->name) == 0);
7559       if (is_opcode_valid (opcode))
7560         {
7561           seen_valid_for_isa = TRUE;
7562           if (is_size_valid (opcode))
7563             {
7564               bfd_boolean delay_slot_ok;
7565
7566               seen_valid_for_size = TRUE;
7567               delay_slot_ok = is_delay_slot_valid (opcode);
7568               if (match_insn (insn, opcode, tokens, opcode_extra,
7569                               lax_match, delay_slot_ok))
7570                 {
7571                   if (!delay_slot_ok)
7572                     {
7573                       if (!invalid_delay_slot)
7574                         invalid_delay_slot = opcode;
7575                     }
7576                   else
7577                     return TRUE;
7578                 }
7579             }
7580         }
7581       ++opcode;
7582     }
7583   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7584
7585   /* If the only matches we found had the wrong length for the delay slot,
7586      pick the first such match.  We'll issue an appropriate warning later.  */
7587   if (invalid_delay_slot)
7588     {
7589       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7590                       lax_match, TRUE))
7591         return TRUE;
7592       abort ();
7593     }
7594
7595   /* Handle the case where we didn't try to match an instruction because
7596      all the alternatives were incompatible with the current ISA.  */
7597   if (!seen_valid_for_isa)
7598     {
7599       match_invalid_for_isa ();
7600       return TRUE;
7601     }
7602
7603   /* Handle the case where we didn't try to match an instruction because
7604      all the alternatives were of the wrong size.  */
7605   if (!seen_valid_for_size)
7606     {
7607       if (mips_opts.insn32)
7608         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7609       else
7610         set_insn_error_i
7611           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7612            8 * forced_insn_length);
7613       return TRUE;
7614     }
7615
7616   return FALSE;
7617 }
7618
7619 /* Like match_insns, but for MIPS16.  */
7620
7621 static bfd_boolean
7622 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7623                     struct mips_operand_token *tokens)
7624 {
7625   const struct mips_opcode *opcode;
7626   bfd_boolean seen_valid_for_isa;
7627
7628   /* Search for a match, ignoring alternatives that don't satisfy the
7629      current ISA.  There are no separate entries for extended forms so
7630      we deal with forced_length later.  */
7631   seen_valid_for_isa = FALSE;
7632   opcode = first;
7633   do
7634     {
7635       gas_assert (strcmp (opcode->name, first->name) == 0);
7636       if (is_opcode_valid_16 (opcode))
7637         {
7638           seen_valid_for_isa = TRUE;
7639           if (match_mips16_insn (insn, opcode, tokens))
7640             return TRUE;
7641         }
7642       ++opcode;
7643     }
7644   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7645          && strcmp (opcode->name, first->name) == 0);
7646
7647   /* Handle the case where we didn't try to match an instruction because
7648      all the alternatives were incompatible with the current ISA.  */
7649   if (!seen_valid_for_isa)
7650     {
7651       match_invalid_for_isa ();
7652       return TRUE;
7653     }
7654
7655   return FALSE;
7656 }
7657
7658 /* Set up global variables for the start of a new macro.  */
7659
7660 static void
7661 macro_start (void)
7662 {
7663   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7664   memset (&mips_macro_warning.first_insn_sizes, 0,
7665           sizeof (mips_macro_warning.first_insn_sizes));
7666   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7667   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7668                                      && delayed_branch_p (&history[0]));
7669   switch (history[0].insn_mo->pinfo2
7670           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7671     {
7672     case INSN2_BRANCH_DELAY_32BIT:
7673       mips_macro_warning.delay_slot_length = 4;
7674       break;
7675     case INSN2_BRANCH_DELAY_16BIT:
7676       mips_macro_warning.delay_slot_length = 2;
7677       break;
7678     default:
7679       mips_macro_warning.delay_slot_length = 0;
7680       break;
7681     }
7682   mips_macro_warning.first_frag = NULL;
7683 }
7684
7685 /* Given that a macro is longer than one instruction or of the wrong size,
7686    return the appropriate warning for it.  Return null if no warning is
7687    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7688    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7689    and RELAX_NOMACRO.  */
7690
7691 static const char *
7692 macro_warning (relax_substateT subtype)
7693 {
7694   if (subtype & RELAX_DELAY_SLOT)
7695     return _("macro instruction expanded into multiple instructions"
7696              " in a branch delay slot");
7697   else if (subtype & RELAX_NOMACRO)
7698     return _("macro instruction expanded into multiple instructions");
7699   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7700                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7701     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7702             ? _("macro instruction expanded into a wrong size instruction"
7703                 " in a 16-bit branch delay slot")
7704             : _("macro instruction expanded into a wrong size instruction"
7705                 " in a 32-bit branch delay slot"));
7706   else
7707     return 0;
7708 }
7709
7710 /* Finish up a macro.  Emit warnings as appropriate.  */
7711
7712 static void
7713 macro_end (void)
7714 {
7715   /* Relaxation warning flags.  */
7716   relax_substateT subtype = 0;
7717
7718   /* Check delay slot size requirements.  */
7719   if (mips_macro_warning.delay_slot_length == 2)
7720     subtype |= RELAX_DELAY_SLOT_16BIT;
7721   if (mips_macro_warning.delay_slot_length != 0)
7722     {
7723       if (mips_macro_warning.delay_slot_length
7724           != mips_macro_warning.first_insn_sizes[0])
7725         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7726       if (mips_macro_warning.delay_slot_length
7727           != mips_macro_warning.first_insn_sizes[1])
7728         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7729     }
7730
7731   /* Check instruction count requirements.  */
7732   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7733     {
7734       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7735         subtype |= RELAX_SECOND_LONGER;
7736       if (mips_opts.warn_about_macros)
7737         subtype |= RELAX_NOMACRO;
7738       if (mips_macro_warning.delay_slot_p)
7739         subtype |= RELAX_DELAY_SLOT;
7740     }
7741
7742   /* If both alternatives fail to fill a delay slot correctly,
7743      emit the warning now.  */
7744   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7745       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7746     {
7747       relax_substateT s;
7748       const char *msg;
7749
7750       s = subtype & (RELAX_DELAY_SLOT_16BIT
7751                      | RELAX_DELAY_SLOT_SIZE_FIRST
7752                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7753       msg = macro_warning (s);
7754       if (msg != NULL)
7755         as_warn ("%s", msg);
7756       subtype &= ~s;
7757     }
7758
7759   /* If both implementations are longer than 1 instruction, then emit the
7760      warning now.  */
7761   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7762     {
7763       relax_substateT s;
7764       const char *msg;
7765
7766       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7767       msg = macro_warning (s);
7768       if (msg != NULL)
7769         as_warn ("%s", msg);
7770       subtype &= ~s;
7771     }
7772
7773   /* If any flags still set, then one implementation might need a warning
7774      and the other either will need one of a different kind or none at all.
7775      Pass any remaining flags over to relaxation.  */
7776   if (mips_macro_warning.first_frag != NULL)
7777     mips_macro_warning.first_frag->fr_subtype |= subtype;
7778 }
7779
7780 /* Instruction operand formats used in macros that vary between
7781    standard MIPS and microMIPS code.  */
7782
7783 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7784 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7785 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7786 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7787 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7788 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7789 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7790 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7791
7792 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7793 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7794 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7795 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7796 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7797 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7798 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7799 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7800
7801 /* Read a macro's relocation codes from *ARGS and store them in *R.
7802    The first argument in *ARGS will be either the code for a single
7803    relocation or -1 followed by the three codes that make up a
7804    composite relocation.  */
7805
7806 static void
7807 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7808 {
7809   int i, next;
7810
7811   next = va_arg (*args, int);
7812   if (next >= 0)
7813     r[0] = (bfd_reloc_code_real_type) next;
7814   else
7815     {
7816       for (i = 0; i < 3; i++)
7817         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7818       /* This function is only used for 16-bit relocation fields.
7819          To make the macro code simpler, treat an unrelocated value
7820          in the same way as BFD_RELOC_LO16.  */
7821       if (r[0] == BFD_RELOC_UNUSED)
7822         r[0] = BFD_RELOC_LO16;
7823     }
7824 }
7825
7826 /* Build an instruction created by a macro expansion.  This is passed
7827    a pointer to the count of instructions created so far, an
7828    expression, the name of the instruction to build, an operand format
7829    string, and corresponding arguments.  */
7830
7831 static void
7832 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7833 {
7834   const struct mips_opcode *mo = NULL;
7835   bfd_reloc_code_real_type r[3];
7836   const struct mips_opcode *amo;
7837   const struct mips_operand *operand;
7838   struct hash_control *hash;
7839   struct mips_cl_insn insn;
7840   va_list args;
7841   unsigned int uval;
7842
7843   va_start (args, fmt);
7844
7845   if (mips_opts.mips16)
7846     {
7847       mips16_macro_build (ep, name, fmt, &args);
7848       va_end (args);
7849       return;
7850     }
7851
7852   r[0] = BFD_RELOC_UNUSED;
7853   r[1] = BFD_RELOC_UNUSED;
7854   r[2] = BFD_RELOC_UNUSED;
7855   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7856   amo = (struct mips_opcode *) hash_find (hash, name);
7857   gas_assert (amo);
7858   gas_assert (strcmp (name, amo->name) == 0);
7859
7860   do
7861     {
7862       /* Search until we get a match for NAME.  It is assumed here that
7863          macros will never generate MDMX, MIPS-3D, or MT instructions.
7864          We try to match an instruction that fulfils the branch delay
7865          slot instruction length requirement (if any) of the previous
7866          instruction.  While doing this we record the first instruction
7867          seen that matches all the other conditions and use it anyway
7868          if the requirement cannot be met; we will issue an appropriate
7869          warning later on.  */
7870       if (strcmp (fmt, amo->args) == 0
7871           && amo->pinfo != INSN_MACRO
7872           && is_opcode_valid (amo)
7873           && is_size_valid (amo))
7874         {
7875           if (is_delay_slot_valid (amo))
7876             {
7877               mo = amo;
7878               break;
7879             }
7880           else if (!mo)
7881             mo = amo;
7882         }
7883
7884       ++amo;
7885       gas_assert (amo->name);
7886     }
7887   while (strcmp (name, amo->name) == 0);
7888
7889   gas_assert (mo);
7890   create_insn (&insn, mo);
7891   for (; *fmt; ++fmt)
7892     {
7893       switch (*fmt)
7894         {
7895         case ',':
7896         case '(':
7897         case ')':
7898         case 'z':
7899           break;
7900
7901         case 'i':
7902         case 'j':
7903           macro_read_relocs (&args, r);
7904           gas_assert (*r == BFD_RELOC_GPREL16
7905                       || *r == BFD_RELOC_MIPS_HIGHER
7906                       || *r == BFD_RELOC_HI16_S
7907                       || *r == BFD_RELOC_LO16
7908                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7909           break;
7910
7911         case 'o':
7912           macro_read_relocs (&args, r);
7913           break;
7914
7915         case 'u':
7916           macro_read_relocs (&args, r);
7917           gas_assert (ep != NULL
7918                       && (ep->X_op == O_constant
7919                           || (ep->X_op == O_symbol
7920                               && (*r == BFD_RELOC_MIPS_HIGHEST
7921                                   || *r == BFD_RELOC_HI16_S
7922                                   || *r == BFD_RELOC_HI16
7923                                   || *r == BFD_RELOC_GPREL16
7924                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7925                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7926           break;
7927
7928         case 'p':
7929           gas_assert (ep != NULL);
7930
7931           /*
7932            * This allows macro() to pass an immediate expression for
7933            * creating short branches without creating a symbol.
7934            *
7935            * We don't allow branch relaxation for these branches, as
7936            * they should only appear in ".set nomacro" anyway.
7937            */
7938           if (ep->X_op == O_constant)
7939             {
7940               /* For microMIPS we always use relocations for branches.
7941                  So we should not resolve immediate values.  */
7942               gas_assert (!mips_opts.micromips);
7943
7944               if ((ep->X_add_number & 3) != 0)
7945                 as_bad (_("branch to misaligned address (0x%lx)"),
7946                         (unsigned long) ep->X_add_number);
7947               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7948                 as_bad (_("branch address range overflow (0x%lx)"),
7949                         (unsigned long) ep->X_add_number);
7950               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7951               ep = NULL;
7952             }
7953           else
7954             *r = BFD_RELOC_16_PCREL_S2;
7955           break;
7956
7957         case 'a':
7958           gas_assert (ep != NULL);
7959           *r = BFD_RELOC_MIPS_JMP;
7960           break;
7961
7962         default:
7963           operand = (mips_opts.micromips
7964                      ? decode_micromips_operand (fmt)
7965                      : decode_mips_operand (fmt));
7966           if (!operand)
7967             abort ();
7968
7969           uval = va_arg (args, int);
7970           if (operand->type == OP_CLO_CLZ_DEST)
7971             uval |= (uval << 5);
7972           insn_insert_operand (&insn, operand, uval);
7973
7974           if (*fmt == '+' || *fmt == 'm')
7975             ++fmt;
7976           break;
7977         }
7978     }
7979   va_end (args);
7980   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7981
7982   append_insn (&insn, ep, r, TRUE);
7983 }
7984
7985 static void
7986 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7987                     va_list *args)
7988 {
7989   struct mips_opcode *mo;
7990   struct mips_cl_insn insn;
7991   const struct mips_operand *operand;
7992   bfd_reloc_code_real_type r[3]
7993     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7994
7995   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7996   gas_assert (mo);
7997   gas_assert (strcmp (name, mo->name) == 0);
7998
7999   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8000     {
8001       ++mo;
8002       gas_assert (mo->name);
8003       gas_assert (strcmp (name, mo->name) == 0);
8004     }
8005
8006   create_insn (&insn, mo);
8007   for (; *fmt; ++fmt)
8008     {
8009       int c;
8010
8011       c = *fmt;
8012       switch (c)
8013         {
8014         case ',':
8015         case '(':
8016         case ')':
8017           break;
8018
8019         case '0':
8020         case 'S':
8021         case 'P':
8022         case 'R':
8023           break;
8024
8025         case '<':
8026         case '>':
8027         case '4':
8028         case '5':
8029         case 'H':
8030         case 'W':
8031         case 'D':
8032         case 'j':
8033         case '8':
8034         case 'V':
8035         case 'C':
8036         case 'U':
8037         case 'k':
8038         case 'K':
8039         case 'p':
8040         case 'q':
8041           {
8042             offsetT value;
8043
8044             gas_assert (ep != NULL);
8045
8046             if (ep->X_op != O_constant)
8047               *r = (int) BFD_RELOC_UNUSED + c;
8048             else if (calculate_reloc (*r, ep->X_add_number, &value))
8049               {
8050                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8051                 ep = NULL;
8052                 *r = BFD_RELOC_UNUSED;
8053               }
8054           }
8055           break;
8056
8057         default:
8058           operand = decode_mips16_operand (c, FALSE);
8059           if (!operand)
8060             abort ();
8061
8062           insn_insert_operand (&insn, operand, va_arg (*args, int));
8063           break;
8064         }
8065     }
8066
8067   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8068
8069   append_insn (&insn, ep, r, TRUE);
8070 }
8071
8072 /*
8073  * Generate a "jalr" instruction with a relocation hint to the called
8074  * function.  This occurs in NewABI PIC code.
8075  */
8076 static void
8077 macro_build_jalr (expressionS *ep, int cprestore)
8078 {
8079   static const bfd_reloc_code_real_type jalr_relocs[2]
8080     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8081   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8082   const char *jalr;
8083   char *f = NULL;
8084
8085   if (MIPS_JALR_HINT_P (ep))
8086     {
8087       frag_grow (8);
8088       f = frag_more (0);
8089     }
8090   if (mips_opts.micromips)
8091     {
8092       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8093               ? "jalr" : "jalrs");
8094       if (MIPS_JALR_HINT_P (ep)
8095           || mips_opts.insn32
8096           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8097         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8098       else
8099         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8100     }
8101   else
8102     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8103   if (MIPS_JALR_HINT_P (ep))
8104     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8105 }
8106
8107 /*
8108  * Generate a "lui" instruction.
8109  */
8110 static void
8111 macro_build_lui (expressionS *ep, int regnum)
8112 {
8113   gas_assert (! mips_opts.mips16);
8114
8115   if (ep->X_op != O_constant)
8116     {
8117       gas_assert (ep->X_op == O_symbol);
8118       /* _gp_disp is a special case, used from s_cpload.
8119          __gnu_local_gp is used if mips_no_shared.  */
8120       gas_assert (mips_pic == NO_PIC
8121               || (! HAVE_NEWABI
8122                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8123               || (! mips_in_shared
8124                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8125                              "__gnu_local_gp") == 0));
8126     }
8127
8128   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8129 }
8130
8131 /* Generate a sequence of instructions to do a load or store from a constant
8132    offset off of a base register (breg) into/from a target register (treg),
8133    using AT if necessary.  */
8134 static void
8135 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8136                               int treg, int breg, int dbl)
8137 {
8138   gas_assert (ep->X_op == O_constant);
8139
8140   /* Sign-extending 32-bit constants makes their handling easier.  */
8141   if (!dbl)
8142     normalize_constant_expr (ep);
8143
8144   /* Right now, this routine can only handle signed 32-bit constants.  */
8145   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8146     as_warn (_("operand overflow"));
8147
8148   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8149     {
8150       /* Signed 16-bit offset will fit in the op.  Easy!  */
8151       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8152     }
8153   else
8154     {
8155       /* 32-bit offset, need multiple instructions and AT, like:
8156            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8157            addu     $tempreg,$tempreg,$breg
8158            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8159          to handle the complete offset.  */
8160       macro_build_lui (ep, AT);
8161       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8162       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8163
8164       if (!mips_opts.at)
8165         as_bad (_("macro used $at after \".set noat\""));
8166     }
8167 }
8168
8169 /*                      set_at()
8170  * Generates code to set the $at register to true (one)
8171  * if reg is less than the immediate expression.
8172  */
8173 static void
8174 set_at (int reg, int unsignedp)
8175 {
8176   if (imm_expr.X_add_number >= -0x8000
8177       && imm_expr.X_add_number < 0x8000)
8178     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8179                  AT, reg, BFD_RELOC_LO16);
8180   else
8181     {
8182       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8183       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8184     }
8185 }
8186
8187 /* Count the leading zeroes by performing a binary chop. This is a
8188    bulky bit of source, but performance is a LOT better for the
8189    majority of values than a simple loop to count the bits:
8190        for (lcnt = 0; (lcnt < 32); lcnt++)
8191          if ((v) & (1 << (31 - lcnt)))
8192            break;
8193   However it is not code size friendly, and the gain will drop a bit
8194   on certain cached systems.
8195 */
8196 #define COUNT_TOP_ZEROES(v)             \
8197   (((v) & ~0xffff) == 0                 \
8198    ? ((v) & ~0xff) == 0                 \
8199      ? ((v) & ~0xf) == 0                \
8200        ? ((v) & ~0x3) == 0              \
8201          ? ((v) & ~0x1) == 0            \
8202            ? !(v)                       \
8203              ? 32                       \
8204              : 31                       \
8205            : 30                         \
8206          : ((v) & ~0x7) == 0            \
8207            ? 29                         \
8208            : 28                         \
8209        : ((v) & ~0x3f) == 0             \
8210          ? ((v) & ~0x1f) == 0           \
8211            ? 27                         \
8212            : 26                         \
8213          : ((v) & ~0x7f) == 0           \
8214            ? 25                         \
8215            : 24                         \
8216      : ((v) & ~0xfff) == 0              \
8217        ? ((v) & ~0x3ff) == 0            \
8218          ? ((v) & ~0x1ff) == 0          \
8219            ? 23                         \
8220            : 22                         \
8221          : ((v) & ~0x7ff) == 0          \
8222            ? 21                         \
8223            : 20                         \
8224        : ((v) & ~0x3fff) == 0           \
8225          ? ((v) & ~0x1fff) == 0         \
8226            ? 19                         \
8227            : 18                         \
8228          : ((v) & ~0x7fff) == 0         \
8229            ? 17                         \
8230            : 16                         \
8231    : ((v) & ~0xffffff) == 0             \
8232      ? ((v) & ~0xfffff) == 0            \
8233        ? ((v) & ~0x3ffff) == 0          \
8234          ? ((v) & ~0x1ffff) == 0        \
8235            ? 15                         \
8236            : 14                         \
8237          : ((v) & ~0x7ffff) == 0        \
8238            ? 13                         \
8239            : 12                         \
8240        : ((v) & ~0x3fffff) == 0         \
8241          ? ((v) & ~0x1fffff) == 0       \
8242            ? 11                         \
8243            : 10                         \
8244          : ((v) & ~0x7fffff) == 0       \
8245            ? 9                          \
8246            : 8                          \
8247      : ((v) & ~0xfffffff) == 0          \
8248        ? ((v) & ~0x3ffffff) == 0        \
8249          ? ((v) & ~0x1ffffff) == 0      \
8250            ? 7                          \
8251            : 6                          \
8252          : ((v) & ~0x7ffffff) == 0      \
8253            ? 5                          \
8254            : 4                          \
8255        : ((v) & ~0x3fffffff) == 0       \
8256          ? ((v) & ~0x1fffffff) == 0     \
8257            ? 3                          \
8258            : 2                          \
8259          : ((v) & ~0x7fffffff) == 0     \
8260            ? 1                          \
8261            : 0)
8262
8263 /*                      load_register()
8264  *  This routine generates the least number of instructions necessary to load
8265  *  an absolute expression value into a register.
8266  */
8267 static void
8268 load_register (int reg, expressionS *ep, int dbl)
8269 {
8270   int freg;
8271   expressionS hi32, lo32;
8272
8273   if (ep->X_op != O_big)
8274     {
8275       gas_assert (ep->X_op == O_constant);
8276
8277       /* Sign-extending 32-bit constants makes their handling easier.  */
8278       if (!dbl)
8279         normalize_constant_expr (ep);
8280
8281       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8282         {
8283           /* We can handle 16 bit signed values with an addiu to
8284              $zero.  No need to ever use daddiu here, since $zero and
8285              the result are always correct in 32 bit mode.  */
8286           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8287           return;
8288         }
8289       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8290         {
8291           /* We can handle 16 bit unsigned values with an ori to
8292              $zero.  */
8293           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8294           return;
8295         }
8296       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8297         {
8298           /* 32 bit values require an lui.  */
8299           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8300           if ((ep->X_add_number & 0xffff) != 0)
8301             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8302           return;
8303         }
8304     }
8305
8306   /* The value is larger than 32 bits.  */
8307
8308   if (!dbl || HAVE_32BIT_GPRS)
8309     {
8310       char value[32];
8311
8312       sprintf_vma (value, ep->X_add_number);
8313       as_bad (_("number (0x%s) larger than 32 bits"), value);
8314       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8315       return;
8316     }
8317
8318   if (ep->X_op != O_big)
8319     {
8320       hi32 = *ep;
8321       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8322       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8323       hi32.X_add_number &= 0xffffffff;
8324       lo32 = *ep;
8325       lo32.X_add_number &= 0xffffffff;
8326     }
8327   else
8328     {
8329       gas_assert (ep->X_add_number > 2);
8330       if (ep->X_add_number == 3)
8331         generic_bignum[3] = 0;
8332       else if (ep->X_add_number > 4)
8333         as_bad (_("number larger than 64 bits"));
8334       lo32.X_op = O_constant;
8335       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8336       hi32.X_op = O_constant;
8337       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8338     }
8339
8340   if (hi32.X_add_number == 0)
8341     freg = 0;
8342   else
8343     {
8344       int shift, bit;
8345       unsigned long hi, lo;
8346
8347       if (hi32.X_add_number == (offsetT) 0xffffffff)
8348         {
8349           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8350             {
8351               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8352               return;
8353             }
8354           if (lo32.X_add_number & 0x80000000)
8355             {
8356               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8357               if (lo32.X_add_number & 0xffff)
8358                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8359               return;
8360             }
8361         }
8362
8363       /* Check for 16bit shifted constant.  We know that hi32 is
8364          non-zero, so start the mask on the first bit of the hi32
8365          value.  */
8366       shift = 17;
8367       do
8368         {
8369           unsigned long himask, lomask;
8370
8371           if (shift < 32)
8372             {
8373               himask = 0xffff >> (32 - shift);
8374               lomask = (0xffff << shift) & 0xffffffff;
8375             }
8376           else
8377             {
8378               himask = 0xffff << (shift - 32);
8379               lomask = 0;
8380             }
8381           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8382               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8383             {
8384               expressionS tmp;
8385
8386               tmp.X_op = O_constant;
8387               if (shift < 32)
8388                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8389                                     | (lo32.X_add_number >> shift));
8390               else
8391                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8392               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8393               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8394                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8395               return;
8396             }
8397           ++shift;
8398         }
8399       while (shift <= (64 - 16));
8400
8401       /* Find the bit number of the lowest one bit, and store the
8402          shifted value in hi/lo.  */
8403       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8404       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8405       if (lo != 0)
8406         {
8407           bit = 0;
8408           while ((lo & 1) == 0)
8409             {
8410               lo >>= 1;
8411               ++bit;
8412             }
8413           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8414           hi >>= bit;
8415         }
8416       else
8417         {
8418           bit = 32;
8419           while ((hi & 1) == 0)
8420             {
8421               hi >>= 1;
8422               ++bit;
8423             }
8424           lo = hi;
8425           hi = 0;
8426         }
8427
8428       /* Optimize if the shifted value is a (power of 2) - 1.  */
8429       if ((hi == 0 && ((lo + 1) & lo) == 0)
8430           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8431         {
8432           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8433           if (shift != 0)
8434             {
8435               expressionS tmp;
8436
8437               /* This instruction will set the register to be all
8438                  ones.  */
8439               tmp.X_op = O_constant;
8440               tmp.X_add_number = (offsetT) -1;
8441               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8442               if (bit != 0)
8443                 {
8444                   bit += shift;
8445                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8446                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8447                 }
8448               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8449                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8450               return;
8451             }
8452         }
8453
8454       /* Sign extend hi32 before calling load_register, because we can
8455          generally get better code when we load a sign extended value.  */
8456       if ((hi32.X_add_number & 0x80000000) != 0)
8457         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8458       load_register (reg, &hi32, 0);
8459       freg = reg;
8460     }
8461   if ((lo32.X_add_number & 0xffff0000) == 0)
8462     {
8463       if (freg != 0)
8464         {
8465           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8466           freg = reg;
8467         }
8468     }
8469   else
8470     {
8471       expressionS mid16;
8472
8473       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8474         {
8475           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8476           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8477           return;
8478         }
8479
8480       if (freg != 0)
8481         {
8482           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8483           freg = reg;
8484         }
8485       mid16 = lo32;
8486       mid16.X_add_number >>= 16;
8487       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8488       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8489       freg = reg;
8490     }
8491   if ((lo32.X_add_number & 0xffff) != 0)
8492     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8493 }
8494
8495 static inline void
8496 load_delay_nop (void)
8497 {
8498   if (!gpr_interlocks)
8499     macro_build (NULL, "nop", "");
8500 }
8501
8502 /* Load an address into a register.  */
8503
8504 static void
8505 load_address (int reg, expressionS *ep, int *used_at)
8506 {
8507   if (ep->X_op != O_constant
8508       && ep->X_op != O_symbol)
8509     {
8510       as_bad (_("expression too complex"));
8511       ep->X_op = O_constant;
8512     }
8513
8514   if (ep->X_op == O_constant)
8515     {
8516       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8517       return;
8518     }
8519
8520   if (mips_pic == NO_PIC)
8521     {
8522       /* If this is a reference to a GP relative symbol, we want
8523            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8524          Otherwise we want
8525            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8526            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8527          If we have an addend, we always use the latter form.
8528
8529          With 64bit address space and a usable $at we want
8530            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8531            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8532            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8533            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8534            dsll32       $reg,0
8535            daddu        $reg,$reg,$at
8536
8537          If $at is already in use, we use a path which is suboptimal
8538          on superscalar processors.
8539            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8540            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8541            dsll         $reg,16
8542            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8543            dsll         $reg,16
8544            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8545
8546          For GP relative symbols in 64bit address space we can use
8547          the same sequence as in 32bit address space.  */
8548       if (HAVE_64BIT_SYMBOLS)
8549         {
8550           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8551               && !nopic_need_relax (ep->X_add_symbol, 1))
8552             {
8553               relax_start (ep->X_add_symbol);
8554               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8555                            mips_gp_register, BFD_RELOC_GPREL16);
8556               relax_switch ();
8557             }
8558
8559           if (*used_at == 0 && mips_opts.at)
8560             {
8561               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8562               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8563               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8564                            BFD_RELOC_MIPS_HIGHER);
8565               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8566               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8567               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8568               *used_at = 1;
8569             }
8570           else
8571             {
8572               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8573               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8574                            BFD_RELOC_MIPS_HIGHER);
8575               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8576               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8577               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8578               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8579             }
8580
8581           if (mips_relax.sequence)
8582             relax_end ();
8583         }
8584       else
8585         {
8586           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8587               && !nopic_need_relax (ep->X_add_symbol, 1))
8588             {
8589               relax_start (ep->X_add_symbol);
8590               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8591                            mips_gp_register, BFD_RELOC_GPREL16);
8592               relax_switch ();
8593             }
8594           macro_build_lui (ep, reg);
8595           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8596                        reg, reg, BFD_RELOC_LO16);
8597           if (mips_relax.sequence)
8598             relax_end ();
8599         }
8600     }
8601   else if (!mips_big_got)
8602     {
8603       expressionS ex;
8604
8605       /* If this is a reference to an external symbol, we want
8606            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8607          Otherwise we want
8608            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8609            nop
8610            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8611          If there is a constant, it must be added in after.
8612
8613          If we have NewABI, we want
8614            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8615          unless we're referencing a global symbol with a non-zero
8616          offset, in which case cst must be added separately.  */
8617       if (HAVE_NEWABI)
8618         {
8619           if (ep->X_add_number)
8620             {
8621               ex.X_add_number = ep->X_add_number;
8622               ep->X_add_number = 0;
8623               relax_start (ep->X_add_symbol);
8624               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8625                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8626               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8627                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8628               ex.X_op = O_constant;
8629               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8630                            reg, reg, BFD_RELOC_LO16);
8631               ep->X_add_number = ex.X_add_number;
8632               relax_switch ();
8633             }
8634           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8635                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8636           if (mips_relax.sequence)
8637             relax_end ();
8638         }
8639       else
8640         {
8641           ex.X_add_number = ep->X_add_number;
8642           ep->X_add_number = 0;
8643           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8644                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8645           load_delay_nop ();
8646           relax_start (ep->X_add_symbol);
8647           relax_switch ();
8648           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8649                        BFD_RELOC_LO16);
8650           relax_end ();
8651
8652           if (ex.X_add_number != 0)
8653             {
8654               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8655                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8656               ex.X_op = O_constant;
8657               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8658                            reg, reg, BFD_RELOC_LO16);
8659             }
8660         }
8661     }
8662   else if (mips_big_got)
8663     {
8664       expressionS ex;
8665
8666       /* This is the large GOT case.  If this is a reference to an
8667          external symbol, we want
8668            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8669            addu         $reg,$reg,$gp
8670            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8671
8672          Otherwise, for a reference to a local symbol in old ABI, we want
8673            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8674            nop
8675            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8676          If there is a constant, it must be added in after.
8677
8678          In the NewABI, for local symbols, with or without offsets, we want:
8679            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8680            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8681       */
8682       if (HAVE_NEWABI)
8683         {
8684           ex.X_add_number = ep->X_add_number;
8685           ep->X_add_number = 0;
8686           relax_start (ep->X_add_symbol);
8687           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8688           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8689                        reg, reg, mips_gp_register);
8690           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8691                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8692           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8693             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8694           else if (ex.X_add_number)
8695             {
8696               ex.X_op = O_constant;
8697               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8698                            BFD_RELOC_LO16);
8699             }
8700
8701           ep->X_add_number = ex.X_add_number;
8702           relax_switch ();
8703           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8704                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8705           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8706                        BFD_RELOC_MIPS_GOT_OFST);
8707           relax_end ();
8708         }
8709       else
8710         {
8711           ex.X_add_number = ep->X_add_number;
8712           ep->X_add_number = 0;
8713           relax_start (ep->X_add_symbol);
8714           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8715           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8716                        reg, reg, mips_gp_register);
8717           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8718                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8719           relax_switch ();
8720           if (reg_needs_delay (mips_gp_register))
8721             {
8722               /* We need a nop before loading from $gp.  This special
8723                  check is required because the lui which starts the main
8724                  instruction stream does not refer to $gp, and so will not
8725                  insert the nop which may be required.  */
8726               macro_build (NULL, "nop", "");
8727             }
8728           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8729                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8730           load_delay_nop ();
8731           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8732                        BFD_RELOC_LO16);
8733           relax_end ();
8734
8735           if (ex.X_add_number != 0)
8736             {
8737               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8738                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8739               ex.X_op = O_constant;
8740               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8741                            BFD_RELOC_LO16);
8742             }
8743         }
8744     }
8745   else
8746     abort ();
8747
8748   if (!mips_opts.at && *used_at == 1)
8749     as_bad (_("macro used $at after \".set noat\""));
8750 }
8751
8752 /* Move the contents of register SOURCE into register DEST.  */
8753
8754 static void
8755 move_register (int dest, int source)
8756 {
8757   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8758      instruction specifically requires a 32-bit one.  */
8759   if (mips_opts.micromips
8760       && !mips_opts.insn32
8761       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8762     macro_build (NULL, "move", "mp,mj", dest, source);
8763   else
8764     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8765                  dest, source, 0);
8766 }
8767
8768 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8769    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8770    The two alternatives are:
8771
8772    Global symbol                Local sybmol
8773    -------------                ------------
8774    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8775    ...                          ...
8776    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8777
8778    load_got_offset emits the first instruction and add_got_offset
8779    emits the second for a 16-bit offset or add_got_offset_hilo emits
8780    a sequence to add a 32-bit offset using a scratch register.  */
8781
8782 static void
8783 load_got_offset (int dest, expressionS *local)
8784 {
8785   expressionS global;
8786
8787   global = *local;
8788   global.X_add_number = 0;
8789
8790   relax_start (local->X_add_symbol);
8791   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8792                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8793   relax_switch ();
8794   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8795                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8796   relax_end ();
8797 }
8798
8799 static void
8800 add_got_offset (int dest, expressionS *local)
8801 {
8802   expressionS global;
8803
8804   global.X_op = O_constant;
8805   global.X_op_symbol = NULL;
8806   global.X_add_symbol = NULL;
8807   global.X_add_number = local->X_add_number;
8808
8809   relax_start (local->X_add_symbol);
8810   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8811                dest, dest, BFD_RELOC_LO16);
8812   relax_switch ();
8813   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8814   relax_end ();
8815 }
8816
8817 static void
8818 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8819 {
8820   expressionS global;
8821   int hold_mips_optimize;
8822
8823   global.X_op = O_constant;
8824   global.X_op_symbol = NULL;
8825   global.X_add_symbol = NULL;
8826   global.X_add_number = local->X_add_number;
8827
8828   relax_start (local->X_add_symbol);
8829   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8830   relax_switch ();
8831   /* Set mips_optimize around the lui instruction to avoid
8832      inserting an unnecessary nop after the lw.  */
8833   hold_mips_optimize = mips_optimize;
8834   mips_optimize = 2;
8835   macro_build_lui (&global, tmp);
8836   mips_optimize = hold_mips_optimize;
8837   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8838   relax_end ();
8839
8840   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8841 }
8842
8843 /* Emit a sequence of instructions to emulate a branch likely operation.
8844    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8845    is its complementing branch with the original condition negated.
8846    CALL is set if the original branch specified the link operation.
8847    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8848
8849    Code like this is produced in the noreorder mode:
8850
8851         BRNEG   <args>, 1f
8852          nop
8853         b       <sym>
8854          delay slot (executed only if branch taken)
8855     1:
8856
8857    or, if CALL is set:
8858
8859         BRNEG   <args>, 1f
8860          nop
8861         bal     <sym>
8862          delay slot (executed only if branch taken)
8863     1:
8864
8865    In the reorder mode the delay slot would be filled with a nop anyway,
8866    so code produced is simply:
8867
8868         BR      <args>, <sym>
8869          nop
8870
8871    This function is used when producing code for the microMIPS ASE that
8872    does not implement branch likely instructions in hardware.  */
8873
8874 static void
8875 macro_build_branch_likely (const char *br, const char *brneg,
8876                            int call, expressionS *ep, const char *fmt,
8877                            unsigned int sreg, unsigned int treg)
8878 {
8879   int noreorder = mips_opts.noreorder;
8880   expressionS expr1;
8881
8882   gas_assert (mips_opts.micromips);
8883   start_noreorder ();
8884   if (noreorder)
8885     {
8886       micromips_label_expr (&expr1);
8887       macro_build (&expr1, brneg, fmt, sreg, treg);
8888       macro_build (NULL, "nop", "");
8889       macro_build (ep, call ? "bal" : "b", "p");
8890
8891       /* Set to true so that append_insn adds a label.  */
8892       emit_branch_likely_macro = TRUE;
8893     }
8894   else
8895     {
8896       macro_build (ep, br, fmt, sreg, treg);
8897       macro_build (NULL, "nop", "");
8898     }
8899   end_noreorder ();
8900 }
8901
8902 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8903    the condition code tested.  EP specifies the branch target.  */
8904
8905 static void
8906 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8907 {
8908   const int call = 0;
8909   const char *brneg;
8910   const char *br;
8911
8912   switch (type)
8913     {
8914     case M_BC1FL:
8915       br = "bc1f";
8916       brneg = "bc1t";
8917       break;
8918     case M_BC1TL:
8919       br = "bc1t";
8920       brneg = "bc1f";
8921       break;
8922     case M_BC2FL:
8923       br = "bc2f";
8924       brneg = "bc2t";
8925       break;
8926     case M_BC2TL:
8927       br = "bc2t";
8928       brneg = "bc2f";
8929       break;
8930     default:
8931       abort ();
8932     }
8933   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8934 }
8935
8936 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8937    the register tested.  EP specifies the branch target.  */
8938
8939 static void
8940 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8941 {
8942   const char *brneg = NULL;
8943   const char *br;
8944   int call = 0;
8945
8946   switch (type)
8947     {
8948     case M_BGEZ:
8949       br = "bgez";
8950       break;
8951     case M_BGEZL:
8952       br = mips_opts.micromips ? "bgez" : "bgezl";
8953       brneg = "bltz";
8954       break;
8955     case M_BGEZALL:
8956       gas_assert (mips_opts.micromips);
8957       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8958       brneg = "bltz";
8959       call = 1;
8960       break;
8961     case M_BGTZ:
8962       br = "bgtz";
8963       break;
8964     case M_BGTZL:
8965       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8966       brneg = "blez";
8967       break;
8968     case M_BLEZ:
8969       br = "blez";
8970       break;
8971     case M_BLEZL:
8972       br = mips_opts.micromips ? "blez" : "blezl";
8973       brneg = "bgtz";
8974       break;
8975     case M_BLTZ:
8976       br = "bltz";
8977       break;
8978     case M_BLTZL:
8979       br = mips_opts.micromips ? "bltz" : "bltzl";
8980       brneg = "bgez";
8981       break;
8982     case M_BLTZALL:
8983       gas_assert (mips_opts.micromips);
8984       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8985       brneg = "bgez";
8986       call = 1;
8987       break;
8988     default:
8989       abort ();
8990     }
8991   if (mips_opts.micromips && brneg)
8992     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8993   else
8994     macro_build (ep, br, "s,p", sreg);
8995 }
8996
8997 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8998    TREG as the registers tested.  EP specifies the branch target.  */
8999
9000 static void
9001 macro_build_branch_rsrt (int type, expressionS *ep,
9002                          unsigned int sreg, unsigned int treg)
9003 {
9004   const char *brneg = NULL;
9005   const int call = 0;
9006   const char *br;
9007
9008   switch (type)
9009     {
9010     case M_BEQ:
9011     case M_BEQ_I:
9012       br = "beq";
9013       break;
9014     case M_BEQL:
9015     case M_BEQL_I:
9016       br = mips_opts.micromips ? "beq" : "beql";
9017       brneg = "bne";
9018       break;
9019     case M_BNE:
9020     case M_BNE_I:
9021       br = "bne";
9022       break;
9023     case M_BNEL:
9024     case M_BNEL_I:
9025       br = mips_opts.micromips ? "bne" : "bnel";
9026       brneg = "beq";
9027       break;
9028     default:
9029       abort ();
9030     }
9031   if (mips_opts.micromips && brneg)
9032     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9033   else
9034     macro_build (ep, br, "s,t,p", sreg, treg);
9035 }
9036
9037 /* Return the high part that should be loaded in order to make the low
9038    part of VALUE accessible using an offset of OFFBITS bits.  */
9039
9040 static offsetT
9041 offset_high_part (offsetT value, unsigned int offbits)
9042 {
9043   offsetT bias;
9044   addressT low_mask;
9045
9046   if (offbits == 0)
9047     return value;
9048   bias = 1 << (offbits - 1);
9049   low_mask = bias * 2 - 1;
9050   return (value + bias) & ~low_mask;
9051 }
9052
9053 /* Return true if the value stored in offset_expr and offset_reloc
9054    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9055    amount that the caller wants to add without inducing overflow
9056    and ALIGN is the known alignment of the value in bytes.  */
9057
9058 static bfd_boolean
9059 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9060 {
9061   if (offbits == 16)
9062     {
9063       /* Accept any relocation operator if overflow isn't a concern.  */
9064       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9065         return TRUE;
9066
9067       /* These relocations are guaranteed not to overflow in correct links.  */
9068       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9069           || gprel16_reloc_p (*offset_reloc))
9070         return TRUE;
9071     }
9072   if (offset_expr.X_op == O_constant
9073       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9074       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9075     return TRUE;
9076   return FALSE;
9077 }
9078
9079 /*
9080  *                      Build macros
9081  *   This routine implements the seemingly endless macro or synthesized
9082  * instructions and addressing modes in the mips assembly language. Many
9083  * of these macros are simple and are similar to each other. These could
9084  * probably be handled by some kind of table or grammar approach instead of
9085  * this verbose method. Others are not simple macros but are more like
9086  * optimizing code generation.
9087  *   One interesting optimization is when several store macros appear
9088  * consecutively that would load AT with the upper half of the same address.
9089  * The ensuing load upper instructions are ommited. This implies some kind
9090  * of global optimization. We currently only optimize within a single macro.
9091  *   For many of the load and store macros if the address is specified as a
9092  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9093  * first load register 'at' with zero and use it as the base register. The
9094  * mips assembler simply uses register $zero. Just one tiny optimization
9095  * we're missing.
9096  */
9097 static void
9098 macro (struct mips_cl_insn *ip, char *str)
9099 {
9100   const struct mips_operand_array *operands;
9101   unsigned int breg, i;
9102   unsigned int tempreg;
9103   int mask;
9104   int used_at = 0;
9105   expressionS label_expr;
9106   expressionS expr1;
9107   expressionS *ep;
9108   const char *s;
9109   const char *s2;
9110   const char *fmt;
9111   int likely = 0;
9112   int coproc = 0;
9113   int offbits = 16;
9114   int call = 0;
9115   int jals = 0;
9116   int dbl = 0;
9117   int imm = 0;
9118   int ust = 0;
9119   int lp = 0;
9120   bfd_boolean large_offset;
9121   int off;
9122   int hold_mips_optimize;
9123   unsigned int align;
9124   unsigned int op[MAX_OPERANDS];
9125
9126   gas_assert (! mips_opts.mips16);
9127
9128   operands = insn_operands (ip);
9129   for (i = 0; i < MAX_OPERANDS; i++)
9130     if (operands->operand[i])
9131       op[i] = insn_extract_operand (ip, operands->operand[i]);
9132     else
9133       op[i] = -1;
9134
9135   mask = ip->insn_mo->mask;
9136
9137   label_expr.X_op = O_constant;
9138   label_expr.X_op_symbol = NULL;
9139   label_expr.X_add_symbol = NULL;
9140   label_expr.X_add_number = 0;
9141
9142   expr1.X_op = O_constant;
9143   expr1.X_op_symbol = NULL;
9144   expr1.X_add_symbol = NULL;
9145   expr1.X_add_number = 1;
9146   align = 1;
9147
9148   switch (mask)
9149     {
9150     case M_DABS:
9151       dbl = 1;
9152     case M_ABS:
9153       /*    bgez    $a0,1f
9154             move    v0,$a0
9155             sub     v0,$zero,$a0
9156          1:
9157        */
9158
9159       start_noreorder ();
9160
9161       if (mips_opts.micromips)
9162         micromips_label_expr (&label_expr);
9163       else
9164         label_expr.X_add_number = 8;
9165       macro_build (&label_expr, "bgez", "s,p", op[1]);
9166       if (op[0] == op[1])
9167         macro_build (NULL, "nop", "");
9168       else
9169         move_register (op[0], op[1]);
9170       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9171       if (mips_opts.micromips)
9172         micromips_add_label ();
9173
9174       end_noreorder ();
9175       break;
9176
9177     case M_ADD_I:
9178       s = "addi";
9179       s2 = "add";
9180       goto do_addi;
9181     case M_ADDU_I:
9182       s = "addiu";
9183       s2 = "addu";
9184       goto do_addi;
9185     case M_DADD_I:
9186       dbl = 1;
9187       s = "daddi";
9188       s2 = "dadd";
9189       if (!mips_opts.micromips)
9190         goto do_addi;
9191       if (imm_expr.X_add_number >= -0x200
9192           && imm_expr.X_add_number < 0x200)
9193         {
9194           macro_build (NULL, s, "t,r,.", op[0], op[1],
9195                        (int) imm_expr.X_add_number);
9196           break;
9197         }
9198       goto do_addi_i;
9199     case M_DADDU_I:
9200       dbl = 1;
9201       s = "daddiu";
9202       s2 = "daddu";
9203     do_addi:
9204       if (imm_expr.X_add_number >= -0x8000
9205           && imm_expr.X_add_number < 0x8000)
9206         {
9207           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9208           break;
9209         }
9210     do_addi_i:
9211       used_at = 1;
9212       load_register (AT, &imm_expr, dbl);
9213       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9214       break;
9215
9216     case M_AND_I:
9217       s = "andi";
9218       s2 = "and";
9219       goto do_bit;
9220     case M_OR_I:
9221       s = "ori";
9222       s2 = "or";
9223       goto do_bit;
9224     case M_NOR_I:
9225       s = "";
9226       s2 = "nor";
9227       goto do_bit;
9228     case M_XOR_I:
9229       s = "xori";
9230       s2 = "xor";
9231     do_bit:
9232       if (imm_expr.X_add_number >= 0
9233           && imm_expr.X_add_number < 0x10000)
9234         {
9235           if (mask != M_NOR_I)
9236             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9237           else
9238             {
9239               macro_build (&imm_expr, "ori", "t,r,i",
9240                            op[0], op[1], BFD_RELOC_LO16);
9241               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9242             }
9243           break;
9244         }
9245
9246       used_at = 1;
9247       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9248       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9249       break;
9250
9251     case M_BALIGN:
9252       switch (imm_expr.X_add_number)
9253         {
9254         case 0:
9255           macro_build (NULL, "nop", "");
9256           break;
9257         case 2:
9258           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9259           break;
9260         case 1:
9261         case 3:
9262           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9263                        (int) imm_expr.X_add_number);
9264           break;
9265         default:
9266           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9267                   (unsigned long) imm_expr.X_add_number);
9268           break;
9269         }
9270       break;
9271
9272     case M_BC1FL:
9273     case M_BC1TL:
9274     case M_BC2FL:
9275     case M_BC2TL:
9276       gas_assert (mips_opts.micromips);
9277       macro_build_branch_ccl (mask, &offset_expr,
9278                               EXTRACT_OPERAND (1, BCC, *ip));
9279       break;
9280
9281     case M_BEQ_I:
9282     case M_BEQL_I:
9283     case M_BNE_I:
9284     case M_BNEL_I:
9285       if (imm_expr.X_add_number == 0)
9286         op[1] = 0;
9287       else
9288         {
9289           op[1] = AT;
9290           used_at = 1;
9291           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9292         }
9293       /* Fall through.  */
9294     case M_BEQL:
9295     case M_BNEL:
9296       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9297       break;
9298
9299     case M_BGEL:
9300       likely = 1;
9301     case M_BGE:
9302       if (op[1] == 0)
9303         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9304       else if (op[0] == 0)
9305         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9306       else
9307         {
9308           used_at = 1;
9309           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9310           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9311                                    &offset_expr, AT, ZERO);
9312         }
9313       break;
9314
9315     case M_BGEZL:
9316     case M_BGEZALL:
9317     case M_BGTZL:
9318     case M_BLEZL:
9319     case M_BLTZL:
9320     case M_BLTZALL:
9321       macro_build_branch_rs (mask, &offset_expr, op[0]);
9322       break;
9323
9324     case M_BGTL_I:
9325       likely = 1;
9326     case M_BGT_I:
9327       /* Check for > max integer.  */
9328       if (imm_expr.X_add_number >= GPR_SMAX)
9329         {
9330         do_false:
9331           /* Result is always false.  */
9332           if (! likely)
9333             macro_build (NULL, "nop", "");
9334           else
9335             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9336           break;
9337         }
9338       ++imm_expr.X_add_number;
9339       /* FALLTHROUGH */
9340     case M_BGE_I:
9341     case M_BGEL_I:
9342       if (mask == M_BGEL_I)
9343         likely = 1;
9344       if (imm_expr.X_add_number == 0)
9345         {
9346           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9347                                  &offset_expr, op[0]);
9348           break;
9349         }
9350       if (imm_expr.X_add_number == 1)
9351         {
9352           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9353                                  &offset_expr, op[0]);
9354           break;
9355         }
9356       if (imm_expr.X_add_number <= GPR_SMIN)
9357         {
9358         do_true:
9359           /* result is always true */
9360           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9361           macro_build (&offset_expr, "b", "p");
9362           break;
9363         }
9364       used_at = 1;
9365       set_at (op[0], 0);
9366       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9367                                &offset_expr, AT, ZERO);
9368       break;
9369
9370     case M_BGEUL:
9371       likely = 1;
9372     case M_BGEU:
9373       if (op[1] == 0)
9374         goto do_true;
9375       else if (op[0] == 0)
9376         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9377                                  &offset_expr, ZERO, op[1]);
9378       else
9379         {
9380           used_at = 1;
9381           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9382           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9383                                    &offset_expr, AT, ZERO);
9384         }
9385       break;
9386
9387     case M_BGTUL_I:
9388       likely = 1;
9389     case M_BGTU_I:
9390       if (op[0] == 0
9391           || (HAVE_32BIT_GPRS
9392               && imm_expr.X_add_number == -1))
9393         goto do_false;
9394       ++imm_expr.X_add_number;
9395       /* FALLTHROUGH */
9396     case M_BGEU_I:
9397     case M_BGEUL_I:
9398       if (mask == M_BGEUL_I)
9399         likely = 1;
9400       if (imm_expr.X_add_number == 0)
9401         goto do_true;
9402       else if (imm_expr.X_add_number == 1)
9403         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9404                                  &offset_expr, op[0], ZERO);
9405       else
9406         {
9407           used_at = 1;
9408           set_at (op[0], 1);
9409           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9410                                    &offset_expr, AT, ZERO);
9411         }
9412       break;
9413
9414     case M_BGTL:
9415       likely = 1;
9416     case M_BGT:
9417       if (op[1] == 0)
9418         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9419       else if (op[0] == 0)
9420         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9421       else
9422         {
9423           used_at = 1;
9424           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9425           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9426                                    &offset_expr, AT, ZERO);
9427         }
9428       break;
9429
9430     case M_BGTUL:
9431       likely = 1;
9432     case M_BGTU:
9433       if (op[1] == 0)
9434         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9435                                  &offset_expr, op[0], ZERO);
9436       else if (op[0] == 0)
9437         goto do_false;
9438       else
9439         {
9440           used_at = 1;
9441           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9442           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9443                                    &offset_expr, AT, ZERO);
9444         }
9445       break;
9446
9447     case M_BLEL:
9448       likely = 1;
9449     case M_BLE:
9450       if (op[1] == 0)
9451         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9452       else if (op[0] == 0)
9453         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9454       else
9455         {
9456           used_at = 1;
9457           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9458           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9459                                    &offset_expr, AT, ZERO);
9460         }
9461       break;
9462
9463     case M_BLEL_I:
9464       likely = 1;
9465     case M_BLE_I:
9466       if (imm_expr.X_add_number >= GPR_SMAX)
9467         goto do_true;
9468       ++imm_expr.X_add_number;
9469       /* FALLTHROUGH */
9470     case M_BLT_I:
9471     case M_BLTL_I:
9472       if (mask == M_BLTL_I)
9473         likely = 1;
9474       if (imm_expr.X_add_number == 0)
9475         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9476       else if (imm_expr.X_add_number == 1)
9477         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9478       else
9479         {
9480           used_at = 1;
9481           set_at (op[0], 0);
9482           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9483                                    &offset_expr, AT, ZERO);
9484         }
9485       break;
9486
9487     case M_BLEUL:
9488       likely = 1;
9489     case M_BLEU:
9490       if (op[1] == 0)
9491         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9492                                  &offset_expr, op[0], ZERO);
9493       else if (op[0] == 0)
9494         goto do_true;
9495       else
9496         {
9497           used_at = 1;
9498           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9499           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9500                                    &offset_expr, AT, ZERO);
9501         }
9502       break;
9503
9504     case M_BLEUL_I:
9505       likely = 1;
9506     case M_BLEU_I:
9507       if (op[0] == 0
9508           || (HAVE_32BIT_GPRS
9509               && imm_expr.X_add_number == -1))
9510         goto do_true;
9511       ++imm_expr.X_add_number;
9512       /* FALLTHROUGH */
9513     case M_BLTU_I:
9514     case M_BLTUL_I:
9515       if (mask == M_BLTUL_I)
9516         likely = 1;
9517       if (imm_expr.X_add_number == 0)
9518         goto do_false;
9519       else if (imm_expr.X_add_number == 1)
9520         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9521                                  &offset_expr, op[0], ZERO);
9522       else
9523         {
9524           used_at = 1;
9525           set_at (op[0], 1);
9526           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9527                                    &offset_expr, AT, ZERO);
9528         }
9529       break;
9530
9531     case M_BLTL:
9532       likely = 1;
9533     case M_BLT:
9534       if (op[1] == 0)
9535         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9536       else if (op[0] == 0)
9537         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9538       else
9539         {
9540           used_at = 1;
9541           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9542           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9543                                    &offset_expr, AT, ZERO);
9544         }
9545       break;
9546
9547     case M_BLTUL:
9548       likely = 1;
9549     case M_BLTU:
9550       if (op[1] == 0)
9551         goto do_false;
9552       else if (op[0] == 0)
9553         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9554                                  &offset_expr, ZERO, op[1]);
9555       else
9556         {
9557           used_at = 1;
9558           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9559           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9560                                    &offset_expr, AT, ZERO);
9561         }
9562       break;
9563
9564     case M_DDIV_3:
9565       dbl = 1;
9566     case M_DIV_3:
9567       s = "mflo";
9568       goto do_div3;
9569     case M_DREM_3:
9570       dbl = 1;
9571     case M_REM_3:
9572       s = "mfhi";
9573     do_div3:
9574       if (op[2] == 0)
9575         {
9576           as_warn (_("divide by zero"));
9577           if (mips_trap)
9578             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9579           else
9580             macro_build (NULL, "break", BRK_FMT, 7);
9581           break;
9582         }
9583
9584       start_noreorder ();
9585       if (mips_trap)
9586         {
9587           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9588           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9589         }
9590       else
9591         {
9592           if (mips_opts.micromips)
9593             micromips_label_expr (&label_expr);
9594           else
9595             label_expr.X_add_number = 8;
9596           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9597           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9598           macro_build (NULL, "break", BRK_FMT, 7);
9599           if (mips_opts.micromips)
9600             micromips_add_label ();
9601         }
9602       expr1.X_add_number = -1;
9603       used_at = 1;
9604       load_register (AT, &expr1, dbl);
9605       if (mips_opts.micromips)
9606         micromips_label_expr (&label_expr);
9607       else
9608         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9609       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9610       if (dbl)
9611         {
9612           expr1.X_add_number = 1;
9613           load_register (AT, &expr1, dbl);
9614           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9615         }
9616       else
9617         {
9618           expr1.X_add_number = 0x80000000;
9619           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9620         }
9621       if (mips_trap)
9622         {
9623           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9624           /* We want to close the noreorder block as soon as possible, so
9625              that later insns are available for delay slot filling.  */
9626           end_noreorder ();
9627         }
9628       else
9629         {
9630           if (mips_opts.micromips)
9631             micromips_label_expr (&label_expr);
9632           else
9633             label_expr.X_add_number = 8;
9634           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9635           macro_build (NULL, "nop", "");
9636
9637           /* We want to close the noreorder block as soon as possible, so
9638              that later insns are available for delay slot filling.  */
9639           end_noreorder ();
9640
9641           macro_build (NULL, "break", BRK_FMT, 6);
9642         }
9643       if (mips_opts.micromips)
9644         micromips_add_label ();
9645       macro_build (NULL, s, MFHL_FMT, op[0]);
9646       break;
9647
9648     case M_DIV_3I:
9649       s = "div";
9650       s2 = "mflo";
9651       goto do_divi;
9652     case M_DIVU_3I:
9653       s = "divu";
9654       s2 = "mflo";
9655       goto do_divi;
9656     case M_REM_3I:
9657       s = "div";
9658       s2 = "mfhi";
9659       goto do_divi;
9660     case M_REMU_3I:
9661       s = "divu";
9662       s2 = "mfhi";
9663       goto do_divi;
9664     case M_DDIV_3I:
9665       dbl = 1;
9666       s = "ddiv";
9667       s2 = "mflo";
9668       goto do_divi;
9669     case M_DDIVU_3I:
9670       dbl = 1;
9671       s = "ddivu";
9672       s2 = "mflo";
9673       goto do_divi;
9674     case M_DREM_3I:
9675       dbl = 1;
9676       s = "ddiv";
9677       s2 = "mfhi";
9678       goto do_divi;
9679     case M_DREMU_3I:
9680       dbl = 1;
9681       s = "ddivu";
9682       s2 = "mfhi";
9683     do_divi:
9684       if (imm_expr.X_add_number == 0)
9685         {
9686           as_warn (_("divide by zero"));
9687           if (mips_trap)
9688             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9689           else
9690             macro_build (NULL, "break", BRK_FMT, 7);
9691           break;
9692         }
9693       if (imm_expr.X_add_number == 1)
9694         {
9695           if (strcmp (s2, "mflo") == 0)
9696             move_register (op[0], op[1]);
9697           else
9698             move_register (op[0], ZERO);
9699           break;
9700         }
9701       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9702         {
9703           if (strcmp (s2, "mflo") == 0)
9704             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9705           else
9706             move_register (op[0], ZERO);
9707           break;
9708         }
9709
9710       used_at = 1;
9711       load_register (AT, &imm_expr, dbl);
9712       macro_build (NULL, s, "z,s,t", op[1], AT);
9713       macro_build (NULL, s2, MFHL_FMT, op[0]);
9714       break;
9715
9716     case M_DIVU_3:
9717       s = "divu";
9718       s2 = "mflo";
9719       goto do_divu3;
9720     case M_REMU_3:
9721       s = "divu";
9722       s2 = "mfhi";
9723       goto do_divu3;
9724     case M_DDIVU_3:
9725       s = "ddivu";
9726       s2 = "mflo";
9727       goto do_divu3;
9728     case M_DREMU_3:
9729       s = "ddivu";
9730       s2 = "mfhi";
9731     do_divu3:
9732       start_noreorder ();
9733       if (mips_trap)
9734         {
9735           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9736           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9737           /* We want to close the noreorder block as soon as possible, so
9738              that later insns are available for delay slot filling.  */
9739           end_noreorder ();
9740         }
9741       else
9742         {
9743           if (mips_opts.micromips)
9744             micromips_label_expr (&label_expr);
9745           else
9746             label_expr.X_add_number = 8;
9747           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9748           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9749
9750           /* We want to close the noreorder block as soon as possible, so
9751              that later insns are available for delay slot filling.  */
9752           end_noreorder ();
9753           macro_build (NULL, "break", BRK_FMT, 7);
9754           if (mips_opts.micromips)
9755             micromips_add_label ();
9756         }
9757       macro_build (NULL, s2, MFHL_FMT, op[0]);
9758       break;
9759
9760     case M_DLCA_AB:
9761       dbl = 1;
9762     case M_LCA_AB:
9763       call = 1;
9764       goto do_la;
9765     case M_DLA_AB:
9766       dbl = 1;
9767     case M_LA_AB:
9768     do_la:
9769       /* Load the address of a symbol into a register.  If breg is not
9770          zero, we then add a base register to it.  */
9771
9772       breg = op[2];
9773       if (dbl && HAVE_32BIT_GPRS)
9774         as_warn (_("dla used to load 32-bit register"));
9775
9776       if (!dbl && HAVE_64BIT_OBJECTS)
9777         as_warn (_("la used to load 64-bit address"));
9778
9779       if (small_offset_p (0, align, 16))
9780         {
9781           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9782                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9783           break;
9784         }
9785
9786       if (mips_opts.at && (op[0] == breg))
9787         {
9788           tempreg = AT;
9789           used_at = 1;
9790         }
9791       else
9792         tempreg = op[0];
9793
9794       if (offset_expr.X_op != O_symbol
9795           && offset_expr.X_op != O_constant)
9796         {
9797           as_bad (_("expression too complex"));
9798           offset_expr.X_op = O_constant;
9799         }
9800
9801       if (offset_expr.X_op == O_constant)
9802         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9803       else if (mips_pic == NO_PIC)
9804         {
9805           /* If this is a reference to a GP relative symbol, we want
9806                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9807              Otherwise we want
9808                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9809                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9810              If we have a constant, we need two instructions anyhow,
9811              so we may as well always use the latter form.
9812
9813              With 64bit address space and a usable $at we want
9814                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9815                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9816                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9817                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9818                dsll32   $tempreg,0
9819                daddu    $tempreg,$tempreg,$at
9820
9821              If $at is already in use, we use a path which is suboptimal
9822              on superscalar processors.
9823                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9824                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9825                dsll     $tempreg,16
9826                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9827                dsll     $tempreg,16
9828                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9829
9830              For GP relative symbols in 64bit address space we can use
9831              the same sequence as in 32bit address space.  */
9832           if (HAVE_64BIT_SYMBOLS)
9833             {
9834               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9835                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9836                 {
9837                   relax_start (offset_expr.X_add_symbol);
9838                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9839                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9840                   relax_switch ();
9841                 }
9842
9843               if (used_at == 0 && mips_opts.at)
9844                 {
9845                   macro_build (&offset_expr, "lui", LUI_FMT,
9846                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9847                   macro_build (&offset_expr, "lui", LUI_FMT,
9848                                AT, BFD_RELOC_HI16_S);
9849                   macro_build (&offset_expr, "daddiu", "t,r,j",
9850                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9851                   macro_build (&offset_expr, "daddiu", "t,r,j",
9852                                AT, AT, BFD_RELOC_LO16);
9853                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9854                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9855                   used_at = 1;
9856                 }
9857               else
9858                 {
9859                   macro_build (&offset_expr, "lui", LUI_FMT,
9860                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9861                   macro_build (&offset_expr, "daddiu", "t,r,j",
9862                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9863                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9864                   macro_build (&offset_expr, "daddiu", "t,r,j",
9865                                tempreg, tempreg, BFD_RELOC_HI16_S);
9866                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9867                   macro_build (&offset_expr, "daddiu", "t,r,j",
9868                                tempreg, tempreg, BFD_RELOC_LO16);
9869                 }
9870
9871               if (mips_relax.sequence)
9872                 relax_end ();
9873             }
9874           else
9875             {
9876               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9877                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9878                 {
9879                   relax_start (offset_expr.X_add_symbol);
9880                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9881                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9882                   relax_switch ();
9883                 }
9884               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9885                 as_bad (_("offset too large"));
9886               macro_build_lui (&offset_expr, tempreg);
9887               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9888                            tempreg, tempreg, BFD_RELOC_LO16);
9889               if (mips_relax.sequence)
9890                 relax_end ();
9891             }
9892         }
9893       else if (!mips_big_got && !HAVE_NEWABI)
9894         {
9895           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9896
9897           /* If this is a reference to an external symbol, and there
9898              is no constant, we want
9899                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9900              or for lca or if tempreg is PIC_CALL_REG
9901                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9902              For a local symbol, we want
9903                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9904                nop
9905                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9906
9907              If we have a small constant, and this is a reference to
9908              an external symbol, we want
9909                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9910                nop
9911                addiu    $tempreg,$tempreg,<constant>
9912              For a local symbol, we want the same instruction
9913              sequence, but we output a BFD_RELOC_LO16 reloc on the
9914              addiu instruction.
9915
9916              If we have a large constant, and this is a reference to
9917              an external symbol, we want
9918                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9919                lui      $at,<hiconstant>
9920                addiu    $at,$at,<loconstant>
9921                addu     $tempreg,$tempreg,$at
9922              For a local symbol, we want the same instruction
9923              sequence, but we output a BFD_RELOC_LO16 reloc on the
9924              addiu instruction.
9925            */
9926
9927           if (offset_expr.X_add_number == 0)
9928             {
9929               if (mips_pic == SVR4_PIC
9930                   && breg == 0
9931                   && (call || tempreg == PIC_CALL_REG))
9932                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9933
9934               relax_start (offset_expr.X_add_symbol);
9935               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9936                            lw_reloc_type, mips_gp_register);
9937               if (breg != 0)
9938                 {
9939                   /* We're going to put in an addu instruction using
9940                      tempreg, so we may as well insert the nop right
9941                      now.  */
9942                   load_delay_nop ();
9943                 }
9944               relax_switch ();
9945               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9946                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9947               load_delay_nop ();
9948               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9949                            tempreg, tempreg, BFD_RELOC_LO16);
9950               relax_end ();
9951               /* FIXME: If breg == 0, and the next instruction uses
9952                  $tempreg, then if this variant case is used an extra
9953                  nop will be generated.  */
9954             }
9955           else if (offset_expr.X_add_number >= -0x8000
9956                    && offset_expr.X_add_number < 0x8000)
9957             {
9958               load_got_offset (tempreg, &offset_expr);
9959               load_delay_nop ();
9960               add_got_offset (tempreg, &offset_expr);
9961             }
9962           else
9963             {
9964               expr1.X_add_number = offset_expr.X_add_number;
9965               offset_expr.X_add_number =
9966                 SEXT_16BIT (offset_expr.X_add_number);
9967               load_got_offset (tempreg, &offset_expr);
9968               offset_expr.X_add_number = expr1.X_add_number;
9969               /* If we are going to add in a base register, and the
9970                  target register and the base register are the same,
9971                  then we are using AT as a temporary register.  Since
9972                  we want to load the constant into AT, we add our
9973                  current AT (from the global offset table) and the
9974                  register into the register now, and pretend we were
9975                  not using a base register.  */
9976               if (breg == op[0])
9977                 {
9978                   load_delay_nop ();
9979                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9980                                op[0], AT, breg);
9981                   breg = 0;
9982                   tempreg = op[0];
9983                 }
9984               add_got_offset_hilo (tempreg, &offset_expr, AT);
9985               used_at = 1;
9986             }
9987         }
9988       else if (!mips_big_got && HAVE_NEWABI)
9989         {
9990           int add_breg_early = 0;
9991
9992           /* If this is a reference to an external, and there is no
9993              constant, or local symbol (*), with or without a
9994              constant, we want
9995                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9996              or for lca or if tempreg is PIC_CALL_REG
9997                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9998
9999              If we have a small constant, and this is a reference to
10000              an external symbol, we want
10001                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10002                addiu    $tempreg,$tempreg,<constant>
10003
10004              If we have a large constant, and this is a reference to
10005              an external symbol, we want
10006                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10007                lui      $at,<hiconstant>
10008                addiu    $at,$at,<loconstant>
10009                addu     $tempreg,$tempreg,$at
10010
10011              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10012              local symbols, even though it introduces an additional
10013              instruction.  */
10014
10015           if (offset_expr.X_add_number)
10016             {
10017               expr1.X_add_number = offset_expr.X_add_number;
10018               offset_expr.X_add_number = 0;
10019
10020               relax_start (offset_expr.X_add_symbol);
10021               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10022                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10023
10024               if (expr1.X_add_number >= -0x8000
10025                   && expr1.X_add_number < 0x8000)
10026                 {
10027                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10028                                tempreg, tempreg, BFD_RELOC_LO16);
10029                 }
10030               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10031                 {
10032                   unsigned int dreg;
10033
10034                   /* If we are going to add in a base register, and the
10035                      target register and the base register are the same,
10036                      then we are using AT as a temporary register.  Since
10037                      we want to load the constant into AT, we add our
10038                      current AT (from the global offset table) and the
10039                      register into the register now, and pretend we were
10040                      not using a base register.  */
10041                   if (breg != op[0])
10042                     dreg = tempreg;
10043                   else
10044                     {
10045                       gas_assert (tempreg == AT);
10046                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10047                                    op[0], AT, breg);
10048                       dreg = op[0];
10049                       add_breg_early = 1;
10050                     }
10051
10052                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10053                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10054                                dreg, dreg, AT);
10055
10056                   used_at = 1;
10057                 }
10058               else
10059                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10060
10061               relax_switch ();
10062               offset_expr.X_add_number = expr1.X_add_number;
10063
10064               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10065                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10066               if (add_breg_early)
10067                 {
10068                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10069                                op[0], tempreg, breg);
10070                   breg = 0;
10071                   tempreg = op[0];
10072                 }
10073               relax_end ();
10074             }
10075           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10076             {
10077               relax_start (offset_expr.X_add_symbol);
10078               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10079                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10080               relax_switch ();
10081               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10082                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10083               relax_end ();
10084             }
10085           else
10086             {
10087               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10088                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10089             }
10090         }
10091       else if (mips_big_got && !HAVE_NEWABI)
10092         {
10093           int gpdelay;
10094           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10095           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10096           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10097
10098           /* This is the large GOT case.  If this is a reference to an
10099              external symbol, and there is no constant, we want
10100                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10101                addu     $tempreg,$tempreg,$gp
10102                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10103              or for lca or if tempreg is PIC_CALL_REG
10104                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10105                addu     $tempreg,$tempreg,$gp
10106                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10107              For a local symbol, we want
10108                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10109                nop
10110                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10111
10112              If we have a small constant, and this is a reference to
10113              an external symbol, we want
10114                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10115                addu     $tempreg,$tempreg,$gp
10116                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10117                nop
10118                addiu    $tempreg,$tempreg,<constant>
10119              For a local symbol, we want
10120                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10121                nop
10122                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10123
10124              If we have a large constant, and this is a reference to
10125              an external symbol, we want
10126                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10127                addu     $tempreg,$tempreg,$gp
10128                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10129                lui      $at,<hiconstant>
10130                addiu    $at,$at,<loconstant>
10131                addu     $tempreg,$tempreg,$at
10132              For a local symbol, we want
10133                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10134                lui      $at,<hiconstant>
10135                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10136                addu     $tempreg,$tempreg,$at
10137           */
10138
10139           expr1.X_add_number = offset_expr.X_add_number;
10140           offset_expr.X_add_number = 0;
10141           relax_start (offset_expr.X_add_symbol);
10142           gpdelay = reg_needs_delay (mips_gp_register);
10143           if (expr1.X_add_number == 0 && breg == 0
10144               && (call || tempreg == PIC_CALL_REG))
10145             {
10146               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10147               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10148             }
10149           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10150           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10151                        tempreg, tempreg, mips_gp_register);
10152           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10153                        tempreg, lw_reloc_type, tempreg);
10154           if (expr1.X_add_number == 0)
10155             {
10156               if (breg != 0)
10157                 {
10158                   /* We're going to put in an addu instruction using
10159                      tempreg, so we may as well insert the nop right
10160                      now.  */
10161                   load_delay_nop ();
10162                 }
10163             }
10164           else if (expr1.X_add_number >= -0x8000
10165                    && expr1.X_add_number < 0x8000)
10166             {
10167               load_delay_nop ();
10168               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10169                            tempreg, tempreg, BFD_RELOC_LO16);
10170             }
10171           else
10172             {
10173               unsigned int dreg;
10174
10175               /* If we are going to add in a base register, and the
10176                  target register and the base register are the same,
10177                  then we are using AT as a temporary register.  Since
10178                  we want to load the constant into AT, we add our
10179                  current AT (from the global offset table) and the
10180                  register into the register now, and pretend we were
10181                  not using a base register.  */
10182               if (breg != op[0])
10183                 dreg = tempreg;
10184               else
10185                 {
10186                   gas_assert (tempreg == AT);
10187                   load_delay_nop ();
10188                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10189                                op[0], AT, breg);
10190                   dreg = op[0];
10191                 }
10192
10193               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10194               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10195
10196               used_at = 1;
10197             }
10198           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10199           relax_switch ();
10200
10201           if (gpdelay)
10202             {
10203               /* This is needed because this instruction uses $gp, but
10204                  the first instruction on the main stream does not.  */
10205               macro_build (NULL, "nop", "");
10206             }
10207
10208           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10209                        local_reloc_type, mips_gp_register);
10210           if (expr1.X_add_number >= -0x8000
10211               && expr1.X_add_number < 0x8000)
10212             {
10213               load_delay_nop ();
10214               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10215                            tempreg, tempreg, BFD_RELOC_LO16);
10216               /* FIXME: If add_number is 0, and there was no base
10217                  register, the external symbol case ended with a load,
10218                  so if the symbol turns out to not be external, and
10219                  the next instruction uses tempreg, an unnecessary nop
10220                  will be inserted.  */
10221             }
10222           else
10223             {
10224               if (breg == op[0])
10225                 {
10226                   /* We must add in the base register now, as in the
10227                      external symbol case.  */
10228                   gas_assert (tempreg == AT);
10229                   load_delay_nop ();
10230                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10231                                op[0], AT, breg);
10232                   tempreg = op[0];
10233                   /* We set breg to 0 because we have arranged to add
10234                      it in in both cases.  */
10235                   breg = 0;
10236                 }
10237
10238               macro_build_lui (&expr1, AT);
10239               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10240                            AT, AT, BFD_RELOC_LO16);
10241               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10242                            tempreg, tempreg, AT);
10243               used_at = 1;
10244             }
10245           relax_end ();
10246         }
10247       else if (mips_big_got && HAVE_NEWABI)
10248         {
10249           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10250           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10251           int add_breg_early = 0;
10252
10253           /* This is the large GOT case.  If this is a reference to an
10254              external symbol, and there is no constant, we want
10255                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10256                add      $tempreg,$tempreg,$gp
10257                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10258              or for lca or if tempreg is PIC_CALL_REG
10259                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10260                add      $tempreg,$tempreg,$gp
10261                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10262
10263              If we have a small constant, and this is a reference to
10264              an external symbol, we want
10265                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10266                add      $tempreg,$tempreg,$gp
10267                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10268                addi     $tempreg,$tempreg,<constant>
10269
10270              If we have a large constant, and this is a reference to
10271              an external symbol, we want
10272                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10273                addu     $tempreg,$tempreg,$gp
10274                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10275                lui      $at,<hiconstant>
10276                addi     $at,$at,<loconstant>
10277                add      $tempreg,$tempreg,$at
10278
10279              If we have NewABI, and we know it's a local symbol, we want
10280                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10281                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10282              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10283
10284           relax_start (offset_expr.X_add_symbol);
10285
10286           expr1.X_add_number = offset_expr.X_add_number;
10287           offset_expr.X_add_number = 0;
10288
10289           if (expr1.X_add_number == 0 && breg == 0
10290               && (call || tempreg == PIC_CALL_REG))
10291             {
10292               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10293               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10294             }
10295           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10296           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10297                        tempreg, tempreg, mips_gp_register);
10298           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10299                        tempreg, lw_reloc_type, tempreg);
10300
10301           if (expr1.X_add_number == 0)
10302             ;
10303           else if (expr1.X_add_number >= -0x8000
10304                    && expr1.X_add_number < 0x8000)
10305             {
10306               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10307                            tempreg, tempreg, BFD_RELOC_LO16);
10308             }
10309           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10310             {
10311               unsigned int dreg;
10312
10313               /* If we are going to add in a base register, and the
10314                  target register and the base register are the same,
10315                  then we are using AT as a temporary register.  Since
10316                  we want to load the constant into AT, we add our
10317                  current AT (from the global offset table) and the
10318                  register into the register now, and pretend we were
10319                  not using a base register.  */
10320               if (breg != op[0])
10321                 dreg = tempreg;
10322               else
10323                 {
10324                   gas_assert (tempreg == AT);
10325                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10326                                op[0], AT, breg);
10327                   dreg = op[0];
10328                   add_breg_early = 1;
10329                 }
10330
10331               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10332               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10333
10334               used_at = 1;
10335             }
10336           else
10337             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10338
10339           relax_switch ();
10340           offset_expr.X_add_number = expr1.X_add_number;
10341           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10342                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10343           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10344                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10345           if (add_breg_early)
10346             {
10347               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10348                            op[0], tempreg, breg);
10349               breg = 0;
10350               tempreg = op[0];
10351             }
10352           relax_end ();
10353         }
10354       else
10355         abort ();
10356
10357       if (breg != 0)
10358         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10359       break;
10360
10361     case M_MSGSND:
10362       gas_assert (!mips_opts.micromips);
10363       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10364       break;
10365
10366     case M_MSGLD:
10367       gas_assert (!mips_opts.micromips);
10368       macro_build (NULL, "c2", "C", 0x02);
10369       break;
10370
10371     case M_MSGLD_T:
10372       gas_assert (!mips_opts.micromips);
10373       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10374       break;
10375
10376     case M_MSGWAIT:
10377       gas_assert (!mips_opts.micromips);
10378       macro_build (NULL, "c2", "C", 3);
10379       break;
10380
10381     case M_MSGWAIT_T:
10382       gas_assert (!mips_opts.micromips);
10383       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10384       break;
10385
10386     case M_J_A:
10387       /* The j instruction may not be used in PIC code, since it
10388          requires an absolute address.  We convert it to a b
10389          instruction.  */
10390       if (mips_pic == NO_PIC)
10391         macro_build (&offset_expr, "j", "a");
10392       else
10393         macro_build (&offset_expr, "b", "p");
10394       break;
10395
10396       /* The jal instructions must be handled as macros because when
10397          generating PIC code they expand to multi-instruction
10398          sequences.  Normally they are simple instructions.  */
10399     case M_JALS_1:
10400       op[1] = op[0];
10401       op[0] = RA;
10402       /* Fall through.  */
10403     case M_JALS_2:
10404       gas_assert (mips_opts.micromips);
10405       if (mips_opts.insn32)
10406         {
10407           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10408           break;
10409         }
10410       jals = 1;
10411       goto jal;
10412     case M_JAL_1:
10413       op[1] = op[0];
10414       op[0] = RA;
10415       /* Fall through.  */
10416     case M_JAL_2:
10417     jal:
10418       if (mips_pic == NO_PIC)
10419         {
10420           s = jals ? "jalrs" : "jalr";
10421           if (mips_opts.micromips
10422               && !mips_opts.insn32
10423               && op[0] == RA
10424               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10425             macro_build (NULL, s, "mj", op[1]);
10426           else
10427             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10428         }
10429       else
10430         {
10431           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10432                            && mips_cprestore_offset >= 0);
10433
10434           if (op[1] != PIC_CALL_REG)
10435             as_warn (_("MIPS PIC call to register other than $25"));
10436
10437           s = ((mips_opts.micromips
10438                 && !mips_opts.insn32
10439                 && (!mips_opts.noreorder || cprestore))
10440                ? "jalrs" : "jalr");
10441           if (mips_opts.micromips
10442               && !mips_opts.insn32
10443               && op[0] == RA
10444               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10445             macro_build (NULL, s, "mj", op[1]);
10446           else
10447             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10448           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10449             {
10450               if (mips_cprestore_offset < 0)
10451                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10452               else
10453                 {
10454                   if (!mips_frame_reg_valid)
10455                     {
10456                       as_warn (_("no .frame pseudo-op used in PIC code"));
10457                       /* Quiet this warning.  */
10458                       mips_frame_reg_valid = 1;
10459                     }
10460                   if (!mips_cprestore_valid)
10461                     {
10462                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10463                       /* Quiet this warning.  */
10464                       mips_cprestore_valid = 1;
10465                     }
10466                   if (mips_opts.noreorder)
10467                     macro_build (NULL, "nop", "");
10468                   expr1.X_add_number = mips_cprestore_offset;
10469                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10470                                                 mips_gp_register,
10471                                                 mips_frame_reg,
10472                                                 HAVE_64BIT_ADDRESSES);
10473                 }
10474             }
10475         }
10476
10477       break;
10478
10479     case M_JALS_A:
10480       gas_assert (mips_opts.micromips);
10481       if (mips_opts.insn32)
10482         {
10483           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10484           break;
10485         }
10486       jals = 1;
10487       /* Fall through.  */
10488     case M_JAL_A:
10489       if (mips_pic == NO_PIC)
10490         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10491       else if (mips_pic == SVR4_PIC)
10492         {
10493           /* If this is a reference to an external symbol, and we are
10494              using a small GOT, we want
10495                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10496                nop
10497                jalr     $ra,$25
10498                nop
10499                lw       $gp,cprestore($sp)
10500              The cprestore value is set using the .cprestore
10501              pseudo-op.  If we are using a big GOT, we want
10502                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10503                addu     $25,$25,$gp
10504                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10505                nop
10506                jalr     $ra,$25
10507                nop
10508                lw       $gp,cprestore($sp)
10509              If the symbol is not external, we want
10510                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10511                nop
10512                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10513                jalr     $ra,$25
10514                nop
10515                lw $gp,cprestore($sp)
10516
10517              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10518              sequences above, minus nops, unless the symbol is local,
10519              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10520              GOT_DISP.  */
10521           if (HAVE_NEWABI)
10522             {
10523               if (!mips_big_got)
10524                 {
10525                   relax_start (offset_expr.X_add_symbol);
10526                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10527                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10528                                mips_gp_register);
10529                   relax_switch ();
10530                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10531                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10532                                mips_gp_register);
10533                   relax_end ();
10534                 }
10535               else
10536                 {
10537                   relax_start (offset_expr.X_add_symbol);
10538                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10539                                BFD_RELOC_MIPS_CALL_HI16);
10540                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10541                                PIC_CALL_REG, mips_gp_register);
10542                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10543                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10544                                PIC_CALL_REG);
10545                   relax_switch ();
10546                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10547                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10548                                mips_gp_register);
10549                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10550                                PIC_CALL_REG, PIC_CALL_REG,
10551                                BFD_RELOC_MIPS_GOT_OFST);
10552                   relax_end ();
10553                 }
10554
10555               macro_build_jalr (&offset_expr, 0);
10556             }
10557           else
10558             {
10559               relax_start (offset_expr.X_add_symbol);
10560               if (!mips_big_got)
10561                 {
10562                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10563                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10564                                mips_gp_register);
10565                   load_delay_nop ();
10566                   relax_switch ();
10567                 }
10568               else
10569                 {
10570                   int gpdelay;
10571
10572                   gpdelay = reg_needs_delay (mips_gp_register);
10573                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10574                                BFD_RELOC_MIPS_CALL_HI16);
10575                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10576                                PIC_CALL_REG, mips_gp_register);
10577                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10578                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10579                                PIC_CALL_REG);
10580                   load_delay_nop ();
10581                   relax_switch ();
10582                   if (gpdelay)
10583                     macro_build (NULL, "nop", "");
10584                 }
10585               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10586                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10587                            mips_gp_register);
10588               load_delay_nop ();
10589               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10590                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10591               relax_end ();
10592               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10593
10594               if (mips_cprestore_offset < 0)
10595                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10596               else
10597                 {
10598                   if (!mips_frame_reg_valid)
10599                     {
10600                       as_warn (_("no .frame pseudo-op used in PIC code"));
10601                       /* Quiet this warning.  */
10602                       mips_frame_reg_valid = 1;
10603                     }
10604                   if (!mips_cprestore_valid)
10605                     {
10606                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10607                       /* Quiet this warning.  */
10608                       mips_cprestore_valid = 1;
10609                     }
10610                   if (mips_opts.noreorder)
10611                     macro_build (NULL, "nop", "");
10612                   expr1.X_add_number = mips_cprestore_offset;
10613                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10614                                                 mips_gp_register,
10615                                                 mips_frame_reg,
10616                                                 HAVE_64BIT_ADDRESSES);
10617                 }
10618             }
10619         }
10620       else if (mips_pic == VXWORKS_PIC)
10621         as_bad (_("non-PIC jump used in PIC library"));
10622       else
10623         abort ();
10624
10625       break;
10626
10627     case M_LBUE_AB:
10628       s = "lbue";
10629       fmt = "t,+j(b)";
10630       offbits = 9;
10631       goto ld_st;
10632     case M_LHUE_AB:
10633       s = "lhue";
10634       fmt = "t,+j(b)";
10635       offbits = 9;
10636       goto ld_st;
10637     case M_LBE_AB:
10638       s = "lbe";
10639       fmt = "t,+j(b)";
10640       offbits = 9;
10641       goto ld_st;
10642     case M_LHE_AB:
10643       s = "lhe";
10644       fmt = "t,+j(b)";
10645       offbits = 9;
10646       goto ld_st;
10647     case M_LLE_AB:
10648       s = "lle";
10649       fmt = "t,+j(b)";
10650       offbits = 9;
10651       goto ld_st;
10652     case M_LWE_AB:
10653       s = "lwe";
10654       fmt = "t,+j(b)";
10655       offbits = 9;
10656       goto ld_st;
10657     case M_LWLE_AB:
10658       s = "lwle";
10659       fmt = "t,+j(b)";
10660       offbits = 9;
10661       goto ld_st;
10662     case M_LWRE_AB:
10663       s = "lwre";
10664       fmt = "t,+j(b)";
10665       offbits = 9;
10666       goto ld_st;
10667     case M_SBE_AB:
10668       s = "sbe";
10669       fmt = "t,+j(b)";
10670       offbits = 9;
10671       goto ld_st;
10672     case M_SCE_AB:
10673       s = "sce";
10674       fmt = "t,+j(b)";
10675       offbits = 9;
10676       goto ld_st;
10677     case M_SHE_AB:
10678       s = "she";
10679       fmt = "t,+j(b)";
10680       offbits = 9;
10681       goto ld_st;
10682     case M_SWE_AB:
10683       s = "swe";
10684       fmt = "t,+j(b)";
10685       offbits = 9;
10686       goto ld_st;
10687     case M_SWLE_AB:
10688       s = "swle";
10689       fmt = "t,+j(b)";
10690       offbits = 9;
10691       goto ld_st;
10692     case M_SWRE_AB:
10693       s = "swre";
10694       fmt = "t,+j(b)";
10695       offbits = 9;
10696       goto ld_st;
10697     case M_ACLR_AB:
10698       s = "aclr";
10699       fmt = "\\,~(b)";
10700       offbits = 12;
10701       goto ld_st;
10702     case M_ASET_AB:
10703       s = "aset";
10704       fmt = "\\,~(b)";
10705       offbits = 12;
10706       goto ld_st;
10707     case M_LB_AB:
10708       s = "lb";
10709       fmt = "t,o(b)";
10710       goto ld;
10711     case M_LBU_AB:
10712       s = "lbu";
10713       fmt = "t,o(b)";
10714       goto ld;
10715     case M_LH_AB:
10716       s = "lh";
10717       fmt = "t,o(b)";
10718       goto ld;
10719     case M_LHU_AB:
10720       s = "lhu";
10721       fmt = "t,o(b)";
10722       goto ld;
10723     case M_LW_AB:
10724       s = "lw";
10725       fmt = "t,o(b)";
10726       goto ld;
10727     case M_LWC0_AB:
10728       gas_assert (!mips_opts.micromips);
10729       s = "lwc0";
10730       fmt = "E,o(b)";
10731       /* Itbl support may require additional care here.  */
10732       coproc = 1;
10733       goto ld_st;
10734     case M_LWC1_AB:
10735       s = "lwc1";
10736       fmt = "T,o(b)";
10737       /* Itbl support may require additional care here.  */
10738       coproc = 1;
10739       goto ld_st;
10740     case M_LWC2_AB:
10741       s = "lwc2";
10742       fmt = COP12_FMT;
10743       offbits = (mips_opts.micromips ? 12 : 16);
10744       /* Itbl support may require additional care here.  */
10745       coproc = 1;
10746       goto ld_st;
10747     case M_LWC3_AB:
10748       gas_assert (!mips_opts.micromips);
10749       s = "lwc3";
10750       fmt = "E,o(b)";
10751       /* Itbl support may require additional care here.  */
10752       coproc = 1;
10753       goto ld_st;
10754     case M_LWL_AB:
10755       s = "lwl";
10756       fmt = MEM12_FMT;
10757       offbits = (mips_opts.micromips ? 12 : 16);
10758       goto ld_st;
10759     case M_LWR_AB:
10760       s = "lwr";
10761       fmt = MEM12_FMT;
10762       offbits = (mips_opts.micromips ? 12 : 16);
10763       goto ld_st;
10764     case M_LDC1_AB:
10765       s = "ldc1";
10766       fmt = "T,o(b)";
10767       /* Itbl support may require additional care here.  */
10768       coproc = 1;
10769       goto ld_st;
10770     case M_LDC2_AB:
10771       s = "ldc2";
10772       fmt = COP12_FMT;
10773       offbits = (mips_opts.micromips ? 12 : 16);
10774       /* Itbl support may require additional care here.  */
10775       coproc = 1;
10776       goto ld_st;
10777     case M_LQC2_AB:
10778       s = "lqc2";
10779       fmt = "+7,o(b)";
10780       /* Itbl support may require additional care here.  */
10781       coproc = 1;
10782       goto ld_st;
10783     case M_LDC3_AB:
10784       s = "ldc3";
10785       fmt = "E,o(b)";
10786       /* Itbl support may require additional care here.  */
10787       coproc = 1;
10788       goto ld_st;
10789     case M_LDL_AB:
10790       s = "ldl";
10791       fmt = MEM12_FMT;
10792       offbits = (mips_opts.micromips ? 12 : 16);
10793       goto ld_st;
10794     case M_LDR_AB:
10795       s = "ldr";
10796       fmt = MEM12_FMT;
10797       offbits = (mips_opts.micromips ? 12 : 16);
10798       goto ld_st;
10799     case M_LL_AB:
10800       s = "ll";
10801       fmt = MEM12_FMT;
10802       offbits = (mips_opts.micromips ? 12 : 16);
10803       goto ld;
10804     case M_LLD_AB:
10805       s = "lld";
10806       fmt = MEM12_FMT;
10807       offbits = (mips_opts.micromips ? 12 : 16);
10808       goto ld;
10809     case M_LWU_AB:
10810       s = "lwu";
10811       fmt = MEM12_FMT;
10812       offbits = (mips_opts.micromips ? 12 : 16);
10813       goto ld;
10814     case M_LWP_AB:
10815       gas_assert (mips_opts.micromips);
10816       s = "lwp";
10817       fmt = "t,~(b)";
10818       offbits = 12;
10819       lp = 1;
10820       goto ld;
10821     case M_LDP_AB:
10822       gas_assert (mips_opts.micromips);
10823       s = "ldp";
10824       fmt = "t,~(b)";
10825       offbits = 12;
10826       lp = 1;
10827       goto ld;
10828     case M_LWM_AB:
10829       gas_assert (mips_opts.micromips);
10830       s = "lwm";
10831       fmt = "n,~(b)";
10832       offbits = 12;
10833       goto ld_st;
10834     case M_LDM_AB:
10835       gas_assert (mips_opts.micromips);
10836       s = "ldm";
10837       fmt = "n,~(b)";
10838       offbits = 12;
10839       goto ld_st;
10840
10841     ld:
10842       /* We don't want to use $0 as tempreg.  */
10843       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10844         goto ld_st;
10845       else
10846         tempreg = op[0] + lp;
10847       goto ld_noat;
10848
10849     case M_SB_AB:
10850       s = "sb";
10851       fmt = "t,o(b)";
10852       goto ld_st;
10853     case M_SH_AB:
10854       s = "sh";
10855       fmt = "t,o(b)";
10856       goto ld_st;
10857     case M_SW_AB:
10858       s = "sw";
10859       fmt = "t,o(b)";
10860       goto ld_st;
10861     case M_SWC0_AB:
10862       gas_assert (!mips_opts.micromips);
10863       s = "swc0";
10864       fmt = "E,o(b)";
10865       /* Itbl support may require additional care here.  */
10866       coproc = 1;
10867       goto ld_st;
10868     case M_SWC1_AB:
10869       s = "swc1";
10870       fmt = "T,o(b)";
10871       /* Itbl support may require additional care here.  */
10872       coproc = 1;
10873       goto ld_st;
10874     case M_SWC2_AB:
10875       s = "swc2";
10876       fmt = COP12_FMT;
10877       offbits = (mips_opts.micromips ? 12 : 16);
10878       /* Itbl support may require additional care here.  */
10879       coproc = 1;
10880       goto ld_st;
10881     case M_SWC3_AB:
10882       gas_assert (!mips_opts.micromips);
10883       s = "swc3";
10884       fmt = "E,o(b)";
10885       /* Itbl support may require additional care here.  */
10886       coproc = 1;
10887       goto ld_st;
10888     case M_SWL_AB:
10889       s = "swl";
10890       fmt = MEM12_FMT;
10891       offbits = (mips_opts.micromips ? 12 : 16);
10892       goto ld_st;
10893     case M_SWR_AB:
10894       s = "swr";
10895       fmt = MEM12_FMT;
10896       offbits = (mips_opts.micromips ? 12 : 16);
10897       goto ld_st;
10898     case M_SC_AB:
10899       s = "sc";
10900       fmt = MEM12_FMT;
10901       offbits = (mips_opts.micromips ? 12 : 16);
10902       goto ld_st;
10903     case M_SCD_AB:
10904       s = "scd";
10905       fmt = MEM12_FMT;
10906       offbits = (mips_opts.micromips ? 12 : 16);
10907       goto ld_st;
10908     case M_CACHE_AB:
10909       s = "cache";
10910       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10911       offbits = (mips_opts.micromips ? 12 : 16);
10912       goto ld_st;
10913     case M_CACHEE_AB:
10914       s = "cachee";
10915       fmt = "k,+j(b)";
10916       offbits = 9;
10917       goto ld_st;
10918     case M_PREF_AB:
10919       s = "pref";
10920       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10921       offbits = (mips_opts.micromips ? 12 : 16);
10922       goto ld_st;
10923     case M_PREFE_AB:
10924       s = "prefe";
10925       fmt = "k,+j(b)";
10926       offbits = 9;
10927       goto ld_st;
10928     case M_SDC1_AB:
10929       s = "sdc1";
10930       fmt = "T,o(b)";
10931       coproc = 1;
10932       /* Itbl support may require additional care here.  */
10933       goto ld_st;
10934     case M_SDC2_AB:
10935       s = "sdc2";
10936       fmt = COP12_FMT;
10937       offbits = (mips_opts.micromips ? 12 : 16);
10938       /* Itbl support may require additional care here.  */
10939       coproc = 1;
10940       goto ld_st;
10941     case M_SQC2_AB:
10942       s = "sqc2";
10943       fmt = "+7,o(b)";
10944       /* Itbl support may require additional care here.  */
10945       coproc = 1;
10946       goto ld_st;
10947     case M_SDC3_AB:
10948       gas_assert (!mips_opts.micromips);
10949       s = "sdc3";
10950       fmt = "E,o(b)";
10951       /* Itbl support may require additional care here.  */
10952       coproc = 1;
10953       goto ld_st;
10954     case M_SDL_AB:
10955       s = "sdl";
10956       fmt = MEM12_FMT;
10957       offbits = (mips_opts.micromips ? 12 : 16);
10958       goto ld_st;
10959     case M_SDR_AB:
10960       s = "sdr";
10961       fmt = MEM12_FMT;
10962       offbits = (mips_opts.micromips ? 12 : 16);
10963       goto ld_st;
10964     case M_SWP_AB:
10965       gas_assert (mips_opts.micromips);
10966       s = "swp";
10967       fmt = "t,~(b)";
10968       offbits = 12;
10969       goto ld_st;
10970     case M_SDP_AB:
10971       gas_assert (mips_opts.micromips);
10972       s = "sdp";
10973       fmt = "t,~(b)";
10974       offbits = 12;
10975       goto ld_st;
10976     case M_SWM_AB:
10977       gas_assert (mips_opts.micromips);
10978       s = "swm";
10979       fmt = "n,~(b)";
10980       offbits = 12;
10981       goto ld_st;
10982     case M_SDM_AB:
10983       gas_assert (mips_opts.micromips);
10984       s = "sdm";
10985       fmt = "n,~(b)";
10986       offbits = 12;
10987
10988     ld_st:
10989       tempreg = AT;
10990     ld_noat:
10991       breg = op[2];
10992       if (small_offset_p (0, align, 16))
10993         {
10994           /* The first case exists for M_LD_AB and M_SD_AB, which are
10995              macros for o32 but which should act like normal instructions
10996              otherwise.  */
10997           if (offbits == 16)
10998             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10999                          offset_reloc[1], offset_reloc[2], breg);
11000           else if (small_offset_p (0, align, offbits))
11001             {
11002               if (offbits == 0)
11003                 macro_build (NULL, s, fmt, op[0], breg);
11004               else
11005                 macro_build (NULL, s, fmt, op[0],
11006                              (int) offset_expr.X_add_number, breg);
11007             }
11008           else
11009             {
11010               if (tempreg == AT)
11011                 used_at = 1;
11012               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11013                            tempreg, breg, -1, offset_reloc[0],
11014                            offset_reloc[1], offset_reloc[2]);
11015               if (offbits == 0)
11016                 macro_build (NULL, s, fmt, op[0], tempreg);
11017               else
11018                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11019             }
11020           break;
11021         }
11022
11023       if (tempreg == AT)
11024         used_at = 1;
11025
11026       if (offset_expr.X_op != O_constant
11027           && offset_expr.X_op != O_symbol)
11028         {
11029           as_bad (_("expression too complex"));
11030           offset_expr.X_op = O_constant;
11031         }
11032
11033       if (HAVE_32BIT_ADDRESSES
11034           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11035         {
11036           char value [32];
11037
11038           sprintf_vma (value, offset_expr.X_add_number);
11039           as_bad (_("number (0x%s) larger than 32 bits"), value);
11040         }
11041
11042       /* A constant expression in PIC code can be handled just as it
11043          is in non PIC code.  */
11044       if (offset_expr.X_op == O_constant)
11045         {
11046           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11047                                                  offbits == 0 ? 16 : offbits);
11048           offset_expr.X_add_number -= expr1.X_add_number;
11049
11050           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11051           if (breg != 0)
11052             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11053                          tempreg, tempreg, breg);
11054           if (offbits == 0)
11055             {
11056               if (offset_expr.X_add_number != 0)
11057                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11058                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11059               macro_build (NULL, s, fmt, op[0], tempreg);
11060             }
11061           else if (offbits == 16)
11062             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11063           else
11064             macro_build (NULL, s, fmt, op[0],
11065                          (int) offset_expr.X_add_number, tempreg);
11066         }
11067       else if (offbits != 16)
11068         {
11069           /* The offset field is too narrow to be used for a low-part
11070              relocation, so load the whole address into the auxillary
11071              register.  */
11072           load_address (tempreg, &offset_expr, &used_at);
11073           if (breg != 0)
11074             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11075                          tempreg, tempreg, breg);
11076           if (offbits == 0)
11077             macro_build (NULL, s, fmt, op[0], tempreg);
11078           else
11079             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11080         }
11081       else if (mips_pic == NO_PIC)
11082         {
11083           /* If this is a reference to a GP relative symbol, and there
11084              is no base register, we want
11085                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11086              Otherwise, if there is no base register, we want
11087                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11088                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11089              If we have a constant, we need two instructions anyhow,
11090              so we always use the latter form.
11091
11092              If we have a base register, and this is a reference to a
11093              GP relative symbol, we want
11094                addu     $tempreg,$breg,$gp
11095                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11096              Otherwise we want
11097                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11098                addu     $tempreg,$tempreg,$breg
11099                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11100              With a constant we always use the latter case.
11101
11102              With 64bit address space and no base register and $at usable,
11103              we want
11104                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11105                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11106                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11107                dsll32   $tempreg,0
11108                daddu    $tempreg,$at
11109                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11110              If we have a base register, we want
11111                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11112                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11113                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11114                daddu    $at,$breg
11115                dsll32   $tempreg,0
11116                daddu    $tempreg,$at
11117                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11118
11119              Without $at we can't generate the optimal path for superscalar
11120              processors here since this would require two temporary registers.
11121                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11122                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11123                dsll     $tempreg,16
11124                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11125                dsll     $tempreg,16
11126                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11127              If we have a base register, we want
11128                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11129                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11130                dsll     $tempreg,16
11131                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11132                dsll     $tempreg,16
11133                daddu    $tempreg,$tempreg,$breg
11134                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11135
11136              For GP relative symbols in 64bit address space we can use
11137              the same sequence as in 32bit address space.  */
11138           if (HAVE_64BIT_SYMBOLS)
11139             {
11140               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11141                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11142                 {
11143                   relax_start (offset_expr.X_add_symbol);
11144                   if (breg == 0)
11145                     {
11146                       macro_build (&offset_expr, s, fmt, op[0],
11147                                    BFD_RELOC_GPREL16, mips_gp_register);
11148                     }
11149                   else
11150                     {
11151                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11152                                    tempreg, breg, mips_gp_register);
11153                       macro_build (&offset_expr, s, fmt, op[0],
11154                                    BFD_RELOC_GPREL16, tempreg);
11155                     }
11156                   relax_switch ();
11157                 }
11158
11159               if (used_at == 0 && mips_opts.at)
11160                 {
11161                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11162                                BFD_RELOC_MIPS_HIGHEST);
11163                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11164                                BFD_RELOC_HI16_S);
11165                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11166                                tempreg, BFD_RELOC_MIPS_HIGHER);
11167                   if (breg != 0)
11168                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11169                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11170                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11171                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11172                                tempreg);
11173                   used_at = 1;
11174                 }
11175               else
11176                 {
11177                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11178                                BFD_RELOC_MIPS_HIGHEST);
11179                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11180                                tempreg, BFD_RELOC_MIPS_HIGHER);
11181                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11182                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11183                                tempreg, BFD_RELOC_HI16_S);
11184                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11185                   if (breg != 0)
11186                     macro_build (NULL, "daddu", "d,v,t",
11187                                  tempreg, tempreg, breg);
11188                   macro_build (&offset_expr, s, fmt, op[0],
11189                                BFD_RELOC_LO16, tempreg);
11190                 }
11191
11192               if (mips_relax.sequence)
11193                 relax_end ();
11194               break;
11195             }
11196
11197           if (breg == 0)
11198             {
11199               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11200                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11201                 {
11202                   relax_start (offset_expr.X_add_symbol);
11203                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11204                                mips_gp_register);
11205                   relax_switch ();
11206                 }
11207               macro_build_lui (&offset_expr, tempreg);
11208               macro_build (&offset_expr, s, fmt, op[0],
11209                            BFD_RELOC_LO16, tempreg);
11210               if (mips_relax.sequence)
11211                 relax_end ();
11212             }
11213           else
11214             {
11215               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11216                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11217                 {
11218                   relax_start (offset_expr.X_add_symbol);
11219                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11220                                tempreg, breg, mips_gp_register);
11221                   macro_build (&offset_expr, s, fmt, op[0],
11222                                BFD_RELOC_GPREL16, tempreg);
11223                   relax_switch ();
11224                 }
11225               macro_build_lui (&offset_expr, tempreg);
11226               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11227                            tempreg, tempreg, breg);
11228               macro_build (&offset_expr, s, fmt, op[0],
11229                            BFD_RELOC_LO16, tempreg);
11230               if (mips_relax.sequence)
11231                 relax_end ();
11232             }
11233         }
11234       else if (!mips_big_got)
11235         {
11236           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11237
11238           /* If this is a reference to an external symbol, we want
11239                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11240                nop
11241                <op>     op[0],0($tempreg)
11242              Otherwise we want
11243                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11244                nop
11245                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11246                <op>     op[0],0($tempreg)
11247
11248              For NewABI, we want
11249                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11250                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11251
11252              If there is a base register, we add it to $tempreg before
11253              the <op>.  If there is a constant, we stick it in the
11254              <op> instruction.  We don't handle constants larger than
11255              16 bits, because we have no way to load the upper 16 bits
11256              (actually, we could handle them for the subset of cases
11257              in which we are not using $at).  */
11258           gas_assert (offset_expr.X_op == O_symbol);
11259           if (HAVE_NEWABI)
11260             {
11261               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11262                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11263               if (breg != 0)
11264                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11265                              tempreg, tempreg, breg);
11266               macro_build (&offset_expr, s, fmt, op[0],
11267                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11268               break;
11269             }
11270           expr1.X_add_number = offset_expr.X_add_number;
11271           offset_expr.X_add_number = 0;
11272           if (expr1.X_add_number < -0x8000
11273               || expr1.X_add_number >= 0x8000)
11274             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11275           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11276                        lw_reloc_type, mips_gp_register);
11277           load_delay_nop ();
11278           relax_start (offset_expr.X_add_symbol);
11279           relax_switch ();
11280           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11281                        tempreg, BFD_RELOC_LO16);
11282           relax_end ();
11283           if (breg != 0)
11284             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11285                          tempreg, tempreg, breg);
11286           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11287         }
11288       else if (mips_big_got && !HAVE_NEWABI)
11289         {
11290           int gpdelay;
11291
11292           /* If this is a reference to an external symbol, we want
11293                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11294                addu     $tempreg,$tempreg,$gp
11295                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11296                <op>     op[0],0($tempreg)
11297              Otherwise we want
11298                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11299                nop
11300                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11301                <op>     op[0],0($tempreg)
11302              If there is a base register, we add it to $tempreg before
11303              the <op>.  If there is a constant, we stick it in the
11304              <op> instruction.  We don't handle constants larger than
11305              16 bits, because we have no way to load the upper 16 bits
11306              (actually, we could handle them for the subset of cases
11307              in which we are not using $at).  */
11308           gas_assert (offset_expr.X_op == O_symbol);
11309           expr1.X_add_number = offset_expr.X_add_number;
11310           offset_expr.X_add_number = 0;
11311           if (expr1.X_add_number < -0x8000
11312               || expr1.X_add_number >= 0x8000)
11313             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11314           gpdelay = reg_needs_delay (mips_gp_register);
11315           relax_start (offset_expr.X_add_symbol);
11316           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11317                        BFD_RELOC_MIPS_GOT_HI16);
11318           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11319                        mips_gp_register);
11320           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11321                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11322           relax_switch ();
11323           if (gpdelay)
11324             macro_build (NULL, "nop", "");
11325           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11326                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11327           load_delay_nop ();
11328           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11329                        tempreg, BFD_RELOC_LO16);
11330           relax_end ();
11331
11332           if (breg != 0)
11333             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11334                          tempreg, tempreg, breg);
11335           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11336         }
11337       else if (mips_big_got && HAVE_NEWABI)
11338         {
11339           /* If this is a reference to an external symbol, we want
11340                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11341                add      $tempreg,$tempreg,$gp
11342                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11343                <op>     op[0],<ofst>($tempreg)
11344              Otherwise, for local symbols, we want:
11345                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11346                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11347           gas_assert (offset_expr.X_op == O_symbol);
11348           expr1.X_add_number = offset_expr.X_add_number;
11349           offset_expr.X_add_number = 0;
11350           if (expr1.X_add_number < -0x8000
11351               || expr1.X_add_number >= 0x8000)
11352             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11353           relax_start (offset_expr.X_add_symbol);
11354           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11355                        BFD_RELOC_MIPS_GOT_HI16);
11356           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11357                        mips_gp_register);
11358           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11359                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11360           if (breg != 0)
11361             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11362                          tempreg, tempreg, breg);
11363           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11364
11365           relax_switch ();
11366           offset_expr.X_add_number = expr1.X_add_number;
11367           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11368                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11369           if (breg != 0)
11370             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11371                          tempreg, tempreg, breg);
11372           macro_build (&offset_expr, s, fmt, op[0],
11373                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11374           relax_end ();
11375         }
11376       else
11377         abort ();
11378
11379       break;
11380
11381     case M_JRADDIUSP:
11382       gas_assert (mips_opts.micromips);
11383       gas_assert (mips_opts.insn32);
11384       start_noreorder ();
11385       macro_build (NULL, "jr", "s", RA);
11386       expr1.X_add_number = op[0] << 2;
11387       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11388       end_noreorder ();
11389       break;
11390
11391     case M_JRC:
11392       gas_assert (mips_opts.micromips);
11393       gas_assert (mips_opts.insn32);
11394       macro_build (NULL, "jr", "s", op[0]);
11395       if (mips_opts.noreorder)
11396         macro_build (NULL, "nop", "");
11397       break;
11398
11399     case M_LI:
11400     case M_LI_S:
11401       load_register (op[0], &imm_expr, 0);
11402       break;
11403
11404     case M_DLI:
11405       load_register (op[0], &imm_expr, 1);
11406       break;
11407
11408     case M_LI_SS:
11409       if (imm_expr.X_op == O_constant)
11410         {
11411           used_at = 1;
11412           load_register (AT, &imm_expr, 0);
11413           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11414           break;
11415         }
11416       else
11417         {
11418           gas_assert (imm_expr.X_op == O_absent
11419                       && offset_expr.X_op == O_symbol
11420                       && strcmp (segment_name (S_GET_SEGMENT
11421                                                (offset_expr.X_add_symbol)),
11422                                  ".lit4") == 0
11423                       && offset_expr.X_add_number == 0);
11424           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11425                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11426           break;
11427         }
11428
11429     case M_LI_D:
11430       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11431          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11432          order 32 bits of the value and the low order 32 bits are either
11433          zero or in OFFSET_EXPR.  */
11434       if (imm_expr.X_op == O_constant)
11435         {
11436           if (HAVE_64BIT_GPRS)
11437             load_register (op[0], &imm_expr, 1);
11438           else
11439             {
11440               int hreg, lreg;
11441
11442               if (target_big_endian)
11443                 {
11444                   hreg = op[0];
11445                   lreg = op[0] + 1;
11446                 }
11447               else
11448                 {
11449                   hreg = op[0] + 1;
11450                   lreg = op[0];
11451                 }
11452
11453               if (hreg <= 31)
11454                 load_register (hreg, &imm_expr, 0);
11455               if (lreg <= 31)
11456                 {
11457                   if (offset_expr.X_op == O_absent)
11458                     move_register (lreg, 0);
11459                   else
11460                     {
11461                       gas_assert (offset_expr.X_op == O_constant);
11462                       load_register (lreg, &offset_expr, 0);
11463                     }
11464                 }
11465             }
11466           break;
11467         }
11468       gas_assert (imm_expr.X_op == O_absent);
11469
11470       /* We know that sym is in the .rdata section.  First we get the
11471          upper 16 bits of the address.  */
11472       if (mips_pic == NO_PIC)
11473         {
11474           macro_build_lui (&offset_expr, AT);
11475           used_at = 1;
11476         }
11477       else
11478         {
11479           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11480                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11481           used_at = 1;
11482         }
11483
11484       /* Now we load the register(s).  */
11485       if (HAVE_64BIT_GPRS)
11486         {
11487           used_at = 1;
11488           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11489                        BFD_RELOC_LO16, AT);
11490         }
11491       else
11492         {
11493           used_at = 1;
11494           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11495                        BFD_RELOC_LO16, AT);
11496           if (op[0] != RA)
11497             {
11498               /* FIXME: How in the world do we deal with the possible
11499                  overflow here?  */
11500               offset_expr.X_add_number += 4;
11501               macro_build (&offset_expr, "lw", "t,o(b)",
11502                            op[0] + 1, BFD_RELOC_LO16, AT);
11503             }
11504         }
11505       break;
11506
11507     case M_LI_DD:
11508       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11509          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11510          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11511          the value and the low order 32 bits are either zero or in
11512          OFFSET_EXPR.  */
11513       if (imm_expr.X_op == O_constant)
11514         {
11515           used_at = 1;
11516           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11517           if (HAVE_64BIT_FPRS)
11518             {
11519               gas_assert (HAVE_64BIT_GPRS);
11520               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11521             }
11522           else
11523             {
11524               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11525               if (offset_expr.X_op == O_absent)
11526                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11527               else
11528                 {
11529                   gas_assert (offset_expr.X_op == O_constant);
11530                   load_register (AT, &offset_expr, 0);
11531                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11532                 }
11533             }
11534           break;
11535         }
11536
11537       gas_assert (imm_expr.X_op == O_absent
11538                   && offset_expr.X_op == O_symbol
11539                   && offset_expr.X_add_number == 0);
11540       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11541       if (strcmp (s, ".lit8") == 0)
11542         {
11543           op[2] = mips_gp_register;
11544           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11545           offset_reloc[1] = BFD_RELOC_UNUSED;
11546           offset_reloc[2] = BFD_RELOC_UNUSED;
11547         }
11548       else
11549         {
11550           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11551           used_at = 1;
11552           if (mips_pic != NO_PIC)
11553             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11554                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11555           else
11556             {
11557               /* FIXME: This won't work for a 64 bit address.  */
11558               macro_build_lui (&offset_expr, AT);
11559             }
11560
11561           op[2] = AT;
11562           offset_reloc[0] = BFD_RELOC_LO16;
11563           offset_reloc[1] = BFD_RELOC_UNUSED;
11564           offset_reloc[2] = BFD_RELOC_UNUSED;
11565         }
11566       align = 8;
11567       /* Fall through */
11568
11569     case M_L_DAB:
11570       /*
11571        * The MIPS assembler seems to check for X_add_number not
11572        * being double aligned and generating:
11573        *        lui     at,%hi(foo+1)
11574        *        addu    at,at,v1
11575        *        addiu   at,at,%lo(foo+1)
11576        *        lwc1    f2,0(at)
11577        *        lwc1    f3,4(at)
11578        * But, the resulting address is the same after relocation so why
11579        * generate the extra instruction?
11580        */
11581       /* Itbl support may require additional care here.  */
11582       coproc = 1;
11583       fmt = "T,o(b)";
11584       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11585         {
11586           s = "ldc1";
11587           goto ld_st;
11588         }
11589       s = "lwc1";
11590       goto ldd_std;
11591
11592     case M_S_DAB:
11593       gas_assert (!mips_opts.micromips);
11594       /* Itbl support may require additional care here.  */
11595       coproc = 1;
11596       fmt = "T,o(b)";
11597       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11598         {
11599           s = "sdc1";
11600           goto ld_st;
11601         }
11602       s = "swc1";
11603       goto ldd_std;
11604
11605     case M_LQ_AB:
11606       fmt = "t,o(b)";
11607       s = "lq";
11608       goto ld;
11609
11610     case M_SQ_AB:
11611       fmt = "t,o(b)";
11612       s = "sq";
11613       goto ld_st;
11614
11615     case M_LD_AB:
11616       fmt = "t,o(b)";
11617       if (HAVE_64BIT_GPRS)
11618         {
11619           s = "ld";
11620           goto ld;
11621         }
11622       s = "lw";
11623       goto ldd_std;
11624
11625     case M_SD_AB:
11626       fmt = "t,o(b)";
11627       if (HAVE_64BIT_GPRS)
11628         {
11629           s = "sd";
11630           goto ld_st;
11631         }
11632       s = "sw";
11633
11634     ldd_std:
11635       /* Even on a big endian machine $fn comes before $fn+1.  We have
11636          to adjust when loading from memory.  We set coproc if we must
11637          load $fn+1 first.  */
11638       /* Itbl support may require additional care here.  */
11639       if (!target_big_endian)
11640         coproc = 0;
11641
11642       breg = op[2];
11643       if (small_offset_p (0, align, 16))
11644         {
11645           ep = &offset_expr;
11646           if (!small_offset_p (4, align, 16))
11647             {
11648               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11649                            -1, offset_reloc[0], offset_reloc[1],
11650                            offset_reloc[2]);
11651               expr1.X_add_number = 0;
11652               ep = &expr1;
11653               breg = AT;
11654               used_at = 1;
11655               offset_reloc[0] = BFD_RELOC_LO16;
11656               offset_reloc[1] = BFD_RELOC_UNUSED;
11657               offset_reloc[2] = BFD_RELOC_UNUSED;
11658             }
11659           if (strcmp (s, "lw") == 0 && op[0] == breg)
11660             {
11661               ep->X_add_number += 4;
11662               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11663                            offset_reloc[1], offset_reloc[2], breg);
11664               ep->X_add_number -= 4;
11665               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11666                            offset_reloc[1], offset_reloc[2], breg);
11667             }
11668           else
11669             {
11670               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11671                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11672                            breg);
11673               ep->X_add_number += 4;
11674               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11675                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11676                            breg);
11677             }
11678           break;
11679         }
11680
11681       if (offset_expr.X_op != O_symbol
11682           && offset_expr.X_op != O_constant)
11683         {
11684           as_bad (_("expression too complex"));
11685           offset_expr.X_op = O_constant;
11686         }
11687
11688       if (HAVE_32BIT_ADDRESSES
11689           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11690         {
11691           char value [32];
11692
11693           sprintf_vma (value, offset_expr.X_add_number);
11694           as_bad (_("number (0x%s) larger than 32 bits"), value);
11695         }
11696
11697       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11698         {
11699           /* If this is a reference to a GP relative symbol, we want
11700                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11701                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11702              If we have a base register, we use this
11703                addu     $at,$breg,$gp
11704                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11705                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11706              If this is not a GP relative symbol, we want
11707                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11708                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11709                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11710              If there is a base register, we add it to $at after the
11711              lui instruction.  If there is a constant, we always use
11712              the last case.  */
11713           if (offset_expr.X_op == O_symbol
11714               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11715               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11716             {
11717               relax_start (offset_expr.X_add_symbol);
11718               if (breg == 0)
11719                 {
11720                   tempreg = mips_gp_register;
11721                 }
11722               else
11723                 {
11724                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11725                                AT, breg, mips_gp_register);
11726                   tempreg = AT;
11727                   used_at = 1;
11728                 }
11729
11730               /* Itbl support may require additional care here.  */
11731               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11732                            BFD_RELOC_GPREL16, tempreg);
11733               offset_expr.X_add_number += 4;
11734
11735               /* Set mips_optimize to 2 to avoid inserting an
11736                  undesired nop.  */
11737               hold_mips_optimize = mips_optimize;
11738               mips_optimize = 2;
11739               /* Itbl support may require additional care here.  */
11740               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11741                            BFD_RELOC_GPREL16, tempreg);
11742               mips_optimize = hold_mips_optimize;
11743
11744               relax_switch ();
11745
11746               offset_expr.X_add_number -= 4;
11747             }
11748           used_at = 1;
11749           if (offset_high_part (offset_expr.X_add_number, 16)
11750               != offset_high_part (offset_expr.X_add_number + 4, 16))
11751             {
11752               load_address (AT, &offset_expr, &used_at);
11753               offset_expr.X_op = O_constant;
11754               offset_expr.X_add_number = 0;
11755             }
11756           else
11757             macro_build_lui (&offset_expr, AT);
11758           if (breg != 0)
11759             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11760           /* Itbl support may require additional care here.  */
11761           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11762                        BFD_RELOC_LO16, AT);
11763           /* FIXME: How do we handle overflow here?  */
11764           offset_expr.X_add_number += 4;
11765           /* Itbl support may require additional care here.  */
11766           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11767                        BFD_RELOC_LO16, AT);
11768           if (mips_relax.sequence)
11769             relax_end ();
11770         }
11771       else if (!mips_big_got)
11772         {
11773           /* If this is a reference to an external symbol, we want
11774                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11775                nop
11776                <op>     op[0],0($at)
11777                <op>     op[0]+1,4($at)
11778              Otherwise we want
11779                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11780                nop
11781                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11782                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11783              If there is a base register we add it to $at before the
11784              lwc1 instructions.  If there is a constant we include it
11785              in the lwc1 instructions.  */
11786           used_at = 1;
11787           expr1.X_add_number = offset_expr.X_add_number;
11788           if (expr1.X_add_number < -0x8000
11789               || expr1.X_add_number >= 0x8000 - 4)
11790             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11791           load_got_offset (AT, &offset_expr);
11792           load_delay_nop ();
11793           if (breg != 0)
11794             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11795
11796           /* Set mips_optimize to 2 to avoid inserting an undesired
11797              nop.  */
11798           hold_mips_optimize = mips_optimize;
11799           mips_optimize = 2;
11800
11801           /* Itbl support may require additional care here.  */
11802           relax_start (offset_expr.X_add_symbol);
11803           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11804                        BFD_RELOC_LO16, AT);
11805           expr1.X_add_number += 4;
11806           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11807                        BFD_RELOC_LO16, AT);
11808           relax_switch ();
11809           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11810                        BFD_RELOC_LO16, AT);
11811           offset_expr.X_add_number += 4;
11812           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11813                        BFD_RELOC_LO16, AT);
11814           relax_end ();
11815
11816           mips_optimize = hold_mips_optimize;
11817         }
11818       else if (mips_big_got)
11819         {
11820           int gpdelay;
11821
11822           /* If this is a reference to an external symbol, we want
11823                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11824                addu     $at,$at,$gp
11825                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11826                nop
11827                <op>     op[0],0($at)
11828                <op>     op[0]+1,4($at)
11829              Otherwise we want
11830                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11831                nop
11832                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11833                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11834              If there is a base register we add it to $at before the
11835              lwc1 instructions.  If there is a constant we include it
11836              in the lwc1 instructions.  */
11837           used_at = 1;
11838           expr1.X_add_number = offset_expr.X_add_number;
11839           offset_expr.X_add_number = 0;
11840           if (expr1.X_add_number < -0x8000
11841               || expr1.X_add_number >= 0x8000 - 4)
11842             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11843           gpdelay = reg_needs_delay (mips_gp_register);
11844           relax_start (offset_expr.X_add_symbol);
11845           macro_build (&offset_expr, "lui", LUI_FMT,
11846                        AT, BFD_RELOC_MIPS_GOT_HI16);
11847           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11848                        AT, AT, mips_gp_register);
11849           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11850                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11851           load_delay_nop ();
11852           if (breg != 0)
11853             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11854           /* Itbl support may require additional care here.  */
11855           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11856                        BFD_RELOC_LO16, AT);
11857           expr1.X_add_number += 4;
11858
11859           /* Set mips_optimize to 2 to avoid inserting an undesired
11860              nop.  */
11861           hold_mips_optimize = mips_optimize;
11862           mips_optimize = 2;
11863           /* Itbl support may require additional care here.  */
11864           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11865                        BFD_RELOC_LO16, AT);
11866           mips_optimize = hold_mips_optimize;
11867           expr1.X_add_number -= 4;
11868
11869           relax_switch ();
11870           offset_expr.X_add_number = expr1.X_add_number;
11871           if (gpdelay)
11872             macro_build (NULL, "nop", "");
11873           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11874                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11875           load_delay_nop ();
11876           if (breg != 0)
11877             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11878           /* Itbl support may require additional care here.  */
11879           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11880                        BFD_RELOC_LO16, AT);
11881           offset_expr.X_add_number += 4;
11882
11883           /* Set mips_optimize to 2 to avoid inserting an undesired
11884              nop.  */
11885           hold_mips_optimize = mips_optimize;
11886           mips_optimize = 2;
11887           /* Itbl support may require additional care here.  */
11888           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11889                        BFD_RELOC_LO16, AT);
11890           mips_optimize = hold_mips_optimize;
11891           relax_end ();
11892         }
11893       else
11894         abort ();
11895
11896       break;
11897         
11898     case M_SAA_AB:
11899       s = "saa";
11900       offbits = 0;
11901       fmt = "t,(b)";
11902       goto ld_st;
11903     case M_SAAD_AB:
11904       s = "saad";
11905       offbits = 0;
11906       fmt = "t,(b)";
11907       goto ld_st;
11908
11909    /* New code added to support COPZ instructions.
11910       This code builds table entries out of the macros in mip_opcodes.
11911       R4000 uses interlocks to handle coproc delays.
11912       Other chips (like the R3000) require nops to be inserted for delays.
11913
11914       FIXME: Currently, we require that the user handle delays.
11915       In order to fill delay slots for non-interlocked chips,
11916       we must have a way to specify delays based on the coprocessor.
11917       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11918       What are the side-effects of the cop instruction?
11919       What cache support might we have and what are its effects?
11920       Both coprocessor & memory require delays. how long???
11921       What registers are read/set/modified?
11922
11923       If an itbl is provided to interpret cop instructions,
11924       this knowledge can be encoded in the itbl spec.  */
11925
11926     case M_COP0:
11927       s = "c0";
11928       goto copz;
11929     case M_COP1:
11930       s = "c1";
11931       goto copz;
11932     case M_COP2:
11933       s = "c2";
11934       goto copz;
11935     case M_COP3:
11936       s = "c3";
11937     copz:
11938       gas_assert (!mips_opts.micromips);
11939       /* For now we just do C (same as Cz).  The parameter will be
11940          stored in insn_opcode by mips_ip.  */
11941       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11942       break;
11943
11944     case M_MOVE:
11945       move_register (op[0], op[1]);
11946       break;
11947
11948     case M_MOVEP:
11949       gas_assert (mips_opts.micromips);
11950       gas_assert (mips_opts.insn32);
11951       move_register (micromips_to_32_reg_h_map1[op[0]],
11952                      micromips_to_32_reg_m_map[op[1]]);
11953       move_register (micromips_to_32_reg_h_map2[op[0]],
11954                      micromips_to_32_reg_n_map[op[2]]);
11955       break;
11956
11957     case M_DMUL:
11958       dbl = 1;
11959     case M_MUL:
11960       if (mips_opts.arch == CPU_R5900)
11961         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11962                      op[2]);
11963       else
11964         {
11965           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11966           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11967         }
11968       break;
11969
11970     case M_DMUL_I:
11971       dbl = 1;
11972     case M_MUL_I:
11973       /* The MIPS assembler some times generates shifts and adds.  I'm
11974          not trying to be that fancy. GCC should do this for us
11975          anyway.  */
11976       used_at = 1;
11977       load_register (AT, &imm_expr, dbl);
11978       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11979       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11980       break;
11981
11982     case M_DMULO_I:
11983       dbl = 1;
11984     case M_MULO_I:
11985       imm = 1;
11986       goto do_mulo;
11987
11988     case M_DMULO:
11989       dbl = 1;
11990     case M_MULO:
11991     do_mulo:
11992       start_noreorder ();
11993       used_at = 1;
11994       if (imm)
11995         load_register (AT, &imm_expr, dbl);
11996       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11997                    op[1], imm ? AT : op[2]);
11998       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11999       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12000       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12001       if (mips_trap)
12002         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12003       else
12004         {
12005           if (mips_opts.micromips)
12006             micromips_label_expr (&label_expr);
12007           else
12008             label_expr.X_add_number = 8;
12009           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12010           macro_build (NULL, "nop", "");
12011           macro_build (NULL, "break", BRK_FMT, 6);
12012           if (mips_opts.micromips)
12013             micromips_add_label ();
12014         }
12015       end_noreorder ();
12016       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12017       break;
12018
12019     case M_DMULOU_I:
12020       dbl = 1;
12021     case M_MULOU_I:
12022       imm = 1;
12023       goto do_mulou;
12024
12025     case M_DMULOU:
12026       dbl = 1;
12027     case M_MULOU:
12028     do_mulou:
12029       start_noreorder ();
12030       used_at = 1;
12031       if (imm)
12032         load_register (AT, &imm_expr, dbl);
12033       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12034                    op[1], imm ? AT : op[2]);
12035       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12036       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12037       if (mips_trap)
12038         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12039       else
12040         {
12041           if (mips_opts.micromips)
12042             micromips_label_expr (&label_expr);
12043           else
12044             label_expr.X_add_number = 8;
12045           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12046           macro_build (NULL, "nop", "");
12047           macro_build (NULL, "break", BRK_FMT, 6);
12048           if (mips_opts.micromips)
12049             micromips_add_label ();
12050         }
12051       end_noreorder ();
12052       break;
12053
12054     case M_DROL:
12055       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12056         {
12057           if (op[0] == op[1])
12058             {
12059               tempreg = AT;
12060               used_at = 1;
12061             }
12062           else
12063             tempreg = op[0];
12064           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12065           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12066           break;
12067         }
12068       used_at = 1;
12069       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12070       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12071       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12072       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12073       break;
12074
12075     case M_ROL:
12076       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12077         {
12078           if (op[0] == op[1])
12079             {
12080               tempreg = AT;
12081               used_at = 1;
12082             }
12083           else
12084             tempreg = op[0];
12085           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12086           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12087           break;
12088         }
12089       used_at = 1;
12090       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12091       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12092       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12093       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12094       break;
12095
12096     case M_DROL_I:
12097       {
12098         unsigned int rot;
12099         char *l;
12100         char *rr;
12101
12102         rot = imm_expr.X_add_number & 0x3f;
12103         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12104           {
12105             rot = (64 - rot) & 0x3f;
12106             if (rot >= 32)
12107               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12108             else
12109               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12110             break;
12111           }
12112         if (rot == 0)
12113           {
12114             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12115             break;
12116           }
12117         l = (rot < 0x20) ? "dsll" : "dsll32";
12118         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12119         rot &= 0x1f;
12120         used_at = 1;
12121         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12122         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12123         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12124       }
12125       break;
12126
12127     case M_ROL_I:
12128       {
12129         unsigned int rot;
12130
12131         rot = imm_expr.X_add_number & 0x1f;
12132         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12133           {
12134             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12135                          (32 - rot) & 0x1f);
12136             break;
12137           }
12138         if (rot == 0)
12139           {
12140             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12141             break;
12142           }
12143         used_at = 1;
12144         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12145         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12146         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12147       }
12148       break;
12149
12150     case M_DROR:
12151       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12152         {
12153           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12154           break;
12155         }
12156       used_at = 1;
12157       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12158       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12159       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12160       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12161       break;
12162
12163     case M_ROR:
12164       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12165         {
12166           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12167           break;
12168         }
12169       used_at = 1;
12170       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12171       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12172       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12173       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12174       break;
12175
12176     case M_DROR_I:
12177       {
12178         unsigned int rot;
12179         char *l;
12180         char *rr;
12181
12182         rot = imm_expr.X_add_number & 0x3f;
12183         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12184           {
12185             if (rot >= 32)
12186               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12187             else
12188               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12189             break;
12190           }
12191         if (rot == 0)
12192           {
12193             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12194             break;
12195           }
12196         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12197         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12198         rot &= 0x1f;
12199         used_at = 1;
12200         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12201         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12202         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12203       }
12204       break;
12205
12206     case M_ROR_I:
12207       {
12208         unsigned int rot;
12209
12210         rot = imm_expr.X_add_number & 0x1f;
12211         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12212           {
12213             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12214             break;
12215           }
12216         if (rot == 0)
12217           {
12218             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12219             break;
12220           }
12221         used_at = 1;
12222         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12223         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12224         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12225       }
12226       break;
12227
12228     case M_SEQ:
12229       if (op[1] == 0)
12230         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12231       else if (op[2] == 0)
12232         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12233       else
12234         {
12235           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12236           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12237         }
12238       break;
12239
12240     case M_SEQ_I:
12241       if (imm_expr.X_add_number == 0)
12242         {
12243           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12244           break;
12245         }
12246       if (op[1] == 0)
12247         {
12248           as_warn (_("instruction %s: result is always false"),
12249                    ip->insn_mo->name);
12250           move_register (op[0], 0);
12251           break;
12252         }
12253       if (CPU_HAS_SEQ (mips_opts.arch)
12254           && -512 <= imm_expr.X_add_number
12255           && imm_expr.X_add_number < 512)
12256         {
12257           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12258                        (int) imm_expr.X_add_number);
12259           break;
12260         }
12261       if (imm_expr.X_add_number >= 0
12262           && imm_expr.X_add_number < 0x10000)
12263         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12264       else if (imm_expr.X_add_number > -0x8000
12265                && imm_expr.X_add_number < 0)
12266         {
12267           imm_expr.X_add_number = -imm_expr.X_add_number;
12268           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12269                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12270         }
12271       else if (CPU_HAS_SEQ (mips_opts.arch))
12272         {
12273           used_at = 1;
12274           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12275           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12276           break;
12277         }
12278       else
12279         {
12280           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12281           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12282           used_at = 1;
12283         }
12284       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12285       break;
12286
12287     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12288       s = "slt";
12289       goto sge;
12290     case M_SGEU:
12291       s = "sltu";
12292     sge:
12293       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12294       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12295       break;
12296
12297     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12298     case M_SGEU_I:
12299       if (imm_expr.X_add_number >= -0x8000
12300           && imm_expr.X_add_number < 0x8000)
12301         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12302                      op[0], op[1], BFD_RELOC_LO16);
12303       else
12304         {
12305           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12306           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12307                        op[0], op[1], AT);
12308           used_at = 1;
12309         }
12310       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12311       break;
12312
12313     case M_SGT:         /* X > Y  <==>  Y < X */
12314       s = "slt";
12315       goto sgt;
12316     case M_SGTU:
12317       s = "sltu";
12318     sgt:
12319       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12320       break;
12321
12322     case M_SGT_I:       /* X > I  <==>  I < X */
12323       s = "slt";
12324       goto sgti;
12325     case M_SGTU_I:
12326       s = "sltu";
12327     sgti:
12328       used_at = 1;
12329       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12330       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12331       break;
12332
12333     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12334       s = "slt";
12335       goto sle;
12336     case M_SLEU:
12337       s = "sltu";
12338     sle:
12339       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12340       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12341       break;
12342
12343     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12344       s = "slt";
12345       goto slei;
12346     case M_SLEU_I:
12347       s = "sltu";
12348     slei:
12349       used_at = 1;
12350       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12351       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12352       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12353       break;
12354
12355     case M_SLT_I:
12356       if (imm_expr.X_add_number >= -0x8000
12357           && imm_expr.X_add_number < 0x8000)
12358         {
12359           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12360                        BFD_RELOC_LO16);
12361           break;
12362         }
12363       used_at = 1;
12364       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12365       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12366       break;
12367
12368     case M_SLTU_I:
12369       if (imm_expr.X_add_number >= -0x8000
12370           && imm_expr.X_add_number < 0x8000)
12371         {
12372           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12373                        BFD_RELOC_LO16);
12374           break;
12375         }
12376       used_at = 1;
12377       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12378       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12379       break;
12380
12381     case M_SNE:
12382       if (op[1] == 0)
12383         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12384       else if (op[2] == 0)
12385         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12386       else
12387         {
12388           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12389           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12390         }
12391       break;
12392
12393     case M_SNE_I:
12394       if (imm_expr.X_add_number == 0)
12395         {
12396           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12397           break;
12398         }
12399       if (op[1] == 0)
12400         {
12401           as_warn (_("instruction %s: result is always true"),
12402                    ip->insn_mo->name);
12403           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12404                        op[0], 0, BFD_RELOC_LO16);
12405           break;
12406         }
12407       if (CPU_HAS_SEQ (mips_opts.arch)
12408           && -512 <= imm_expr.X_add_number
12409           && imm_expr.X_add_number < 512)
12410         {
12411           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12412                        (int) imm_expr.X_add_number);
12413           break;
12414         }
12415       if (imm_expr.X_add_number >= 0
12416           && imm_expr.X_add_number < 0x10000)
12417         {
12418           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12419                        BFD_RELOC_LO16);
12420         }
12421       else if (imm_expr.X_add_number > -0x8000
12422                && imm_expr.X_add_number < 0)
12423         {
12424           imm_expr.X_add_number = -imm_expr.X_add_number;
12425           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12426                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12427         }
12428       else if (CPU_HAS_SEQ (mips_opts.arch))
12429         {
12430           used_at = 1;
12431           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12432           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12433           break;
12434         }
12435       else
12436         {
12437           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12438           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12439           used_at = 1;
12440         }
12441       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12442       break;
12443
12444     case M_SUB_I:
12445       s = "addi";
12446       s2 = "sub";
12447       goto do_subi;
12448     case M_SUBU_I:
12449       s = "addiu";
12450       s2 = "subu";
12451       goto do_subi;
12452     case M_DSUB_I:
12453       dbl = 1;
12454       s = "daddi";
12455       s2 = "dsub";
12456       if (!mips_opts.micromips)
12457         goto do_subi;
12458       if (imm_expr.X_add_number > -0x200
12459           && imm_expr.X_add_number <= 0x200)
12460         {
12461           macro_build (NULL, s, "t,r,.", op[0], op[1],
12462                        (int) -imm_expr.X_add_number);
12463           break;
12464         }
12465       goto do_subi_i;
12466     case M_DSUBU_I:
12467       dbl = 1;
12468       s = "daddiu";
12469       s2 = "dsubu";
12470     do_subi:
12471       if (imm_expr.X_add_number > -0x8000
12472           && imm_expr.X_add_number <= 0x8000)
12473         {
12474           imm_expr.X_add_number = -imm_expr.X_add_number;
12475           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12476           break;
12477         }
12478     do_subi_i:
12479       used_at = 1;
12480       load_register (AT, &imm_expr, dbl);
12481       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12482       break;
12483
12484     case M_TEQ_I:
12485       s = "teq";
12486       goto trap;
12487     case M_TGE_I:
12488       s = "tge";
12489       goto trap;
12490     case M_TGEU_I:
12491       s = "tgeu";
12492       goto trap;
12493     case M_TLT_I:
12494       s = "tlt";
12495       goto trap;
12496     case M_TLTU_I:
12497       s = "tltu";
12498       goto trap;
12499     case M_TNE_I:
12500       s = "tne";
12501     trap:
12502       used_at = 1;
12503       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12504       macro_build (NULL, s, "s,t", op[0], AT);
12505       break;
12506
12507     case M_TRUNCWS:
12508     case M_TRUNCWD:
12509       gas_assert (!mips_opts.micromips);
12510       gas_assert (mips_opts.isa == ISA_MIPS1);
12511       used_at = 1;
12512
12513       /*
12514        * Is the double cfc1 instruction a bug in the mips assembler;
12515        * or is there a reason for it?
12516        */
12517       start_noreorder ();
12518       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12519       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12520       macro_build (NULL, "nop", "");
12521       expr1.X_add_number = 3;
12522       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12523       expr1.X_add_number = 2;
12524       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12525       macro_build (NULL, "ctc1", "t,G", AT, RA);
12526       macro_build (NULL, "nop", "");
12527       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12528                    op[0], op[1]);
12529       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12530       macro_build (NULL, "nop", "");
12531       end_noreorder ();
12532       break;
12533
12534     case M_ULH_AB:
12535       s = "lb";
12536       s2 = "lbu";
12537       off = 1;
12538       goto uld_st;
12539     case M_ULHU_AB:
12540       s = "lbu";
12541       s2 = "lbu";
12542       off = 1;
12543       goto uld_st;
12544     case M_ULW_AB:
12545       s = "lwl";
12546       s2 = "lwr";
12547       offbits = (mips_opts.micromips ? 12 : 16);
12548       off = 3;
12549       goto uld_st;
12550     case M_ULD_AB:
12551       s = "ldl";
12552       s2 = "ldr";
12553       offbits = (mips_opts.micromips ? 12 : 16);
12554       off = 7;
12555       goto uld_st;
12556     case M_USH_AB:
12557       s = "sb";
12558       s2 = "sb";
12559       off = 1;
12560       ust = 1;
12561       goto uld_st;
12562     case M_USW_AB:
12563       s = "swl";
12564       s2 = "swr";
12565       offbits = (mips_opts.micromips ? 12 : 16);
12566       off = 3;
12567       ust = 1;
12568       goto uld_st;
12569     case M_USD_AB:
12570       s = "sdl";
12571       s2 = "sdr";
12572       offbits = (mips_opts.micromips ? 12 : 16);
12573       off = 7;
12574       ust = 1;
12575
12576     uld_st:
12577       breg = op[2];
12578       large_offset = !small_offset_p (off, align, offbits);
12579       ep = &offset_expr;
12580       expr1.X_add_number = 0;
12581       if (large_offset)
12582         {
12583           used_at = 1;
12584           tempreg = AT;
12585           if (small_offset_p (0, align, 16))
12586             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12587                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12588           else
12589             {
12590               load_address (tempreg, ep, &used_at);
12591               if (breg != 0)
12592                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12593                              tempreg, tempreg, breg);
12594             }
12595           offset_reloc[0] = BFD_RELOC_LO16;
12596           offset_reloc[1] = BFD_RELOC_UNUSED;
12597           offset_reloc[2] = BFD_RELOC_UNUSED;
12598           breg = tempreg;
12599           tempreg = op[0];
12600           ep = &expr1;
12601         }
12602       else if (!ust && op[0] == breg)
12603         {
12604           used_at = 1;
12605           tempreg = AT;
12606         }
12607       else
12608         tempreg = op[0];
12609
12610       if (off == 1)
12611         goto ulh_sh;
12612
12613       if (!target_big_endian)
12614         ep->X_add_number += off;
12615       if (offbits == 12)
12616         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12617       else
12618         macro_build (ep, s, "t,o(b)", tempreg, -1,
12619                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12620
12621       if (!target_big_endian)
12622         ep->X_add_number -= off;
12623       else
12624         ep->X_add_number += off;
12625       if (offbits == 12)
12626         macro_build (NULL, s2, "t,~(b)",
12627                      tempreg, (int) ep->X_add_number, breg);
12628       else
12629         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12630                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12631
12632       /* If necessary, move the result in tempreg to the final destination.  */
12633       if (!ust && op[0] != tempreg)
12634         {
12635           /* Protect second load's delay slot.  */
12636           load_delay_nop ();
12637           move_register (op[0], tempreg);
12638         }
12639       break;
12640
12641     ulh_sh:
12642       used_at = 1;
12643       if (target_big_endian == ust)
12644         ep->X_add_number += off;
12645       tempreg = ust || large_offset ? op[0] : AT;
12646       macro_build (ep, s, "t,o(b)", tempreg, -1,
12647                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12648
12649       /* For halfword transfers we need a temporary register to shuffle
12650          bytes.  Unfortunately for M_USH_A we have none available before
12651          the next store as AT holds the base address.  We deal with this
12652          case by clobbering TREG and then restoring it as with ULH.  */
12653       tempreg = ust == large_offset ? op[0] : AT;
12654       if (ust)
12655         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12656
12657       if (target_big_endian == ust)
12658         ep->X_add_number -= off;
12659       else
12660         ep->X_add_number += off;
12661       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12662                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12663
12664       /* For M_USH_A re-retrieve the LSB.  */
12665       if (ust && large_offset)
12666         {
12667           if (target_big_endian)
12668             ep->X_add_number += off;
12669           else
12670             ep->X_add_number -= off;
12671           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12672                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12673         }
12674       /* For ULH and M_USH_A OR the LSB in.  */
12675       if (!ust || large_offset)
12676         {
12677           tempreg = !large_offset ? AT : op[0];
12678           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12679           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12680         }
12681       break;
12682
12683     default:
12684       /* FIXME: Check if this is one of the itbl macros, since they
12685          are added dynamically.  */
12686       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12687       break;
12688     }
12689   if (!mips_opts.at && used_at)
12690     as_bad (_("macro used $at after \".set noat\""));
12691 }
12692
12693 /* Implement macros in mips16 mode.  */
12694
12695 static void
12696 mips16_macro (struct mips_cl_insn *ip)
12697 {
12698   const struct mips_operand_array *operands;
12699   int mask;
12700   int tmp;
12701   expressionS expr1;
12702   int dbl;
12703   const char *s, *s2, *s3;
12704   unsigned int op[MAX_OPERANDS];
12705   unsigned int i;
12706
12707   mask = ip->insn_mo->mask;
12708
12709   operands = insn_operands (ip);
12710   for (i = 0; i < MAX_OPERANDS; i++)
12711     if (operands->operand[i])
12712       op[i] = insn_extract_operand (ip, operands->operand[i]);
12713     else
12714       op[i] = -1;
12715
12716   expr1.X_op = O_constant;
12717   expr1.X_op_symbol = NULL;
12718   expr1.X_add_symbol = NULL;
12719   expr1.X_add_number = 1;
12720
12721   dbl = 0;
12722
12723   switch (mask)
12724     {
12725     default:
12726       abort ();
12727
12728     case M_DDIV_3:
12729       dbl = 1;
12730     case M_DIV_3:
12731       s = "mflo";
12732       goto do_div3;
12733     case M_DREM_3:
12734       dbl = 1;
12735     case M_REM_3:
12736       s = "mfhi";
12737     do_div3:
12738       start_noreorder ();
12739       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12740       expr1.X_add_number = 2;
12741       macro_build (&expr1, "bnez", "x,p", op[2]);
12742       macro_build (NULL, "break", "6", 7);
12743
12744       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12745          since that causes an overflow.  We should do that as well,
12746          but I don't see how to do the comparisons without a temporary
12747          register.  */
12748       end_noreorder ();
12749       macro_build (NULL, s, "x", op[0]);
12750       break;
12751
12752     case M_DIVU_3:
12753       s = "divu";
12754       s2 = "mflo";
12755       goto do_divu3;
12756     case M_REMU_3:
12757       s = "divu";
12758       s2 = "mfhi";
12759       goto do_divu3;
12760     case M_DDIVU_3:
12761       s = "ddivu";
12762       s2 = "mflo";
12763       goto do_divu3;
12764     case M_DREMU_3:
12765       s = "ddivu";
12766       s2 = "mfhi";
12767     do_divu3:
12768       start_noreorder ();
12769       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12770       expr1.X_add_number = 2;
12771       macro_build (&expr1, "bnez", "x,p", op[2]);
12772       macro_build (NULL, "break", "6", 7);
12773       end_noreorder ();
12774       macro_build (NULL, s2, "x", op[0]);
12775       break;
12776
12777     case M_DMUL:
12778       dbl = 1;
12779     case M_MUL:
12780       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12781       macro_build (NULL, "mflo", "x", op[0]);
12782       break;
12783
12784     case M_DSUBU_I:
12785       dbl = 1;
12786       goto do_subu;
12787     case M_SUBU_I:
12788     do_subu:
12789       imm_expr.X_add_number = -imm_expr.X_add_number;
12790       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12791       break;
12792
12793     case M_SUBU_I_2:
12794       imm_expr.X_add_number = -imm_expr.X_add_number;
12795       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12796       break;
12797
12798     case M_DSUBU_I_2:
12799       imm_expr.X_add_number = -imm_expr.X_add_number;
12800       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12801       break;
12802
12803     case M_BEQ:
12804       s = "cmp";
12805       s2 = "bteqz";
12806       goto do_branch;
12807     case M_BNE:
12808       s = "cmp";
12809       s2 = "btnez";
12810       goto do_branch;
12811     case M_BLT:
12812       s = "slt";
12813       s2 = "btnez";
12814       goto do_branch;
12815     case M_BLTU:
12816       s = "sltu";
12817       s2 = "btnez";
12818       goto do_branch;
12819     case M_BLE:
12820       s = "slt";
12821       s2 = "bteqz";
12822       goto do_reverse_branch;
12823     case M_BLEU:
12824       s = "sltu";
12825       s2 = "bteqz";
12826       goto do_reverse_branch;
12827     case M_BGE:
12828       s = "slt";
12829       s2 = "bteqz";
12830       goto do_branch;
12831     case M_BGEU:
12832       s = "sltu";
12833       s2 = "bteqz";
12834       goto do_branch;
12835     case M_BGT:
12836       s = "slt";
12837       s2 = "btnez";
12838       goto do_reverse_branch;
12839     case M_BGTU:
12840       s = "sltu";
12841       s2 = "btnez";
12842
12843     do_reverse_branch:
12844       tmp = op[1];
12845       op[1] = op[0];
12846       op[0] = tmp;
12847
12848     do_branch:
12849       macro_build (NULL, s, "x,y", op[0], op[1]);
12850       macro_build (&offset_expr, s2, "p");
12851       break;
12852
12853     case M_BEQ_I:
12854       s = "cmpi";
12855       s2 = "bteqz";
12856       s3 = "x,U";
12857       goto do_branch_i;
12858     case M_BNE_I:
12859       s = "cmpi";
12860       s2 = "btnez";
12861       s3 = "x,U";
12862       goto do_branch_i;
12863     case M_BLT_I:
12864       s = "slti";
12865       s2 = "btnez";
12866       s3 = "x,8";
12867       goto do_branch_i;
12868     case M_BLTU_I:
12869       s = "sltiu";
12870       s2 = "btnez";
12871       s3 = "x,8";
12872       goto do_branch_i;
12873     case M_BLE_I:
12874       s = "slti";
12875       s2 = "btnez";
12876       s3 = "x,8";
12877       goto do_addone_branch_i;
12878     case M_BLEU_I:
12879       s = "sltiu";
12880       s2 = "btnez";
12881       s3 = "x,8";
12882       goto do_addone_branch_i;
12883     case M_BGE_I:
12884       s = "slti";
12885       s2 = "bteqz";
12886       s3 = "x,8";
12887       goto do_branch_i;
12888     case M_BGEU_I:
12889       s = "sltiu";
12890       s2 = "bteqz";
12891       s3 = "x,8";
12892       goto do_branch_i;
12893     case M_BGT_I:
12894       s = "slti";
12895       s2 = "bteqz";
12896       s3 = "x,8";
12897       goto do_addone_branch_i;
12898     case M_BGTU_I:
12899       s = "sltiu";
12900       s2 = "bteqz";
12901       s3 = "x,8";
12902
12903     do_addone_branch_i:
12904       ++imm_expr.X_add_number;
12905
12906     do_branch_i:
12907       macro_build (&imm_expr, s, s3, op[0]);
12908       macro_build (&offset_expr, s2, "p");
12909       break;
12910
12911     case M_ABS:
12912       expr1.X_add_number = 0;
12913       macro_build (&expr1, "slti", "x,8", op[1]);
12914       if (op[0] != op[1])
12915         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12916       expr1.X_add_number = 2;
12917       macro_build (&expr1, "bteqz", "p");
12918       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12919       break;
12920     }
12921 }
12922
12923 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12924    opcode bits in *OPCODE_EXTRA.  */
12925
12926 static struct mips_opcode *
12927 mips_lookup_insn (struct hash_control *hash, const char *start,
12928                   ssize_t length, unsigned int *opcode_extra)
12929 {
12930   char *name, *dot, *p;
12931   unsigned int mask, suffix;
12932   ssize_t opend;
12933   struct mips_opcode *insn;
12934
12935   /* Make a copy of the instruction so that we can fiddle with it.  */
12936   name = alloca (length + 1);
12937   memcpy (name, start, length);
12938   name[length] = '\0';
12939
12940   /* Look up the instruction as-is.  */
12941   insn = (struct mips_opcode *) hash_find (hash, name);
12942   if (insn)
12943     return insn;
12944
12945   dot = strchr (name, '.');
12946   if (dot && dot[1])
12947     {
12948       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12949       p = mips_parse_vu0_channels (dot + 1, &mask);
12950       if (*p == 0 && mask != 0)
12951         {
12952           *dot = 0;
12953           insn = (struct mips_opcode *) hash_find (hash, name);
12954           *dot = '.';
12955           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12956             {
12957               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12958               return insn;
12959             }
12960         }
12961     }
12962
12963   if (mips_opts.micromips)
12964     {
12965       /* See if there's an instruction size override suffix,
12966          either `16' or `32', at the end of the mnemonic proper,
12967          that defines the operation, i.e. before the first `.'
12968          character if any.  Strip it and retry.  */
12969       opend = dot != NULL ? dot - name : length;
12970       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12971         suffix = 2;
12972       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12973         suffix = 4;
12974       else
12975         suffix = 0;
12976       if (suffix)
12977         {
12978           memcpy (name + opend - 2, name + opend, length - opend + 1);
12979           insn = (struct mips_opcode *) hash_find (hash, name);
12980           if (insn)
12981             {
12982               forced_insn_length = suffix;
12983               return insn;
12984             }
12985         }
12986     }
12987
12988   return NULL;
12989 }
12990
12991 /* Assemble an instruction into its binary format.  If the instruction
12992    is a macro, set imm_expr and offset_expr to the values associated
12993    with "I" and "A" operands respectively.  Otherwise store the value
12994    of the relocatable field (if any) in offset_expr.  In both cases
12995    set offset_reloc to the relocation operators applied to offset_expr.  */
12996
12997 static void
12998 mips_ip (char *str, struct mips_cl_insn *insn)
12999 {
13000   const struct mips_opcode *first, *past;
13001   struct hash_control *hash;
13002   char format;
13003   size_t end;
13004   struct mips_operand_token *tokens;
13005   unsigned int opcode_extra;
13006
13007   if (mips_opts.micromips)
13008     {
13009       hash = micromips_op_hash;
13010       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13011     }
13012   else
13013     {
13014       hash = op_hash;
13015       past = &mips_opcodes[NUMOPCODES];
13016     }
13017   forced_insn_length = 0;
13018   opcode_extra = 0;
13019
13020   /* We first try to match an instruction up to a space or to the end.  */
13021   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13022     continue;
13023
13024   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13025   if (first == NULL)
13026     {
13027       set_insn_error (0, _("unrecognized opcode"));
13028       return;
13029     }
13030
13031   if (strcmp (first->name, "li.s") == 0)
13032     format = 'f';
13033   else if (strcmp (first->name, "li.d") == 0)
13034     format = 'd';
13035   else
13036     format = 0;
13037   tokens = mips_parse_arguments (str + end, format);
13038   if (!tokens)
13039     return;
13040
13041   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13042       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13043     set_insn_error (0, _("invalid operands"));
13044
13045   obstack_free (&mips_operand_tokens, tokens);
13046 }
13047
13048 /* As for mips_ip, but used when assembling MIPS16 code.
13049    Also set forced_insn_length to the resulting instruction size in
13050    bytes if the user explicitly requested a small or extended instruction.  */
13051
13052 static void
13053 mips16_ip (char *str, struct mips_cl_insn *insn)
13054 {
13055   char *end, *s, c;
13056   struct mips_opcode *first;
13057   struct mips_operand_token *tokens;
13058
13059   forced_insn_length = 0;
13060
13061   for (s = str; ISLOWER (*s); ++s)
13062     ;
13063   end = s;
13064   c = *end;
13065   switch (c)
13066     {
13067     case '\0':
13068       break;
13069
13070     case ' ':
13071       s++;
13072       break;
13073
13074     case '.':
13075       if (s[1] == 't' && s[2] == ' ')
13076         {
13077           forced_insn_length = 2;
13078           s += 3;
13079           break;
13080         }
13081       else if (s[1] == 'e' && s[2] == ' ')
13082         {
13083           forced_insn_length = 4;
13084           s += 3;
13085           break;
13086         }
13087       /* Fall through.  */
13088     default:
13089       set_insn_error (0, _("unrecognized opcode"));
13090       return;
13091     }
13092
13093   if (mips_opts.noautoextend && !forced_insn_length)
13094     forced_insn_length = 2;
13095
13096   *end = 0;
13097   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13098   *end = c;
13099
13100   if (!first)
13101     {
13102       set_insn_error (0, _("unrecognized opcode"));
13103       return;
13104     }
13105
13106   tokens = mips_parse_arguments (s, 0);
13107   if (!tokens)
13108     return;
13109
13110   if (!match_mips16_insns (insn, first, tokens))
13111     set_insn_error (0, _("invalid operands"));
13112
13113   obstack_free (&mips_operand_tokens, tokens);
13114 }
13115
13116 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13117    NBITS is the number of significant bits in VAL.  */
13118
13119 static unsigned long
13120 mips16_immed_extend (offsetT val, unsigned int nbits)
13121 {
13122   int extval;
13123   if (nbits == 16)
13124     {
13125       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13126       val &= 0x1f;
13127     }
13128   else if (nbits == 15)
13129     {
13130       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13131       val &= 0xf;
13132     }
13133   else
13134     {
13135       extval = ((val & 0x1f) << 6) | (val & 0x20);
13136       val = 0;
13137     }
13138   return (extval << 16) | val;
13139 }
13140
13141 /* Like decode_mips16_operand, but require the operand to be defined and
13142    require it to be an integer.  */
13143
13144 static const struct mips_int_operand *
13145 mips16_immed_operand (int type, bfd_boolean extended_p)
13146 {
13147   const struct mips_operand *operand;
13148
13149   operand = decode_mips16_operand (type, extended_p);
13150   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13151     abort ();
13152   return (const struct mips_int_operand *) operand;
13153 }
13154
13155 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13156
13157 static bfd_boolean
13158 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13159                          bfd_reloc_code_real_type reloc, offsetT sval)
13160 {
13161   int min_val, max_val;
13162
13163   min_val = mips_int_operand_min (operand);
13164   max_val = mips_int_operand_max (operand);
13165   if (reloc != BFD_RELOC_UNUSED)
13166     {
13167       if (min_val < 0)
13168         sval = SEXT_16BIT (sval);
13169       else
13170         sval &= 0xffff;
13171     }
13172
13173   return (sval >= min_val
13174           && sval <= max_val
13175           && (sval & ((1 << operand->shift) - 1)) == 0);
13176 }
13177
13178 /* Install immediate value VAL into MIPS16 instruction *INSN,
13179    extending it if necessary.  The instruction in *INSN may
13180    already be extended.
13181
13182    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13183    if none.  In the former case, VAL is a 16-bit number with no
13184    defined signedness.
13185
13186    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13187    is the length that the user requested, or 0 if none.  */
13188
13189 static void
13190 mips16_immed (char *file, unsigned int line, int type,
13191               bfd_reloc_code_real_type reloc, offsetT val,
13192               unsigned int user_insn_length, unsigned long *insn)
13193 {
13194   const struct mips_int_operand *operand;
13195   unsigned int uval, length;
13196
13197   operand = mips16_immed_operand (type, FALSE);
13198   if (!mips16_immed_in_range_p (operand, reloc, val))
13199     {
13200       /* We need an extended instruction.  */
13201       if (user_insn_length == 2)
13202         as_bad_where (file, line, _("invalid unextended operand value"));
13203       else
13204         *insn |= MIPS16_EXTEND;
13205     }
13206   else if (user_insn_length == 4)
13207     {
13208       /* The operand doesn't force an unextended instruction to be extended.
13209          Warn if the user wanted an extended instruction anyway.  */
13210       *insn |= MIPS16_EXTEND;
13211       as_warn_where (file, line,
13212                      _("extended operand requested but not required"));
13213     }
13214
13215   length = mips16_opcode_length (*insn);
13216   if (length == 4)
13217     {
13218       operand = mips16_immed_operand (type, TRUE);
13219       if (!mips16_immed_in_range_p (operand, reloc, val))
13220         as_bad_where (file, line,
13221                       _("operand value out of range for instruction"));
13222     }
13223   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13224   if (length == 2)
13225     *insn = mips_insert_operand (&operand->root, *insn, uval);
13226   else
13227     *insn |= mips16_immed_extend (uval, operand->root.size);
13228 }
13229 \f
13230 struct percent_op_match
13231 {
13232   const char *str;
13233   bfd_reloc_code_real_type reloc;
13234 };
13235
13236 static const struct percent_op_match mips_percent_op[] =
13237 {
13238   {"%lo", BFD_RELOC_LO16},
13239   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13240   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13241   {"%call16", BFD_RELOC_MIPS_CALL16},
13242   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13243   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13244   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13245   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13246   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13247   {"%got", BFD_RELOC_MIPS_GOT16},
13248   {"%gp_rel", BFD_RELOC_GPREL16},
13249   {"%half", BFD_RELOC_16},
13250   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13251   {"%higher", BFD_RELOC_MIPS_HIGHER},
13252   {"%neg", BFD_RELOC_MIPS_SUB},
13253   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13254   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13255   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13256   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13257   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13258   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13259   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13260   {"%hi", BFD_RELOC_HI16_S}
13261 };
13262
13263 static const struct percent_op_match mips16_percent_op[] =
13264 {
13265   {"%lo", BFD_RELOC_MIPS16_LO16},
13266   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13267   {"%got", BFD_RELOC_MIPS16_GOT16},
13268   {"%call16", BFD_RELOC_MIPS16_CALL16},
13269   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13270   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13271   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13272   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13273   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13274   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13275   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13276   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13277 };
13278
13279
13280 /* Return true if *STR points to a relocation operator.  When returning true,
13281    move *STR over the operator and store its relocation code in *RELOC.
13282    Leave both *STR and *RELOC alone when returning false.  */
13283
13284 static bfd_boolean
13285 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13286 {
13287   const struct percent_op_match *percent_op;
13288   size_t limit, i;
13289
13290   if (mips_opts.mips16)
13291     {
13292       percent_op = mips16_percent_op;
13293       limit = ARRAY_SIZE (mips16_percent_op);
13294     }
13295   else
13296     {
13297       percent_op = mips_percent_op;
13298       limit = ARRAY_SIZE (mips_percent_op);
13299     }
13300
13301   for (i = 0; i < limit; i++)
13302     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13303       {
13304         int len = strlen (percent_op[i].str);
13305
13306         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13307           continue;
13308
13309         *str += strlen (percent_op[i].str);
13310         *reloc = percent_op[i].reloc;
13311
13312         /* Check whether the output BFD supports this relocation.
13313            If not, issue an error and fall back on something safe.  */
13314         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13315           {
13316             as_bad (_("relocation %s isn't supported by the current ABI"),
13317                     percent_op[i].str);
13318             *reloc = BFD_RELOC_UNUSED;
13319           }
13320         return TRUE;
13321       }
13322   return FALSE;
13323 }
13324
13325
13326 /* Parse string STR as a 16-bit relocatable operand.  Store the
13327    expression in *EP and the relocations in the array starting
13328    at RELOC.  Return the number of relocation operators used.
13329
13330    On exit, EXPR_END points to the first character after the expression.  */
13331
13332 static size_t
13333 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13334                        char *str)
13335 {
13336   bfd_reloc_code_real_type reversed_reloc[3];
13337   size_t reloc_index, i;
13338   int crux_depth, str_depth;
13339   char *crux;
13340
13341   /* Search for the start of the main expression, recoding relocations
13342      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13343      of the main expression and with CRUX_DEPTH containing the number
13344      of open brackets at that point.  */
13345   reloc_index = -1;
13346   str_depth = 0;
13347   do
13348     {
13349       reloc_index++;
13350       crux = str;
13351       crux_depth = str_depth;
13352
13353       /* Skip over whitespace and brackets, keeping count of the number
13354          of brackets.  */
13355       while (*str == ' ' || *str == '\t' || *str == '(')
13356         if (*str++ == '(')
13357           str_depth++;
13358     }
13359   while (*str == '%'
13360          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13361          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13362
13363   my_getExpression (ep, crux);
13364   str = expr_end;
13365
13366   /* Match every open bracket.  */
13367   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13368     if (*str++ == ')')
13369       crux_depth--;
13370
13371   if (crux_depth > 0)
13372     as_bad (_("unclosed '('"));
13373
13374   expr_end = str;
13375
13376   if (reloc_index != 0)
13377     {
13378       prev_reloc_op_frag = frag_now;
13379       for (i = 0; i < reloc_index; i++)
13380         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13381     }
13382
13383   return reloc_index;
13384 }
13385
13386 static void
13387 my_getExpression (expressionS *ep, char *str)
13388 {
13389   char *save_in;
13390
13391   save_in = input_line_pointer;
13392   input_line_pointer = str;
13393   expression (ep);
13394   expr_end = input_line_pointer;
13395   input_line_pointer = save_in;
13396 }
13397
13398 char *
13399 md_atof (int type, char *litP, int *sizeP)
13400 {
13401   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13402 }
13403
13404 void
13405 md_number_to_chars (char *buf, valueT val, int n)
13406 {
13407   if (target_big_endian)
13408     number_to_chars_bigendian (buf, val, n);
13409   else
13410     number_to_chars_littleendian (buf, val, n);
13411 }
13412 \f
13413 static int support_64bit_objects(void)
13414 {
13415   const char **list, **l;
13416   int yes;
13417
13418   list = bfd_target_list ();
13419   for (l = list; *l != NULL; l++)
13420     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13421         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13422       break;
13423   yes = (*l != NULL);
13424   free (list);
13425   return yes;
13426 }
13427
13428 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13429    NEW_VALUE.  Warn if another value was already specified.  Note:
13430    we have to defer parsing the -march and -mtune arguments in order
13431    to handle 'from-abi' correctly, since the ABI might be specified
13432    in a later argument.  */
13433
13434 static void
13435 mips_set_option_string (const char **string_ptr, const char *new_value)
13436 {
13437   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13438     as_warn (_("a different %s was already specified, is now %s"),
13439              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13440              new_value);
13441
13442   *string_ptr = new_value;
13443 }
13444
13445 int
13446 md_parse_option (int c, char *arg)
13447 {
13448   unsigned int i;
13449
13450   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13451     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13452       {
13453         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13454                                            c == mips_ases[i].option_on);
13455         return 1;
13456       }
13457
13458   switch (c)
13459     {
13460     case OPTION_CONSTRUCT_FLOATS:
13461       mips_disable_float_construction = 0;
13462       break;
13463
13464     case OPTION_NO_CONSTRUCT_FLOATS:
13465       mips_disable_float_construction = 1;
13466       break;
13467
13468     case OPTION_TRAP:
13469       mips_trap = 1;
13470       break;
13471
13472     case OPTION_BREAK:
13473       mips_trap = 0;
13474       break;
13475
13476     case OPTION_EB:
13477       target_big_endian = 1;
13478       break;
13479
13480     case OPTION_EL:
13481       target_big_endian = 0;
13482       break;
13483
13484     case 'O':
13485       if (arg == NULL)
13486         mips_optimize = 1;
13487       else if (arg[0] == '0')
13488         mips_optimize = 0;
13489       else if (arg[0] == '1')
13490         mips_optimize = 1;
13491       else
13492         mips_optimize = 2;
13493       break;
13494
13495     case 'g':
13496       if (arg == NULL)
13497         mips_debug = 2;
13498       else
13499         mips_debug = atoi (arg);
13500       break;
13501
13502     case OPTION_MIPS1:
13503       file_mips_isa = ISA_MIPS1;
13504       break;
13505
13506     case OPTION_MIPS2:
13507       file_mips_isa = ISA_MIPS2;
13508       break;
13509
13510     case OPTION_MIPS3:
13511       file_mips_isa = ISA_MIPS3;
13512       break;
13513
13514     case OPTION_MIPS4:
13515       file_mips_isa = ISA_MIPS4;
13516       break;
13517
13518     case OPTION_MIPS5:
13519       file_mips_isa = ISA_MIPS5;
13520       break;
13521
13522     case OPTION_MIPS32:
13523       file_mips_isa = ISA_MIPS32;
13524       break;
13525
13526     case OPTION_MIPS32R2:
13527       file_mips_isa = ISA_MIPS32R2;
13528       break;
13529
13530     case OPTION_MIPS64R2:
13531       file_mips_isa = ISA_MIPS64R2;
13532       break;
13533
13534     case OPTION_MIPS64:
13535       file_mips_isa = ISA_MIPS64;
13536       break;
13537
13538     case OPTION_MTUNE:
13539       mips_set_option_string (&mips_tune_string, arg);
13540       break;
13541
13542     case OPTION_MARCH:
13543       mips_set_option_string (&mips_arch_string, arg);
13544       break;
13545
13546     case OPTION_M4650:
13547       mips_set_option_string (&mips_arch_string, "4650");
13548       mips_set_option_string (&mips_tune_string, "4650");
13549       break;
13550
13551     case OPTION_NO_M4650:
13552       break;
13553
13554     case OPTION_M4010:
13555       mips_set_option_string (&mips_arch_string, "4010");
13556       mips_set_option_string (&mips_tune_string, "4010");
13557       break;
13558
13559     case OPTION_NO_M4010:
13560       break;
13561
13562     case OPTION_M4100:
13563       mips_set_option_string (&mips_arch_string, "4100");
13564       mips_set_option_string (&mips_tune_string, "4100");
13565       break;
13566
13567     case OPTION_NO_M4100:
13568       break;
13569
13570     case OPTION_M3900:
13571       mips_set_option_string (&mips_arch_string, "3900");
13572       mips_set_option_string (&mips_tune_string, "3900");
13573       break;
13574
13575     case OPTION_NO_M3900:
13576       break;
13577
13578     case OPTION_MICROMIPS:
13579       if (mips_opts.mips16 == 1)
13580         {
13581           as_bad (_("-mmicromips cannot be used with -mips16"));
13582           return 0;
13583         }
13584       mips_opts.micromips = 1;
13585       mips_no_prev_insn ();
13586       break;
13587
13588     case OPTION_NO_MICROMIPS:
13589       mips_opts.micromips = 0;
13590       mips_no_prev_insn ();
13591       break;
13592
13593     case OPTION_MIPS16:
13594       if (mips_opts.micromips == 1)
13595         {
13596           as_bad (_("-mips16 cannot be used with -micromips"));
13597           return 0;
13598         }
13599       mips_opts.mips16 = 1;
13600       mips_no_prev_insn ();
13601       break;
13602
13603     case OPTION_NO_MIPS16:
13604       mips_opts.mips16 = 0;
13605       mips_no_prev_insn ();
13606       break;
13607
13608     case OPTION_FIX_24K:
13609       mips_fix_24k = 1;
13610       break;
13611
13612     case OPTION_NO_FIX_24K:
13613       mips_fix_24k = 0;
13614       break;
13615
13616     case OPTION_FIX_RM7000:
13617       mips_fix_rm7000 = 1;
13618       break;
13619
13620     case OPTION_NO_FIX_RM7000:
13621       mips_fix_rm7000 = 0;
13622       break;
13623
13624     case OPTION_FIX_LOONGSON2F_JUMP:
13625       mips_fix_loongson2f_jump = TRUE;
13626       break;
13627
13628     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13629       mips_fix_loongson2f_jump = FALSE;
13630       break;
13631
13632     case OPTION_FIX_LOONGSON2F_NOP:
13633       mips_fix_loongson2f_nop = TRUE;
13634       break;
13635
13636     case OPTION_NO_FIX_LOONGSON2F_NOP:
13637       mips_fix_loongson2f_nop = FALSE;
13638       break;
13639
13640     case OPTION_FIX_VR4120:
13641       mips_fix_vr4120 = 1;
13642       break;
13643
13644     case OPTION_NO_FIX_VR4120:
13645       mips_fix_vr4120 = 0;
13646       break;
13647
13648     case OPTION_FIX_VR4130:
13649       mips_fix_vr4130 = 1;
13650       break;
13651
13652     case OPTION_NO_FIX_VR4130:
13653       mips_fix_vr4130 = 0;
13654       break;
13655
13656     case OPTION_FIX_CN63XXP1:
13657       mips_fix_cn63xxp1 = TRUE;
13658       break;
13659
13660     case OPTION_NO_FIX_CN63XXP1:
13661       mips_fix_cn63xxp1 = FALSE;
13662       break;
13663
13664     case OPTION_RELAX_BRANCH:
13665       mips_relax_branch = 1;
13666       break;
13667
13668     case OPTION_NO_RELAX_BRANCH:
13669       mips_relax_branch = 0;
13670       break;
13671
13672     case OPTION_INSN32:
13673       mips_opts.insn32 = TRUE;
13674       break;
13675
13676     case OPTION_NO_INSN32:
13677       mips_opts.insn32 = FALSE;
13678       break;
13679
13680     case OPTION_MSHARED:
13681       mips_in_shared = TRUE;
13682       break;
13683
13684     case OPTION_MNO_SHARED:
13685       mips_in_shared = FALSE;
13686       break;
13687
13688     case OPTION_MSYM32:
13689       mips_opts.sym32 = TRUE;
13690       break;
13691
13692     case OPTION_MNO_SYM32:
13693       mips_opts.sym32 = FALSE;
13694       break;
13695
13696       /* When generating ELF code, we permit -KPIC and -call_shared to
13697          select SVR4_PIC, and -non_shared to select no PIC.  This is
13698          intended to be compatible with Irix 5.  */
13699     case OPTION_CALL_SHARED:
13700       mips_pic = SVR4_PIC;
13701       mips_abicalls = TRUE;
13702       break;
13703
13704     case OPTION_CALL_NONPIC:
13705       mips_pic = NO_PIC;
13706       mips_abicalls = TRUE;
13707       break;
13708
13709     case OPTION_NON_SHARED:
13710       mips_pic = NO_PIC;
13711       mips_abicalls = FALSE;
13712       break;
13713
13714       /* The -xgot option tells the assembler to use 32 bit offsets
13715          when accessing the got in SVR4_PIC mode.  It is for Irix
13716          compatibility.  */
13717     case OPTION_XGOT:
13718       mips_big_got = 1;
13719       break;
13720
13721     case 'G':
13722       g_switch_value = atoi (arg);
13723       g_switch_seen = 1;
13724       break;
13725
13726       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13727          and -mabi=64.  */
13728     case OPTION_32:
13729       mips_abi = O32_ABI;
13730       break;
13731
13732     case OPTION_N32:
13733       mips_abi = N32_ABI;
13734       break;
13735
13736     case OPTION_64:
13737       mips_abi = N64_ABI;
13738       if (!support_64bit_objects())
13739         as_fatal (_("no compiled in support for 64 bit object file format"));
13740       break;
13741
13742     case OPTION_GP32:
13743       file_mips_gp32 = 1;
13744       break;
13745
13746     case OPTION_GP64:
13747       file_mips_gp32 = 0;
13748       break;
13749
13750     case OPTION_FP32:
13751       file_mips_fp32 = 1;
13752       break;
13753
13754     case OPTION_FP64:
13755       file_mips_fp32 = 0;
13756       break;
13757
13758     case OPTION_SINGLE_FLOAT:
13759       file_mips_single_float = 1;
13760       break;
13761
13762     case OPTION_DOUBLE_FLOAT:
13763       file_mips_single_float = 0;
13764       break;
13765
13766     case OPTION_SOFT_FLOAT:
13767       file_mips_soft_float = 1;
13768       break;
13769
13770     case OPTION_HARD_FLOAT:
13771       file_mips_soft_float = 0;
13772       break;
13773
13774     case OPTION_MABI:
13775       if (strcmp (arg, "32") == 0)
13776         mips_abi = O32_ABI;
13777       else if (strcmp (arg, "o64") == 0)
13778         mips_abi = O64_ABI;
13779       else if (strcmp (arg, "n32") == 0)
13780         mips_abi = N32_ABI;
13781       else if (strcmp (arg, "64") == 0)
13782         {
13783           mips_abi = N64_ABI;
13784           if (! support_64bit_objects())
13785             as_fatal (_("no compiled in support for 64 bit object file "
13786                         "format"));
13787         }
13788       else if (strcmp (arg, "eabi") == 0)
13789         mips_abi = EABI_ABI;
13790       else
13791         {
13792           as_fatal (_("invalid abi -mabi=%s"), arg);
13793           return 0;
13794         }
13795       break;
13796
13797     case OPTION_M7000_HILO_FIX:
13798       mips_7000_hilo_fix = TRUE;
13799       break;
13800
13801     case OPTION_MNO_7000_HILO_FIX:
13802       mips_7000_hilo_fix = FALSE;
13803       break;
13804
13805     case OPTION_MDEBUG:
13806       mips_flag_mdebug = TRUE;
13807       break;
13808
13809     case OPTION_NO_MDEBUG:
13810       mips_flag_mdebug = FALSE;
13811       break;
13812
13813     case OPTION_PDR:
13814       mips_flag_pdr = TRUE;
13815       break;
13816
13817     case OPTION_NO_PDR:
13818       mips_flag_pdr = FALSE;
13819       break;
13820
13821     case OPTION_MVXWORKS_PIC:
13822       mips_pic = VXWORKS_PIC;
13823       break;
13824
13825     case OPTION_NAN:
13826       if (strcmp (arg, "2008") == 0)
13827         mips_flag_nan2008 = TRUE;
13828       else if (strcmp (arg, "legacy") == 0)
13829         mips_flag_nan2008 = FALSE;
13830       else
13831         {
13832           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
13833           return 0;
13834         }
13835       break;
13836
13837     default:
13838       return 0;
13839     }
13840
13841     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13842
13843   return 1;
13844 }
13845 \f
13846 /* Set up globals to generate code for the ISA or processor
13847    described by INFO.  */
13848
13849 static void
13850 mips_set_architecture (const struct mips_cpu_info *info)
13851 {
13852   if (info != 0)
13853     {
13854       file_mips_arch = info->cpu;
13855       mips_opts.arch = info->cpu;
13856       mips_opts.isa = info->isa;
13857     }
13858 }
13859
13860
13861 /* Likewise for tuning.  */
13862
13863 static void
13864 mips_set_tune (const struct mips_cpu_info *info)
13865 {
13866   if (info != 0)
13867     mips_tune = info->cpu;
13868 }
13869
13870
13871 void
13872 mips_after_parse_args (void)
13873 {
13874   const struct mips_cpu_info *arch_info = 0;
13875   const struct mips_cpu_info *tune_info = 0;
13876
13877   /* GP relative stuff not working for PE */
13878   if (strncmp (TARGET_OS, "pe", 2) == 0)
13879     {
13880       if (g_switch_seen && g_switch_value != 0)
13881         as_bad (_("-G not supported in this configuration"));
13882       g_switch_value = 0;
13883     }
13884
13885   if (mips_abi == NO_ABI)
13886     mips_abi = MIPS_DEFAULT_ABI;
13887
13888   /* The following code determines the architecture and register size.
13889      Similar code was added to GCC 3.3 (see override_options() in
13890      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13891      as much as possible.  */
13892
13893   if (mips_arch_string != 0)
13894     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13895
13896   if (file_mips_isa != ISA_UNKNOWN)
13897     {
13898       /* Handle -mipsN.  At this point, file_mips_isa contains the
13899          ISA level specified by -mipsN, while arch_info->isa contains
13900          the -march selection (if any).  */
13901       if (arch_info != 0)
13902         {
13903           /* -march takes precedence over -mipsN, since it is more descriptive.
13904              There's no harm in specifying both as long as the ISA levels
13905              are the same.  */
13906           if (file_mips_isa != arch_info->isa)
13907             as_bad (_("-%s conflicts with the other architecture options,"
13908                       " which imply -%s"),
13909                     mips_cpu_info_from_isa (file_mips_isa)->name,
13910                     mips_cpu_info_from_isa (arch_info->isa)->name);
13911         }
13912       else
13913         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13914     }
13915
13916   if (arch_info == 0)
13917     {
13918       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13919       gas_assert (arch_info);
13920     }
13921
13922   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13923     as_bad (_("-march=%s is not compatible with the selected ABI"),
13924             arch_info->name);
13925
13926   mips_set_architecture (arch_info);
13927
13928   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13929   if (mips_tune_string != 0)
13930     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13931
13932   if (tune_info == 0)
13933     mips_set_tune (arch_info);
13934   else
13935     mips_set_tune (tune_info);
13936
13937   if (file_mips_gp32 >= 0)
13938     {
13939       /* The user specified the size of the integer registers.  Make sure
13940          it agrees with the ABI and ISA.  */
13941       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13942         as_bad (_("-mgp64 used with a 32-bit processor"));
13943       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13944         as_bad (_("-mgp32 used with a 64-bit ABI"));
13945       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13946         as_bad (_("-mgp64 used with a 32-bit ABI"));
13947     }
13948   else
13949     {
13950       /* Infer the integer register size from the ABI and processor.
13951          Restrict ourselves to 32-bit registers if that's all the
13952          processor has, or if the ABI cannot handle 64-bit registers.  */
13953       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13954                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13955     }
13956
13957   switch (file_mips_fp32)
13958     {
13959     default:
13960     case -1:
13961       /* No user specified float register size.
13962          ??? GAS treats single-float processors as though they had 64-bit
13963          float registers (although it complains when double-precision
13964          instructions are used).  As things stand, saying they have 32-bit
13965          registers would lead to spurious "register must be even" messages.
13966          So here we assume float registers are never smaller than the
13967          integer ones.  */
13968       if (file_mips_gp32 == 0)
13969         /* 64-bit integer registers implies 64-bit float registers.  */
13970         file_mips_fp32 = 0;
13971       else if ((mips_opts.ase & FP64_ASES)
13972                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13973         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13974         file_mips_fp32 = 0;
13975       else
13976         /* 32-bit float registers.  */
13977         file_mips_fp32 = 1;
13978       break;
13979
13980     /* The user specified the size of the float registers.  Check if it
13981        agrees with the ABI and ISA.  */
13982     case 0:
13983       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13984         as_bad (_("-mfp64 used with a 32-bit fpu"));
13985       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13986                && !ISA_HAS_MXHC1 (mips_opts.isa))
13987         as_warn (_("-mfp64 used with a 32-bit ABI"));
13988       break;
13989     case 1:
13990       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13991         as_warn (_("-mfp32 used with a 64-bit ABI"));
13992       break;
13993     }
13994
13995   /* End of GCC-shared inference code.  */
13996
13997   /* This flag is set when we have a 64-bit capable CPU but use only
13998      32-bit wide registers.  Note that EABI does not use it.  */
13999   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14000       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14001           || mips_abi == O32_ABI))
14002     mips_32bitmode = 1;
14003
14004   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14005     as_bad (_("trap exception not supported at ISA 1"));
14006
14007   /* If the selected architecture includes support for ASEs, enable
14008      generation of code for them.  */
14009   if (mips_opts.mips16 == -1)
14010     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14011   if (mips_opts.micromips == -1)
14012     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14013
14014   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
14015      ASEs from being selected implicitly.  */
14016   if (file_mips_fp32 == 1)
14017     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
14018
14019   /* If the user didn't explicitly select or deselect a particular ASE,
14020      use the default setting for the CPU.  */
14021   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
14022
14023   file_mips_isa = mips_opts.isa;
14024   file_ase = mips_opts.ase;
14025   mips_opts.gp32 = file_mips_gp32;
14026   mips_opts.fp32 = file_mips_fp32;
14027   mips_opts.soft_float = file_mips_soft_float;
14028   mips_opts.single_float = file_mips_single_float;
14029
14030   mips_check_isa_supports_ases ();
14031
14032   if (mips_flag_mdebug < 0)
14033     mips_flag_mdebug = 0;
14034 }
14035 \f
14036 void
14037 mips_init_after_args (void)
14038 {
14039   /* initialize opcodes */
14040   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14041   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14042 }
14043
14044 long
14045 md_pcrel_from (fixS *fixP)
14046 {
14047   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14048   switch (fixP->fx_r_type)
14049     {
14050     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14051     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14052       /* Return the address of the delay slot.  */
14053       return addr + 2;
14054
14055     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14056     case BFD_RELOC_MICROMIPS_JMP:
14057     case BFD_RELOC_16_PCREL_S2:
14058     case BFD_RELOC_MIPS_JMP:
14059       /* Return the address of the delay slot.  */
14060       return addr + 4;
14061
14062     case BFD_RELOC_32_PCREL:
14063       return addr;
14064
14065     default:
14066       /* We have no relocation type for PC relative MIPS16 instructions.  */
14067       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
14068         as_bad_where (fixP->fx_file, fixP->fx_line,
14069                       _("PC relative MIPS16 instruction references"
14070                         " a different section"));
14071       return addr;
14072     }
14073 }
14074
14075 /* This is called before the symbol table is processed.  In order to
14076    work with gcc when using mips-tfile, we must keep all local labels.
14077    However, in other cases, we want to discard them.  If we were
14078    called with -g, but we didn't see any debugging information, it may
14079    mean that gcc is smuggling debugging information through to
14080    mips-tfile, in which case we must generate all local labels.  */
14081
14082 void
14083 mips_frob_file_before_adjust (void)
14084 {
14085 #ifndef NO_ECOFF_DEBUGGING
14086   if (ECOFF_DEBUGGING
14087       && mips_debug != 0
14088       && ! ecoff_debugging_seen)
14089     flag_keep_locals = 1;
14090 #endif
14091 }
14092
14093 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14094    the corresponding LO16 reloc.  This is called before md_apply_fix and
14095    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14096    relocation operators.
14097
14098    For our purposes, a %lo() expression matches a %got() or %hi()
14099    expression if:
14100
14101       (a) it refers to the same symbol; and
14102       (b) the offset applied in the %lo() expression is no lower than
14103           the offset applied in the %got() or %hi().
14104
14105    (b) allows us to cope with code like:
14106
14107         lui     $4,%hi(foo)
14108         lh      $4,%lo(foo+2)($4)
14109
14110    ...which is legal on RELA targets, and has a well-defined behaviour
14111    if the user knows that adding 2 to "foo" will not induce a carry to
14112    the high 16 bits.
14113
14114    When several %lo()s match a particular %got() or %hi(), we use the
14115    following rules to distinguish them:
14116
14117      (1) %lo()s with smaller offsets are a better match than %lo()s with
14118          higher offsets.
14119
14120      (2) %lo()s with no matching %got() or %hi() are better than those
14121          that already have a matching %got() or %hi().
14122
14123      (3) later %lo()s are better than earlier %lo()s.
14124
14125    These rules are applied in order.
14126
14127    (1) means, among other things, that %lo()s with identical offsets are
14128    chosen if they exist.
14129
14130    (2) means that we won't associate several high-part relocations with
14131    the same low-part relocation unless there's no alternative.  Having
14132    several high parts for the same low part is a GNU extension; this rule
14133    allows careful users to avoid it.
14134
14135    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14136    with the last high-part relocation being at the front of the list.
14137    It therefore makes sense to choose the last matching low-part
14138    relocation, all other things being equal.  It's also easier
14139    to code that way.  */
14140
14141 void
14142 mips_frob_file (void)
14143 {
14144   struct mips_hi_fixup *l;
14145   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14146
14147   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14148     {
14149       segment_info_type *seginfo;
14150       bfd_boolean matched_lo_p;
14151       fixS **hi_pos, **lo_pos, **pos;
14152
14153       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14154
14155       /* If a GOT16 relocation turns out to be against a global symbol,
14156          there isn't supposed to be a matching LO.  Ignore %gots against
14157          constants; we'll report an error for those later.  */
14158       if (got16_reloc_p (l->fixp->fx_r_type)
14159           && !(l->fixp->fx_addsy
14160                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14161         continue;
14162
14163       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14164       if (fixup_has_matching_lo_p (l->fixp))
14165         continue;
14166
14167       seginfo = seg_info (l->seg);
14168
14169       /* Set HI_POS to the position of this relocation in the chain.
14170          Set LO_POS to the position of the chosen low-part relocation.
14171          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14172          relocation that matches an immediately-preceding high-part
14173          relocation.  */
14174       hi_pos = NULL;
14175       lo_pos = NULL;
14176       matched_lo_p = FALSE;
14177       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14178
14179       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14180         {
14181           if (*pos == l->fixp)
14182             hi_pos = pos;
14183
14184           if ((*pos)->fx_r_type == looking_for_rtype
14185               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14186               && (*pos)->fx_offset >= l->fixp->fx_offset
14187               && (lo_pos == NULL
14188                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14189                   || (!matched_lo_p
14190                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14191             lo_pos = pos;
14192
14193           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14194                           && fixup_has_matching_lo_p (*pos));
14195         }
14196
14197       /* If we found a match, remove the high-part relocation from its
14198          current position and insert it before the low-part relocation.
14199          Make the offsets match so that fixup_has_matching_lo_p()
14200          will return true.
14201
14202          We don't warn about unmatched high-part relocations since some
14203          versions of gcc have been known to emit dead "lui ...%hi(...)"
14204          instructions.  */
14205       if (lo_pos != NULL)
14206         {
14207           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14208           if (l->fixp->fx_next != *lo_pos)
14209             {
14210               *hi_pos = l->fixp->fx_next;
14211               l->fixp->fx_next = *lo_pos;
14212               *lo_pos = l->fixp;
14213             }
14214         }
14215     }
14216 }
14217
14218 int
14219 mips_force_relocation (fixS *fixp)
14220 {
14221   if (generic_force_reloc (fixp))
14222     return 1;
14223
14224   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14225      so that the linker relaxation can update targets.  */
14226   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14227       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14228       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14229     return 1;
14230
14231   return 0;
14232 }
14233
14234 /* Read the instruction associated with RELOC from BUF.  */
14235
14236 static unsigned int
14237 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14238 {
14239   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14240     return read_compressed_insn (buf, 4);
14241   else
14242     return read_insn (buf);
14243 }
14244
14245 /* Write instruction INSN to BUF, given that it has been relocated
14246    by RELOC.  */
14247
14248 static void
14249 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14250                   unsigned long insn)
14251 {
14252   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14253     write_compressed_insn (buf, insn, 4);
14254   else
14255     write_insn (buf, insn);
14256 }
14257
14258 /* Apply a fixup to the object file.  */
14259
14260 void
14261 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14262 {
14263   char *buf;
14264   unsigned long insn;
14265   reloc_howto_type *howto;
14266
14267   /* We ignore generic BFD relocations we don't know about.  */
14268   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14269   if (! howto)
14270     return;
14271
14272   gas_assert (fixP->fx_size == 2
14273               || fixP->fx_size == 4
14274               || fixP->fx_r_type == BFD_RELOC_16
14275               || fixP->fx_r_type == BFD_RELOC_64
14276               || fixP->fx_r_type == BFD_RELOC_CTOR
14277               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14278               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14279               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14280               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14281               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14282
14283   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14284
14285   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
14286               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14287               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14288               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
14289               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
14290
14291   /* Don't treat parts of a composite relocation as done.  There are two
14292      reasons for this:
14293
14294      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14295          should nevertheless be emitted if the first part is.
14296
14297      (2) In normal usage, composite relocations are never assembly-time
14298          constants.  The easiest way of dealing with the pathological
14299          exceptions is to generate a relocation against STN_UNDEF and
14300          leave everything up to the linker.  */
14301   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14302     fixP->fx_done = 1;
14303
14304   switch (fixP->fx_r_type)
14305     {
14306     case BFD_RELOC_MIPS_TLS_GD:
14307     case BFD_RELOC_MIPS_TLS_LDM:
14308     case BFD_RELOC_MIPS_TLS_DTPREL32:
14309     case BFD_RELOC_MIPS_TLS_DTPREL64:
14310     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14311     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14312     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14313     case BFD_RELOC_MIPS_TLS_TPREL32:
14314     case BFD_RELOC_MIPS_TLS_TPREL64:
14315     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14316     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14317     case BFD_RELOC_MICROMIPS_TLS_GD:
14318     case BFD_RELOC_MICROMIPS_TLS_LDM:
14319     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14320     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14321     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14322     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14323     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14324     case BFD_RELOC_MIPS16_TLS_GD:
14325     case BFD_RELOC_MIPS16_TLS_LDM:
14326     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14327     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14328     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14329     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14330     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14331       if (!fixP->fx_addsy)
14332         {
14333           as_bad_where (fixP->fx_file, fixP->fx_line,
14334                         _("TLS relocation against a constant"));
14335           break;
14336         }
14337       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14338       /* fall through */
14339
14340     case BFD_RELOC_MIPS_JMP:
14341     case BFD_RELOC_MIPS_SHIFT5:
14342     case BFD_RELOC_MIPS_SHIFT6:
14343     case BFD_RELOC_MIPS_GOT_DISP:
14344     case BFD_RELOC_MIPS_GOT_PAGE:
14345     case BFD_RELOC_MIPS_GOT_OFST:
14346     case BFD_RELOC_MIPS_SUB:
14347     case BFD_RELOC_MIPS_INSERT_A:
14348     case BFD_RELOC_MIPS_INSERT_B:
14349     case BFD_RELOC_MIPS_DELETE:
14350     case BFD_RELOC_MIPS_HIGHEST:
14351     case BFD_RELOC_MIPS_HIGHER:
14352     case BFD_RELOC_MIPS_SCN_DISP:
14353     case BFD_RELOC_MIPS_REL16:
14354     case BFD_RELOC_MIPS_RELGOT:
14355     case BFD_RELOC_MIPS_JALR:
14356     case BFD_RELOC_HI16:
14357     case BFD_RELOC_HI16_S:
14358     case BFD_RELOC_LO16:
14359     case BFD_RELOC_GPREL16:
14360     case BFD_RELOC_MIPS_LITERAL:
14361     case BFD_RELOC_MIPS_CALL16:
14362     case BFD_RELOC_MIPS_GOT16:
14363     case BFD_RELOC_GPREL32:
14364     case BFD_RELOC_MIPS_GOT_HI16:
14365     case BFD_RELOC_MIPS_GOT_LO16:
14366     case BFD_RELOC_MIPS_CALL_HI16:
14367     case BFD_RELOC_MIPS_CALL_LO16:
14368     case BFD_RELOC_MIPS16_GPREL:
14369     case BFD_RELOC_MIPS16_GOT16:
14370     case BFD_RELOC_MIPS16_CALL16:
14371     case BFD_RELOC_MIPS16_HI16:
14372     case BFD_RELOC_MIPS16_HI16_S:
14373     case BFD_RELOC_MIPS16_LO16:
14374     case BFD_RELOC_MIPS16_JMP:
14375     case BFD_RELOC_MICROMIPS_JMP:
14376     case BFD_RELOC_MICROMIPS_GOT_DISP:
14377     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14378     case BFD_RELOC_MICROMIPS_GOT_OFST:
14379     case BFD_RELOC_MICROMIPS_SUB:
14380     case BFD_RELOC_MICROMIPS_HIGHEST:
14381     case BFD_RELOC_MICROMIPS_HIGHER:
14382     case BFD_RELOC_MICROMIPS_SCN_DISP:
14383     case BFD_RELOC_MICROMIPS_JALR:
14384     case BFD_RELOC_MICROMIPS_HI16:
14385     case BFD_RELOC_MICROMIPS_HI16_S:
14386     case BFD_RELOC_MICROMIPS_LO16:
14387     case BFD_RELOC_MICROMIPS_GPREL16:
14388     case BFD_RELOC_MICROMIPS_LITERAL:
14389     case BFD_RELOC_MICROMIPS_CALL16:
14390     case BFD_RELOC_MICROMIPS_GOT16:
14391     case BFD_RELOC_MICROMIPS_GOT_HI16:
14392     case BFD_RELOC_MICROMIPS_GOT_LO16:
14393     case BFD_RELOC_MICROMIPS_CALL_HI16:
14394     case BFD_RELOC_MICROMIPS_CALL_LO16:
14395     case BFD_RELOC_MIPS_EH:
14396       if (fixP->fx_done)
14397         {
14398           offsetT value;
14399
14400           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14401             {
14402               insn = read_reloc_insn (buf, fixP->fx_r_type);
14403               if (mips16_reloc_p (fixP->fx_r_type))
14404                 insn |= mips16_immed_extend (value, 16);
14405               else
14406                 insn |= (value & 0xffff);
14407               write_reloc_insn (buf, fixP->fx_r_type, insn);
14408             }
14409           else
14410             as_bad_where (fixP->fx_file, fixP->fx_line,
14411                           _("unsupported constant in relocation"));
14412         }
14413       break;
14414
14415     case BFD_RELOC_64:
14416       /* This is handled like BFD_RELOC_32, but we output a sign
14417          extended value if we are only 32 bits.  */
14418       if (fixP->fx_done)
14419         {
14420           if (8 <= sizeof (valueT))
14421             md_number_to_chars (buf, *valP, 8);
14422           else
14423             {
14424               valueT hiv;
14425
14426               if ((*valP & 0x80000000) != 0)
14427                 hiv = 0xffffffff;
14428               else
14429                 hiv = 0;
14430               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14431               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14432             }
14433         }
14434       break;
14435
14436     case BFD_RELOC_RVA:
14437     case BFD_RELOC_32:
14438     case BFD_RELOC_32_PCREL:
14439     case BFD_RELOC_16:
14440       /* If we are deleting this reloc entry, we must fill in the
14441          value now.  This can happen if we have a .word which is not
14442          resolved when it appears but is later defined.  */
14443       if (fixP->fx_done)
14444         md_number_to_chars (buf, *valP, fixP->fx_size);
14445       break;
14446
14447     case BFD_RELOC_16_PCREL_S2:
14448       if ((*valP & 0x3) != 0)
14449         as_bad_where (fixP->fx_file, fixP->fx_line,
14450                       _("branch to misaligned address (%lx)"), (long) *valP);
14451
14452       /* We need to save the bits in the instruction since fixup_segment()
14453          might be deleting the relocation entry (i.e., a branch within
14454          the current segment).  */
14455       if (! fixP->fx_done)
14456         break;
14457
14458       /* Update old instruction data.  */
14459       insn = read_insn (buf);
14460
14461       if (*valP + 0x20000 <= 0x3ffff)
14462         {
14463           insn |= (*valP >> 2) & 0xffff;
14464           write_insn (buf, insn);
14465         }
14466       else if (mips_pic == NO_PIC
14467                && fixP->fx_done
14468                && fixP->fx_frag->fr_address >= text_section->vma
14469                && (fixP->fx_frag->fr_address
14470                    < text_section->vma + bfd_get_section_size (text_section))
14471                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14472                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14473                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14474         {
14475           /* The branch offset is too large.  If this is an
14476              unconditional branch, and we are not generating PIC code,
14477              we can convert it to an absolute jump instruction.  */
14478           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14479             insn = 0x0c000000;  /* jal */
14480           else
14481             insn = 0x08000000;  /* j */
14482           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14483           fixP->fx_done = 0;
14484           fixP->fx_addsy = section_symbol (text_section);
14485           *valP += md_pcrel_from (fixP);
14486           write_insn (buf, insn);
14487         }
14488       else
14489         {
14490           /* If we got here, we have branch-relaxation disabled,
14491              and there's nothing we can do to fix this instruction
14492              without turning it into a longer sequence.  */
14493           as_bad_where (fixP->fx_file, fixP->fx_line,
14494                         _("branch out of range"));
14495         }
14496       break;
14497
14498     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14499     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14500     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14501       /* We adjust the offset back to even.  */
14502       if ((*valP & 0x1) != 0)
14503         --(*valP);
14504
14505       if (! fixP->fx_done)
14506         break;
14507
14508       /* Should never visit here, because we keep the relocation.  */
14509       abort ();
14510       break;
14511
14512     case BFD_RELOC_VTABLE_INHERIT:
14513       fixP->fx_done = 0;
14514       if (fixP->fx_addsy
14515           && !S_IS_DEFINED (fixP->fx_addsy)
14516           && !S_IS_WEAK (fixP->fx_addsy))
14517         S_SET_WEAK (fixP->fx_addsy);
14518       break;
14519
14520     case BFD_RELOC_VTABLE_ENTRY:
14521       fixP->fx_done = 0;
14522       break;
14523
14524     default:
14525       abort ();
14526     }
14527
14528   /* Remember value for tc_gen_reloc.  */
14529   fixP->fx_addnumber = *valP;
14530 }
14531
14532 static symbolS *
14533 get_symbol (void)
14534 {
14535   int c;
14536   char *name;
14537   symbolS *p;
14538
14539   name = input_line_pointer;
14540   c = get_symbol_end ();
14541   p = (symbolS *) symbol_find_or_make (name);
14542   *input_line_pointer = c;
14543   return p;
14544 }
14545
14546 /* Align the current frag to a given power of two.  If a particular
14547    fill byte should be used, FILL points to an integer that contains
14548    that byte, otherwise FILL is null.
14549
14550    This function used to have the comment:
14551
14552       The MIPS assembler also automatically adjusts any preceding label.
14553
14554    The implementation therefore applied the adjustment to a maximum of
14555    one label.  However, other label adjustments are applied to batches
14556    of labels, and adjusting just one caused problems when new labels
14557    were added for the sake of debugging or unwind information.
14558    We therefore adjust all preceding labels (given as LABELS) instead.  */
14559
14560 static void
14561 mips_align (int to, int *fill, struct insn_label_list *labels)
14562 {
14563   mips_emit_delays ();
14564   mips_record_compressed_mode ();
14565   if (fill == NULL && subseg_text_p (now_seg))
14566     frag_align_code (to, 0);
14567   else
14568     frag_align (to, fill ? *fill : 0, 0);
14569   record_alignment (now_seg, to);
14570   mips_move_labels (labels, FALSE);
14571 }
14572
14573 /* Align to a given power of two.  .align 0 turns off the automatic
14574    alignment used by the data creating pseudo-ops.  */
14575
14576 static void
14577 s_align (int x ATTRIBUTE_UNUSED)
14578 {
14579   int temp, fill_value, *fill_ptr;
14580   long max_alignment = 28;
14581
14582   /* o Note that the assembler pulls down any immediately preceding label
14583        to the aligned address.
14584      o It's not documented but auto alignment is reinstated by
14585        a .align pseudo instruction.
14586      o Note also that after auto alignment is turned off the mips assembler
14587        issues an error on attempt to assemble an improperly aligned data item.
14588        We don't.  */
14589
14590   temp = get_absolute_expression ();
14591   if (temp > max_alignment)
14592     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14593   else if (temp < 0)
14594     {
14595       as_warn (_("alignment negative, 0 assumed"));
14596       temp = 0;
14597     }
14598   if (*input_line_pointer == ',')
14599     {
14600       ++input_line_pointer;
14601       fill_value = get_absolute_expression ();
14602       fill_ptr = &fill_value;
14603     }
14604   else
14605     fill_ptr = 0;
14606   if (temp)
14607     {
14608       segment_info_type *si = seg_info (now_seg);
14609       struct insn_label_list *l = si->label_list;
14610       /* Auto alignment should be switched on by next section change.  */
14611       auto_align = 1;
14612       mips_align (temp, fill_ptr, l);
14613     }
14614   else
14615     {
14616       auto_align = 0;
14617     }
14618
14619   demand_empty_rest_of_line ();
14620 }
14621
14622 static void
14623 s_change_sec (int sec)
14624 {
14625   segT seg;
14626
14627   /* The ELF backend needs to know that we are changing sections, so
14628      that .previous works correctly.  We could do something like check
14629      for an obj_section_change_hook macro, but that might be confusing
14630      as it would not be appropriate to use it in the section changing
14631      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14632      This should be cleaner, somehow.  */
14633   obj_elf_section_change_hook ();
14634
14635   mips_emit_delays ();
14636
14637   switch (sec)
14638     {
14639     case 't':
14640       s_text (0);
14641       break;
14642     case 'd':
14643       s_data (0);
14644       break;
14645     case 'b':
14646       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14647       demand_empty_rest_of_line ();
14648       break;
14649
14650     case 'r':
14651       seg = subseg_new (RDATA_SECTION_NAME,
14652                         (subsegT) get_absolute_expression ());
14653       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14654                                               | SEC_READONLY | SEC_RELOC
14655                                               | SEC_DATA));
14656       if (strncmp (TARGET_OS, "elf", 3) != 0)
14657         record_alignment (seg, 4);
14658       demand_empty_rest_of_line ();
14659       break;
14660
14661     case 's':
14662       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14663       bfd_set_section_flags (stdoutput, seg,
14664                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14665       if (strncmp (TARGET_OS, "elf", 3) != 0)
14666         record_alignment (seg, 4);
14667       demand_empty_rest_of_line ();
14668       break;
14669
14670     case 'B':
14671       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14672       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14673       if (strncmp (TARGET_OS, "elf", 3) != 0)
14674         record_alignment (seg, 4);
14675       demand_empty_rest_of_line ();
14676       break;
14677     }
14678
14679   auto_align = 1;
14680 }
14681
14682 void
14683 s_change_section (int ignore ATTRIBUTE_UNUSED)
14684 {
14685   char *section_name;
14686   char c;
14687   char next_c = 0;
14688   int section_type;
14689   int section_flag;
14690   int section_entry_size;
14691   int section_alignment;
14692
14693   section_name = input_line_pointer;
14694   c = get_symbol_end ();
14695   if (c)
14696     next_c = *(input_line_pointer + 1);
14697
14698   /* Do we have .section Name<,"flags">?  */
14699   if (c != ',' || (c == ',' && next_c == '"'))
14700     {
14701       /* just after name is now '\0'.  */
14702       *input_line_pointer = c;
14703       input_line_pointer = section_name;
14704       obj_elf_section (ignore);
14705       return;
14706     }
14707   input_line_pointer++;
14708
14709   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14710   if (c == ',')
14711     section_type = get_absolute_expression ();
14712   else
14713     section_type = 0;
14714   if (*input_line_pointer++ == ',')
14715     section_flag = get_absolute_expression ();
14716   else
14717     section_flag = 0;
14718   if (*input_line_pointer++ == ',')
14719     section_entry_size = get_absolute_expression ();
14720   else
14721     section_entry_size = 0;
14722   if (*input_line_pointer++ == ',')
14723     section_alignment = get_absolute_expression ();
14724   else
14725     section_alignment = 0;
14726   /* FIXME: really ignore?  */
14727   (void) section_alignment;
14728
14729   section_name = xstrdup (section_name);
14730
14731   /* When using the generic form of .section (as implemented by obj-elf.c),
14732      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14733      traditionally had to fall back on the more common @progbits instead.
14734
14735      There's nothing really harmful in this, since bfd will correct
14736      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14737      means that, for backwards compatibility, the special_section entries
14738      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14739
14740      Even so, we shouldn't force users of the MIPS .section syntax to
14741      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14742      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14743      generic type-checking code.  */
14744   if (section_type == SHT_MIPS_DWARF)
14745     section_type = SHT_PROGBITS;
14746
14747   obj_elf_change_section (section_name, section_type, section_flag,
14748                           section_entry_size, 0, 0, 0);
14749
14750   if (now_seg->name != section_name)
14751     free (section_name);
14752 }
14753
14754 void
14755 mips_enable_auto_align (void)
14756 {
14757   auto_align = 1;
14758 }
14759
14760 static void
14761 s_cons (int log_size)
14762 {
14763   segment_info_type *si = seg_info (now_seg);
14764   struct insn_label_list *l = si->label_list;
14765
14766   mips_emit_delays ();
14767   if (log_size > 0 && auto_align)
14768     mips_align (log_size, 0, l);
14769   cons (1 << log_size);
14770   mips_clear_insn_labels ();
14771 }
14772
14773 static void
14774 s_float_cons (int type)
14775 {
14776   segment_info_type *si = seg_info (now_seg);
14777   struct insn_label_list *l = si->label_list;
14778
14779   mips_emit_delays ();
14780
14781   if (auto_align)
14782     {
14783       if (type == 'd')
14784         mips_align (3, 0, l);
14785       else
14786         mips_align (2, 0, l);
14787     }
14788
14789   float_cons (type);
14790   mips_clear_insn_labels ();
14791 }
14792
14793 /* Handle .globl.  We need to override it because on Irix 5 you are
14794    permitted to say
14795        .globl foo .text
14796    where foo is an undefined symbol, to mean that foo should be
14797    considered to be the address of a function.  */
14798
14799 static void
14800 s_mips_globl (int x ATTRIBUTE_UNUSED)
14801 {
14802   char *name;
14803   int c;
14804   symbolS *symbolP;
14805   flagword flag;
14806
14807   do
14808     {
14809       name = input_line_pointer;
14810       c = get_symbol_end ();
14811       symbolP = symbol_find_or_make (name);
14812       S_SET_EXTERNAL (symbolP);
14813
14814       *input_line_pointer = c;
14815       SKIP_WHITESPACE ();
14816
14817       /* On Irix 5, every global symbol that is not explicitly labelled as
14818          being a function is apparently labelled as being an object.  */
14819       flag = BSF_OBJECT;
14820
14821       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14822           && (*input_line_pointer != ','))
14823         {
14824           char *secname;
14825           asection *sec;
14826
14827           secname = input_line_pointer;
14828           c = get_symbol_end ();
14829           sec = bfd_get_section_by_name (stdoutput, secname);
14830           if (sec == NULL)
14831             as_bad (_("%s: no such section"), secname);
14832           *input_line_pointer = c;
14833
14834           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14835             flag = BSF_FUNCTION;
14836         }
14837
14838       symbol_get_bfdsym (symbolP)->flags |= flag;
14839
14840       c = *input_line_pointer;
14841       if (c == ',')
14842         {
14843           input_line_pointer++;
14844           SKIP_WHITESPACE ();
14845           if (is_end_of_line[(unsigned char) *input_line_pointer])
14846             c = '\n';
14847         }
14848     }
14849   while (c == ',');
14850
14851   demand_empty_rest_of_line ();
14852 }
14853
14854 static void
14855 s_option (int x ATTRIBUTE_UNUSED)
14856 {
14857   char *opt;
14858   char c;
14859
14860   opt = input_line_pointer;
14861   c = get_symbol_end ();
14862
14863   if (*opt == 'O')
14864     {
14865       /* FIXME: What does this mean?  */
14866     }
14867   else if (strncmp (opt, "pic", 3) == 0)
14868     {
14869       int i;
14870
14871       i = atoi (opt + 3);
14872       if (i == 0)
14873         mips_pic = NO_PIC;
14874       else if (i == 2)
14875         {
14876           mips_pic = SVR4_PIC;
14877           mips_abicalls = TRUE;
14878         }
14879       else
14880         as_bad (_(".option pic%d not supported"), i);
14881
14882       if (mips_pic == SVR4_PIC)
14883         {
14884           if (g_switch_seen && g_switch_value != 0)
14885             as_warn (_("-G may not be used with SVR4 PIC code"));
14886           g_switch_value = 0;
14887           bfd_set_gp_size (stdoutput, 0);
14888         }
14889     }
14890   else
14891     as_warn (_("unrecognized option \"%s\""), opt);
14892
14893   *input_line_pointer = c;
14894   demand_empty_rest_of_line ();
14895 }
14896
14897 /* This structure is used to hold a stack of .set values.  */
14898
14899 struct mips_option_stack
14900 {
14901   struct mips_option_stack *next;
14902   struct mips_set_options options;
14903 };
14904
14905 static struct mips_option_stack *mips_opts_stack;
14906
14907 /* Handle the .set pseudo-op.  */
14908
14909 static void
14910 s_mipsset (int x ATTRIBUTE_UNUSED)
14911 {
14912   char *name = input_line_pointer, ch;
14913   const struct mips_ase *ase;
14914
14915   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14916     ++input_line_pointer;
14917   ch = *input_line_pointer;
14918   *input_line_pointer = '\0';
14919
14920   if (strcmp (name, "reorder") == 0)
14921     {
14922       if (mips_opts.noreorder)
14923         end_noreorder ();
14924     }
14925   else if (strcmp (name, "noreorder") == 0)
14926     {
14927       if (!mips_opts.noreorder)
14928         start_noreorder ();
14929     }
14930   else if (strncmp (name, "at=", 3) == 0)
14931     {
14932       char *s = name + 3;
14933
14934       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14935         as_bad (_("unrecognized register name `%s'"), s);
14936     }
14937   else if (strcmp (name, "at") == 0)
14938     {
14939       mips_opts.at = ATREG;
14940     }
14941   else if (strcmp (name, "noat") == 0)
14942     {
14943       mips_opts.at = ZERO;
14944     }
14945   else if (strcmp (name, "macro") == 0)
14946     {
14947       mips_opts.warn_about_macros = 0;
14948     }
14949   else if (strcmp (name, "nomacro") == 0)
14950     {
14951       if (mips_opts.noreorder == 0)
14952         as_bad (_("`noreorder' must be set before `nomacro'"));
14953       mips_opts.warn_about_macros = 1;
14954     }
14955   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14956     {
14957       mips_opts.nomove = 0;
14958     }
14959   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14960     {
14961       mips_opts.nomove = 1;
14962     }
14963   else if (strcmp (name, "bopt") == 0)
14964     {
14965       mips_opts.nobopt = 0;
14966     }
14967   else if (strcmp (name, "nobopt") == 0)
14968     {
14969       mips_opts.nobopt = 1;
14970     }
14971   else if (strcmp (name, "gp=default") == 0)
14972     mips_opts.gp32 = file_mips_gp32;
14973   else if (strcmp (name, "gp=32") == 0)
14974     mips_opts.gp32 = 1;
14975   else if (strcmp (name, "gp=64") == 0)
14976     {
14977       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14978         as_warn (_("%s isa does not support 64-bit registers"),
14979                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14980       mips_opts.gp32 = 0;
14981     }
14982   else if (strcmp (name, "fp=default") == 0)
14983     mips_opts.fp32 = file_mips_fp32;
14984   else if (strcmp (name, "fp=32") == 0)
14985     mips_opts.fp32 = 1;
14986   else if (strcmp (name, "fp=64") == 0)
14987     {
14988       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14989         as_warn (_("%s isa does not support 64-bit floating point registers"),
14990                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14991       mips_opts.fp32 = 0;
14992     }
14993   else if (strcmp (name, "softfloat") == 0)
14994     mips_opts.soft_float = 1;
14995   else if (strcmp (name, "hardfloat") == 0)
14996     mips_opts.soft_float = 0;
14997   else if (strcmp (name, "singlefloat") == 0)
14998     mips_opts.single_float = 1;
14999   else if (strcmp (name, "doublefloat") == 0)
15000     mips_opts.single_float = 0;
15001   else if (strcmp (name, "mips16") == 0
15002            || strcmp (name, "MIPS-16") == 0)
15003     {
15004       if (mips_opts.micromips == 1)
15005         as_fatal (_("`mips16' cannot be used with `micromips'"));
15006       mips_opts.mips16 = 1;
15007     }
15008   else if (strcmp (name, "nomips16") == 0
15009            || strcmp (name, "noMIPS-16") == 0)
15010     mips_opts.mips16 = 0;
15011   else if (strcmp (name, "micromips") == 0)
15012     {
15013       if (mips_opts.mips16 == 1)
15014         as_fatal (_("`micromips' cannot be used with `mips16'"));
15015       mips_opts.micromips = 1;
15016     }
15017   else if (strcmp (name, "nomicromips") == 0)
15018     mips_opts.micromips = 0;
15019   else if (name[0] == 'n'
15020            && name[1] == 'o'
15021            && (ase = mips_lookup_ase (name + 2)))
15022     mips_set_ase (ase, FALSE);
15023   else if ((ase = mips_lookup_ase (name)))
15024     mips_set_ase (ase, TRUE);
15025   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15026     {
15027       int reset = 0;
15028
15029       /* Permit the user to change the ISA and architecture on the fly.
15030          Needless to say, misuse can cause serious problems.  */
15031       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15032         {
15033           reset = 1;
15034           mips_opts.isa = file_mips_isa;
15035           mips_opts.arch = file_mips_arch;
15036         }
15037       else if (strncmp (name, "arch=", 5) == 0)
15038         {
15039           const struct mips_cpu_info *p;
15040
15041           p = mips_parse_cpu("internal use", name + 5);
15042           if (!p)
15043             as_bad (_("unknown architecture %s"), name + 5);
15044           else
15045             {
15046               mips_opts.arch = p->cpu;
15047               mips_opts.isa = p->isa;
15048             }
15049         }
15050       else if (strncmp (name, "mips", 4) == 0)
15051         {
15052           const struct mips_cpu_info *p;
15053
15054           p = mips_parse_cpu("internal use", name);
15055           if (!p)
15056             as_bad (_("unknown ISA level %s"), name + 4);
15057           else
15058             {
15059               mips_opts.arch = p->cpu;
15060               mips_opts.isa = p->isa;
15061             }
15062         }
15063       else
15064         as_bad (_("unknown ISA or architecture %s"), name);
15065
15066       switch (mips_opts.isa)
15067         {
15068         case  0:
15069           break;
15070         case ISA_MIPS1:
15071         case ISA_MIPS2:
15072         case ISA_MIPS32:
15073         case ISA_MIPS32R2:
15074           mips_opts.gp32 = 1;
15075           mips_opts.fp32 = 1;
15076           break;
15077         case ISA_MIPS3:
15078         case ISA_MIPS4:
15079         case ISA_MIPS5:
15080         case ISA_MIPS64:
15081         case ISA_MIPS64R2:
15082           mips_opts.gp32 = 0;
15083           if (mips_opts.arch == CPU_R5900)
15084             {
15085                 mips_opts.fp32 = 1;
15086             }
15087           else
15088             {
15089           mips_opts.fp32 = 0;
15090             }
15091           break;
15092         default:
15093           as_bad (_("unknown ISA level %s"), name + 4);
15094           break;
15095         }
15096       if (reset)
15097         {
15098           mips_opts.gp32 = file_mips_gp32;
15099           mips_opts.fp32 = file_mips_fp32;
15100         }
15101     }
15102   else if (strcmp (name, "autoextend") == 0)
15103     mips_opts.noautoextend = 0;
15104   else if (strcmp (name, "noautoextend") == 0)
15105     mips_opts.noautoextend = 1;
15106   else if (strcmp (name, "insn32") == 0)
15107     mips_opts.insn32 = TRUE;
15108   else if (strcmp (name, "noinsn32") == 0)
15109     mips_opts.insn32 = FALSE;
15110   else if (strcmp (name, "push") == 0)
15111     {
15112       struct mips_option_stack *s;
15113
15114       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15115       s->next = mips_opts_stack;
15116       s->options = mips_opts;
15117       mips_opts_stack = s;
15118     }
15119   else if (strcmp (name, "pop") == 0)
15120     {
15121       struct mips_option_stack *s;
15122
15123       s = mips_opts_stack;
15124       if (s == NULL)
15125         as_bad (_(".set pop with no .set push"));
15126       else
15127         {
15128           /* If we're changing the reorder mode we need to handle
15129              delay slots correctly.  */
15130           if (s->options.noreorder && ! mips_opts.noreorder)
15131             start_noreorder ();
15132           else if (! s->options.noreorder && mips_opts.noreorder)
15133             end_noreorder ();
15134
15135           mips_opts = s->options;
15136           mips_opts_stack = s->next;
15137           free (s);
15138         }
15139     }
15140   else if (strcmp (name, "sym32") == 0)
15141     mips_opts.sym32 = TRUE;
15142   else if (strcmp (name, "nosym32") == 0)
15143     mips_opts.sym32 = FALSE;
15144   else if (strchr (name, ','))
15145     {
15146       /* Generic ".set" directive; use the generic handler.  */
15147       *input_line_pointer = ch;
15148       input_line_pointer = name;
15149       s_set (0);
15150       return;
15151     }
15152   else
15153     {
15154       as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15155     }
15156   mips_check_isa_supports_ases ();
15157   *input_line_pointer = ch;
15158   demand_empty_rest_of_line ();
15159 }
15160
15161 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15162    .option pic2.  It means to generate SVR4 PIC calls.  */
15163
15164 static void
15165 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15166 {
15167   mips_pic = SVR4_PIC;
15168   mips_abicalls = TRUE;
15169
15170   if (g_switch_seen && g_switch_value != 0)
15171     as_warn (_("-G may not be used with SVR4 PIC code"));
15172   g_switch_value = 0;
15173
15174   bfd_set_gp_size (stdoutput, 0);
15175   demand_empty_rest_of_line ();
15176 }
15177
15178 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15179    PIC code.  It sets the $gp register for the function based on the
15180    function address, which is in the register named in the argument.
15181    This uses a relocation against _gp_disp, which is handled specially
15182    by the linker.  The result is:
15183         lui     $gp,%hi(_gp_disp)
15184         addiu   $gp,$gp,%lo(_gp_disp)
15185         addu    $gp,$gp,.cpload argument
15186    The .cpload argument is normally $25 == $t9.
15187
15188    The -mno-shared option changes this to:
15189         lui     $gp,%hi(__gnu_local_gp)
15190         addiu   $gp,$gp,%lo(__gnu_local_gp)
15191    and the argument is ignored.  This saves an instruction, but the
15192    resulting code is not position independent; it uses an absolute
15193    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15194    can go into an ordinary executable, but not into a shared library.  */
15195
15196 static void
15197 s_cpload (int ignore ATTRIBUTE_UNUSED)
15198 {
15199   expressionS ex;
15200   int reg;
15201   int in_shared;
15202
15203   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15204      .cpload is ignored.  */
15205   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15206     {
15207       s_ignore (0);
15208       return;
15209     }
15210
15211   if (mips_opts.mips16)
15212     {
15213       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15214       ignore_rest_of_line ();
15215       return;
15216     }
15217
15218   /* .cpload should be in a .set noreorder section.  */
15219   if (mips_opts.noreorder == 0)
15220     as_warn (_(".cpload not in noreorder section"));
15221
15222   reg = tc_get_register (0);
15223
15224   /* If we need to produce a 64-bit address, we are better off using
15225      the default instruction sequence.  */
15226   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15227
15228   ex.X_op = O_symbol;
15229   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15230                                          "__gnu_local_gp");
15231   ex.X_op_symbol = NULL;
15232   ex.X_add_number = 0;
15233
15234   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15235   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15236
15237   mips_mark_labels ();
15238   mips_assembling_insn = TRUE;
15239
15240   macro_start ();
15241   macro_build_lui (&ex, mips_gp_register);
15242   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15243                mips_gp_register, BFD_RELOC_LO16);
15244   if (in_shared)
15245     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15246                  mips_gp_register, reg);
15247   macro_end ();
15248
15249   mips_assembling_insn = FALSE;
15250   demand_empty_rest_of_line ();
15251 }
15252
15253 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15254      .cpsetup $reg1, offset|$reg2, label
15255
15256    If offset is given, this results in:
15257      sd         $gp, offset($sp)
15258      lui        $gp, %hi(%neg(%gp_rel(label)))
15259      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15260      daddu      $gp, $gp, $reg1
15261
15262    If $reg2 is given, this results in:
15263      daddu      $reg2, $gp, $0
15264      lui        $gp, %hi(%neg(%gp_rel(label)))
15265      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15266      daddu      $gp, $gp, $reg1
15267    $reg1 is normally $25 == $t9.
15268
15269    The -mno-shared option replaces the last three instructions with
15270         lui     $gp,%hi(_gp)
15271         addiu   $gp,$gp,%lo(_gp)  */
15272
15273 static void
15274 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15275 {
15276   expressionS ex_off;
15277   expressionS ex_sym;
15278   int reg1;
15279
15280   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15281      We also need NewABI support.  */
15282   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15283     {
15284       s_ignore (0);
15285       return;
15286     }
15287
15288   if (mips_opts.mips16)
15289     {
15290       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15291       ignore_rest_of_line ();
15292       return;
15293     }
15294
15295   reg1 = tc_get_register (0);
15296   SKIP_WHITESPACE ();
15297   if (*input_line_pointer != ',')
15298     {
15299       as_bad (_("missing argument separator ',' for .cpsetup"));
15300       return;
15301     }
15302   else
15303     ++input_line_pointer;
15304   SKIP_WHITESPACE ();
15305   if (*input_line_pointer == '$')
15306     {
15307       mips_cpreturn_register = tc_get_register (0);
15308       mips_cpreturn_offset = -1;
15309     }
15310   else
15311     {
15312       mips_cpreturn_offset = get_absolute_expression ();
15313       mips_cpreturn_register = -1;
15314     }
15315   SKIP_WHITESPACE ();
15316   if (*input_line_pointer != ',')
15317     {
15318       as_bad (_("missing argument separator ',' for .cpsetup"));
15319       return;
15320     }
15321   else
15322     ++input_line_pointer;
15323   SKIP_WHITESPACE ();
15324   expression (&ex_sym);
15325
15326   mips_mark_labels ();
15327   mips_assembling_insn = TRUE;
15328
15329   macro_start ();
15330   if (mips_cpreturn_register == -1)
15331     {
15332       ex_off.X_op = O_constant;
15333       ex_off.X_add_symbol = NULL;
15334       ex_off.X_op_symbol = NULL;
15335       ex_off.X_add_number = mips_cpreturn_offset;
15336
15337       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15338                    BFD_RELOC_LO16, SP);
15339     }
15340   else
15341     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15342                  mips_gp_register, 0);
15343
15344   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15345     {
15346       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15347                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15348                    BFD_RELOC_HI16_S);
15349
15350       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15351                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15352                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15353
15354       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15355                    mips_gp_register, reg1);
15356     }
15357   else
15358     {
15359       expressionS ex;
15360
15361       ex.X_op = O_symbol;
15362       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15363       ex.X_op_symbol = NULL;
15364       ex.X_add_number = 0;
15365
15366       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15367       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15368
15369       macro_build_lui (&ex, mips_gp_register);
15370       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15371                    mips_gp_register, BFD_RELOC_LO16);
15372     }
15373
15374   macro_end ();
15375
15376   mips_assembling_insn = FALSE;
15377   demand_empty_rest_of_line ();
15378 }
15379
15380 static void
15381 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15382 {
15383   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15384      .cplocal is ignored.  */
15385   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15386     {
15387       s_ignore (0);
15388       return;
15389     }
15390
15391   if (mips_opts.mips16)
15392     {
15393       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15394       ignore_rest_of_line ();
15395       return;
15396     }
15397
15398   mips_gp_register = tc_get_register (0);
15399   demand_empty_rest_of_line ();
15400 }
15401
15402 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15403    offset from $sp.  The offset is remembered, and after making a PIC
15404    call $gp is restored from that location.  */
15405
15406 static void
15407 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15408 {
15409   expressionS ex;
15410
15411   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15412      .cprestore is ignored.  */
15413   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15414     {
15415       s_ignore (0);
15416       return;
15417     }
15418
15419   if (mips_opts.mips16)
15420     {
15421       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15422       ignore_rest_of_line ();
15423       return;
15424     }
15425
15426   mips_cprestore_offset = get_absolute_expression ();
15427   mips_cprestore_valid = 1;
15428
15429   ex.X_op = O_constant;
15430   ex.X_add_symbol = NULL;
15431   ex.X_op_symbol = NULL;
15432   ex.X_add_number = mips_cprestore_offset;
15433
15434   mips_mark_labels ();
15435   mips_assembling_insn = TRUE;
15436
15437   macro_start ();
15438   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15439                                 SP, HAVE_64BIT_ADDRESSES);
15440   macro_end ();
15441
15442   mips_assembling_insn = FALSE;
15443   demand_empty_rest_of_line ();
15444 }
15445
15446 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15447    was given in the preceding .cpsetup, it results in:
15448      ld         $gp, offset($sp)
15449
15450    If a register $reg2 was given there, it results in:
15451      daddu      $gp, $reg2, $0  */
15452
15453 static void
15454 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15455 {
15456   expressionS ex;
15457
15458   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15459      We also need NewABI support.  */
15460   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15461     {
15462       s_ignore (0);
15463       return;
15464     }
15465
15466   if (mips_opts.mips16)
15467     {
15468       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15469       ignore_rest_of_line ();
15470       return;
15471     }
15472
15473   mips_mark_labels ();
15474   mips_assembling_insn = TRUE;
15475
15476   macro_start ();
15477   if (mips_cpreturn_register == -1)
15478     {
15479       ex.X_op = O_constant;
15480       ex.X_add_symbol = NULL;
15481       ex.X_op_symbol = NULL;
15482       ex.X_add_number = mips_cpreturn_offset;
15483
15484       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15485     }
15486   else
15487     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15488                  mips_cpreturn_register, 0);
15489   macro_end ();
15490
15491   mips_assembling_insn = FALSE;
15492   demand_empty_rest_of_line ();
15493 }
15494
15495 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15496    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15497    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15498    debug information or MIPS16 TLS.  */
15499
15500 static void
15501 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15502                      bfd_reloc_code_real_type rtype)
15503 {
15504   expressionS ex;
15505   char *p;
15506
15507   expression (&ex);
15508
15509   if (ex.X_op != O_symbol)
15510     {
15511       as_bad (_("unsupported use of %s"), dirstr);
15512       ignore_rest_of_line ();
15513     }
15514
15515   p = frag_more (bytes);
15516   md_number_to_chars (p, 0, bytes);
15517   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15518   demand_empty_rest_of_line ();
15519   mips_clear_insn_labels ();
15520 }
15521
15522 /* Handle .dtprelword.  */
15523
15524 static void
15525 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15526 {
15527   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15528 }
15529
15530 /* Handle .dtpreldword.  */
15531
15532 static void
15533 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15534 {
15535   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15536 }
15537
15538 /* Handle .tprelword.  */
15539
15540 static void
15541 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15542 {
15543   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15544 }
15545
15546 /* Handle .tpreldword.  */
15547
15548 static void
15549 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15550 {
15551   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15552 }
15553
15554 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15555    code.  It sets the offset to use in gp_rel relocations.  */
15556
15557 static void
15558 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15559 {
15560   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15561      We also need NewABI support.  */
15562   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15563     {
15564       s_ignore (0);
15565       return;
15566     }
15567
15568   mips_gprel_offset = get_absolute_expression ();
15569
15570   demand_empty_rest_of_line ();
15571 }
15572
15573 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15574    code.  It generates a 32 bit GP relative reloc.  */
15575
15576 static void
15577 s_gpword (int ignore ATTRIBUTE_UNUSED)
15578 {
15579   segment_info_type *si;
15580   struct insn_label_list *l;
15581   expressionS ex;
15582   char *p;
15583
15584   /* When not generating PIC code, this is treated as .word.  */
15585   if (mips_pic != SVR4_PIC)
15586     {
15587       s_cons (2);
15588       return;
15589     }
15590
15591   si = seg_info (now_seg);
15592   l = si->label_list;
15593   mips_emit_delays ();
15594   if (auto_align)
15595     mips_align (2, 0, l);
15596
15597   expression (&ex);
15598   mips_clear_insn_labels ();
15599
15600   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15601     {
15602       as_bad (_("unsupported use of .gpword"));
15603       ignore_rest_of_line ();
15604     }
15605
15606   p = frag_more (4);
15607   md_number_to_chars (p, 0, 4);
15608   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15609                BFD_RELOC_GPREL32);
15610
15611   demand_empty_rest_of_line ();
15612 }
15613
15614 static void
15615 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15616 {
15617   segment_info_type *si;
15618   struct insn_label_list *l;
15619   expressionS ex;
15620   char *p;
15621
15622   /* When not generating PIC code, this is treated as .dword.  */
15623   if (mips_pic != SVR4_PIC)
15624     {
15625       s_cons (3);
15626       return;
15627     }
15628
15629   si = seg_info (now_seg);
15630   l = si->label_list;
15631   mips_emit_delays ();
15632   if (auto_align)
15633     mips_align (3, 0, l);
15634
15635   expression (&ex);
15636   mips_clear_insn_labels ();
15637
15638   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15639     {
15640       as_bad (_("unsupported use of .gpdword"));
15641       ignore_rest_of_line ();
15642     }
15643
15644   p = frag_more (8);
15645   md_number_to_chars (p, 0, 8);
15646   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15647                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15648
15649   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15650   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15651            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15652
15653   demand_empty_rest_of_line ();
15654 }
15655
15656 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15657    tables.  It generates a R_MIPS_EH reloc.  */
15658
15659 static void
15660 s_ehword (int ignore ATTRIBUTE_UNUSED)
15661 {
15662   expressionS ex;
15663   char *p;
15664
15665   mips_emit_delays ();
15666
15667   expression (&ex);
15668   mips_clear_insn_labels ();
15669
15670   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15671     {
15672       as_bad (_("unsupported use of .ehword"));
15673       ignore_rest_of_line ();
15674     }
15675
15676   p = frag_more (4);
15677   md_number_to_chars (p, 0, 4);
15678   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15679                BFD_RELOC_MIPS_EH);
15680
15681   demand_empty_rest_of_line ();
15682 }
15683
15684 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15685    tables in SVR4 PIC code.  */
15686
15687 static void
15688 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15689 {
15690   int reg;
15691
15692   /* This is ignored when not generating SVR4 PIC code.  */
15693   if (mips_pic != SVR4_PIC)
15694     {
15695       s_ignore (0);
15696       return;
15697     }
15698
15699   mips_mark_labels ();
15700   mips_assembling_insn = TRUE;
15701
15702   /* Add $gp to the register named as an argument.  */
15703   macro_start ();
15704   reg = tc_get_register (0);
15705   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15706   macro_end ();
15707
15708   mips_assembling_insn = FALSE;
15709   demand_empty_rest_of_line ();
15710 }
15711
15712 /* Handle the .insn pseudo-op.  This marks instruction labels in
15713    mips16/micromips mode.  This permits the linker to handle them specially,
15714    such as generating jalx instructions when needed.  We also make
15715    them odd for the duration of the assembly, in order to generate the
15716    right sort of code.  We will make them even in the adjust_symtab
15717    routine, while leaving them marked.  This is convenient for the
15718    debugger and the disassembler.  The linker knows to make them odd
15719    again.  */
15720
15721 static void
15722 s_insn (int ignore ATTRIBUTE_UNUSED)
15723 {
15724   mips_mark_labels ();
15725
15726   demand_empty_rest_of_line ();
15727 }
15728
15729 /* Handle the .nan pseudo-op.  */
15730
15731 static void
15732 s_nan (int ignore ATTRIBUTE_UNUSED)
15733 {
15734   static const char str_legacy[] = "legacy";
15735   static const char str_2008[] = "2008";
15736   size_t i;
15737
15738   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15739
15740   if (i == sizeof (str_2008) - 1
15741       && memcmp (input_line_pointer, str_2008, i) == 0)
15742     mips_flag_nan2008 = TRUE;
15743   else if (i == sizeof (str_legacy) - 1
15744            && memcmp (input_line_pointer, str_legacy, i) == 0)
15745     mips_flag_nan2008 = FALSE;
15746   else
15747     as_bad (_("bad .nan directive"));
15748
15749   input_line_pointer += i;
15750   demand_empty_rest_of_line ();
15751 }
15752
15753 /* Handle a .stab[snd] directive.  Ideally these directives would be
15754    implemented in a transparent way, so that removing them would not
15755    have any effect on the generated instructions.  However, s_stab
15756    internally changes the section, so in practice we need to decide
15757    now whether the preceding label marks compressed code.  We do not
15758    support changing the compression mode of a label after a .stab*
15759    directive, such as in:
15760
15761    foo:
15762         .stabs ...
15763         .set mips16
15764
15765    so the current mode wins.  */
15766
15767 static void
15768 s_mips_stab (int type)
15769 {
15770   mips_mark_labels ();
15771   s_stab (type);
15772 }
15773
15774 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15775
15776 static void
15777 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15778 {
15779   char *name;
15780   int c;
15781   symbolS *symbolP;
15782   expressionS exp;
15783
15784   name = input_line_pointer;
15785   c = get_symbol_end ();
15786   symbolP = symbol_find_or_make (name);
15787   S_SET_WEAK (symbolP);
15788   *input_line_pointer = c;
15789
15790   SKIP_WHITESPACE ();
15791
15792   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15793     {
15794       if (S_IS_DEFINED (symbolP))
15795         {
15796           as_bad (_("ignoring attempt to redefine symbol %s"),
15797                   S_GET_NAME (symbolP));
15798           ignore_rest_of_line ();
15799           return;
15800         }
15801
15802       if (*input_line_pointer == ',')
15803         {
15804           ++input_line_pointer;
15805           SKIP_WHITESPACE ();
15806         }
15807
15808       expression (&exp);
15809       if (exp.X_op != O_symbol)
15810         {
15811           as_bad (_("bad .weakext directive"));
15812           ignore_rest_of_line ();
15813           return;
15814         }
15815       symbol_set_value_expression (symbolP, &exp);
15816     }
15817
15818   demand_empty_rest_of_line ();
15819 }
15820
15821 /* Parse a register string into a number.  Called from the ECOFF code
15822    to parse .frame.  The argument is non-zero if this is the frame
15823    register, so that we can record it in mips_frame_reg.  */
15824
15825 int
15826 tc_get_register (int frame)
15827 {
15828   unsigned int reg;
15829
15830   SKIP_WHITESPACE ();
15831   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15832     reg = 0;
15833   if (frame)
15834     {
15835       mips_frame_reg = reg != 0 ? reg : SP;
15836       mips_frame_reg_valid = 1;
15837       mips_cprestore_valid = 0;
15838     }
15839   return reg;
15840 }
15841
15842 valueT
15843 md_section_align (asection *seg, valueT addr)
15844 {
15845   int align = bfd_get_section_alignment (stdoutput, seg);
15846
15847   /* We don't need to align ELF sections to the full alignment.
15848      However, Irix 5 may prefer that we align them at least to a 16
15849      byte boundary.  We don't bother to align the sections if we
15850      are targeted for an embedded system.  */
15851   if (strncmp (TARGET_OS, "elf", 3) == 0)
15852     return addr;
15853   if (align > 4)
15854     align = 4;
15855
15856   return ((addr + (1 << align) - 1) & (-1 << align));
15857 }
15858
15859 /* Utility routine, called from above as well.  If called while the
15860    input file is still being read, it's only an approximation.  (For
15861    example, a symbol may later become defined which appeared to be
15862    undefined earlier.)  */
15863
15864 static int
15865 nopic_need_relax (symbolS *sym, int before_relaxing)
15866 {
15867   if (sym == 0)
15868     return 0;
15869
15870   if (g_switch_value > 0)
15871     {
15872       const char *symname;
15873       int change;
15874
15875       /* Find out whether this symbol can be referenced off the $gp
15876          register.  It can be if it is smaller than the -G size or if
15877          it is in the .sdata or .sbss section.  Certain symbols can
15878          not be referenced off the $gp, although it appears as though
15879          they can.  */
15880       symname = S_GET_NAME (sym);
15881       if (symname != (const char *) NULL
15882           && (strcmp (symname, "eprol") == 0
15883               || strcmp (symname, "etext") == 0
15884               || strcmp (symname, "_gp") == 0
15885               || strcmp (symname, "edata") == 0
15886               || strcmp (symname, "_fbss") == 0
15887               || strcmp (symname, "_fdata") == 0
15888               || strcmp (symname, "_ftext") == 0
15889               || strcmp (symname, "end") == 0
15890               || strcmp (symname, "_gp_disp") == 0))
15891         change = 1;
15892       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15893                && (0
15894 #ifndef NO_ECOFF_DEBUGGING
15895                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15896                        && (symbol_get_obj (sym)->ecoff_extern_size
15897                            <= g_switch_value))
15898 #endif
15899                    /* We must defer this decision until after the whole
15900                       file has been read, since there might be a .extern
15901                       after the first use of this symbol.  */
15902                    || (before_relaxing
15903 #ifndef NO_ECOFF_DEBUGGING
15904                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15905 #endif
15906                        && S_GET_VALUE (sym) == 0)
15907                    || (S_GET_VALUE (sym) != 0
15908                        && S_GET_VALUE (sym) <= g_switch_value)))
15909         change = 0;
15910       else
15911         {
15912           const char *segname;
15913
15914           segname = segment_name (S_GET_SEGMENT (sym));
15915           gas_assert (strcmp (segname, ".lit8") != 0
15916                   && strcmp (segname, ".lit4") != 0);
15917           change = (strcmp (segname, ".sdata") != 0
15918                     && strcmp (segname, ".sbss") != 0
15919                     && strncmp (segname, ".sdata.", 7) != 0
15920                     && strncmp (segname, ".sbss.", 6) != 0
15921                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15922                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15923         }
15924       return change;
15925     }
15926   else
15927     /* We are not optimizing for the $gp register.  */
15928     return 1;
15929 }
15930
15931
15932 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15933
15934 static bfd_boolean
15935 pic_need_relax (symbolS *sym, asection *segtype)
15936 {
15937   asection *symsec;
15938
15939   /* Handle the case of a symbol equated to another symbol.  */
15940   while (symbol_equated_reloc_p (sym))
15941     {
15942       symbolS *n;
15943
15944       /* It's possible to get a loop here in a badly written program.  */
15945       n = symbol_get_value_expression (sym)->X_add_symbol;
15946       if (n == sym)
15947         break;
15948       sym = n;
15949     }
15950
15951   if (symbol_section_p (sym))
15952     return TRUE;
15953
15954   symsec = S_GET_SEGMENT (sym);
15955
15956   /* This must duplicate the test in adjust_reloc_syms.  */
15957   return (!bfd_is_und_section (symsec)
15958           && !bfd_is_abs_section (symsec)
15959           && !bfd_is_com_section (symsec)
15960           && !s_is_linkonce (sym, segtype)
15961           /* A global or weak symbol is treated as external.  */
15962           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15963 }
15964
15965
15966 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15967    extended opcode.  SEC is the section the frag is in.  */
15968
15969 static int
15970 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15971 {
15972   int type;
15973   const struct mips_int_operand *operand;
15974   offsetT val;
15975   segT symsec;
15976   fragS *sym_frag;
15977
15978   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15979     return 0;
15980   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15981     return 1;
15982
15983   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15984   operand = mips16_immed_operand (type, FALSE);
15985
15986   sym_frag = symbol_get_frag (fragp->fr_symbol);
15987   val = S_GET_VALUE (fragp->fr_symbol);
15988   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15989
15990   if (operand->root.type == OP_PCREL)
15991     {
15992       const struct mips_pcrel_operand *pcrel_op;
15993       addressT addr;
15994       offsetT maxtiny;
15995
15996       /* We won't have the section when we are called from
15997          mips_relax_frag.  However, we will always have been called
15998          from md_estimate_size_before_relax first.  If this is a
15999          branch to a different section, we mark it as such.  If SEC is
16000          NULL, and the frag is not marked, then it must be a branch to
16001          the same section.  */
16002       pcrel_op = (const struct mips_pcrel_operand *) operand;
16003       if (sec == NULL)
16004         {
16005           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16006             return 1;
16007         }
16008       else
16009         {
16010           /* Must have been called from md_estimate_size_before_relax.  */
16011           if (symsec != sec)
16012             {
16013               fragp->fr_subtype =
16014                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16015
16016               /* FIXME: We should support this, and let the linker
16017                  catch branches and loads that are out of range.  */
16018               as_bad_where (fragp->fr_file, fragp->fr_line,
16019                             _("unsupported PC relative reference to different section"));
16020
16021               return 1;
16022             }
16023           if (fragp != sym_frag && sym_frag->fr_address == 0)
16024             /* Assume non-extended on the first relaxation pass.
16025                The address we have calculated will be bogus if this is
16026                a forward branch to another frag, as the forward frag
16027                will have fr_address == 0.  */
16028             return 0;
16029         }
16030
16031       /* In this case, we know for sure that the symbol fragment is in
16032          the same section.  If the relax_marker of the symbol fragment
16033          differs from the relax_marker of this fragment, we have not
16034          yet adjusted the symbol fragment fr_address.  We want to add
16035          in STRETCH in order to get a better estimate of the address.
16036          This particularly matters because of the shift bits.  */
16037       if (stretch != 0
16038           && sym_frag->relax_marker != fragp->relax_marker)
16039         {
16040           fragS *f;
16041
16042           /* Adjust stretch for any alignment frag.  Note that if have
16043              been expanding the earlier code, the symbol may be
16044              defined in what appears to be an earlier frag.  FIXME:
16045              This doesn't handle the fr_subtype field, which specifies
16046              a maximum number of bytes to skip when doing an
16047              alignment.  */
16048           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16049             {
16050               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16051                 {
16052                   if (stretch < 0)
16053                     stretch = - ((- stretch)
16054                                  & ~ ((1 << (int) f->fr_offset) - 1));
16055                   else
16056                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16057                   if (stretch == 0)
16058                     break;
16059                 }
16060             }
16061           if (f != NULL)
16062             val += stretch;
16063         }
16064
16065       addr = fragp->fr_address + fragp->fr_fix;
16066
16067       /* The base address rules are complicated.  The base address of
16068          a branch is the following instruction.  The base address of a
16069          PC relative load or add is the instruction itself, but if it
16070          is in a delay slot (in which case it can not be extended) use
16071          the address of the instruction whose delay slot it is in.  */
16072       if (pcrel_op->include_isa_bit)
16073         {
16074           addr += 2;
16075
16076           /* If we are currently assuming that this frag should be
16077              extended, then, the current address is two bytes
16078              higher.  */
16079           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16080             addr += 2;
16081
16082           /* Ignore the low bit in the target, since it will be set
16083              for a text label.  */
16084           val &= -2;
16085         }
16086       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16087         addr -= 4;
16088       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16089         addr -= 2;
16090
16091       val -= addr & -(1 << pcrel_op->align_log2);
16092
16093       /* If any of the shifted bits are set, we must use an extended
16094          opcode.  If the address depends on the size of this
16095          instruction, this can lead to a loop, so we arrange to always
16096          use an extended opcode.  We only check this when we are in
16097          the main relaxation loop, when SEC is NULL.  */
16098       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16099         {
16100           fragp->fr_subtype =
16101             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16102           return 1;
16103         }
16104
16105       /* If we are about to mark a frag as extended because the value
16106          is precisely the next value above maxtiny, then there is a
16107          chance of an infinite loop as in the following code:
16108              la $4,foo
16109              .skip      1020
16110              .align     2
16111            foo:
16112          In this case when the la is extended, foo is 0x3fc bytes
16113          away, so the la can be shrunk, but then foo is 0x400 away, so
16114          the la must be extended.  To avoid this loop, we mark the
16115          frag as extended if it was small, and is about to become
16116          extended with the next value above maxtiny.  */
16117       maxtiny = mips_int_operand_max (operand);
16118       if (val == maxtiny + (1 << operand->shift)
16119           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16120           && sec == NULL)
16121         {
16122           fragp->fr_subtype =
16123             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16124           return 1;
16125         }
16126     }
16127   else if (symsec != absolute_section && sec != NULL)
16128     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16129
16130   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16131 }
16132
16133 /* Compute the length of a branch sequence, and adjust the
16134    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16135    worst-case length is computed, with UPDATE being used to indicate
16136    whether an unconditional (-1), branch-likely (+1) or regular (0)
16137    branch is to be computed.  */
16138 static int
16139 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16140 {
16141   bfd_boolean toofar;
16142   int length;
16143
16144   if (fragp
16145       && S_IS_DEFINED (fragp->fr_symbol)
16146       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16147     {
16148       addressT addr;
16149       offsetT val;
16150
16151       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16152
16153       addr = fragp->fr_address + fragp->fr_fix + 4;
16154
16155       val -= addr;
16156
16157       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16158     }
16159   else if (fragp)
16160     /* If the symbol is not defined or it's in a different segment,
16161        assume the user knows what's going on and emit a short
16162        branch.  */
16163     toofar = FALSE;
16164   else
16165     toofar = TRUE;
16166
16167   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16168     fragp->fr_subtype
16169       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16170                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16171                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16172                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16173                              toofar);
16174
16175   length = 4;
16176   if (toofar)
16177     {
16178       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16179         length += 8;
16180
16181       if (mips_pic != NO_PIC)
16182         {
16183           /* Additional space for PIC loading of target address.  */
16184           length += 8;
16185           if (mips_opts.isa == ISA_MIPS1)
16186             /* Additional space for $at-stabilizing nop.  */
16187             length += 4;
16188         }
16189
16190       /* If branch is conditional.  */
16191       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16192         length += 8;
16193     }
16194
16195   return length;
16196 }
16197
16198 /* Compute the length of a branch sequence, and adjust the
16199    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16200    worst-case length is computed, with UPDATE being used to indicate
16201    whether an unconditional (-1), or regular (0) branch is to be
16202    computed.  */
16203
16204 static int
16205 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16206 {
16207   bfd_boolean toofar;
16208   int length;
16209
16210   if (fragp
16211       && S_IS_DEFINED (fragp->fr_symbol)
16212       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16213     {
16214       addressT addr;
16215       offsetT val;
16216
16217       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16218       /* Ignore the low bit in the target, since it will be set
16219          for a text label.  */
16220       if ((val & 1) != 0)
16221         --val;
16222
16223       addr = fragp->fr_address + fragp->fr_fix + 4;
16224
16225       val -= addr;
16226
16227       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16228     }
16229   else if (fragp)
16230     /* If the symbol is not defined or it's in a different segment,
16231        assume the user knows what's going on and emit a short
16232        branch.  */
16233     toofar = FALSE;
16234   else
16235     toofar = TRUE;
16236
16237   if (fragp && update
16238       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16239     fragp->fr_subtype = (toofar
16240                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16241                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16242
16243   length = 4;
16244   if (toofar)
16245     {
16246       bfd_boolean compact_known = fragp != NULL;
16247       bfd_boolean compact = FALSE;
16248       bfd_boolean uncond;
16249
16250       if (compact_known)
16251         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16252       if (fragp)
16253         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16254       else
16255         uncond = update < 0;
16256
16257       /* If label is out of range, we turn branch <br>:
16258
16259                 <br>    label                   # 4 bytes
16260             0:
16261
16262          into:
16263
16264                 j       label                   # 4 bytes
16265                 nop                             # 2 bytes if compact && !PIC
16266             0:
16267        */
16268       if (mips_pic == NO_PIC && (!compact_known || compact))
16269         length += 2;
16270
16271       /* If assembling PIC code, we further turn:
16272
16273                         j       label                   # 4 bytes
16274
16275          into:
16276
16277                         lw/ld   at, %got(label)(gp)     # 4 bytes
16278                         d/addiu at, %lo(label)          # 4 bytes
16279                         jr/c    at                      # 2 bytes
16280        */
16281       if (mips_pic != NO_PIC)
16282         length += 6;
16283
16284       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16285
16286                         <brneg> 0f                      # 4 bytes
16287                         nop                             # 2 bytes if !compact
16288        */
16289       if (!uncond)
16290         length += (compact_known && compact) ? 4 : 6;
16291     }
16292
16293   return length;
16294 }
16295
16296 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16297    bit accordingly.  */
16298
16299 static int
16300 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16301 {
16302   bfd_boolean toofar;
16303
16304   if (fragp
16305       && S_IS_DEFINED (fragp->fr_symbol)
16306       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16307     {
16308       addressT addr;
16309       offsetT val;
16310       int type;
16311
16312       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16313       /* Ignore the low bit in the target, since it will be set
16314          for a text label.  */
16315       if ((val & 1) != 0)
16316         --val;
16317
16318       /* Assume this is a 2-byte branch.  */
16319       addr = fragp->fr_address + fragp->fr_fix + 2;
16320
16321       /* We try to avoid the infinite loop by not adding 2 more bytes for
16322          long branches.  */
16323
16324       val -= addr;
16325
16326       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16327       if (type == 'D')
16328         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16329       else if (type == 'E')
16330         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16331       else
16332         abort ();
16333     }
16334   else
16335     /* If the symbol is not defined or it's in a different segment,
16336        we emit a normal 32-bit branch.  */
16337     toofar = TRUE;
16338
16339   if (fragp && update
16340       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16341     fragp->fr_subtype
16342       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16343                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16344
16345   if (toofar)
16346     return 4;
16347
16348   return 2;
16349 }
16350
16351 /* Estimate the size of a frag before relaxing.  Unless this is the
16352    mips16, we are not really relaxing here, and the final size is
16353    encoded in the subtype information.  For the mips16, we have to
16354    decide whether we are using an extended opcode or not.  */
16355
16356 int
16357 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16358 {
16359   int change;
16360
16361   if (RELAX_BRANCH_P (fragp->fr_subtype))
16362     {
16363
16364       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16365
16366       return fragp->fr_var;
16367     }
16368
16369   if (RELAX_MIPS16_P (fragp->fr_subtype))
16370     /* We don't want to modify the EXTENDED bit here; it might get us
16371        into infinite loops.  We change it only in mips_relax_frag().  */
16372     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16373
16374   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16375     {
16376       int length = 4;
16377
16378       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16379         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16380       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16381         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16382       fragp->fr_var = length;
16383
16384       return length;
16385     }
16386
16387   if (mips_pic == NO_PIC)
16388     change = nopic_need_relax (fragp->fr_symbol, 0);
16389   else if (mips_pic == SVR4_PIC)
16390     change = pic_need_relax (fragp->fr_symbol, segtype);
16391   else if (mips_pic == VXWORKS_PIC)
16392     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16393     change = 0;
16394   else
16395     abort ();
16396
16397   if (change)
16398     {
16399       fragp->fr_subtype |= RELAX_USE_SECOND;
16400       return -RELAX_FIRST (fragp->fr_subtype);
16401     }
16402   else
16403     return -RELAX_SECOND (fragp->fr_subtype);
16404 }
16405
16406 /* This is called to see whether a reloc against a defined symbol
16407    should be converted into a reloc against a section.  */
16408
16409 int
16410 mips_fix_adjustable (fixS *fixp)
16411 {
16412   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16413       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16414     return 0;
16415
16416   if (fixp->fx_addsy == NULL)
16417     return 1;
16418
16419   /* If symbol SYM is in a mergeable section, relocations of the form
16420      SYM + 0 can usually be made section-relative.  The mergeable data
16421      is then identified by the section offset rather than by the symbol.
16422
16423      However, if we're generating REL LO16 relocations, the offset is split
16424      between the LO16 and parterning high part relocation.  The linker will
16425      need to recalculate the complete offset in order to correctly identify
16426      the merge data.
16427
16428      The linker has traditionally not looked for the parterning high part
16429      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16430      placed anywhere.  Rather than break backwards compatibility by changing
16431      this, it seems better not to force the issue, and instead keep the
16432      original symbol.  This will work with either linker behavior.  */
16433   if ((lo16_reloc_p (fixp->fx_r_type)
16434        || reloc_needs_lo_p (fixp->fx_r_type))
16435       && HAVE_IN_PLACE_ADDENDS
16436       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16437     return 0;
16438
16439   /* There is no place to store an in-place offset for JALR relocations.
16440      Likewise an in-range offset of limited PC-relative relocations may
16441      overflow the in-place relocatable field if recalculated against the
16442      start address of the symbol's containing section.  */
16443   if (HAVE_IN_PLACE_ADDENDS
16444       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16445           || jalr_reloc_p (fixp->fx_r_type)))
16446     return 0;
16447
16448   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16449      to a floating-point stub.  The same is true for non-R_MIPS16_26
16450      relocations against MIPS16 functions; in this case, the stub becomes
16451      the function's canonical address.
16452
16453      Floating-point stubs are stored in unique .mips16.call.* or
16454      .mips16.fn.* sections.  If a stub T for function F is in section S,
16455      the first relocation in section S must be against F; this is how the
16456      linker determines the target function.  All relocations that might
16457      resolve to T must also be against F.  We therefore have the following
16458      restrictions, which are given in an intentionally-redundant way:
16459
16460        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16461           symbols.
16462
16463        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16464           if that stub might be used.
16465
16466        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16467           symbols.
16468
16469        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16470           that stub might be used.
16471
16472      There is a further restriction:
16473
16474        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16475           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16476           targets with in-place addends; the relocation field cannot
16477           encode the low bit.
16478
16479      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16480      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16481      such relocations on REL targets.
16482
16483      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16484      relocation against some symbol R, no relocation against R may be
16485      reduced.  (Note that this deals with (2) as well as (1) because
16486      relocations against global symbols will never be reduced on ELF
16487      targets.)  This approach is a little simpler than trying to detect
16488      stub sections, and gives the "all or nothing" per-symbol consistency
16489      that we have for MIPS16 symbols.  */
16490   if (fixp->fx_subsy == NULL
16491       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16492           || *symbol_get_tc (fixp->fx_addsy)
16493           || (HAVE_IN_PLACE_ADDENDS
16494               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16495               && jmp_reloc_p (fixp->fx_r_type))))
16496     return 0;
16497
16498   return 1;
16499 }
16500
16501 /* Translate internal representation of relocation info to BFD target
16502    format.  */
16503
16504 arelent **
16505 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16506 {
16507   static arelent *retval[4];
16508   arelent *reloc;
16509   bfd_reloc_code_real_type code;
16510
16511   memset (retval, 0, sizeof(retval));
16512   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16513   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16514   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16515   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16516
16517   if (fixp->fx_pcrel)
16518     {
16519       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16520                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16521                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16522                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16523                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16524
16525       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16526          Relocations want only the symbol offset.  */
16527       reloc->addend = fixp->fx_addnumber + reloc->address;
16528     }
16529   else
16530     reloc->addend = fixp->fx_addnumber;
16531
16532   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16533      entry to be used in the relocation's section offset.  */
16534   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16535     {
16536       reloc->address = reloc->addend;
16537       reloc->addend = 0;
16538     }
16539
16540   code = fixp->fx_r_type;
16541
16542   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16543   if (reloc->howto == NULL)
16544     {
16545       as_bad_where (fixp->fx_file, fixp->fx_line,
16546                     _("cannot represent %s relocation in this object file"
16547                       " format"),
16548                     bfd_get_reloc_code_name (code));
16549       retval[0] = NULL;
16550     }
16551
16552   return retval;
16553 }
16554
16555 /* Relax a machine dependent frag.  This returns the amount by which
16556    the current size of the frag should change.  */
16557
16558 int
16559 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16560 {
16561   if (RELAX_BRANCH_P (fragp->fr_subtype))
16562     {
16563       offsetT old_var = fragp->fr_var;
16564
16565       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16566
16567       return fragp->fr_var - old_var;
16568     }
16569
16570   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16571     {
16572       offsetT old_var = fragp->fr_var;
16573       offsetT new_var = 4;
16574
16575       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16576         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16577       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16578         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16579       fragp->fr_var = new_var;
16580
16581       return new_var - old_var;
16582     }
16583
16584   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16585     return 0;
16586
16587   if (mips16_extended_frag (fragp, NULL, stretch))
16588     {
16589       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16590         return 0;
16591       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16592       return 2;
16593     }
16594   else
16595     {
16596       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16597         return 0;
16598       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16599       return -2;
16600     }
16601
16602   return 0;
16603 }
16604
16605 /* Convert a machine dependent frag.  */
16606
16607 void
16608 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16609 {
16610   if (RELAX_BRANCH_P (fragp->fr_subtype))
16611     {
16612       char *buf;
16613       unsigned long insn;
16614       expressionS exp;
16615       fixS *fixp;
16616
16617       buf = fragp->fr_literal + fragp->fr_fix;
16618       insn = read_insn (buf);
16619
16620       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16621         {
16622           /* We generate a fixup instead of applying it right now
16623              because, if there are linker relaxations, we're going to
16624              need the relocations.  */
16625           exp.X_op = O_symbol;
16626           exp.X_add_symbol = fragp->fr_symbol;
16627           exp.X_add_number = fragp->fr_offset;
16628
16629           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16630                               BFD_RELOC_16_PCREL_S2);
16631           fixp->fx_file = fragp->fr_file;
16632           fixp->fx_line = fragp->fr_line;
16633
16634           buf = write_insn (buf, insn);
16635         }
16636       else
16637         {
16638           int i;
16639
16640           as_warn_where (fragp->fr_file, fragp->fr_line,
16641                          _("relaxed out-of-range branch into a jump"));
16642
16643           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16644             goto uncond;
16645
16646           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16647             {
16648               /* Reverse the branch.  */
16649               switch ((insn >> 28) & 0xf)
16650                 {
16651                 case 4:
16652                   if ((insn & 0xff000000) == 0x47000000
16653                       || (insn & 0xff600000) == 0x45600000)
16654                     {
16655                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16656                          reversed by tweaking bit 23.  */
16657                       insn ^= 0x00800000;
16658                     }
16659                   else
16660                     {
16661                       /* bc[0-3][tf]l? instructions can have the condition
16662                          reversed by tweaking a single TF bit, and their
16663                          opcodes all have 0x4???????.  */
16664                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16665                       insn ^= 0x00010000;
16666                     }
16667                   break;
16668
16669                 case 0:
16670                   /* bltz       0x04000000      bgez    0x04010000
16671                      bltzal     0x04100000      bgezal  0x04110000  */
16672                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16673                   insn ^= 0x00010000;
16674                   break;
16675
16676                 case 1:
16677                   /* beq        0x10000000      bne     0x14000000
16678                      blez       0x18000000      bgtz    0x1c000000  */
16679                   insn ^= 0x04000000;
16680                   break;
16681
16682                 default:
16683                   abort ();
16684                 }
16685             }
16686
16687           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16688             {
16689               /* Clear the and-link bit.  */
16690               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16691
16692               /* bltzal         0x04100000      bgezal  0x04110000
16693                  bltzall        0x04120000      bgezall 0x04130000  */
16694               insn &= ~0x00100000;
16695             }
16696
16697           /* Branch over the branch (if the branch was likely) or the
16698              full jump (not likely case).  Compute the offset from the
16699              current instruction to branch to.  */
16700           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16701             i = 16;
16702           else
16703             {
16704               /* How many bytes in instructions we've already emitted?  */
16705               i = buf - fragp->fr_literal - fragp->fr_fix;
16706               /* How many bytes in instructions from here to the end?  */
16707               i = fragp->fr_var - i;
16708             }
16709           /* Convert to instruction count.  */
16710           i >>= 2;
16711           /* Branch counts from the next instruction.  */
16712           i--;
16713           insn |= i;
16714           /* Branch over the jump.  */
16715           buf = write_insn (buf, insn);
16716
16717           /* nop */
16718           buf = write_insn (buf, 0);
16719
16720           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16721             {
16722               /* beql $0, $0, 2f */
16723               insn = 0x50000000;
16724               /* Compute the PC offset from the current instruction to
16725                  the end of the variable frag.  */
16726               /* How many bytes in instructions we've already emitted?  */
16727               i = buf - fragp->fr_literal - fragp->fr_fix;
16728               /* How many bytes in instructions from here to the end?  */
16729               i = fragp->fr_var - i;
16730               /* Convert to instruction count.  */
16731               i >>= 2;
16732               /* Don't decrement i, because we want to branch over the
16733                  delay slot.  */
16734               insn |= i;
16735
16736               buf = write_insn (buf, insn);
16737               buf = write_insn (buf, 0);
16738             }
16739
16740         uncond:
16741           if (mips_pic == NO_PIC)
16742             {
16743               /* j or jal.  */
16744               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16745                       ? 0x0c000000 : 0x08000000);
16746               exp.X_op = O_symbol;
16747               exp.X_add_symbol = fragp->fr_symbol;
16748               exp.X_add_number = fragp->fr_offset;
16749
16750               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16751                                   FALSE, BFD_RELOC_MIPS_JMP);
16752               fixp->fx_file = fragp->fr_file;
16753               fixp->fx_line = fragp->fr_line;
16754
16755               buf = write_insn (buf, insn);
16756             }
16757           else
16758             {
16759               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16760
16761               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16762               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16763               insn |= at << OP_SH_RT;
16764               exp.X_op = O_symbol;
16765               exp.X_add_symbol = fragp->fr_symbol;
16766               exp.X_add_number = fragp->fr_offset;
16767
16768               if (fragp->fr_offset)
16769                 {
16770                   exp.X_add_symbol = make_expr_symbol (&exp);
16771                   exp.X_add_number = 0;
16772                 }
16773
16774               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16775                                   FALSE, BFD_RELOC_MIPS_GOT16);
16776               fixp->fx_file = fragp->fr_file;
16777               fixp->fx_line = fragp->fr_line;
16778
16779               buf = write_insn (buf, insn);
16780
16781               if (mips_opts.isa == ISA_MIPS1)
16782                 /* nop */
16783                 buf = write_insn (buf, 0);
16784
16785               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16786               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16787               insn |= at << OP_SH_RS | at << OP_SH_RT;
16788
16789               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16790                                   FALSE, BFD_RELOC_LO16);
16791               fixp->fx_file = fragp->fr_file;
16792               fixp->fx_line = fragp->fr_line;
16793
16794               buf = write_insn (buf, insn);
16795
16796               /* j(al)r $at.  */
16797               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16798                 insn = 0x0000f809;
16799               else
16800                 insn = 0x00000008;
16801               insn |= at << OP_SH_RS;
16802
16803               buf = write_insn (buf, insn);
16804             }
16805         }
16806
16807       fragp->fr_fix += fragp->fr_var;
16808       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16809       return;
16810     }
16811
16812   /* Relax microMIPS branches.  */
16813   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16814     {
16815       char *buf = fragp->fr_literal + fragp->fr_fix;
16816       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16817       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16818       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16819       bfd_boolean short_ds;
16820       unsigned long insn;
16821       expressionS exp;
16822       fixS *fixp;
16823
16824       exp.X_op = O_symbol;
16825       exp.X_add_symbol = fragp->fr_symbol;
16826       exp.X_add_number = fragp->fr_offset;
16827
16828       fragp->fr_fix += fragp->fr_var;
16829
16830       /* Handle 16-bit branches that fit or are forced to fit.  */
16831       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16832         {
16833           /* We generate a fixup instead of applying it right now,
16834              because if there is linker relaxation, we're going to
16835              need the relocations.  */
16836           if (type == 'D')
16837             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16838                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16839           else if (type == 'E')
16840             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16841                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16842           else
16843             abort ();
16844
16845           fixp->fx_file = fragp->fr_file;
16846           fixp->fx_line = fragp->fr_line;
16847
16848           /* These relocations can have an addend that won't fit in
16849              2 octets.  */
16850           fixp->fx_no_overflow = 1;
16851
16852           return;
16853         }
16854
16855       /* Handle 32-bit branches that fit or are forced to fit.  */
16856       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16857           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16858         {
16859           /* We generate a fixup instead of applying it right now,
16860              because if there is linker relaxation, we're going to
16861              need the relocations.  */
16862           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16863                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16864           fixp->fx_file = fragp->fr_file;
16865           fixp->fx_line = fragp->fr_line;
16866
16867           if (type == 0)
16868             return;
16869         }
16870
16871       /* Relax 16-bit branches to 32-bit branches.  */
16872       if (type != 0)
16873         {
16874           insn = read_compressed_insn (buf, 2);
16875
16876           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16877             insn = 0x94000000;                          /* beq  */
16878           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16879             {
16880               unsigned long regno;
16881
16882               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16883               regno = micromips_to_32_reg_d_map [regno];
16884               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16885               insn |= regno << MICROMIPSOP_SH_RS;
16886             }
16887           else
16888             abort ();
16889
16890           /* Nothing else to do, just write it out.  */
16891           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16892               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16893             {
16894               buf = write_compressed_insn (buf, insn, 4);
16895               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16896               return;
16897             }
16898         }
16899       else
16900         insn = read_compressed_insn (buf, 4);
16901
16902       /* Relax 32-bit branches to a sequence of instructions.  */
16903       as_warn_where (fragp->fr_file, fragp->fr_line,
16904                      _("relaxed out-of-range branch into a jump"));
16905
16906       /* Set the short-delay-slot bit.  */
16907       short_ds = al && (insn & 0x02000000) != 0;
16908
16909       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16910         {
16911           symbolS *l;
16912
16913           /* Reverse the branch.  */
16914           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16915               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16916             insn ^= 0x20000000;
16917           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16918                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16919                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16920                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16921                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16922                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16923                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16924                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16925                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16926                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16927             insn ^= 0x00400000;
16928           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16929                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16930                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16931                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16932             insn ^= 0x00200000;
16933           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
16934                                                                    BNZ.df  */
16935                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
16936                                                                    BNZ.V */
16937             insn ^= 0x00800000;
16938           else
16939             abort ();
16940
16941           if (al)
16942             {
16943               /* Clear the and-link and short-delay-slot bits.  */
16944               gas_assert ((insn & 0xfda00000) == 0x40200000);
16945
16946               /* bltzal  0x40200000     bgezal  0x40600000  */
16947               /* bltzals 0x42200000     bgezals 0x42600000  */
16948               insn &= ~0x02200000;
16949             }
16950
16951           /* Make a label at the end for use with the branch.  */
16952           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16953           micromips_label_inc ();
16954           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16955
16956           /* Refer to it.  */
16957           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16958                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16959           fixp->fx_file = fragp->fr_file;
16960           fixp->fx_line = fragp->fr_line;
16961
16962           /* Branch over the jump.  */
16963           buf = write_compressed_insn (buf, insn, 4);
16964           if (!compact)
16965             /* nop */
16966             buf = write_compressed_insn (buf, 0x0c00, 2);
16967         }
16968
16969       if (mips_pic == NO_PIC)
16970         {
16971           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16972
16973           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16974           insn = al ? jal : 0xd4000000;
16975
16976           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16977                               BFD_RELOC_MICROMIPS_JMP);
16978           fixp->fx_file = fragp->fr_file;
16979           fixp->fx_line = fragp->fr_line;
16980
16981           buf = write_compressed_insn (buf, insn, 4);
16982           if (compact)
16983             /* nop */
16984             buf = write_compressed_insn (buf, 0x0c00, 2);
16985         }
16986       else
16987         {
16988           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16989           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16990           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16991
16992           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16993           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16994           insn |= at << MICROMIPSOP_SH_RT;
16995
16996           if (exp.X_add_number)
16997             {
16998               exp.X_add_symbol = make_expr_symbol (&exp);
16999               exp.X_add_number = 0;
17000             }
17001
17002           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17003                               BFD_RELOC_MICROMIPS_GOT16);
17004           fixp->fx_file = fragp->fr_file;
17005           fixp->fx_line = fragp->fr_line;
17006
17007           buf = write_compressed_insn (buf, insn, 4);
17008
17009           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17010           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17011           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17012
17013           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17014                               BFD_RELOC_MICROMIPS_LO16);
17015           fixp->fx_file = fragp->fr_file;
17016           fixp->fx_line = fragp->fr_line;
17017
17018           buf = write_compressed_insn (buf, insn, 4);
17019
17020           /* jr/jrc/jalr/jalrs $at  */
17021           insn = al ? jalr : jr;
17022           insn |= at << MICROMIPSOP_SH_MJ;
17023
17024           buf = write_compressed_insn (buf, insn, 2);
17025         }
17026
17027       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17028       return;
17029     }
17030
17031   if (RELAX_MIPS16_P (fragp->fr_subtype))
17032     {
17033       int type;
17034       const struct mips_int_operand *operand;
17035       offsetT val;
17036       char *buf;
17037       unsigned int user_length, length;
17038       unsigned long insn;
17039       bfd_boolean ext;
17040
17041       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17042       operand = mips16_immed_operand (type, FALSE);
17043
17044       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17045       val = resolve_symbol_value (fragp->fr_symbol);
17046       if (operand->root.type == OP_PCREL)
17047         {
17048           const struct mips_pcrel_operand *pcrel_op;
17049           addressT addr;
17050
17051           pcrel_op = (const struct mips_pcrel_operand *) operand;
17052           addr = fragp->fr_address + fragp->fr_fix;
17053
17054           /* The rules for the base address of a PC relative reloc are
17055              complicated; see mips16_extended_frag.  */
17056           if (pcrel_op->include_isa_bit)
17057             {
17058               addr += 2;
17059               if (ext)
17060                 addr += 2;
17061               /* Ignore the low bit in the target, since it will be
17062                  set for a text label.  */
17063               val &= -2;
17064             }
17065           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17066             addr -= 4;
17067           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17068             addr -= 2;
17069
17070           addr &= -(1 << pcrel_op->align_log2);
17071           val -= addr;
17072
17073           /* Make sure the section winds up with the alignment we have
17074              assumed.  */
17075           if (operand->shift > 0)
17076             record_alignment (asec, operand->shift);
17077         }
17078
17079       if (ext
17080           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17081               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17082         as_warn_where (fragp->fr_file, fragp->fr_line,
17083                        _("extended instruction in delay slot"));
17084
17085       buf = fragp->fr_literal + fragp->fr_fix;
17086
17087       insn = read_compressed_insn (buf, 2);
17088       if (ext)
17089         insn |= MIPS16_EXTEND;
17090
17091       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17092         user_length = 4;
17093       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17094         user_length = 2;
17095       else
17096         user_length = 0;
17097
17098       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17099                     BFD_RELOC_UNUSED, val, user_length, &insn);
17100
17101       length = (ext ? 4 : 2);
17102       gas_assert (mips16_opcode_length (insn) == length);
17103       write_compressed_insn (buf, insn, length);
17104       fragp->fr_fix += length;
17105     }
17106   else
17107     {
17108       relax_substateT subtype = fragp->fr_subtype;
17109       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17110       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17111       int first, second;
17112       fixS *fixp;
17113
17114       first = RELAX_FIRST (subtype);
17115       second = RELAX_SECOND (subtype);
17116       fixp = (fixS *) fragp->fr_opcode;
17117
17118       /* If the delay slot chosen does not match the size of the instruction,
17119          then emit a warning.  */
17120       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17121            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17122         {
17123           relax_substateT s;
17124           const char *msg;
17125
17126           s = subtype & (RELAX_DELAY_SLOT_16BIT
17127                          | RELAX_DELAY_SLOT_SIZE_FIRST
17128                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17129           msg = macro_warning (s);
17130           if (msg != NULL)
17131             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17132           subtype &= ~s;
17133         }
17134
17135       /* Possibly emit a warning if we've chosen the longer option.  */
17136       if (use_second == second_longer)
17137         {
17138           relax_substateT s;
17139           const char *msg;
17140
17141           s = (subtype
17142                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17143           msg = macro_warning (s);
17144           if (msg != NULL)
17145             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17146           subtype &= ~s;
17147         }
17148
17149       /* Go through all the fixups for the first sequence.  Disable them
17150          (by marking them as done) if we're going to use the second
17151          sequence instead.  */
17152       while (fixp
17153              && fixp->fx_frag == fragp
17154              && fixp->fx_where < fragp->fr_fix - second)
17155         {
17156           if (subtype & RELAX_USE_SECOND)
17157             fixp->fx_done = 1;
17158           fixp = fixp->fx_next;
17159         }
17160
17161       /* Go through the fixups for the second sequence.  Disable them if
17162          we're going to use the first sequence, otherwise adjust their
17163          addresses to account for the relaxation.  */
17164       while (fixp && fixp->fx_frag == fragp)
17165         {
17166           if (subtype & RELAX_USE_SECOND)
17167             fixp->fx_where -= first;
17168           else
17169             fixp->fx_done = 1;
17170           fixp = fixp->fx_next;
17171         }
17172
17173       /* Now modify the frag contents.  */
17174       if (subtype & RELAX_USE_SECOND)
17175         {
17176           char *start;
17177
17178           start = fragp->fr_literal + fragp->fr_fix - first - second;
17179           memmove (start, start + first, second);
17180           fragp->fr_fix -= first;
17181         }
17182       else
17183         fragp->fr_fix -= second;
17184     }
17185 }
17186
17187 /* This function is called after the relocs have been generated.
17188    We've been storing mips16 text labels as odd.  Here we convert them
17189    back to even for the convenience of the debugger.  */
17190
17191 void
17192 mips_frob_file_after_relocs (void)
17193 {
17194   asymbol **syms;
17195   unsigned int count, i;
17196
17197   syms = bfd_get_outsymbols (stdoutput);
17198   count = bfd_get_symcount (stdoutput);
17199   for (i = 0; i < count; i++, syms++)
17200     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17201         && ((*syms)->value & 1) != 0)
17202       {
17203         (*syms)->value &= ~1;
17204         /* If the symbol has an odd size, it was probably computed
17205            incorrectly, so adjust that as well.  */
17206         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17207           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17208       }
17209 }
17210
17211 /* This function is called whenever a label is defined, including fake
17212    labels instantiated off the dot special symbol.  It is used when
17213    handling branch delays; if a branch has a label, we assume we cannot
17214    move it.  This also bumps the value of the symbol by 1 in compressed
17215    code.  */
17216
17217 static void
17218 mips_record_label (symbolS *sym)
17219 {
17220   segment_info_type *si = seg_info (now_seg);
17221   struct insn_label_list *l;
17222
17223   if (free_insn_labels == NULL)
17224     l = (struct insn_label_list *) xmalloc (sizeof *l);
17225   else
17226     {
17227       l = free_insn_labels;
17228       free_insn_labels = l->next;
17229     }
17230
17231   l->label = sym;
17232   l->next = si->label_list;
17233   si->label_list = l;
17234 }
17235
17236 /* This function is called as tc_frob_label() whenever a label is defined
17237    and adds a DWARF-2 record we only want for true labels.  */
17238
17239 void
17240 mips_define_label (symbolS *sym)
17241 {
17242   mips_record_label (sym);
17243   dwarf2_emit_label (sym);
17244 }
17245
17246 /* This function is called by tc_new_dot_label whenever a new dot symbol
17247    is defined.  */
17248
17249 void
17250 mips_add_dot_label (symbolS *sym)
17251 {
17252   mips_record_label (sym);
17253   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17254     mips_compressed_mark_label (sym);
17255 }
17256 \f
17257 /* Some special processing for a MIPS ELF file.  */
17258
17259 void
17260 mips_elf_final_processing (void)
17261 {
17262   /* Write out the register information.  */
17263   if (mips_abi != N64_ABI)
17264     {
17265       Elf32_RegInfo s;
17266
17267       s.ri_gprmask = mips_gprmask;
17268       s.ri_cprmask[0] = mips_cprmask[0];
17269       s.ri_cprmask[1] = mips_cprmask[1];
17270       s.ri_cprmask[2] = mips_cprmask[2];
17271       s.ri_cprmask[3] = mips_cprmask[3];
17272       /* The gp_value field is set by the MIPS ELF backend.  */
17273
17274       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17275                                        ((Elf32_External_RegInfo *)
17276                                         mips_regmask_frag));
17277     }
17278   else
17279     {
17280       Elf64_Internal_RegInfo s;
17281
17282       s.ri_gprmask = mips_gprmask;
17283       s.ri_pad = 0;
17284       s.ri_cprmask[0] = mips_cprmask[0];
17285       s.ri_cprmask[1] = mips_cprmask[1];
17286       s.ri_cprmask[2] = mips_cprmask[2];
17287       s.ri_cprmask[3] = mips_cprmask[3];
17288       /* The gp_value field is set by the MIPS ELF backend.  */
17289
17290       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17291                                        ((Elf64_External_RegInfo *)
17292                                         mips_regmask_frag));
17293     }
17294
17295   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17296      sort of BFD interface for this.  */
17297   if (mips_any_noreorder)
17298     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17299   if (mips_pic != NO_PIC)
17300     {
17301       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17302       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17303     }
17304   if (mips_abicalls)
17305     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17306
17307   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17308      defined at present; this might need to change in future.  */
17309   if (file_ase_mips16)
17310     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17311   if (file_ase_micromips)
17312     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17313   if (file_ase & ASE_MDMX)
17314     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17315
17316   /* Set the MIPS ELF ABI flags.  */
17317   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17318     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17319   else if (mips_abi == O64_ABI)
17320     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17321   else if (mips_abi == EABI_ABI)
17322     {
17323       if (!file_mips_gp32)
17324         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17325       else
17326         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17327     }
17328   else if (mips_abi == N32_ABI)
17329     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17330
17331   /* Nothing to do for N64_ABI.  */
17332
17333   if (mips_32bitmode)
17334     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17335
17336   if (mips_flag_nan2008)
17337     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17338
17339   /* 32 bit code with 64 bit FP registers.  */
17340   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17341     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17342 }
17343 \f
17344 typedef struct proc {
17345   symbolS *func_sym;
17346   symbolS *func_end_sym;
17347   unsigned long reg_mask;
17348   unsigned long reg_offset;
17349   unsigned long fpreg_mask;
17350   unsigned long fpreg_offset;
17351   unsigned long frame_offset;
17352   unsigned long frame_reg;
17353   unsigned long pc_reg;
17354 } procS;
17355
17356 static procS cur_proc;
17357 static procS *cur_proc_ptr;
17358 static int numprocs;
17359
17360 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17361    as "2", and a normal nop as "0".  */
17362
17363 #define NOP_OPCODE_MIPS         0
17364 #define NOP_OPCODE_MIPS16       1
17365 #define NOP_OPCODE_MICROMIPS    2
17366
17367 char
17368 mips_nop_opcode (void)
17369 {
17370   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17371     return NOP_OPCODE_MICROMIPS;
17372   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17373     return NOP_OPCODE_MIPS16;
17374   else
17375     return NOP_OPCODE_MIPS;
17376 }
17377
17378 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17379    32-bit microMIPS NOPs here (if applicable).  */
17380
17381 void
17382 mips_handle_align (fragS *fragp)
17383 {
17384   char nop_opcode;
17385   char *p;
17386   int bytes, size, excess;
17387   valueT opcode;
17388
17389   if (fragp->fr_type != rs_align_code)
17390     return;
17391
17392   p = fragp->fr_literal + fragp->fr_fix;
17393   nop_opcode = *p;
17394   switch (nop_opcode)
17395     {
17396     case NOP_OPCODE_MICROMIPS:
17397       opcode = micromips_nop32_insn.insn_opcode;
17398       size = 4;
17399       break;
17400     case NOP_OPCODE_MIPS16:
17401       opcode = mips16_nop_insn.insn_opcode;
17402       size = 2;
17403       break;
17404     case NOP_OPCODE_MIPS:
17405     default:
17406       opcode = nop_insn.insn_opcode;
17407       size = 4;
17408       break;
17409     }
17410
17411   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17412   excess = bytes % size;
17413
17414   /* Handle the leading part if we're not inserting a whole number of
17415      instructions, and make it the end of the fixed part of the frag.
17416      Try to fit in a short microMIPS NOP if applicable and possible,
17417      and use zeroes otherwise.  */
17418   gas_assert (excess < 4);
17419   fragp->fr_fix += excess;
17420   switch (excess)
17421     {
17422     case 3:
17423       *p++ = '\0';
17424       /* Fall through.  */
17425     case 2:
17426       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17427         {
17428           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17429           break;
17430         }
17431       *p++ = '\0';
17432       /* Fall through.  */
17433     case 1:
17434       *p++ = '\0';
17435       /* Fall through.  */
17436     case 0:
17437       break;
17438     }
17439
17440   md_number_to_chars (p, opcode, size);
17441   fragp->fr_var = size;
17442 }
17443
17444 static void
17445 md_obj_begin (void)
17446 {
17447 }
17448
17449 static void
17450 md_obj_end (void)
17451 {
17452   /* Check for premature end, nesting errors, etc.  */
17453   if (cur_proc_ptr)
17454     as_warn (_("missing .end at end of assembly"));
17455 }
17456
17457 static long
17458 get_number (void)
17459 {
17460   int negative = 0;
17461   long val = 0;
17462
17463   if (*input_line_pointer == '-')
17464     {
17465       ++input_line_pointer;
17466       negative = 1;
17467     }
17468   if (!ISDIGIT (*input_line_pointer))
17469     as_bad (_("expected simple number"));
17470   if (input_line_pointer[0] == '0')
17471     {
17472       if (input_line_pointer[1] == 'x')
17473         {
17474           input_line_pointer += 2;
17475           while (ISXDIGIT (*input_line_pointer))
17476             {
17477               val <<= 4;
17478               val |= hex_value (*input_line_pointer++);
17479             }
17480           return negative ? -val : val;
17481         }
17482       else
17483         {
17484           ++input_line_pointer;
17485           while (ISDIGIT (*input_line_pointer))
17486             {
17487               val <<= 3;
17488               val |= *input_line_pointer++ - '0';
17489             }
17490           return negative ? -val : val;
17491         }
17492     }
17493   if (!ISDIGIT (*input_line_pointer))
17494     {
17495       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17496               *input_line_pointer, *input_line_pointer);
17497       as_warn (_("invalid number"));
17498       return -1;
17499     }
17500   while (ISDIGIT (*input_line_pointer))
17501     {
17502       val *= 10;
17503       val += *input_line_pointer++ - '0';
17504     }
17505   return negative ? -val : val;
17506 }
17507
17508 /* The .file directive; just like the usual .file directive, but there
17509    is an initial number which is the ECOFF file index.  In the non-ECOFF
17510    case .file implies DWARF-2.  */
17511
17512 static void
17513 s_mips_file (int x ATTRIBUTE_UNUSED)
17514 {
17515   static int first_file_directive = 0;
17516
17517   if (ECOFF_DEBUGGING)
17518     {
17519       get_number ();
17520       s_app_file (0);
17521     }
17522   else
17523     {
17524       char *filename;
17525
17526       filename = dwarf2_directive_file (0);
17527
17528       /* Versions of GCC up to 3.1 start files with a ".file"
17529          directive even for stabs output.  Make sure that this
17530          ".file" is handled.  Note that you need a version of GCC
17531          after 3.1 in order to support DWARF-2 on MIPS.  */
17532       if (filename != NULL && ! first_file_directive)
17533         {
17534           (void) new_logical_line (filename, -1);
17535           s_app_file_string (filename, 0);
17536         }
17537       first_file_directive = 1;
17538     }
17539 }
17540
17541 /* The .loc directive, implying DWARF-2.  */
17542
17543 static void
17544 s_mips_loc (int x ATTRIBUTE_UNUSED)
17545 {
17546   if (!ECOFF_DEBUGGING)
17547     dwarf2_directive_loc (0);
17548 }
17549
17550 /* The .end directive.  */
17551
17552 static void
17553 s_mips_end (int x ATTRIBUTE_UNUSED)
17554 {
17555   symbolS *p;
17556
17557   /* Following functions need their own .frame and .cprestore directives.  */
17558   mips_frame_reg_valid = 0;
17559   mips_cprestore_valid = 0;
17560
17561   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17562     {
17563       p = get_symbol ();
17564       demand_empty_rest_of_line ();
17565     }
17566   else
17567     p = NULL;
17568
17569   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17570     as_warn (_(".end not in text section"));
17571
17572   if (!cur_proc_ptr)
17573     {
17574       as_warn (_(".end directive without a preceding .ent directive"));
17575       demand_empty_rest_of_line ();
17576       return;
17577     }
17578
17579   if (p != NULL)
17580     {
17581       gas_assert (S_GET_NAME (p));
17582       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17583         as_warn (_(".end symbol does not match .ent symbol"));
17584
17585       if (debug_type == DEBUG_STABS)
17586         stabs_generate_asm_endfunc (S_GET_NAME (p),
17587                                     S_GET_NAME (p));
17588     }
17589   else
17590     as_warn (_(".end directive missing or unknown symbol"));
17591
17592   /* Create an expression to calculate the size of the function.  */
17593   if (p && cur_proc_ptr)
17594     {
17595       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17596       expressionS *exp = xmalloc (sizeof (expressionS));
17597
17598       obj->size = exp;
17599       exp->X_op = O_subtract;
17600       exp->X_add_symbol = symbol_temp_new_now ();
17601       exp->X_op_symbol = p;
17602       exp->X_add_number = 0;
17603
17604       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17605     }
17606
17607   /* Generate a .pdr section.  */
17608   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17609     {
17610       segT saved_seg = now_seg;
17611       subsegT saved_subseg = now_subseg;
17612       expressionS exp;
17613       char *fragp;
17614
17615 #ifdef md_flush_pending_output
17616       md_flush_pending_output ();
17617 #endif
17618
17619       gas_assert (pdr_seg);
17620       subseg_set (pdr_seg, 0);
17621
17622       /* Write the symbol.  */
17623       exp.X_op = O_symbol;
17624       exp.X_add_symbol = p;
17625       exp.X_add_number = 0;
17626       emit_expr (&exp, 4);
17627
17628       fragp = frag_more (7 * 4);
17629
17630       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17631       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17632       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17633       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17634       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17635       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17636       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17637
17638       subseg_set (saved_seg, saved_subseg);
17639     }
17640
17641   cur_proc_ptr = NULL;
17642 }
17643
17644 /* The .aent and .ent directives.  */
17645
17646 static void
17647 s_mips_ent (int aent)
17648 {
17649   symbolS *symbolP;
17650
17651   symbolP = get_symbol ();
17652   if (*input_line_pointer == ',')
17653     ++input_line_pointer;
17654   SKIP_WHITESPACE ();
17655   if (ISDIGIT (*input_line_pointer)
17656       || *input_line_pointer == '-')
17657     get_number ();
17658
17659   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17660     as_warn (_(".ent or .aent not in text section"));
17661
17662   if (!aent && cur_proc_ptr)
17663     as_warn (_("missing .end"));
17664
17665   if (!aent)
17666     {
17667       /* This function needs its own .frame and .cprestore directives.  */
17668       mips_frame_reg_valid = 0;
17669       mips_cprestore_valid = 0;
17670
17671       cur_proc_ptr = &cur_proc;
17672       memset (cur_proc_ptr, '\0', sizeof (procS));
17673
17674       cur_proc_ptr->func_sym = symbolP;
17675
17676       ++numprocs;
17677
17678       if (debug_type == DEBUG_STABS)
17679         stabs_generate_asm_func (S_GET_NAME (symbolP),
17680                                  S_GET_NAME (symbolP));
17681     }
17682
17683   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17684
17685   demand_empty_rest_of_line ();
17686 }
17687
17688 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17689    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17690    s_mips_frame is used so that we can set the PDR information correctly.
17691    We can't use the ecoff routines because they make reference to the ecoff
17692    symbol table (in the mdebug section).  */
17693
17694 static void
17695 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17696 {
17697   if (ECOFF_DEBUGGING)
17698     s_ignore (ignore);
17699   else
17700     {
17701       long val;
17702
17703       if (cur_proc_ptr == (procS *) NULL)
17704         {
17705           as_warn (_(".frame outside of .ent"));
17706           demand_empty_rest_of_line ();
17707           return;
17708         }
17709
17710       cur_proc_ptr->frame_reg = tc_get_register (1);
17711
17712       SKIP_WHITESPACE ();
17713       if (*input_line_pointer++ != ','
17714           || get_absolute_expression_and_terminator (&val) != ',')
17715         {
17716           as_warn (_("bad .frame directive"));
17717           --input_line_pointer;
17718           demand_empty_rest_of_line ();
17719           return;
17720         }
17721
17722       cur_proc_ptr->frame_offset = val;
17723       cur_proc_ptr->pc_reg = tc_get_register (0);
17724
17725       demand_empty_rest_of_line ();
17726     }
17727 }
17728
17729 /* The .fmask and .mask directives. If the mdebug section is present
17730    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17731    embedded targets, s_mips_mask is used so that we can set the PDR
17732    information correctly. We can't use the ecoff routines because they
17733    make reference to the ecoff symbol table (in the mdebug section).  */
17734
17735 static void
17736 s_mips_mask (int reg_type)
17737 {
17738   if (ECOFF_DEBUGGING)
17739     s_ignore (reg_type);
17740   else
17741     {
17742       long mask, off;
17743
17744       if (cur_proc_ptr == (procS *) NULL)
17745         {
17746           as_warn (_(".mask/.fmask outside of .ent"));
17747           demand_empty_rest_of_line ();
17748           return;
17749         }
17750
17751       if (get_absolute_expression_and_terminator (&mask) != ',')
17752         {
17753           as_warn (_("bad .mask/.fmask directive"));
17754           --input_line_pointer;
17755           demand_empty_rest_of_line ();
17756           return;
17757         }
17758
17759       off = get_absolute_expression ();
17760
17761       if (reg_type == 'F')
17762         {
17763           cur_proc_ptr->fpreg_mask = mask;
17764           cur_proc_ptr->fpreg_offset = off;
17765         }
17766       else
17767         {
17768           cur_proc_ptr->reg_mask = mask;
17769           cur_proc_ptr->reg_offset = off;
17770         }
17771
17772       demand_empty_rest_of_line ();
17773     }
17774 }
17775
17776 /* A table describing all the processors gas knows about.  Names are
17777    matched in the order listed.
17778
17779    To ease comparison, please keep this table in the same order as
17780    gcc's mips_cpu_info_table[].  */
17781 static const struct mips_cpu_info mips_cpu_info_table[] =
17782 {
17783   /* Entries for generic ISAs */
17784   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17785   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17786   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17787   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17788   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17789   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17790   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17791   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17792   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17793
17794   /* MIPS I */
17795   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17796   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17797   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17798
17799   /* MIPS II */
17800   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17801
17802   /* MIPS III */
17803   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17804   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17805   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17806   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17807   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17808   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17809   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17810   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17811   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17812   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17813   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17814   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17815   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17816   /* ST Microelectronics Loongson 2E and 2F cores */
17817   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17818   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17819
17820   /* MIPS IV */
17821   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17822   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17823   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17824   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17825   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17826   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17827   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17828   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17829   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17830   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17831   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17832   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17833   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17834   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17835   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17836
17837   /* MIPS 32 */
17838   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17839   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17840   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17841   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17842
17843   /* MIPS 32 Release 2 */
17844   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17845   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17846   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17847   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17848   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17849   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17850   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17851   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17852   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17853                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17854   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17855                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17856   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17857   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17858   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17859   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17860   /* Deprecated forms of the above.  */
17861   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17862   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17863   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17864   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17865   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17866   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17867   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17868   /* Deprecated forms of the above.  */
17869   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17870   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17871   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17872   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17873   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17874   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17875   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17876   /* Deprecated forms of the above.  */
17877   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17878   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17879   /* 34Kn is a 34kc without DSP.  */
17880   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17881   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17882   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17883   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17884   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17885   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17886   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17887   /* Deprecated forms of the above.  */
17888   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17889   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17890   /* 1004K cores are multiprocessor versions of the 34K.  */
17891   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17892   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17893   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17894   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17895
17896   /* MIPS 64 */
17897   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17898   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17899   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17900   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17901
17902   /* Broadcom SB-1 CPU core */
17903   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17904   /* Broadcom SB-1A CPU core */
17905   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17906   
17907   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
17908
17909   /* MIPS 64 Release 2 */
17910
17911   /* Cavium Networks Octeon CPU core */
17912   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17913   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17914   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17915
17916   /* RMI Xlr */
17917   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17918
17919   /* Broadcom XLP.
17920      XLP is mostly like XLR, with the prominent exception that it is
17921      MIPS64R2 rather than MIPS64.  */
17922   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17923
17924   /* End marker */
17925   { NULL, 0, 0, 0, 0 }
17926 };
17927
17928
17929 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17930    with a final "000" replaced by "k".  Ignore case.
17931
17932    Note: this function is shared between GCC and GAS.  */
17933
17934 static bfd_boolean
17935 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17936 {
17937   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17938     given++, canonical++;
17939
17940   return ((*given == 0 && *canonical == 0)
17941           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17942 }
17943
17944
17945 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17946    CPU name.  We've traditionally allowed a lot of variation here.
17947
17948    Note: this function is shared between GCC and GAS.  */
17949
17950 static bfd_boolean
17951 mips_matching_cpu_name_p (const char *canonical, const char *given)
17952 {
17953   /* First see if the name matches exactly, or with a final "000"
17954      turned into "k".  */
17955   if (mips_strict_matching_cpu_name_p (canonical, given))
17956     return TRUE;
17957
17958   /* If not, try comparing based on numerical designation alone.
17959      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17960   if (TOLOWER (*given) == 'r')
17961     given++;
17962   if (!ISDIGIT (*given))
17963     return FALSE;
17964
17965   /* Skip over some well-known prefixes in the canonical name,
17966      hoping to find a number there too.  */
17967   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17968     canonical += 2;
17969   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17970     canonical += 2;
17971   else if (TOLOWER (canonical[0]) == 'r')
17972     canonical += 1;
17973
17974   return mips_strict_matching_cpu_name_p (canonical, given);
17975 }
17976
17977
17978 /* Parse an option that takes the name of a processor as its argument.
17979    OPTION is the name of the option and CPU_STRING is the argument.
17980    Return the corresponding processor enumeration if the CPU_STRING is
17981    recognized, otherwise report an error and return null.
17982
17983    A similar function exists in GCC.  */
17984
17985 static const struct mips_cpu_info *
17986 mips_parse_cpu (const char *option, const char *cpu_string)
17987 {
17988   const struct mips_cpu_info *p;
17989
17990   /* 'from-abi' selects the most compatible architecture for the given
17991      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17992      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17993      version.  Look first at the -mgp options, if given, otherwise base
17994      the choice on MIPS_DEFAULT_64BIT.
17995
17996      Treat NO_ABI like the EABIs.  One reason to do this is that the
17997      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17998      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17999      'mips64', just as we did in the days before 'from-abi'.  */
18000   if (strcasecmp (cpu_string, "from-abi") == 0)
18001     {
18002       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18003         return mips_cpu_info_from_isa (ISA_MIPS1);
18004
18005       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18006         return mips_cpu_info_from_isa (ISA_MIPS3);
18007
18008       if (file_mips_gp32 >= 0)
18009         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
18010
18011       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18012                                      ? ISA_MIPS3
18013                                      : ISA_MIPS1);
18014     }
18015
18016   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18017   if (strcasecmp (cpu_string, "default") == 0)
18018     return 0;
18019
18020   for (p = mips_cpu_info_table; p->name != 0; p++)
18021     if (mips_matching_cpu_name_p (p->name, cpu_string))
18022       return p;
18023
18024   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18025   return 0;
18026 }
18027
18028 /* Return the canonical processor information for ISA (a member of the
18029    ISA_MIPS* enumeration).  */
18030
18031 static const struct mips_cpu_info *
18032 mips_cpu_info_from_isa (int isa)
18033 {
18034   int i;
18035
18036   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18037     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18038         && isa == mips_cpu_info_table[i].isa)
18039       return (&mips_cpu_info_table[i]);
18040
18041   return NULL;
18042 }
18043
18044 static const struct mips_cpu_info *
18045 mips_cpu_info_from_arch (int arch)
18046 {
18047   int i;
18048
18049   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18050     if (arch == mips_cpu_info_table[i].cpu)
18051       return (&mips_cpu_info_table[i]);
18052
18053   return NULL;
18054 }
18055 \f
18056 static void
18057 show (FILE *stream, const char *string, int *col_p, int *first_p)
18058 {
18059   if (*first_p)
18060     {
18061       fprintf (stream, "%24s", "");
18062       *col_p = 24;
18063     }
18064   else
18065     {
18066       fprintf (stream, ", ");
18067       *col_p += 2;
18068     }
18069
18070   if (*col_p + strlen (string) > 72)
18071     {
18072       fprintf (stream, "\n%24s", "");
18073       *col_p = 24;
18074     }
18075
18076   fprintf (stream, "%s", string);
18077   *col_p += strlen (string);
18078
18079   *first_p = 0;
18080 }
18081
18082 void
18083 md_show_usage (FILE *stream)
18084 {
18085   int column, first;
18086   size_t i;
18087
18088   fprintf (stream, _("\
18089 MIPS options:\n\
18090 -EB                     generate big endian output\n\
18091 -EL                     generate little endian output\n\
18092 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18093 -G NUM                  allow referencing objects up to NUM bytes\n\
18094                         implicitly with the gp register [default 8]\n"));
18095   fprintf (stream, _("\
18096 -mips1                  generate MIPS ISA I instructions\n\
18097 -mips2                  generate MIPS ISA II instructions\n\
18098 -mips3                  generate MIPS ISA III instructions\n\
18099 -mips4                  generate MIPS ISA IV instructions\n\
18100 -mips5                  generate MIPS ISA V instructions\n\
18101 -mips32                 generate MIPS32 ISA instructions\n\
18102 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18103 -mips64                 generate MIPS64 ISA instructions\n\
18104 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18105 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18106
18107   first = 1;
18108
18109   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18110     show (stream, mips_cpu_info_table[i].name, &column, &first);
18111   show (stream, "from-abi", &column, &first);
18112   fputc ('\n', stream);
18113
18114   fprintf (stream, _("\
18115 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18116 -no-mCPU                don't generate code specific to CPU.\n\
18117                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18118
18119   first = 1;
18120
18121   show (stream, "3900", &column, &first);
18122   show (stream, "4010", &column, &first);
18123   show (stream, "4100", &column, &first);
18124   show (stream, "4650", &column, &first);
18125   fputc ('\n', stream);
18126
18127   fprintf (stream, _("\
18128 -mips16                 generate mips16 instructions\n\
18129 -no-mips16              do not generate mips16 instructions\n"));
18130   fprintf (stream, _("\
18131 -mmicromips             generate microMIPS instructions\n\
18132 -mno-micromips          do not generate microMIPS instructions\n"));
18133   fprintf (stream, _("\
18134 -msmartmips             generate smartmips instructions\n\
18135 -mno-smartmips          do not generate smartmips instructions\n"));  
18136   fprintf (stream, _("\
18137 -mdsp                   generate DSP instructions\n\
18138 -mno-dsp                do not generate DSP instructions\n"));
18139   fprintf (stream, _("\
18140 -mdspr2                 generate DSP R2 instructions\n\
18141 -mno-dspr2              do not generate DSP R2 instructions\n"));
18142   fprintf (stream, _("\
18143 -mmt                    generate MT instructions\n\
18144 -mno-mt                 do not generate MT instructions\n"));
18145   fprintf (stream, _("\
18146 -mmcu                   generate MCU instructions\n\
18147 -mno-mcu                do not generate MCU instructions\n"));
18148   fprintf (stream, _("\
18149 -mmsa                   generate MSA instructions\n\
18150 -mno-msa                do not generate MSA instructions\n"));
18151   fprintf (stream, _("\
18152 -mvirt                  generate Virtualization instructions\n\
18153 -mno-virt               do not generate Virtualization instructions\n"));
18154   fprintf (stream, _("\
18155 -minsn32                only generate 32-bit microMIPS instructions\n\
18156 -mno-insn32             generate all microMIPS instructions\n"));
18157   fprintf (stream, _("\
18158 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18159 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18160 -mfix-vr4120            work around certain VR4120 errata\n\
18161 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18162 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18163 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18164 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18165 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18166 -msym32                 assume all symbols have 32-bit values\n\
18167 -O0                     remove unneeded NOPs, do not swap branches\n\
18168 -O                      remove unneeded NOPs and swap branches\n\
18169 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18170 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18171   fprintf (stream, _("\
18172 -mhard-float            allow floating-point instructions\n\
18173 -msoft-float            do not allow floating-point instructions\n\
18174 -msingle-float          only allow 32-bit floating-point operations\n\
18175 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18176 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18177 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18178 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18179
18180   first = 1;
18181
18182   show (stream, "legacy", &column, &first);
18183   show (stream, "2008", &column, &first);
18184
18185   fputc ('\n', stream);
18186
18187   fprintf (stream, _("\
18188 -KPIC, -call_shared     generate SVR4 position independent code\n\
18189 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18190 -mvxworks-pic           generate VxWorks position independent code\n\
18191 -non_shared             do not generate code that can operate with DSOs\n\
18192 -xgot                   assume a 32 bit GOT\n\
18193 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18194 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18195                         position dependent (non shared) code\n\
18196 -mabi=ABI               create ABI conformant object file for:\n"));
18197
18198   first = 1;
18199
18200   show (stream, "32", &column, &first);
18201   show (stream, "o64", &column, &first);
18202   show (stream, "n32", &column, &first);
18203   show (stream, "64", &column, &first);
18204   show (stream, "eabi", &column, &first);
18205
18206   fputc ('\n', stream);
18207
18208   fprintf (stream, _("\
18209 -32                     create o32 ABI object file (default)\n\
18210 -n32                    create n32 ABI object file\n\
18211 -64                     create 64 ABI object file\n"));
18212 }
18213
18214 #ifdef TE_IRIX
18215 enum dwarf2_format
18216 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18217 {
18218   if (HAVE_64BIT_SYMBOLS)
18219     return dwarf2_format_64bit_irix;
18220   else
18221     return dwarf2_format_32bit;
18222 }
18223 #endif
18224
18225 int
18226 mips_dwarf2_addr_size (void)
18227 {
18228   if (HAVE_64BIT_OBJECTS)
18229     return 8;
18230   else
18231     return 4;
18232 }
18233
18234 /* Standard calling conventions leave the CFA at SP on entry.  */
18235 void
18236 mips_cfi_frame_initial_instructions (void)
18237 {
18238   cfi_add_CFA_def_cfa_register (SP);
18239 }
18240
18241 int
18242 tc_mips_regname_to_dw2regnum (char *regname)
18243 {
18244   unsigned int regnum = -1;
18245   unsigned int reg;
18246
18247   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18248     regnum = reg;
18249
18250   return regnum;
18251 }