2013-09-12 Chao-ying Fu <Chao-ying.Fu@imgtec.com>
[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_DELAY.  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-cn63xxp1 */
869 static bfd_boolean mips_fix_cn63xxp1;
870
871 /* We don't relax branches by default, since this causes us to expand
872    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
873    fail to compute the offset before expanding the macro to the most
874    efficient expansion.  */
875
876 static int mips_relax_branch;
877 \f
878 /* The expansion of many macros depends on the type of symbol that
879    they refer to.  For example, when generating position-dependent code,
880    a macro that refers to a symbol may have two different expansions,
881    one which uses GP-relative addresses and one which uses absolute
882    addresses.  When generating SVR4-style PIC, a macro may have
883    different expansions for local and global symbols.
884
885    We handle these situations by generating both sequences and putting
886    them in variant frags.  In position-dependent code, the first sequence
887    will be the GP-relative one and the second sequence will be the
888    absolute one.  In SVR4 PIC, the first sequence will be for global
889    symbols and the second will be for local symbols.
890
891    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
892    SECOND are the lengths of the two sequences in bytes.  These fields
893    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
894    the subtype has the following flags:
895
896    RELAX_USE_SECOND
897         Set if it has been decided that we should use the second
898         sequence instead of the first.
899
900    RELAX_SECOND_LONGER
901         Set in the first variant frag if the macro's second implementation
902         is longer than its first.  This refers to the macro as a whole,
903         not an individual relaxation.
904
905    RELAX_NOMACRO
906         Set in the first variant frag if the macro appeared in a .set nomacro
907         block and if one alternative requires a warning but the other does not.
908
909    RELAX_DELAY_SLOT
910         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
911         delay slot.
912
913    RELAX_DELAY_SLOT_16BIT
914         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
915         16-bit instruction.
916
917    RELAX_DELAY_SLOT_SIZE_FIRST
918         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
919         the macro is of the wrong size for the branch delay slot.
920
921    RELAX_DELAY_SLOT_SIZE_SECOND
922         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
923         the macro is of the wrong size for the branch delay slot.
924
925    The frag's "opcode" points to the first fixup for relaxable code.
926
927    Relaxable macros are generated using a sequence such as:
928
929       relax_start (SYMBOL);
930       ... generate first expansion ...
931       relax_switch ();
932       ... generate second expansion ...
933       relax_end ();
934
935    The code and fixups for the unwanted alternative are discarded
936    by md_convert_frag.  */
937 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
938
939 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
940 #define RELAX_SECOND(X) ((X) & 0xff)
941 #define RELAX_USE_SECOND 0x10000
942 #define RELAX_SECOND_LONGER 0x20000
943 #define RELAX_NOMACRO 0x40000
944 #define RELAX_DELAY_SLOT 0x80000
945 #define RELAX_DELAY_SLOT_16BIT 0x100000
946 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
947 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
948
949 /* Branch without likely bit.  If label is out of range, we turn:
950
951         beq reg1, reg2, label
952         delay slot
953
954    into
955
956         bne reg1, reg2, 0f
957         nop
958         j label
959      0: delay slot
960
961    with the following opcode replacements:
962
963         beq <-> bne
964         blez <-> bgtz
965         bltz <-> bgez
966         bc1f <-> bc1t
967
968         bltzal <-> bgezal  (with jal label instead of j label)
969
970    Even though keeping the delay slot instruction in the delay slot of
971    the branch would be more efficient, it would be very tricky to do
972    correctly, because we'd have to introduce a variable frag *after*
973    the delay slot instruction, and expand that instead.  Let's do it
974    the easy way for now, even if the branch-not-taken case now costs
975    one additional instruction.  Out-of-range branches are not supposed
976    to be common, anyway.
977
978    Branch likely.  If label is out of range, we turn:
979
980         beql reg1, reg2, label
981         delay slot (annulled if branch not taken)
982
983    into
984
985         beql reg1, reg2, 1f
986         nop
987         beql $0, $0, 2f
988         nop
989      1: j[al] label
990         delay slot (executed only if branch taken)
991      2:
992
993    It would be possible to generate a shorter sequence by losing the
994    likely bit, generating something like:
995
996         bne reg1, reg2, 0f
997         nop
998         j[al] label
999         delay slot (executed only if branch taken)
1000      0:
1001
1002         beql -> bne
1003         bnel -> beq
1004         blezl -> bgtz
1005         bgtzl -> blez
1006         bltzl -> bgez
1007         bgezl -> bltz
1008         bc1fl -> bc1t
1009         bc1tl -> bc1f
1010
1011         bltzall -> bgezal  (with jal label instead of j label)
1012         bgezall -> bltzal  (ditto)
1013
1014
1015    but it's not clear that it would actually improve performance.  */
1016 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1017   ((relax_substateT)                                            \
1018    (0xc0000000                                                  \
1019     | ((at) & 0x1f)                                             \
1020     | ((toofar) ? 0x20 : 0)                                     \
1021     | ((link) ? 0x40 : 0)                                       \
1022     | ((likely) ? 0x80 : 0)                                     \
1023     | ((uncond) ? 0x100 : 0)))
1024 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1025 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1026 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1027 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1028 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1029 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1030
1031 /* For mips16 code, we use an entirely different form of relaxation.
1032    mips16 supports two versions of most instructions which take
1033    immediate values: a small one which takes some small value, and a
1034    larger one which takes a 16 bit value.  Since branches also follow
1035    this pattern, relaxing these values is required.
1036
1037    We can assemble both mips16 and normal MIPS code in a single
1038    object.  Therefore, we need to support this type of relaxation at
1039    the same time that we support the relaxation described above.  We
1040    use the high bit of the subtype field to distinguish these cases.
1041
1042    The information we store for this type of relaxation is the
1043    argument code found in the opcode file for this relocation, whether
1044    the user explicitly requested a small or extended form, and whether
1045    the relocation is in a jump or jal delay slot.  That tells us the
1046    size of the value, and how it should be stored.  We also store
1047    whether the fragment is considered to be extended or not.  We also
1048    store whether this is known to be a branch to a different section,
1049    whether we have tried to relax this frag yet, and whether we have
1050    ever extended a PC relative fragment because of a shift count.  */
1051 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1052   (0x80000000                                                   \
1053    | ((type) & 0xff)                                            \
1054    | ((small) ? 0x100 : 0)                                      \
1055    | ((ext) ? 0x200 : 0)                                        \
1056    | ((dslot) ? 0x400 : 0)                                      \
1057    | ((jal_dslot) ? 0x800 : 0))
1058 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1059 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1060 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1061 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1062 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1063 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1064 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1065 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1066 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1067 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1068 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1069 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1070
1071 /* For microMIPS code, we use relaxation similar to one we use for
1072    MIPS16 code.  Some instructions that take immediate values support
1073    two encodings: a small one which takes some small value, and a
1074    larger one which takes a 16 bit value.  As some branches also follow
1075    this pattern, relaxing these values is required.
1076
1077    We can assemble both microMIPS and normal MIPS code in a single
1078    object.  Therefore, we need to support this type of relaxation at
1079    the same time that we support the relaxation described above.  We
1080    use one of the high bits of the subtype field to distinguish these
1081    cases.
1082
1083    The information we store for this type of relaxation is the argument
1084    code found in the opcode file for this relocation, the register
1085    selected as the assembler temporary, whether the branch is
1086    unconditional, whether it is compact, whether it stores the link
1087    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1088    branches to a sequence of instructions is enabled, and whether the
1089    displacement of a branch is too large to fit as an immediate argument
1090    of a 16-bit and a 32-bit branch, respectively.  */
1091 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1092                                relax32, toofar16, toofar32)     \
1093   (0x40000000                                                   \
1094    | ((type) & 0xff)                                            \
1095    | (((at) & 0x1f) << 8)                                       \
1096    | ((uncond) ? 0x2000 : 0)                                    \
1097    | ((compact) ? 0x4000 : 0)                                   \
1098    | ((link) ? 0x8000 : 0)                                      \
1099    | ((relax32) ? 0x10000 : 0)                                  \
1100    | ((toofar16) ? 0x20000 : 0)                                 \
1101    | ((toofar32) ? 0x40000 : 0))
1102 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1103 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1104 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1105 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1106 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1107 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1108 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1109
1110 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1111 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1112 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1113 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1114 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1115 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1116
1117 /* Sign-extend 16-bit value X.  */
1118 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1119
1120 /* Is the given value a sign-extended 32-bit value?  */
1121 #define IS_SEXT_32BIT_NUM(x)                                            \
1122   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1123    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1124
1125 /* Is the given value a sign-extended 16-bit value?  */
1126 #define IS_SEXT_16BIT_NUM(x)                                            \
1127   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1128    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1129
1130 /* Is the given value a sign-extended 12-bit value?  */
1131 #define IS_SEXT_12BIT_NUM(x)                                            \
1132   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1133
1134 /* Is the given value a sign-extended 9-bit value?  */
1135 #define IS_SEXT_9BIT_NUM(x)                                             \
1136   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1137
1138 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1139 #define IS_ZEXT_32BIT_NUM(x)                                            \
1140   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1141    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1142
1143 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1144    SHIFT places.  */
1145 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1146   (((STRUCT) >> (SHIFT)) & (MASK))
1147
1148 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1149 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1150   (!(MICROMIPS) \
1151    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1152    : EXTRACT_BITS ((INSN).insn_opcode, \
1153                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1154 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1155   EXTRACT_BITS ((INSN).insn_opcode, \
1156                 MIPS16OP_MASK_##FIELD, \
1157                 MIPS16OP_SH_##FIELD)
1158
1159 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1160 #define MIPS16_EXTEND (0xf000U << 16)
1161 \f
1162 /* Whether or not we are emitting a branch-likely macro.  */
1163 static bfd_boolean emit_branch_likely_macro = FALSE;
1164
1165 /* Global variables used when generating relaxable macros.  See the
1166    comment above RELAX_ENCODE for more details about how relaxation
1167    is used.  */
1168 static struct {
1169   /* 0 if we're not emitting a relaxable macro.
1170      1 if we're emitting the first of the two relaxation alternatives.
1171      2 if we're emitting the second alternative.  */
1172   int sequence;
1173
1174   /* The first relaxable fixup in the current frag.  (In other words,
1175      the first fixup that refers to relaxable code.)  */
1176   fixS *first_fixup;
1177
1178   /* sizes[0] says how many bytes of the first alternative are stored in
1179      the current frag.  Likewise sizes[1] for the second alternative.  */
1180   unsigned int sizes[2];
1181
1182   /* The symbol on which the choice of sequence depends.  */
1183   symbolS *symbol;
1184 } mips_relax;
1185 \f
1186 /* Global variables used to decide whether a macro needs a warning.  */
1187 static struct {
1188   /* True if the macro is in a branch delay slot.  */
1189   bfd_boolean delay_slot_p;
1190
1191   /* Set to the length in bytes required if the macro is in a delay slot
1192      that requires a specific length of instruction, otherwise zero.  */
1193   unsigned int delay_slot_length;
1194
1195   /* For relaxable macros, sizes[0] is the length of the first alternative
1196      in bytes and sizes[1] is the length of the second alternative.
1197      For non-relaxable macros, both elements give the length of the
1198      macro in bytes.  */
1199   unsigned int sizes[2];
1200
1201   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1202      instruction of the first alternative in bytes and first_insn_sizes[1]
1203      is the length of the first instruction of the second alternative.
1204      For non-relaxable macros, both elements give the length of the first
1205      instruction in bytes.
1206
1207      Set to zero if we haven't yet seen the first instruction.  */
1208   unsigned int first_insn_sizes[2];
1209
1210   /* For relaxable macros, insns[0] is the number of instructions for the
1211      first alternative and insns[1] is the number of instructions for the
1212      second alternative.
1213
1214      For non-relaxable macros, both elements give the number of
1215      instructions for the macro.  */
1216   unsigned int insns[2];
1217
1218   /* The first variant frag for this macro.  */
1219   fragS *first_frag;
1220 } mips_macro_warning;
1221 \f
1222 /* Prototypes for static functions.  */
1223
1224 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1225
1226 static void append_insn
1227   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1228    bfd_boolean expansionp);
1229 static void mips_no_prev_insn (void);
1230 static void macro_build (expressionS *, const char *, const char *, ...);
1231 static void mips16_macro_build
1232   (expressionS *, const char *, const char *, va_list *);
1233 static void load_register (int, expressionS *, int);
1234 static void macro_start (void);
1235 static void macro_end (void);
1236 static void macro (struct mips_cl_insn *ip, char *str);
1237 static void mips16_macro (struct mips_cl_insn * ip);
1238 static void mips_ip (char *str, struct mips_cl_insn * ip);
1239 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1240 static void mips16_immed
1241   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1242    unsigned int, unsigned long *);
1243 static size_t my_getSmallExpression
1244   (expressionS *, bfd_reloc_code_real_type *, char *);
1245 static void my_getExpression (expressionS *, char *);
1246 static void s_align (int);
1247 static void s_change_sec (int);
1248 static void s_change_section (int);
1249 static void s_cons (int);
1250 static void s_float_cons (int);
1251 static void s_mips_globl (int);
1252 static void s_option (int);
1253 static void s_mipsset (int);
1254 static void s_abicalls (int);
1255 static void s_cpload (int);
1256 static void s_cpsetup (int);
1257 static void s_cplocal (int);
1258 static void s_cprestore (int);
1259 static void s_cpreturn (int);
1260 static void s_dtprelword (int);
1261 static void s_dtpreldword (int);
1262 static void s_tprelword (int);
1263 static void s_tpreldword (int);
1264 static void s_gpvalue (int);
1265 static void s_gpword (int);
1266 static void s_gpdword (int);
1267 static void s_ehword (int);
1268 static void s_cpadd (int);
1269 static void s_insn (int);
1270 static void s_nan (int);
1271 static void md_obj_begin (void);
1272 static void md_obj_end (void);
1273 static void s_mips_ent (int);
1274 static void s_mips_end (int);
1275 static void s_mips_frame (int);
1276 static void s_mips_mask (int reg_type);
1277 static void s_mips_stab (int);
1278 static void s_mips_weakext (int);
1279 static void s_mips_file (int);
1280 static void s_mips_loc (int);
1281 static bfd_boolean pic_need_relax (symbolS *, asection *);
1282 static int relaxed_branch_length (fragS *, asection *, int);
1283 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1284 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1285
1286 /* Table and functions used to map between CPU/ISA names, and
1287    ISA levels, and CPU numbers.  */
1288
1289 struct mips_cpu_info
1290 {
1291   const char *name;           /* CPU or ISA name.  */
1292   int flags;                  /* MIPS_CPU_* flags.  */
1293   int ase;                    /* Set of ASEs implemented by the CPU.  */
1294   int isa;                    /* ISA level.  */
1295   int cpu;                    /* CPU number (default CPU if ISA).  */
1296 };
1297
1298 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1299
1300 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1301 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1302 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1303 \f
1304 /* Command-line options.  */
1305 const char *md_shortopts = "O::g::G:";
1306
1307 enum options
1308   {
1309     OPTION_MARCH = OPTION_MD_BASE,
1310     OPTION_MTUNE,
1311     OPTION_MIPS1,
1312     OPTION_MIPS2,
1313     OPTION_MIPS3,
1314     OPTION_MIPS4,
1315     OPTION_MIPS5,
1316     OPTION_MIPS32,
1317     OPTION_MIPS64,
1318     OPTION_MIPS32R2,
1319     OPTION_MIPS64R2,
1320     OPTION_MIPS16,
1321     OPTION_NO_MIPS16,
1322     OPTION_MIPS3D,
1323     OPTION_NO_MIPS3D,
1324     OPTION_MDMX,
1325     OPTION_NO_MDMX,
1326     OPTION_DSP,
1327     OPTION_NO_DSP,
1328     OPTION_MT,
1329     OPTION_NO_MT,
1330     OPTION_VIRT,
1331     OPTION_NO_VIRT,
1332     OPTION_SMARTMIPS,
1333     OPTION_NO_SMARTMIPS,
1334     OPTION_DSPR2,
1335     OPTION_NO_DSPR2,
1336     OPTION_EVA,
1337     OPTION_NO_EVA,
1338     OPTION_MICROMIPS,
1339     OPTION_NO_MICROMIPS,
1340     OPTION_MCU,
1341     OPTION_NO_MCU,
1342     OPTION_COMPAT_ARCH_BASE,
1343     OPTION_M4650,
1344     OPTION_NO_M4650,
1345     OPTION_M4010,
1346     OPTION_NO_M4010,
1347     OPTION_M4100,
1348     OPTION_NO_M4100,
1349     OPTION_M3900,
1350     OPTION_NO_M3900,
1351     OPTION_M7000_HILO_FIX,
1352     OPTION_MNO_7000_HILO_FIX,
1353     OPTION_FIX_24K,
1354     OPTION_NO_FIX_24K,
1355     OPTION_FIX_LOONGSON2F_JUMP,
1356     OPTION_NO_FIX_LOONGSON2F_JUMP,
1357     OPTION_FIX_LOONGSON2F_NOP,
1358     OPTION_NO_FIX_LOONGSON2F_NOP,
1359     OPTION_FIX_VR4120,
1360     OPTION_NO_FIX_VR4120,
1361     OPTION_FIX_VR4130,
1362     OPTION_NO_FIX_VR4130,
1363     OPTION_FIX_CN63XXP1,
1364     OPTION_NO_FIX_CN63XXP1,
1365     OPTION_TRAP,
1366     OPTION_BREAK,
1367     OPTION_EB,
1368     OPTION_EL,
1369     OPTION_FP32,
1370     OPTION_GP32,
1371     OPTION_CONSTRUCT_FLOATS,
1372     OPTION_NO_CONSTRUCT_FLOATS,
1373     OPTION_FP64,
1374     OPTION_GP64,
1375     OPTION_RELAX_BRANCH,
1376     OPTION_NO_RELAX_BRANCH,
1377     OPTION_INSN32,
1378     OPTION_NO_INSN32,
1379     OPTION_MSHARED,
1380     OPTION_MNO_SHARED,
1381     OPTION_MSYM32,
1382     OPTION_MNO_SYM32,
1383     OPTION_SOFT_FLOAT,
1384     OPTION_HARD_FLOAT,
1385     OPTION_SINGLE_FLOAT,
1386     OPTION_DOUBLE_FLOAT,
1387     OPTION_32,
1388     OPTION_CALL_SHARED,
1389     OPTION_CALL_NONPIC,
1390     OPTION_NON_SHARED,
1391     OPTION_XGOT,
1392     OPTION_MABI,
1393     OPTION_N32,
1394     OPTION_64,
1395     OPTION_MDEBUG,
1396     OPTION_NO_MDEBUG,
1397     OPTION_PDR,
1398     OPTION_NO_PDR,
1399     OPTION_MVXWORKS_PIC,
1400     OPTION_NAN,
1401     OPTION_END_OF_ENUM
1402   };
1403
1404 struct option md_longopts[] =
1405 {
1406   /* Options which specify architecture.  */
1407   {"march", required_argument, NULL, OPTION_MARCH},
1408   {"mtune", required_argument, NULL, OPTION_MTUNE},
1409   {"mips0", no_argument, NULL, OPTION_MIPS1},
1410   {"mips1", no_argument, NULL, OPTION_MIPS1},
1411   {"mips2", no_argument, NULL, OPTION_MIPS2},
1412   {"mips3", no_argument, NULL, OPTION_MIPS3},
1413   {"mips4", no_argument, NULL, OPTION_MIPS4},
1414   {"mips5", no_argument, NULL, OPTION_MIPS5},
1415   {"mips32", no_argument, NULL, OPTION_MIPS32},
1416   {"mips64", no_argument, NULL, OPTION_MIPS64},
1417   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1418   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1419
1420   /* Options which specify Application Specific Extensions (ASEs).  */
1421   {"mips16", no_argument, NULL, OPTION_MIPS16},
1422   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1423   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1424   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1425   {"mdmx", no_argument, NULL, OPTION_MDMX},
1426   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1427   {"mdsp", no_argument, NULL, OPTION_DSP},
1428   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1429   {"mmt", no_argument, NULL, OPTION_MT},
1430   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1431   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1432   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1433   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1434   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1435   {"meva", no_argument, NULL, OPTION_EVA},
1436   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1437   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1438   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1439   {"mmcu", no_argument, NULL, OPTION_MCU},
1440   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1441   {"mvirt", no_argument, NULL, OPTION_VIRT},
1442   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1443
1444   /* Old-style architecture options.  Don't add more of these.  */
1445   {"m4650", no_argument, NULL, OPTION_M4650},
1446   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1447   {"m4010", no_argument, NULL, OPTION_M4010},
1448   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1449   {"m4100", no_argument, NULL, OPTION_M4100},
1450   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1451   {"m3900", no_argument, NULL, OPTION_M3900},
1452   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1453
1454   /* Options which enable bug fixes.  */
1455   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1456   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1457   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1458   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1459   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1460   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1461   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1462   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1463   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1464   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1465   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1466   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1467   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1468   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1469   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1470
1471   /* Miscellaneous options.  */
1472   {"trap", no_argument, NULL, OPTION_TRAP},
1473   {"no-break", no_argument, NULL, OPTION_TRAP},
1474   {"break", no_argument, NULL, OPTION_BREAK},
1475   {"no-trap", no_argument, NULL, OPTION_BREAK},
1476   {"EB", no_argument, NULL, OPTION_EB},
1477   {"EL", no_argument, NULL, OPTION_EL},
1478   {"mfp32", no_argument, NULL, OPTION_FP32},
1479   {"mgp32", no_argument, NULL, OPTION_GP32},
1480   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1481   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1482   {"mfp64", no_argument, NULL, OPTION_FP64},
1483   {"mgp64", no_argument, NULL, OPTION_GP64},
1484   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1485   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1486   {"minsn32", no_argument, NULL, OPTION_INSN32},
1487   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1488   {"mshared", no_argument, NULL, OPTION_MSHARED},
1489   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1490   {"msym32", no_argument, NULL, OPTION_MSYM32},
1491   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1492   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1493   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1494   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1495   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1496
1497   /* Strictly speaking this next option is ELF specific,
1498      but we allow it for other ports as well in order to
1499      make testing easier.  */
1500   {"32", no_argument, NULL, OPTION_32},
1501
1502   /* ELF-specific options.  */
1503   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1504   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1505   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1506   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1507   {"xgot", no_argument, NULL, OPTION_XGOT},
1508   {"mabi", required_argument, NULL, OPTION_MABI},
1509   {"n32", no_argument, NULL, OPTION_N32},
1510   {"64", no_argument, NULL, OPTION_64},
1511   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1512   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1513   {"mpdr", no_argument, NULL, OPTION_PDR},
1514   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1515   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1516   {"mnan", required_argument, NULL, OPTION_NAN},
1517
1518   {NULL, no_argument, NULL, 0}
1519 };
1520 size_t md_longopts_size = sizeof (md_longopts);
1521 \f
1522 /* Information about either an Application Specific Extension or an
1523    optional architecture feature that, for simplicity, we treat in the
1524    same way as an ASE.  */
1525 struct mips_ase
1526 {
1527   /* The name of the ASE, used in both the command-line and .set options.  */
1528   const char *name;
1529
1530   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1531      and 64-bit architectures, the flags here refer to the subset that
1532      is available on both.  */
1533   unsigned int flags;
1534
1535   /* The ASE_* flag used for instructions that are available on 64-bit
1536      architectures but that are not included in FLAGS.  */
1537   unsigned int flags64;
1538
1539   /* The command-line options that turn the ASE on and off.  */
1540   int option_on;
1541   int option_off;
1542
1543   /* The minimum required architecture revisions for MIPS32, MIPS64,
1544      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1545   int mips32_rev;
1546   int mips64_rev;
1547   int micromips32_rev;
1548   int micromips64_rev;
1549 };
1550
1551 /* A table of all supported ASEs.  */
1552 static const struct mips_ase mips_ases[] = {
1553   { "dsp", ASE_DSP, ASE_DSP64,
1554     OPTION_DSP, OPTION_NO_DSP,
1555     2, 2, 2, 2 },
1556
1557   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1558     OPTION_DSPR2, OPTION_NO_DSPR2,
1559     2, 2, 2, 2 },
1560
1561   { "eva", ASE_EVA, 0,
1562     OPTION_EVA, OPTION_NO_EVA,
1563     2, 2, 2, 2 },
1564
1565   { "mcu", ASE_MCU, 0,
1566     OPTION_MCU, OPTION_NO_MCU,
1567     2, 2, 2, 2 },
1568
1569   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1570   { "mdmx", ASE_MDMX, 0,
1571     OPTION_MDMX, OPTION_NO_MDMX,
1572     -1, 1, -1, -1 },
1573
1574   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1575   { "mips3d", ASE_MIPS3D, 0,
1576     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1577     2, 1, -1, -1 },
1578
1579   { "mt", ASE_MT, 0,
1580     OPTION_MT, OPTION_NO_MT,
1581     2, 2, -1, -1 },
1582
1583   { "smartmips", ASE_SMARTMIPS, 0,
1584     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1585     1, -1, -1, -1 },
1586
1587   { "virt", ASE_VIRT, ASE_VIRT64,
1588     OPTION_VIRT, OPTION_NO_VIRT,
1589     2, 2, 2, 2 }
1590 };
1591
1592 /* The set of ASEs that require -mfp64.  */
1593 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1594
1595 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1596 static const unsigned int mips_ase_groups[] = {
1597   ASE_DSP | ASE_DSPR2
1598 };
1599 \f
1600 /* Pseudo-op table.
1601
1602    The following pseudo-ops from the Kane and Heinrich MIPS book
1603    should be defined here, but are currently unsupported: .alias,
1604    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1605
1606    The following pseudo-ops from the Kane and Heinrich MIPS book are
1607    specific to the type of debugging information being generated, and
1608    should be defined by the object format: .aent, .begin, .bend,
1609    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1610    .vreg.
1611
1612    The following pseudo-ops from the Kane and Heinrich MIPS book are
1613    not MIPS CPU specific, but are also not specific to the object file
1614    format.  This file is probably the best place to define them, but
1615    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1616
1617 static const pseudo_typeS mips_pseudo_table[] =
1618 {
1619   /* MIPS specific pseudo-ops.  */
1620   {"option", s_option, 0},
1621   {"set", s_mipsset, 0},
1622   {"rdata", s_change_sec, 'r'},
1623   {"sdata", s_change_sec, 's'},
1624   {"livereg", s_ignore, 0},
1625   {"abicalls", s_abicalls, 0},
1626   {"cpload", s_cpload, 0},
1627   {"cpsetup", s_cpsetup, 0},
1628   {"cplocal", s_cplocal, 0},
1629   {"cprestore", s_cprestore, 0},
1630   {"cpreturn", s_cpreturn, 0},
1631   {"dtprelword", s_dtprelword, 0},
1632   {"dtpreldword", s_dtpreldword, 0},
1633   {"tprelword", s_tprelword, 0},
1634   {"tpreldword", s_tpreldword, 0},
1635   {"gpvalue", s_gpvalue, 0},
1636   {"gpword", s_gpword, 0},
1637   {"gpdword", s_gpdword, 0},
1638   {"ehword", s_ehword, 0},
1639   {"cpadd", s_cpadd, 0},
1640   {"insn", s_insn, 0},
1641   {"nan", s_nan, 0},
1642
1643   /* Relatively generic pseudo-ops that happen to be used on MIPS
1644      chips.  */
1645   {"asciiz", stringer, 8 + 1},
1646   {"bss", s_change_sec, 'b'},
1647   {"err", s_err, 0},
1648   {"half", s_cons, 1},
1649   {"dword", s_cons, 3},
1650   {"weakext", s_mips_weakext, 0},
1651   {"origin", s_org, 0},
1652   {"repeat", s_rept, 0},
1653
1654   /* For MIPS this is non-standard, but we define it for consistency.  */
1655   {"sbss", s_change_sec, 'B'},
1656
1657   /* These pseudo-ops are defined in read.c, but must be overridden
1658      here for one reason or another.  */
1659   {"align", s_align, 0},
1660   {"byte", s_cons, 0},
1661   {"data", s_change_sec, 'd'},
1662   {"double", s_float_cons, 'd'},
1663   {"float", s_float_cons, 'f'},
1664   {"globl", s_mips_globl, 0},
1665   {"global", s_mips_globl, 0},
1666   {"hword", s_cons, 1},
1667   {"int", s_cons, 2},
1668   {"long", s_cons, 2},
1669   {"octa", s_cons, 4},
1670   {"quad", s_cons, 3},
1671   {"section", s_change_section, 0},
1672   {"short", s_cons, 1},
1673   {"single", s_float_cons, 'f'},
1674   {"stabd", s_mips_stab, 'd'},
1675   {"stabn", s_mips_stab, 'n'},
1676   {"stabs", s_mips_stab, 's'},
1677   {"text", s_change_sec, 't'},
1678   {"word", s_cons, 2},
1679
1680   { "extern", ecoff_directive_extern, 0},
1681
1682   { NULL, NULL, 0 },
1683 };
1684
1685 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1686 {
1687   /* These pseudo-ops should be defined by the object file format.
1688      However, a.out doesn't support them, so we have versions here.  */
1689   {"aent", s_mips_ent, 1},
1690   {"bgnb", s_ignore, 0},
1691   {"end", s_mips_end, 0},
1692   {"endb", s_ignore, 0},
1693   {"ent", s_mips_ent, 0},
1694   {"file", s_mips_file, 0},
1695   {"fmask", s_mips_mask, 'F'},
1696   {"frame", s_mips_frame, 0},
1697   {"loc", s_mips_loc, 0},
1698   {"mask", s_mips_mask, 'R'},
1699   {"verstamp", s_ignore, 0},
1700   { NULL, NULL, 0 },
1701 };
1702
1703 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1704    purpose of the `.dc.a' internal pseudo-op.  */
1705
1706 int
1707 mips_address_bytes (void)
1708 {
1709   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1710 }
1711
1712 extern void pop_insert (const pseudo_typeS *);
1713
1714 void
1715 mips_pop_insert (void)
1716 {
1717   pop_insert (mips_pseudo_table);
1718   if (! ECOFF_DEBUGGING)
1719     pop_insert (mips_nonecoff_pseudo_table);
1720 }
1721 \f
1722 /* Symbols labelling the current insn.  */
1723
1724 struct insn_label_list
1725 {
1726   struct insn_label_list *next;
1727   symbolS *label;
1728 };
1729
1730 static struct insn_label_list *free_insn_labels;
1731 #define label_list tc_segment_info_data.labels
1732
1733 static void mips_clear_insn_labels (void);
1734 static void mips_mark_labels (void);
1735 static void mips_compressed_mark_labels (void);
1736
1737 static inline void
1738 mips_clear_insn_labels (void)
1739 {
1740   register struct insn_label_list **pl;
1741   segment_info_type *si;
1742
1743   if (now_seg)
1744     {
1745       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1746         ;
1747       
1748       si = seg_info (now_seg);
1749       *pl = si->label_list;
1750       si->label_list = NULL;
1751     }
1752 }
1753
1754 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1755
1756 static inline void
1757 mips_mark_labels (void)
1758 {
1759   if (HAVE_CODE_COMPRESSION)
1760     mips_compressed_mark_labels ();
1761 }
1762 \f
1763 static char *expr_end;
1764
1765 /* An expression in a macro instruction.  This is set by mips_ip and
1766    mips16_ip and when populated is always an O_constant.  */
1767
1768 static expressionS imm_expr;
1769
1770 /* The relocatable field in an instruction and the relocs associated
1771    with it.  These variables are used for instructions like LUI and
1772    JAL as well as true offsets.  They are also used for address
1773    operands in macros.  */
1774
1775 static expressionS offset_expr;
1776 static bfd_reloc_code_real_type offset_reloc[3]
1777   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1778
1779 /* This is set to the resulting size of the instruction to be produced
1780    by mips16_ip if an explicit extension is used or by mips_ip if an
1781    explicit size is supplied.  */
1782
1783 static unsigned int forced_insn_length;
1784
1785 /* True if we are assembling an instruction.  All dot symbols defined during
1786    this time should be treated as code labels.  */
1787
1788 static bfd_boolean mips_assembling_insn;
1789
1790 /* The pdr segment for per procedure frame/regmask info.  Not used for
1791    ECOFF debugging.  */
1792
1793 static segT pdr_seg;
1794
1795 /* The default target format to use.  */
1796
1797 #if defined (TE_FreeBSD)
1798 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1799 #elif defined (TE_TMIPS)
1800 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1801 #else
1802 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1803 #endif
1804
1805 const char *
1806 mips_target_format (void)
1807 {
1808   switch (OUTPUT_FLAVOR)
1809     {
1810     case bfd_target_elf_flavour:
1811 #ifdef TE_VXWORKS
1812       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1813         return (target_big_endian
1814                 ? "elf32-bigmips-vxworks"
1815                 : "elf32-littlemips-vxworks");
1816 #endif
1817       return (target_big_endian
1818               ? (HAVE_64BIT_OBJECTS
1819                  ? ELF_TARGET ("elf64-", "big")
1820                  : (HAVE_NEWABI
1821                     ? ELF_TARGET ("elf32-n", "big")
1822                     : ELF_TARGET ("elf32-", "big")))
1823               : (HAVE_64BIT_OBJECTS
1824                  ? ELF_TARGET ("elf64-", "little")
1825                  : (HAVE_NEWABI
1826                     ? ELF_TARGET ("elf32-n", "little")
1827                     : ELF_TARGET ("elf32-", "little"))));
1828     default:
1829       abort ();
1830       return NULL;
1831     }
1832 }
1833
1834 /* Return the ISA revision that is currently in use, or 0 if we are
1835    generating code for MIPS V or below.  */
1836
1837 static int
1838 mips_isa_rev (void)
1839 {
1840   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1841     return 2;
1842
1843   /* microMIPS implies revision 2 or above.  */
1844   if (mips_opts.micromips)
1845     return 2;
1846
1847   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1848     return 1;
1849
1850   return 0;
1851 }
1852
1853 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1854
1855 static unsigned int
1856 mips_ase_mask (unsigned int flags)
1857 {
1858   unsigned int i;
1859
1860   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1861     if (flags & mips_ase_groups[i])
1862       flags |= mips_ase_groups[i];
1863   return flags;
1864 }
1865
1866 /* Check whether the current ISA supports ASE.  Issue a warning if
1867    appropriate.  */
1868
1869 static void
1870 mips_check_isa_supports_ase (const struct mips_ase *ase)
1871 {
1872   const char *base;
1873   int min_rev, size;
1874   static unsigned int warned_isa;
1875   static unsigned int warned_fp32;
1876
1877   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1878     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1879   else
1880     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1881   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1882       && (warned_isa & ase->flags) != ase->flags)
1883     {
1884       warned_isa |= ase->flags;
1885       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1886       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1887       if (min_rev < 0)
1888         as_warn (_("the %d-bit %s architecture does not support the"
1889                    " `%s' extension"), size, base, ase->name);
1890       else
1891         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1892                  ase->name, base, size, min_rev);
1893     }
1894   if ((ase->flags & FP64_ASES)
1895       && mips_opts.fp32
1896       && (warned_fp32 & ase->flags) != ase->flags)
1897     {
1898       warned_fp32 |= ase->flags;
1899       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1900     }
1901 }
1902
1903 /* Check all enabled ASEs to see whether they are supported by the
1904    chosen architecture.  */
1905
1906 static void
1907 mips_check_isa_supports_ases (void)
1908 {
1909   unsigned int i, mask;
1910
1911   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1912     {
1913       mask = mips_ase_mask (mips_ases[i].flags);
1914       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1915         mips_check_isa_supports_ase (&mips_ases[i]);
1916     }
1917 }
1918
1919 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1920    that were affected.  */
1921
1922 static unsigned int
1923 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1924 {
1925   unsigned int mask;
1926
1927   mask = mips_ase_mask (ase->flags);
1928   mips_opts.ase &= ~mask;
1929   if (enabled_p)
1930     mips_opts.ase |= ase->flags;
1931   return mask;
1932 }
1933
1934 /* Return the ASE called NAME, or null if none.  */
1935
1936 static const struct mips_ase *
1937 mips_lookup_ase (const char *name)
1938 {
1939   unsigned int i;
1940
1941   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1942     if (strcmp (name, mips_ases[i].name) == 0)
1943       return &mips_ases[i];
1944   return NULL;
1945 }
1946
1947 /* Return the length of a microMIPS instruction in bytes.  If bits of
1948    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1949    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1950    major opcode) will require further modifications to the opcode
1951    table.  */
1952
1953 static inline unsigned int
1954 micromips_insn_length (const struct mips_opcode *mo)
1955 {
1956   return (mo->mask >> 16) == 0 ? 2 : 4;
1957 }
1958
1959 /* Return the length of MIPS16 instruction OPCODE.  */
1960
1961 static inline unsigned int
1962 mips16_opcode_length (unsigned long opcode)
1963 {
1964   return (opcode >> 16) == 0 ? 2 : 4;
1965 }
1966
1967 /* Return the length of instruction INSN.  */
1968
1969 static inline unsigned int
1970 insn_length (const struct mips_cl_insn *insn)
1971 {
1972   if (mips_opts.micromips)
1973     return micromips_insn_length (insn->insn_mo);
1974   else if (mips_opts.mips16)
1975     return mips16_opcode_length (insn->insn_opcode);
1976   else
1977     return 4;
1978 }
1979
1980 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
1981
1982 static void
1983 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
1984 {
1985   size_t i;
1986
1987   insn->insn_mo = mo;
1988   insn->insn_opcode = mo->match;
1989   insn->frag = NULL;
1990   insn->where = 0;
1991   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
1992     insn->fixp[i] = NULL;
1993   insn->fixed_p = (mips_opts.noreorder > 0);
1994   insn->noreorder_p = (mips_opts.noreorder > 0);
1995   insn->mips16_absolute_jump_p = 0;
1996   insn->complete_p = 0;
1997   insn->cleared_p = 0;
1998 }
1999
2000 /* Get a list of all the operands in INSN.  */
2001
2002 static const struct mips_operand_array *
2003 insn_operands (const struct mips_cl_insn *insn)
2004 {
2005   if (insn->insn_mo >= &mips_opcodes[0]
2006       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2007     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2008
2009   if (insn->insn_mo >= &mips16_opcodes[0]
2010       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2011     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2012
2013   if (insn->insn_mo >= &micromips_opcodes[0]
2014       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2015     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2016
2017   abort ();
2018 }
2019
2020 /* Get a description of operand OPNO of INSN.  */
2021
2022 static const struct mips_operand *
2023 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2024 {
2025   const struct mips_operand_array *operands;
2026
2027   operands = insn_operands (insn);
2028   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2029     abort ();
2030   return operands->operand[opno];
2031 }
2032
2033 /* Install UVAL as the value of OPERAND in INSN.  */
2034
2035 static inline void
2036 insn_insert_operand (struct mips_cl_insn *insn,
2037                      const struct mips_operand *operand, unsigned int uval)
2038 {
2039   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2040 }
2041
2042 /* Extract the value of OPERAND from INSN.  */
2043
2044 static inline unsigned
2045 insn_extract_operand (const struct mips_cl_insn *insn,
2046                       const struct mips_operand *operand)
2047 {
2048   return mips_extract_operand (operand, insn->insn_opcode);
2049 }
2050
2051 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2052
2053 static void
2054 mips_record_compressed_mode (void)
2055 {
2056   segment_info_type *si;
2057
2058   si = seg_info (now_seg);
2059   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2060     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2061   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2062     si->tc_segment_info_data.micromips = mips_opts.micromips;
2063 }
2064
2065 /* Read a standard MIPS instruction from BUF.  */
2066
2067 static unsigned long
2068 read_insn (char *buf)
2069 {
2070   if (target_big_endian)
2071     return bfd_getb32 ((bfd_byte *) buf);
2072   else
2073     return bfd_getl32 ((bfd_byte *) buf);
2074 }
2075
2076 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2077    the next byte.  */
2078
2079 static char *
2080 write_insn (char *buf, unsigned int insn)
2081 {
2082   md_number_to_chars (buf, insn, 4);
2083   return buf + 4;
2084 }
2085
2086 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2087    has length LENGTH.  */
2088
2089 static unsigned long
2090 read_compressed_insn (char *buf, unsigned int length)
2091 {
2092   unsigned long insn;
2093   unsigned int i;
2094
2095   insn = 0;
2096   for (i = 0; i < length; i += 2)
2097     {
2098       insn <<= 16;
2099       if (target_big_endian)
2100         insn |= bfd_getb16 ((char *) buf);
2101       else
2102         insn |= bfd_getl16 ((char *) buf);
2103       buf += 2;
2104     }
2105   return insn;
2106 }
2107
2108 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2109    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2110
2111 static char *
2112 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2113 {
2114   unsigned int i;
2115
2116   for (i = 0; i < length; i += 2)
2117     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2118   return buf + length;
2119 }
2120
2121 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2122
2123 static void
2124 install_insn (const struct mips_cl_insn *insn)
2125 {
2126   char *f = insn->frag->fr_literal + insn->where;
2127   if (HAVE_CODE_COMPRESSION)
2128     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2129   else
2130     write_insn (f, insn->insn_opcode);
2131   mips_record_compressed_mode ();
2132 }
2133
2134 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2135    and install the opcode in the new location.  */
2136
2137 static void
2138 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2139 {
2140   size_t i;
2141
2142   insn->frag = frag;
2143   insn->where = where;
2144   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2145     if (insn->fixp[i] != NULL)
2146       {
2147         insn->fixp[i]->fx_frag = frag;
2148         insn->fixp[i]->fx_where = where;
2149       }
2150   install_insn (insn);
2151 }
2152
2153 /* Add INSN to the end of the output.  */
2154
2155 static void
2156 add_fixed_insn (struct mips_cl_insn *insn)
2157 {
2158   char *f = frag_more (insn_length (insn));
2159   move_insn (insn, frag_now, f - frag_now->fr_literal);
2160 }
2161
2162 /* Start a variant frag and move INSN to the start of the variant part,
2163    marking it as fixed.  The other arguments are as for frag_var.  */
2164
2165 static void
2166 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2167                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2168 {
2169   frag_grow (max_chars);
2170   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2171   insn->fixed_p = 1;
2172   frag_var (rs_machine_dependent, max_chars, var,
2173             subtype, symbol, offset, NULL);
2174 }
2175
2176 /* Insert N copies of INSN into the history buffer, starting at
2177    position FIRST.  Neither FIRST nor N need to be clipped.  */
2178
2179 static void
2180 insert_into_history (unsigned int first, unsigned int n,
2181                      const struct mips_cl_insn *insn)
2182 {
2183   if (mips_relax.sequence != 2)
2184     {
2185       unsigned int i;
2186
2187       for (i = ARRAY_SIZE (history); i-- > first;)
2188         if (i >= first + n)
2189           history[i] = history[i - n];
2190         else
2191           history[i] = *insn;
2192     }
2193 }
2194
2195 /* Clear the error in insn_error.  */
2196
2197 static void
2198 clear_insn_error (void)
2199 {
2200   memset (&insn_error, 0, sizeof (insn_error));
2201 }
2202
2203 /* Possibly record error message MSG for the current instruction.
2204    If the error is about a particular argument, ARGNUM is the 1-based
2205    number of that argument, otherwise it is 0.  FORMAT is the format
2206    of MSG.  Return true if MSG was used, false if the current message
2207    was kept.  */
2208
2209 static bfd_boolean
2210 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2211                        const char *msg)
2212 {
2213   if (argnum == 0)
2214     {
2215       /* Give priority to errors against specific arguments, and to
2216          the first whole-instruction message.  */
2217       if (insn_error.msg)
2218         return FALSE;
2219     }
2220   else
2221     {
2222       /* Keep insn_error if it is against a later argument.  */
2223       if (argnum < insn_error.min_argnum)
2224         return FALSE;
2225
2226       /* If both errors are against the same argument but are different,
2227          give up on reporting a specific error for this argument.
2228          See the comment about mips_insn_error for details.  */
2229       if (argnum == insn_error.min_argnum
2230           && insn_error.msg
2231           && strcmp (insn_error.msg, msg) != 0)
2232         {
2233           insn_error.msg = 0;
2234           insn_error.min_argnum += 1;
2235           return FALSE;
2236         }
2237     }
2238   insn_error.min_argnum = argnum;
2239   insn_error.format = format;
2240   insn_error.msg = msg;
2241   return TRUE;
2242 }
2243
2244 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2245    as for set_insn_error_format.  */
2246
2247 static void
2248 set_insn_error (int argnum, const char *msg)
2249 {
2250   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2251 }
2252
2253 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2254    as for set_insn_error_format.  */
2255
2256 static void
2257 set_insn_error_i (int argnum, const char *msg, int i)
2258 {
2259   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2260     insn_error.u.i = i;
2261 }
2262
2263 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2264    are as for set_insn_error_format.  */
2265
2266 static void
2267 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2268 {
2269   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2270     {
2271       insn_error.u.ss[0] = s1;
2272       insn_error.u.ss[1] = s2;
2273     }
2274 }
2275
2276 /* Report the error in insn_error, which is against assembly code STR.  */
2277
2278 static void
2279 report_insn_error (const char *str)
2280 {
2281   const char *msg;
2282
2283   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2284   switch (insn_error.format)
2285     {
2286     case ERR_FMT_PLAIN:
2287       as_bad (msg, str);
2288       break;
2289
2290     case ERR_FMT_I:
2291       as_bad (msg, insn_error.u.i, str);
2292       break;
2293
2294     case ERR_FMT_SS:
2295       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2296       break;
2297     }
2298 }
2299
2300 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2301    the idea is to make it obvious at a glance that each errata is
2302    included.  */
2303
2304 static void
2305 init_vr4120_conflicts (void)
2306 {
2307 #define CONFLICT(FIRST, SECOND) \
2308     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2309
2310   /* Errata 21 - [D]DIV[U] after [D]MACC */
2311   CONFLICT (MACC, DIV);
2312   CONFLICT (DMACC, DIV);
2313
2314   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2315   CONFLICT (DMULT, DMULT);
2316   CONFLICT (DMULT, DMACC);
2317   CONFLICT (DMACC, DMULT);
2318   CONFLICT (DMACC, DMACC);
2319
2320   /* Errata 24 - MT{LO,HI} after [D]MACC */
2321   CONFLICT (MACC, MTHILO);
2322   CONFLICT (DMACC, MTHILO);
2323
2324   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2325      instruction is executed immediately after a MACC or DMACC
2326      instruction, the result of [either instruction] is incorrect."  */
2327   CONFLICT (MACC, MULT);
2328   CONFLICT (MACC, DMULT);
2329   CONFLICT (DMACC, MULT);
2330   CONFLICT (DMACC, DMULT);
2331
2332   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2333      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2334      DDIV or DDIVU instruction, the result of the MACC or
2335      DMACC instruction is incorrect.".  */
2336   CONFLICT (DMULT, MACC);
2337   CONFLICT (DMULT, DMACC);
2338   CONFLICT (DIV, MACC);
2339   CONFLICT (DIV, DMACC);
2340
2341 #undef CONFLICT
2342 }
2343
2344 struct regname {
2345   const char *name;
2346   unsigned int num;
2347 };
2348
2349 #define RNUM_MASK       0x00000ff
2350 #define RTYPE_MASK      0x0efff00
2351 #define RTYPE_NUM       0x0000100
2352 #define RTYPE_FPU       0x0000200
2353 #define RTYPE_FCC       0x0000400
2354 #define RTYPE_VEC       0x0000800
2355 #define RTYPE_GP        0x0001000
2356 #define RTYPE_CP0       0x0002000
2357 #define RTYPE_PC        0x0004000
2358 #define RTYPE_ACC       0x0008000
2359 #define RTYPE_CCC       0x0010000
2360 #define RTYPE_VI        0x0020000
2361 #define RTYPE_VF        0x0040000
2362 #define RTYPE_R5900_I   0x0080000
2363 #define RTYPE_R5900_Q   0x0100000
2364 #define RTYPE_R5900_R   0x0200000
2365 #define RTYPE_R5900_ACC 0x0400000
2366 #define RWARN           0x8000000
2367
2368 #define GENERIC_REGISTER_NUMBERS \
2369     {"$0",      RTYPE_NUM | 0},  \
2370     {"$1",      RTYPE_NUM | 1},  \
2371     {"$2",      RTYPE_NUM | 2},  \
2372     {"$3",      RTYPE_NUM | 3},  \
2373     {"$4",      RTYPE_NUM | 4},  \
2374     {"$5",      RTYPE_NUM | 5},  \
2375     {"$6",      RTYPE_NUM | 6},  \
2376     {"$7",      RTYPE_NUM | 7},  \
2377     {"$8",      RTYPE_NUM | 8},  \
2378     {"$9",      RTYPE_NUM | 9},  \
2379     {"$10",     RTYPE_NUM | 10}, \
2380     {"$11",     RTYPE_NUM | 11}, \
2381     {"$12",     RTYPE_NUM | 12}, \
2382     {"$13",     RTYPE_NUM | 13}, \
2383     {"$14",     RTYPE_NUM | 14}, \
2384     {"$15",     RTYPE_NUM | 15}, \
2385     {"$16",     RTYPE_NUM | 16}, \
2386     {"$17",     RTYPE_NUM | 17}, \
2387     {"$18",     RTYPE_NUM | 18}, \
2388     {"$19",     RTYPE_NUM | 19}, \
2389     {"$20",     RTYPE_NUM | 20}, \
2390     {"$21",     RTYPE_NUM | 21}, \
2391     {"$22",     RTYPE_NUM | 22}, \
2392     {"$23",     RTYPE_NUM | 23}, \
2393     {"$24",     RTYPE_NUM | 24}, \
2394     {"$25",     RTYPE_NUM | 25}, \
2395     {"$26",     RTYPE_NUM | 26}, \
2396     {"$27",     RTYPE_NUM | 27}, \
2397     {"$28",     RTYPE_NUM | 28}, \
2398     {"$29",     RTYPE_NUM | 29}, \
2399     {"$30",     RTYPE_NUM | 30}, \
2400     {"$31",     RTYPE_NUM | 31} 
2401
2402 #define FPU_REGISTER_NAMES       \
2403     {"$f0",     RTYPE_FPU | 0},  \
2404     {"$f1",     RTYPE_FPU | 1},  \
2405     {"$f2",     RTYPE_FPU | 2},  \
2406     {"$f3",     RTYPE_FPU | 3},  \
2407     {"$f4",     RTYPE_FPU | 4},  \
2408     {"$f5",     RTYPE_FPU | 5},  \
2409     {"$f6",     RTYPE_FPU | 6},  \
2410     {"$f7",     RTYPE_FPU | 7},  \
2411     {"$f8",     RTYPE_FPU | 8},  \
2412     {"$f9",     RTYPE_FPU | 9},  \
2413     {"$f10",    RTYPE_FPU | 10}, \
2414     {"$f11",    RTYPE_FPU | 11}, \
2415     {"$f12",    RTYPE_FPU | 12}, \
2416     {"$f13",    RTYPE_FPU | 13}, \
2417     {"$f14",    RTYPE_FPU | 14}, \
2418     {"$f15",    RTYPE_FPU | 15}, \
2419     {"$f16",    RTYPE_FPU | 16}, \
2420     {"$f17",    RTYPE_FPU | 17}, \
2421     {"$f18",    RTYPE_FPU | 18}, \
2422     {"$f19",    RTYPE_FPU | 19}, \
2423     {"$f20",    RTYPE_FPU | 20}, \
2424     {"$f21",    RTYPE_FPU | 21}, \
2425     {"$f22",    RTYPE_FPU | 22}, \
2426     {"$f23",    RTYPE_FPU | 23}, \
2427     {"$f24",    RTYPE_FPU | 24}, \
2428     {"$f25",    RTYPE_FPU | 25}, \
2429     {"$f26",    RTYPE_FPU | 26}, \
2430     {"$f27",    RTYPE_FPU | 27}, \
2431     {"$f28",    RTYPE_FPU | 28}, \
2432     {"$f29",    RTYPE_FPU | 29}, \
2433     {"$f30",    RTYPE_FPU | 30}, \
2434     {"$f31",    RTYPE_FPU | 31}
2435
2436 #define FPU_CONDITION_CODE_NAMES \
2437     {"$fcc0",   RTYPE_FCC | 0},  \
2438     {"$fcc1",   RTYPE_FCC | 1},  \
2439     {"$fcc2",   RTYPE_FCC | 2},  \
2440     {"$fcc3",   RTYPE_FCC | 3},  \
2441     {"$fcc4",   RTYPE_FCC | 4},  \
2442     {"$fcc5",   RTYPE_FCC | 5},  \
2443     {"$fcc6",   RTYPE_FCC | 6},  \
2444     {"$fcc7",   RTYPE_FCC | 7}
2445
2446 #define COPROC_CONDITION_CODE_NAMES         \
2447     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2448     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2449     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2450     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2451     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2452     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2453     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2454     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2455
2456 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2457     {"$a4",     RTYPE_GP | 8},  \
2458     {"$a5",     RTYPE_GP | 9},  \
2459     {"$a6",     RTYPE_GP | 10}, \
2460     {"$a7",     RTYPE_GP | 11}, \
2461     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2462     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2463     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2464     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2465     {"$t0",     RTYPE_GP | 12}, \
2466     {"$t1",     RTYPE_GP | 13}, \
2467     {"$t2",     RTYPE_GP | 14}, \
2468     {"$t3",     RTYPE_GP | 15}
2469
2470 #define O32_SYMBOLIC_REGISTER_NAMES \
2471     {"$t0",     RTYPE_GP | 8},  \
2472     {"$t1",     RTYPE_GP | 9},  \
2473     {"$t2",     RTYPE_GP | 10}, \
2474     {"$t3",     RTYPE_GP | 11}, \
2475     {"$t4",     RTYPE_GP | 12}, \
2476     {"$t5",     RTYPE_GP | 13}, \
2477     {"$t6",     RTYPE_GP | 14}, \
2478     {"$t7",     RTYPE_GP | 15}, \
2479     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2480     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2481     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2482     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2483
2484 /* Remaining symbolic register names */
2485 #define SYMBOLIC_REGISTER_NAMES \
2486     {"$zero",   RTYPE_GP | 0},  \
2487     {"$at",     RTYPE_GP | 1},  \
2488     {"$AT",     RTYPE_GP | 1},  \
2489     {"$v0",     RTYPE_GP | 2},  \
2490     {"$v1",     RTYPE_GP | 3},  \
2491     {"$a0",     RTYPE_GP | 4},  \
2492     {"$a1",     RTYPE_GP | 5},  \
2493     {"$a2",     RTYPE_GP | 6},  \
2494     {"$a3",     RTYPE_GP | 7},  \
2495     {"$s0",     RTYPE_GP | 16}, \
2496     {"$s1",     RTYPE_GP | 17}, \
2497     {"$s2",     RTYPE_GP | 18}, \
2498     {"$s3",     RTYPE_GP | 19}, \
2499     {"$s4",     RTYPE_GP | 20}, \
2500     {"$s5",     RTYPE_GP | 21}, \
2501     {"$s6",     RTYPE_GP | 22}, \
2502     {"$s7",     RTYPE_GP | 23}, \
2503     {"$t8",     RTYPE_GP | 24}, \
2504     {"$t9",     RTYPE_GP | 25}, \
2505     {"$k0",     RTYPE_GP | 26}, \
2506     {"$kt0",    RTYPE_GP | 26}, \
2507     {"$k1",     RTYPE_GP | 27}, \
2508     {"$kt1",    RTYPE_GP | 27}, \
2509     {"$gp",     RTYPE_GP | 28}, \
2510     {"$sp",     RTYPE_GP | 29}, \
2511     {"$s8",     RTYPE_GP | 30}, \
2512     {"$fp",     RTYPE_GP | 30}, \
2513     {"$ra",     RTYPE_GP | 31}
2514
2515 #define MIPS16_SPECIAL_REGISTER_NAMES \
2516     {"$pc",     RTYPE_PC | 0}
2517
2518 #define MDMX_VECTOR_REGISTER_NAMES \
2519     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2520     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2521     {"$v2",     RTYPE_VEC | 2},  \
2522     {"$v3",     RTYPE_VEC | 3},  \
2523     {"$v4",     RTYPE_VEC | 4},  \
2524     {"$v5",     RTYPE_VEC | 5},  \
2525     {"$v6",     RTYPE_VEC | 6},  \
2526     {"$v7",     RTYPE_VEC | 7},  \
2527     {"$v8",     RTYPE_VEC | 8},  \
2528     {"$v9",     RTYPE_VEC | 9},  \
2529     {"$v10",    RTYPE_VEC | 10}, \
2530     {"$v11",    RTYPE_VEC | 11}, \
2531     {"$v12",    RTYPE_VEC | 12}, \
2532     {"$v13",    RTYPE_VEC | 13}, \
2533     {"$v14",    RTYPE_VEC | 14}, \
2534     {"$v15",    RTYPE_VEC | 15}, \
2535     {"$v16",    RTYPE_VEC | 16}, \
2536     {"$v17",    RTYPE_VEC | 17}, \
2537     {"$v18",    RTYPE_VEC | 18}, \
2538     {"$v19",    RTYPE_VEC | 19}, \
2539     {"$v20",    RTYPE_VEC | 20}, \
2540     {"$v21",    RTYPE_VEC | 21}, \
2541     {"$v22",    RTYPE_VEC | 22}, \
2542     {"$v23",    RTYPE_VEC | 23}, \
2543     {"$v24",    RTYPE_VEC | 24}, \
2544     {"$v25",    RTYPE_VEC | 25}, \
2545     {"$v26",    RTYPE_VEC | 26}, \
2546     {"$v27",    RTYPE_VEC | 27}, \
2547     {"$v28",    RTYPE_VEC | 28}, \
2548     {"$v29",    RTYPE_VEC | 29}, \
2549     {"$v30",    RTYPE_VEC | 30}, \
2550     {"$v31",    RTYPE_VEC | 31}
2551
2552 #define R5900_I_NAMES \
2553     {"$I",      RTYPE_R5900_I | 0}
2554
2555 #define R5900_Q_NAMES \
2556     {"$Q",      RTYPE_R5900_Q | 0}
2557
2558 #define R5900_R_NAMES \
2559     {"$R",      RTYPE_R5900_R | 0}
2560
2561 #define R5900_ACC_NAMES \
2562     {"$ACC",    RTYPE_R5900_ACC | 0 }
2563
2564 #define MIPS_DSP_ACCUMULATOR_NAMES \
2565     {"$ac0",    RTYPE_ACC | 0}, \
2566     {"$ac1",    RTYPE_ACC | 1}, \
2567     {"$ac2",    RTYPE_ACC | 2}, \
2568     {"$ac3",    RTYPE_ACC | 3}
2569
2570 static const struct regname reg_names[] = {
2571   GENERIC_REGISTER_NUMBERS,
2572   FPU_REGISTER_NAMES,
2573   FPU_CONDITION_CODE_NAMES,
2574   COPROC_CONDITION_CODE_NAMES,
2575
2576   /* The $txx registers depends on the abi,
2577      these will be added later into the symbol table from
2578      one of the tables below once mips_abi is set after 
2579      parsing of arguments from the command line. */
2580   SYMBOLIC_REGISTER_NAMES,
2581
2582   MIPS16_SPECIAL_REGISTER_NAMES,
2583   MDMX_VECTOR_REGISTER_NAMES,
2584   R5900_I_NAMES,
2585   R5900_Q_NAMES,
2586   R5900_R_NAMES,
2587   R5900_ACC_NAMES,
2588   MIPS_DSP_ACCUMULATOR_NAMES,
2589   {0, 0}
2590 };
2591
2592 static const struct regname reg_names_o32[] = {
2593   O32_SYMBOLIC_REGISTER_NAMES,
2594   {0, 0}
2595 };
2596
2597 static const struct regname reg_names_n32n64[] = {
2598   N32N64_SYMBOLIC_REGISTER_NAMES,
2599   {0, 0}
2600 };
2601
2602 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2603    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2604    of these register symbols, return the associated vector register,
2605    otherwise return SYMVAL itself.  */
2606
2607 static unsigned int
2608 mips_prefer_vec_regno (unsigned int symval)
2609 {
2610   if ((symval & -2) == (RTYPE_GP | 2))
2611     return RTYPE_VEC | (symval & 1);
2612   return symval;
2613 }
2614
2615 /* Return true if string [S, E) is a valid register name, storing its
2616    symbol value in *SYMVAL_PTR if so.  */
2617
2618 static bfd_boolean
2619 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2620 {
2621   char save_c;
2622   symbolS *symbol;
2623
2624   /* Terminate name.  */
2625   save_c = *e;
2626   *e = '\0';
2627
2628   /* Look up the name.  */
2629   symbol = symbol_find (s);
2630   *e = save_c;
2631
2632   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2633     return FALSE;
2634
2635   *symval_ptr = S_GET_VALUE (symbol);
2636   return TRUE;
2637 }
2638
2639 /* Return true if the string at *SPTR is a valid register name.  Allow it
2640    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2641    is nonnull.
2642
2643    When returning true, move *SPTR past the register, store the
2644    register's symbol value in *SYMVAL_PTR and the channel mask in
2645    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2646    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2647    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2648
2649 static bfd_boolean
2650 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2651                      unsigned int *channels_ptr)
2652 {
2653   char *s, *e, *m;
2654   const char *q;
2655   unsigned int channels, symval, bit;
2656
2657   /* Find end of name.  */
2658   s = e = *sptr;
2659   if (is_name_beginner (*e))
2660     ++e;
2661   while (is_part_of_name (*e))
2662     ++e;
2663
2664   channels = 0;
2665   if (!mips_parse_register_1 (s, e, &symval))
2666     {
2667       if (!channels_ptr)
2668         return FALSE;
2669
2670       /* Eat characters from the end of the string that are valid
2671          channel suffixes.  The preceding register must be $ACC or
2672          end with a digit, so there is no ambiguity.  */
2673       bit = 1;
2674       m = e;
2675       for (q = "wzyx"; *q; q++, bit <<= 1)
2676         if (m > s && m[-1] == *q)
2677           {
2678             --m;
2679             channels |= bit;
2680           }
2681
2682       if (channels == 0
2683           || !mips_parse_register_1 (s, m, &symval)
2684           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2685         return FALSE;
2686     }
2687
2688   *sptr = e;
2689   *symval_ptr = symval;
2690   if (channels_ptr)
2691     *channels_ptr = channels;
2692   return TRUE;
2693 }
2694
2695 /* Check if SPTR points at a valid register specifier according to TYPES.
2696    If so, then return 1, advance S to consume the specifier and store
2697    the register's number in REGNOP, otherwise return 0.  */
2698
2699 static int
2700 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2701 {
2702   unsigned int regno;
2703
2704   if (mips_parse_register (s, &regno, NULL))
2705     {
2706       if (types & RTYPE_VEC)
2707         regno = mips_prefer_vec_regno (regno);
2708       if (regno & types)
2709         regno &= RNUM_MASK;
2710       else
2711         regno = ~0;
2712     }
2713   else
2714     {
2715       if (types & RWARN)
2716         as_warn (_("unrecognized register name `%s'"), *s);
2717       regno = ~0;
2718     }
2719   if (regnop)
2720     *regnop = regno;
2721   return regno <= RNUM_MASK;
2722 }
2723
2724 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2725    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2726
2727 static char *
2728 mips_parse_vu0_channels (char *s, unsigned int *channels)
2729 {
2730   unsigned int i;
2731
2732   *channels = 0;
2733   for (i = 0; i < 4; i++)
2734     if (*s == "xyzw"[i])
2735       {
2736         *channels |= 1 << (3 - i);
2737         ++s;
2738       }
2739   return s;
2740 }
2741
2742 /* Token types for parsed operand lists.  */
2743 enum mips_operand_token_type {
2744   /* A plain register, e.g. $f2.  */
2745   OT_REG,
2746
2747   /* A 4-bit XYZW channel mask.  */
2748   OT_CHANNELS,
2749
2750   /* An element of a vector, e.g. $v0[1].  */
2751   OT_REG_ELEMENT,
2752
2753   /* A continuous range of registers, e.g. $s0-$s4.  */
2754   OT_REG_RANGE,
2755
2756   /* A (possibly relocated) expression.  */
2757   OT_INTEGER,
2758
2759   /* A floating-point value.  */
2760   OT_FLOAT,
2761
2762   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2763      before OT_REGs.  */
2764   OT_CHAR,
2765
2766   /* A doubled character, either "--" or "++".  */
2767   OT_DOUBLE_CHAR,
2768
2769   /* The end of the operand list.  */
2770   OT_END
2771 };
2772
2773 /* A parsed operand token.  */
2774 struct mips_operand_token
2775 {
2776   /* The type of token.  */
2777   enum mips_operand_token_type type;
2778   union
2779   {
2780     /* The register symbol value for an OT_REG.  */
2781     unsigned int regno;
2782
2783     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2784     unsigned int channels;
2785
2786     /* The register symbol value and index for an OT_REG_ELEMENT.  */
2787     struct {
2788       unsigned int regno;
2789       addressT index;
2790     } reg_element;
2791
2792     /* The two register symbol values involved in an OT_REG_RANGE.  */
2793     struct {
2794       unsigned int regno1;
2795       unsigned int regno2;
2796     } reg_range;
2797
2798     /* The value of an OT_INTEGER.  The value is represented as an
2799        expression and the relocation operators that were applied to
2800        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2801        relocation operators were used.  */
2802     struct {
2803       expressionS value;
2804       bfd_reloc_code_real_type relocs[3];
2805     } integer;
2806
2807     /* The binary data for an OT_FLOAT constant, and the number of bytes
2808        in the constant.  */
2809     struct {
2810       unsigned char data[8];
2811       int length;
2812     } flt;
2813
2814     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2815     char ch;
2816   } u;
2817 };
2818
2819 /* An obstack used to construct lists of mips_operand_tokens.  */
2820 static struct obstack mips_operand_tokens;
2821
2822 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2823
2824 static void
2825 mips_add_token (struct mips_operand_token *token,
2826                 enum mips_operand_token_type type)
2827 {
2828   token->type = type;
2829   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2830 }
2831
2832 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2833    and OT_REG tokens for them if so, and return a pointer to the first
2834    unconsumed character.  Return null otherwise.  */
2835
2836 static char *
2837 mips_parse_base_start (char *s)
2838 {
2839   struct mips_operand_token token;
2840   unsigned int regno, channels;
2841   bfd_boolean decrement_p;
2842
2843   if (*s != '(')
2844     return 0;
2845
2846   ++s;
2847   SKIP_SPACE_TABS (s);
2848
2849   /* Only match "--" as part of a base expression.  In other contexts "--X"
2850      is a double negative.  */
2851   decrement_p = (s[0] == '-' && s[1] == '-');
2852   if (decrement_p)
2853     {
2854       s += 2;
2855       SKIP_SPACE_TABS (s);
2856     }
2857
2858   /* Allow a channel specifier because that leads to better error messages
2859      than treating something like "$vf0x++" as an expression.  */
2860   if (!mips_parse_register (&s, &regno, &channels))
2861     return 0;
2862
2863   token.u.ch = '(';
2864   mips_add_token (&token, OT_CHAR);
2865
2866   if (decrement_p)
2867     {
2868       token.u.ch = '-';
2869       mips_add_token (&token, OT_DOUBLE_CHAR);
2870     }
2871
2872   token.u.regno = regno;
2873   mips_add_token (&token, OT_REG);
2874
2875   if (channels)
2876     {
2877       token.u.channels = channels;
2878       mips_add_token (&token, OT_CHANNELS);
2879     }
2880
2881   /* For consistency, only match "++" as part of base expressions too.  */
2882   SKIP_SPACE_TABS (s);
2883   if (s[0] == '+' && s[1] == '+')
2884     {
2885       s += 2;
2886       token.u.ch = '+';
2887       mips_add_token (&token, OT_DOUBLE_CHAR);
2888     }
2889
2890   return s;
2891 }
2892
2893 /* Parse one or more tokens from S.  Return a pointer to the first
2894    unconsumed character on success.  Return null if an error was found
2895    and store the error text in insn_error.  FLOAT_FORMAT is as for
2896    mips_parse_arguments.  */
2897
2898 static char *
2899 mips_parse_argument_token (char *s, char float_format)
2900 {
2901   char *end, *save_in, *err;
2902   unsigned int regno1, regno2, channels;
2903   struct mips_operand_token token;
2904
2905   /* First look for "($reg", since we want to treat that as an
2906      OT_CHAR and OT_REG rather than an expression.  */
2907   end = mips_parse_base_start (s);
2908   if (end)
2909     return end;
2910
2911   /* Handle other characters that end up as OT_CHARs.  */
2912   if (*s == ')' || *s == ',')
2913     {
2914       token.u.ch = *s;
2915       mips_add_token (&token, OT_CHAR);
2916       ++s;
2917       return s;
2918     }
2919
2920   /* Handle tokens that start with a register.  */
2921   if (mips_parse_register (&s, &regno1, &channels))
2922     {
2923       if (channels)
2924         {
2925           /* A register and a VU0 channel suffix.  */
2926           token.u.regno = regno1;
2927           mips_add_token (&token, OT_REG);
2928
2929           token.u.channels = channels;
2930           mips_add_token (&token, OT_CHANNELS);
2931           return s;
2932         }
2933
2934       SKIP_SPACE_TABS (s);
2935       if (*s == '-')
2936         {
2937           /* A register range.  */
2938           ++s;
2939           SKIP_SPACE_TABS (s);
2940           if (!mips_parse_register (&s, &regno2, NULL))
2941             {
2942               set_insn_error (0, _("invalid register range"));
2943               return 0;
2944             }
2945
2946           token.u.reg_range.regno1 = regno1;
2947           token.u.reg_range.regno2 = regno2;
2948           mips_add_token (&token, OT_REG_RANGE);
2949           return s;
2950         }
2951       else if (*s == '[')
2952         {
2953           /* A vector element.  */
2954           expressionS element;
2955
2956           ++s;
2957           SKIP_SPACE_TABS (s);
2958           my_getExpression (&element, s);
2959           if (element.X_op != O_constant)
2960             {
2961               set_insn_error (0, _("vector element must be constant"));
2962               return 0;
2963             }
2964           s = expr_end;
2965           SKIP_SPACE_TABS (s);
2966           if (*s != ']')
2967             {
2968               set_insn_error (0, _("missing `]'"));
2969               return 0;
2970             }
2971           ++s;
2972
2973           token.u.reg_element.regno = regno1;
2974           token.u.reg_element.index = element.X_add_number;
2975           mips_add_token (&token, OT_REG_ELEMENT);
2976           return s;
2977         }
2978
2979       /* Looks like just a plain register.  */
2980       token.u.regno = regno1;
2981       mips_add_token (&token, OT_REG);
2982       return s;
2983     }
2984
2985   if (float_format)
2986     {
2987       /* First try to treat expressions as floats.  */
2988       save_in = input_line_pointer;
2989       input_line_pointer = s;
2990       err = md_atof (float_format, (char *) token.u.flt.data,
2991                      &token.u.flt.length);
2992       end = input_line_pointer;
2993       input_line_pointer = save_in;
2994       if (err && *err)
2995         {
2996           set_insn_error (0, err);
2997           return 0;
2998         }
2999       if (s != end)
3000         {
3001           mips_add_token (&token, OT_FLOAT);
3002           return end;
3003         }
3004     }
3005
3006   /* Treat everything else as an integer expression.  */
3007   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3008   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3009   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3010   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3011   s = expr_end;
3012   mips_add_token (&token, OT_INTEGER);
3013   return s;
3014 }
3015
3016 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3017    if expressions should be treated as 32-bit floating-point constants,
3018    'd' if they should be treated as 64-bit floating-point constants,
3019    or 0 if they should be treated as integer expressions (the usual case).
3020
3021    Return a list of tokens on success, otherwise return 0.  The caller
3022    must obstack_free the list after use.  */
3023
3024 static struct mips_operand_token *
3025 mips_parse_arguments (char *s, char float_format)
3026 {
3027   struct mips_operand_token token;
3028
3029   SKIP_SPACE_TABS (s);
3030   while (*s)
3031     {
3032       s = mips_parse_argument_token (s, float_format);
3033       if (!s)
3034         {
3035           obstack_free (&mips_operand_tokens,
3036                         obstack_finish (&mips_operand_tokens));
3037           return 0;
3038         }
3039       SKIP_SPACE_TABS (s);
3040     }
3041   mips_add_token (&token, OT_END);
3042   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3043 }
3044
3045 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3046    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3047
3048 static bfd_boolean
3049 is_opcode_valid (const struct mips_opcode *mo)
3050 {
3051   int isa = mips_opts.isa;
3052   int ase = mips_opts.ase;
3053   int fp_s, fp_d;
3054   unsigned int i;
3055
3056   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3057     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3058       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3059         ase |= mips_ases[i].flags64;
3060
3061   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3062     return FALSE;
3063
3064   /* Check whether the instruction or macro requires single-precision or
3065      double-precision floating-point support.  Note that this information is
3066      stored differently in the opcode table for insns and macros.  */
3067   if (mo->pinfo == INSN_MACRO)
3068     {
3069       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3070       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3071     }
3072   else
3073     {
3074       fp_s = mo->pinfo & FP_S;
3075       fp_d = mo->pinfo & FP_D;
3076     }
3077
3078   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3079     return FALSE;
3080
3081   if (fp_s && mips_opts.soft_float)
3082     return FALSE;
3083
3084   return TRUE;
3085 }
3086
3087 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3088    selected ISA and architecture.  */
3089
3090 static bfd_boolean
3091 is_opcode_valid_16 (const struct mips_opcode *mo)
3092 {
3093   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3094 }
3095
3096 /* Return TRUE if the size of the microMIPS opcode MO matches one
3097    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3098
3099 static bfd_boolean
3100 is_size_valid (const struct mips_opcode *mo)
3101 {
3102   if (!mips_opts.micromips)
3103     return TRUE;
3104
3105   if (mips_opts.insn32)
3106     {
3107       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3108         return FALSE;
3109       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3110         return FALSE;
3111     }
3112   if (!forced_insn_length)
3113     return TRUE;
3114   if (mo->pinfo == INSN_MACRO)
3115     return FALSE;
3116   return forced_insn_length == micromips_insn_length (mo);
3117 }
3118
3119 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3120    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3121
3122    We don't accept macros in 16-bit delay slots to avoid a case where
3123    a macro expansion fails because it relies on a preceding 32-bit real
3124    instruction to have matched and does not handle the operands correctly.
3125    The only macros that may expand to 16-bit instructions are JAL that
3126    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3127    and BGT (that likewise cannot be placed in a delay slot) that decay to
3128    a NOP.  In all these cases the macros precede any corresponding real
3129    instruction definitions in the opcode table, so they will match in the
3130    second pass where the size of the delay slot is ignored and therefore
3131    produce correct code.  */
3132
3133 static bfd_boolean
3134 is_delay_slot_valid (const struct mips_opcode *mo)
3135 {
3136   if (!mips_opts.micromips)
3137     return TRUE;
3138
3139   if (mo->pinfo == INSN_MACRO)
3140     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3141   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3142       && micromips_insn_length (mo) != 4)
3143     return FALSE;
3144   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3145       && micromips_insn_length (mo) != 2)
3146     return FALSE;
3147
3148   return TRUE;
3149 }
3150
3151 /* For consistency checking, verify that all bits of OPCODE are specified
3152    either by the match/mask part of the instruction definition, or by the
3153    operand list.  Also build up a list of operands in OPERANDS.
3154
3155    INSN_BITS says which bits of the instruction are significant.
3156    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3157    provides the mips_operand description of each operand.  DECODE_OPERAND
3158    is null for MIPS16 instructions.  */
3159
3160 static int
3161 validate_mips_insn (const struct mips_opcode *opcode,
3162                     unsigned long insn_bits,
3163                     const struct mips_operand *(*decode_operand) (const char *),
3164                     struct mips_operand_array *operands)
3165 {
3166   const char *s;
3167   unsigned long used_bits, doubled, undefined, opno, mask;
3168   const struct mips_operand *operand;
3169
3170   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3171   if ((mask & opcode->match) != opcode->match)
3172     {
3173       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3174               opcode->name, opcode->args);
3175       return 0;
3176     }
3177   used_bits = 0;
3178   opno = 0;
3179   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3180     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3181   for (s = opcode->args; *s; ++s)
3182     switch (*s)
3183       {
3184       case ',':
3185       case '(':
3186       case ')':
3187         break;
3188
3189       case '#':
3190         s++;
3191         break;
3192
3193       default:
3194         if (!decode_operand)
3195           operand = decode_mips16_operand (*s, FALSE);
3196         else
3197           operand = decode_operand (s);
3198         if (!operand && opcode->pinfo != INSN_MACRO)
3199           {
3200             as_bad (_("internal: unknown operand type: %s %s"),
3201                     opcode->name, opcode->args);
3202             return 0;
3203           }
3204         gas_assert (opno < MAX_OPERANDS);
3205         operands->operand[opno] = operand;
3206         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3207           {
3208             used_bits = mips_insert_operand (operand, used_bits, -1);
3209             if (operand->type == OP_MDMX_IMM_REG)
3210               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3211                  has separate entries for each format.  */
3212               used_bits &= ~(1 << (operand->lsb + 5));
3213             if (operand->type == OP_ENTRY_EXIT_LIST)
3214               used_bits &= ~(mask & 0x700);
3215           }
3216         /* Skip prefix characters.  */
3217         if (decode_operand && (*s == '+' || *s == 'm'))
3218           ++s;
3219         opno += 1;
3220         break;
3221       }
3222   doubled = used_bits & mask & insn_bits;
3223   if (doubled)
3224     {
3225       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3226                 " %s %s"), doubled, opcode->name, opcode->args);
3227       return 0;
3228     }
3229   used_bits |= mask;
3230   undefined = ~used_bits & insn_bits;
3231   if (opcode->pinfo != INSN_MACRO && undefined)
3232     {
3233       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3234               undefined, opcode->name, opcode->args);
3235       return 0;
3236     }
3237   used_bits &= ~insn_bits;
3238   if (used_bits)
3239     {
3240       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3241               used_bits, opcode->name, opcode->args);
3242       return 0;
3243     }
3244   return 1;
3245 }
3246
3247 /* The MIPS16 version of validate_mips_insn.  */
3248
3249 static int
3250 validate_mips16_insn (const struct mips_opcode *opcode,
3251                       struct mips_operand_array *operands)
3252 {
3253   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3254     {
3255       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3256          instruction.  Use TMP to describe the full instruction.  */
3257       struct mips_opcode tmp;
3258
3259       tmp = *opcode;
3260       tmp.match <<= 16;
3261       tmp.mask <<= 16;
3262       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3263     }
3264   return validate_mips_insn (opcode, 0xffff, 0, operands);
3265 }
3266
3267 /* The microMIPS version of validate_mips_insn.  */
3268
3269 static int
3270 validate_micromips_insn (const struct mips_opcode *opc,
3271                          struct mips_operand_array *operands)
3272 {
3273   unsigned long insn_bits;
3274   unsigned long major;
3275   unsigned int length;
3276
3277   if (opc->pinfo == INSN_MACRO)
3278     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3279                                operands);
3280
3281   length = micromips_insn_length (opc);
3282   if (length != 2 && length != 4)
3283     {
3284       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3285                 "%s %s"), length, opc->name, opc->args);
3286       return 0;
3287     }
3288   major = opc->match >> (10 + 8 * (length - 2));
3289   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3290       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3291     {
3292       as_bad (_("internal error: bad microMIPS opcode "
3293                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3294       return 0;
3295     }
3296
3297   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3298   insn_bits = 1 << 4 * length;
3299   insn_bits <<= 4 * length;
3300   insn_bits -= 1;
3301   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3302                              operands);
3303 }
3304
3305 /* This function is called once, at assembler startup time.  It should set up
3306    all the tables, etc. that the MD part of the assembler will need.  */
3307
3308 void
3309 md_begin (void)
3310 {
3311   const char *retval = NULL;
3312   int i = 0;
3313   int broken = 0;
3314
3315   if (mips_pic != NO_PIC)
3316     {
3317       if (g_switch_seen && g_switch_value != 0)
3318         as_bad (_("-G may not be used in position-independent code"));
3319       g_switch_value = 0;
3320     }
3321
3322   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3323     as_warn (_("could not set architecture and machine"));
3324
3325   op_hash = hash_new ();
3326
3327   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3328   for (i = 0; i < NUMOPCODES;)
3329     {
3330       const char *name = mips_opcodes[i].name;
3331
3332       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3333       if (retval != NULL)
3334         {
3335           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3336                    mips_opcodes[i].name, retval);
3337           /* Probably a memory allocation problem?  Give up now.  */
3338           as_fatal (_("broken assembler, no assembly attempted"));
3339         }
3340       do
3341         {
3342           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3343                                    decode_mips_operand, &mips_operands[i]))
3344             broken = 1;
3345           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3346             {
3347               create_insn (&nop_insn, mips_opcodes + i);
3348               if (mips_fix_loongson2f_nop)
3349                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3350               nop_insn.fixed_p = 1;
3351             }
3352           ++i;
3353         }
3354       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3355     }
3356
3357   mips16_op_hash = hash_new ();
3358   mips16_operands = XCNEWVEC (struct mips_operand_array,
3359                               bfd_mips16_num_opcodes);
3360
3361   i = 0;
3362   while (i < bfd_mips16_num_opcodes)
3363     {
3364       const char *name = mips16_opcodes[i].name;
3365
3366       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3367       if (retval != NULL)
3368         as_fatal (_("internal: can't hash `%s': %s"),
3369                   mips16_opcodes[i].name, retval);
3370       do
3371         {
3372           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3373             broken = 1;
3374           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3375             {
3376               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3377               mips16_nop_insn.fixed_p = 1;
3378             }
3379           ++i;
3380         }
3381       while (i < bfd_mips16_num_opcodes
3382              && strcmp (mips16_opcodes[i].name, name) == 0);
3383     }
3384
3385   micromips_op_hash = hash_new ();
3386   micromips_operands = XCNEWVEC (struct mips_operand_array,
3387                                  bfd_micromips_num_opcodes);
3388
3389   i = 0;
3390   while (i < bfd_micromips_num_opcodes)
3391     {
3392       const char *name = micromips_opcodes[i].name;
3393
3394       retval = hash_insert (micromips_op_hash, name,
3395                             (void *) &micromips_opcodes[i]);
3396       if (retval != NULL)
3397         as_fatal (_("internal: can't hash `%s': %s"),
3398                   micromips_opcodes[i].name, retval);
3399       do
3400         {
3401           struct mips_cl_insn *micromips_nop_insn;
3402
3403           if (!validate_micromips_insn (&micromips_opcodes[i],
3404                                         &micromips_operands[i]))
3405             broken = 1;
3406
3407           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3408             {
3409               if (micromips_insn_length (micromips_opcodes + i) == 2)
3410                 micromips_nop_insn = &micromips_nop16_insn;
3411               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3412                 micromips_nop_insn = &micromips_nop32_insn;
3413               else
3414                 continue;
3415
3416               if (micromips_nop_insn->insn_mo == NULL
3417                   && strcmp (name, "nop") == 0)
3418                 {
3419                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3420                   micromips_nop_insn->fixed_p = 1;
3421                 }
3422             }
3423         }
3424       while (++i < bfd_micromips_num_opcodes
3425              && strcmp (micromips_opcodes[i].name, name) == 0);
3426     }
3427
3428   if (broken)
3429     as_fatal (_("broken assembler, no assembly attempted"));
3430
3431   /* We add all the general register names to the symbol table.  This
3432      helps us detect invalid uses of them.  */
3433   for (i = 0; reg_names[i].name; i++) 
3434     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3435                                      reg_names[i].num, /* & RNUM_MASK, */
3436                                      &zero_address_frag));
3437   if (HAVE_NEWABI)
3438     for (i = 0; reg_names_n32n64[i].name; i++) 
3439       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3440                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3441                                        &zero_address_frag));
3442   else
3443     for (i = 0; reg_names_o32[i].name; i++) 
3444       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3445                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3446                                        &zero_address_frag));
3447
3448   for (i = 0; i < 32; i++)
3449     {
3450       char regname[7];
3451
3452       /* R5900 VU0 floating-point register.  */
3453       regname[sizeof (rename) - 1] = 0;
3454       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3455       symbol_table_insert (symbol_new (regname, reg_section,
3456                                        RTYPE_VF | i, &zero_address_frag));
3457
3458       /* R5900 VU0 integer register.  */
3459       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3460       symbol_table_insert (symbol_new (regname, reg_section,
3461                                        RTYPE_VI | i, &zero_address_frag));
3462
3463     }
3464
3465   obstack_init (&mips_operand_tokens);
3466
3467   mips_no_prev_insn ();
3468
3469   mips_gprmask = 0;
3470   mips_cprmask[0] = 0;
3471   mips_cprmask[1] = 0;
3472   mips_cprmask[2] = 0;
3473   mips_cprmask[3] = 0;
3474
3475   /* set the default alignment for the text section (2**2) */
3476   record_alignment (text_section, 2);
3477
3478   bfd_set_gp_size (stdoutput, g_switch_value);
3479
3480   /* On a native system other than VxWorks, sections must be aligned
3481      to 16 byte boundaries.  When configured for an embedded ELF
3482      target, we don't bother.  */
3483   if (strncmp (TARGET_OS, "elf", 3) != 0
3484       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3485     {
3486       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3487       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3488       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3489     }
3490
3491   /* Create a .reginfo section for register masks and a .mdebug
3492      section for debugging information.  */
3493   {
3494     segT seg;
3495     subsegT subseg;
3496     flagword flags;
3497     segT sec;
3498
3499     seg = now_seg;
3500     subseg = now_subseg;
3501
3502     /* The ABI says this section should be loaded so that the
3503        running program can access it.  However, we don't load it
3504        if we are configured for an embedded target */
3505     flags = SEC_READONLY | SEC_DATA;
3506     if (strncmp (TARGET_OS, "elf", 3) != 0)
3507       flags |= SEC_ALLOC | SEC_LOAD;
3508
3509     if (mips_abi != N64_ABI)
3510       {
3511         sec = subseg_new (".reginfo", (subsegT) 0);
3512
3513         bfd_set_section_flags (stdoutput, sec, flags);
3514         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3515
3516         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3517       }
3518     else
3519       {
3520         /* The 64-bit ABI uses a .MIPS.options section rather than
3521            .reginfo section.  */
3522         sec = subseg_new (".MIPS.options", (subsegT) 0);
3523         bfd_set_section_flags (stdoutput, sec, flags);
3524         bfd_set_section_alignment (stdoutput, sec, 3);
3525
3526         /* Set up the option header.  */
3527         {
3528           Elf_Internal_Options opthdr;
3529           char *f;
3530
3531           opthdr.kind = ODK_REGINFO;
3532           opthdr.size = (sizeof (Elf_External_Options)
3533                          + sizeof (Elf64_External_RegInfo));
3534           opthdr.section = 0;
3535           opthdr.info = 0;
3536           f = frag_more (sizeof (Elf_External_Options));
3537           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3538                                          (Elf_External_Options *) f);
3539
3540           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3541         }
3542       }
3543
3544     if (ECOFF_DEBUGGING)
3545       {
3546         sec = subseg_new (".mdebug", (subsegT) 0);
3547         (void) bfd_set_section_flags (stdoutput, sec,
3548                                       SEC_HAS_CONTENTS | SEC_READONLY);
3549         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3550       }
3551     else if (mips_flag_pdr)
3552       {
3553         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3554         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3555                                       SEC_READONLY | SEC_RELOC
3556                                       | SEC_DEBUGGING);
3557         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3558       }
3559
3560     subseg_set (seg, subseg);
3561   }
3562
3563   if (! ECOFF_DEBUGGING)
3564     md_obj_begin ();
3565
3566   if (mips_fix_vr4120)
3567     init_vr4120_conflicts ();
3568 }
3569
3570 void
3571 md_mips_end (void)
3572 {
3573   mips_emit_delays ();
3574   if (! ECOFF_DEBUGGING)
3575     md_obj_end ();
3576 }
3577
3578 void
3579 md_assemble (char *str)
3580 {
3581   struct mips_cl_insn insn;
3582   bfd_reloc_code_real_type unused_reloc[3]
3583     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3584
3585   imm_expr.X_op = O_absent;
3586   offset_expr.X_op = O_absent;
3587   offset_reloc[0] = BFD_RELOC_UNUSED;
3588   offset_reloc[1] = BFD_RELOC_UNUSED;
3589   offset_reloc[2] = BFD_RELOC_UNUSED;
3590
3591   mips_mark_labels ();
3592   mips_assembling_insn = TRUE;
3593   clear_insn_error ();
3594
3595   if (mips_opts.mips16)
3596     mips16_ip (str, &insn);
3597   else
3598     {
3599       mips_ip (str, &insn);
3600       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3601             str, insn.insn_opcode));
3602     }
3603
3604   if (insn_error.msg)
3605     report_insn_error (str);
3606   else if (insn.insn_mo->pinfo == INSN_MACRO)
3607     {
3608       macro_start ();
3609       if (mips_opts.mips16)
3610         mips16_macro (&insn);
3611       else
3612         macro (&insn, str);
3613       macro_end ();
3614     }
3615   else
3616     {
3617       if (offset_expr.X_op != O_absent)
3618         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3619       else
3620         append_insn (&insn, NULL, unused_reloc, FALSE);
3621     }
3622
3623   mips_assembling_insn = FALSE;
3624 }
3625
3626 /* Convenience functions for abstracting away the differences between
3627    MIPS16 and non-MIPS16 relocations.  */
3628
3629 static inline bfd_boolean
3630 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3631 {
3632   switch (reloc)
3633     {
3634     case BFD_RELOC_MIPS16_JMP:
3635     case BFD_RELOC_MIPS16_GPREL:
3636     case BFD_RELOC_MIPS16_GOT16:
3637     case BFD_RELOC_MIPS16_CALL16:
3638     case BFD_RELOC_MIPS16_HI16_S:
3639     case BFD_RELOC_MIPS16_HI16:
3640     case BFD_RELOC_MIPS16_LO16:
3641       return TRUE;
3642
3643     default:
3644       return FALSE;
3645     }
3646 }
3647
3648 static inline bfd_boolean
3649 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3650 {
3651   switch (reloc)
3652     {
3653     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3654     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3655     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3656     case BFD_RELOC_MICROMIPS_GPREL16:
3657     case BFD_RELOC_MICROMIPS_JMP:
3658     case BFD_RELOC_MICROMIPS_HI16:
3659     case BFD_RELOC_MICROMIPS_HI16_S:
3660     case BFD_RELOC_MICROMIPS_LO16:
3661     case BFD_RELOC_MICROMIPS_LITERAL:
3662     case BFD_RELOC_MICROMIPS_GOT16:
3663     case BFD_RELOC_MICROMIPS_CALL16:
3664     case BFD_RELOC_MICROMIPS_GOT_HI16:
3665     case BFD_RELOC_MICROMIPS_GOT_LO16:
3666     case BFD_RELOC_MICROMIPS_CALL_HI16:
3667     case BFD_RELOC_MICROMIPS_CALL_LO16:
3668     case BFD_RELOC_MICROMIPS_SUB:
3669     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3670     case BFD_RELOC_MICROMIPS_GOT_OFST:
3671     case BFD_RELOC_MICROMIPS_GOT_DISP:
3672     case BFD_RELOC_MICROMIPS_HIGHEST:
3673     case BFD_RELOC_MICROMIPS_HIGHER:
3674     case BFD_RELOC_MICROMIPS_SCN_DISP:
3675     case BFD_RELOC_MICROMIPS_JALR:
3676       return TRUE;
3677
3678     default:
3679       return FALSE;
3680     }
3681 }
3682
3683 static inline bfd_boolean
3684 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3685 {
3686   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3687 }
3688
3689 static inline bfd_boolean
3690 got16_reloc_p (bfd_reloc_code_real_type reloc)
3691 {
3692   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3693           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3694 }
3695
3696 static inline bfd_boolean
3697 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3698 {
3699   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3700           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3701 }
3702
3703 static inline bfd_boolean
3704 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3705 {
3706   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3707           || reloc == BFD_RELOC_MICROMIPS_LO16);
3708 }
3709
3710 static inline bfd_boolean
3711 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3712 {
3713   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3714 }
3715
3716 static inline bfd_boolean
3717 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3718 {
3719   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3720           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3721 }
3722
3723 /* Return true if RELOC is a PC-relative relocation that does not have
3724    full address range.  */
3725
3726 static inline bfd_boolean
3727 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3728 {
3729   switch (reloc)
3730     {
3731     case BFD_RELOC_16_PCREL_S2:
3732     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3733     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3734     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3735       return TRUE;
3736
3737     case BFD_RELOC_32_PCREL:
3738       return HAVE_64BIT_ADDRESSES;
3739
3740     default:
3741       return FALSE;
3742     }
3743 }
3744
3745 /* Return true if the given relocation might need a matching %lo().
3746    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3747    need a matching %lo() when applied to local symbols.  */
3748
3749 static inline bfd_boolean
3750 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3751 {
3752   return (HAVE_IN_PLACE_ADDENDS
3753           && (hi16_reloc_p (reloc)
3754               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3755                  all GOT16 relocations evaluate to "G".  */
3756               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3757 }
3758
3759 /* Return the type of %lo() reloc needed by RELOC, given that
3760    reloc_needs_lo_p.  */
3761
3762 static inline bfd_reloc_code_real_type
3763 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3764 {
3765   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3766           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3767              : BFD_RELOC_LO16));
3768 }
3769
3770 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3771    relocation.  */
3772
3773 static inline bfd_boolean
3774 fixup_has_matching_lo_p (fixS *fixp)
3775 {
3776   return (fixp->fx_next != NULL
3777           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3778           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3779           && fixp->fx_offset == fixp->fx_next->fx_offset);
3780 }
3781
3782 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3783    says whether the labels refer to text or data.  */
3784
3785 static void
3786 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3787 {
3788   struct insn_label_list *l;
3789   valueT val;
3790
3791   for (l = labels; l != NULL; l = l->next)
3792     {
3793       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3794       symbol_set_frag (l->label, frag_now);
3795       val = (valueT) frag_now_fix ();
3796       /* MIPS16/microMIPS text labels are stored as odd.  */
3797       if (text_p && HAVE_CODE_COMPRESSION)
3798         ++val;
3799       S_SET_VALUE (l->label, val);
3800     }
3801 }
3802
3803 /* Move all labels in insn_labels to the current insertion point
3804    and treat them as text labels.  */
3805
3806 static void
3807 mips_move_text_labels (void)
3808 {
3809   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3810 }
3811
3812 static bfd_boolean
3813 s_is_linkonce (symbolS *sym, segT from_seg)
3814 {
3815   bfd_boolean linkonce = FALSE;
3816   segT symseg = S_GET_SEGMENT (sym);
3817
3818   if (symseg != from_seg && !S_IS_LOCAL (sym))
3819     {
3820       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3821         linkonce = TRUE;
3822       /* The GNU toolchain uses an extension for ELF: a section
3823          beginning with the magic string .gnu.linkonce is a
3824          linkonce section.  */
3825       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3826                    sizeof ".gnu.linkonce" - 1) == 0)
3827         linkonce = TRUE;
3828     }
3829   return linkonce;
3830 }
3831
3832 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3833    linker to handle them specially, such as generating jalx instructions
3834    when needed.  We also make them odd for the duration of the assembly,
3835    in order to generate the right sort of code.  We will make them even
3836    in the adjust_symtab routine, while leaving them marked.  This is
3837    convenient for the debugger and the disassembler.  The linker knows
3838    to make them odd again.  */
3839
3840 static void
3841 mips_compressed_mark_label (symbolS *label)
3842 {
3843   gas_assert (HAVE_CODE_COMPRESSION);
3844
3845   if (mips_opts.mips16)
3846     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3847   else
3848     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3849   if ((S_GET_VALUE (label) & 1) == 0
3850       /* Don't adjust the address if the label is global or weak, or
3851          in a link-once section, since we'll be emitting symbol reloc
3852          references to it which will be patched up by the linker, and
3853          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3854       && !S_IS_WEAK (label)
3855       && !S_IS_EXTERNAL (label)
3856       && !s_is_linkonce (label, now_seg))
3857     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3858 }
3859
3860 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3861
3862 static void
3863 mips_compressed_mark_labels (void)
3864 {
3865   struct insn_label_list *l;
3866
3867   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3868     mips_compressed_mark_label (l->label);
3869 }
3870
3871 /* End the current frag.  Make it a variant frag and record the
3872    relaxation info.  */
3873
3874 static void
3875 relax_close_frag (void)
3876 {
3877   mips_macro_warning.first_frag = frag_now;
3878   frag_var (rs_machine_dependent, 0, 0,
3879             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3880             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3881
3882   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3883   mips_relax.first_fixup = 0;
3884 }
3885
3886 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3887    See the comment above RELAX_ENCODE for more details.  */
3888
3889 static void
3890 relax_start (symbolS *symbol)
3891 {
3892   gas_assert (mips_relax.sequence == 0);
3893   mips_relax.sequence = 1;
3894   mips_relax.symbol = symbol;
3895 }
3896
3897 /* Start generating the second version of a relaxable sequence.
3898    See the comment above RELAX_ENCODE for more details.  */
3899
3900 static void
3901 relax_switch (void)
3902 {
3903   gas_assert (mips_relax.sequence == 1);
3904   mips_relax.sequence = 2;
3905 }
3906
3907 /* End the current relaxable sequence.  */
3908
3909 static void
3910 relax_end (void)
3911 {
3912   gas_assert (mips_relax.sequence == 2);
3913   relax_close_frag ();
3914   mips_relax.sequence = 0;
3915 }
3916
3917 /* Return true if IP is a delayed branch or jump.  */
3918
3919 static inline bfd_boolean
3920 delayed_branch_p (const struct mips_cl_insn *ip)
3921 {
3922   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3923                                 | INSN_COND_BRANCH_DELAY
3924                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3925 }
3926
3927 /* Return true if IP is a compact branch or jump.  */
3928
3929 static inline bfd_boolean
3930 compact_branch_p (const struct mips_cl_insn *ip)
3931 {
3932   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3933                                  | INSN2_COND_BRANCH)) != 0;
3934 }
3935
3936 /* Return true if IP is an unconditional branch or jump.  */
3937
3938 static inline bfd_boolean
3939 uncond_branch_p (const struct mips_cl_insn *ip)
3940 {
3941   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3942           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3943 }
3944
3945 /* Return true if IP is a branch-likely instruction.  */
3946
3947 static inline bfd_boolean
3948 branch_likely_p (const struct mips_cl_insn *ip)
3949 {
3950   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3951 }
3952
3953 /* Return the type of nop that should be used to fill the delay slot
3954    of delayed branch IP.  */
3955
3956 static struct mips_cl_insn *
3957 get_delay_slot_nop (const struct mips_cl_insn *ip)
3958 {
3959   if (mips_opts.micromips
3960       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3961     return &micromips_nop32_insn;
3962   return NOP_INSN;
3963 }
3964
3965 /* Return a mask that has bit N set if OPCODE reads the register(s)
3966    in operand N.  */
3967
3968 static unsigned int
3969 insn_read_mask (const struct mips_opcode *opcode)
3970 {
3971   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
3972 }
3973
3974 /* Return a mask that has bit N set if OPCODE writes to the register(s)
3975    in operand N.  */
3976
3977 static unsigned int
3978 insn_write_mask (const struct mips_opcode *opcode)
3979 {
3980   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
3981 }
3982
3983 /* Return a mask of the registers specified by operand OPERAND of INSN.
3984    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
3985    is set.  */
3986
3987 static unsigned int
3988 operand_reg_mask (const struct mips_cl_insn *insn,
3989                   const struct mips_operand *operand,
3990                   unsigned int type_mask)
3991 {
3992   unsigned int uval, vsel;
3993
3994   switch (operand->type)
3995     {
3996     case OP_INT:
3997     case OP_MAPPED_INT:
3998     case OP_MSB:
3999     case OP_PCREL:
4000     case OP_PERF_REG:
4001     case OP_ADDIUSP_INT:
4002     case OP_ENTRY_EXIT_LIST:
4003     case OP_REPEAT_DEST_REG:
4004     case OP_REPEAT_PREV_REG:
4005     case OP_PC:
4006     case OP_VU0_SUFFIX:
4007     case OP_VU0_MATCH_SUFFIX:
4008       abort ();
4009
4010     case OP_REG:
4011     case OP_OPTIONAL_REG:
4012       {
4013         const struct mips_reg_operand *reg_op;
4014
4015         reg_op = (const struct mips_reg_operand *) operand;
4016         if (!(type_mask & (1 << reg_op->reg_type)))
4017           return 0;
4018         uval = insn_extract_operand (insn, operand);
4019         return 1 << mips_decode_reg_operand (reg_op, uval);
4020       }
4021
4022     case OP_REG_PAIR:
4023       {
4024         const struct mips_reg_pair_operand *pair_op;
4025
4026         pair_op = (const struct mips_reg_pair_operand *) operand;
4027         if (!(type_mask & (1 << pair_op->reg_type)))
4028           return 0;
4029         uval = insn_extract_operand (insn, operand);
4030         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4031       }
4032
4033     case OP_CLO_CLZ_DEST:
4034       if (!(type_mask & (1 << OP_REG_GP)))
4035         return 0;
4036       uval = insn_extract_operand (insn, operand);
4037       return (1 << (uval & 31)) | (1 << (uval >> 5));
4038
4039     case OP_LWM_SWM_LIST:
4040       abort ();
4041
4042     case OP_SAVE_RESTORE_LIST:
4043       abort ();
4044
4045     case OP_MDMX_IMM_REG:
4046       if (!(type_mask & (1 << OP_REG_VEC)))
4047         return 0;
4048       uval = insn_extract_operand (insn, operand);
4049       vsel = uval >> 5;
4050       if ((vsel & 0x18) == 0x18)
4051         return 0;
4052       return 1 << (uval & 31);
4053     }
4054   abort ();
4055 }
4056
4057 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4058    where bit N of OPNO_MASK is set if operand N should be included.
4059    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4060    is set.  */
4061
4062 static unsigned int
4063 insn_reg_mask (const struct mips_cl_insn *insn,
4064                unsigned int type_mask, unsigned int opno_mask)
4065 {
4066   unsigned int opno, reg_mask;
4067
4068   opno = 0;
4069   reg_mask = 0;
4070   while (opno_mask != 0)
4071     {
4072       if (opno_mask & 1)
4073         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4074       opno_mask >>= 1;
4075       opno += 1;
4076     }
4077   return reg_mask;
4078 }
4079
4080 /* Return the mask of core registers that IP reads.  */
4081
4082 static unsigned int
4083 gpr_read_mask (const struct mips_cl_insn *ip)
4084 {
4085   unsigned long pinfo, pinfo2;
4086   unsigned int mask;
4087
4088   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4089   pinfo = ip->insn_mo->pinfo;
4090   pinfo2 = ip->insn_mo->pinfo2;
4091   if (pinfo & INSN_UDI)
4092     {
4093       /* UDI instructions have traditionally been assumed to read RS
4094          and RT.  */
4095       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4096       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4097     }
4098   if (pinfo & INSN_READ_GPR_24)
4099     mask |= 1 << 24;
4100   if (pinfo2 & INSN2_READ_GPR_16)
4101     mask |= 1 << 16;
4102   if (pinfo2 & INSN2_READ_SP)
4103     mask |= 1 << SP;
4104   if (pinfo2 & INSN2_READ_GPR_31)
4105     mask |= 1 << 31;
4106   /* Don't include register 0.  */
4107   return mask & ~1;
4108 }
4109
4110 /* Return the mask of core registers that IP writes.  */
4111
4112 static unsigned int
4113 gpr_write_mask (const struct mips_cl_insn *ip)
4114 {
4115   unsigned long pinfo, pinfo2;
4116   unsigned int mask;
4117
4118   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4119   pinfo = ip->insn_mo->pinfo;
4120   pinfo2 = ip->insn_mo->pinfo2;
4121   if (pinfo & INSN_WRITE_GPR_24)
4122     mask |= 1 << 24;
4123   if (pinfo & INSN_WRITE_GPR_31)
4124     mask |= 1 << 31;
4125   if (pinfo & INSN_UDI)
4126     /* UDI instructions have traditionally been assumed to write to RD.  */
4127     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4128   if (pinfo2 & INSN2_WRITE_SP)
4129     mask |= 1 << SP;
4130   /* Don't include register 0.  */
4131   return mask & ~1;
4132 }
4133
4134 /* Return the mask of floating-point registers that IP reads.  */
4135
4136 static unsigned int
4137 fpr_read_mask (const struct mips_cl_insn *ip)
4138 {
4139   unsigned long pinfo;
4140   unsigned int mask;
4141
4142   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4143                         insn_read_mask (ip->insn_mo));
4144   pinfo = ip->insn_mo->pinfo;
4145   /* Conservatively treat all operands to an FP_D instruction are doubles.
4146      (This is overly pessimistic for things like cvt.d.s.)  */
4147   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4148     mask |= mask << 1;
4149   return mask;
4150 }
4151
4152 /* Return the mask of floating-point registers that IP writes.  */
4153
4154 static unsigned int
4155 fpr_write_mask (const struct mips_cl_insn *ip)
4156 {
4157   unsigned long pinfo;
4158   unsigned int mask;
4159
4160   mask = insn_reg_mask (ip, (1 << OP_REG_FP) | (1 << OP_REG_VEC),
4161                         insn_write_mask (ip->insn_mo));
4162   pinfo = ip->insn_mo->pinfo;
4163   /* Conservatively treat all operands to an FP_D instruction are doubles.
4164      (This is overly pessimistic for things like cvt.s.d.)  */
4165   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4166     mask |= mask << 1;
4167   return mask;
4168 }
4169
4170 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4171    Check whether that is allowed.  */
4172
4173 static bfd_boolean
4174 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4175 {
4176   const char *s = insn->name;
4177
4178   if (insn->pinfo == INSN_MACRO)
4179     /* Let a macro pass, we'll catch it later when it is expanded.  */
4180     return TRUE;
4181
4182   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4183     {
4184       /* Allow odd registers for single-precision ops.  */
4185       switch (insn->pinfo & (FP_S | FP_D))
4186         {
4187         case FP_S:
4188         case 0:
4189           return TRUE;
4190         case FP_D:
4191           return FALSE;
4192         default:
4193           break;
4194         }
4195
4196       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4197       s = strchr (insn->name, '.');
4198       if (s != NULL && opnum == 2)
4199         s = strchr (s + 1, '.');
4200       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4201     }
4202
4203   /* Single-precision coprocessor loads and moves are OK too.  */
4204   if ((insn->pinfo & FP_S)
4205       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4206                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4207     return TRUE;
4208
4209   return FALSE;
4210 }
4211
4212 /* Information about an instruction argument that we're trying to match.  */
4213 struct mips_arg_info
4214 {
4215   /* The instruction so far.  */
4216   struct mips_cl_insn *insn;
4217
4218   /* The first unconsumed operand token.  */
4219   struct mips_operand_token *token;
4220
4221   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4222   int opnum;
4223
4224   /* The 1-based argument number, for error reporting.  This does not
4225      count elided optional registers, etc..  */
4226   int argnum;
4227
4228   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4229   unsigned int last_regno;
4230
4231   /* If the first operand was an OP_REG, this is the register that it
4232      specified, otherwise it is ILLEGAL_REG.  */
4233   unsigned int dest_regno;
4234
4235   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4236      where it gives the lsb position.  */
4237   unsigned int last_op_int;
4238
4239   /* If true, match routines should assume that no later instruction
4240      alternative matches and should therefore be as accomodating as
4241      possible.  Match routines should not report errors if something
4242      is only invalid for !LAX_MATCH.  */
4243   bfd_boolean lax_match;
4244
4245   /* True if a reference to the current AT register was seen.  */
4246   bfd_boolean seen_at;
4247 };
4248
4249 /* Record that the argument is out of range.  */
4250
4251 static void
4252 match_out_of_range (struct mips_arg_info *arg)
4253 {
4254   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4255 }
4256
4257 /* Record that the argument isn't constant but needs to be.  */
4258
4259 static void
4260 match_not_constant (struct mips_arg_info *arg)
4261 {
4262   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4263                     arg->argnum);
4264 }
4265
4266 /* Try to match an OT_CHAR token for character CH.  Consume the token
4267    and return true on success, otherwise return false.  */
4268
4269 static bfd_boolean
4270 match_char (struct mips_arg_info *arg, char ch)
4271 {
4272   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4273     {
4274       ++arg->token;
4275       if (ch == ',')
4276         arg->argnum += 1;
4277       return TRUE;
4278     }
4279   return FALSE;
4280 }
4281
4282 /* Try to get an expression from the next tokens in ARG.  Consume the
4283    tokens and return true on success, storing the expression value in
4284    VALUE and relocation types in R.  */
4285
4286 static bfd_boolean
4287 match_expression (struct mips_arg_info *arg, expressionS *value,
4288                   bfd_reloc_code_real_type *r)
4289 {
4290   /* If the next token is a '(' that was parsed as being part of a base
4291      expression, assume we have an elided offset.  The later match will fail
4292      if this turns out to be wrong.  */
4293   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4294     {
4295       value->X_op = O_constant;
4296       value->X_add_number = 0;
4297       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4298       return TRUE;
4299     }
4300
4301   /* Reject register-based expressions such as "0+$2" and "(($2))".
4302      For plain registers the default error seems more appropriate.  */
4303   if (arg->token->type == OT_INTEGER
4304       && arg->token->u.integer.value.X_op == O_register)
4305     {
4306       set_insn_error (arg->argnum, _("register value used as expression"));
4307       return FALSE;
4308     }
4309
4310   if (arg->token->type == OT_INTEGER)
4311     {
4312       *value = arg->token->u.integer.value;
4313       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4314       ++arg->token;
4315       return TRUE;
4316     }
4317
4318   set_insn_error_i
4319     (arg->argnum, _("operand %d must be an immediate expression"),
4320      arg->argnum);
4321   return FALSE;
4322 }
4323
4324 /* Try to get a constant expression from the next tokens in ARG.  Consume
4325    the tokens and return return true on success, storing the constant value
4326    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4327    error.  */
4328
4329 static bfd_boolean
4330 match_const_int (struct mips_arg_info *arg, offsetT *value)
4331 {
4332   expressionS ex;
4333   bfd_reloc_code_real_type r[3];
4334
4335   if (!match_expression (arg, &ex, r))
4336     return FALSE;
4337
4338   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4339     *value = ex.X_add_number;
4340   else
4341     {
4342       match_not_constant (arg);
4343       return FALSE;
4344     }
4345   return TRUE;
4346 }
4347
4348 /* Return the RTYPE_* flags for a register operand of type TYPE that
4349    appears in instruction OPCODE.  */
4350
4351 static unsigned int
4352 convert_reg_type (const struct mips_opcode *opcode,
4353                   enum mips_reg_operand_type type)
4354 {
4355   switch (type)
4356     {
4357     case OP_REG_GP:
4358       return RTYPE_NUM | RTYPE_GP;
4359
4360     case OP_REG_FP:
4361       /* Allow vector register names for MDMX if the instruction is a 64-bit
4362          FPR load, store or move (including moves to and from GPRs).  */
4363       if ((mips_opts.ase & ASE_MDMX)
4364           && (opcode->pinfo & FP_D)
4365           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4366                                | INSN_COPROC_MEMORY_DELAY
4367                                | INSN_LOAD_COPROC_DELAY
4368                                | INSN_LOAD_MEMORY_DELAY
4369                                | INSN_STORE_MEMORY)))
4370         return RTYPE_FPU | RTYPE_VEC;
4371       return RTYPE_FPU;
4372
4373     case OP_REG_CCC:
4374       if (opcode->pinfo & (FP_D | FP_S))
4375         return RTYPE_CCC | RTYPE_FCC;
4376       return RTYPE_CCC;
4377
4378     case OP_REG_VEC:
4379       if (opcode->membership & INSN_5400)
4380         return RTYPE_FPU;
4381       return RTYPE_FPU | RTYPE_VEC;
4382
4383     case OP_REG_ACC:
4384       return RTYPE_ACC;
4385
4386     case OP_REG_COPRO:
4387       if (opcode->name[strlen (opcode->name) - 1] == '0')
4388         return RTYPE_NUM | RTYPE_CP0;
4389       return RTYPE_NUM;
4390
4391     case OP_REG_HW:
4392       return RTYPE_NUM;
4393
4394     case OP_REG_VI:
4395       return RTYPE_NUM | RTYPE_VI;
4396
4397     case OP_REG_VF:
4398       return RTYPE_NUM | RTYPE_VF;
4399
4400     case OP_REG_R5900_I:
4401       return RTYPE_R5900_I;
4402
4403     case OP_REG_R5900_Q:
4404       return RTYPE_R5900_Q;
4405
4406     case OP_REG_R5900_R:
4407       return RTYPE_R5900_R;
4408
4409     case OP_REG_R5900_ACC:
4410       return RTYPE_R5900_ACC;
4411     }
4412   abort ();
4413 }
4414
4415 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4416
4417 static void
4418 check_regno (struct mips_arg_info *arg,
4419              enum mips_reg_operand_type type, unsigned int regno)
4420 {
4421   if (AT && type == OP_REG_GP && regno == AT)
4422     arg->seen_at = TRUE;
4423
4424   if (type == OP_REG_FP
4425       && (regno & 1) != 0
4426       && HAVE_32BIT_FPRS
4427       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4428     as_warn (_("float register should be even, was %d"), regno);
4429
4430   if (type == OP_REG_CCC)
4431     {
4432       const char *name;
4433       size_t length;
4434
4435       name = arg->insn->insn_mo->name;
4436       length = strlen (name);
4437       if ((regno & 1) != 0
4438           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4439               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4440         as_warn (_("condition code register should be even for %s, was %d"),
4441                  name, regno);
4442
4443       if ((regno & 3) != 0
4444           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4445         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4446                  name, regno);
4447     }
4448 }
4449
4450 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4451    a register of type TYPE.  Return true on success, storing the register
4452    number in *REGNO and warning about any dubious uses.  */
4453
4454 static bfd_boolean
4455 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4456              unsigned int symval, unsigned int *regno)
4457 {
4458   if (type == OP_REG_VEC)
4459     symval = mips_prefer_vec_regno (symval);
4460   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4461     return FALSE;
4462
4463   *regno = symval & RNUM_MASK;
4464   check_regno (arg, type, *regno);
4465   return TRUE;
4466 }
4467
4468 /* Try to interpret the next token in ARG as a register of type TYPE.
4469    Consume the token and return true on success, storing the register
4470    number in *REGNO.  Return false on failure.  */
4471
4472 static bfd_boolean
4473 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4474            unsigned int *regno)
4475 {
4476   if (arg->token->type == OT_REG
4477       && match_regno (arg, type, arg->token->u.regno, regno))
4478     {
4479       ++arg->token;
4480       return TRUE;
4481     }
4482   return FALSE;
4483 }
4484
4485 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4486    Consume the token and return true on success, storing the register numbers
4487    in *REGNO1 and *REGNO2.  Return false on failure.  */
4488
4489 static bfd_boolean
4490 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4491                  unsigned int *regno1, unsigned int *regno2)
4492 {
4493   if (match_reg (arg, type, regno1))
4494     {
4495       *regno2 = *regno1;
4496       return TRUE;
4497     }
4498   if (arg->token->type == OT_REG_RANGE
4499       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4500       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4501       && *regno1 <= *regno2)
4502     {
4503       ++arg->token;
4504       return TRUE;
4505     }
4506   return FALSE;
4507 }
4508
4509 /* OP_INT matcher.  */
4510
4511 static bfd_boolean
4512 match_int_operand (struct mips_arg_info *arg,
4513                    const struct mips_operand *operand_base)
4514 {
4515   const struct mips_int_operand *operand;
4516   unsigned int uval;
4517   int min_val, max_val, factor;
4518   offsetT sval;
4519
4520   operand = (const struct mips_int_operand *) operand_base;
4521   factor = 1 << operand->shift;
4522   min_val = mips_int_operand_min (operand);
4523   max_val = mips_int_operand_max (operand);
4524
4525   if (operand_base->lsb == 0
4526       && operand_base->size == 16
4527       && operand->shift == 0
4528       && operand->bias == 0
4529       && (operand->max_val == 32767 || operand->max_val == 65535))
4530     {
4531       /* The operand can be relocated.  */
4532       if (!match_expression (arg, &offset_expr, offset_reloc))
4533         return FALSE;
4534
4535       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4536         /* Relocation operators were used.  Accept the arguent and
4537            leave the relocation value in offset_expr and offset_relocs
4538            for the caller to process.  */
4539         return TRUE;
4540
4541       if (offset_expr.X_op != O_constant)
4542         {
4543           /* Accept non-constant operands if no later alternative matches,
4544              leaving it for the caller to process.  */
4545           if (!arg->lax_match)
4546             return FALSE;
4547           offset_reloc[0] = BFD_RELOC_LO16;
4548           return TRUE;
4549         }
4550
4551       /* Clear the global state; we're going to install the operand
4552          ourselves.  */
4553       sval = offset_expr.X_add_number;
4554       offset_expr.X_op = O_absent;
4555
4556       /* For compatibility with older assemblers, we accept
4557          0x8000-0xffff as signed 16-bit numbers when only
4558          signed numbers are allowed.  */
4559       if (sval > max_val)
4560         {
4561           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4562           if (!arg->lax_match && sval <= max_val)
4563             return FALSE;
4564         }
4565     }
4566   else
4567     {
4568       if (!match_const_int (arg, &sval))
4569         return FALSE;
4570     }
4571
4572   arg->last_op_int = sval;
4573
4574   if (sval < min_val || sval > max_val || sval % factor)
4575     {
4576       match_out_of_range (arg);
4577       return FALSE;
4578     }
4579
4580   uval = (unsigned int) sval >> operand->shift;
4581   uval -= operand->bias;
4582
4583   /* Handle -mfix-cn63xxp1.  */
4584   if (arg->opnum == 1
4585       && mips_fix_cn63xxp1
4586       && !mips_opts.micromips
4587       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4588     switch (uval)
4589       {
4590       case 5:
4591       case 25:
4592       case 26:
4593       case 27:
4594       case 28:
4595       case 29:
4596       case 30:
4597       case 31:
4598         /* These are ok.  */
4599         break;
4600
4601       default:
4602         /* The rest must be changed to 28.  */
4603         uval = 28;
4604         break;
4605       }
4606
4607   insn_insert_operand (arg->insn, operand_base, uval);
4608   return TRUE;
4609 }
4610
4611 /* OP_MAPPED_INT matcher.  */
4612
4613 static bfd_boolean
4614 match_mapped_int_operand (struct mips_arg_info *arg,
4615                           const struct mips_operand *operand_base)
4616 {
4617   const struct mips_mapped_int_operand *operand;
4618   unsigned int uval, num_vals;
4619   offsetT sval;
4620
4621   operand = (const struct mips_mapped_int_operand *) operand_base;
4622   if (!match_const_int (arg, &sval))
4623     return FALSE;
4624
4625   num_vals = 1 << operand_base->size;
4626   for (uval = 0; uval < num_vals; uval++)
4627     if (operand->int_map[uval] == sval)
4628       break;
4629   if (uval == num_vals)
4630     {
4631       match_out_of_range (arg);
4632       return FALSE;
4633     }
4634
4635   insn_insert_operand (arg->insn, operand_base, uval);
4636   return TRUE;
4637 }
4638
4639 /* OP_MSB matcher.  */
4640
4641 static bfd_boolean
4642 match_msb_operand (struct mips_arg_info *arg,
4643                    const struct mips_operand *operand_base)
4644 {
4645   const struct mips_msb_operand *operand;
4646   int min_val, max_val, max_high;
4647   offsetT size, sval, high;
4648
4649   operand = (const struct mips_msb_operand *) operand_base;
4650   min_val = operand->bias;
4651   max_val = min_val + (1 << operand_base->size) - 1;
4652   max_high = operand->opsize;
4653
4654   if (!match_const_int (arg, &size))
4655     return FALSE;
4656
4657   high = size + arg->last_op_int;
4658   sval = operand->add_lsb ? high : size;
4659
4660   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4661     {
4662       match_out_of_range (arg);
4663       return FALSE;
4664     }
4665   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4666   return TRUE;
4667 }
4668
4669 /* OP_REG matcher.  */
4670
4671 static bfd_boolean
4672 match_reg_operand (struct mips_arg_info *arg,
4673                    const struct mips_operand *operand_base)
4674 {
4675   const struct mips_reg_operand *operand;
4676   unsigned int regno, uval, num_vals;
4677
4678   operand = (const struct mips_reg_operand *) operand_base;
4679   if (!match_reg (arg, operand->reg_type, &regno))
4680     return FALSE;
4681
4682   if (operand->reg_map)
4683     {
4684       num_vals = 1 << operand->root.size;
4685       for (uval = 0; uval < num_vals; uval++)
4686         if (operand->reg_map[uval] == regno)
4687           break;
4688       if (num_vals == uval)
4689         return FALSE;
4690     }
4691   else
4692     uval = regno;
4693
4694   arg->last_regno = regno;
4695   if (arg->opnum == 1)
4696     arg->dest_regno = regno;
4697   insn_insert_operand (arg->insn, operand_base, uval);
4698   return TRUE;
4699 }
4700
4701 /* OP_REG_PAIR matcher.  */
4702
4703 static bfd_boolean
4704 match_reg_pair_operand (struct mips_arg_info *arg,
4705                         const struct mips_operand *operand_base)
4706 {
4707   const struct mips_reg_pair_operand *operand;
4708   unsigned int regno1, regno2, uval, num_vals;
4709
4710   operand = (const struct mips_reg_pair_operand *) operand_base;
4711   if (!match_reg (arg, operand->reg_type, &regno1)
4712       || !match_char (arg, ',')
4713       || !match_reg (arg, operand->reg_type, &regno2))
4714     return FALSE;
4715
4716   num_vals = 1 << operand_base->size;
4717   for (uval = 0; uval < num_vals; uval++)
4718     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4719       break;
4720   if (uval == num_vals)
4721     return FALSE;
4722
4723   insn_insert_operand (arg->insn, operand_base, uval);
4724   return TRUE;
4725 }
4726
4727 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4728
4729 static bfd_boolean
4730 match_pcrel_operand (struct mips_arg_info *arg)
4731 {
4732   bfd_reloc_code_real_type r[3];
4733
4734   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4735 }
4736
4737 /* OP_PERF_REG matcher.  */
4738
4739 static bfd_boolean
4740 match_perf_reg_operand (struct mips_arg_info *arg,
4741                         const struct mips_operand *operand)
4742 {
4743   offsetT sval;
4744
4745   if (!match_const_int (arg, &sval))
4746     return FALSE;
4747
4748   if (sval != 0
4749       && (sval != 1
4750           || (mips_opts.arch == CPU_R5900
4751               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4752                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4753     {
4754       set_insn_error (arg->argnum, _("invalid performance register"));
4755       return FALSE;
4756     }
4757
4758   insn_insert_operand (arg->insn, operand, sval);
4759   return TRUE;
4760 }
4761
4762 /* OP_ADDIUSP matcher.  */
4763
4764 static bfd_boolean
4765 match_addiusp_operand (struct mips_arg_info *arg,
4766                        const struct mips_operand *operand)
4767 {
4768   offsetT sval;
4769   unsigned int uval;
4770
4771   if (!match_const_int (arg, &sval))
4772     return FALSE;
4773
4774   if (sval % 4)
4775     {
4776       match_out_of_range (arg);
4777       return FALSE;
4778     }
4779
4780   sval /= 4;
4781   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4782     {
4783       match_out_of_range (arg);
4784       return FALSE;
4785     }
4786
4787   uval = (unsigned int) sval;
4788   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4789   insn_insert_operand (arg->insn, operand, uval);
4790   return TRUE;
4791 }
4792
4793 /* OP_CLO_CLZ_DEST matcher.  */
4794
4795 static bfd_boolean
4796 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4797                             const struct mips_operand *operand)
4798 {
4799   unsigned int regno;
4800
4801   if (!match_reg (arg, OP_REG_GP, &regno))
4802     return FALSE;
4803
4804   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4805   return TRUE;
4806 }
4807
4808 /* OP_LWM_SWM_LIST matcher.  */
4809
4810 static bfd_boolean
4811 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4812                             const struct mips_operand *operand)
4813 {
4814   unsigned int reglist, sregs, ra, regno1, regno2;
4815   struct mips_arg_info reset;
4816
4817   reglist = 0;
4818   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4819     return FALSE;
4820   do
4821     {
4822       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4823         {
4824           reglist |= 1 << FP;
4825           regno2 = S7;
4826         }
4827       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4828       reset = *arg;
4829     }
4830   while (match_char (arg, ',')
4831          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4832   *arg = reset;
4833
4834   if (operand->size == 2)
4835     {
4836       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4837
4838          s0, ra
4839          s0, s1, ra, s2, s3
4840          s0-s2, ra
4841
4842          and any permutations of these.  */
4843       if ((reglist & 0xfff1ffff) != 0x80010000)
4844         return FALSE;
4845
4846       sregs = (reglist >> 17) & 7;
4847       ra = 0;
4848     }
4849   else
4850     {
4851       /* The list must include at least one of ra and s0-sN,
4852          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4853          which are $23 and $30 respectively.)  E.g.:
4854
4855          ra
4856          s0
4857          ra, s0, s1, s2
4858          s0-s8
4859          s0-s5, ra
4860
4861          and any permutations of these.  */
4862       if ((reglist & 0x3f00ffff) != 0)
4863         return FALSE;
4864
4865       ra = (reglist >> 27) & 0x10;
4866       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4867     }
4868   sregs += 1;
4869   if ((sregs & -sregs) != sregs)
4870     return FALSE;
4871
4872   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4873   return TRUE;
4874 }
4875
4876 /* OP_ENTRY_EXIT_LIST matcher.  */
4877
4878 static unsigned int
4879 match_entry_exit_operand (struct mips_arg_info *arg,
4880                           const struct mips_operand *operand)
4881 {
4882   unsigned int mask;
4883   bfd_boolean is_exit;
4884
4885   /* The format is the same for both ENTRY and EXIT, but the constraints
4886      are different.  */
4887   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4888   mask = (is_exit ? 7 << 3 : 0);
4889   do
4890     {
4891       unsigned int regno1, regno2;
4892       bfd_boolean is_freg;
4893
4894       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4895         is_freg = FALSE;
4896       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4897         is_freg = TRUE;
4898       else
4899         return FALSE;
4900
4901       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4902         {
4903           mask &= ~(7 << 3);
4904           mask |= (5 + regno2) << 3;
4905         }
4906       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4907         mask |= (regno2 - 3) << 3;
4908       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4909         mask |= (regno2 - 15) << 1;
4910       else if (regno1 == RA && regno2 == RA)
4911         mask |= 1;
4912       else
4913         return FALSE;
4914     }
4915   while (match_char (arg, ','));
4916
4917   insn_insert_operand (arg->insn, operand, mask);
4918   return TRUE;
4919 }
4920
4921 /* OP_SAVE_RESTORE_LIST matcher.  */
4922
4923 static bfd_boolean
4924 match_save_restore_list_operand (struct mips_arg_info *arg)
4925 {
4926   unsigned int opcode, args, statics, sregs;
4927   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4928   offsetT frame_size;
4929
4930   opcode = arg->insn->insn_opcode;
4931   frame_size = 0;
4932   num_frame_sizes = 0;
4933   args = 0;
4934   statics = 0;
4935   sregs = 0;
4936   do
4937     {
4938       unsigned int regno1, regno2;
4939
4940       if (arg->token->type == OT_INTEGER)
4941         {
4942           /* Handle the frame size.  */
4943           if (!match_const_int (arg, &frame_size))
4944             return FALSE;
4945           num_frame_sizes += 1;
4946         }
4947       else
4948         {
4949           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4950             return FALSE;
4951
4952           while (regno1 <= regno2)
4953             {
4954               if (regno1 >= 4 && regno1 <= 7)
4955                 {
4956                   if (num_frame_sizes == 0)
4957                     /* args $a0-$a3 */
4958                     args |= 1 << (regno1 - 4);
4959                   else
4960                     /* statics $a0-$a3 */
4961                     statics |= 1 << (regno1 - 4);
4962                 }
4963               else if (regno1 >= 16 && regno1 <= 23)
4964                 /* $s0-$s7 */
4965                 sregs |= 1 << (regno1 - 16);
4966               else if (regno1 == 30)
4967                 /* $s8 */
4968                 sregs |= 1 << 8;
4969               else if (regno1 == 31)
4970                 /* Add $ra to insn.  */
4971                 opcode |= 0x40;
4972               else
4973                 return FALSE;
4974               regno1 += 1;
4975               if (regno1 == 24)
4976                 regno1 = 30;
4977             }
4978         }
4979     }
4980   while (match_char (arg, ','));
4981
4982   /* Encode args/statics combination.  */
4983   if (args & statics)
4984     return FALSE;
4985   else if (args == 0xf)
4986     /* All $a0-$a3 are args.  */
4987     opcode |= MIPS16_ALL_ARGS << 16;
4988   else if (statics == 0xf)
4989     /* All $a0-$a3 are statics.  */
4990     opcode |= MIPS16_ALL_STATICS << 16;
4991   else
4992     {
4993       /* Count arg registers.  */
4994       num_args = 0;
4995       while (args & 0x1)
4996         {
4997           args >>= 1;
4998           num_args += 1;
4999         }
5000       if (args != 0)
5001         return FALSE;
5002
5003       /* Count static registers.  */
5004       num_statics = 0;
5005       while (statics & 0x8)
5006         {
5007           statics = (statics << 1) & 0xf;
5008           num_statics += 1;
5009         }
5010       if (statics != 0)
5011         return FALSE;
5012
5013       /* Encode args/statics.  */
5014       opcode |= ((num_args << 2) | num_statics) << 16;
5015     }
5016
5017   /* Encode $s0/$s1.  */
5018   if (sregs & (1 << 0))         /* $s0 */
5019     opcode |= 0x20;
5020   if (sregs & (1 << 1))         /* $s1 */
5021     opcode |= 0x10;
5022   sregs >>= 2;
5023
5024   /* Encode $s2-$s8. */
5025   num_sregs = 0;
5026   while (sregs & 1)
5027     {
5028       sregs >>= 1;
5029       num_sregs += 1;
5030     }
5031   if (sregs != 0)
5032     return FALSE;
5033   opcode |= num_sregs << 24;
5034
5035   /* Encode frame size.  */
5036   if (num_frame_sizes == 0)
5037     {
5038       set_insn_error (arg->argnum, _("missing frame size"));
5039       return FALSE;
5040     }
5041   if (num_frame_sizes > 1)
5042     {
5043       set_insn_error (arg->argnum, _("frame size specified twice"));
5044       return FALSE;
5045     }
5046   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5047     {
5048       set_insn_error (arg->argnum, _("invalid frame size"));
5049       return FALSE;
5050     }
5051   if (frame_size != 128 || (opcode >> 16) != 0)
5052     {
5053       frame_size /= 8;
5054       opcode |= (((frame_size & 0xf0) << 16)
5055                  | (frame_size & 0x0f));
5056     }
5057
5058   /* Finally build the instruction.  */
5059   if ((opcode >> 16) != 0 || frame_size == 0)
5060     opcode |= MIPS16_EXTEND;
5061   arg->insn->insn_opcode = opcode;
5062   return TRUE;
5063 }
5064
5065 /* OP_MDMX_IMM_REG matcher.  */
5066
5067 static bfd_boolean
5068 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5069                             const struct mips_operand *operand)
5070 {
5071   unsigned int regno, uval;
5072   bfd_boolean is_qh;
5073   const struct mips_opcode *opcode;
5074
5075   /* The mips_opcode records whether this is an octobyte or quadhalf
5076      instruction.  Start out with that bit in place.  */
5077   opcode = arg->insn->insn_mo;
5078   uval = mips_extract_operand (operand, opcode->match);
5079   is_qh = (uval != 0);
5080
5081   if (arg->token->type == OT_REG || arg->token->type == OT_REG_ELEMENT)
5082     {
5083       if ((opcode->membership & INSN_5400)
5084           && strcmp (opcode->name, "rzu.ob") == 0)
5085         {
5086           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5087                             arg->argnum);
5088           return FALSE;
5089         }
5090
5091       /* Check whether this is a vector register or a broadcast of
5092          a single element.  */
5093       if (arg->token->type == OT_REG_ELEMENT)
5094         {
5095           if (!match_regno (arg, OP_REG_VEC, arg->token->u.reg_element.regno,
5096                             &regno))
5097             return FALSE;
5098           if (arg->token->u.reg_element.index > (is_qh ? 3 : 7))
5099             {
5100               set_insn_error (arg->argnum, _("invalid element selector"));
5101               return FALSE;
5102             }
5103           else
5104             uval |= arg->token->u.reg_element.index << (is_qh ? 2 : 1) << 5;
5105         }
5106       else
5107         {
5108           /* A full vector.  */
5109           if ((opcode->membership & INSN_5400)
5110               && (strcmp (opcode->name, "sll.ob") == 0
5111                   || strcmp (opcode->name, "srl.ob") == 0))
5112             {
5113               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5114                                 arg->argnum);
5115               return FALSE;
5116             }
5117
5118           if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5119             return FALSE;
5120           if (is_qh)
5121             uval |= MDMX_FMTSEL_VEC_QH << 5;
5122           else
5123             uval |= MDMX_FMTSEL_VEC_OB << 5;
5124         }
5125       uval |= regno;
5126       ++arg->token;
5127     }
5128   else
5129     {
5130       offsetT sval;
5131
5132       if (!match_const_int (arg, &sval))
5133         return FALSE;
5134       if (sval < 0 || sval > 31)
5135         {
5136           match_out_of_range (arg);
5137           return FALSE;
5138         }
5139       uval |= (sval & 31);
5140       if (is_qh)
5141         uval |= MDMX_FMTSEL_IMM_QH << 5;
5142       else
5143         uval |= MDMX_FMTSEL_IMM_OB << 5;
5144     }
5145   insn_insert_operand (arg->insn, operand, uval);
5146   return TRUE;
5147 }
5148
5149 /* OP_PC matcher.  */
5150
5151 static bfd_boolean
5152 match_pc_operand (struct mips_arg_info *arg)
5153 {
5154   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5155     {
5156       ++arg->token;
5157       return TRUE;
5158     }
5159   return FALSE;
5160 }
5161
5162 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5163    register that we need to match.  */
5164
5165 static bfd_boolean
5166 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5167 {
5168   unsigned int regno;
5169
5170   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5171 }
5172
5173 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5174    the length of the value in bytes (4 for float, 8 for double) and
5175    USING_GPRS says whether the destination is a GPR rather than an FPR.
5176
5177    Return the constant in IMM and OFFSET as follows:
5178
5179    - If the constant should be loaded via memory, set IMM to O_absent and
5180      OFFSET to the memory address.
5181
5182    - Otherwise, if the constant should be loaded into two 32-bit registers,
5183      set IMM to the O_constant to load into the high register and OFFSET
5184      to the corresponding value for the low register.
5185
5186    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5187
5188    These constants only appear as the last operand in an instruction,
5189    and every instruction that accepts them in any variant accepts them
5190    in all variants.  This means we don't have to worry about backing out
5191    any changes if the instruction does not match.  We just match
5192    unconditionally and report an error if the constant is invalid.  */
5193
5194 static bfd_boolean
5195 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5196                       expressionS *offset, int length, bfd_boolean using_gprs)
5197 {
5198   char *p;
5199   segT seg, new_seg;
5200   subsegT subseg;
5201   const char *newname;
5202   unsigned char *data;
5203
5204   /* Where the constant is placed is based on how the MIPS assembler
5205      does things:
5206
5207      length == 4 && using_gprs  -- immediate value only
5208      length == 8 && using_gprs  -- .rdata or immediate value
5209      length == 4 && !using_gprs -- .lit4 or immediate value
5210      length == 8 && !using_gprs -- .lit8 or immediate value
5211
5212      The .lit4 and .lit8 sections are only used if permitted by the
5213      -G argument.  */
5214   if (arg->token->type != OT_FLOAT)
5215     {
5216       set_insn_error (arg->argnum, _("floating-point expression required"));
5217       return FALSE;
5218     }
5219
5220   gas_assert (arg->token->u.flt.length == length);
5221   data = arg->token->u.flt.data;
5222   ++arg->token;
5223
5224   /* Handle 32-bit constants for which an immediate value is best.  */
5225   if (length == 4
5226       && (using_gprs
5227           || g_switch_value < 4
5228           || (data[0] == 0 && data[1] == 0)
5229           || (data[2] == 0 && data[3] == 0)))
5230     {
5231       imm->X_op = O_constant;
5232       if (!target_big_endian)
5233         imm->X_add_number = bfd_getl32 (data);
5234       else
5235         imm->X_add_number = bfd_getb32 (data);
5236       offset->X_op = O_absent;
5237       return TRUE;
5238     }
5239
5240   /* Handle 64-bit constants for which an immediate value is best.  */
5241   if (length == 8
5242       && !mips_disable_float_construction
5243       /* Constants can only be constructed in GPRs and copied
5244          to FPRs if the GPRs are at least as wide as the FPRs.
5245          Force the constant into memory if we are using 64-bit FPRs
5246          but the GPRs are only 32 bits wide.  */
5247       /* ??? No longer true with the addition of MTHC1, but this
5248          is legacy code...  */
5249       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5250       && ((data[0] == 0 && data[1] == 0)
5251           || (data[2] == 0 && data[3] == 0))
5252       && ((data[4] == 0 && data[5] == 0)
5253           || (data[6] == 0 && data[7] == 0)))
5254     {
5255       /* The value is simple enough to load with a couple of instructions.
5256          If using 32-bit registers, set IMM to the high order 32 bits and
5257          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5258          64 bit constant.  */
5259       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5260         {
5261           imm->X_op = O_constant;
5262           offset->X_op = O_constant;
5263           if (!target_big_endian)
5264             {
5265               imm->X_add_number = bfd_getl32 (data + 4);
5266               offset->X_add_number = bfd_getl32 (data);
5267             }
5268           else
5269             {
5270               imm->X_add_number = bfd_getb32 (data);
5271               offset->X_add_number = bfd_getb32 (data + 4);
5272             }
5273           if (offset->X_add_number == 0)
5274             offset->X_op = O_absent;
5275         }
5276       else
5277         {
5278           imm->X_op = O_constant;
5279           if (!target_big_endian)
5280             imm->X_add_number = bfd_getl64 (data);
5281           else
5282             imm->X_add_number = bfd_getb64 (data);
5283           offset->X_op = O_absent;
5284         }
5285       return TRUE;
5286     }
5287
5288   /* Switch to the right section.  */
5289   seg = now_seg;
5290   subseg = now_subseg;
5291   if (length == 4)
5292     {
5293       gas_assert (!using_gprs && g_switch_value >= 4);
5294       newname = ".lit4";
5295     }
5296   else
5297     {
5298       if (using_gprs || g_switch_value < 8)
5299         newname = RDATA_SECTION_NAME;
5300       else
5301         newname = ".lit8";
5302     }
5303
5304   new_seg = subseg_new (newname, (subsegT) 0);
5305   bfd_set_section_flags (stdoutput, new_seg,
5306                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5307   frag_align (length == 4 ? 2 : 3, 0, 0);
5308   if (strncmp (TARGET_OS, "elf", 3) != 0)
5309     record_alignment (new_seg, 4);
5310   else
5311     record_alignment (new_seg, length == 4 ? 2 : 3);
5312   if (seg == now_seg)
5313     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5314
5315   /* Set the argument to the current address in the section.  */
5316   imm->X_op = O_absent;
5317   offset->X_op = O_symbol;
5318   offset->X_add_symbol = symbol_temp_new_now ();
5319   offset->X_add_number = 0;
5320
5321   /* Put the floating point number into the section.  */
5322   p = frag_more (length);
5323   memcpy (p, data, length);
5324
5325   /* Switch back to the original section.  */
5326   subseg_set (seg, subseg);
5327   return TRUE;
5328 }
5329
5330 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5331    them.  */
5332
5333 static bfd_boolean
5334 match_vu0_suffix_operand (struct mips_arg_info *arg,
5335                           const struct mips_operand *operand,
5336                           bfd_boolean match_p)
5337 {
5338   unsigned int uval;
5339
5340   /* The operand can be an XYZW mask or a single 2-bit channel index
5341      (with X being 0).  */
5342   gas_assert (operand->size == 2 || operand->size == 4);
5343
5344   /* The suffix can be omitted when it is already part of the opcode.  */
5345   if (arg->token->type != OT_CHANNELS)
5346     return match_p;
5347
5348   uval = arg->token->u.channels;
5349   if (operand->size == 2)
5350     {
5351       /* Check that a single bit is set and convert it into a 2-bit index.  */
5352       if ((uval & -uval) != uval)
5353         return FALSE;
5354       uval = 4 - ffs (uval);
5355     }
5356
5357   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5358     return FALSE;
5359
5360   ++arg->token;
5361   if (!match_p)
5362     insn_insert_operand (arg->insn, operand, uval);
5363   return TRUE;
5364 }
5365
5366 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5367    of the argument text if the match is successful, otherwise return null.  */
5368
5369 static bfd_boolean
5370 match_operand (struct mips_arg_info *arg,
5371                const struct mips_operand *operand)
5372 {
5373   switch (operand->type)
5374     {
5375     case OP_INT:
5376       return match_int_operand (arg, operand);
5377
5378     case OP_MAPPED_INT:
5379       return match_mapped_int_operand (arg, operand);
5380
5381     case OP_MSB:
5382       return match_msb_operand (arg, operand);
5383
5384     case OP_REG:
5385     case OP_OPTIONAL_REG:
5386       return match_reg_operand (arg, operand);
5387
5388     case OP_REG_PAIR:
5389       return match_reg_pair_operand (arg, operand);
5390
5391     case OP_PCREL:
5392       return match_pcrel_operand (arg);
5393
5394     case OP_PERF_REG:
5395       return match_perf_reg_operand (arg, operand);
5396
5397     case OP_ADDIUSP_INT:
5398       return match_addiusp_operand (arg, operand);
5399
5400     case OP_CLO_CLZ_DEST:
5401       return match_clo_clz_dest_operand (arg, operand);
5402
5403     case OP_LWM_SWM_LIST:
5404       return match_lwm_swm_list_operand (arg, operand);
5405
5406     case OP_ENTRY_EXIT_LIST:
5407       return match_entry_exit_operand (arg, operand);
5408
5409     case OP_SAVE_RESTORE_LIST:
5410       return match_save_restore_list_operand (arg);
5411
5412     case OP_MDMX_IMM_REG:
5413       return match_mdmx_imm_reg_operand (arg, operand);
5414
5415     case OP_REPEAT_DEST_REG:
5416       return match_tied_reg_operand (arg, arg->dest_regno);
5417
5418     case OP_REPEAT_PREV_REG:
5419       return match_tied_reg_operand (arg, arg->last_regno);
5420
5421     case OP_PC:
5422       return match_pc_operand (arg);
5423
5424     case OP_VU0_SUFFIX:
5425       return match_vu0_suffix_operand (arg, operand, FALSE);
5426
5427     case OP_VU0_MATCH_SUFFIX:
5428       return match_vu0_suffix_operand (arg, operand, TRUE);
5429     }
5430   abort ();
5431 }
5432
5433 /* ARG is the state after successfully matching an instruction.
5434    Issue any queued-up warnings.  */
5435
5436 static void
5437 check_completed_insn (struct mips_arg_info *arg)
5438 {
5439   if (arg->seen_at)
5440     {
5441       if (AT == ATREG)
5442         as_warn (_("used $at without \".set noat\""));
5443       else
5444         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5445     }
5446 }
5447
5448 /* Return true if modifying general-purpose register REG needs a delay.  */
5449
5450 static bfd_boolean
5451 reg_needs_delay (unsigned int reg)
5452 {
5453   unsigned long prev_pinfo;
5454
5455   prev_pinfo = history[0].insn_mo->pinfo;
5456   if (!mips_opts.noreorder
5457       && (((prev_pinfo & INSN_LOAD_MEMORY_DELAY) && !gpr_interlocks)
5458           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5459       && (gpr_write_mask (&history[0]) & (1 << reg)))
5460     return TRUE;
5461
5462   return FALSE;
5463 }
5464
5465 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5466    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5467    by VR4120 errata.  */
5468
5469 static unsigned int
5470 classify_vr4120_insn (const char *name)
5471 {
5472   if (strncmp (name, "macc", 4) == 0)
5473     return FIX_VR4120_MACC;
5474   if (strncmp (name, "dmacc", 5) == 0)
5475     return FIX_VR4120_DMACC;
5476   if (strncmp (name, "mult", 4) == 0)
5477     return FIX_VR4120_MULT;
5478   if (strncmp (name, "dmult", 5) == 0)
5479     return FIX_VR4120_DMULT;
5480   if (strstr (name, "div"))
5481     return FIX_VR4120_DIV;
5482   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5483     return FIX_VR4120_MTHILO;
5484   return NUM_FIX_VR4120_CLASSES;
5485 }
5486
5487 #define INSN_ERET  0x42000018
5488 #define INSN_DERET 0x4200001f
5489
5490 /* Return the number of instructions that must separate INSN1 and INSN2,
5491    where INSN1 is the earlier instruction.  Return the worst-case value
5492    for any INSN2 if INSN2 is null.  */
5493
5494 static unsigned int
5495 insns_between (const struct mips_cl_insn *insn1,
5496                const struct mips_cl_insn *insn2)
5497 {
5498   unsigned long pinfo1, pinfo2;
5499   unsigned int mask;
5500
5501   /* If INFO2 is null, pessimistically assume that all flags are set for
5502      the second instruction.  */
5503   pinfo1 = insn1->insn_mo->pinfo;
5504   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5505
5506   /* For most targets, write-after-read dependencies on the HI and LO
5507      registers must be separated by at least two instructions.  */
5508   if (!hilo_interlocks)
5509     {
5510       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5511         return 2;
5512       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5513         return 2;
5514     }
5515
5516   /* If we're working around r7000 errata, there must be two instructions
5517      between an mfhi or mflo and any instruction that uses the result.  */
5518   if (mips_7000_hilo_fix
5519       && !mips_opts.micromips
5520       && MF_HILO_INSN (pinfo1)
5521       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5522     return 2;
5523
5524   /* If we're working around 24K errata, one instruction is required
5525      if an ERET or DERET is followed by a branch instruction.  */
5526   if (mips_fix_24k && !mips_opts.micromips)
5527     {
5528       if (insn1->insn_opcode == INSN_ERET
5529           || insn1->insn_opcode == INSN_DERET)
5530         {
5531           if (insn2 == NULL
5532               || insn2->insn_opcode == INSN_ERET
5533               || insn2->insn_opcode == INSN_DERET
5534               || delayed_branch_p (insn2))
5535             return 1;
5536         }
5537     }
5538
5539   /* If working around VR4120 errata, check for combinations that need
5540      a single intervening instruction.  */
5541   if (mips_fix_vr4120 && !mips_opts.micromips)
5542     {
5543       unsigned int class1, class2;
5544
5545       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5546       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5547         {
5548           if (insn2 == NULL)
5549             return 1;
5550           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5551           if (vr4120_conflicts[class1] & (1 << class2))
5552             return 1;
5553         }
5554     }
5555
5556   if (!HAVE_CODE_COMPRESSION)
5557     {
5558       /* Check for GPR or coprocessor load delays.  All such delays
5559          are on the RT register.  */
5560       /* Itbl support may require additional care here.  */
5561       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY_DELAY))
5562           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5563         {
5564           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5565             return 1;
5566         }
5567
5568       /* Check for generic coprocessor hazards.
5569
5570          This case is not handled very well.  There is no special
5571          knowledge of CP0 handling, and the coprocessors other than
5572          the floating point unit are not distinguished at all.  */
5573       /* Itbl support may require additional care here. FIXME!
5574          Need to modify this to include knowledge about
5575          user specified delays!  */
5576       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5577                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5578         {
5579           /* Handle cases where INSN1 writes to a known general coprocessor
5580              register.  There must be a one instruction delay before INSN2
5581              if INSN2 reads that register, otherwise no delay is needed.  */
5582           mask = fpr_write_mask (insn1);
5583           if (mask != 0)
5584             {
5585               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5586                 return 1;
5587             }
5588           else
5589             {
5590               /* Read-after-write dependencies on the control registers
5591                  require a two-instruction gap.  */
5592               if ((pinfo1 & INSN_WRITE_COND_CODE)
5593                   && (pinfo2 & INSN_READ_COND_CODE))
5594                 return 2;
5595
5596               /* We don't know exactly what INSN1 does.  If INSN2 is
5597                  also a coprocessor instruction, assume there must be
5598                  a one instruction gap.  */
5599               if (pinfo2 & INSN_COP)
5600                 return 1;
5601             }
5602         }
5603
5604       /* Check for read-after-write dependencies on the coprocessor
5605          control registers in cases where INSN1 does not need a general
5606          coprocessor delay.  This means that INSN1 is a floating point
5607          comparison instruction.  */
5608       /* Itbl support may require additional care here.  */
5609       else if (!cop_interlocks
5610                && (pinfo1 & INSN_WRITE_COND_CODE)
5611                && (pinfo2 & INSN_READ_COND_CODE))
5612         return 1;
5613     }
5614
5615   return 0;
5616 }
5617
5618 /* Return the number of nops that would be needed to work around the
5619    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5620    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5621    that are contained within the first IGNORE instructions of HIST.  */
5622
5623 static int
5624 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5625                  const struct mips_cl_insn *insn)
5626 {
5627   int i, j;
5628   unsigned int mask;
5629
5630   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5631      are not affected by the errata.  */
5632   if (insn != 0
5633       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5634           || strcmp (insn->insn_mo->name, "mtlo") == 0
5635           || strcmp (insn->insn_mo->name, "mthi") == 0))
5636     return 0;
5637
5638   /* Search for the first MFLO or MFHI.  */
5639   for (i = 0; i < MAX_VR4130_NOPS; i++)
5640     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5641       {
5642         /* Extract the destination register.  */
5643         mask = gpr_write_mask (&hist[i]);
5644
5645         /* No nops are needed if INSN reads that register.  */
5646         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5647           return 0;
5648
5649         /* ...or if any of the intervening instructions do.  */
5650         for (j = 0; j < i; j++)
5651           if (gpr_read_mask (&hist[j]) & mask)
5652             return 0;
5653
5654         if (i >= ignore)
5655           return MAX_VR4130_NOPS - i;
5656       }
5657   return 0;
5658 }
5659
5660 #define BASE_REG_EQ(INSN1, INSN2)       \
5661   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5662       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5663
5664 /* Return the minimum alignment for this store instruction.  */
5665
5666 static int
5667 fix_24k_align_to (const struct mips_opcode *mo)
5668 {
5669   if (strcmp (mo->name, "sh") == 0)
5670     return 2;
5671
5672   if (strcmp (mo->name, "swc1") == 0
5673       || strcmp (mo->name, "swc2") == 0
5674       || strcmp (mo->name, "sw") == 0
5675       || strcmp (mo->name, "sc") == 0
5676       || strcmp (mo->name, "s.s") == 0)
5677     return 4;
5678
5679   if (strcmp (mo->name, "sdc1") == 0
5680       || strcmp (mo->name, "sdc2") == 0
5681       || strcmp (mo->name, "s.d") == 0)
5682     return 8;
5683
5684   /* sb, swl, swr */
5685   return 1;
5686 }
5687
5688 struct fix_24k_store_info
5689   {
5690     /* Immediate offset, if any, for this store instruction.  */
5691     short off;
5692     /* Alignment required by this store instruction.  */
5693     int align_to;
5694     /* True for register offsets.  */
5695     int register_offset;
5696   };
5697
5698 /* Comparison function used by qsort.  */
5699
5700 static int
5701 fix_24k_sort (const void *a, const void *b)
5702 {
5703   const struct fix_24k_store_info *pos1 = a;
5704   const struct fix_24k_store_info *pos2 = b;
5705
5706   return (pos1->off - pos2->off);
5707 }
5708
5709 /* INSN is a store instruction.  Try to record the store information
5710    in STINFO.  Return false if the information isn't known.  */
5711
5712 static bfd_boolean
5713 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5714                            const struct mips_cl_insn *insn)
5715 {
5716   /* The instruction must have a known offset.  */
5717   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5718     return FALSE;
5719
5720   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5721   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5722   return TRUE;
5723 }
5724
5725 /* Return the number of nops that would be needed to work around the 24k
5726    "lost data on stores during refill" errata if instruction INSN
5727    immediately followed the 2 instructions described by HIST.
5728    Ignore hazards that are contained within the first IGNORE
5729    instructions of HIST.
5730
5731    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5732    for the data cache refills and store data. The following describes
5733    the scenario where the store data could be lost.
5734
5735    * A data cache miss, due to either a load or a store, causing fill
5736      data to be supplied by the memory subsystem
5737    * The first three doublewords of fill data are returned and written
5738      into the cache
5739    * A sequence of four stores occurs in consecutive cycles around the
5740      final doubleword of the fill:
5741    * Store A
5742    * Store B
5743    * Store C
5744    * Zero, One or more instructions
5745    * Store D
5746
5747    The four stores A-D must be to different doublewords of the line that
5748    is being filled. The fourth instruction in the sequence above permits
5749    the fill of the final doubleword to be transferred from the FSB into
5750    the cache. In the sequence above, the stores may be either integer
5751    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5752    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5753    different doublewords on the line. If the floating point unit is
5754    running in 1:2 mode, it is not possible to create the sequence above
5755    using only floating point store instructions.
5756
5757    In this case, the cache line being filled is incorrectly marked
5758    invalid, thereby losing the data from any store to the line that
5759    occurs between the original miss and the completion of the five
5760    cycle sequence shown above.
5761
5762    The workarounds are:
5763
5764    * Run the data cache in write-through mode.
5765    * Insert a non-store instruction between
5766      Store A and Store B or Store B and Store C.  */
5767   
5768 static int
5769 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5770               const struct mips_cl_insn *insn)
5771 {
5772   struct fix_24k_store_info pos[3];
5773   int align, i, base_offset;
5774
5775   if (ignore >= 2)
5776     return 0;
5777
5778   /* If the previous instruction wasn't a store, there's nothing to
5779      worry about.  */
5780   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5781     return 0;
5782
5783   /* If the instructions after the previous one are unknown, we have
5784      to assume the worst.  */
5785   if (!insn)
5786     return 1;
5787
5788   /* Check whether we are dealing with three consecutive stores.  */
5789   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5790       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5791     return 0;
5792
5793   /* If we don't know the relationship between the store addresses,
5794      assume the worst.  */
5795   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5796       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5797     return 1;
5798
5799   if (!fix_24k_record_store_info (&pos[0], insn)
5800       || !fix_24k_record_store_info (&pos[1], &hist[0])
5801       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5802     return 1;
5803
5804   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5805
5806   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5807      X bytes and such that the base register + X is known to be aligned
5808      to align bytes.  */
5809
5810   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5811     align = 8;
5812   else
5813     {
5814       align = pos[0].align_to;
5815       base_offset = pos[0].off;
5816       for (i = 1; i < 3; i++)
5817         if (align < pos[i].align_to)
5818           {
5819             align = pos[i].align_to;
5820             base_offset = pos[i].off;
5821           }
5822       for (i = 0; i < 3; i++)
5823         pos[i].off -= base_offset;
5824     }
5825
5826   pos[0].off &= ~align + 1;
5827   pos[1].off &= ~align + 1;
5828   pos[2].off &= ~align + 1;
5829
5830   /* If any two stores write to the same chunk, they also write to the
5831      same doubleword.  The offsets are still sorted at this point.  */
5832   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5833     return 0;
5834
5835   /* A range of at least 9 bytes is needed for the stores to be in
5836      non-overlapping doublewords.  */
5837   if (pos[2].off - pos[0].off <= 8)
5838     return 0;
5839
5840   if (pos[2].off - pos[1].off >= 24
5841       || pos[1].off - pos[0].off >= 24
5842       || pos[2].off - pos[0].off >= 32)
5843     return 0;
5844
5845   return 1;
5846 }
5847
5848 /* Return the number of nops that would be needed if instruction INSN
5849    immediately followed the MAX_NOPS instructions given by HIST,
5850    where HIST[0] is the most recent instruction.  Ignore hazards
5851    between INSN and the first IGNORE instructions in HIST.
5852
5853    If INSN is null, return the worse-case number of nops for any
5854    instruction.  */
5855
5856 static int
5857 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5858                const struct mips_cl_insn *insn)
5859 {
5860   int i, nops, tmp_nops;
5861
5862   nops = 0;
5863   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5864     {
5865       tmp_nops = insns_between (hist + i, insn) - i;
5866       if (tmp_nops > nops)
5867         nops = tmp_nops;
5868     }
5869
5870   if (mips_fix_vr4130 && !mips_opts.micromips)
5871     {
5872       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5873       if (tmp_nops > nops)
5874         nops = tmp_nops;
5875     }
5876
5877   if (mips_fix_24k && !mips_opts.micromips)
5878     {
5879       tmp_nops = nops_for_24k (ignore, hist, insn);
5880       if (tmp_nops > nops)
5881         nops = tmp_nops;
5882     }
5883
5884   return nops;
5885 }
5886
5887 /* The variable arguments provide NUM_INSNS extra instructions that
5888    might be added to HIST.  Return the largest number of nops that
5889    would be needed after the extended sequence, ignoring hazards
5890    in the first IGNORE instructions.  */
5891
5892 static int
5893 nops_for_sequence (int num_insns, int ignore,
5894                    const struct mips_cl_insn *hist, ...)
5895 {
5896   va_list args;
5897   struct mips_cl_insn buffer[MAX_NOPS];
5898   struct mips_cl_insn *cursor;
5899   int nops;
5900
5901   va_start (args, hist);
5902   cursor = buffer + num_insns;
5903   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
5904   while (cursor > buffer)
5905     *--cursor = *va_arg (args, const struct mips_cl_insn *);
5906
5907   nops = nops_for_insn (ignore, buffer, NULL);
5908   va_end (args);
5909   return nops;
5910 }
5911
5912 /* Like nops_for_insn, but if INSN is a branch, take into account the
5913    worst-case delay for the branch target.  */
5914
5915 static int
5916 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
5917                          const struct mips_cl_insn *insn)
5918 {
5919   int nops, tmp_nops;
5920
5921   nops = nops_for_insn (ignore, hist, insn);
5922   if (delayed_branch_p (insn))
5923     {
5924       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
5925                                     hist, insn, get_delay_slot_nop (insn));
5926       if (tmp_nops > nops)
5927         nops = tmp_nops;
5928     }
5929   else if (compact_branch_p (insn))
5930     {
5931       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
5932       if (tmp_nops > nops)
5933         nops = tmp_nops;
5934     }
5935   return nops;
5936 }
5937
5938 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
5939
5940 static void
5941 fix_loongson2f_nop (struct mips_cl_insn * ip)
5942 {
5943   gas_assert (!HAVE_CODE_COMPRESSION);
5944   if (strcmp (ip->insn_mo->name, "nop") == 0)
5945     ip->insn_opcode = LOONGSON2F_NOP_INSN;
5946 }
5947
5948 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
5949                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
5950
5951 static void
5952 fix_loongson2f_jump (struct mips_cl_insn * ip)
5953 {
5954   gas_assert (!HAVE_CODE_COMPRESSION);
5955   if (strcmp (ip->insn_mo->name, "j") == 0
5956       || strcmp (ip->insn_mo->name, "jr") == 0
5957       || strcmp (ip->insn_mo->name, "jalr") == 0)
5958     {
5959       int sreg;
5960       expressionS ep;
5961
5962       if (! mips_opts.at)
5963         return;
5964
5965       sreg = EXTRACT_OPERAND (0, RS, *ip);
5966       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
5967         return;
5968
5969       ep.X_op = O_constant;
5970       ep.X_add_number = 0xcfff0000;
5971       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
5972       ep.X_add_number = 0xffff;
5973       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
5974       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
5975     }
5976 }
5977
5978 static void
5979 fix_loongson2f (struct mips_cl_insn * ip)
5980 {
5981   if (mips_fix_loongson2f_nop)
5982     fix_loongson2f_nop (ip);
5983
5984   if (mips_fix_loongson2f_jump)
5985     fix_loongson2f_jump (ip);
5986 }
5987
5988 /* IP is a branch that has a delay slot, and we need to fill it
5989    automatically.   Return true if we can do that by swapping IP
5990    with the previous instruction.
5991    ADDRESS_EXPR is an operand of the instruction to be used with
5992    RELOC_TYPE.  */
5993
5994 static bfd_boolean
5995 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
5996                    bfd_reloc_code_real_type *reloc_type)
5997 {
5998   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
5999   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6000
6001   /* -O2 and above is required for this optimization.  */
6002   if (mips_optimize < 2)
6003     return FALSE;
6004
6005   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6006   if (mips_opts.nomove)
6007     return FALSE;
6008
6009   /* We can't swap if the previous instruction's position is fixed.  */
6010   if (history[0].fixed_p)
6011     return FALSE;
6012
6013   /* If the previous previous insn was in a .set noreorder, we can't
6014      swap.  Actually, the MIPS assembler will swap in this situation.
6015      However, gcc configured -with-gnu-as will generate code like
6016
6017         .set    noreorder
6018         lw      $4,XXX
6019         .set    reorder
6020         INSN
6021         bne     $4,$0,foo
6022
6023      in which we can not swap the bne and INSN.  If gcc is not configured
6024      -with-gnu-as, it does not output the .set pseudo-ops.  */
6025   if (history[1].noreorder_p)
6026     return FALSE;
6027
6028   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6029      This means that the previous instruction was a 4-byte one anyhow.  */
6030   if (mips_opts.mips16 && history[0].fixp[0])
6031     return FALSE;
6032
6033   /* If the branch is itself the target of a branch, we can not swap.
6034      We cheat on this; all we check for is whether there is a label on
6035      this instruction.  If there are any branches to anything other than
6036      a label, users must use .set noreorder.  */
6037   if (seg_info (now_seg)->label_list)
6038     return FALSE;
6039
6040   /* If the previous instruction is in a variant frag other than this
6041      branch's one, we cannot do the swap.  This does not apply to
6042      MIPS16 code, which uses variant frags for different purposes.  */
6043   if (!mips_opts.mips16
6044       && history[0].frag
6045       && history[0].frag->fr_type == rs_machine_dependent)
6046     return FALSE;
6047
6048   /* We do not swap with instructions that cannot architecturally
6049      be placed in a branch delay slot, such as SYNC or ERET.  We
6050      also refrain from swapping with a trap instruction, since it
6051      complicates trap handlers to have the trap instruction be in
6052      a delay slot.  */
6053   prev_pinfo = history[0].insn_mo->pinfo;
6054   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6055     return FALSE;
6056
6057   /* Check for conflicts between the branch and the instructions
6058      before the candidate delay slot.  */
6059   if (nops_for_insn (0, history + 1, ip) > 0)
6060     return FALSE;
6061
6062   /* Check for conflicts between the swapped sequence and the
6063      target of the branch.  */
6064   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6065     return FALSE;
6066
6067   /* If the branch reads a register that the previous
6068      instruction sets, we can not swap.  */
6069   gpr_read = gpr_read_mask (ip);
6070   prev_gpr_write = gpr_write_mask (&history[0]);
6071   if (gpr_read & prev_gpr_write)
6072     return FALSE;
6073
6074   /* If the branch writes a register that the previous
6075      instruction sets, we can not swap.  */
6076   gpr_write = gpr_write_mask (ip);
6077   if (gpr_write & prev_gpr_write)
6078     return FALSE;
6079
6080   /* If the branch writes a register that the previous
6081      instruction reads, we can not swap.  */
6082   prev_gpr_read = gpr_read_mask (&history[0]);
6083   if (gpr_write & prev_gpr_read)
6084     return FALSE;
6085
6086   /* If one instruction sets a condition code and the
6087      other one uses a condition code, we can not swap.  */
6088   pinfo = ip->insn_mo->pinfo;
6089   if ((pinfo & INSN_READ_COND_CODE)
6090       && (prev_pinfo & INSN_WRITE_COND_CODE))
6091     return FALSE;
6092   if ((pinfo & INSN_WRITE_COND_CODE)
6093       && (prev_pinfo & INSN_READ_COND_CODE))
6094     return FALSE;
6095
6096   /* If the previous instruction uses the PC, we can not swap.  */
6097   prev_pinfo2 = history[0].insn_mo->pinfo2;
6098   if (prev_pinfo2 & INSN2_READ_PC)
6099     return FALSE;
6100
6101   /* If the previous instruction has an incorrect size for a fixed
6102      branch delay slot in microMIPS mode, we cannot swap.  */
6103   pinfo2 = ip->insn_mo->pinfo2;
6104   if (mips_opts.micromips
6105       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6106       && insn_length (history) != 2)
6107     return FALSE;
6108   if (mips_opts.micromips
6109       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6110       && insn_length (history) != 4)
6111     return FALSE;
6112
6113   /* On R5900 short loops need to be fixed by inserting a nop in
6114      the branch delay slots.
6115      A short loop can be terminated too early.  */
6116   if (mips_opts.arch == CPU_R5900
6117       /* Check if instruction has a parameter, ignore "j $31". */
6118       && (address_expr != NULL)
6119       /* Parameter must be 16 bit. */
6120       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6121       /* Branch to same segment. */
6122       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6123       /* Branch to same code fragment. */
6124       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6125       /* Can only calculate branch offset if value is known. */
6126       && symbol_constant_p(address_expr->X_add_symbol)
6127       /* Check if branch is really conditional. */
6128       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6129         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6130         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6131     {
6132       int distance;
6133       /* Check if loop is shorter than 6 instructions including
6134          branch and delay slot.  */
6135       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6136       if (distance <= 20)
6137         {
6138           int i;
6139           int rv;
6140
6141           rv = FALSE;
6142           /* When the loop includes branches or jumps,
6143              it is not a short loop. */
6144           for (i = 0; i < (distance / 4); i++)
6145             {
6146               if ((history[i].cleared_p)
6147                   || delayed_branch_p(&history[i]))
6148                 {
6149                   rv = TRUE;
6150                   break;
6151                 }
6152             }
6153           if (rv == FALSE)
6154             {
6155               /* Insert nop after branch to fix short loop. */
6156               return FALSE;
6157             }
6158         }
6159     }
6160
6161   return TRUE;
6162 }
6163
6164 /* Decide how we should add IP to the instruction stream.
6165    ADDRESS_EXPR is an operand of the instruction to be used with
6166    RELOC_TYPE.  */
6167
6168 static enum append_method
6169 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6170                    bfd_reloc_code_real_type *reloc_type)
6171 {
6172   /* The relaxed version of a macro sequence must be inherently
6173      hazard-free.  */
6174   if (mips_relax.sequence == 2)
6175     return APPEND_ADD;
6176
6177   /* We must not dabble with instructions in a ".set norerorder" block.  */
6178   if (mips_opts.noreorder)
6179     return APPEND_ADD;
6180
6181   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6182   if (delayed_branch_p (ip))
6183     {
6184       if (!branch_likely_p (ip)
6185           && can_swap_branch_p (ip, address_expr, reloc_type))
6186         return APPEND_SWAP;
6187
6188       if (mips_opts.mips16
6189           && ISA_SUPPORTS_MIPS16E
6190           && gpr_read_mask (ip) != 0)
6191         return APPEND_ADD_COMPACT;
6192
6193       return APPEND_ADD_WITH_NOP;
6194     }
6195
6196   return APPEND_ADD;
6197 }
6198
6199 /* IP is a MIPS16 instruction whose opcode we have just changed.
6200    Point IP->insn_mo to the new opcode's definition.  */
6201
6202 static void
6203 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6204 {
6205   const struct mips_opcode *mo, *end;
6206
6207   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6208   for (mo = ip->insn_mo; mo < end; mo++)
6209     if ((ip->insn_opcode & mo->mask) == mo->match)
6210       {
6211         ip->insn_mo = mo;
6212         return;
6213       }
6214   abort ();
6215 }
6216
6217 /* For microMIPS macros, we need to generate a local number label
6218    as the target of branches.  */
6219 #define MICROMIPS_LABEL_CHAR            '\037'
6220 static unsigned long micromips_target_label;
6221 static char micromips_target_name[32];
6222
6223 static char *
6224 micromips_label_name (void)
6225 {
6226   char *p = micromips_target_name;
6227   char symbol_name_temporary[24];
6228   unsigned long l;
6229   int i;
6230
6231   if (*p)
6232     return p;
6233
6234   i = 0;
6235   l = micromips_target_label;
6236 #ifdef LOCAL_LABEL_PREFIX
6237   *p++ = LOCAL_LABEL_PREFIX;
6238 #endif
6239   *p++ = 'L';
6240   *p++ = MICROMIPS_LABEL_CHAR;
6241   do
6242     {
6243       symbol_name_temporary[i++] = l % 10 + '0';
6244       l /= 10;
6245     }
6246   while (l != 0);
6247   while (i > 0)
6248     *p++ = symbol_name_temporary[--i];
6249   *p = '\0';
6250
6251   return micromips_target_name;
6252 }
6253
6254 static void
6255 micromips_label_expr (expressionS *label_expr)
6256 {
6257   label_expr->X_op = O_symbol;
6258   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6259   label_expr->X_add_number = 0;
6260 }
6261
6262 static void
6263 micromips_label_inc (void)
6264 {
6265   micromips_target_label++;
6266   *micromips_target_name = '\0';
6267 }
6268
6269 static void
6270 micromips_add_label (void)
6271 {
6272   symbolS *s;
6273
6274   s = colon (micromips_label_name ());
6275   micromips_label_inc ();
6276   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6277 }
6278
6279 /* If assembling microMIPS code, then return the microMIPS reloc
6280    corresponding to the requested one if any.  Otherwise return
6281    the reloc unchanged.  */
6282
6283 static bfd_reloc_code_real_type
6284 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6285 {
6286   static const bfd_reloc_code_real_type relocs[][2] =
6287     {
6288       /* Keep sorted incrementally by the left-hand key.  */
6289       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6290       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6291       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6292       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6293       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6294       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6295       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6296       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6297       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6298       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6299       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6300       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6301       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6302       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6303       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6304       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6305       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6306       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6307       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6308       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6309       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6310       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6311       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6312       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6313       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6314       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6315       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6316     };
6317   bfd_reloc_code_real_type r;
6318   size_t i;
6319
6320   if (!mips_opts.micromips)
6321     return reloc;
6322   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6323     {
6324       r = relocs[i][0];
6325       if (r > reloc)
6326         return reloc;
6327       if (r == reloc)
6328         return relocs[i][1];
6329     }
6330   return reloc;
6331 }
6332
6333 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6334    Return true on success, storing the resolved value in RESULT.  */
6335
6336 static bfd_boolean
6337 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6338                  offsetT *result)
6339 {
6340   switch (reloc)
6341     {
6342     case BFD_RELOC_MIPS_HIGHEST:
6343     case BFD_RELOC_MICROMIPS_HIGHEST:
6344       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6345       return TRUE;
6346
6347     case BFD_RELOC_MIPS_HIGHER:
6348     case BFD_RELOC_MICROMIPS_HIGHER:
6349       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6350       return TRUE;
6351
6352     case BFD_RELOC_HI16_S:
6353     case BFD_RELOC_MICROMIPS_HI16_S:
6354     case BFD_RELOC_MIPS16_HI16_S:
6355       *result = ((operand + 0x8000) >> 16) & 0xffff;
6356       return TRUE;
6357
6358     case BFD_RELOC_HI16:
6359     case BFD_RELOC_MICROMIPS_HI16:
6360     case BFD_RELOC_MIPS16_HI16:
6361       *result = (operand >> 16) & 0xffff;
6362       return TRUE;
6363
6364     case BFD_RELOC_LO16:
6365     case BFD_RELOC_MICROMIPS_LO16:
6366     case BFD_RELOC_MIPS16_LO16:
6367       *result = operand & 0xffff;
6368       return TRUE;
6369
6370     case BFD_RELOC_UNUSED:
6371       *result = operand;
6372       return TRUE;
6373
6374     default:
6375       return FALSE;
6376     }
6377 }
6378
6379 /* Output an instruction.  IP is the instruction information.
6380    ADDRESS_EXPR is an operand of the instruction to be used with
6381    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6382    a macro expansion.  */
6383
6384 static void
6385 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6386              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6387 {
6388   unsigned long prev_pinfo2, pinfo;
6389   bfd_boolean relaxed_branch = FALSE;
6390   enum append_method method;
6391   bfd_boolean relax32;
6392   int branch_disp;
6393
6394   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6395     fix_loongson2f (ip);
6396
6397   file_ase_mips16 |= mips_opts.mips16;
6398   file_ase_micromips |= mips_opts.micromips;
6399
6400   prev_pinfo2 = history[0].insn_mo->pinfo2;
6401   pinfo = ip->insn_mo->pinfo;
6402
6403   if (mips_opts.micromips
6404       && !expansionp
6405       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6406            && micromips_insn_length (ip->insn_mo) != 2)
6407           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6408               && micromips_insn_length (ip->insn_mo) != 4)))
6409     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6410              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6411
6412   if (address_expr == NULL)
6413     ip->complete_p = 1;
6414   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6415            && reloc_type[1] == BFD_RELOC_UNUSED
6416            && reloc_type[2] == BFD_RELOC_UNUSED
6417            && address_expr->X_op == O_constant)
6418     {
6419       switch (*reloc_type)
6420         {
6421         case BFD_RELOC_MIPS_JMP:
6422           {
6423             int shift;
6424
6425             shift = mips_opts.micromips ? 1 : 2;
6426             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6427               as_bad (_("jump to misaligned address (0x%lx)"),
6428                       (unsigned long) address_expr->X_add_number);
6429             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6430                                 & 0x3ffffff);
6431             ip->complete_p = 1;
6432           }
6433           break;
6434
6435         case BFD_RELOC_MIPS16_JMP:
6436           if ((address_expr->X_add_number & 3) != 0)
6437             as_bad (_("jump to misaligned address (0x%lx)"),
6438                     (unsigned long) address_expr->X_add_number);
6439           ip->insn_opcode |=
6440             (((address_expr->X_add_number & 0x7c0000) << 3)
6441                | ((address_expr->X_add_number & 0xf800000) >> 7)
6442                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6443           ip->complete_p = 1;
6444           break;
6445
6446         case BFD_RELOC_16_PCREL_S2:
6447           {
6448             int shift;
6449
6450             shift = mips_opts.micromips ? 1 : 2;
6451             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6452               as_bad (_("branch to misaligned address (0x%lx)"),
6453                       (unsigned long) address_expr->X_add_number);
6454             if (!mips_relax_branch)
6455               {
6456                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6457                     & ~((1 << (shift + 16)) - 1))
6458                   as_bad (_("branch address range overflow (0x%lx)"),
6459                           (unsigned long) address_expr->X_add_number);
6460                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6461                                     & 0xffff);
6462               }
6463           }
6464           break;
6465
6466         default:
6467           {
6468             offsetT value;
6469
6470             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6471                                  &value))
6472               {
6473                 ip->insn_opcode |= value & 0xffff;
6474                 ip->complete_p = 1;
6475               }
6476           }
6477           break;
6478         }
6479     }
6480
6481   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6482     {
6483       /* There are a lot of optimizations we could do that we don't.
6484          In particular, we do not, in general, reorder instructions.
6485          If you use gcc with optimization, it will reorder
6486          instructions and generally do much more optimization then we
6487          do here; repeating all that work in the assembler would only
6488          benefit hand written assembly code, and does not seem worth
6489          it.  */
6490       int nops = (mips_optimize == 0
6491                   ? nops_for_insn (0, history, NULL)
6492                   : nops_for_insn_or_target (0, history, ip));
6493       if (nops > 0)
6494         {
6495           fragS *old_frag;
6496           unsigned long old_frag_offset;
6497           int i;
6498
6499           old_frag = frag_now;
6500           old_frag_offset = frag_now_fix ();
6501
6502           for (i = 0; i < nops; i++)
6503             add_fixed_insn (NOP_INSN);
6504           insert_into_history (0, nops, NOP_INSN);
6505
6506           if (listing)
6507             {
6508               listing_prev_line ();
6509               /* We may be at the start of a variant frag.  In case we
6510                  are, make sure there is enough space for the frag
6511                  after the frags created by listing_prev_line.  The
6512                  argument to frag_grow here must be at least as large
6513                  as the argument to all other calls to frag_grow in
6514                  this file.  We don't have to worry about being in the
6515                  middle of a variant frag, because the variants insert
6516                  all needed nop instructions themselves.  */
6517               frag_grow (40);
6518             }
6519
6520           mips_move_text_labels ();
6521
6522 #ifndef NO_ECOFF_DEBUGGING
6523           if (ECOFF_DEBUGGING)
6524             ecoff_fix_loc (old_frag, old_frag_offset);
6525 #endif
6526         }
6527     }
6528   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6529     {
6530       int nops;
6531
6532       /* Work out how many nops in prev_nop_frag are needed by IP,
6533          ignoring hazards generated by the first prev_nop_frag_since
6534          instructions.  */
6535       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6536       gas_assert (nops <= prev_nop_frag_holds);
6537
6538       /* Enforce NOPS as a minimum.  */
6539       if (nops > prev_nop_frag_required)
6540         prev_nop_frag_required = nops;
6541
6542       if (prev_nop_frag_holds == prev_nop_frag_required)
6543         {
6544           /* Settle for the current number of nops.  Update the history
6545              accordingly (for the benefit of any future .set reorder code).  */
6546           prev_nop_frag = NULL;
6547           insert_into_history (prev_nop_frag_since,
6548                                prev_nop_frag_holds, NOP_INSN);
6549         }
6550       else
6551         {
6552           /* Allow this instruction to replace one of the nops that was
6553              tentatively added to prev_nop_frag.  */
6554           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6555           prev_nop_frag_holds--;
6556           prev_nop_frag_since++;
6557         }
6558     }
6559
6560   method = get_append_method (ip, address_expr, reloc_type);
6561   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6562
6563   dwarf2_emit_insn (0);
6564   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6565      so "move" the instruction address accordingly.
6566
6567      Also, it doesn't seem appropriate for the assembler to reorder .loc
6568      entries.  If this instruction is a branch that we are going to swap
6569      with the previous instruction, the two instructions should be
6570      treated as a unit, and the debug information for both instructions
6571      should refer to the start of the branch sequence.  Using the
6572      current position is certainly wrong when swapping a 32-bit branch
6573      and a 16-bit delay slot, since the current position would then be
6574      in the middle of a branch.  */
6575   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6576
6577   relax32 = (mips_relax_branch
6578              /* Don't try branch relaxation within .set nomacro, or within
6579                 .set noat if we use $at for PIC computations.  If it turns
6580                 out that the branch was out-of-range, we'll get an error.  */
6581              && !mips_opts.warn_about_macros
6582              && (mips_opts.at || mips_pic == NO_PIC)
6583              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6584                 as they have no complementing branches.  */
6585              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6586
6587   if (!HAVE_CODE_COMPRESSION
6588       && address_expr
6589       && relax32
6590       && *reloc_type == BFD_RELOC_16_PCREL_S2
6591       && delayed_branch_p (ip))
6592     {
6593       relaxed_branch = TRUE;
6594       add_relaxed_insn (ip, (relaxed_branch_length
6595                              (NULL, NULL,
6596                               uncond_branch_p (ip) ? -1
6597                               : branch_likely_p (ip) ? 1
6598                               : 0)), 4,
6599                         RELAX_BRANCH_ENCODE
6600                         (AT,
6601                          uncond_branch_p (ip),
6602                          branch_likely_p (ip),
6603                          pinfo & INSN_WRITE_GPR_31,
6604                          0),
6605                         address_expr->X_add_symbol,
6606                         address_expr->X_add_number);
6607       *reloc_type = BFD_RELOC_UNUSED;
6608     }
6609   else if (mips_opts.micromips
6610            && address_expr
6611            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6612                || *reloc_type > BFD_RELOC_UNUSED)
6613            && (delayed_branch_p (ip) || compact_branch_p (ip))
6614            /* Don't try branch relaxation when users specify
6615               16-bit/32-bit instructions.  */
6616            && !forced_insn_length)
6617     {
6618       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6619       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6620       int uncond = uncond_branch_p (ip) ? -1 : 0;
6621       int compact = compact_branch_p (ip);
6622       int al = pinfo & INSN_WRITE_GPR_31;
6623       int length32;
6624
6625       gas_assert (address_expr != NULL);
6626       gas_assert (!mips_relax.sequence);
6627
6628       relaxed_branch = TRUE;
6629       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6630       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6631                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6632                                                 relax32, 0, 0),
6633                         address_expr->X_add_symbol,
6634                         address_expr->X_add_number);
6635       *reloc_type = BFD_RELOC_UNUSED;
6636     }
6637   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6638     {
6639       /* We need to set up a variant frag.  */
6640       gas_assert (address_expr != NULL);
6641       add_relaxed_insn (ip, 4, 0,
6642                         RELAX_MIPS16_ENCODE
6643                         (*reloc_type - BFD_RELOC_UNUSED,
6644                          forced_insn_length == 2, forced_insn_length == 4,
6645                          delayed_branch_p (&history[0]),
6646                          history[0].mips16_absolute_jump_p),
6647                         make_expr_symbol (address_expr), 0);
6648     }
6649   else if (mips_opts.mips16 && insn_length (ip) == 2)
6650     {
6651       if (!delayed_branch_p (ip))
6652         /* Make sure there is enough room to swap this instruction with
6653            a following jump instruction.  */
6654         frag_grow (6);
6655       add_fixed_insn (ip);
6656     }
6657   else
6658     {
6659       if (mips_opts.mips16
6660           && mips_opts.noreorder
6661           && delayed_branch_p (&history[0]))
6662         as_warn (_("extended instruction in delay slot"));
6663
6664       if (mips_relax.sequence)
6665         {
6666           /* If we've reached the end of this frag, turn it into a variant
6667              frag and record the information for the instructions we've
6668              written so far.  */
6669           if (frag_room () < 4)
6670             relax_close_frag ();
6671           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6672         }
6673
6674       if (mips_relax.sequence != 2)
6675         {
6676           if (mips_macro_warning.first_insn_sizes[0] == 0)
6677             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6678           mips_macro_warning.sizes[0] += insn_length (ip);
6679           mips_macro_warning.insns[0]++;
6680         }
6681       if (mips_relax.sequence != 1)
6682         {
6683           if (mips_macro_warning.first_insn_sizes[1] == 0)
6684             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6685           mips_macro_warning.sizes[1] += insn_length (ip);
6686           mips_macro_warning.insns[1]++;
6687         }
6688
6689       if (mips_opts.mips16)
6690         {
6691           ip->fixed_p = 1;
6692           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6693         }
6694       add_fixed_insn (ip);
6695     }
6696
6697   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6698     {
6699       bfd_reloc_code_real_type final_type[3];
6700       reloc_howto_type *howto0;
6701       reloc_howto_type *howto;
6702       int i;
6703
6704       /* Perform any necessary conversion to microMIPS relocations
6705          and find out how many relocations there actually are.  */
6706       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6707         final_type[i] = micromips_map_reloc (reloc_type[i]);
6708
6709       /* In a compound relocation, it is the final (outermost)
6710          operator that determines the relocated field.  */
6711       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6712       if (!howto)
6713         abort ();
6714
6715       if (i > 1)
6716         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6717       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6718                                  bfd_get_reloc_size (howto),
6719                                  address_expr,
6720                                  howto0 && howto0->pc_relative,
6721                                  final_type[0]);
6722
6723       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6724       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6725         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6726
6727       /* These relocations can have an addend that won't fit in
6728          4 octets for 64bit assembly.  */
6729       if (HAVE_64BIT_GPRS
6730           && ! howto->partial_inplace
6731           && (reloc_type[0] == BFD_RELOC_16
6732               || reloc_type[0] == BFD_RELOC_32
6733               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6734               || reloc_type[0] == BFD_RELOC_GPREL16
6735               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6736               || reloc_type[0] == BFD_RELOC_GPREL32
6737               || reloc_type[0] == BFD_RELOC_64
6738               || reloc_type[0] == BFD_RELOC_CTOR
6739               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6740               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6741               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6742               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6743               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6744               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6745               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6746               || hi16_reloc_p (reloc_type[0])
6747               || lo16_reloc_p (reloc_type[0])))
6748         ip->fixp[0]->fx_no_overflow = 1;
6749
6750       /* These relocations can have an addend that won't fit in 2 octets.  */
6751       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6752           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6753         ip->fixp[0]->fx_no_overflow = 1;
6754
6755       if (mips_relax.sequence)
6756         {
6757           if (mips_relax.first_fixup == 0)
6758             mips_relax.first_fixup = ip->fixp[0];
6759         }
6760       else if (reloc_needs_lo_p (*reloc_type))
6761         {
6762           struct mips_hi_fixup *hi_fixup;
6763
6764           /* Reuse the last entry if it already has a matching %lo.  */
6765           hi_fixup = mips_hi_fixup_list;
6766           if (hi_fixup == 0
6767               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6768             {
6769               hi_fixup = ((struct mips_hi_fixup *)
6770                           xmalloc (sizeof (struct mips_hi_fixup)));
6771               hi_fixup->next = mips_hi_fixup_list;
6772               mips_hi_fixup_list = hi_fixup;
6773             }
6774           hi_fixup->fixp = ip->fixp[0];
6775           hi_fixup->seg = now_seg;
6776         }
6777
6778       /* Add fixups for the second and third relocations, if given.
6779          Note that the ABI allows the second relocation to be
6780          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6781          moment we only use RSS_UNDEF, but we could add support
6782          for the others if it ever becomes necessary.  */
6783       for (i = 1; i < 3; i++)
6784         if (reloc_type[i] != BFD_RELOC_UNUSED)
6785           {
6786             ip->fixp[i] = fix_new (ip->frag, ip->where,
6787                                    ip->fixp[0]->fx_size, NULL, 0,
6788                                    FALSE, final_type[i]);
6789
6790             /* Use fx_tcbit to mark compound relocs.  */
6791             ip->fixp[0]->fx_tcbit = 1;
6792             ip->fixp[i]->fx_tcbit = 1;
6793           }
6794     }
6795   install_insn (ip);
6796
6797   /* Update the register mask information.  */
6798   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6799   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6800
6801   switch (method)
6802     {
6803     case APPEND_ADD:
6804       insert_into_history (0, 1, ip);
6805       break;
6806
6807     case APPEND_ADD_WITH_NOP:
6808       {
6809         struct mips_cl_insn *nop;
6810
6811         insert_into_history (0, 1, ip);
6812         nop = get_delay_slot_nop (ip);
6813         add_fixed_insn (nop);
6814         insert_into_history (0, 1, nop);
6815         if (mips_relax.sequence)
6816           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6817       }
6818       break;
6819
6820     case APPEND_ADD_COMPACT:
6821       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6822       gas_assert (mips_opts.mips16);
6823       ip->insn_opcode |= 0x0080;
6824       find_altered_mips16_opcode (ip);
6825       install_insn (ip);
6826       insert_into_history (0, 1, ip);
6827       break;
6828
6829     case APPEND_SWAP:
6830       {
6831         struct mips_cl_insn delay = history[0];
6832         if (mips_opts.mips16)
6833           {
6834             know (delay.frag == ip->frag);
6835             move_insn (ip, delay.frag, delay.where);
6836             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6837           }
6838         else if (relaxed_branch || delay.frag != ip->frag)
6839           {
6840             /* Add the delay slot instruction to the end of the
6841                current frag and shrink the fixed part of the
6842                original frag.  If the branch occupies the tail of
6843                the latter, move it backwards to cover the gap.  */
6844             delay.frag->fr_fix -= branch_disp;
6845             if (delay.frag == ip->frag)
6846               move_insn (ip, ip->frag, ip->where - branch_disp);
6847             add_fixed_insn (&delay);
6848           }
6849         else
6850           {
6851             move_insn (&delay, ip->frag,
6852                        ip->where - branch_disp + insn_length (ip));
6853             move_insn (ip, history[0].frag, history[0].where);
6854           }
6855         history[0] = *ip;
6856         delay.fixed_p = 1;
6857         insert_into_history (0, 1, &delay);
6858       }
6859       break;
6860     }
6861
6862   /* If we have just completed an unconditional branch, clear the history.  */
6863   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6864       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6865     {
6866       unsigned int i;
6867
6868       mips_no_prev_insn ();
6869
6870       for (i = 0; i < ARRAY_SIZE (history); i++)
6871         history[i].cleared_p = 1;
6872     }
6873
6874   /* We need to emit a label at the end of branch-likely macros.  */
6875   if (emit_branch_likely_macro)
6876     {
6877       emit_branch_likely_macro = FALSE;
6878       micromips_add_label ();
6879     }
6880
6881   /* We just output an insn, so the next one doesn't have a label.  */
6882   mips_clear_insn_labels ();
6883 }
6884
6885 /* Forget that there was any previous instruction or label.
6886    When BRANCH is true, the branch history is also flushed.  */
6887
6888 static void
6889 mips_no_prev_insn (void)
6890 {
6891   prev_nop_frag = NULL;
6892   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
6893   mips_clear_insn_labels ();
6894 }
6895
6896 /* This function must be called before we emit something other than
6897    instructions.  It is like mips_no_prev_insn except that it inserts
6898    any NOPS that might be needed by previous instructions.  */
6899
6900 void
6901 mips_emit_delays (void)
6902 {
6903   if (! mips_opts.noreorder)
6904     {
6905       int nops = nops_for_insn (0, history, NULL);
6906       if (nops > 0)
6907         {
6908           while (nops-- > 0)
6909             add_fixed_insn (NOP_INSN);
6910           mips_move_text_labels ();
6911         }
6912     }
6913   mips_no_prev_insn ();
6914 }
6915
6916 /* Start a (possibly nested) noreorder block.  */
6917
6918 static void
6919 start_noreorder (void)
6920 {
6921   if (mips_opts.noreorder == 0)
6922     {
6923       unsigned int i;
6924       int nops;
6925
6926       /* None of the instructions before the .set noreorder can be moved.  */
6927       for (i = 0; i < ARRAY_SIZE (history); i++)
6928         history[i].fixed_p = 1;
6929
6930       /* Insert any nops that might be needed between the .set noreorder
6931          block and the previous instructions.  We will later remove any
6932          nops that turn out not to be needed.  */
6933       nops = nops_for_insn (0, history, NULL);
6934       if (nops > 0)
6935         {
6936           if (mips_optimize != 0)
6937             {
6938               /* Record the frag which holds the nop instructions, so
6939                  that we can remove them if we don't need them.  */
6940               frag_grow (nops * NOP_INSN_SIZE);
6941               prev_nop_frag = frag_now;
6942               prev_nop_frag_holds = nops;
6943               prev_nop_frag_required = 0;
6944               prev_nop_frag_since = 0;
6945             }
6946
6947           for (; nops > 0; --nops)
6948             add_fixed_insn (NOP_INSN);
6949
6950           /* Move on to a new frag, so that it is safe to simply
6951              decrease the size of prev_nop_frag.  */
6952           frag_wane (frag_now);
6953           frag_new (0);
6954           mips_move_text_labels ();
6955         }
6956       mips_mark_labels ();
6957       mips_clear_insn_labels ();
6958     }
6959   mips_opts.noreorder++;
6960   mips_any_noreorder = 1;
6961 }
6962
6963 /* End a nested noreorder block.  */
6964
6965 static void
6966 end_noreorder (void)
6967 {
6968   mips_opts.noreorder--;
6969   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
6970     {
6971       /* Commit to inserting prev_nop_frag_required nops and go back to
6972          handling nop insertion the .set reorder way.  */
6973       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
6974                                 * NOP_INSN_SIZE);
6975       insert_into_history (prev_nop_frag_since,
6976                            prev_nop_frag_required, NOP_INSN);
6977       prev_nop_frag = NULL;
6978     }
6979 }
6980
6981 /* Sign-extend 32-bit mode constants that have bit 31 set and all
6982    higher bits unset.  */
6983
6984 static void
6985 normalize_constant_expr (expressionS *ex)
6986 {
6987   if (ex->X_op == O_constant
6988       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
6989     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
6990                         - 0x80000000);
6991 }
6992
6993 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
6994    all higher bits unset.  */
6995
6996 static void
6997 normalize_address_expr (expressionS *ex)
6998 {
6999   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7000         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7001       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7002     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7003                         - 0x80000000);
7004 }
7005
7006 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7007    Return true if the match was successful.
7008
7009    OPCODE_EXTRA is a value that should be ORed into the opcode
7010    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7011    there are more alternatives after OPCODE and SOFT_MATCH is
7012    as for mips_arg_info.  */
7013
7014 static bfd_boolean
7015 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7016             struct mips_operand_token *tokens, unsigned int opcode_extra,
7017             bfd_boolean lax_match, bfd_boolean complete_p)
7018 {
7019   const char *args;
7020   struct mips_arg_info arg;
7021   const struct mips_operand *operand;
7022   char c;
7023
7024   imm_expr.X_op = O_absent;
7025   offset_expr.X_op = O_absent;
7026   offset_reloc[0] = BFD_RELOC_UNUSED;
7027   offset_reloc[1] = BFD_RELOC_UNUSED;
7028   offset_reloc[2] = BFD_RELOC_UNUSED;
7029
7030   create_insn (insn, opcode);
7031   /* When no opcode suffix is specified, assume ".xyzw". */
7032   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7033     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7034   else
7035     insn->insn_opcode |= opcode_extra;
7036   memset (&arg, 0, sizeof (arg));
7037   arg.insn = insn;
7038   arg.token = tokens;
7039   arg.argnum = 1;
7040   arg.last_regno = ILLEGAL_REG;
7041   arg.dest_regno = ILLEGAL_REG;
7042   arg.lax_match = lax_match;
7043   for (args = opcode->args;; ++args)
7044     {
7045       if (arg.token->type == OT_END)
7046         {
7047           /* Handle unary instructions in which only one operand is given.
7048              The source is then the same as the destination.  */
7049           if (arg.opnum == 1 && *args == ',')
7050             {
7051               operand = (mips_opts.micromips
7052                          ? decode_micromips_operand (args + 1)
7053                          : decode_mips_operand (args + 1));
7054               if (operand && mips_optional_operand_p (operand))
7055                 {
7056                   arg.token = tokens;
7057                   arg.argnum = 1;
7058                   continue;
7059                 }
7060             }
7061
7062           /* Treat elided base registers as $0.  */
7063           if (strcmp (args, "(b)") == 0)
7064             args += 3;
7065
7066           if (args[0] == '+')
7067             switch (args[1])
7068               {
7069               case 'K':
7070               case 'N':
7071                 /* The register suffix is optional. */
7072                 args += 2;
7073                 break;
7074               }
7075
7076           /* Fail the match if there were too few operands.  */
7077           if (*args)
7078             return FALSE;
7079
7080           /* Successful match.  */
7081           if (!complete_p)
7082             return TRUE;
7083           clear_insn_error ();
7084           if (arg.dest_regno == arg.last_regno
7085               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7086             {
7087               if (arg.opnum == 2)
7088                 set_insn_error
7089                   (0, _("source and destination must be different"));
7090               else if (arg.last_regno == 31)
7091                 set_insn_error
7092                   (0, _("a destination register must be supplied"));
7093             }
7094           else if (arg.last_regno == 31
7095                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7096                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7097             set_insn_error (0, _("the source register must not be $31"));
7098           check_completed_insn (&arg);
7099           return TRUE;
7100         }
7101
7102       /* Fail the match if the line has too many operands.   */
7103       if (*args == 0)
7104         return FALSE;
7105
7106       /* Handle characters that need to match exactly.  */
7107       if (*args == '(' || *args == ')' || *args == ',')
7108         {
7109           if (match_char (&arg, *args))
7110             continue;
7111           return FALSE;
7112         }
7113       if (*args == '#')
7114         {
7115           ++args;
7116           if (arg.token->type == OT_DOUBLE_CHAR
7117               && arg.token->u.ch == *args)
7118             {
7119               ++arg.token;
7120               continue;
7121             }
7122           return FALSE;
7123         }
7124
7125       /* Handle special macro operands.  Work out the properties of
7126          other operands.  */
7127       arg.opnum += 1;
7128       switch (*args)
7129         {
7130         case '+':
7131           switch (args[1])
7132             {
7133             case 'i':
7134               *offset_reloc = BFD_RELOC_MIPS_JMP;
7135               break;
7136             }
7137           break;
7138
7139         case 'I':
7140           if (!match_const_int (&arg, &imm_expr.X_add_number))
7141             return FALSE;
7142           imm_expr.X_op = O_constant;
7143           if (HAVE_32BIT_GPRS)
7144             normalize_constant_expr (&imm_expr);
7145           continue;
7146
7147         case 'A':
7148           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7149             {
7150               /* Assume that the offset has been elided and that what
7151                  we saw was a base register.  The match will fail later
7152                  if that assumption turns out to be wrong.  */
7153               offset_expr.X_op = O_constant;
7154               offset_expr.X_add_number = 0;
7155             }
7156           else
7157             {
7158               if (!match_expression (&arg, &offset_expr, offset_reloc))
7159                 return FALSE;
7160               normalize_address_expr (&offset_expr);
7161             }
7162           continue;
7163
7164         case 'F':
7165           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7166                                      8, TRUE))
7167             return FALSE;
7168           continue;
7169
7170         case 'L':
7171           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7172                                      8, FALSE))
7173             return FALSE;
7174           continue;
7175
7176         case 'f':
7177           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7178                                      4, TRUE))
7179             return FALSE;
7180           continue;
7181
7182         case 'l':
7183           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7184                                      4, FALSE))
7185             return FALSE;
7186           continue;
7187
7188         case 'p':
7189           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7190           break;
7191
7192         case 'a':
7193           *offset_reloc = BFD_RELOC_MIPS_JMP;
7194           break;
7195
7196         case 'm':
7197           gas_assert (mips_opts.micromips);
7198           c = args[1];
7199           switch (c)
7200             {
7201             case 'D':
7202             case 'E':
7203               if (!forced_insn_length)
7204                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7205               else if (c == 'D')
7206                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7207               else
7208                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7209               break;
7210             }
7211           break;
7212         }
7213
7214       operand = (mips_opts.micromips
7215                  ? decode_micromips_operand (args)
7216                  : decode_mips_operand (args));
7217       if (!operand)
7218         abort ();
7219
7220       /* Skip prefixes.  */
7221       if (*args == '+' || *args == 'm')
7222         args++;
7223
7224       if (mips_optional_operand_p (operand)
7225           && args[1] == ','
7226           && (arg.token[0].type != OT_REG
7227               || arg.token[1].type == OT_END))
7228         {
7229           /* Assume that the register has been elided and is the
7230              same as the first operand.  */
7231           arg.token = tokens;
7232           arg.argnum = 1;
7233         }
7234
7235       if (!match_operand (&arg, operand))
7236         return FALSE;
7237     }
7238 }
7239
7240 /* Like match_insn, but for MIPS16.  */
7241
7242 static bfd_boolean
7243 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7244                    struct mips_operand_token *tokens)
7245 {
7246   const char *args;
7247   const struct mips_operand *operand;
7248   const struct mips_operand *ext_operand;
7249   struct mips_arg_info arg;
7250   int relax_char;
7251
7252   create_insn (insn, opcode);
7253   imm_expr.X_op = O_absent;
7254   offset_expr.X_op = O_absent;
7255   offset_reloc[0] = BFD_RELOC_UNUSED;
7256   offset_reloc[1] = BFD_RELOC_UNUSED;
7257   offset_reloc[2] = BFD_RELOC_UNUSED;
7258   relax_char = 0;
7259
7260   memset (&arg, 0, sizeof (arg));
7261   arg.insn = insn;
7262   arg.token = tokens;
7263   arg.argnum = 1;
7264   arg.last_regno = ILLEGAL_REG;
7265   arg.dest_regno = ILLEGAL_REG;
7266   relax_char = 0;
7267   for (args = opcode->args;; ++args)
7268     {
7269       int c;
7270
7271       if (arg.token->type == OT_END)
7272         {
7273           offsetT value;
7274
7275           /* Handle unary instructions in which only one operand is given.
7276              The source is then the same as the destination.  */
7277           if (arg.opnum == 1 && *args == ',')
7278             {
7279               operand = decode_mips16_operand (args[1], FALSE);
7280               if (operand && mips_optional_operand_p (operand))
7281                 {
7282                   arg.token = tokens;
7283                   arg.argnum = 1;
7284                   continue;
7285                 }
7286             }
7287
7288           /* Fail the match if there were too few operands.  */
7289           if (*args)
7290             return FALSE;
7291
7292           /* Successful match.  Stuff the immediate value in now, if
7293              we can.  */
7294           clear_insn_error ();
7295           if (opcode->pinfo == INSN_MACRO)
7296             {
7297               gas_assert (relax_char == 0 || relax_char == 'p');
7298               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7299             }
7300           else if (relax_char
7301                    && offset_expr.X_op == O_constant
7302                    && calculate_reloc (*offset_reloc,
7303                                        offset_expr.X_add_number,
7304                                        &value))
7305             {
7306               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7307                             forced_insn_length, &insn->insn_opcode);
7308               offset_expr.X_op = O_absent;
7309               *offset_reloc = BFD_RELOC_UNUSED;
7310             }
7311           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7312             {
7313               if (forced_insn_length == 2)
7314                 set_insn_error (0, _("invalid unextended operand value"));
7315               forced_insn_length = 4;
7316               insn->insn_opcode |= MIPS16_EXTEND;
7317             }
7318           else if (relax_char)
7319             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7320
7321           check_completed_insn (&arg);
7322           return TRUE;
7323         }
7324
7325       /* Fail the match if the line has too many operands.   */
7326       if (*args == 0)
7327         return FALSE;
7328
7329       /* Handle characters that need to match exactly.  */
7330       if (*args == '(' || *args == ')' || *args == ',')
7331         {
7332           if (match_char (&arg, *args))
7333             continue;
7334           return FALSE;
7335         }
7336
7337       arg.opnum += 1;
7338       c = *args;
7339       switch (c)
7340         {
7341         case 'p':
7342         case 'q':
7343         case 'A':
7344         case 'B':
7345         case 'E':
7346           relax_char = c;
7347           break;
7348
7349         case 'I':
7350           if (!match_const_int (&arg, &imm_expr.X_add_number))
7351             return FALSE;
7352           imm_expr.X_op = O_constant;
7353           if (HAVE_32BIT_GPRS)
7354             normalize_constant_expr (&imm_expr);
7355           continue;
7356
7357         case 'a':
7358         case 'i':
7359           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7360           insn->insn_opcode <<= 16;
7361           break;
7362         }
7363
7364       operand = decode_mips16_operand (c, FALSE);
7365       if (!operand)
7366         abort ();
7367
7368       /* '6' is a special case.  It is used for BREAK and SDBBP,
7369          whose operands are only meaningful to the software that decodes
7370          them.  This means that there is no architectural reason why
7371          they cannot be prefixed by EXTEND, but in practice,
7372          exception handlers will only look at the instruction
7373          itself.  We therefore allow '6' to be extended when
7374          disassembling but not when assembling.  */
7375       if (operand->type != OP_PCREL && c != '6')
7376         {
7377           ext_operand = decode_mips16_operand (c, TRUE);
7378           if (operand != ext_operand)
7379             {
7380               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7381                 {
7382                   offset_expr.X_op = O_constant;
7383                   offset_expr.X_add_number = 0;
7384                   relax_char = c;
7385                   continue;
7386                 }
7387
7388               /* We need the OT_INTEGER check because some MIPS16
7389                  immediate variants are listed before the register ones.  */
7390               if (arg.token->type != OT_INTEGER
7391                   || !match_expression (&arg, &offset_expr, offset_reloc))
7392                 return FALSE;
7393
7394               /* '8' is used for SLTI(U) and has traditionally not
7395                  been allowed to take relocation operators.  */
7396               if (offset_reloc[0] != BFD_RELOC_UNUSED
7397                   && (ext_operand->size != 16 || c == '8'))
7398                 return FALSE;
7399
7400               relax_char = c;
7401               continue;
7402             }
7403         }
7404
7405       if (mips_optional_operand_p (operand)
7406           && args[1] == ','
7407           && (arg.token[0].type != OT_REG
7408               || arg.token[1].type == OT_END))
7409         {
7410           /* Assume that the register has been elided and is the
7411              same as the first operand.  */
7412           arg.token = tokens;
7413           arg.argnum = 1;
7414         }
7415
7416       if (!match_operand (&arg, operand))
7417         return FALSE;
7418     }
7419 }
7420
7421 /* Record that the current instruction is invalid for the current ISA.  */
7422
7423 static void
7424 match_invalid_for_isa (void)
7425 {
7426   set_insn_error_ss
7427     (0, _("opcode not supported on this processor: %s (%s)"),
7428      mips_cpu_info_from_arch (mips_opts.arch)->name,
7429      mips_cpu_info_from_isa (mips_opts.isa)->name);
7430 }
7431
7432 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7433    Return true if a definite match or failure was found, storing any match
7434    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7435    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7436    tried and failed to match under normal conditions and now want to try a
7437    more relaxed match.  */
7438
7439 static bfd_boolean
7440 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7441              const struct mips_opcode *past, struct mips_operand_token *tokens,
7442              int opcode_extra, bfd_boolean lax_match)
7443 {
7444   const struct mips_opcode *opcode;
7445   const struct mips_opcode *invalid_delay_slot;
7446   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7447
7448   /* Search for a match, ignoring alternatives that don't satisfy the
7449      current ISA or forced_length.  */
7450   invalid_delay_slot = 0;
7451   seen_valid_for_isa = FALSE;
7452   seen_valid_for_size = FALSE;
7453   opcode = first;
7454   do
7455     {
7456       gas_assert (strcmp (opcode->name, first->name) == 0);
7457       if (is_opcode_valid (opcode))
7458         {
7459           seen_valid_for_isa = TRUE;
7460           if (is_size_valid (opcode))
7461             {
7462               bfd_boolean delay_slot_ok;
7463
7464               seen_valid_for_size = TRUE;
7465               delay_slot_ok = is_delay_slot_valid (opcode);
7466               if (match_insn (insn, opcode, tokens, opcode_extra,
7467                               lax_match, delay_slot_ok))
7468                 {
7469                   if (!delay_slot_ok)
7470                     {
7471                       if (!invalid_delay_slot)
7472                         invalid_delay_slot = opcode;
7473                     }
7474                   else
7475                     return TRUE;
7476                 }
7477             }
7478         }
7479       ++opcode;
7480     }
7481   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7482
7483   /* If the only matches we found had the wrong length for the delay slot,
7484      pick the first such match.  We'll issue an appropriate warning later.  */
7485   if (invalid_delay_slot)
7486     {
7487       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7488                       lax_match, TRUE))
7489         return TRUE;
7490       abort ();
7491     }
7492
7493   /* Handle the case where we didn't try to match an instruction because
7494      all the alternatives were incompatible with the current ISA.  */
7495   if (!seen_valid_for_isa)
7496     {
7497       match_invalid_for_isa ();
7498       return TRUE;
7499     }
7500
7501   /* Handle the case where we didn't try to match an instruction because
7502      all the alternatives were of the wrong size.  */
7503   if (!seen_valid_for_size)
7504     {
7505       if (mips_opts.insn32)
7506         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7507       else
7508         set_insn_error_i
7509           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7510            8 * forced_insn_length);
7511       return TRUE;
7512     }
7513
7514   return FALSE;
7515 }
7516
7517 /* Like match_insns, but for MIPS16.  */
7518
7519 static bfd_boolean
7520 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7521                     struct mips_operand_token *tokens)
7522 {
7523   const struct mips_opcode *opcode;
7524   bfd_boolean seen_valid_for_isa;
7525
7526   /* Search for a match, ignoring alternatives that don't satisfy the
7527      current ISA.  There are no separate entries for extended forms so
7528      we deal with forced_length later.  */
7529   seen_valid_for_isa = FALSE;
7530   opcode = first;
7531   do
7532     {
7533       gas_assert (strcmp (opcode->name, first->name) == 0);
7534       if (is_opcode_valid_16 (opcode))
7535         {
7536           seen_valid_for_isa = TRUE;
7537           if (match_mips16_insn (insn, opcode, tokens))
7538             return TRUE;
7539         }
7540       ++opcode;
7541     }
7542   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7543          && strcmp (opcode->name, first->name) == 0);
7544
7545   /* Handle the case where we didn't try to match an instruction because
7546      all the alternatives were incompatible with the current ISA.  */
7547   if (!seen_valid_for_isa)
7548     {
7549       match_invalid_for_isa ();
7550       return TRUE;
7551     }
7552
7553   return FALSE;
7554 }
7555
7556 /* Set up global variables for the start of a new macro.  */
7557
7558 static void
7559 macro_start (void)
7560 {
7561   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7562   memset (&mips_macro_warning.first_insn_sizes, 0,
7563           sizeof (mips_macro_warning.first_insn_sizes));
7564   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7565   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7566                                      && delayed_branch_p (&history[0]));
7567   switch (history[0].insn_mo->pinfo2
7568           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7569     {
7570     case INSN2_BRANCH_DELAY_32BIT:
7571       mips_macro_warning.delay_slot_length = 4;
7572       break;
7573     case INSN2_BRANCH_DELAY_16BIT:
7574       mips_macro_warning.delay_slot_length = 2;
7575       break;
7576     default:
7577       mips_macro_warning.delay_slot_length = 0;
7578       break;
7579     }
7580   mips_macro_warning.first_frag = NULL;
7581 }
7582
7583 /* Given that a macro is longer than one instruction or of the wrong size,
7584    return the appropriate warning for it.  Return null if no warning is
7585    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7586    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7587    and RELAX_NOMACRO.  */
7588
7589 static const char *
7590 macro_warning (relax_substateT subtype)
7591 {
7592   if (subtype & RELAX_DELAY_SLOT)
7593     return _("macro instruction expanded into multiple instructions"
7594              " in a branch delay slot");
7595   else if (subtype & RELAX_NOMACRO)
7596     return _("macro instruction expanded into multiple instructions");
7597   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7598                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7599     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7600             ? _("macro instruction expanded into a wrong size instruction"
7601                 " in a 16-bit branch delay slot")
7602             : _("macro instruction expanded into a wrong size instruction"
7603                 " in a 32-bit branch delay slot"));
7604   else
7605     return 0;
7606 }
7607
7608 /* Finish up a macro.  Emit warnings as appropriate.  */
7609
7610 static void
7611 macro_end (void)
7612 {
7613   /* Relaxation warning flags.  */
7614   relax_substateT subtype = 0;
7615
7616   /* Check delay slot size requirements.  */
7617   if (mips_macro_warning.delay_slot_length == 2)
7618     subtype |= RELAX_DELAY_SLOT_16BIT;
7619   if (mips_macro_warning.delay_slot_length != 0)
7620     {
7621       if (mips_macro_warning.delay_slot_length
7622           != mips_macro_warning.first_insn_sizes[0])
7623         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7624       if (mips_macro_warning.delay_slot_length
7625           != mips_macro_warning.first_insn_sizes[1])
7626         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7627     }
7628
7629   /* Check instruction count requirements.  */
7630   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7631     {
7632       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7633         subtype |= RELAX_SECOND_LONGER;
7634       if (mips_opts.warn_about_macros)
7635         subtype |= RELAX_NOMACRO;
7636       if (mips_macro_warning.delay_slot_p)
7637         subtype |= RELAX_DELAY_SLOT;
7638     }
7639
7640   /* If both alternatives fail to fill a delay slot correctly,
7641      emit the warning now.  */
7642   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7643       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7644     {
7645       relax_substateT s;
7646       const char *msg;
7647
7648       s = subtype & (RELAX_DELAY_SLOT_16BIT
7649                      | RELAX_DELAY_SLOT_SIZE_FIRST
7650                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7651       msg = macro_warning (s);
7652       if (msg != NULL)
7653         as_warn ("%s", msg);
7654       subtype &= ~s;
7655     }
7656
7657   /* If both implementations are longer than 1 instruction, then emit the
7658      warning now.  */
7659   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7660     {
7661       relax_substateT s;
7662       const char *msg;
7663
7664       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7665       msg = macro_warning (s);
7666       if (msg != NULL)
7667         as_warn ("%s", msg);
7668       subtype &= ~s;
7669     }
7670
7671   /* If any flags still set, then one implementation might need a warning
7672      and the other either will need one of a different kind or none at all.
7673      Pass any remaining flags over to relaxation.  */
7674   if (mips_macro_warning.first_frag != NULL)
7675     mips_macro_warning.first_frag->fr_subtype |= subtype;
7676 }
7677
7678 /* Instruction operand formats used in macros that vary between
7679    standard MIPS and microMIPS code.  */
7680
7681 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7682 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7683 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7684 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7685 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7686 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7687 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7688 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7689
7690 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7691 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7692 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7693 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7694 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7695 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7696 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7697 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7698
7699 /* Read a macro's relocation codes from *ARGS and store them in *R.
7700    The first argument in *ARGS will be either the code for a single
7701    relocation or -1 followed by the three codes that make up a
7702    composite relocation.  */
7703
7704 static void
7705 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7706 {
7707   int i, next;
7708
7709   next = va_arg (*args, int);
7710   if (next >= 0)
7711     r[0] = (bfd_reloc_code_real_type) next;
7712   else
7713     {
7714       for (i = 0; i < 3; i++)
7715         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7716       /* This function is only used for 16-bit relocation fields.
7717          To make the macro code simpler, treat an unrelocated value
7718          in the same way as BFD_RELOC_LO16.  */
7719       if (r[0] == BFD_RELOC_UNUSED)
7720         r[0] = BFD_RELOC_LO16;
7721     }
7722 }
7723
7724 /* Build an instruction created by a macro expansion.  This is passed
7725    a pointer to the count of instructions created so far, an
7726    expression, the name of the instruction to build, an operand format
7727    string, and corresponding arguments.  */
7728
7729 static void
7730 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7731 {
7732   const struct mips_opcode *mo = NULL;
7733   bfd_reloc_code_real_type r[3];
7734   const struct mips_opcode *amo;
7735   const struct mips_operand *operand;
7736   struct hash_control *hash;
7737   struct mips_cl_insn insn;
7738   va_list args;
7739   unsigned int uval;
7740
7741   va_start (args, fmt);
7742
7743   if (mips_opts.mips16)
7744     {
7745       mips16_macro_build (ep, name, fmt, &args);
7746       va_end (args);
7747       return;
7748     }
7749
7750   r[0] = BFD_RELOC_UNUSED;
7751   r[1] = BFD_RELOC_UNUSED;
7752   r[2] = BFD_RELOC_UNUSED;
7753   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7754   amo = (struct mips_opcode *) hash_find (hash, name);
7755   gas_assert (amo);
7756   gas_assert (strcmp (name, amo->name) == 0);
7757
7758   do
7759     {
7760       /* Search until we get a match for NAME.  It is assumed here that
7761          macros will never generate MDMX, MIPS-3D, or MT instructions.
7762          We try to match an instruction that fulfils the branch delay
7763          slot instruction length requirement (if any) of the previous
7764          instruction.  While doing this we record the first instruction
7765          seen that matches all the other conditions and use it anyway
7766          if the requirement cannot be met; we will issue an appropriate
7767          warning later on.  */
7768       if (strcmp (fmt, amo->args) == 0
7769           && amo->pinfo != INSN_MACRO
7770           && is_opcode_valid (amo)
7771           && is_size_valid (amo))
7772         {
7773           if (is_delay_slot_valid (amo))
7774             {
7775               mo = amo;
7776               break;
7777             }
7778           else if (!mo)
7779             mo = amo;
7780         }
7781
7782       ++amo;
7783       gas_assert (amo->name);
7784     }
7785   while (strcmp (name, amo->name) == 0);
7786
7787   gas_assert (mo);
7788   create_insn (&insn, mo);
7789   for (; *fmt; ++fmt)
7790     {
7791       switch (*fmt)
7792         {
7793         case ',':
7794         case '(':
7795         case ')':
7796         case 'z':
7797           break;
7798
7799         case 'i':
7800         case 'j':
7801           macro_read_relocs (&args, r);
7802           gas_assert (*r == BFD_RELOC_GPREL16
7803                       || *r == BFD_RELOC_MIPS_HIGHER
7804                       || *r == BFD_RELOC_HI16_S
7805                       || *r == BFD_RELOC_LO16
7806                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7807           break;
7808
7809         case 'o':
7810           macro_read_relocs (&args, r);
7811           break;
7812
7813         case 'u':
7814           macro_read_relocs (&args, r);
7815           gas_assert (ep != NULL
7816                       && (ep->X_op == O_constant
7817                           || (ep->X_op == O_symbol
7818                               && (*r == BFD_RELOC_MIPS_HIGHEST
7819                                   || *r == BFD_RELOC_HI16_S
7820                                   || *r == BFD_RELOC_HI16
7821                                   || *r == BFD_RELOC_GPREL16
7822                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7823                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7824           break;
7825
7826         case 'p':
7827           gas_assert (ep != NULL);
7828
7829           /*
7830            * This allows macro() to pass an immediate expression for
7831            * creating short branches without creating a symbol.
7832            *
7833            * We don't allow branch relaxation for these branches, as
7834            * they should only appear in ".set nomacro" anyway.
7835            */
7836           if (ep->X_op == O_constant)
7837             {
7838               /* For microMIPS we always use relocations for branches.
7839                  So we should not resolve immediate values.  */
7840               gas_assert (!mips_opts.micromips);
7841
7842               if ((ep->X_add_number & 3) != 0)
7843                 as_bad (_("branch to misaligned address (0x%lx)"),
7844                         (unsigned long) ep->X_add_number);
7845               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7846                 as_bad (_("branch address range overflow (0x%lx)"),
7847                         (unsigned long) ep->X_add_number);
7848               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7849               ep = NULL;
7850             }
7851           else
7852             *r = BFD_RELOC_16_PCREL_S2;
7853           break;
7854
7855         case 'a':
7856           gas_assert (ep != NULL);
7857           *r = BFD_RELOC_MIPS_JMP;
7858           break;
7859
7860         default:
7861           operand = (mips_opts.micromips
7862                      ? decode_micromips_operand (fmt)
7863                      : decode_mips_operand (fmt));
7864           if (!operand)
7865             abort ();
7866
7867           uval = va_arg (args, int);
7868           if (operand->type == OP_CLO_CLZ_DEST)
7869             uval |= (uval << 5);
7870           insn_insert_operand (&insn, operand, uval);
7871
7872           if (*fmt == '+' || *fmt == 'm')
7873             ++fmt;
7874           break;
7875         }
7876     }
7877   va_end (args);
7878   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7879
7880   append_insn (&insn, ep, r, TRUE);
7881 }
7882
7883 static void
7884 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7885                     va_list *args)
7886 {
7887   struct mips_opcode *mo;
7888   struct mips_cl_insn insn;
7889   const struct mips_operand *operand;
7890   bfd_reloc_code_real_type r[3]
7891     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
7892
7893   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
7894   gas_assert (mo);
7895   gas_assert (strcmp (name, mo->name) == 0);
7896
7897   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
7898     {
7899       ++mo;
7900       gas_assert (mo->name);
7901       gas_assert (strcmp (name, mo->name) == 0);
7902     }
7903
7904   create_insn (&insn, mo);
7905   for (; *fmt; ++fmt)
7906     {
7907       int c;
7908
7909       c = *fmt;
7910       switch (c)
7911         {
7912         case ',':
7913         case '(':
7914         case ')':
7915           break;
7916
7917         case '0':
7918         case 'S':
7919         case 'P':
7920         case 'R':
7921           break;
7922
7923         case '<':
7924         case '>':
7925         case '4':
7926         case '5':
7927         case 'H':
7928         case 'W':
7929         case 'D':
7930         case 'j':
7931         case '8':
7932         case 'V':
7933         case 'C':
7934         case 'U':
7935         case 'k':
7936         case 'K':
7937         case 'p':
7938         case 'q':
7939           {
7940             offsetT value;
7941
7942             gas_assert (ep != NULL);
7943
7944             if (ep->X_op != O_constant)
7945               *r = (int) BFD_RELOC_UNUSED + c;
7946             else if (calculate_reloc (*r, ep->X_add_number, &value))
7947               {
7948                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
7949                 ep = NULL;
7950                 *r = BFD_RELOC_UNUSED;
7951               }
7952           }
7953           break;
7954
7955         default:
7956           operand = decode_mips16_operand (c, FALSE);
7957           if (!operand)
7958             abort ();
7959
7960           insn_insert_operand (&insn, operand, va_arg (*args, int));
7961           break;
7962         }
7963     }
7964
7965   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7966
7967   append_insn (&insn, ep, r, TRUE);
7968 }
7969
7970 /*
7971  * Generate a "jalr" instruction with a relocation hint to the called
7972  * function.  This occurs in NewABI PIC code.
7973  */
7974 static void
7975 macro_build_jalr (expressionS *ep, int cprestore)
7976 {
7977   static const bfd_reloc_code_real_type jalr_relocs[2]
7978     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
7979   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
7980   const char *jalr;
7981   char *f = NULL;
7982
7983   if (MIPS_JALR_HINT_P (ep))
7984     {
7985       frag_grow (8);
7986       f = frag_more (0);
7987     }
7988   if (mips_opts.micromips)
7989     {
7990       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
7991               ? "jalr" : "jalrs");
7992       if (MIPS_JALR_HINT_P (ep)
7993           || mips_opts.insn32
7994           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
7995         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
7996       else
7997         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
7998     }
7999   else
8000     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8001   if (MIPS_JALR_HINT_P (ep))
8002     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8003 }
8004
8005 /*
8006  * Generate a "lui" instruction.
8007  */
8008 static void
8009 macro_build_lui (expressionS *ep, int regnum)
8010 {
8011   gas_assert (! mips_opts.mips16);
8012
8013   if (ep->X_op != O_constant)
8014     {
8015       gas_assert (ep->X_op == O_symbol);
8016       /* _gp_disp is a special case, used from s_cpload.
8017          __gnu_local_gp is used if mips_no_shared.  */
8018       gas_assert (mips_pic == NO_PIC
8019               || (! HAVE_NEWABI
8020                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8021               || (! mips_in_shared
8022                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8023                              "__gnu_local_gp") == 0));
8024     }
8025
8026   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8027 }
8028
8029 /* Generate a sequence of instructions to do a load or store from a constant
8030    offset off of a base register (breg) into/from a target register (treg),
8031    using AT if necessary.  */
8032 static void
8033 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8034                               int treg, int breg, int dbl)
8035 {
8036   gas_assert (ep->X_op == O_constant);
8037
8038   /* Sign-extending 32-bit constants makes their handling easier.  */
8039   if (!dbl)
8040     normalize_constant_expr (ep);
8041
8042   /* Right now, this routine can only handle signed 32-bit constants.  */
8043   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8044     as_warn (_("operand overflow"));
8045
8046   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8047     {
8048       /* Signed 16-bit offset will fit in the op.  Easy!  */
8049       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8050     }
8051   else
8052     {
8053       /* 32-bit offset, need multiple instructions and AT, like:
8054            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8055            addu     $tempreg,$tempreg,$breg
8056            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8057          to handle the complete offset.  */
8058       macro_build_lui (ep, AT);
8059       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8060       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8061
8062       if (!mips_opts.at)
8063         as_bad (_("macro used $at after \".set noat\""));
8064     }
8065 }
8066
8067 /*                      set_at()
8068  * Generates code to set the $at register to true (one)
8069  * if reg is less than the immediate expression.
8070  */
8071 static void
8072 set_at (int reg, int unsignedp)
8073 {
8074   if (imm_expr.X_add_number >= -0x8000
8075       && imm_expr.X_add_number < 0x8000)
8076     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8077                  AT, reg, BFD_RELOC_LO16);
8078   else
8079     {
8080       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8081       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8082     }
8083 }
8084
8085 /* Count the leading zeroes by performing a binary chop. This is a
8086    bulky bit of source, but performance is a LOT better for the
8087    majority of values than a simple loop to count the bits:
8088        for (lcnt = 0; (lcnt < 32); lcnt++)
8089          if ((v) & (1 << (31 - lcnt)))
8090            break;
8091   However it is not code size friendly, and the gain will drop a bit
8092   on certain cached systems.
8093 */
8094 #define COUNT_TOP_ZEROES(v)             \
8095   (((v) & ~0xffff) == 0                 \
8096    ? ((v) & ~0xff) == 0                 \
8097      ? ((v) & ~0xf) == 0                \
8098        ? ((v) & ~0x3) == 0              \
8099          ? ((v) & ~0x1) == 0            \
8100            ? !(v)                       \
8101              ? 32                       \
8102              : 31                       \
8103            : 30                         \
8104          : ((v) & ~0x7) == 0            \
8105            ? 29                         \
8106            : 28                         \
8107        : ((v) & ~0x3f) == 0             \
8108          ? ((v) & ~0x1f) == 0           \
8109            ? 27                         \
8110            : 26                         \
8111          : ((v) & ~0x7f) == 0           \
8112            ? 25                         \
8113            : 24                         \
8114      : ((v) & ~0xfff) == 0              \
8115        ? ((v) & ~0x3ff) == 0            \
8116          ? ((v) & ~0x1ff) == 0          \
8117            ? 23                         \
8118            : 22                         \
8119          : ((v) & ~0x7ff) == 0          \
8120            ? 21                         \
8121            : 20                         \
8122        : ((v) & ~0x3fff) == 0           \
8123          ? ((v) & ~0x1fff) == 0         \
8124            ? 19                         \
8125            : 18                         \
8126          : ((v) & ~0x7fff) == 0         \
8127            ? 17                         \
8128            : 16                         \
8129    : ((v) & ~0xffffff) == 0             \
8130      ? ((v) & ~0xfffff) == 0            \
8131        ? ((v) & ~0x3ffff) == 0          \
8132          ? ((v) & ~0x1ffff) == 0        \
8133            ? 15                         \
8134            : 14                         \
8135          : ((v) & ~0x7ffff) == 0        \
8136            ? 13                         \
8137            : 12                         \
8138        : ((v) & ~0x3fffff) == 0         \
8139          ? ((v) & ~0x1fffff) == 0       \
8140            ? 11                         \
8141            : 10                         \
8142          : ((v) & ~0x7fffff) == 0       \
8143            ? 9                          \
8144            : 8                          \
8145      : ((v) & ~0xfffffff) == 0          \
8146        ? ((v) & ~0x3ffffff) == 0        \
8147          ? ((v) & ~0x1ffffff) == 0      \
8148            ? 7                          \
8149            : 6                          \
8150          : ((v) & ~0x7ffffff) == 0      \
8151            ? 5                          \
8152            : 4                          \
8153        : ((v) & ~0x3fffffff) == 0       \
8154          ? ((v) & ~0x1fffffff) == 0     \
8155            ? 3                          \
8156            : 2                          \
8157          : ((v) & ~0x7fffffff) == 0     \
8158            ? 1                          \
8159            : 0)
8160
8161 /*                      load_register()
8162  *  This routine generates the least number of instructions necessary to load
8163  *  an absolute expression value into a register.
8164  */
8165 static void
8166 load_register (int reg, expressionS *ep, int dbl)
8167 {
8168   int freg;
8169   expressionS hi32, lo32;
8170
8171   if (ep->X_op != O_big)
8172     {
8173       gas_assert (ep->X_op == O_constant);
8174
8175       /* Sign-extending 32-bit constants makes their handling easier.  */
8176       if (!dbl)
8177         normalize_constant_expr (ep);
8178
8179       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8180         {
8181           /* We can handle 16 bit signed values with an addiu to
8182              $zero.  No need to ever use daddiu here, since $zero and
8183              the result are always correct in 32 bit mode.  */
8184           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8185           return;
8186         }
8187       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8188         {
8189           /* We can handle 16 bit unsigned values with an ori to
8190              $zero.  */
8191           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8192           return;
8193         }
8194       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8195         {
8196           /* 32 bit values require an lui.  */
8197           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8198           if ((ep->X_add_number & 0xffff) != 0)
8199             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8200           return;
8201         }
8202     }
8203
8204   /* The value is larger than 32 bits.  */
8205
8206   if (!dbl || HAVE_32BIT_GPRS)
8207     {
8208       char value[32];
8209
8210       sprintf_vma (value, ep->X_add_number);
8211       as_bad (_("number (0x%s) larger than 32 bits"), value);
8212       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8213       return;
8214     }
8215
8216   if (ep->X_op != O_big)
8217     {
8218       hi32 = *ep;
8219       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8220       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8221       hi32.X_add_number &= 0xffffffff;
8222       lo32 = *ep;
8223       lo32.X_add_number &= 0xffffffff;
8224     }
8225   else
8226     {
8227       gas_assert (ep->X_add_number > 2);
8228       if (ep->X_add_number == 3)
8229         generic_bignum[3] = 0;
8230       else if (ep->X_add_number > 4)
8231         as_bad (_("number larger than 64 bits"));
8232       lo32.X_op = O_constant;
8233       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8234       hi32.X_op = O_constant;
8235       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8236     }
8237
8238   if (hi32.X_add_number == 0)
8239     freg = 0;
8240   else
8241     {
8242       int shift, bit;
8243       unsigned long hi, lo;
8244
8245       if (hi32.X_add_number == (offsetT) 0xffffffff)
8246         {
8247           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8248             {
8249               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8250               return;
8251             }
8252           if (lo32.X_add_number & 0x80000000)
8253             {
8254               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8255               if (lo32.X_add_number & 0xffff)
8256                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8257               return;
8258             }
8259         }
8260
8261       /* Check for 16bit shifted constant.  We know that hi32 is
8262          non-zero, so start the mask on the first bit of the hi32
8263          value.  */
8264       shift = 17;
8265       do
8266         {
8267           unsigned long himask, lomask;
8268
8269           if (shift < 32)
8270             {
8271               himask = 0xffff >> (32 - shift);
8272               lomask = (0xffff << shift) & 0xffffffff;
8273             }
8274           else
8275             {
8276               himask = 0xffff << (shift - 32);
8277               lomask = 0;
8278             }
8279           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8280               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8281             {
8282               expressionS tmp;
8283
8284               tmp.X_op = O_constant;
8285               if (shift < 32)
8286                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8287                                     | (lo32.X_add_number >> shift));
8288               else
8289                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8290               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8291               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8292                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8293               return;
8294             }
8295           ++shift;
8296         }
8297       while (shift <= (64 - 16));
8298
8299       /* Find the bit number of the lowest one bit, and store the
8300          shifted value in hi/lo.  */
8301       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8302       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8303       if (lo != 0)
8304         {
8305           bit = 0;
8306           while ((lo & 1) == 0)
8307             {
8308               lo >>= 1;
8309               ++bit;
8310             }
8311           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8312           hi >>= bit;
8313         }
8314       else
8315         {
8316           bit = 32;
8317           while ((hi & 1) == 0)
8318             {
8319               hi >>= 1;
8320               ++bit;
8321             }
8322           lo = hi;
8323           hi = 0;
8324         }
8325
8326       /* Optimize if the shifted value is a (power of 2) - 1.  */
8327       if ((hi == 0 && ((lo + 1) & lo) == 0)
8328           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8329         {
8330           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8331           if (shift != 0)
8332             {
8333               expressionS tmp;
8334
8335               /* This instruction will set the register to be all
8336                  ones.  */
8337               tmp.X_op = O_constant;
8338               tmp.X_add_number = (offsetT) -1;
8339               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8340               if (bit != 0)
8341                 {
8342                   bit += shift;
8343                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8344                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8345                 }
8346               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8347                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8348               return;
8349             }
8350         }
8351
8352       /* Sign extend hi32 before calling load_register, because we can
8353          generally get better code when we load a sign extended value.  */
8354       if ((hi32.X_add_number & 0x80000000) != 0)
8355         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8356       load_register (reg, &hi32, 0);
8357       freg = reg;
8358     }
8359   if ((lo32.X_add_number & 0xffff0000) == 0)
8360     {
8361       if (freg != 0)
8362         {
8363           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8364           freg = reg;
8365         }
8366     }
8367   else
8368     {
8369       expressionS mid16;
8370
8371       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8372         {
8373           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8374           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8375           return;
8376         }
8377
8378       if (freg != 0)
8379         {
8380           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8381           freg = reg;
8382         }
8383       mid16 = lo32;
8384       mid16.X_add_number >>= 16;
8385       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8386       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8387       freg = reg;
8388     }
8389   if ((lo32.X_add_number & 0xffff) != 0)
8390     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8391 }
8392
8393 static inline void
8394 load_delay_nop (void)
8395 {
8396   if (!gpr_interlocks)
8397     macro_build (NULL, "nop", "");
8398 }
8399
8400 /* Load an address into a register.  */
8401
8402 static void
8403 load_address (int reg, expressionS *ep, int *used_at)
8404 {
8405   if (ep->X_op != O_constant
8406       && ep->X_op != O_symbol)
8407     {
8408       as_bad (_("expression too complex"));
8409       ep->X_op = O_constant;
8410     }
8411
8412   if (ep->X_op == O_constant)
8413     {
8414       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8415       return;
8416     }
8417
8418   if (mips_pic == NO_PIC)
8419     {
8420       /* If this is a reference to a GP relative symbol, we want
8421            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8422          Otherwise we want
8423            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8424            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8425          If we have an addend, we always use the latter form.
8426
8427          With 64bit address space and a usable $at we want
8428            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8429            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8430            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8431            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8432            dsll32       $reg,0
8433            daddu        $reg,$reg,$at
8434
8435          If $at is already in use, we use a path which is suboptimal
8436          on superscalar processors.
8437            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8438            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8439            dsll         $reg,16
8440            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8441            dsll         $reg,16
8442            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8443
8444          For GP relative symbols in 64bit address space we can use
8445          the same sequence as in 32bit address space.  */
8446       if (HAVE_64BIT_SYMBOLS)
8447         {
8448           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8449               && !nopic_need_relax (ep->X_add_symbol, 1))
8450             {
8451               relax_start (ep->X_add_symbol);
8452               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8453                            mips_gp_register, BFD_RELOC_GPREL16);
8454               relax_switch ();
8455             }
8456
8457           if (*used_at == 0 && mips_opts.at)
8458             {
8459               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8460               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8461               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8462                            BFD_RELOC_MIPS_HIGHER);
8463               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8464               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8465               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8466               *used_at = 1;
8467             }
8468           else
8469             {
8470               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8471               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8472                            BFD_RELOC_MIPS_HIGHER);
8473               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8474               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8475               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8476               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8477             }
8478
8479           if (mips_relax.sequence)
8480             relax_end ();
8481         }
8482       else
8483         {
8484           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8485               && !nopic_need_relax (ep->X_add_symbol, 1))
8486             {
8487               relax_start (ep->X_add_symbol);
8488               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8489                            mips_gp_register, BFD_RELOC_GPREL16);
8490               relax_switch ();
8491             }
8492           macro_build_lui (ep, reg);
8493           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8494                        reg, reg, BFD_RELOC_LO16);
8495           if (mips_relax.sequence)
8496             relax_end ();
8497         }
8498     }
8499   else if (!mips_big_got)
8500     {
8501       expressionS ex;
8502
8503       /* If this is a reference to an external symbol, we want
8504            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8505          Otherwise we want
8506            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8507            nop
8508            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8509          If there is a constant, it must be added in after.
8510
8511          If we have NewABI, we want
8512            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8513          unless we're referencing a global symbol with a non-zero
8514          offset, in which case cst must be added separately.  */
8515       if (HAVE_NEWABI)
8516         {
8517           if (ep->X_add_number)
8518             {
8519               ex.X_add_number = ep->X_add_number;
8520               ep->X_add_number = 0;
8521               relax_start (ep->X_add_symbol);
8522               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8523                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8524               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8525                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8526               ex.X_op = O_constant;
8527               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8528                            reg, reg, BFD_RELOC_LO16);
8529               ep->X_add_number = ex.X_add_number;
8530               relax_switch ();
8531             }
8532           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8533                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8534           if (mips_relax.sequence)
8535             relax_end ();
8536         }
8537       else
8538         {
8539           ex.X_add_number = ep->X_add_number;
8540           ep->X_add_number = 0;
8541           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8542                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8543           load_delay_nop ();
8544           relax_start (ep->X_add_symbol);
8545           relax_switch ();
8546           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8547                        BFD_RELOC_LO16);
8548           relax_end ();
8549
8550           if (ex.X_add_number != 0)
8551             {
8552               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8553                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8554               ex.X_op = O_constant;
8555               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8556                            reg, reg, BFD_RELOC_LO16);
8557             }
8558         }
8559     }
8560   else if (mips_big_got)
8561     {
8562       expressionS ex;
8563
8564       /* This is the large GOT case.  If this is a reference to an
8565          external symbol, we want
8566            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8567            addu         $reg,$reg,$gp
8568            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8569
8570          Otherwise, for a reference to a local symbol in old ABI, we want
8571            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8572            nop
8573            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8574          If there is a constant, it must be added in after.
8575
8576          In the NewABI, for local symbols, with or without offsets, we want:
8577            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8578            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8579       */
8580       if (HAVE_NEWABI)
8581         {
8582           ex.X_add_number = ep->X_add_number;
8583           ep->X_add_number = 0;
8584           relax_start (ep->X_add_symbol);
8585           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8586           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8587                        reg, reg, mips_gp_register);
8588           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8589                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8590           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8591             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8592           else if (ex.X_add_number)
8593             {
8594               ex.X_op = O_constant;
8595               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8596                            BFD_RELOC_LO16);
8597             }
8598
8599           ep->X_add_number = ex.X_add_number;
8600           relax_switch ();
8601           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8602                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8603           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8604                        BFD_RELOC_MIPS_GOT_OFST);
8605           relax_end ();
8606         }
8607       else
8608         {
8609           ex.X_add_number = ep->X_add_number;
8610           ep->X_add_number = 0;
8611           relax_start (ep->X_add_symbol);
8612           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8613           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8614                        reg, reg, mips_gp_register);
8615           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8616                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8617           relax_switch ();
8618           if (reg_needs_delay (mips_gp_register))
8619             {
8620               /* We need a nop before loading from $gp.  This special
8621                  check is required because the lui which starts the main
8622                  instruction stream does not refer to $gp, and so will not
8623                  insert the nop which may be required.  */
8624               macro_build (NULL, "nop", "");
8625             }
8626           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8627                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8628           load_delay_nop ();
8629           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8630                        BFD_RELOC_LO16);
8631           relax_end ();
8632
8633           if (ex.X_add_number != 0)
8634             {
8635               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8636                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8637               ex.X_op = O_constant;
8638               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8639                            BFD_RELOC_LO16);
8640             }
8641         }
8642     }
8643   else
8644     abort ();
8645
8646   if (!mips_opts.at && *used_at == 1)
8647     as_bad (_("macro used $at after \".set noat\""));
8648 }
8649
8650 /* Move the contents of register SOURCE into register DEST.  */
8651
8652 static void
8653 move_register (int dest, int source)
8654 {
8655   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8656      instruction specifically requires a 32-bit one.  */
8657   if (mips_opts.micromips
8658       && !mips_opts.insn32
8659       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8660     macro_build (NULL, "move", "mp,mj", dest, source);
8661   else
8662     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8663                  dest, source, 0);
8664 }
8665
8666 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8667    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8668    The two alternatives are:
8669
8670    Global symbol                Local sybmol
8671    -------------                ------------
8672    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8673    ...                          ...
8674    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8675
8676    load_got_offset emits the first instruction and add_got_offset
8677    emits the second for a 16-bit offset or add_got_offset_hilo emits
8678    a sequence to add a 32-bit offset using a scratch register.  */
8679
8680 static void
8681 load_got_offset (int dest, expressionS *local)
8682 {
8683   expressionS global;
8684
8685   global = *local;
8686   global.X_add_number = 0;
8687
8688   relax_start (local->X_add_symbol);
8689   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8690                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8691   relax_switch ();
8692   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8693                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8694   relax_end ();
8695 }
8696
8697 static void
8698 add_got_offset (int dest, expressionS *local)
8699 {
8700   expressionS global;
8701
8702   global.X_op = O_constant;
8703   global.X_op_symbol = NULL;
8704   global.X_add_symbol = NULL;
8705   global.X_add_number = local->X_add_number;
8706
8707   relax_start (local->X_add_symbol);
8708   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8709                dest, dest, BFD_RELOC_LO16);
8710   relax_switch ();
8711   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8712   relax_end ();
8713 }
8714
8715 static void
8716 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8717 {
8718   expressionS global;
8719   int hold_mips_optimize;
8720
8721   global.X_op = O_constant;
8722   global.X_op_symbol = NULL;
8723   global.X_add_symbol = NULL;
8724   global.X_add_number = local->X_add_number;
8725
8726   relax_start (local->X_add_symbol);
8727   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8728   relax_switch ();
8729   /* Set mips_optimize around the lui instruction to avoid
8730      inserting an unnecessary nop after the lw.  */
8731   hold_mips_optimize = mips_optimize;
8732   mips_optimize = 2;
8733   macro_build_lui (&global, tmp);
8734   mips_optimize = hold_mips_optimize;
8735   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8736   relax_end ();
8737
8738   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8739 }
8740
8741 /* Emit a sequence of instructions to emulate a branch likely operation.
8742    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8743    is its complementing branch with the original condition negated.
8744    CALL is set if the original branch specified the link operation.
8745    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8746
8747    Code like this is produced in the noreorder mode:
8748
8749         BRNEG   <args>, 1f
8750          nop
8751         b       <sym>
8752          delay slot (executed only if branch taken)
8753     1:
8754
8755    or, if CALL is set:
8756
8757         BRNEG   <args>, 1f
8758          nop
8759         bal     <sym>
8760          delay slot (executed only if branch taken)
8761     1:
8762
8763    In the reorder mode the delay slot would be filled with a nop anyway,
8764    so code produced is simply:
8765
8766         BR      <args>, <sym>
8767          nop
8768
8769    This function is used when producing code for the microMIPS ASE that
8770    does not implement branch likely instructions in hardware.  */
8771
8772 static void
8773 macro_build_branch_likely (const char *br, const char *brneg,
8774                            int call, expressionS *ep, const char *fmt,
8775                            unsigned int sreg, unsigned int treg)
8776 {
8777   int noreorder = mips_opts.noreorder;
8778   expressionS expr1;
8779
8780   gas_assert (mips_opts.micromips);
8781   start_noreorder ();
8782   if (noreorder)
8783     {
8784       micromips_label_expr (&expr1);
8785       macro_build (&expr1, brneg, fmt, sreg, treg);
8786       macro_build (NULL, "nop", "");
8787       macro_build (ep, call ? "bal" : "b", "p");
8788
8789       /* Set to true so that append_insn adds a label.  */
8790       emit_branch_likely_macro = TRUE;
8791     }
8792   else
8793     {
8794       macro_build (ep, br, fmt, sreg, treg);
8795       macro_build (NULL, "nop", "");
8796     }
8797   end_noreorder ();
8798 }
8799
8800 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8801    the condition code tested.  EP specifies the branch target.  */
8802
8803 static void
8804 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8805 {
8806   const int call = 0;
8807   const char *brneg;
8808   const char *br;
8809
8810   switch (type)
8811     {
8812     case M_BC1FL:
8813       br = "bc1f";
8814       brneg = "bc1t";
8815       break;
8816     case M_BC1TL:
8817       br = "bc1t";
8818       brneg = "bc1f";
8819       break;
8820     case M_BC2FL:
8821       br = "bc2f";
8822       brneg = "bc2t";
8823       break;
8824     case M_BC2TL:
8825       br = "bc2t";
8826       brneg = "bc2f";
8827       break;
8828     default:
8829       abort ();
8830     }
8831   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8832 }
8833
8834 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8835    the register tested.  EP specifies the branch target.  */
8836
8837 static void
8838 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8839 {
8840   const char *brneg = NULL;
8841   const char *br;
8842   int call = 0;
8843
8844   switch (type)
8845     {
8846     case M_BGEZ:
8847       br = "bgez";
8848       break;
8849     case M_BGEZL:
8850       br = mips_opts.micromips ? "bgez" : "bgezl";
8851       brneg = "bltz";
8852       break;
8853     case M_BGEZALL:
8854       gas_assert (mips_opts.micromips);
8855       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8856       brneg = "bltz";
8857       call = 1;
8858       break;
8859     case M_BGTZ:
8860       br = "bgtz";
8861       break;
8862     case M_BGTZL:
8863       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8864       brneg = "blez";
8865       break;
8866     case M_BLEZ:
8867       br = "blez";
8868       break;
8869     case M_BLEZL:
8870       br = mips_opts.micromips ? "blez" : "blezl";
8871       brneg = "bgtz";
8872       break;
8873     case M_BLTZ:
8874       br = "bltz";
8875       break;
8876     case M_BLTZL:
8877       br = mips_opts.micromips ? "bltz" : "bltzl";
8878       brneg = "bgez";
8879       break;
8880     case M_BLTZALL:
8881       gas_assert (mips_opts.micromips);
8882       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8883       brneg = "bgez";
8884       call = 1;
8885       break;
8886     default:
8887       abort ();
8888     }
8889   if (mips_opts.micromips && brneg)
8890     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8891   else
8892     macro_build (ep, br, "s,p", sreg);
8893 }
8894
8895 /* Emit a three-argument branch macro specified by TYPE, using SREG and
8896    TREG as the registers tested.  EP specifies the branch target.  */
8897
8898 static void
8899 macro_build_branch_rsrt (int type, expressionS *ep,
8900                          unsigned int sreg, unsigned int treg)
8901 {
8902   const char *brneg = NULL;
8903   const int call = 0;
8904   const char *br;
8905
8906   switch (type)
8907     {
8908     case M_BEQ:
8909     case M_BEQ_I:
8910       br = "beq";
8911       break;
8912     case M_BEQL:
8913     case M_BEQL_I:
8914       br = mips_opts.micromips ? "beq" : "beql";
8915       brneg = "bne";
8916       break;
8917     case M_BNE:
8918     case M_BNE_I:
8919       br = "bne";
8920       break;
8921     case M_BNEL:
8922     case M_BNEL_I:
8923       br = mips_opts.micromips ? "bne" : "bnel";
8924       brneg = "beq";
8925       break;
8926     default:
8927       abort ();
8928     }
8929   if (mips_opts.micromips && brneg)
8930     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
8931   else
8932     macro_build (ep, br, "s,t,p", sreg, treg);
8933 }
8934
8935 /* Return the high part that should be loaded in order to make the low
8936    part of VALUE accessible using an offset of OFFBITS bits.  */
8937
8938 static offsetT
8939 offset_high_part (offsetT value, unsigned int offbits)
8940 {
8941   offsetT bias;
8942   addressT low_mask;
8943
8944   if (offbits == 0)
8945     return value;
8946   bias = 1 << (offbits - 1);
8947   low_mask = bias * 2 - 1;
8948   return (value + bias) & ~low_mask;
8949 }
8950
8951 /* Return true if the value stored in offset_expr and offset_reloc
8952    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
8953    amount that the caller wants to add without inducing overflow
8954    and ALIGN is the known alignment of the value in bytes.  */
8955
8956 static bfd_boolean
8957 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
8958 {
8959   if (offbits == 16)
8960     {
8961       /* Accept any relocation operator if overflow isn't a concern.  */
8962       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
8963         return TRUE;
8964
8965       /* These relocations are guaranteed not to overflow in correct links.  */
8966       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
8967           || gprel16_reloc_p (*offset_reloc))
8968         return TRUE;
8969     }
8970   if (offset_expr.X_op == O_constant
8971       && offset_high_part (offset_expr.X_add_number, offbits) == 0
8972       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
8973     return TRUE;
8974   return FALSE;
8975 }
8976
8977 /*
8978  *                      Build macros
8979  *   This routine implements the seemingly endless macro or synthesized
8980  * instructions and addressing modes in the mips assembly language. Many
8981  * of these macros are simple and are similar to each other. These could
8982  * probably be handled by some kind of table or grammar approach instead of
8983  * this verbose method. Others are not simple macros but are more like
8984  * optimizing code generation.
8985  *   One interesting optimization is when several store macros appear
8986  * consecutively that would load AT with the upper half of the same address.
8987  * The ensuing load upper instructions are ommited. This implies some kind
8988  * of global optimization. We currently only optimize within a single macro.
8989  *   For many of the load and store macros if the address is specified as a
8990  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
8991  * first load register 'at' with zero and use it as the base register. The
8992  * mips assembler simply uses register $zero. Just one tiny optimization
8993  * we're missing.
8994  */
8995 static void
8996 macro (struct mips_cl_insn *ip, char *str)
8997 {
8998   const struct mips_operand_array *operands;
8999   unsigned int breg, i;
9000   unsigned int tempreg;
9001   int mask;
9002   int used_at = 0;
9003   expressionS label_expr;
9004   expressionS expr1;
9005   expressionS *ep;
9006   const char *s;
9007   const char *s2;
9008   const char *fmt;
9009   int likely = 0;
9010   int coproc = 0;
9011   int offbits = 16;
9012   int call = 0;
9013   int jals = 0;
9014   int dbl = 0;
9015   int imm = 0;
9016   int ust = 0;
9017   int lp = 0;
9018   bfd_boolean large_offset;
9019   int off;
9020   int hold_mips_optimize;
9021   unsigned int align;
9022   unsigned int op[MAX_OPERANDS];
9023
9024   gas_assert (! mips_opts.mips16);
9025
9026   operands = insn_operands (ip);
9027   for (i = 0; i < MAX_OPERANDS; i++)
9028     if (operands->operand[i])
9029       op[i] = insn_extract_operand (ip, operands->operand[i]);
9030     else
9031       op[i] = -1;
9032
9033   mask = ip->insn_mo->mask;
9034
9035   label_expr.X_op = O_constant;
9036   label_expr.X_op_symbol = NULL;
9037   label_expr.X_add_symbol = NULL;
9038   label_expr.X_add_number = 0;
9039
9040   expr1.X_op = O_constant;
9041   expr1.X_op_symbol = NULL;
9042   expr1.X_add_symbol = NULL;
9043   expr1.X_add_number = 1;
9044   align = 1;
9045
9046   switch (mask)
9047     {
9048     case M_DABS:
9049       dbl = 1;
9050     case M_ABS:
9051       /*    bgez    $a0,1f
9052             move    v0,$a0
9053             sub     v0,$zero,$a0
9054          1:
9055        */
9056
9057       start_noreorder ();
9058
9059       if (mips_opts.micromips)
9060         micromips_label_expr (&label_expr);
9061       else
9062         label_expr.X_add_number = 8;
9063       macro_build (&label_expr, "bgez", "s,p", op[1]);
9064       if (op[0] == op[1])
9065         macro_build (NULL, "nop", "");
9066       else
9067         move_register (op[0], op[1]);
9068       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9069       if (mips_opts.micromips)
9070         micromips_add_label ();
9071
9072       end_noreorder ();
9073       break;
9074
9075     case M_ADD_I:
9076       s = "addi";
9077       s2 = "add";
9078       goto do_addi;
9079     case M_ADDU_I:
9080       s = "addiu";
9081       s2 = "addu";
9082       goto do_addi;
9083     case M_DADD_I:
9084       dbl = 1;
9085       s = "daddi";
9086       s2 = "dadd";
9087       if (!mips_opts.micromips)
9088         goto do_addi;
9089       if (imm_expr.X_add_number >= -0x200
9090           && imm_expr.X_add_number < 0x200)
9091         {
9092           macro_build (NULL, s, "t,r,.", op[0], op[1],
9093                        (int) imm_expr.X_add_number);
9094           break;
9095         }
9096       goto do_addi_i;
9097     case M_DADDU_I:
9098       dbl = 1;
9099       s = "daddiu";
9100       s2 = "daddu";
9101     do_addi:
9102       if (imm_expr.X_add_number >= -0x8000
9103           && imm_expr.X_add_number < 0x8000)
9104         {
9105           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9106           break;
9107         }
9108     do_addi_i:
9109       used_at = 1;
9110       load_register (AT, &imm_expr, dbl);
9111       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9112       break;
9113
9114     case M_AND_I:
9115       s = "andi";
9116       s2 = "and";
9117       goto do_bit;
9118     case M_OR_I:
9119       s = "ori";
9120       s2 = "or";
9121       goto do_bit;
9122     case M_NOR_I:
9123       s = "";
9124       s2 = "nor";
9125       goto do_bit;
9126     case M_XOR_I:
9127       s = "xori";
9128       s2 = "xor";
9129     do_bit:
9130       if (imm_expr.X_add_number >= 0
9131           && imm_expr.X_add_number < 0x10000)
9132         {
9133           if (mask != M_NOR_I)
9134             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9135           else
9136             {
9137               macro_build (&imm_expr, "ori", "t,r,i",
9138                            op[0], op[1], BFD_RELOC_LO16);
9139               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9140             }
9141           break;
9142         }
9143
9144       used_at = 1;
9145       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9146       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9147       break;
9148
9149     case M_BALIGN:
9150       switch (imm_expr.X_add_number)
9151         {
9152         case 0:
9153           macro_build (NULL, "nop", "");
9154           break;
9155         case 2:
9156           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9157           break;
9158         case 1:
9159         case 3:
9160           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9161                        (int) imm_expr.X_add_number);
9162           break;
9163         default:
9164           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9165                   (unsigned long) imm_expr.X_add_number);
9166           break;
9167         }
9168       break;
9169
9170     case M_BC1FL:
9171     case M_BC1TL:
9172     case M_BC2FL:
9173     case M_BC2TL:
9174       gas_assert (mips_opts.micromips);
9175       macro_build_branch_ccl (mask, &offset_expr,
9176                               EXTRACT_OPERAND (1, BCC, *ip));
9177       break;
9178
9179     case M_BEQ_I:
9180     case M_BEQL_I:
9181     case M_BNE_I:
9182     case M_BNEL_I:
9183       if (imm_expr.X_add_number == 0)
9184         op[1] = 0;
9185       else
9186         {
9187           op[1] = AT;
9188           used_at = 1;
9189           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9190         }
9191       /* Fall through.  */
9192     case M_BEQL:
9193     case M_BNEL:
9194       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9195       break;
9196
9197     case M_BGEL:
9198       likely = 1;
9199     case M_BGE:
9200       if (op[1] == 0)
9201         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9202       else if (op[0] == 0)
9203         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9204       else
9205         {
9206           used_at = 1;
9207           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9208           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9209                                    &offset_expr, AT, ZERO);
9210         }
9211       break;
9212
9213     case M_BGEZL:
9214     case M_BGEZALL:
9215     case M_BGTZL:
9216     case M_BLEZL:
9217     case M_BLTZL:
9218     case M_BLTZALL:
9219       macro_build_branch_rs (mask, &offset_expr, op[0]);
9220       break;
9221
9222     case M_BGTL_I:
9223       likely = 1;
9224     case M_BGT_I:
9225       /* Check for > max integer.  */
9226       if (imm_expr.X_add_number >= GPR_SMAX)
9227         {
9228         do_false:
9229           /* Result is always false.  */
9230           if (! likely)
9231             macro_build (NULL, "nop", "");
9232           else
9233             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9234           break;
9235         }
9236       ++imm_expr.X_add_number;
9237       /* FALLTHROUGH */
9238     case M_BGE_I:
9239     case M_BGEL_I:
9240       if (mask == M_BGEL_I)
9241         likely = 1;
9242       if (imm_expr.X_add_number == 0)
9243         {
9244           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9245                                  &offset_expr, op[0]);
9246           break;
9247         }
9248       if (imm_expr.X_add_number == 1)
9249         {
9250           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9251                                  &offset_expr, op[0]);
9252           break;
9253         }
9254       if (imm_expr.X_add_number <= GPR_SMIN)
9255         {
9256         do_true:
9257           /* result is always true */
9258           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9259           macro_build (&offset_expr, "b", "p");
9260           break;
9261         }
9262       used_at = 1;
9263       set_at (op[0], 0);
9264       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9265                                &offset_expr, AT, ZERO);
9266       break;
9267
9268     case M_BGEUL:
9269       likely = 1;
9270     case M_BGEU:
9271       if (op[1] == 0)
9272         goto do_true;
9273       else if (op[0] == 0)
9274         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9275                                  &offset_expr, ZERO, op[1]);
9276       else
9277         {
9278           used_at = 1;
9279           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9280           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9281                                    &offset_expr, AT, ZERO);
9282         }
9283       break;
9284
9285     case M_BGTUL_I:
9286       likely = 1;
9287     case M_BGTU_I:
9288       if (op[0] == 0
9289           || (HAVE_32BIT_GPRS
9290               && imm_expr.X_add_number == -1))
9291         goto do_false;
9292       ++imm_expr.X_add_number;
9293       /* FALLTHROUGH */
9294     case M_BGEU_I:
9295     case M_BGEUL_I:
9296       if (mask == M_BGEUL_I)
9297         likely = 1;
9298       if (imm_expr.X_add_number == 0)
9299         goto do_true;
9300       else if (imm_expr.X_add_number == 1)
9301         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9302                                  &offset_expr, op[0], ZERO);
9303       else
9304         {
9305           used_at = 1;
9306           set_at (op[0], 1);
9307           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9308                                    &offset_expr, AT, ZERO);
9309         }
9310       break;
9311
9312     case M_BGTL:
9313       likely = 1;
9314     case M_BGT:
9315       if (op[1] == 0)
9316         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9317       else if (op[0] == 0)
9318         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9319       else
9320         {
9321           used_at = 1;
9322           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9323           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9324                                    &offset_expr, AT, ZERO);
9325         }
9326       break;
9327
9328     case M_BGTUL:
9329       likely = 1;
9330     case M_BGTU:
9331       if (op[1] == 0)
9332         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9333                                  &offset_expr, op[0], ZERO);
9334       else if (op[0] == 0)
9335         goto do_false;
9336       else
9337         {
9338           used_at = 1;
9339           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9340           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9341                                    &offset_expr, AT, ZERO);
9342         }
9343       break;
9344
9345     case M_BLEL:
9346       likely = 1;
9347     case M_BLE:
9348       if (op[1] == 0)
9349         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9350       else if (op[0] == 0)
9351         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9352       else
9353         {
9354           used_at = 1;
9355           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9356           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9357                                    &offset_expr, AT, ZERO);
9358         }
9359       break;
9360
9361     case M_BLEL_I:
9362       likely = 1;
9363     case M_BLE_I:
9364       if (imm_expr.X_add_number >= GPR_SMAX)
9365         goto do_true;
9366       ++imm_expr.X_add_number;
9367       /* FALLTHROUGH */
9368     case M_BLT_I:
9369     case M_BLTL_I:
9370       if (mask == M_BLTL_I)
9371         likely = 1;
9372       if (imm_expr.X_add_number == 0)
9373         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9374       else if (imm_expr.X_add_number == 1)
9375         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9376       else
9377         {
9378           used_at = 1;
9379           set_at (op[0], 0);
9380           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9381                                    &offset_expr, AT, ZERO);
9382         }
9383       break;
9384
9385     case M_BLEUL:
9386       likely = 1;
9387     case M_BLEU:
9388       if (op[1] == 0)
9389         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9390                                  &offset_expr, op[0], ZERO);
9391       else if (op[0] == 0)
9392         goto do_true;
9393       else
9394         {
9395           used_at = 1;
9396           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9397           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9398                                    &offset_expr, AT, ZERO);
9399         }
9400       break;
9401
9402     case M_BLEUL_I:
9403       likely = 1;
9404     case M_BLEU_I:
9405       if (op[0] == 0
9406           || (HAVE_32BIT_GPRS
9407               && imm_expr.X_add_number == -1))
9408         goto do_true;
9409       ++imm_expr.X_add_number;
9410       /* FALLTHROUGH */
9411     case M_BLTU_I:
9412     case M_BLTUL_I:
9413       if (mask == M_BLTUL_I)
9414         likely = 1;
9415       if (imm_expr.X_add_number == 0)
9416         goto do_false;
9417       else if (imm_expr.X_add_number == 1)
9418         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9419                                  &offset_expr, op[0], ZERO);
9420       else
9421         {
9422           used_at = 1;
9423           set_at (op[0], 1);
9424           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9425                                    &offset_expr, AT, ZERO);
9426         }
9427       break;
9428
9429     case M_BLTL:
9430       likely = 1;
9431     case M_BLT:
9432       if (op[1] == 0)
9433         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9434       else if (op[0] == 0)
9435         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9436       else
9437         {
9438           used_at = 1;
9439           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9440           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9441                                    &offset_expr, AT, ZERO);
9442         }
9443       break;
9444
9445     case M_BLTUL:
9446       likely = 1;
9447     case M_BLTU:
9448       if (op[1] == 0)
9449         goto do_false;
9450       else if (op[0] == 0)
9451         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9452                                  &offset_expr, ZERO, op[1]);
9453       else
9454         {
9455           used_at = 1;
9456           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9457           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9458                                    &offset_expr, AT, ZERO);
9459         }
9460       break;
9461
9462     case M_DDIV_3:
9463       dbl = 1;
9464     case M_DIV_3:
9465       s = "mflo";
9466       goto do_div3;
9467     case M_DREM_3:
9468       dbl = 1;
9469     case M_REM_3:
9470       s = "mfhi";
9471     do_div3:
9472       if (op[2] == 0)
9473         {
9474           as_warn (_("divide by zero"));
9475           if (mips_trap)
9476             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9477           else
9478             macro_build (NULL, "break", BRK_FMT, 7);
9479           break;
9480         }
9481
9482       start_noreorder ();
9483       if (mips_trap)
9484         {
9485           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9486           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9487         }
9488       else
9489         {
9490           if (mips_opts.micromips)
9491             micromips_label_expr (&label_expr);
9492           else
9493             label_expr.X_add_number = 8;
9494           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9495           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9496           macro_build (NULL, "break", BRK_FMT, 7);
9497           if (mips_opts.micromips)
9498             micromips_add_label ();
9499         }
9500       expr1.X_add_number = -1;
9501       used_at = 1;
9502       load_register (AT, &expr1, dbl);
9503       if (mips_opts.micromips)
9504         micromips_label_expr (&label_expr);
9505       else
9506         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9507       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9508       if (dbl)
9509         {
9510           expr1.X_add_number = 1;
9511           load_register (AT, &expr1, dbl);
9512           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9513         }
9514       else
9515         {
9516           expr1.X_add_number = 0x80000000;
9517           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9518         }
9519       if (mips_trap)
9520         {
9521           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9522           /* We want to close the noreorder block as soon as possible, so
9523              that later insns are available for delay slot filling.  */
9524           end_noreorder ();
9525         }
9526       else
9527         {
9528           if (mips_opts.micromips)
9529             micromips_label_expr (&label_expr);
9530           else
9531             label_expr.X_add_number = 8;
9532           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9533           macro_build (NULL, "nop", "");
9534
9535           /* We want to close the noreorder block as soon as possible, so
9536              that later insns are available for delay slot filling.  */
9537           end_noreorder ();
9538
9539           macro_build (NULL, "break", BRK_FMT, 6);
9540         }
9541       if (mips_opts.micromips)
9542         micromips_add_label ();
9543       macro_build (NULL, s, MFHL_FMT, op[0]);
9544       break;
9545
9546     case M_DIV_3I:
9547       s = "div";
9548       s2 = "mflo";
9549       goto do_divi;
9550     case M_DIVU_3I:
9551       s = "divu";
9552       s2 = "mflo";
9553       goto do_divi;
9554     case M_REM_3I:
9555       s = "div";
9556       s2 = "mfhi";
9557       goto do_divi;
9558     case M_REMU_3I:
9559       s = "divu";
9560       s2 = "mfhi";
9561       goto do_divi;
9562     case M_DDIV_3I:
9563       dbl = 1;
9564       s = "ddiv";
9565       s2 = "mflo";
9566       goto do_divi;
9567     case M_DDIVU_3I:
9568       dbl = 1;
9569       s = "ddivu";
9570       s2 = "mflo";
9571       goto do_divi;
9572     case M_DREM_3I:
9573       dbl = 1;
9574       s = "ddiv";
9575       s2 = "mfhi";
9576       goto do_divi;
9577     case M_DREMU_3I:
9578       dbl = 1;
9579       s = "ddivu";
9580       s2 = "mfhi";
9581     do_divi:
9582       if (imm_expr.X_add_number == 0)
9583         {
9584           as_warn (_("divide by zero"));
9585           if (mips_trap)
9586             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9587           else
9588             macro_build (NULL, "break", BRK_FMT, 7);
9589           break;
9590         }
9591       if (imm_expr.X_add_number == 1)
9592         {
9593           if (strcmp (s2, "mflo") == 0)
9594             move_register (op[0], op[1]);
9595           else
9596             move_register (op[0], ZERO);
9597           break;
9598         }
9599       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9600         {
9601           if (strcmp (s2, "mflo") == 0)
9602             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9603           else
9604             move_register (op[0], ZERO);
9605           break;
9606         }
9607
9608       used_at = 1;
9609       load_register (AT, &imm_expr, dbl);
9610       macro_build (NULL, s, "z,s,t", op[1], AT);
9611       macro_build (NULL, s2, MFHL_FMT, op[0]);
9612       break;
9613
9614     case M_DIVU_3:
9615       s = "divu";
9616       s2 = "mflo";
9617       goto do_divu3;
9618     case M_REMU_3:
9619       s = "divu";
9620       s2 = "mfhi";
9621       goto do_divu3;
9622     case M_DDIVU_3:
9623       s = "ddivu";
9624       s2 = "mflo";
9625       goto do_divu3;
9626     case M_DREMU_3:
9627       s = "ddivu";
9628       s2 = "mfhi";
9629     do_divu3:
9630       start_noreorder ();
9631       if (mips_trap)
9632         {
9633           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9634           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9635           /* We want to close the noreorder block as soon as possible, so
9636              that later insns are available for delay slot filling.  */
9637           end_noreorder ();
9638         }
9639       else
9640         {
9641           if (mips_opts.micromips)
9642             micromips_label_expr (&label_expr);
9643           else
9644             label_expr.X_add_number = 8;
9645           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9646           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9647
9648           /* We want to close the noreorder block as soon as possible, so
9649              that later insns are available for delay slot filling.  */
9650           end_noreorder ();
9651           macro_build (NULL, "break", BRK_FMT, 7);
9652           if (mips_opts.micromips)
9653             micromips_add_label ();
9654         }
9655       macro_build (NULL, s2, MFHL_FMT, op[0]);
9656       break;
9657
9658     case M_DLCA_AB:
9659       dbl = 1;
9660     case M_LCA_AB:
9661       call = 1;
9662       goto do_la;
9663     case M_DLA_AB:
9664       dbl = 1;
9665     case M_LA_AB:
9666     do_la:
9667       /* Load the address of a symbol into a register.  If breg is not
9668          zero, we then add a base register to it.  */
9669
9670       breg = op[2];
9671       if (dbl && HAVE_32BIT_GPRS)
9672         as_warn (_("dla used to load 32-bit register"));
9673
9674       if (!dbl && HAVE_64BIT_OBJECTS)
9675         as_warn (_("la used to load 64-bit address"));
9676
9677       if (small_offset_p (0, align, 16))
9678         {
9679           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9680                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9681           break;
9682         }
9683
9684       if (mips_opts.at && (op[0] == breg))
9685         {
9686           tempreg = AT;
9687           used_at = 1;
9688         }
9689       else
9690         tempreg = op[0];
9691
9692       if (offset_expr.X_op != O_symbol
9693           && offset_expr.X_op != O_constant)
9694         {
9695           as_bad (_("expression too complex"));
9696           offset_expr.X_op = O_constant;
9697         }
9698
9699       if (offset_expr.X_op == O_constant)
9700         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9701       else if (mips_pic == NO_PIC)
9702         {
9703           /* If this is a reference to a GP relative symbol, we want
9704                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9705              Otherwise we want
9706                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9707                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9708              If we have a constant, we need two instructions anyhow,
9709              so we may as well always use the latter form.
9710
9711              With 64bit address space and a usable $at we want
9712                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9713                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9714                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9715                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9716                dsll32   $tempreg,0
9717                daddu    $tempreg,$tempreg,$at
9718
9719              If $at is already in use, we use a path which is suboptimal
9720              on superscalar processors.
9721                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9722                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9723                dsll     $tempreg,16
9724                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9725                dsll     $tempreg,16
9726                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9727
9728              For GP relative symbols in 64bit address space we can use
9729              the same sequence as in 32bit address space.  */
9730           if (HAVE_64BIT_SYMBOLS)
9731             {
9732               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9733                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9734                 {
9735                   relax_start (offset_expr.X_add_symbol);
9736                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9737                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9738                   relax_switch ();
9739                 }
9740
9741               if (used_at == 0 && mips_opts.at)
9742                 {
9743                   macro_build (&offset_expr, "lui", LUI_FMT,
9744                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9745                   macro_build (&offset_expr, "lui", LUI_FMT,
9746                                AT, BFD_RELOC_HI16_S);
9747                   macro_build (&offset_expr, "daddiu", "t,r,j",
9748                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9749                   macro_build (&offset_expr, "daddiu", "t,r,j",
9750                                AT, AT, BFD_RELOC_LO16);
9751                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9752                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9753                   used_at = 1;
9754                 }
9755               else
9756                 {
9757                   macro_build (&offset_expr, "lui", LUI_FMT,
9758                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9759                   macro_build (&offset_expr, "daddiu", "t,r,j",
9760                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9761                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9762                   macro_build (&offset_expr, "daddiu", "t,r,j",
9763                                tempreg, tempreg, BFD_RELOC_HI16_S);
9764                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9765                   macro_build (&offset_expr, "daddiu", "t,r,j",
9766                                tempreg, tempreg, BFD_RELOC_LO16);
9767                 }
9768
9769               if (mips_relax.sequence)
9770                 relax_end ();
9771             }
9772           else
9773             {
9774               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9775                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9776                 {
9777                   relax_start (offset_expr.X_add_symbol);
9778                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9779                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9780                   relax_switch ();
9781                 }
9782               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9783                 as_bad (_("offset too large"));
9784               macro_build_lui (&offset_expr, tempreg);
9785               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9786                            tempreg, tempreg, BFD_RELOC_LO16);
9787               if (mips_relax.sequence)
9788                 relax_end ();
9789             }
9790         }
9791       else if (!mips_big_got && !HAVE_NEWABI)
9792         {
9793           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9794
9795           /* If this is a reference to an external symbol, and there
9796              is no constant, we want
9797                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9798              or for lca or if tempreg is PIC_CALL_REG
9799                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9800              For a local symbol, we want
9801                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9802                nop
9803                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9804
9805              If we have a small constant, and this is a reference to
9806              an external symbol, we want
9807                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9808                nop
9809                addiu    $tempreg,$tempreg,<constant>
9810              For a local symbol, we want the same instruction
9811              sequence, but we output a BFD_RELOC_LO16 reloc on the
9812              addiu instruction.
9813
9814              If we have a large constant, and this is a reference to
9815              an external symbol, we want
9816                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9817                lui      $at,<hiconstant>
9818                addiu    $at,$at,<loconstant>
9819                addu     $tempreg,$tempreg,$at
9820              For a local symbol, we want the same instruction
9821              sequence, but we output a BFD_RELOC_LO16 reloc on the
9822              addiu instruction.
9823            */
9824
9825           if (offset_expr.X_add_number == 0)
9826             {
9827               if (mips_pic == SVR4_PIC
9828                   && breg == 0
9829                   && (call || tempreg == PIC_CALL_REG))
9830                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9831
9832               relax_start (offset_expr.X_add_symbol);
9833               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9834                            lw_reloc_type, mips_gp_register);
9835               if (breg != 0)
9836                 {
9837                   /* We're going to put in an addu instruction using
9838                      tempreg, so we may as well insert the nop right
9839                      now.  */
9840                   load_delay_nop ();
9841                 }
9842               relax_switch ();
9843               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9844                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9845               load_delay_nop ();
9846               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9847                            tempreg, tempreg, BFD_RELOC_LO16);
9848               relax_end ();
9849               /* FIXME: If breg == 0, and the next instruction uses
9850                  $tempreg, then if this variant case is used an extra
9851                  nop will be generated.  */
9852             }
9853           else if (offset_expr.X_add_number >= -0x8000
9854                    && offset_expr.X_add_number < 0x8000)
9855             {
9856               load_got_offset (tempreg, &offset_expr);
9857               load_delay_nop ();
9858               add_got_offset (tempreg, &offset_expr);
9859             }
9860           else
9861             {
9862               expr1.X_add_number = offset_expr.X_add_number;
9863               offset_expr.X_add_number =
9864                 SEXT_16BIT (offset_expr.X_add_number);
9865               load_got_offset (tempreg, &offset_expr);
9866               offset_expr.X_add_number = expr1.X_add_number;
9867               /* If we are going to add in a base register, and the
9868                  target register and the base register are the same,
9869                  then we are using AT as a temporary register.  Since
9870                  we want to load the constant into AT, we add our
9871                  current AT (from the global offset table) and the
9872                  register into the register now, and pretend we were
9873                  not using a base register.  */
9874               if (breg == op[0])
9875                 {
9876                   load_delay_nop ();
9877                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9878                                op[0], AT, breg);
9879                   breg = 0;
9880                   tempreg = op[0];
9881                 }
9882               add_got_offset_hilo (tempreg, &offset_expr, AT);
9883               used_at = 1;
9884             }
9885         }
9886       else if (!mips_big_got && HAVE_NEWABI)
9887         {
9888           int add_breg_early = 0;
9889
9890           /* If this is a reference to an external, and there is no
9891              constant, or local symbol (*), with or without a
9892              constant, we want
9893                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9894              or for lca or if tempreg is PIC_CALL_REG
9895                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9896
9897              If we have a small constant, and this is a reference to
9898              an external symbol, we want
9899                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9900                addiu    $tempreg,$tempreg,<constant>
9901
9902              If we have a large constant, and this is a reference to
9903              an external symbol, we want
9904                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9905                lui      $at,<hiconstant>
9906                addiu    $at,$at,<loconstant>
9907                addu     $tempreg,$tempreg,$at
9908
9909              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
9910              local symbols, even though it introduces an additional
9911              instruction.  */
9912
9913           if (offset_expr.X_add_number)
9914             {
9915               expr1.X_add_number = offset_expr.X_add_number;
9916               offset_expr.X_add_number = 0;
9917
9918               relax_start (offset_expr.X_add_symbol);
9919               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9920                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9921
9922               if (expr1.X_add_number >= -0x8000
9923                   && expr1.X_add_number < 0x8000)
9924                 {
9925                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
9926                                tempreg, tempreg, BFD_RELOC_LO16);
9927                 }
9928               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
9929                 {
9930                   unsigned int dreg;
9931
9932                   /* If we are going to add in a base register, and the
9933                      target register and the base register are the same,
9934                      then we are using AT as a temporary register.  Since
9935                      we want to load the constant into AT, we add our
9936                      current AT (from the global offset table) and the
9937                      register into the register now, and pretend we were
9938                      not using a base register.  */
9939                   if (breg != op[0])
9940                     dreg = tempreg;
9941                   else
9942                     {
9943                       gas_assert (tempreg == AT);
9944                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9945                                    op[0], AT, breg);
9946                       dreg = op[0];
9947                       add_breg_early = 1;
9948                     }
9949
9950                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
9951                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9952                                dreg, dreg, AT);
9953
9954                   used_at = 1;
9955                 }
9956               else
9957                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
9958
9959               relax_switch ();
9960               offset_expr.X_add_number = expr1.X_add_number;
9961
9962               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9963                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9964               if (add_breg_early)
9965                 {
9966                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9967                                op[0], tempreg, breg);
9968                   breg = 0;
9969                   tempreg = op[0];
9970                 }
9971               relax_end ();
9972             }
9973           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
9974             {
9975               relax_start (offset_expr.X_add_symbol);
9976               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9977                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
9978               relax_switch ();
9979               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9980                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9981               relax_end ();
9982             }
9983           else
9984             {
9985               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9986                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9987             }
9988         }
9989       else if (mips_big_got && !HAVE_NEWABI)
9990         {
9991           int gpdelay;
9992           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
9993           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
9994           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9995
9996           /* This is the large GOT case.  If this is a reference to an
9997              external symbol, and there is no constant, we want
9998                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
9999                addu     $tempreg,$tempreg,$gp
10000                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10001              or for lca or if tempreg is PIC_CALL_REG
10002                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10003                addu     $tempreg,$tempreg,$gp
10004                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10005              For a local symbol, we want
10006                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10007                nop
10008                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10009
10010              If we have a small constant, and this is a reference to
10011              an external symbol, we want
10012                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10013                addu     $tempreg,$tempreg,$gp
10014                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10015                nop
10016                addiu    $tempreg,$tempreg,<constant>
10017              For a local symbol, we want
10018                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10019                nop
10020                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10021
10022              If we have a large constant, and this is a reference to
10023              an external symbol, we want
10024                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10025                addu     $tempreg,$tempreg,$gp
10026                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10027                lui      $at,<hiconstant>
10028                addiu    $at,$at,<loconstant>
10029                addu     $tempreg,$tempreg,$at
10030              For a local symbol, we want
10031                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10032                lui      $at,<hiconstant>
10033                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10034                addu     $tempreg,$tempreg,$at
10035           */
10036
10037           expr1.X_add_number = offset_expr.X_add_number;
10038           offset_expr.X_add_number = 0;
10039           relax_start (offset_expr.X_add_symbol);
10040           gpdelay = reg_needs_delay (mips_gp_register);
10041           if (expr1.X_add_number == 0 && breg == 0
10042               && (call || tempreg == PIC_CALL_REG))
10043             {
10044               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10045               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10046             }
10047           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10048           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10049                        tempreg, tempreg, mips_gp_register);
10050           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10051                        tempreg, lw_reloc_type, tempreg);
10052           if (expr1.X_add_number == 0)
10053             {
10054               if (breg != 0)
10055                 {
10056                   /* We're going to put in an addu instruction using
10057                      tempreg, so we may as well insert the nop right
10058                      now.  */
10059                   load_delay_nop ();
10060                 }
10061             }
10062           else if (expr1.X_add_number >= -0x8000
10063                    && expr1.X_add_number < 0x8000)
10064             {
10065               load_delay_nop ();
10066               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10067                            tempreg, tempreg, BFD_RELOC_LO16);
10068             }
10069           else
10070             {
10071               unsigned int dreg;
10072
10073               /* If we are going to add in a base register, and the
10074                  target register and the base register are the same,
10075                  then we are using AT as a temporary register.  Since
10076                  we want to load the constant into AT, we add our
10077                  current AT (from the global offset table) and the
10078                  register into the register now, and pretend we were
10079                  not using a base register.  */
10080               if (breg != op[0])
10081                 dreg = tempreg;
10082               else
10083                 {
10084                   gas_assert (tempreg == AT);
10085                   load_delay_nop ();
10086                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10087                                op[0], AT, breg);
10088                   dreg = op[0];
10089                 }
10090
10091               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10092               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10093
10094               used_at = 1;
10095             }
10096           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10097           relax_switch ();
10098
10099           if (gpdelay)
10100             {
10101               /* This is needed because this instruction uses $gp, but
10102                  the first instruction on the main stream does not.  */
10103               macro_build (NULL, "nop", "");
10104             }
10105
10106           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10107                        local_reloc_type, mips_gp_register);
10108           if (expr1.X_add_number >= -0x8000
10109               && expr1.X_add_number < 0x8000)
10110             {
10111               load_delay_nop ();
10112               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10113                            tempreg, tempreg, BFD_RELOC_LO16);
10114               /* FIXME: If add_number is 0, and there was no base
10115                  register, the external symbol case ended with a load,
10116                  so if the symbol turns out to not be external, and
10117                  the next instruction uses tempreg, an unnecessary nop
10118                  will be inserted.  */
10119             }
10120           else
10121             {
10122               if (breg == op[0])
10123                 {
10124                   /* We must add in the base register now, as in the
10125                      external symbol case.  */
10126                   gas_assert (tempreg == AT);
10127                   load_delay_nop ();
10128                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10129                                op[0], AT, breg);
10130                   tempreg = op[0];
10131                   /* We set breg to 0 because we have arranged to add
10132                      it in in both cases.  */
10133                   breg = 0;
10134                 }
10135
10136               macro_build_lui (&expr1, AT);
10137               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10138                            AT, AT, BFD_RELOC_LO16);
10139               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10140                            tempreg, tempreg, AT);
10141               used_at = 1;
10142             }
10143           relax_end ();
10144         }
10145       else if (mips_big_got && HAVE_NEWABI)
10146         {
10147           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10148           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10149           int add_breg_early = 0;
10150
10151           /* This is the large GOT case.  If this is a reference to an
10152              external symbol, and there is no constant, we want
10153                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10154                add      $tempreg,$tempreg,$gp
10155                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10156              or for lca or if tempreg is PIC_CALL_REG
10157                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10158                add      $tempreg,$tempreg,$gp
10159                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10160
10161              If we have a small constant, and this is a reference to
10162              an external symbol, we want
10163                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10164                add      $tempreg,$tempreg,$gp
10165                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10166                addi     $tempreg,$tempreg,<constant>
10167
10168              If we have a large constant, and this is a reference to
10169              an external symbol, we want
10170                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10171                addu     $tempreg,$tempreg,$gp
10172                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10173                lui      $at,<hiconstant>
10174                addi     $at,$at,<loconstant>
10175                add      $tempreg,$tempreg,$at
10176
10177              If we have NewABI, and we know it's a local symbol, we want
10178                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10179                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10180              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10181
10182           relax_start (offset_expr.X_add_symbol);
10183
10184           expr1.X_add_number = offset_expr.X_add_number;
10185           offset_expr.X_add_number = 0;
10186
10187           if (expr1.X_add_number == 0 && breg == 0
10188               && (call || tempreg == PIC_CALL_REG))
10189             {
10190               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10191               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10192             }
10193           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10194           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10195                        tempreg, tempreg, mips_gp_register);
10196           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10197                        tempreg, lw_reloc_type, tempreg);
10198
10199           if (expr1.X_add_number == 0)
10200             ;
10201           else if (expr1.X_add_number >= -0x8000
10202                    && expr1.X_add_number < 0x8000)
10203             {
10204               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10205                            tempreg, tempreg, BFD_RELOC_LO16);
10206             }
10207           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10208             {
10209               unsigned int dreg;
10210
10211               /* If we are going to add in a base register, and the
10212                  target register and the base register are the same,
10213                  then we are using AT as a temporary register.  Since
10214                  we want to load the constant into AT, we add our
10215                  current AT (from the global offset table) and the
10216                  register into the register now, and pretend we were
10217                  not using a base register.  */
10218               if (breg != op[0])
10219                 dreg = tempreg;
10220               else
10221                 {
10222                   gas_assert (tempreg == AT);
10223                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10224                                op[0], AT, breg);
10225                   dreg = op[0];
10226                   add_breg_early = 1;
10227                 }
10228
10229               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10230               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10231
10232               used_at = 1;
10233             }
10234           else
10235             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10236
10237           relax_switch ();
10238           offset_expr.X_add_number = expr1.X_add_number;
10239           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10240                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10241           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10242                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10243           if (add_breg_early)
10244             {
10245               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10246                            op[0], tempreg, breg);
10247               breg = 0;
10248               tempreg = op[0];
10249             }
10250           relax_end ();
10251         }
10252       else
10253         abort ();
10254
10255       if (breg != 0)
10256         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10257       break;
10258
10259     case M_MSGSND:
10260       gas_assert (!mips_opts.micromips);
10261       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10262       break;
10263
10264     case M_MSGLD:
10265       gas_assert (!mips_opts.micromips);
10266       macro_build (NULL, "c2", "C", 0x02);
10267       break;
10268
10269     case M_MSGLD_T:
10270       gas_assert (!mips_opts.micromips);
10271       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10272       break;
10273
10274     case M_MSGWAIT:
10275       gas_assert (!mips_opts.micromips);
10276       macro_build (NULL, "c2", "C", 3);
10277       break;
10278
10279     case M_MSGWAIT_T:
10280       gas_assert (!mips_opts.micromips);
10281       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10282       break;
10283
10284     case M_J_A:
10285       /* The j instruction may not be used in PIC code, since it
10286          requires an absolute address.  We convert it to a b
10287          instruction.  */
10288       if (mips_pic == NO_PIC)
10289         macro_build (&offset_expr, "j", "a");
10290       else
10291         macro_build (&offset_expr, "b", "p");
10292       break;
10293
10294       /* The jal instructions must be handled as macros because when
10295          generating PIC code they expand to multi-instruction
10296          sequences.  Normally they are simple instructions.  */
10297     case M_JALS_1:
10298       op[1] = op[0];
10299       op[0] = RA;
10300       /* Fall through.  */
10301     case M_JALS_2:
10302       gas_assert (mips_opts.micromips);
10303       if (mips_opts.insn32)
10304         {
10305           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10306           break;
10307         }
10308       jals = 1;
10309       goto jal;
10310     case M_JAL_1:
10311       op[1] = op[0];
10312       op[0] = RA;
10313       /* Fall through.  */
10314     case M_JAL_2:
10315     jal:
10316       if (mips_pic == NO_PIC)
10317         {
10318           s = jals ? "jalrs" : "jalr";
10319           if (mips_opts.micromips
10320               && !mips_opts.insn32
10321               && op[0] == RA
10322               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10323             macro_build (NULL, s, "mj", op[1]);
10324           else
10325             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10326         }
10327       else
10328         {
10329           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10330                            && mips_cprestore_offset >= 0);
10331
10332           if (op[1] != PIC_CALL_REG)
10333             as_warn (_("MIPS PIC call to register other than $25"));
10334
10335           s = ((mips_opts.micromips
10336                 && !mips_opts.insn32
10337                 && (!mips_opts.noreorder || cprestore))
10338                ? "jalrs" : "jalr");
10339           if (mips_opts.micromips
10340               && !mips_opts.insn32
10341               && op[0] == RA
10342               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10343             macro_build (NULL, s, "mj", op[1]);
10344           else
10345             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10346           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10347             {
10348               if (mips_cprestore_offset < 0)
10349                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10350               else
10351                 {
10352                   if (!mips_frame_reg_valid)
10353                     {
10354                       as_warn (_("no .frame pseudo-op used in PIC code"));
10355                       /* Quiet this warning.  */
10356                       mips_frame_reg_valid = 1;
10357                     }
10358                   if (!mips_cprestore_valid)
10359                     {
10360                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10361                       /* Quiet this warning.  */
10362                       mips_cprestore_valid = 1;
10363                     }
10364                   if (mips_opts.noreorder)
10365                     macro_build (NULL, "nop", "");
10366                   expr1.X_add_number = mips_cprestore_offset;
10367                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10368                                                 mips_gp_register,
10369                                                 mips_frame_reg,
10370                                                 HAVE_64BIT_ADDRESSES);
10371                 }
10372             }
10373         }
10374
10375       break;
10376
10377     case M_JALS_A:
10378       gas_assert (mips_opts.micromips);
10379       if (mips_opts.insn32)
10380         {
10381           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10382           break;
10383         }
10384       jals = 1;
10385       /* Fall through.  */
10386     case M_JAL_A:
10387       if (mips_pic == NO_PIC)
10388         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10389       else if (mips_pic == SVR4_PIC)
10390         {
10391           /* If this is a reference to an external symbol, and we are
10392              using a small GOT, we want
10393                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10394                nop
10395                jalr     $ra,$25
10396                nop
10397                lw       $gp,cprestore($sp)
10398              The cprestore value is set using the .cprestore
10399              pseudo-op.  If we are using a big GOT, we want
10400                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10401                addu     $25,$25,$gp
10402                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10403                nop
10404                jalr     $ra,$25
10405                nop
10406                lw       $gp,cprestore($sp)
10407              If the symbol is not external, we want
10408                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10409                nop
10410                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10411                jalr     $ra,$25
10412                nop
10413                lw $gp,cprestore($sp)
10414
10415              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10416              sequences above, minus nops, unless the symbol is local,
10417              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10418              GOT_DISP.  */
10419           if (HAVE_NEWABI)
10420             {
10421               if (!mips_big_got)
10422                 {
10423                   relax_start (offset_expr.X_add_symbol);
10424                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10425                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10426                                mips_gp_register);
10427                   relax_switch ();
10428                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10429                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10430                                mips_gp_register);
10431                   relax_end ();
10432                 }
10433               else
10434                 {
10435                   relax_start (offset_expr.X_add_symbol);
10436                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10437                                BFD_RELOC_MIPS_CALL_HI16);
10438                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10439                                PIC_CALL_REG, mips_gp_register);
10440                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10441                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10442                                PIC_CALL_REG);
10443                   relax_switch ();
10444                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10445                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10446                                mips_gp_register);
10447                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10448                                PIC_CALL_REG, PIC_CALL_REG,
10449                                BFD_RELOC_MIPS_GOT_OFST);
10450                   relax_end ();
10451                 }
10452
10453               macro_build_jalr (&offset_expr, 0);
10454             }
10455           else
10456             {
10457               relax_start (offset_expr.X_add_symbol);
10458               if (!mips_big_got)
10459                 {
10460                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10461                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10462                                mips_gp_register);
10463                   load_delay_nop ();
10464                   relax_switch ();
10465                 }
10466               else
10467                 {
10468                   int gpdelay;
10469
10470                   gpdelay = reg_needs_delay (mips_gp_register);
10471                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10472                                BFD_RELOC_MIPS_CALL_HI16);
10473                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10474                                PIC_CALL_REG, mips_gp_register);
10475                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10476                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10477                                PIC_CALL_REG);
10478                   load_delay_nop ();
10479                   relax_switch ();
10480                   if (gpdelay)
10481                     macro_build (NULL, "nop", "");
10482                 }
10483               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10484                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10485                            mips_gp_register);
10486               load_delay_nop ();
10487               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10488                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10489               relax_end ();
10490               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10491
10492               if (mips_cprestore_offset < 0)
10493                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10494               else
10495                 {
10496                   if (!mips_frame_reg_valid)
10497                     {
10498                       as_warn (_("no .frame pseudo-op used in PIC code"));
10499                       /* Quiet this warning.  */
10500                       mips_frame_reg_valid = 1;
10501                     }
10502                   if (!mips_cprestore_valid)
10503                     {
10504                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10505                       /* Quiet this warning.  */
10506                       mips_cprestore_valid = 1;
10507                     }
10508                   if (mips_opts.noreorder)
10509                     macro_build (NULL, "nop", "");
10510                   expr1.X_add_number = mips_cprestore_offset;
10511                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10512                                                 mips_gp_register,
10513                                                 mips_frame_reg,
10514                                                 HAVE_64BIT_ADDRESSES);
10515                 }
10516             }
10517         }
10518       else if (mips_pic == VXWORKS_PIC)
10519         as_bad (_("non-PIC jump used in PIC library"));
10520       else
10521         abort ();
10522
10523       break;
10524
10525     case M_LBUE_AB:
10526       s = "lbue";
10527       fmt = "t,+j(b)";
10528       offbits = 9;
10529       goto ld_st;
10530     case M_LHUE_AB:
10531       s = "lhue";
10532       fmt = "t,+j(b)";
10533       offbits = 9;
10534       goto ld_st;
10535     case M_LBE_AB:
10536       s = "lbe";
10537       fmt = "t,+j(b)";
10538       offbits = 9;
10539       goto ld_st;
10540     case M_LHE_AB:
10541       s = "lhe";
10542       fmt = "t,+j(b)";
10543       offbits = 9;
10544       goto ld_st;
10545     case M_LLE_AB:
10546       s = "lle";
10547       fmt = "t,+j(b)";
10548       offbits = 9;
10549       goto ld_st;
10550     case M_LWE_AB:
10551       s = "lwe";
10552       fmt = "t,+j(b)";
10553       offbits = 9;
10554       goto ld_st;
10555     case M_LWLE_AB:
10556       s = "lwle";
10557       fmt = "t,+j(b)";
10558       offbits = 9;
10559       goto ld_st;
10560     case M_LWRE_AB:
10561       s = "lwre";
10562       fmt = "t,+j(b)";
10563       offbits = 9;
10564       goto ld_st;
10565     case M_SBE_AB:
10566       s = "sbe";
10567       fmt = "t,+j(b)";
10568       offbits = 9;
10569       goto ld_st;
10570     case M_SCE_AB:
10571       s = "sce";
10572       fmt = "t,+j(b)";
10573       offbits = 9;
10574       goto ld_st;
10575     case M_SHE_AB:
10576       s = "she";
10577       fmt = "t,+j(b)";
10578       offbits = 9;
10579       goto ld_st;
10580     case M_SWE_AB:
10581       s = "swe";
10582       fmt = "t,+j(b)";
10583       offbits = 9;
10584       goto ld_st;
10585     case M_SWLE_AB:
10586       s = "swle";
10587       fmt = "t,+j(b)";
10588       offbits = 9;
10589       goto ld_st;
10590     case M_SWRE_AB:
10591       s = "swre";
10592       fmt = "t,+j(b)";
10593       offbits = 9;
10594       goto ld_st;
10595     case M_ACLR_AB:
10596       s = "aclr";
10597       fmt = "\\,~(b)";
10598       offbits = 12;
10599       goto ld_st;
10600     case M_ASET_AB:
10601       s = "aset";
10602       fmt = "\\,~(b)";
10603       offbits = 12;
10604       goto ld_st;
10605     case M_LB_AB:
10606       s = "lb";
10607       fmt = "t,o(b)";
10608       goto ld;
10609     case M_LBU_AB:
10610       s = "lbu";
10611       fmt = "t,o(b)";
10612       goto ld;
10613     case M_LH_AB:
10614       s = "lh";
10615       fmt = "t,o(b)";
10616       goto ld;
10617     case M_LHU_AB:
10618       s = "lhu";
10619       fmt = "t,o(b)";
10620       goto ld;
10621     case M_LW_AB:
10622       s = "lw";
10623       fmt = "t,o(b)";
10624       goto ld;
10625     case M_LWC0_AB:
10626       gas_assert (!mips_opts.micromips);
10627       s = "lwc0";
10628       fmt = "E,o(b)";
10629       /* Itbl support may require additional care here.  */
10630       coproc = 1;
10631       goto ld_st;
10632     case M_LWC1_AB:
10633       s = "lwc1";
10634       fmt = "T,o(b)";
10635       /* Itbl support may require additional care here.  */
10636       coproc = 1;
10637       goto ld_st;
10638     case M_LWC2_AB:
10639       s = "lwc2";
10640       fmt = COP12_FMT;
10641       offbits = (mips_opts.micromips ? 12 : 16);
10642       /* Itbl support may require additional care here.  */
10643       coproc = 1;
10644       goto ld_st;
10645     case M_LWC3_AB:
10646       gas_assert (!mips_opts.micromips);
10647       s = "lwc3";
10648       fmt = "E,o(b)";
10649       /* Itbl support may require additional care here.  */
10650       coproc = 1;
10651       goto ld_st;
10652     case M_LWL_AB:
10653       s = "lwl";
10654       fmt = MEM12_FMT;
10655       offbits = (mips_opts.micromips ? 12 : 16);
10656       goto ld_st;
10657     case M_LWR_AB:
10658       s = "lwr";
10659       fmt = MEM12_FMT;
10660       offbits = (mips_opts.micromips ? 12 : 16);
10661       goto ld_st;
10662     case M_LDC1_AB:
10663       s = "ldc1";
10664       fmt = "T,o(b)";
10665       /* Itbl support may require additional care here.  */
10666       coproc = 1;
10667       goto ld_st;
10668     case M_LDC2_AB:
10669       s = "ldc2";
10670       fmt = COP12_FMT;
10671       offbits = (mips_opts.micromips ? 12 : 16);
10672       /* Itbl support may require additional care here.  */
10673       coproc = 1;
10674       goto ld_st;
10675     case M_LQC2_AB:
10676       s = "lqc2";
10677       fmt = "+7,o(b)";
10678       /* Itbl support may require additional care here.  */
10679       coproc = 1;
10680       goto ld_st;
10681     case M_LDC3_AB:
10682       s = "ldc3";
10683       fmt = "E,o(b)";
10684       /* Itbl support may require additional care here.  */
10685       coproc = 1;
10686       goto ld_st;
10687     case M_LDL_AB:
10688       s = "ldl";
10689       fmt = MEM12_FMT;
10690       offbits = (mips_opts.micromips ? 12 : 16);
10691       goto ld_st;
10692     case M_LDR_AB:
10693       s = "ldr";
10694       fmt = MEM12_FMT;
10695       offbits = (mips_opts.micromips ? 12 : 16);
10696       goto ld_st;
10697     case M_LL_AB:
10698       s = "ll";
10699       fmt = MEM12_FMT;
10700       offbits = (mips_opts.micromips ? 12 : 16);
10701       goto ld;
10702     case M_LLD_AB:
10703       s = "lld";
10704       fmt = MEM12_FMT;
10705       offbits = (mips_opts.micromips ? 12 : 16);
10706       goto ld;
10707     case M_LWU_AB:
10708       s = "lwu";
10709       fmt = MEM12_FMT;
10710       offbits = (mips_opts.micromips ? 12 : 16);
10711       goto ld;
10712     case M_LWP_AB:
10713       gas_assert (mips_opts.micromips);
10714       s = "lwp";
10715       fmt = "t,~(b)";
10716       offbits = 12;
10717       lp = 1;
10718       goto ld;
10719     case M_LDP_AB:
10720       gas_assert (mips_opts.micromips);
10721       s = "ldp";
10722       fmt = "t,~(b)";
10723       offbits = 12;
10724       lp = 1;
10725       goto ld;
10726     case M_LWM_AB:
10727       gas_assert (mips_opts.micromips);
10728       s = "lwm";
10729       fmt = "n,~(b)";
10730       offbits = 12;
10731       goto ld_st;
10732     case M_LDM_AB:
10733       gas_assert (mips_opts.micromips);
10734       s = "ldm";
10735       fmt = "n,~(b)";
10736       offbits = 12;
10737       goto ld_st;
10738
10739     ld:
10740       /* We don't want to use $0 as tempreg.  */
10741       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10742         goto ld_st;
10743       else
10744         tempreg = op[0] + lp;
10745       goto ld_noat;
10746
10747     case M_SB_AB:
10748       s = "sb";
10749       fmt = "t,o(b)";
10750       goto ld_st;
10751     case M_SH_AB:
10752       s = "sh";
10753       fmt = "t,o(b)";
10754       goto ld_st;
10755     case M_SW_AB:
10756       s = "sw";
10757       fmt = "t,o(b)";
10758       goto ld_st;
10759     case M_SWC0_AB:
10760       gas_assert (!mips_opts.micromips);
10761       s = "swc0";
10762       fmt = "E,o(b)";
10763       /* Itbl support may require additional care here.  */
10764       coproc = 1;
10765       goto ld_st;
10766     case M_SWC1_AB:
10767       s = "swc1";
10768       fmt = "T,o(b)";
10769       /* Itbl support may require additional care here.  */
10770       coproc = 1;
10771       goto ld_st;
10772     case M_SWC2_AB:
10773       s = "swc2";
10774       fmt = COP12_FMT;
10775       offbits = (mips_opts.micromips ? 12 : 16);
10776       /* Itbl support may require additional care here.  */
10777       coproc = 1;
10778       goto ld_st;
10779     case M_SWC3_AB:
10780       gas_assert (!mips_opts.micromips);
10781       s = "swc3";
10782       fmt = "E,o(b)";
10783       /* Itbl support may require additional care here.  */
10784       coproc = 1;
10785       goto ld_st;
10786     case M_SWL_AB:
10787       s = "swl";
10788       fmt = MEM12_FMT;
10789       offbits = (mips_opts.micromips ? 12 : 16);
10790       goto ld_st;
10791     case M_SWR_AB:
10792       s = "swr";
10793       fmt = MEM12_FMT;
10794       offbits = (mips_opts.micromips ? 12 : 16);
10795       goto ld_st;
10796     case M_SC_AB:
10797       s = "sc";
10798       fmt = MEM12_FMT;
10799       offbits = (mips_opts.micromips ? 12 : 16);
10800       goto ld_st;
10801     case M_SCD_AB:
10802       s = "scd";
10803       fmt = MEM12_FMT;
10804       offbits = (mips_opts.micromips ? 12 : 16);
10805       goto ld_st;
10806     case M_CACHE_AB:
10807       s = "cache";
10808       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10809       offbits = (mips_opts.micromips ? 12 : 16);
10810       goto ld_st;
10811     case M_CACHEE_AB:
10812       s = "cachee";
10813       fmt = "k,+j(b)";
10814       offbits = 9;
10815       goto ld_st;
10816     case M_PREF_AB:
10817       s = "pref";
10818       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10819       offbits = (mips_opts.micromips ? 12 : 16);
10820       goto ld_st;
10821     case M_PREFE_AB:
10822       s = "prefe";
10823       fmt = "k,+j(b)";
10824       offbits = 9;
10825       goto ld_st;
10826     case M_SDC1_AB:
10827       s = "sdc1";
10828       fmt = "T,o(b)";
10829       coproc = 1;
10830       /* Itbl support may require additional care here.  */
10831       goto ld_st;
10832     case M_SDC2_AB:
10833       s = "sdc2";
10834       fmt = COP12_FMT;
10835       offbits = (mips_opts.micromips ? 12 : 16);
10836       /* Itbl support may require additional care here.  */
10837       coproc = 1;
10838       goto ld_st;
10839     case M_SQC2_AB:
10840       s = "sqc2";
10841       fmt = "+7,o(b)";
10842       /* Itbl support may require additional care here.  */
10843       coproc = 1;
10844       goto ld_st;
10845     case M_SDC3_AB:
10846       gas_assert (!mips_opts.micromips);
10847       s = "sdc3";
10848       fmt = "E,o(b)";
10849       /* Itbl support may require additional care here.  */
10850       coproc = 1;
10851       goto ld_st;
10852     case M_SDL_AB:
10853       s = "sdl";
10854       fmt = MEM12_FMT;
10855       offbits = (mips_opts.micromips ? 12 : 16);
10856       goto ld_st;
10857     case M_SDR_AB:
10858       s = "sdr";
10859       fmt = MEM12_FMT;
10860       offbits = (mips_opts.micromips ? 12 : 16);
10861       goto ld_st;
10862     case M_SWP_AB:
10863       gas_assert (mips_opts.micromips);
10864       s = "swp";
10865       fmt = "t,~(b)";
10866       offbits = 12;
10867       goto ld_st;
10868     case M_SDP_AB:
10869       gas_assert (mips_opts.micromips);
10870       s = "sdp";
10871       fmt = "t,~(b)";
10872       offbits = 12;
10873       goto ld_st;
10874     case M_SWM_AB:
10875       gas_assert (mips_opts.micromips);
10876       s = "swm";
10877       fmt = "n,~(b)";
10878       offbits = 12;
10879       goto ld_st;
10880     case M_SDM_AB:
10881       gas_assert (mips_opts.micromips);
10882       s = "sdm";
10883       fmt = "n,~(b)";
10884       offbits = 12;
10885
10886     ld_st:
10887       tempreg = AT;
10888     ld_noat:
10889       breg = op[2];
10890       if (small_offset_p (0, align, 16))
10891         {
10892           /* The first case exists for M_LD_AB and M_SD_AB, which are
10893              macros for o32 but which should act like normal instructions
10894              otherwise.  */
10895           if (offbits == 16)
10896             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
10897                          offset_reloc[1], offset_reloc[2], breg);
10898           else if (small_offset_p (0, align, offbits))
10899             {
10900               if (offbits == 0)
10901                 macro_build (NULL, s, fmt, op[0], breg);
10902               else
10903                 macro_build (NULL, s, fmt, op[0],
10904                              (int) offset_expr.X_add_number, breg);
10905             }
10906           else
10907             {
10908               if (tempreg == AT)
10909                 used_at = 1;
10910               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10911                            tempreg, breg, -1, offset_reloc[0],
10912                            offset_reloc[1], offset_reloc[2]);
10913               if (offbits == 0)
10914                 macro_build (NULL, s, fmt, op[0], tempreg);
10915               else
10916                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
10917             }
10918           break;
10919         }
10920
10921       if (tempreg == AT)
10922         used_at = 1;
10923
10924       if (offset_expr.X_op != O_constant
10925           && offset_expr.X_op != O_symbol)
10926         {
10927           as_bad (_("expression too complex"));
10928           offset_expr.X_op = O_constant;
10929         }
10930
10931       if (HAVE_32BIT_ADDRESSES
10932           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10933         {
10934           char value [32];
10935
10936           sprintf_vma (value, offset_expr.X_add_number);
10937           as_bad (_("number (0x%s) larger than 32 bits"), value);
10938         }
10939
10940       /* A constant expression in PIC code can be handled just as it
10941          is in non PIC code.  */
10942       if (offset_expr.X_op == O_constant)
10943         {
10944           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
10945                                                  offbits == 0 ? 16 : offbits);
10946           offset_expr.X_add_number -= expr1.X_add_number;
10947
10948           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
10949           if (breg != 0)
10950             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10951                          tempreg, tempreg, breg);
10952           if (offbits == 0)
10953             {
10954               if (offset_expr.X_add_number != 0)
10955                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
10956                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
10957               macro_build (NULL, s, fmt, op[0], tempreg);
10958             }
10959           else if (offbits == 16)
10960             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
10961           else
10962             macro_build (NULL, s, fmt, op[0],
10963                          (int) offset_expr.X_add_number, tempreg);
10964         }
10965       else if (offbits != 16)
10966         {
10967           /* The offset field is too narrow to be used for a low-part
10968              relocation, so load the whole address into the auxillary
10969              register.  */
10970           load_address (tempreg, &offset_expr, &used_at);
10971           if (breg != 0)
10972             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10973                          tempreg, tempreg, breg);
10974           if (offbits == 0)
10975             macro_build (NULL, s, fmt, op[0], tempreg);
10976           else
10977             macro_build (NULL, s, fmt, op[0], 0, tempreg);
10978         }
10979       else if (mips_pic == NO_PIC)
10980         {
10981           /* If this is a reference to a GP relative symbol, and there
10982              is no base register, we want
10983                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
10984              Otherwise, if there is no base register, we want
10985                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10986                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10987              If we have a constant, we need two instructions anyhow,
10988              so we always use the latter form.
10989
10990              If we have a base register, and this is a reference to a
10991              GP relative symbol, we want
10992                addu     $tempreg,$breg,$gp
10993                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
10994              Otherwise we want
10995                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10996                addu     $tempreg,$tempreg,$breg
10997                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
10998              With a constant we always use the latter case.
10999
11000              With 64bit address space and no base register and $at usable,
11001              we want
11002                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11003                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11004                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11005                dsll32   $tempreg,0
11006                daddu    $tempreg,$at
11007                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11008              If we have a base register, we want
11009                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11010                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11011                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11012                daddu    $at,$breg
11013                dsll32   $tempreg,0
11014                daddu    $tempreg,$at
11015                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11016
11017              Without $at we can't generate the optimal path for superscalar
11018              processors here since this would require two temporary registers.
11019                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11020                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11021                dsll     $tempreg,16
11022                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11023                dsll     $tempreg,16
11024                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11025              If we have a base register, we want
11026                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11027                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11028                dsll     $tempreg,16
11029                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11030                dsll     $tempreg,16
11031                daddu    $tempreg,$tempreg,$breg
11032                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11033
11034              For GP relative symbols in 64bit address space we can use
11035              the same sequence as in 32bit address space.  */
11036           if (HAVE_64BIT_SYMBOLS)
11037             {
11038               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11039                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11040                 {
11041                   relax_start (offset_expr.X_add_symbol);
11042                   if (breg == 0)
11043                     {
11044                       macro_build (&offset_expr, s, fmt, op[0],
11045                                    BFD_RELOC_GPREL16, mips_gp_register);
11046                     }
11047                   else
11048                     {
11049                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11050                                    tempreg, breg, mips_gp_register);
11051                       macro_build (&offset_expr, s, fmt, op[0],
11052                                    BFD_RELOC_GPREL16, tempreg);
11053                     }
11054                   relax_switch ();
11055                 }
11056
11057               if (used_at == 0 && mips_opts.at)
11058                 {
11059                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11060                                BFD_RELOC_MIPS_HIGHEST);
11061                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11062                                BFD_RELOC_HI16_S);
11063                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11064                                tempreg, BFD_RELOC_MIPS_HIGHER);
11065                   if (breg != 0)
11066                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11067                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11068                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11069                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11070                                tempreg);
11071                   used_at = 1;
11072                 }
11073               else
11074                 {
11075                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11076                                BFD_RELOC_MIPS_HIGHEST);
11077                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11078                                tempreg, BFD_RELOC_MIPS_HIGHER);
11079                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11080                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11081                                tempreg, BFD_RELOC_HI16_S);
11082                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11083                   if (breg != 0)
11084                     macro_build (NULL, "daddu", "d,v,t",
11085                                  tempreg, tempreg, breg);
11086                   macro_build (&offset_expr, s, fmt, op[0],
11087                                BFD_RELOC_LO16, tempreg);
11088                 }
11089
11090               if (mips_relax.sequence)
11091                 relax_end ();
11092               break;
11093             }
11094
11095           if (breg == 0)
11096             {
11097               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11098                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11099                 {
11100                   relax_start (offset_expr.X_add_symbol);
11101                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11102                                mips_gp_register);
11103                   relax_switch ();
11104                 }
11105               macro_build_lui (&offset_expr, tempreg);
11106               macro_build (&offset_expr, s, fmt, op[0],
11107                            BFD_RELOC_LO16, tempreg);
11108               if (mips_relax.sequence)
11109                 relax_end ();
11110             }
11111           else
11112             {
11113               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11114                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11115                 {
11116                   relax_start (offset_expr.X_add_symbol);
11117                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11118                                tempreg, breg, mips_gp_register);
11119                   macro_build (&offset_expr, s, fmt, op[0],
11120                                BFD_RELOC_GPREL16, tempreg);
11121                   relax_switch ();
11122                 }
11123               macro_build_lui (&offset_expr, tempreg);
11124               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11125                            tempreg, tempreg, breg);
11126               macro_build (&offset_expr, s, fmt, op[0],
11127                            BFD_RELOC_LO16, tempreg);
11128               if (mips_relax.sequence)
11129                 relax_end ();
11130             }
11131         }
11132       else if (!mips_big_got)
11133         {
11134           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11135
11136           /* If this is a reference to an external symbol, we want
11137                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11138                nop
11139                <op>     op[0],0($tempreg)
11140              Otherwise we want
11141                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11142                nop
11143                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11144                <op>     op[0],0($tempreg)
11145
11146              For NewABI, we want
11147                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11148                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11149
11150              If there is a base register, we add it to $tempreg before
11151              the <op>.  If there is a constant, we stick it in the
11152              <op> instruction.  We don't handle constants larger than
11153              16 bits, because we have no way to load the upper 16 bits
11154              (actually, we could handle them for the subset of cases
11155              in which we are not using $at).  */
11156           gas_assert (offset_expr.X_op == O_symbol);
11157           if (HAVE_NEWABI)
11158             {
11159               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11160                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11161               if (breg != 0)
11162                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11163                              tempreg, tempreg, breg);
11164               macro_build (&offset_expr, s, fmt, op[0],
11165                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11166               break;
11167             }
11168           expr1.X_add_number = offset_expr.X_add_number;
11169           offset_expr.X_add_number = 0;
11170           if (expr1.X_add_number < -0x8000
11171               || expr1.X_add_number >= 0x8000)
11172             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11173           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11174                        lw_reloc_type, mips_gp_register);
11175           load_delay_nop ();
11176           relax_start (offset_expr.X_add_symbol);
11177           relax_switch ();
11178           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11179                        tempreg, BFD_RELOC_LO16);
11180           relax_end ();
11181           if (breg != 0)
11182             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11183                          tempreg, tempreg, breg);
11184           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11185         }
11186       else if (mips_big_got && !HAVE_NEWABI)
11187         {
11188           int gpdelay;
11189
11190           /* If this is a reference to an external symbol, we want
11191                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11192                addu     $tempreg,$tempreg,$gp
11193                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11194                <op>     op[0],0($tempreg)
11195              Otherwise we want
11196                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11197                nop
11198                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11199                <op>     op[0],0($tempreg)
11200              If there is a base register, we add it to $tempreg before
11201              the <op>.  If there is a constant, we stick it in the
11202              <op> instruction.  We don't handle constants larger than
11203              16 bits, because we have no way to load the upper 16 bits
11204              (actually, we could handle them for the subset of cases
11205              in which we are not using $at).  */
11206           gas_assert (offset_expr.X_op == O_symbol);
11207           expr1.X_add_number = offset_expr.X_add_number;
11208           offset_expr.X_add_number = 0;
11209           if (expr1.X_add_number < -0x8000
11210               || expr1.X_add_number >= 0x8000)
11211             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11212           gpdelay = reg_needs_delay (mips_gp_register);
11213           relax_start (offset_expr.X_add_symbol);
11214           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11215                        BFD_RELOC_MIPS_GOT_HI16);
11216           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11217                        mips_gp_register);
11218           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11219                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11220           relax_switch ();
11221           if (gpdelay)
11222             macro_build (NULL, "nop", "");
11223           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11224                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11225           load_delay_nop ();
11226           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11227                        tempreg, BFD_RELOC_LO16);
11228           relax_end ();
11229
11230           if (breg != 0)
11231             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11232                          tempreg, tempreg, breg);
11233           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11234         }
11235       else if (mips_big_got && HAVE_NEWABI)
11236         {
11237           /* If this is a reference to an external symbol, we want
11238                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11239                add      $tempreg,$tempreg,$gp
11240                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11241                <op>     op[0],<ofst>($tempreg)
11242              Otherwise, for local symbols, we want:
11243                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11244                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11245           gas_assert (offset_expr.X_op == O_symbol);
11246           expr1.X_add_number = offset_expr.X_add_number;
11247           offset_expr.X_add_number = 0;
11248           if (expr1.X_add_number < -0x8000
11249               || expr1.X_add_number >= 0x8000)
11250             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11251           relax_start (offset_expr.X_add_symbol);
11252           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11253                        BFD_RELOC_MIPS_GOT_HI16);
11254           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11255                        mips_gp_register);
11256           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11257                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11258           if (breg != 0)
11259             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11260                          tempreg, tempreg, breg);
11261           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11262
11263           relax_switch ();
11264           offset_expr.X_add_number = expr1.X_add_number;
11265           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11266                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11267           if (breg != 0)
11268             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11269                          tempreg, tempreg, breg);
11270           macro_build (&offset_expr, s, fmt, op[0],
11271                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11272           relax_end ();
11273         }
11274       else
11275         abort ();
11276
11277       break;
11278
11279     case M_JRADDIUSP:
11280       gas_assert (mips_opts.micromips);
11281       gas_assert (mips_opts.insn32);
11282       start_noreorder ();
11283       macro_build (NULL, "jr", "s", RA);
11284       expr1.X_add_number = op[0] << 2;
11285       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11286       end_noreorder ();
11287       break;
11288
11289     case M_JRC:
11290       gas_assert (mips_opts.micromips);
11291       gas_assert (mips_opts.insn32);
11292       macro_build (NULL, "jr", "s", op[0]);
11293       if (mips_opts.noreorder)
11294         macro_build (NULL, "nop", "");
11295       break;
11296
11297     case M_LI:
11298     case M_LI_S:
11299       load_register (op[0], &imm_expr, 0);
11300       break;
11301
11302     case M_DLI:
11303       load_register (op[0], &imm_expr, 1);
11304       break;
11305
11306     case M_LI_SS:
11307       if (imm_expr.X_op == O_constant)
11308         {
11309           used_at = 1;
11310           load_register (AT, &imm_expr, 0);
11311           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11312           break;
11313         }
11314       else
11315         {
11316           gas_assert (imm_expr.X_op == O_absent
11317                       && offset_expr.X_op == O_symbol
11318                       && strcmp (segment_name (S_GET_SEGMENT
11319                                                (offset_expr.X_add_symbol)),
11320                                  ".lit4") == 0
11321                       && offset_expr.X_add_number == 0);
11322           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11323                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11324           break;
11325         }
11326
11327     case M_LI_D:
11328       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11329          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11330          order 32 bits of the value and the low order 32 bits are either
11331          zero or in OFFSET_EXPR.  */
11332       if (imm_expr.X_op == O_constant)
11333         {
11334           if (HAVE_64BIT_GPRS)
11335             load_register (op[0], &imm_expr, 1);
11336           else
11337             {
11338               int hreg, lreg;
11339
11340               if (target_big_endian)
11341                 {
11342                   hreg = op[0];
11343                   lreg = op[0] + 1;
11344                 }
11345               else
11346                 {
11347                   hreg = op[0] + 1;
11348                   lreg = op[0];
11349                 }
11350
11351               if (hreg <= 31)
11352                 load_register (hreg, &imm_expr, 0);
11353               if (lreg <= 31)
11354                 {
11355                   if (offset_expr.X_op == O_absent)
11356                     move_register (lreg, 0);
11357                   else
11358                     {
11359                       gas_assert (offset_expr.X_op == O_constant);
11360                       load_register (lreg, &offset_expr, 0);
11361                     }
11362                 }
11363             }
11364           break;
11365         }
11366       gas_assert (imm_expr.X_op == O_absent);
11367
11368       /* We know that sym is in the .rdata section.  First we get the
11369          upper 16 bits of the address.  */
11370       if (mips_pic == NO_PIC)
11371         {
11372           macro_build_lui (&offset_expr, AT);
11373           used_at = 1;
11374         }
11375       else
11376         {
11377           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11378                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11379           used_at = 1;
11380         }
11381
11382       /* Now we load the register(s).  */
11383       if (HAVE_64BIT_GPRS)
11384         {
11385           used_at = 1;
11386           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11387                        BFD_RELOC_LO16, AT);
11388         }
11389       else
11390         {
11391           used_at = 1;
11392           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11393                        BFD_RELOC_LO16, AT);
11394           if (op[0] != RA)
11395             {
11396               /* FIXME: How in the world do we deal with the possible
11397                  overflow here?  */
11398               offset_expr.X_add_number += 4;
11399               macro_build (&offset_expr, "lw", "t,o(b)",
11400                            op[0] + 1, BFD_RELOC_LO16, AT);
11401             }
11402         }
11403       break;
11404
11405     case M_LI_DD:
11406       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11407          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11408          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11409          the value and the low order 32 bits are either zero or in
11410          OFFSET_EXPR.  */
11411       if (imm_expr.X_op == O_constant)
11412         {
11413           used_at = 1;
11414           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11415           if (HAVE_64BIT_FPRS)
11416             {
11417               gas_assert (HAVE_64BIT_GPRS);
11418               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11419             }
11420           else
11421             {
11422               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11423               if (offset_expr.X_op == O_absent)
11424                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11425               else
11426                 {
11427                   gas_assert (offset_expr.X_op == O_constant);
11428                   load_register (AT, &offset_expr, 0);
11429                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11430                 }
11431             }
11432           break;
11433         }
11434
11435       gas_assert (imm_expr.X_op == O_absent
11436                   && offset_expr.X_op == O_symbol
11437                   && offset_expr.X_add_number == 0);
11438       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11439       if (strcmp (s, ".lit8") == 0)
11440         {
11441           op[2] = mips_gp_register;
11442           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11443           offset_reloc[1] = BFD_RELOC_UNUSED;
11444           offset_reloc[2] = BFD_RELOC_UNUSED;
11445         }
11446       else
11447         {
11448           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11449           used_at = 1;
11450           if (mips_pic != NO_PIC)
11451             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11452                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11453           else
11454             {
11455               /* FIXME: This won't work for a 64 bit address.  */
11456               macro_build_lui (&offset_expr, AT);
11457             }
11458
11459           op[2] = AT;
11460           offset_reloc[0] = BFD_RELOC_LO16;
11461           offset_reloc[1] = BFD_RELOC_UNUSED;
11462           offset_reloc[2] = BFD_RELOC_UNUSED;
11463         }
11464       align = 8;
11465       /* Fall through */
11466
11467     case M_L_DAB:
11468       /*
11469        * The MIPS assembler seems to check for X_add_number not
11470        * being double aligned and generating:
11471        *        lui     at,%hi(foo+1)
11472        *        addu    at,at,v1
11473        *        addiu   at,at,%lo(foo+1)
11474        *        lwc1    f2,0(at)
11475        *        lwc1    f3,4(at)
11476        * But, the resulting address is the same after relocation so why
11477        * generate the extra instruction?
11478        */
11479       /* Itbl support may require additional care here.  */
11480       coproc = 1;
11481       fmt = "T,o(b)";
11482       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11483         {
11484           s = "ldc1";
11485           goto ld_st;
11486         }
11487       s = "lwc1";
11488       goto ldd_std;
11489
11490     case M_S_DAB:
11491       gas_assert (!mips_opts.micromips);
11492       /* Itbl support may require additional care here.  */
11493       coproc = 1;
11494       fmt = "T,o(b)";
11495       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11496         {
11497           s = "sdc1";
11498           goto ld_st;
11499         }
11500       s = "swc1";
11501       goto ldd_std;
11502
11503     case M_LQ_AB:
11504       fmt = "t,o(b)";
11505       s = "lq";
11506       goto ld;
11507
11508     case M_SQ_AB:
11509       fmt = "t,o(b)";
11510       s = "sq";
11511       goto ld_st;
11512
11513     case M_LD_AB:
11514       fmt = "t,o(b)";
11515       if (HAVE_64BIT_GPRS)
11516         {
11517           s = "ld";
11518           goto ld;
11519         }
11520       s = "lw";
11521       goto ldd_std;
11522
11523     case M_SD_AB:
11524       fmt = "t,o(b)";
11525       if (HAVE_64BIT_GPRS)
11526         {
11527           s = "sd";
11528           goto ld_st;
11529         }
11530       s = "sw";
11531
11532     ldd_std:
11533       /* Even on a big endian machine $fn comes before $fn+1.  We have
11534          to adjust when loading from memory.  We set coproc if we must
11535          load $fn+1 first.  */
11536       /* Itbl support may require additional care here.  */
11537       if (!target_big_endian)
11538         coproc = 0;
11539
11540       breg = op[2];
11541       if (small_offset_p (0, align, 16))
11542         {
11543           ep = &offset_expr;
11544           if (!small_offset_p (4, align, 16))
11545             {
11546               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11547                            -1, offset_reloc[0], offset_reloc[1],
11548                            offset_reloc[2]);
11549               expr1.X_add_number = 0;
11550               ep = &expr1;
11551               breg = AT;
11552               used_at = 1;
11553               offset_reloc[0] = BFD_RELOC_LO16;
11554               offset_reloc[1] = BFD_RELOC_UNUSED;
11555               offset_reloc[2] = BFD_RELOC_UNUSED;
11556             }
11557           if (strcmp (s, "lw") == 0 && op[0] == breg)
11558             {
11559               ep->X_add_number += 4;
11560               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11561                            offset_reloc[1], offset_reloc[2], breg);
11562               ep->X_add_number -= 4;
11563               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11564                            offset_reloc[1], offset_reloc[2], breg);
11565             }
11566           else
11567             {
11568               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11569                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11570                            breg);
11571               ep->X_add_number += 4;
11572               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11573                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11574                            breg);
11575             }
11576           break;
11577         }
11578
11579       if (offset_expr.X_op != O_symbol
11580           && offset_expr.X_op != O_constant)
11581         {
11582           as_bad (_("expression too complex"));
11583           offset_expr.X_op = O_constant;
11584         }
11585
11586       if (HAVE_32BIT_ADDRESSES
11587           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11588         {
11589           char value [32];
11590
11591           sprintf_vma (value, offset_expr.X_add_number);
11592           as_bad (_("number (0x%s) larger than 32 bits"), value);
11593         }
11594
11595       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11596         {
11597           /* If this is a reference to a GP relative symbol, we want
11598                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11599                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11600              If we have a base register, we use this
11601                addu     $at,$breg,$gp
11602                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11603                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11604              If this is not a GP relative symbol, we want
11605                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11606                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11607                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11608              If there is a base register, we add it to $at after the
11609              lui instruction.  If there is a constant, we always use
11610              the last case.  */
11611           if (offset_expr.X_op == O_symbol
11612               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11613               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11614             {
11615               relax_start (offset_expr.X_add_symbol);
11616               if (breg == 0)
11617                 {
11618                   tempreg = mips_gp_register;
11619                 }
11620               else
11621                 {
11622                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11623                                AT, breg, mips_gp_register);
11624                   tempreg = AT;
11625                   used_at = 1;
11626                 }
11627
11628               /* Itbl support may require additional care here.  */
11629               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11630                            BFD_RELOC_GPREL16, tempreg);
11631               offset_expr.X_add_number += 4;
11632
11633               /* Set mips_optimize to 2 to avoid inserting an
11634                  undesired nop.  */
11635               hold_mips_optimize = mips_optimize;
11636               mips_optimize = 2;
11637               /* Itbl support may require additional care here.  */
11638               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11639                            BFD_RELOC_GPREL16, tempreg);
11640               mips_optimize = hold_mips_optimize;
11641
11642               relax_switch ();
11643
11644               offset_expr.X_add_number -= 4;
11645             }
11646           used_at = 1;
11647           if (offset_high_part (offset_expr.X_add_number, 16)
11648               != offset_high_part (offset_expr.X_add_number + 4, 16))
11649             {
11650               load_address (AT, &offset_expr, &used_at);
11651               offset_expr.X_op = O_constant;
11652               offset_expr.X_add_number = 0;
11653             }
11654           else
11655             macro_build_lui (&offset_expr, AT);
11656           if (breg != 0)
11657             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11658           /* Itbl support may require additional care here.  */
11659           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11660                        BFD_RELOC_LO16, AT);
11661           /* FIXME: How do we handle overflow here?  */
11662           offset_expr.X_add_number += 4;
11663           /* Itbl support may require additional care here.  */
11664           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11665                        BFD_RELOC_LO16, AT);
11666           if (mips_relax.sequence)
11667             relax_end ();
11668         }
11669       else if (!mips_big_got)
11670         {
11671           /* If this is a reference to an external symbol, we want
11672                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11673                nop
11674                <op>     op[0],0($at)
11675                <op>     op[0]+1,4($at)
11676              Otherwise we want
11677                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11678                nop
11679                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11680                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11681              If there is a base register we add it to $at before the
11682              lwc1 instructions.  If there is a constant we include it
11683              in the lwc1 instructions.  */
11684           used_at = 1;
11685           expr1.X_add_number = offset_expr.X_add_number;
11686           if (expr1.X_add_number < -0x8000
11687               || expr1.X_add_number >= 0x8000 - 4)
11688             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11689           load_got_offset (AT, &offset_expr);
11690           load_delay_nop ();
11691           if (breg != 0)
11692             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11693
11694           /* Set mips_optimize to 2 to avoid inserting an undesired
11695              nop.  */
11696           hold_mips_optimize = mips_optimize;
11697           mips_optimize = 2;
11698
11699           /* Itbl support may require additional care here.  */
11700           relax_start (offset_expr.X_add_symbol);
11701           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11702                        BFD_RELOC_LO16, AT);
11703           expr1.X_add_number += 4;
11704           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11705                        BFD_RELOC_LO16, AT);
11706           relax_switch ();
11707           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11708                        BFD_RELOC_LO16, AT);
11709           offset_expr.X_add_number += 4;
11710           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11711                        BFD_RELOC_LO16, AT);
11712           relax_end ();
11713
11714           mips_optimize = hold_mips_optimize;
11715         }
11716       else if (mips_big_got)
11717         {
11718           int gpdelay;
11719
11720           /* If this is a reference to an external symbol, we want
11721                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11722                addu     $at,$at,$gp
11723                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11724                nop
11725                <op>     op[0],0($at)
11726                <op>     op[0]+1,4($at)
11727              Otherwise we want
11728                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11729                nop
11730                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11731                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11732              If there is a base register we add it to $at before the
11733              lwc1 instructions.  If there is a constant we include it
11734              in the lwc1 instructions.  */
11735           used_at = 1;
11736           expr1.X_add_number = offset_expr.X_add_number;
11737           offset_expr.X_add_number = 0;
11738           if (expr1.X_add_number < -0x8000
11739               || expr1.X_add_number >= 0x8000 - 4)
11740             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11741           gpdelay = reg_needs_delay (mips_gp_register);
11742           relax_start (offset_expr.X_add_symbol);
11743           macro_build (&offset_expr, "lui", LUI_FMT,
11744                        AT, BFD_RELOC_MIPS_GOT_HI16);
11745           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11746                        AT, AT, mips_gp_register);
11747           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11748                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11749           load_delay_nop ();
11750           if (breg != 0)
11751             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11752           /* Itbl support may require additional care here.  */
11753           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11754                        BFD_RELOC_LO16, AT);
11755           expr1.X_add_number += 4;
11756
11757           /* Set mips_optimize to 2 to avoid inserting an undesired
11758              nop.  */
11759           hold_mips_optimize = mips_optimize;
11760           mips_optimize = 2;
11761           /* Itbl support may require additional care here.  */
11762           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11763                        BFD_RELOC_LO16, AT);
11764           mips_optimize = hold_mips_optimize;
11765           expr1.X_add_number -= 4;
11766
11767           relax_switch ();
11768           offset_expr.X_add_number = expr1.X_add_number;
11769           if (gpdelay)
11770             macro_build (NULL, "nop", "");
11771           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11772                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11773           load_delay_nop ();
11774           if (breg != 0)
11775             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11776           /* Itbl support may require additional care here.  */
11777           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11778                        BFD_RELOC_LO16, AT);
11779           offset_expr.X_add_number += 4;
11780
11781           /* Set mips_optimize to 2 to avoid inserting an undesired
11782              nop.  */
11783           hold_mips_optimize = mips_optimize;
11784           mips_optimize = 2;
11785           /* Itbl support may require additional care here.  */
11786           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11787                        BFD_RELOC_LO16, AT);
11788           mips_optimize = hold_mips_optimize;
11789           relax_end ();
11790         }
11791       else
11792         abort ();
11793
11794       break;
11795         
11796     case M_SAA_AB:
11797       s = "saa";
11798       offbits = 0;
11799       fmt = "t,(b)";
11800       goto ld_st;
11801     case M_SAAD_AB:
11802       s = "saad";
11803       offbits = 0;
11804       fmt = "t,(b)";
11805       goto ld_st;
11806
11807    /* New code added to support COPZ instructions.
11808       This code builds table entries out of the macros in mip_opcodes.
11809       R4000 uses interlocks to handle coproc delays.
11810       Other chips (like the R3000) require nops to be inserted for delays.
11811
11812       FIXME: Currently, we require that the user handle delays.
11813       In order to fill delay slots for non-interlocked chips,
11814       we must have a way to specify delays based on the coprocessor.
11815       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11816       What are the side-effects of the cop instruction?
11817       What cache support might we have and what are its effects?
11818       Both coprocessor & memory require delays. how long???
11819       What registers are read/set/modified?
11820
11821       If an itbl is provided to interpret cop instructions,
11822       this knowledge can be encoded in the itbl spec.  */
11823
11824     case M_COP0:
11825       s = "c0";
11826       goto copz;
11827     case M_COP1:
11828       s = "c1";
11829       goto copz;
11830     case M_COP2:
11831       s = "c2";
11832       goto copz;
11833     case M_COP3:
11834       s = "c3";
11835     copz:
11836       gas_assert (!mips_opts.micromips);
11837       /* For now we just do C (same as Cz).  The parameter will be
11838          stored in insn_opcode by mips_ip.  */
11839       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11840       break;
11841
11842     case M_MOVE:
11843       move_register (op[0], op[1]);
11844       break;
11845
11846     case M_MOVEP:
11847       gas_assert (mips_opts.micromips);
11848       gas_assert (mips_opts.insn32);
11849       move_register (micromips_to_32_reg_h_map1[op[0]],
11850                      micromips_to_32_reg_m_map[op[1]]);
11851       move_register (micromips_to_32_reg_h_map2[op[0]],
11852                      micromips_to_32_reg_n_map[op[2]]);
11853       break;
11854
11855     case M_DMUL:
11856       dbl = 1;
11857     case M_MUL:
11858       if (mips_opts.arch == CPU_R5900)
11859         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11860                      op[2]);
11861       else
11862         {
11863           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11864           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11865         }
11866       break;
11867
11868     case M_DMUL_I:
11869       dbl = 1;
11870     case M_MUL_I:
11871       /* The MIPS assembler some times generates shifts and adds.  I'm
11872          not trying to be that fancy. GCC should do this for us
11873          anyway.  */
11874       used_at = 1;
11875       load_register (AT, &imm_expr, dbl);
11876       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11877       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11878       break;
11879
11880     case M_DMULO_I:
11881       dbl = 1;
11882     case M_MULO_I:
11883       imm = 1;
11884       goto do_mulo;
11885
11886     case M_DMULO:
11887       dbl = 1;
11888     case M_MULO:
11889     do_mulo:
11890       start_noreorder ();
11891       used_at = 1;
11892       if (imm)
11893         load_register (AT, &imm_expr, dbl);
11894       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
11895                    op[1], imm ? AT : op[2]);
11896       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11897       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
11898       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11899       if (mips_trap)
11900         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
11901       else
11902         {
11903           if (mips_opts.micromips)
11904             micromips_label_expr (&label_expr);
11905           else
11906             label_expr.X_add_number = 8;
11907           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
11908           macro_build (NULL, "nop", "");
11909           macro_build (NULL, "break", BRK_FMT, 6);
11910           if (mips_opts.micromips)
11911             micromips_add_label ();
11912         }
11913       end_noreorder ();
11914       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11915       break;
11916
11917     case M_DMULOU_I:
11918       dbl = 1;
11919     case M_MULOU_I:
11920       imm = 1;
11921       goto do_mulou;
11922
11923     case M_DMULOU:
11924       dbl = 1;
11925     case M_MULOU:
11926     do_mulou:
11927       start_noreorder ();
11928       used_at = 1;
11929       if (imm)
11930         load_register (AT, &imm_expr, dbl);
11931       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
11932                    op[1], imm ? AT : op[2]);
11933       macro_build (NULL, "mfhi", MFHL_FMT, AT);
11934       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11935       if (mips_trap)
11936         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
11937       else
11938         {
11939           if (mips_opts.micromips)
11940             micromips_label_expr (&label_expr);
11941           else
11942             label_expr.X_add_number = 8;
11943           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
11944           macro_build (NULL, "nop", "");
11945           macro_build (NULL, "break", BRK_FMT, 6);
11946           if (mips_opts.micromips)
11947             micromips_add_label ();
11948         }
11949       end_noreorder ();
11950       break;
11951
11952     case M_DROL:
11953       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
11954         {
11955           if (op[0] == op[1])
11956             {
11957               tempreg = AT;
11958               used_at = 1;
11959             }
11960           else
11961             tempreg = op[0];
11962           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
11963           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
11964           break;
11965         }
11966       used_at = 1;
11967       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
11968       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
11969       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
11970       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11971       break;
11972
11973     case M_ROL:
11974       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
11975         {
11976           if (op[0] == op[1])
11977             {
11978               tempreg = AT;
11979               used_at = 1;
11980             }
11981           else
11982             tempreg = op[0];
11983           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
11984           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
11985           break;
11986         }
11987       used_at = 1;
11988       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
11989       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
11990       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
11991       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
11992       break;
11993
11994     case M_DROL_I:
11995       {
11996         unsigned int rot;
11997         char *l;
11998         char *rr;
11999
12000         rot = imm_expr.X_add_number & 0x3f;
12001         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12002           {
12003             rot = (64 - rot) & 0x3f;
12004             if (rot >= 32)
12005               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12006             else
12007               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12008             break;
12009           }
12010         if (rot == 0)
12011           {
12012             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12013             break;
12014           }
12015         l = (rot < 0x20) ? "dsll" : "dsll32";
12016         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12017         rot &= 0x1f;
12018         used_at = 1;
12019         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12020         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12021         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12022       }
12023       break;
12024
12025     case M_ROL_I:
12026       {
12027         unsigned int rot;
12028
12029         rot = imm_expr.X_add_number & 0x1f;
12030         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12031           {
12032             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12033                          (32 - rot) & 0x1f);
12034             break;
12035           }
12036         if (rot == 0)
12037           {
12038             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12039             break;
12040           }
12041         used_at = 1;
12042         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12043         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12044         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12045       }
12046       break;
12047
12048     case M_DROR:
12049       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12050         {
12051           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12052           break;
12053         }
12054       used_at = 1;
12055       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12056       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12057       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12058       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12059       break;
12060
12061     case M_ROR:
12062       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12063         {
12064           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12065           break;
12066         }
12067       used_at = 1;
12068       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12069       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12070       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12071       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12072       break;
12073
12074     case M_DROR_I:
12075       {
12076         unsigned int rot;
12077         char *l;
12078         char *rr;
12079
12080         rot = imm_expr.X_add_number & 0x3f;
12081         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12082           {
12083             if (rot >= 32)
12084               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12085             else
12086               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12087             break;
12088           }
12089         if (rot == 0)
12090           {
12091             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12092             break;
12093           }
12094         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12095         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12096         rot &= 0x1f;
12097         used_at = 1;
12098         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12099         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12100         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12101       }
12102       break;
12103
12104     case M_ROR_I:
12105       {
12106         unsigned int rot;
12107
12108         rot = imm_expr.X_add_number & 0x1f;
12109         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12110           {
12111             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12112             break;
12113           }
12114         if (rot == 0)
12115           {
12116             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12117             break;
12118           }
12119         used_at = 1;
12120         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12121         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12122         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12123       }
12124       break;
12125
12126     case M_SEQ:
12127       if (op[1] == 0)
12128         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12129       else if (op[2] == 0)
12130         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12131       else
12132         {
12133           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12134           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12135         }
12136       break;
12137
12138     case M_SEQ_I:
12139       if (imm_expr.X_add_number == 0)
12140         {
12141           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12142           break;
12143         }
12144       if (op[1] == 0)
12145         {
12146           as_warn (_("instruction %s: result is always false"),
12147                    ip->insn_mo->name);
12148           move_register (op[0], 0);
12149           break;
12150         }
12151       if (CPU_HAS_SEQ (mips_opts.arch)
12152           && -512 <= imm_expr.X_add_number
12153           && imm_expr.X_add_number < 512)
12154         {
12155           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12156                        (int) imm_expr.X_add_number);
12157           break;
12158         }
12159       if (imm_expr.X_add_number >= 0
12160           && imm_expr.X_add_number < 0x10000)
12161         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12162       else if (imm_expr.X_add_number > -0x8000
12163                && imm_expr.X_add_number < 0)
12164         {
12165           imm_expr.X_add_number = -imm_expr.X_add_number;
12166           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12167                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12168         }
12169       else if (CPU_HAS_SEQ (mips_opts.arch))
12170         {
12171           used_at = 1;
12172           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12173           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12174           break;
12175         }
12176       else
12177         {
12178           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12179           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12180           used_at = 1;
12181         }
12182       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12183       break;
12184
12185     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12186       s = "slt";
12187       goto sge;
12188     case M_SGEU:
12189       s = "sltu";
12190     sge:
12191       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12192       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12193       break;
12194
12195     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12196     case M_SGEU_I:
12197       if (imm_expr.X_add_number >= -0x8000
12198           && imm_expr.X_add_number < 0x8000)
12199         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12200                      op[0], op[1], BFD_RELOC_LO16);
12201       else
12202         {
12203           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12204           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12205                        op[0], op[1], AT);
12206           used_at = 1;
12207         }
12208       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12209       break;
12210
12211     case M_SGT:         /* X > Y  <==>  Y < X */
12212       s = "slt";
12213       goto sgt;
12214     case M_SGTU:
12215       s = "sltu";
12216     sgt:
12217       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12218       break;
12219
12220     case M_SGT_I:       /* X > I  <==>  I < X */
12221       s = "slt";
12222       goto sgti;
12223     case M_SGTU_I:
12224       s = "sltu";
12225     sgti:
12226       used_at = 1;
12227       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12228       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12229       break;
12230
12231     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12232       s = "slt";
12233       goto sle;
12234     case M_SLEU:
12235       s = "sltu";
12236     sle:
12237       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12238       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12239       break;
12240
12241     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12242       s = "slt";
12243       goto slei;
12244     case M_SLEU_I:
12245       s = "sltu";
12246     slei:
12247       used_at = 1;
12248       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12249       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12250       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12251       break;
12252
12253     case M_SLT_I:
12254       if (imm_expr.X_add_number >= -0x8000
12255           && imm_expr.X_add_number < 0x8000)
12256         {
12257           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12258                        BFD_RELOC_LO16);
12259           break;
12260         }
12261       used_at = 1;
12262       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12263       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12264       break;
12265
12266     case M_SLTU_I:
12267       if (imm_expr.X_add_number >= -0x8000
12268           && imm_expr.X_add_number < 0x8000)
12269         {
12270           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12271                        BFD_RELOC_LO16);
12272           break;
12273         }
12274       used_at = 1;
12275       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12276       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12277       break;
12278
12279     case M_SNE:
12280       if (op[1] == 0)
12281         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12282       else if (op[2] == 0)
12283         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12284       else
12285         {
12286           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12287           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12288         }
12289       break;
12290
12291     case M_SNE_I:
12292       if (imm_expr.X_add_number == 0)
12293         {
12294           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12295           break;
12296         }
12297       if (op[1] == 0)
12298         {
12299           as_warn (_("instruction %s: result is always true"),
12300                    ip->insn_mo->name);
12301           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12302                        op[0], 0, BFD_RELOC_LO16);
12303           break;
12304         }
12305       if (CPU_HAS_SEQ (mips_opts.arch)
12306           && -512 <= imm_expr.X_add_number
12307           && imm_expr.X_add_number < 512)
12308         {
12309           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12310                        (int) imm_expr.X_add_number);
12311           break;
12312         }
12313       if (imm_expr.X_add_number >= 0
12314           && imm_expr.X_add_number < 0x10000)
12315         {
12316           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12317                        BFD_RELOC_LO16);
12318         }
12319       else if (imm_expr.X_add_number > -0x8000
12320                && imm_expr.X_add_number < 0)
12321         {
12322           imm_expr.X_add_number = -imm_expr.X_add_number;
12323           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12324                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12325         }
12326       else if (CPU_HAS_SEQ (mips_opts.arch))
12327         {
12328           used_at = 1;
12329           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12330           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12331           break;
12332         }
12333       else
12334         {
12335           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12336           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12337           used_at = 1;
12338         }
12339       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12340       break;
12341
12342     case M_SUB_I:
12343       s = "addi";
12344       s2 = "sub";
12345       goto do_subi;
12346     case M_SUBU_I:
12347       s = "addiu";
12348       s2 = "subu";
12349       goto do_subi;
12350     case M_DSUB_I:
12351       dbl = 1;
12352       s = "daddi";
12353       s2 = "dsub";
12354       if (!mips_opts.micromips)
12355         goto do_subi;
12356       if (imm_expr.X_add_number > -0x200
12357           && imm_expr.X_add_number <= 0x200)
12358         {
12359           macro_build (NULL, s, "t,r,.", op[0], op[1],
12360                        (int) -imm_expr.X_add_number);
12361           break;
12362         }
12363       goto do_subi_i;
12364     case M_DSUBU_I:
12365       dbl = 1;
12366       s = "daddiu";
12367       s2 = "dsubu";
12368     do_subi:
12369       if (imm_expr.X_add_number > -0x8000
12370           && imm_expr.X_add_number <= 0x8000)
12371         {
12372           imm_expr.X_add_number = -imm_expr.X_add_number;
12373           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12374           break;
12375         }
12376     do_subi_i:
12377       used_at = 1;
12378       load_register (AT, &imm_expr, dbl);
12379       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12380       break;
12381
12382     case M_TEQ_I:
12383       s = "teq";
12384       goto trap;
12385     case M_TGE_I:
12386       s = "tge";
12387       goto trap;
12388     case M_TGEU_I:
12389       s = "tgeu";
12390       goto trap;
12391     case M_TLT_I:
12392       s = "tlt";
12393       goto trap;
12394     case M_TLTU_I:
12395       s = "tltu";
12396       goto trap;
12397     case M_TNE_I:
12398       s = "tne";
12399     trap:
12400       used_at = 1;
12401       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12402       macro_build (NULL, s, "s,t", op[0], AT);
12403       break;
12404
12405     case M_TRUNCWS:
12406     case M_TRUNCWD:
12407       gas_assert (!mips_opts.micromips);
12408       gas_assert (mips_opts.isa == ISA_MIPS1);
12409       used_at = 1;
12410
12411       /*
12412        * Is the double cfc1 instruction a bug in the mips assembler;
12413        * or is there a reason for it?
12414        */
12415       start_noreorder ();
12416       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12417       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12418       macro_build (NULL, "nop", "");
12419       expr1.X_add_number = 3;
12420       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12421       expr1.X_add_number = 2;
12422       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12423       macro_build (NULL, "ctc1", "t,G", AT, RA);
12424       macro_build (NULL, "nop", "");
12425       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12426                    op[0], op[1]);
12427       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12428       macro_build (NULL, "nop", "");
12429       end_noreorder ();
12430       break;
12431
12432     case M_ULH_AB:
12433       s = "lb";
12434       s2 = "lbu";
12435       off = 1;
12436       goto uld_st;
12437     case M_ULHU_AB:
12438       s = "lbu";
12439       s2 = "lbu";
12440       off = 1;
12441       goto uld_st;
12442     case M_ULW_AB:
12443       s = "lwl";
12444       s2 = "lwr";
12445       offbits = (mips_opts.micromips ? 12 : 16);
12446       off = 3;
12447       goto uld_st;
12448     case M_ULD_AB:
12449       s = "ldl";
12450       s2 = "ldr";
12451       offbits = (mips_opts.micromips ? 12 : 16);
12452       off = 7;
12453       goto uld_st;
12454     case M_USH_AB:
12455       s = "sb";
12456       s2 = "sb";
12457       off = 1;
12458       ust = 1;
12459       goto uld_st;
12460     case M_USW_AB:
12461       s = "swl";
12462       s2 = "swr";
12463       offbits = (mips_opts.micromips ? 12 : 16);
12464       off = 3;
12465       ust = 1;
12466       goto uld_st;
12467     case M_USD_AB:
12468       s = "sdl";
12469       s2 = "sdr";
12470       offbits = (mips_opts.micromips ? 12 : 16);
12471       off = 7;
12472       ust = 1;
12473
12474     uld_st:
12475       breg = op[2];
12476       large_offset = !small_offset_p (off, align, offbits);
12477       ep = &offset_expr;
12478       expr1.X_add_number = 0;
12479       if (large_offset)
12480         {
12481           used_at = 1;
12482           tempreg = AT;
12483           if (small_offset_p (0, align, 16))
12484             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12485                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12486           else
12487             {
12488               load_address (tempreg, ep, &used_at);
12489               if (breg != 0)
12490                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12491                              tempreg, tempreg, breg);
12492             }
12493           offset_reloc[0] = BFD_RELOC_LO16;
12494           offset_reloc[1] = BFD_RELOC_UNUSED;
12495           offset_reloc[2] = BFD_RELOC_UNUSED;
12496           breg = tempreg;
12497           tempreg = op[0];
12498           ep = &expr1;
12499         }
12500       else if (!ust && op[0] == breg)
12501         {
12502           used_at = 1;
12503           tempreg = AT;
12504         }
12505       else
12506         tempreg = op[0];
12507
12508       if (off == 1)
12509         goto ulh_sh;
12510
12511       if (!target_big_endian)
12512         ep->X_add_number += off;
12513       if (offbits == 12)
12514         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12515       else
12516         macro_build (ep, s, "t,o(b)", tempreg, -1,
12517                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12518
12519       if (!target_big_endian)
12520         ep->X_add_number -= off;
12521       else
12522         ep->X_add_number += off;
12523       if (offbits == 12)
12524         macro_build (NULL, s2, "t,~(b)",
12525                      tempreg, (int) ep->X_add_number, breg);
12526       else
12527         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12528                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12529
12530       /* If necessary, move the result in tempreg to the final destination.  */
12531       if (!ust && op[0] != tempreg)
12532         {
12533           /* Protect second load's delay slot.  */
12534           load_delay_nop ();
12535           move_register (op[0], tempreg);
12536         }
12537       break;
12538
12539     ulh_sh:
12540       used_at = 1;
12541       if (target_big_endian == ust)
12542         ep->X_add_number += off;
12543       tempreg = ust || large_offset ? op[0] : AT;
12544       macro_build (ep, s, "t,o(b)", tempreg, -1,
12545                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12546
12547       /* For halfword transfers we need a temporary register to shuffle
12548          bytes.  Unfortunately for M_USH_A we have none available before
12549          the next store as AT holds the base address.  We deal with this
12550          case by clobbering TREG and then restoring it as with ULH.  */
12551       tempreg = ust == large_offset ? op[0] : AT;
12552       if (ust)
12553         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12554
12555       if (target_big_endian == ust)
12556         ep->X_add_number -= off;
12557       else
12558         ep->X_add_number += off;
12559       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12560                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12561
12562       /* For M_USH_A re-retrieve the LSB.  */
12563       if (ust && large_offset)
12564         {
12565           if (target_big_endian)
12566             ep->X_add_number += off;
12567           else
12568             ep->X_add_number -= off;
12569           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12570                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12571         }
12572       /* For ULH and M_USH_A OR the LSB in.  */
12573       if (!ust || large_offset)
12574         {
12575           tempreg = !large_offset ? AT : op[0];
12576           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12577           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12578         }
12579       break;
12580
12581     default:
12582       /* FIXME: Check if this is one of the itbl macros, since they
12583          are added dynamically.  */
12584       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12585       break;
12586     }
12587   if (!mips_opts.at && used_at)
12588     as_bad (_("macro used $at after \".set noat\""));
12589 }
12590
12591 /* Implement macros in mips16 mode.  */
12592
12593 static void
12594 mips16_macro (struct mips_cl_insn *ip)
12595 {
12596   const struct mips_operand_array *operands;
12597   int mask;
12598   int tmp;
12599   expressionS expr1;
12600   int dbl;
12601   const char *s, *s2, *s3;
12602   unsigned int op[MAX_OPERANDS];
12603   unsigned int i;
12604
12605   mask = ip->insn_mo->mask;
12606
12607   operands = insn_operands (ip);
12608   for (i = 0; i < MAX_OPERANDS; i++)
12609     if (operands->operand[i])
12610       op[i] = insn_extract_operand (ip, operands->operand[i]);
12611     else
12612       op[i] = -1;
12613
12614   expr1.X_op = O_constant;
12615   expr1.X_op_symbol = NULL;
12616   expr1.X_add_symbol = NULL;
12617   expr1.X_add_number = 1;
12618
12619   dbl = 0;
12620
12621   switch (mask)
12622     {
12623     default:
12624       abort ();
12625
12626     case M_DDIV_3:
12627       dbl = 1;
12628     case M_DIV_3:
12629       s = "mflo";
12630       goto do_div3;
12631     case M_DREM_3:
12632       dbl = 1;
12633     case M_REM_3:
12634       s = "mfhi";
12635     do_div3:
12636       start_noreorder ();
12637       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12638       expr1.X_add_number = 2;
12639       macro_build (&expr1, "bnez", "x,p", op[2]);
12640       macro_build (NULL, "break", "6", 7);
12641
12642       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12643          since that causes an overflow.  We should do that as well,
12644          but I don't see how to do the comparisons without a temporary
12645          register.  */
12646       end_noreorder ();
12647       macro_build (NULL, s, "x", op[0]);
12648       break;
12649
12650     case M_DIVU_3:
12651       s = "divu";
12652       s2 = "mflo";
12653       goto do_divu3;
12654     case M_REMU_3:
12655       s = "divu";
12656       s2 = "mfhi";
12657       goto do_divu3;
12658     case M_DDIVU_3:
12659       s = "ddivu";
12660       s2 = "mflo";
12661       goto do_divu3;
12662     case M_DREMU_3:
12663       s = "ddivu";
12664       s2 = "mfhi";
12665     do_divu3:
12666       start_noreorder ();
12667       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12668       expr1.X_add_number = 2;
12669       macro_build (&expr1, "bnez", "x,p", op[2]);
12670       macro_build (NULL, "break", "6", 7);
12671       end_noreorder ();
12672       macro_build (NULL, s2, "x", op[0]);
12673       break;
12674
12675     case M_DMUL:
12676       dbl = 1;
12677     case M_MUL:
12678       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12679       macro_build (NULL, "mflo", "x", op[0]);
12680       break;
12681
12682     case M_DSUBU_I:
12683       dbl = 1;
12684       goto do_subu;
12685     case M_SUBU_I:
12686     do_subu:
12687       imm_expr.X_add_number = -imm_expr.X_add_number;
12688       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12689       break;
12690
12691     case M_SUBU_I_2:
12692       imm_expr.X_add_number = -imm_expr.X_add_number;
12693       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12694       break;
12695
12696     case M_DSUBU_I_2:
12697       imm_expr.X_add_number = -imm_expr.X_add_number;
12698       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12699       break;
12700
12701     case M_BEQ:
12702       s = "cmp";
12703       s2 = "bteqz";
12704       goto do_branch;
12705     case M_BNE:
12706       s = "cmp";
12707       s2 = "btnez";
12708       goto do_branch;
12709     case M_BLT:
12710       s = "slt";
12711       s2 = "btnez";
12712       goto do_branch;
12713     case M_BLTU:
12714       s = "sltu";
12715       s2 = "btnez";
12716       goto do_branch;
12717     case M_BLE:
12718       s = "slt";
12719       s2 = "bteqz";
12720       goto do_reverse_branch;
12721     case M_BLEU:
12722       s = "sltu";
12723       s2 = "bteqz";
12724       goto do_reverse_branch;
12725     case M_BGE:
12726       s = "slt";
12727       s2 = "bteqz";
12728       goto do_branch;
12729     case M_BGEU:
12730       s = "sltu";
12731       s2 = "bteqz";
12732       goto do_branch;
12733     case M_BGT:
12734       s = "slt";
12735       s2 = "btnez";
12736       goto do_reverse_branch;
12737     case M_BGTU:
12738       s = "sltu";
12739       s2 = "btnez";
12740
12741     do_reverse_branch:
12742       tmp = op[1];
12743       op[1] = op[0];
12744       op[0] = tmp;
12745
12746     do_branch:
12747       macro_build (NULL, s, "x,y", op[0], op[1]);
12748       macro_build (&offset_expr, s2, "p");
12749       break;
12750
12751     case M_BEQ_I:
12752       s = "cmpi";
12753       s2 = "bteqz";
12754       s3 = "x,U";
12755       goto do_branch_i;
12756     case M_BNE_I:
12757       s = "cmpi";
12758       s2 = "btnez";
12759       s3 = "x,U";
12760       goto do_branch_i;
12761     case M_BLT_I:
12762       s = "slti";
12763       s2 = "btnez";
12764       s3 = "x,8";
12765       goto do_branch_i;
12766     case M_BLTU_I:
12767       s = "sltiu";
12768       s2 = "btnez";
12769       s3 = "x,8";
12770       goto do_branch_i;
12771     case M_BLE_I:
12772       s = "slti";
12773       s2 = "btnez";
12774       s3 = "x,8";
12775       goto do_addone_branch_i;
12776     case M_BLEU_I:
12777       s = "sltiu";
12778       s2 = "btnez";
12779       s3 = "x,8";
12780       goto do_addone_branch_i;
12781     case M_BGE_I:
12782       s = "slti";
12783       s2 = "bteqz";
12784       s3 = "x,8";
12785       goto do_branch_i;
12786     case M_BGEU_I:
12787       s = "sltiu";
12788       s2 = "bteqz";
12789       s3 = "x,8";
12790       goto do_branch_i;
12791     case M_BGT_I:
12792       s = "slti";
12793       s2 = "bteqz";
12794       s3 = "x,8";
12795       goto do_addone_branch_i;
12796     case M_BGTU_I:
12797       s = "sltiu";
12798       s2 = "bteqz";
12799       s3 = "x,8";
12800
12801     do_addone_branch_i:
12802       ++imm_expr.X_add_number;
12803
12804     do_branch_i:
12805       macro_build (&imm_expr, s, s3, op[0]);
12806       macro_build (&offset_expr, s2, "p");
12807       break;
12808
12809     case M_ABS:
12810       expr1.X_add_number = 0;
12811       macro_build (&expr1, "slti", "x,8", op[1]);
12812       if (op[0] != op[1])
12813         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12814       expr1.X_add_number = 2;
12815       macro_build (&expr1, "bteqz", "p");
12816       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12817       break;
12818     }
12819 }
12820
12821 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12822    opcode bits in *OPCODE_EXTRA.  */
12823
12824 static struct mips_opcode *
12825 mips_lookup_insn (struct hash_control *hash, const char *start,
12826                   ssize_t length, unsigned int *opcode_extra)
12827 {
12828   char *name, *dot, *p;
12829   unsigned int mask, suffix;
12830   ssize_t opend;
12831   struct mips_opcode *insn;
12832
12833   /* Make a copy of the instruction so that we can fiddle with it.  */
12834   name = alloca (length + 1);
12835   memcpy (name, start, length);
12836   name[length] = '\0';
12837
12838   /* Look up the instruction as-is.  */
12839   insn = (struct mips_opcode *) hash_find (hash, name);
12840   if (insn)
12841     return insn;
12842
12843   dot = strchr (name, '.');
12844   if (dot && dot[1])
12845     {
12846       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12847       p = mips_parse_vu0_channels (dot + 1, &mask);
12848       if (*p == 0 && mask != 0)
12849         {
12850           *dot = 0;
12851           insn = (struct mips_opcode *) hash_find (hash, name);
12852           *dot = '.';
12853           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12854             {
12855               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12856               return insn;
12857             }
12858         }
12859     }
12860
12861   if (mips_opts.micromips)
12862     {
12863       /* See if there's an instruction size override suffix,
12864          either `16' or `32', at the end of the mnemonic proper,
12865          that defines the operation, i.e. before the first `.'
12866          character if any.  Strip it and retry.  */
12867       opend = dot != NULL ? dot - name : length;
12868       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12869         suffix = 2;
12870       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12871         suffix = 4;
12872       else
12873         suffix = 0;
12874       if (suffix)
12875         {
12876           memcpy (name + opend - 2, name + opend, length - opend + 1);
12877           insn = (struct mips_opcode *) hash_find (hash, name);
12878           if (insn)
12879             {
12880               forced_insn_length = suffix;
12881               return insn;
12882             }
12883         }
12884     }
12885
12886   return NULL;
12887 }
12888
12889 /* Assemble an instruction into its binary format.  If the instruction
12890    is a macro, set imm_expr and offset_expr to the values associated
12891    with "I" and "A" operands respectively.  Otherwise store the value
12892    of the relocatable field (if any) in offset_expr.  In both cases
12893    set offset_reloc to the relocation operators applied to offset_expr.  */
12894
12895 static void
12896 mips_ip (char *str, struct mips_cl_insn *insn)
12897 {
12898   const struct mips_opcode *first, *past;
12899   struct hash_control *hash;
12900   char format;
12901   size_t end;
12902   struct mips_operand_token *tokens;
12903   unsigned int opcode_extra;
12904
12905   if (mips_opts.micromips)
12906     {
12907       hash = micromips_op_hash;
12908       past = &micromips_opcodes[bfd_micromips_num_opcodes];
12909     }
12910   else
12911     {
12912       hash = op_hash;
12913       past = &mips_opcodes[NUMOPCODES];
12914     }
12915   forced_insn_length = 0;
12916   opcode_extra = 0;
12917
12918   /* We first try to match an instruction up to a space or to the end.  */
12919   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
12920     continue;
12921
12922   first = mips_lookup_insn (hash, str, end, &opcode_extra);
12923   if (first == NULL)
12924     {
12925       set_insn_error (0, _("unrecognized opcode"));
12926       return;
12927     }
12928
12929   if (strcmp (first->name, "li.s") == 0)
12930     format = 'f';
12931   else if (strcmp (first->name, "li.d") == 0)
12932     format = 'd';
12933   else
12934     format = 0;
12935   tokens = mips_parse_arguments (str + end, format);
12936   if (!tokens)
12937     return;
12938
12939   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
12940       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
12941     set_insn_error (0, _("invalid operands"));
12942
12943   obstack_free (&mips_operand_tokens, tokens);
12944 }
12945
12946 /* As for mips_ip, but used when assembling MIPS16 code.
12947    Also set forced_insn_length to the resulting instruction size in
12948    bytes if the user explicitly requested a small or extended instruction.  */
12949
12950 static void
12951 mips16_ip (char *str, struct mips_cl_insn *insn)
12952 {
12953   char *end, *s, c;
12954   struct mips_opcode *first;
12955   struct mips_operand_token *tokens;
12956
12957   forced_insn_length = 0;
12958
12959   for (s = str; ISLOWER (*s); ++s)
12960     ;
12961   end = s;
12962   c = *end;
12963   switch (c)
12964     {
12965     case '\0':
12966       break;
12967
12968     case ' ':
12969       s++;
12970       break;
12971
12972     case '.':
12973       if (s[1] == 't' && s[2] == ' ')
12974         {
12975           forced_insn_length = 2;
12976           s += 3;
12977           break;
12978         }
12979       else if (s[1] == 'e' && s[2] == ' ')
12980         {
12981           forced_insn_length = 4;
12982           s += 3;
12983           break;
12984         }
12985       /* Fall through.  */
12986     default:
12987       set_insn_error (0, _("unrecognized opcode"));
12988       return;
12989     }
12990
12991   if (mips_opts.noautoextend && !forced_insn_length)
12992     forced_insn_length = 2;
12993
12994   *end = 0;
12995   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
12996   *end = c;
12997
12998   if (!first)
12999     {
13000       set_insn_error (0, _("unrecognized opcode"));
13001       return;
13002     }
13003
13004   tokens = mips_parse_arguments (s, 0);
13005   if (!tokens)
13006     return;
13007
13008   if (!match_mips16_insns (insn, first, tokens))
13009     set_insn_error (0, _("invalid operands"));
13010
13011   obstack_free (&mips_operand_tokens, tokens);
13012 }
13013
13014 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13015    NBITS is the number of significant bits in VAL.  */
13016
13017 static unsigned long
13018 mips16_immed_extend (offsetT val, unsigned int nbits)
13019 {
13020   int extval;
13021   if (nbits == 16)
13022     {
13023       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13024       val &= 0x1f;
13025     }
13026   else if (nbits == 15)
13027     {
13028       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13029       val &= 0xf;
13030     }
13031   else
13032     {
13033       extval = ((val & 0x1f) << 6) | (val & 0x20);
13034       val = 0;
13035     }
13036   return (extval << 16) | val;
13037 }
13038
13039 /* Like decode_mips16_operand, but require the operand to be defined and
13040    require it to be an integer.  */
13041
13042 static const struct mips_int_operand *
13043 mips16_immed_operand (int type, bfd_boolean extended_p)
13044 {
13045   const struct mips_operand *operand;
13046
13047   operand = decode_mips16_operand (type, extended_p);
13048   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13049     abort ();
13050   return (const struct mips_int_operand *) operand;
13051 }
13052
13053 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13054
13055 static bfd_boolean
13056 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13057                          bfd_reloc_code_real_type reloc, offsetT sval)
13058 {
13059   int min_val, max_val;
13060
13061   min_val = mips_int_operand_min (operand);
13062   max_val = mips_int_operand_max (operand);
13063   if (reloc != BFD_RELOC_UNUSED)
13064     {
13065       if (min_val < 0)
13066         sval = SEXT_16BIT (sval);
13067       else
13068         sval &= 0xffff;
13069     }
13070
13071   return (sval >= min_val
13072           && sval <= max_val
13073           && (sval & ((1 << operand->shift) - 1)) == 0);
13074 }
13075
13076 /* Install immediate value VAL into MIPS16 instruction *INSN,
13077    extending it if necessary.  The instruction in *INSN may
13078    already be extended.
13079
13080    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13081    if none.  In the former case, VAL is a 16-bit number with no
13082    defined signedness.
13083
13084    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13085    is the length that the user requested, or 0 if none.  */
13086
13087 static void
13088 mips16_immed (char *file, unsigned int line, int type,
13089               bfd_reloc_code_real_type reloc, offsetT val,
13090               unsigned int user_insn_length, unsigned long *insn)
13091 {
13092   const struct mips_int_operand *operand;
13093   unsigned int uval, length;
13094
13095   operand = mips16_immed_operand (type, FALSE);
13096   if (!mips16_immed_in_range_p (operand, reloc, val))
13097     {
13098       /* We need an extended instruction.  */
13099       if (user_insn_length == 2)
13100         as_bad_where (file, line, _("invalid unextended operand value"));
13101       else
13102         *insn |= MIPS16_EXTEND;
13103     }
13104   else if (user_insn_length == 4)
13105     {
13106       /* The operand doesn't force an unextended instruction to be extended.
13107          Warn if the user wanted an extended instruction anyway.  */
13108       *insn |= MIPS16_EXTEND;
13109       as_warn_where (file, line,
13110                      _("extended operand requested but not required"));
13111     }
13112
13113   length = mips16_opcode_length (*insn);
13114   if (length == 4)
13115     {
13116       operand = mips16_immed_operand (type, TRUE);
13117       if (!mips16_immed_in_range_p (operand, reloc, val))
13118         as_bad_where (file, line,
13119                       _("operand value out of range for instruction"));
13120     }
13121   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13122   if (length == 2)
13123     *insn = mips_insert_operand (&operand->root, *insn, uval);
13124   else
13125     *insn |= mips16_immed_extend (uval, operand->root.size);
13126 }
13127 \f
13128 struct percent_op_match
13129 {
13130   const char *str;
13131   bfd_reloc_code_real_type reloc;
13132 };
13133
13134 static const struct percent_op_match mips_percent_op[] =
13135 {
13136   {"%lo", BFD_RELOC_LO16},
13137   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13138   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13139   {"%call16", BFD_RELOC_MIPS_CALL16},
13140   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13141   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13142   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13143   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13144   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13145   {"%got", BFD_RELOC_MIPS_GOT16},
13146   {"%gp_rel", BFD_RELOC_GPREL16},
13147   {"%half", BFD_RELOC_16},
13148   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13149   {"%higher", BFD_RELOC_MIPS_HIGHER},
13150   {"%neg", BFD_RELOC_MIPS_SUB},
13151   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13152   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13153   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13154   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13155   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13156   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13157   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13158   {"%hi", BFD_RELOC_HI16_S}
13159 };
13160
13161 static const struct percent_op_match mips16_percent_op[] =
13162 {
13163   {"%lo", BFD_RELOC_MIPS16_LO16},
13164   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13165   {"%got", BFD_RELOC_MIPS16_GOT16},
13166   {"%call16", BFD_RELOC_MIPS16_CALL16},
13167   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13168   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13169   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13170   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13171   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13172   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13173   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13174   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13175 };
13176
13177
13178 /* Return true if *STR points to a relocation operator.  When returning true,
13179    move *STR over the operator and store its relocation code in *RELOC.
13180    Leave both *STR and *RELOC alone when returning false.  */
13181
13182 static bfd_boolean
13183 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13184 {
13185   const struct percent_op_match *percent_op;
13186   size_t limit, i;
13187
13188   if (mips_opts.mips16)
13189     {
13190       percent_op = mips16_percent_op;
13191       limit = ARRAY_SIZE (mips16_percent_op);
13192     }
13193   else
13194     {
13195       percent_op = mips_percent_op;
13196       limit = ARRAY_SIZE (mips_percent_op);
13197     }
13198
13199   for (i = 0; i < limit; i++)
13200     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13201       {
13202         int len = strlen (percent_op[i].str);
13203
13204         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13205           continue;
13206
13207         *str += strlen (percent_op[i].str);
13208         *reloc = percent_op[i].reloc;
13209
13210         /* Check whether the output BFD supports this relocation.
13211            If not, issue an error and fall back on something safe.  */
13212         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13213           {
13214             as_bad (_("relocation %s isn't supported by the current ABI"),
13215                     percent_op[i].str);
13216             *reloc = BFD_RELOC_UNUSED;
13217           }
13218         return TRUE;
13219       }
13220   return FALSE;
13221 }
13222
13223
13224 /* Parse string STR as a 16-bit relocatable operand.  Store the
13225    expression in *EP and the relocations in the array starting
13226    at RELOC.  Return the number of relocation operators used.
13227
13228    On exit, EXPR_END points to the first character after the expression.  */
13229
13230 static size_t
13231 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13232                        char *str)
13233 {
13234   bfd_reloc_code_real_type reversed_reloc[3];
13235   size_t reloc_index, i;
13236   int crux_depth, str_depth;
13237   char *crux;
13238
13239   /* Search for the start of the main expression, recoding relocations
13240      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13241      of the main expression and with CRUX_DEPTH containing the number
13242      of open brackets at that point.  */
13243   reloc_index = -1;
13244   str_depth = 0;
13245   do
13246     {
13247       reloc_index++;
13248       crux = str;
13249       crux_depth = str_depth;
13250
13251       /* Skip over whitespace and brackets, keeping count of the number
13252          of brackets.  */
13253       while (*str == ' ' || *str == '\t' || *str == '(')
13254         if (*str++ == '(')
13255           str_depth++;
13256     }
13257   while (*str == '%'
13258          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13259          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13260
13261   my_getExpression (ep, crux);
13262   str = expr_end;
13263
13264   /* Match every open bracket.  */
13265   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13266     if (*str++ == ')')
13267       crux_depth--;
13268
13269   if (crux_depth > 0)
13270     as_bad (_("unclosed '('"));
13271
13272   expr_end = str;
13273
13274   if (reloc_index != 0)
13275     {
13276       prev_reloc_op_frag = frag_now;
13277       for (i = 0; i < reloc_index; i++)
13278         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13279     }
13280
13281   return reloc_index;
13282 }
13283
13284 static void
13285 my_getExpression (expressionS *ep, char *str)
13286 {
13287   char *save_in;
13288
13289   save_in = input_line_pointer;
13290   input_line_pointer = str;
13291   expression (ep);
13292   expr_end = input_line_pointer;
13293   input_line_pointer = save_in;
13294 }
13295
13296 char *
13297 md_atof (int type, char *litP, int *sizeP)
13298 {
13299   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13300 }
13301
13302 void
13303 md_number_to_chars (char *buf, valueT val, int n)
13304 {
13305   if (target_big_endian)
13306     number_to_chars_bigendian (buf, val, n);
13307   else
13308     number_to_chars_littleendian (buf, val, n);
13309 }
13310 \f
13311 static int support_64bit_objects(void)
13312 {
13313   const char **list, **l;
13314   int yes;
13315
13316   list = bfd_target_list ();
13317   for (l = list; *l != NULL; l++)
13318     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13319         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13320       break;
13321   yes = (*l != NULL);
13322   free (list);
13323   return yes;
13324 }
13325
13326 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13327    NEW_VALUE.  Warn if another value was already specified.  Note:
13328    we have to defer parsing the -march and -mtune arguments in order
13329    to handle 'from-abi' correctly, since the ABI might be specified
13330    in a later argument.  */
13331
13332 static void
13333 mips_set_option_string (const char **string_ptr, const char *new_value)
13334 {
13335   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13336     as_warn (_("a different %s was already specified, is now %s"),
13337              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13338              new_value);
13339
13340   *string_ptr = new_value;
13341 }
13342
13343 int
13344 md_parse_option (int c, char *arg)
13345 {
13346   unsigned int i;
13347
13348   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13349     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13350       {
13351         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13352                                            c == mips_ases[i].option_on);
13353         return 1;
13354       }
13355
13356   switch (c)
13357     {
13358     case OPTION_CONSTRUCT_FLOATS:
13359       mips_disable_float_construction = 0;
13360       break;
13361
13362     case OPTION_NO_CONSTRUCT_FLOATS:
13363       mips_disable_float_construction = 1;
13364       break;
13365
13366     case OPTION_TRAP:
13367       mips_trap = 1;
13368       break;
13369
13370     case OPTION_BREAK:
13371       mips_trap = 0;
13372       break;
13373
13374     case OPTION_EB:
13375       target_big_endian = 1;
13376       break;
13377
13378     case OPTION_EL:
13379       target_big_endian = 0;
13380       break;
13381
13382     case 'O':
13383       if (arg == NULL)
13384         mips_optimize = 1;
13385       else if (arg[0] == '0')
13386         mips_optimize = 0;
13387       else if (arg[0] == '1')
13388         mips_optimize = 1;
13389       else
13390         mips_optimize = 2;
13391       break;
13392
13393     case 'g':
13394       if (arg == NULL)
13395         mips_debug = 2;
13396       else
13397         mips_debug = atoi (arg);
13398       break;
13399
13400     case OPTION_MIPS1:
13401       file_mips_isa = ISA_MIPS1;
13402       break;
13403
13404     case OPTION_MIPS2:
13405       file_mips_isa = ISA_MIPS2;
13406       break;
13407
13408     case OPTION_MIPS3:
13409       file_mips_isa = ISA_MIPS3;
13410       break;
13411
13412     case OPTION_MIPS4:
13413       file_mips_isa = ISA_MIPS4;
13414       break;
13415
13416     case OPTION_MIPS5:
13417       file_mips_isa = ISA_MIPS5;
13418       break;
13419
13420     case OPTION_MIPS32:
13421       file_mips_isa = ISA_MIPS32;
13422       break;
13423
13424     case OPTION_MIPS32R2:
13425       file_mips_isa = ISA_MIPS32R2;
13426       break;
13427
13428     case OPTION_MIPS64R2:
13429       file_mips_isa = ISA_MIPS64R2;
13430       break;
13431
13432     case OPTION_MIPS64:
13433       file_mips_isa = ISA_MIPS64;
13434       break;
13435
13436     case OPTION_MTUNE:
13437       mips_set_option_string (&mips_tune_string, arg);
13438       break;
13439
13440     case OPTION_MARCH:
13441       mips_set_option_string (&mips_arch_string, arg);
13442       break;
13443
13444     case OPTION_M4650:
13445       mips_set_option_string (&mips_arch_string, "4650");
13446       mips_set_option_string (&mips_tune_string, "4650");
13447       break;
13448
13449     case OPTION_NO_M4650:
13450       break;
13451
13452     case OPTION_M4010:
13453       mips_set_option_string (&mips_arch_string, "4010");
13454       mips_set_option_string (&mips_tune_string, "4010");
13455       break;
13456
13457     case OPTION_NO_M4010:
13458       break;
13459
13460     case OPTION_M4100:
13461       mips_set_option_string (&mips_arch_string, "4100");
13462       mips_set_option_string (&mips_tune_string, "4100");
13463       break;
13464
13465     case OPTION_NO_M4100:
13466       break;
13467
13468     case OPTION_M3900:
13469       mips_set_option_string (&mips_arch_string, "3900");
13470       mips_set_option_string (&mips_tune_string, "3900");
13471       break;
13472
13473     case OPTION_NO_M3900:
13474       break;
13475
13476     case OPTION_MICROMIPS:
13477       if (mips_opts.mips16 == 1)
13478         {
13479           as_bad (_("-mmicromips cannot be used with -mips16"));
13480           return 0;
13481         }
13482       mips_opts.micromips = 1;
13483       mips_no_prev_insn ();
13484       break;
13485
13486     case OPTION_NO_MICROMIPS:
13487       mips_opts.micromips = 0;
13488       mips_no_prev_insn ();
13489       break;
13490
13491     case OPTION_MIPS16:
13492       if (mips_opts.micromips == 1)
13493         {
13494           as_bad (_("-mips16 cannot be used with -micromips"));
13495           return 0;
13496         }
13497       mips_opts.mips16 = 1;
13498       mips_no_prev_insn ();
13499       break;
13500
13501     case OPTION_NO_MIPS16:
13502       mips_opts.mips16 = 0;
13503       mips_no_prev_insn ();
13504       break;
13505
13506     case OPTION_FIX_24K:
13507       mips_fix_24k = 1;
13508       break;
13509
13510     case OPTION_NO_FIX_24K:
13511       mips_fix_24k = 0;
13512       break;
13513
13514     case OPTION_FIX_LOONGSON2F_JUMP:
13515       mips_fix_loongson2f_jump = TRUE;
13516       break;
13517
13518     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13519       mips_fix_loongson2f_jump = FALSE;
13520       break;
13521
13522     case OPTION_FIX_LOONGSON2F_NOP:
13523       mips_fix_loongson2f_nop = TRUE;
13524       break;
13525
13526     case OPTION_NO_FIX_LOONGSON2F_NOP:
13527       mips_fix_loongson2f_nop = FALSE;
13528       break;
13529
13530     case OPTION_FIX_VR4120:
13531       mips_fix_vr4120 = 1;
13532       break;
13533
13534     case OPTION_NO_FIX_VR4120:
13535       mips_fix_vr4120 = 0;
13536       break;
13537
13538     case OPTION_FIX_VR4130:
13539       mips_fix_vr4130 = 1;
13540       break;
13541
13542     case OPTION_NO_FIX_VR4130:
13543       mips_fix_vr4130 = 0;
13544       break;
13545
13546     case OPTION_FIX_CN63XXP1:
13547       mips_fix_cn63xxp1 = TRUE;
13548       break;
13549
13550     case OPTION_NO_FIX_CN63XXP1:
13551       mips_fix_cn63xxp1 = FALSE;
13552       break;
13553
13554     case OPTION_RELAX_BRANCH:
13555       mips_relax_branch = 1;
13556       break;
13557
13558     case OPTION_NO_RELAX_BRANCH:
13559       mips_relax_branch = 0;
13560       break;
13561
13562     case OPTION_INSN32:
13563       mips_opts.insn32 = TRUE;
13564       break;
13565
13566     case OPTION_NO_INSN32:
13567       mips_opts.insn32 = FALSE;
13568       break;
13569
13570     case OPTION_MSHARED:
13571       mips_in_shared = TRUE;
13572       break;
13573
13574     case OPTION_MNO_SHARED:
13575       mips_in_shared = FALSE;
13576       break;
13577
13578     case OPTION_MSYM32:
13579       mips_opts.sym32 = TRUE;
13580       break;
13581
13582     case OPTION_MNO_SYM32:
13583       mips_opts.sym32 = FALSE;
13584       break;
13585
13586       /* When generating ELF code, we permit -KPIC and -call_shared to
13587          select SVR4_PIC, and -non_shared to select no PIC.  This is
13588          intended to be compatible with Irix 5.  */
13589     case OPTION_CALL_SHARED:
13590       mips_pic = SVR4_PIC;
13591       mips_abicalls = TRUE;
13592       break;
13593
13594     case OPTION_CALL_NONPIC:
13595       mips_pic = NO_PIC;
13596       mips_abicalls = TRUE;
13597       break;
13598
13599     case OPTION_NON_SHARED:
13600       mips_pic = NO_PIC;
13601       mips_abicalls = FALSE;
13602       break;
13603
13604       /* The -xgot option tells the assembler to use 32 bit offsets
13605          when accessing the got in SVR4_PIC mode.  It is for Irix
13606          compatibility.  */
13607     case OPTION_XGOT:
13608       mips_big_got = 1;
13609       break;
13610
13611     case 'G':
13612       g_switch_value = atoi (arg);
13613       g_switch_seen = 1;
13614       break;
13615
13616       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13617          and -mabi=64.  */
13618     case OPTION_32:
13619       mips_abi = O32_ABI;
13620       break;
13621
13622     case OPTION_N32:
13623       mips_abi = N32_ABI;
13624       break;
13625
13626     case OPTION_64:
13627       mips_abi = N64_ABI;
13628       if (!support_64bit_objects())
13629         as_fatal (_("no compiled in support for 64 bit object file format"));
13630       break;
13631
13632     case OPTION_GP32:
13633       file_mips_gp32 = 1;
13634       break;
13635
13636     case OPTION_GP64:
13637       file_mips_gp32 = 0;
13638       break;
13639
13640     case OPTION_FP32:
13641       file_mips_fp32 = 1;
13642       break;
13643
13644     case OPTION_FP64:
13645       file_mips_fp32 = 0;
13646       break;
13647
13648     case OPTION_SINGLE_FLOAT:
13649       file_mips_single_float = 1;
13650       break;
13651
13652     case OPTION_DOUBLE_FLOAT:
13653       file_mips_single_float = 0;
13654       break;
13655
13656     case OPTION_SOFT_FLOAT:
13657       file_mips_soft_float = 1;
13658       break;
13659
13660     case OPTION_HARD_FLOAT:
13661       file_mips_soft_float = 0;
13662       break;
13663
13664     case OPTION_MABI:
13665       if (strcmp (arg, "32") == 0)
13666         mips_abi = O32_ABI;
13667       else if (strcmp (arg, "o64") == 0)
13668         mips_abi = O64_ABI;
13669       else if (strcmp (arg, "n32") == 0)
13670         mips_abi = N32_ABI;
13671       else if (strcmp (arg, "64") == 0)
13672         {
13673           mips_abi = N64_ABI;
13674           if (! support_64bit_objects())
13675             as_fatal (_("no compiled in support for 64 bit object file "
13676                         "format"));
13677         }
13678       else if (strcmp (arg, "eabi") == 0)
13679         mips_abi = EABI_ABI;
13680       else
13681         {
13682           as_fatal (_("invalid abi -mabi=%s"), arg);
13683           return 0;
13684         }
13685       break;
13686
13687     case OPTION_M7000_HILO_FIX:
13688       mips_7000_hilo_fix = TRUE;
13689       break;
13690
13691     case OPTION_MNO_7000_HILO_FIX:
13692       mips_7000_hilo_fix = FALSE;
13693       break;
13694
13695     case OPTION_MDEBUG:
13696       mips_flag_mdebug = TRUE;
13697       break;
13698
13699     case OPTION_NO_MDEBUG:
13700       mips_flag_mdebug = FALSE;
13701       break;
13702
13703     case OPTION_PDR:
13704       mips_flag_pdr = TRUE;
13705       break;
13706
13707     case OPTION_NO_PDR:
13708       mips_flag_pdr = FALSE;
13709       break;
13710
13711     case OPTION_MVXWORKS_PIC:
13712       mips_pic = VXWORKS_PIC;
13713       break;
13714
13715     case OPTION_NAN:
13716       if (strcmp (arg, "2008") == 0)
13717         mips_flag_nan2008 = TRUE;
13718       else if (strcmp (arg, "legacy") == 0)
13719         mips_flag_nan2008 = FALSE;
13720       else
13721         {
13722           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
13723           return 0;
13724         }
13725       break;
13726
13727     default:
13728       return 0;
13729     }
13730
13731     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13732
13733   return 1;
13734 }
13735 \f
13736 /* Set up globals to generate code for the ISA or processor
13737    described by INFO.  */
13738
13739 static void
13740 mips_set_architecture (const struct mips_cpu_info *info)
13741 {
13742   if (info != 0)
13743     {
13744       file_mips_arch = info->cpu;
13745       mips_opts.arch = info->cpu;
13746       mips_opts.isa = info->isa;
13747     }
13748 }
13749
13750
13751 /* Likewise for tuning.  */
13752
13753 static void
13754 mips_set_tune (const struct mips_cpu_info *info)
13755 {
13756   if (info != 0)
13757     mips_tune = info->cpu;
13758 }
13759
13760
13761 void
13762 mips_after_parse_args (void)
13763 {
13764   const struct mips_cpu_info *arch_info = 0;
13765   const struct mips_cpu_info *tune_info = 0;
13766
13767   /* GP relative stuff not working for PE */
13768   if (strncmp (TARGET_OS, "pe", 2) == 0)
13769     {
13770       if (g_switch_seen && g_switch_value != 0)
13771         as_bad (_("-G not supported in this configuration"));
13772       g_switch_value = 0;
13773     }
13774
13775   if (mips_abi == NO_ABI)
13776     mips_abi = MIPS_DEFAULT_ABI;
13777
13778   /* The following code determines the architecture and register size.
13779      Similar code was added to GCC 3.3 (see override_options() in
13780      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13781      as much as possible.  */
13782
13783   if (mips_arch_string != 0)
13784     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13785
13786   if (file_mips_isa != ISA_UNKNOWN)
13787     {
13788       /* Handle -mipsN.  At this point, file_mips_isa contains the
13789          ISA level specified by -mipsN, while arch_info->isa contains
13790          the -march selection (if any).  */
13791       if (arch_info != 0)
13792         {
13793           /* -march takes precedence over -mipsN, since it is more descriptive.
13794              There's no harm in specifying both as long as the ISA levels
13795              are the same.  */
13796           if (file_mips_isa != arch_info->isa)
13797             as_bad (_("-%s conflicts with the other architecture options,"
13798                       " which imply -%s"),
13799                     mips_cpu_info_from_isa (file_mips_isa)->name,
13800                     mips_cpu_info_from_isa (arch_info->isa)->name);
13801         }
13802       else
13803         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13804     }
13805
13806   if (arch_info == 0)
13807     {
13808       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13809       gas_assert (arch_info);
13810     }
13811
13812   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13813     as_bad (_("-march=%s is not compatible with the selected ABI"),
13814             arch_info->name);
13815
13816   mips_set_architecture (arch_info);
13817
13818   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13819   if (mips_tune_string != 0)
13820     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13821
13822   if (tune_info == 0)
13823     mips_set_tune (arch_info);
13824   else
13825     mips_set_tune (tune_info);
13826
13827   if (file_mips_gp32 >= 0)
13828     {
13829       /* The user specified the size of the integer registers.  Make sure
13830          it agrees with the ABI and ISA.  */
13831       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13832         as_bad (_("-mgp64 used with a 32-bit processor"));
13833       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13834         as_bad (_("-mgp32 used with a 64-bit ABI"));
13835       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13836         as_bad (_("-mgp64 used with a 32-bit ABI"));
13837     }
13838   else
13839     {
13840       /* Infer the integer register size from the ABI and processor.
13841          Restrict ourselves to 32-bit registers if that's all the
13842          processor has, or if the ABI cannot handle 64-bit registers.  */
13843       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13844                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13845     }
13846
13847   switch (file_mips_fp32)
13848     {
13849     default:
13850     case -1:
13851       /* No user specified float register size.
13852          ??? GAS treats single-float processors as though they had 64-bit
13853          float registers (although it complains when double-precision
13854          instructions are used).  As things stand, saying they have 32-bit
13855          registers would lead to spurious "register must be even" messages.
13856          So here we assume float registers are never smaller than the
13857          integer ones.  */
13858       if (file_mips_gp32 == 0)
13859         /* 64-bit integer registers implies 64-bit float registers.  */
13860         file_mips_fp32 = 0;
13861       else if ((mips_opts.ase & FP64_ASES)
13862                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13863         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13864         file_mips_fp32 = 0;
13865       else
13866         /* 32-bit float registers.  */
13867         file_mips_fp32 = 1;
13868       break;
13869
13870     /* The user specified the size of the float registers.  Check if it
13871        agrees with the ABI and ISA.  */
13872     case 0:
13873       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13874         as_bad (_("-mfp64 used with a 32-bit fpu"));
13875       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13876                && !ISA_HAS_MXHC1 (mips_opts.isa))
13877         as_warn (_("-mfp64 used with a 32-bit ABI"));
13878       break;
13879     case 1:
13880       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13881         as_warn (_("-mfp32 used with a 64-bit ABI"));
13882       break;
13883     }
13884
13885   /* End of GCC-shared inference code.  */
13886
13887   /* This flag is set when we have a 64-bit capable CPU but use only
13888      32-bit wide registers.  Note that EABI does not use it.  */
13889   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
13890       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
13891           || mips_abi == O32_ABI))
13892     mips_32bitmode = 1;
13893
13894   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
13895     as_bad (_("trap exception not supported at ISA 1"));
13896
13897   /* If the selected architecture includes support for ASEs, enable
13898      generation of code for them.  */
13899   if (mips_opts.mips16 == -1)
13900     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
13901   if (mips_opts.micromips == -1)
13902     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
13903
13904   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
13905      ASEs from being selected implicitly.  */
13906   if (file_mips_fp32 == 1)
13907     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
13908
13909   /* If the user didn't explicitly select or deselect a particular ASE,
13910      use the default setting for the CPU.  */
13911   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
13912
13913   file_mips_isa = mips_opts.isa;
13914   file_ase = mips_opts.ase;
13915   mips_opts.gp32 = file_mips_gp32;
13916   mips_opts.fp32 = file_mips_fp32;
13917   mips_opts.soft_float = file_mips_soft_float;
13918   mips_opts.single_float = file_mips_single_float;
13919
13920   mips_check_isa_supports_ases ();
13921
13922   if (mips_flag_mdebug < 0)
13923     mips_flag_mdebug = 0;
13924 }
13925 \f
13926 void
13927 mips_init_after_args (void)
13928 {
13929   /* initialize opcodes */
13930   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
13931   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
13932 }
13933
13934 long
13935 md_pcrel_from (fixS *fixP)
13936 {
13937   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
13938   switch (fixP->fx_r_type)
13939     {
13940     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
13941     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
13942       /* Return the address of the delay slot.  */
13943       return addr + 2;
13944
13945     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
13946     case BFD_RELOC_MICROMIPS_JMP:
13947     case BFD_RELOC_16_PCREL_S2:
13948     case BFD_RELOC_MIPS_JMP:
13949       /* Return the address of the delay slot.  */
13950       return addr + 4;
13951
13952     case BFD_RELOC_32_PCREL:
13953       return addr;
13954
13955     default:
13956       /* We have no relocation type for PC relative MIPS16 instructions.  */
13957       if (fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != now_seg)
13958         as_bad_where (fixP->fx_file, fixP->fx_line,
13959                       _("PC relative MIPS16 instruction references"
13960                         " a different section"));
13961       return addr;
13962     }
13963 }
13964
13965 /* This is called before the symbol table is processed.  In order to
13966    work with gcc when using mips-tfile, we must keep all local labels.
13967    However, in other cases, we want to discard them.  If we were
13968    called with -g, but we didn't see any debugging information, it may
13969    mean that gcc is smuggling debugging information through to
13970    mips-tfile, in which case we must generate all local labels.  */
13971
13972 void
13973 mips_frob_file_before_adjust (void)
13974 {
13975 #ifndef NO_ECOFF_DEBUGGING
13976   if (ECOFF_DEBUGGING
13977       && mips_debug != 0
13978       && ! ecoff_debugging_seen)
13979     flag_keep_locals = 1;
13980 #endif
13981 }
13982
13983 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
13984    the corresponding LO16 reloc.  This is called before md_apply_fix and
13985    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
13986    relocation operators.
13987
13988    For our purposes, a %lo() expression matches a %got() or %hi()
13989    expression if:
13990
13991       (a) it refers to the same symbol; and
13992       (b) the offset applied in the %lo() expression is no lower than
13993           the offset applied in the %got() or %hi().
13994
13995    (b) allows us to cope with code like:
13996
13997         lui     $4,%hi(foo)
13998         lh      $4,%lo(foo+2)($4)
13999
14000    ...which is legal on RELA targets, and has a well-defined behaviour
14001    if the user knows that adding 2 to "foo" will not induce a carry to
14002    the high 16 bits.
14003
14004    When several %lo()s match a particular %got() or %hi(), we use the
14005    following rules to distinguish them:
14006
14007      (1) %lo()s with smaller offsets are a better match than %lo()s with
14008          higher offsets.
14009
14010      (2) %lo()s with no matching %got() or %hi() are better than those
14011          that already have a matching %got() or %hi().
14012
14013      (3) later %lo()s are better than earlier %lo()s.
14014
14015    These rules are applied in order.
14016
14017    (1) means, among other things, that %lo()s with identical offsets are
14018    chosen if they exist.
14019
14020    (2) means that we won't associate several high-part relocations with
14021    the same low-part relocation unless there's no alternative.  Having
14022    several high parts for the same low part is a GNU extension; this rule
14023    allows careful users to avoid it.
14024
14025    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14026    with the last high-part relocation being at the front of the list.
14027    It therefore makes sense to choose the last matching low-part
14028    relocation, all other things being equal.  It's also easier
14029    to code that way.  */
14030
14031 void
14032 mips_frob_file (void)
14033 {
14034   struct mips_hi_fixup *l;
14035   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14036
14037   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14038     {
14039       segment_info_type *seginfo;
14040       bfd_boolean matched_lo_p;
14041       fixS **hi_pos, **lo_pos, **pos;
14042
14043       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14044
14045       /* If a GOT16 relocation turns out to be against a global symbol,
14046          there isn't supposed to be a matching LO.  Ignore %gots against
14047          constants; we'll report an error for those later.  */
14048       if (got16_reloc_p (l->fixp->fx_r_type)
14049           && !(l->fixp->fx_addsy
14050                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14051         continue;
14052
14053       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14054       if (fixup_has_matching_lo_p (l->fixp))
14055         continue;
14056
14057       seginfo = seg_info (l->seg);
14058
14059       /* Set HI_POS to the position of this relocation in the chain.
14060          Set LO_POS to the position of the chosen low-part relocation.
14061          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14062          relocation that matches an immediately-preceding high-part
14063          relocation.  */
14064       hi_pos = NULL;
14065       lo_pos = NULL;
14066       matched_lo_p = FALSE;
14067       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14068
14069       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14070         {
14071           if (*pos == l->fixp)
14072             hi_pos = pos;
14073
14074           if ((*pos)->fx_r_type == looking_for_rtype
14075               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14076               && (*pos)->fx_offset >= l->fixp->fx_offset
14077               && (lo_pos == NULL
14078                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14079                   || (!matched_lo_p
14080                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14081             lo_pos = pos;
14082
14083           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14084                           && fixup_has_matching_lo_p (*pos));
14085         }
14086
14087       /* If we found a match, remove the high-part relocation from its
14088          current position and insert it before the low-part relocation.
14089          Make the offsets match so that fixup_has_matching_lo_p()
14090          will return true.
14091
14092          We don't warn about unmatched high-part relocations since some
14093          versions of gcc have been known to emit dead "lui ...%hi(...)"
14094          instructions.  */
14095       if (lo_pos != NULL)
14096         {
14097           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14098           if (l->fixp->fx_next != *lo_pos)
14099             {
14100               *hi_pos = l->fixp->fx_next;
14101               l->fixp->fx_next = *lo_pos;
14102               *lo_pos = l->fixp;
14103             }
14104         }
14105     }
14106 }
14107
14108 int
14109 mips_force_relocation (fixS *fixp)
14110 {
14111   if (generic_force_reloc (fixp))
14112     return 1;
14113
14114   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14115      so that the linker relaxation can update targets.  */
14116   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14117       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14118       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14119     return 1;
14120
14121   return 0;
14122 }
14123
14124 /* Read the instruction associated with RELOC from BUF.  */
14125
14126 static unsigned int
14127 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14128 {
14129   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14130     return read_compressed_insn (buf, 4);
14131   else
14132     return read_insn (buf);
14133 }
14134
14135 /* Write instruction INSN to BUF, given that it has been relocated
14136    by RELOC.  */
14137
14138 static void
14139 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14140                   unsigned long insn)
14141 {
14142   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14143     write_compressed_insn (buf, insn, 4);
14144   else
14145     write_insn (buf, insn);
14146 }
14147
14148 /* Apply a fixup to the object file.  */
14149
14150 void
14151 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14152 {
14153   char *buf;
14154   unsigned long insn;
14155   reloc_howto_type *howto;
14156
14157   /* We ignore generic BFD relocations we don't know about.  */
14158   howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14159   if (! howto)
14160     return;
14161
14162   gas_assert (fixP->fx_size == 2
14163               || fixP->fx_size == 4
14164               || fixP->fx_r_type == BFD_RELOC_16
14165               || fixP->fx_r_type == BFD_RELOC_64
14166               || fixP->fx_r_type == BFD_RELOC_CTOR
14167               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14168               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14169               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14170               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14171               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14172
14173   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14174
14175   gas_assert (!fixP->fx_pcrel || fixP->fx_r_type == BFD_RELOC_16_PCREL_S2
14176               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14177               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14178               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
14179               || fixP->fx_r_type == BFD_RELOC_32_PCREL);
14180
14181   /* Don't treat parts of a composite relocation as done.  There are two
14182      reasons for this:
14183
14184      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14185          should nevertheless be emitted if the first part is.
14186
14187      (2) In normal usage, composite relocations are never assembly-time
14188          constants.  The easiest way of dealing with the pathological
14189          exceptions is to generate a relocation against STN_UNDEF and
14190          leave everything up to the linker.  */
14191   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14192     fixP->fx_done = 1;
14193
14194   switch (fixP->fx_r_type)
14195     {
14196     case BFD_RELOC_MIPS_TLS_GD:
14197     case BFD_RELOC_MIPS_TLS_LDM:
14198     case BFD_RELOC_MIPS_TLS_DTPREL32:
14199     case BFD_RELOC_MIPS_TLS_DTPREL64:
14200     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14201     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14202     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14203     case BFD_RELOC_MIPS_TLS_TPREL32:
14204     case BFD_RELOC_MIPS_TLS_TPREL64:
14205     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14206     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14207     case BFD_RELOC_MICROMIPS_TLS_GD:
14208     case BFD_RELOC_MICROMIPS_TLS_LDM:
14209     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14210     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14211     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14212     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14213     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14214     case BFD_RELOC_MIPS16_TLS_GD:
14215     case BFD_RELOC_MIPS16_TLS_LDM:
14216     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14217     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14218     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14219     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14220     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14221       if (!fixP->fx_addsy)
14222         {
14223           as_bad_where (fixP->fx_file, fixP->fx_line,
14224                         _("TLS relocation against a constant"));
14225           break;
14226         }
14227       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14228       /* fall through */
14229
14230     case BFD_RELOC_MIPS_JMP:
14231     case BFD_RELOC_MIPS_SHIFT5:
14232     case BFD_RELOC_MIPS_SHIFT6:
14233     case BFD_RELOC_MIPS_GOT_DISP:
14234     case BFD_RELOC_MIPS_GOT_PAGE:
14235     case BFD_RELOC_MIPS_GOT_OFST:
14236     case BFD_RELOC_MIPS_SUB:
14237     case BFD_RELOC_MIPS_INSERT_A:
14238     case BFD_RELOC_MIPS_INSERT_B:
14239     case BFD_RELOC_MIPS_DELETE:
14240     case BFD_RELOC_MIPS_HIGHEST:
14241     case BFD_RELOC_MIPS_HIGHER:
14242     case BFD_RELOC_MIPS_SCN_DISP:
14243     case BFD_RELOC_MIPS_REL16:
14244     case BFD_RELOC_MIPS_RELGOT:
14245     case BFD_RELOC_MIPS_JALR:
14246     case BFD_RELOC_HI16:
14247     case BFD_RELOC_HI16_S:
14248     case BFD_RELOC_LO16:
14249     case BFD_RELOC_GPREL16:
14250     case BFD_RELOC_MIPS_LITERAL:
14251     case BFD_RELOC_MIPS_CALL16:
14252     case BFD_RELOC_MIPS_GOT16:
14253     case BFD_RELOC_GPREL32:
14254     case BFD_RELOC_MIPS_GOT_HI16:
14255     case BFD_RELOC_MIPS_GOT_LO16:
14256     case BFD_RELOC_MIPS_CALL_HI16:
14257     case BFD_RELOC_MIPS_CALL_LO16:
14258     case BFD_RELOC_MIPS16_GPREL:
14259     case BFD_RELOC_MIPS16_GOT16:
14260     case BFD_RELOC_MIPS16_CALL16:
14261     case BFD_RELOC_MIPS16_HI16:
14262     case BFD_RELOC_MIPS16_HI16_S:
14263     case BFD_RELOC_MIPS16_LO16:
14264     case BFD_RELOC_MIPS16_JMP:
14265     case BFD_RELOC_MICROMIPS_JMP:
14266     case BFD_RELOC_MICROMIPS_GOT_DISP:
14267     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14268     case BFD_RELOC_MICROMIPS_GOT_OFST:
14269     case BFD_RELOC_MICROMIPS_SUB:
14270     case BFD_RELOC_MICROMIPS_HIGHEST:
14271     case BFD_RELOC_MICROMIPS_HIGHER:
14272     case BFD_RELOC_MICROMIPS_SCN_DISP:
14273     case BFD_RELOC_MICROMIPS_JALR:
14274     case BFD_RELOC_MICROMIPS_HI16:
14275     case BFD_RELOC_MICROMIPS_HI16_S:
14276     case BFD_RELOC_MICROMIPS_LO16:
14277     case BFD_RELOC_MICROMIPS_GPREL16:
14278     case BFD_RELOC_MICROMIPS_LITERAL:
14279     case BFD_RELOC_MICROMIPS_CALL16:
14280     case BFD_RELOC_MICROMIPS_GOT16:
14281     case BFD_RELOC_MICROMIPS_GOT_HI16:
14282     case BFD_RELOC_MICROMIPS_GOT_LO16:
14283     case BFD_RELOC_MICROMIPS_CALL_HI16:
14284     case BFD_RELOC_MICROMIPS_CALL_LO16:
14285     case BFD_RELOC_MIPS_EH:
14286       if (fixP->fx_done)
14287         {
14288           offsetT value;
14289
14290           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14291             {
14292               insn = read_reloc_insn (buf, fixP->fx_r_type);
14293               if (mips16_reloc_p (fixP->fx_r_type))
14294                 insn |= mips16_immed_extend (value, 16);
14295               else
14296                 insn |= (value & 0xffff);
14297               write_reloc_insn (buf, fixP->fx_r_type, insn);
14298             }
14299           else
14300             as_bad_where (fixP->fx_file, fixP->fx_line,
14301                           _("unsupported constant in relocation"));
14302         }
14303       break;
14304
14305     case BFD_RELOC_64:
14306       /* This is handled like BFD_RELOC_32, but we output a sign
14307          extended value if we are only 32 bits.  */
14308       if (fixP->fx_done)
14309         {
14310           if (8 <= sizeof (valueT))
14311             md_number_to_chars (buf, *valP, 8);
14312           else
14313             {
14314               valueT hiv;
14315
14316               if ((*valP & 0x80000000) != 0)
14317                 hiv = 0xffffffff;
14318               else
14319                 hiv = 0;
14320               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14321               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14322             }
14323         }
14324       break;
14325
14326     case BFD_RELOC_RVA:
14327     case BFD_RELOC_32:
14328     case BFD_RELOC_32_PCREL:
14329     case BFD_RELOC_16:
14330       /* If we are deleting this reloc entry, we must fill in the
14331          value now.  This can happen if we have a .word which is not
14332          resolved when it appears but is later defined.  */
14333       if (fixP->fx_done)
14334         md_number_to_chars (buf, *valP, fixP->fx_size);
14335       break;
14336
14337     case BFD_RELOC_16_PCREL_S2:
14338       if ((*valP & 0x3) != 0)
14339         as_bad_where (fixP->fx_file, fixP->fx_line,
14340                       _("branch to misaligned address (%lx)"), (long) *valP);
14341
14342       /* We need to save the bits in the instruction since fixup_segment()
14343          might be deleting the relocation entry (i.e., a branch within
14344          the current segment).  */
14345       if (! fixP->fx_done)
14346         break;
14347
14348       /* Update old instruction data.  */
14349       insn = read_insn (buf);
14350
14351       if (*valP + 0x20000 <= 0x3ffff)
14352         {
14353           insn |= (*valP >> 2) & 0xffff;
14354           write_insn (buf, insn);
14355         }
14356       else if (mips_pic == NO_PIC
14357                && fixP->fx_done
14358                && fixP->fx_frag->fr_address >= text_section->vma
14359                && (fixP->fx_frag->fr_address
14360                    < text_section->vma + bfd_get_section_size (text_section))
14361                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14362                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14363                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14364         {
14365           /* The branch offset is too large.  If this is an
14366              unconditional branch, and we are not generating PIC code,
14367              we can convert it to an absolute jump instruction.  */
14368           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14369             insn = 0x0c000000;  /* jal */
14370           else
14371             insn = 0x08000000;  /* j */
14372           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14373           fixP->fx_done = 0;
14374           fixP->fx_addsy = section_symbol (text_section);
14375           *valP += md_pcrel_from (fixP);
14376           write_insn (buf, insn);
14377         }
14378       else
14379         {
14380           /* If we got here, we have branch-relaxation disabled,
14381              and there's nothing we can do to fix this instruction
14382              without turning it into a longer sequence.  */
14383           as_bad_where (fixP->fx_file, fixP->fx_line,
14384                         _("branch out of range"));
14385         }
14386       break;
14387
14388     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14389     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14390     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14391       /* We adjust the offset back to even.  */
14392       if ((*valP & 0x1) != 0)
14393         --(*valP);
14394
14395       if (! fixP->fx_done)
14396         break;
14397
14398       /* Should never visit here, because we keep the relocation.  */
14399       abort ();
14400       break;
14401
14402     case BFD_RELOC_VTABLE_INHERIT:
14403       fixP->fx_done = 0;
14404       if (fixP->fx_addsy
14405           && !S_IS_DEFINED (fixP->fx_addsy)
14406           && !S_IS_WEAK (fixP->fx_addsy))
14407         S_SET_WEAK (fixP->fx_addsy);
14408       break;
14409
14410     case BFD_RELOC_VTABLE_ENTRY:
14411       fixP->fx_done = 0;
14412       break;
14413
14414     default:
14415       abort ();
14416     }
14417
14418   /* Remember value for tc_gen_reloc.  */
14419   fixP->fx_addnumber = *valP;
14420 }
14421
14422 static symbolS *
14423 get_symbol (void)
14424 {
14425   int c;
14426   char *name;
14427   symbolS *p;
14428
14429   name = input_line_pointer;
14430   c = get_symbol_end ();
14431   p = (symbolS *) symbol_find_or_make (name);
14432   *input_line_pointer = c;
14433   return p;
14434 }
14435
14436 /* Align the current frag to a given power of two.  If a particular
14437    fill byte should be used, FILL points to an integer that contains
14438    that byte, otherwise FILL is null.
14439
14440    This function used to have the comment:
14441
14442       The MIPS assembler also automatically adjusts any preceding label.
14443
14444    The implementation therefore applied the adjustment to a maximum of
14445    one label.  However, other label adjustments are applied to batches
14446    of labels, and adjusting just one caused problems when new labels
14447    were added for the sake of debugging or unwind information.
14448    We therefore adjust all preceding labels (given as LABELS) instead.  */
14449
14450 static void
14451 mips_align (int to, int *fill, struct insn_label_list *labels)
14452 {
14453   mips_emit_delays ();
14454   mips_record_compressed_mode ();
14455   if (fill == NULL && subseg_text_p (now_seg))
14456     frag_align_code (to, 0);
14457   else
14458     frag_align (to, fill ? *fill : 0, 0);
14459   record_alignment (now_seg, to);
14460   mips_move_labels (labels, FALSE);
14461 }
14462
14463 /* Align to a given power of two.  .align 0 turns off the automatic
14464    alignment used by the data creating pseudo-ops.  */
14465
14466 static void
14467 s_align (int x ATTRIBUTE_UNUSED)
14468 {
14469   int temp, fill_value, *fill_ptr;
14470   long max_alignment = 28;
14471
14472   /* o Note that the assembler pulls down any immediately preceding label
14473        to the aligned address.
14474      o It's not documented but auto alignment is reinstated by
14475        a .align pseudo instruction.
14476      o Note also that after auto alignment is turned off the mips assembler
14477        issues an error on attempt to assemble an improperly aligned data item.
14478        We don't.  */
14479
14480   temp = get_absolute_expression ();
14481   if (temp > max_alignment)
14482     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14483   else if (temp < 0)
14484     {
14485       as_warn (_("alignment negative, 0 assumed"));
14486       temp = 0;
14487     }
14488   if (*input_line_pointer == ',')
14489     {
14490       ++input_line_pointer;
14491       fill_value = get_absolute_expression ();
14492       fill_ptr = &fill_value;
14493     }
14494   else
14495     fill_ptr = 0;
14496   if (temp)
14497     {
14498       segment_info_type *si = seg_info (now_seg);
14499       struct insn_label_list *l = si->label_list;
14500       /* Auto alignment should be switched on by next section change.  */
14501       auto_align = 1;
14502       mips_align (temp, fill_ptr, l);
14503     }
14504   else
14505     {
14506       auto_align = 0;
14507     }
14508
14509   demand_empty_rest_of_line ();
14510 }
14511
14512 static void
14513 s_change_sec (int sec)
14514 {
14515   segT seg;
14516
14517   /* The ELF backend needs to know that we are changing sections, so
14518      that .previous works correctly.  We could do something like check
14519      for an obj_section_change_hook macro, but that might be confusing
14520      as it would not be appropriate to use it in the section changing
14521      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14522      This should be cleaner, somehow.  */
14523   obj_elf_section_change_hook ();
14524
14525   mips_emit_delays ();
14526
14527   switch (sec)
14528     {
14529     case 't':
14530       s_text (0);
14531       break;
14532     case 'd':
14533       s_data (0);
14534       break;
14535     case 'b':
14536       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14537       demand_empty_rest_of_line ();
14538       break;
14539
14540     case 'r':
14541       seg = subseg_new (RDATA_SECTION_NAME,
14542                         (subsegT) get_absolute_expression ());
14543       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14544                                               | SEC_READONLY | SEC_RELOC
14545                                               | SEC_DATA));
14546       if (strncmp (TARGET_OS, "elf", 3) != 0)
14547         record_alignment (seg, 4);
14548       demand_empty_rest_of_line ();
14549       break;
14550
14551     case 's':
14552       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14553       bfd_set_section_flags (stdoutput, seg,
14554                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14555       if (strncmp (TARGET_OS, "elf", 3) != 0)
14556         record_alignment (seg, 4);
14557       demand_empty_rest_of_line ();
14558       break;
14559
14560     case 'B':
14561       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14562       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14563       if (strncmp (TARGET_OS, "elf", 3) != 0)
14564         record_alignment (seg, 4);
14565       demand_empty_rest_of_line ();
14566       break;
14567     }
14568
14569   auto_align = 1;
14570 }
14571
14572 void
14573 s_change_section (int ignore ATTRIBUTE_UNUSED)
14574 {
14575   char *section_name;
14576   char c;
14577   char next_c = 0;
14578   int section_type;
14579   int section_flag;
14580   int section_entry_size;
14581   int section_alignment;
14582
14583   section_name = input_line_pointer;
14584   c = get_symbol_end ();
14585   if (c)
14586     next_c = *(input_line_pointer + 1);
14587
14588   /* Do we have .section Name<,"flags">?  */
14589   if (c != ',' || (c == ',' && next_c == '"'))
14590     {
14591       /* just after name is now '\0'.  */
14592       *input_line_pointer = c;
14593       input_line_pointer = section_name;
14594       obj_elf_section (ignore);
14595       return;
14596     }
14597   input_line_pointer++;
14598
14599   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14600   if (c == ',')
14601     section_type = get_absolute_expression ();
14602   else
14603     section_type = 0;
14604   if (*input_line_pointer++ == ',')
14605     section_flag = get_absolute_expression ();
14606   else
14607     section_flag = 0;
14608   if (*input_line_pointer++ == ',')
14609     section_entry_size = get_absolute_expression ();
14610   else
14611     section_entry_size = 0;
14612   if (*input_line_pointer++ == ',')
14613     section_alignment = get_absolute_expression ();
14614   else
14615     section_alignment = 0;
14616   /* FIXME: really ignore?  */
14617   (void) section_alignment;
14618
14619   section_name = xstrdup (section_name);
14620
14621   /* When using the generic form of .section (as implemented by obj-elf.c),
14622      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14623      traditionally had to fall back on the more common @progbits instead.
14624
14625      There's nothing really harmful in this, since bfd will correct
14626      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14627      means that, for backwards compatibility, the special_section entries
14628      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14629
14630      Even so, we shouldn't force users of the MIPS .section syntax to
14631      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14632      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14633      generic type-checking code.  */
14634   if (section_type == SHT_MIPS_DWARF)
14635     section_type = SHT_PROGBITS;
14636
14637   obj_elf_change_section (section_name, section_type, section_flag,
14638                           section_entry_size, 0, 0, 0);
14639
14640   if (now_seg->name != section_name)
14641     free (section_name);
14642 }
14643
14644 void
14645 mips_enable_auto_align (void)
14646 {
14647   auto_align = 1;
14648 }
14649
14650 static void
14651 s_cons (int log_size)
14652 {
14653   segment_info_type *si = seg_info (now_seg);
14654   struct insn_label_list *l = si->label_list;
14655
14656   mips_emit_delays ();
14657   if (log_size > 0 && auto_align)
14658     mips_align (log_size, 0, l);
14659   cons (1 << log_size);
14660   mips_clear_insn_labels ();
14661 }
14662
14663 static void
14664 s_float_cons (int type)
14665 {
14666   segment_info_type *si = seg_info (now_seg);
14667   struct insn_label_list *l = si->label_list;
14668
14669   mips_emit_delays ();
14670
14671   if (auto_align)
14672     {
14673       if (type == 'd')
14674         mips_align (3, 0, l);
14675       else
14676         mips_align (2, 0, l);
14677     }
14678
14679   float_cons (type);
14680   mips_clear_insn_labels ();
14681 }
14682
14683 /* Handle .globl.  We need to override it because on Irix 5 you are
14684    permitted to say
14685        .globl foo .text
14686    where foo is an undefined symbol, to mean that foo should be
14687    considered to be the address of a function.  */
14688
14689 static void
14690 s_mips_globl (int x ATTRIBUTE_UNUSED)
14691 {
14692   char *name;
14693   int c;
14694   symbolS *symbolP;
14695   flagword flag;
14696
14697   do
14698     {
14699       name = input_line_pointer;
14700       c = get_symbol_end ();
14701       symbolP = symbol_find_or_make (name);
14702       S_SET_EXTERNAL (symbolP);
14703
14704       *input_line_pointer = c;
14705       SKIP_WHITESPACE ();
14706
14707       /* On Irix 5, every global symbol that is not explicitly labelled as
14708          being a function is apparently labelled as being an object.  */
14709       flag = BSF_OBJECT;
14710
14711       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14712           && (*input_line_pointer != ','))
14713         {
14714           char *secname;
14715           asection *sec;
14716
14717           secname = input_line_pointer;
14718           c = get_symbol_end ();
14719           sec = bfd_get_section_by_name (stdoutput, secname);
14720           if (sec == NULL)
14721             as_bad (_("%s: no such section"), secname);
14722           *input_line_pointer = c;
14723
14724           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14725             flag = BSF_FUNCTION;
14726         }
14727
14728       symbol_get_bfdsym (symbolP)->flags |= flag;
14729
14730       c = *input_line_pointer;
14731       if (c == ',')
14732         {
14733           input_line_pointer++;
14734           SKIP_WHITESPACE ();
14735           if (is_end_of_line[(unsigned char) *input_line_pointer])
14736             c = '\n';
14737         }
14738     }
14739   while (c == ',');
14740
14741   demand_empty_rest_of_line ();
14742 }
14743
14744 static void
14745 s_option (int x ATTRIBUTE_UNUSED)
14746 {
14747   char *opt;
14748   char c;
14749
14750   opt = input_line_pointer;
14751   c = get_symbol_end ();
14752
14753   if (*opt == 'O')
14754     {
14755       /* FIXME: What does this mean?  */
14756     }
14757   else if (strncmp (opt, "pic", 3) == 0)
14758     {
14759       int i;
14760
14761       i = atoi (opt + 3);
14762       if (i == 0)
14763         mips_pic = NO_PIC;
14764       else if (i == 2)
14765         {
14766           mips_pic = SVR4_PIC;
14767           mips_abicalls = TRUE;
14768         }
14769       else
14770         as_bad (_(".option pic%d not supported"), i);
14771
14772       if (mips_pic == SVR4_PIC)
14773         {
14774           if (g_switch_seen && g_switch_value != 0)
14775             as_warn (_("-G may not be used with SVR4 PIC code"));
14776           g_switch_value = 0;
14777           bfd_set_gp_size (stdoutput, 0);
14778         }
14779     }
14780   else
14781     as_warn (_("unrecognized option \"%s\""), opt);
14782
14783   *input_line_pointer = c;
14784   demand_empty_rest_of_line ();
14785 }
14786
14787 /* This structure is used to hold a stack of .set values.  */
14788
14789 struct mips_option_stack
14790 {
14791   struct mips_option_stack *next;
14792   struct mips_set_options options;
14793 };
14794
14795 static struct mips_option_stack *mips_opts_stack;
14796
14797 /* Handle the .set pseudo-op.  */
14798
14799 static void
14800 s_mipsset (int x ATTRIBUTE_UNUSED)
14801 {
14802   char *name = input_line_pointer, ch;
14803   const struct mips_ase *ase;
14804
14805   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14806     ++input_line_pointer;
14807   ch = *input_line_pointer;
14808   *input_line_pointer = '\0';
14809
14810   if (strcmp (name, "reorder") == 0)
14811     {
14812       if (mips_opts.noreorder)
14813         end_noreorder ();
14814     }
14815   else if (strcmp (name, "noreorder") == 0)
14816     {
14817       if (!mips_opts.noreorder)
14818         start_noreorder ();
14819     }
14820   else if (strncmp (name, "at=", 3) == 0)
14821     {
14822       char *s = name + 3;
14823
14824       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14825         as_bad (_("unrecognized register name `%s'"), s);
14826     }
14827   else if (strcmp (name, "at") == 0)
14828     {
14829       mips_opts.at = ATREG;
14830     }
14831   else if (strcmp (name, "noat") == 0)
14832     {
14833       mips_opts.at = ZERO;
14834     }
14835   else if (strcmp (name, "macro") == 0)
14836     {
14837       mips_opts.warn_about_macros = 0;
14838     }
14839   else if (strcmp (name, "nomacro") == 0)
14840     {
14841       if (mips_opts.noreorder == 0)
14842         as_bad (_("`noreorder' must be set before `nomacro'"));
14843       mips_opts.warn_about_macros = 1;
14844     }
14845   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14846     {
14847       mips_opts.nomove = 0;
14848     }
14849   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14850     {
14851       mips_opts.nomove = 1;
14852     }
14853   else if (strcmp (name, "bopt") == 0)
14854     {
14855       mips_opts.nobopt = 0;
14856     }
14857   else if (strcmp (name, "nobopt") == 0)
14858     {
14859       mips_opts.nobopt = 1;
14860     }
14861   else if (strcmp (name, "gp=default") == 0)
14862     mips_opts.gp32 = file_mips_gp32;
14863   else if (strcmp (name, "gp=32") == 0)
14864     mips_opts.gp32 = 1;
14865   else if (strcmp (name, "gp=64") == 0)
14866     {
14867       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14868         as_warn (_("%s isa does not support 64-bit registers"),
14869                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14870       mips_opts.gp32 = 0;
14871     }
14872   else if (strcmp (name, "fp=default") == 0)
14873     mips_opts.fp32 = file_mips_fp32;
14874   else if (strcmp (name, "fp=32") == 0)
14875     mips_opts.fp32 = 1;
14876   else if (strcmp (name, "fp=64") == 0)
14877     {
14878       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
14879         as_warn (_("%s isa does not support 64-bit floating point registers"),
14880                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14881       mips_opts.fp32 = 0;
14882     }
14883   else if (strcmp (name, "softfloat") == 0)
14884     mips_opts.soft_float = 1;
14885   else if (strcmp (name, "hardfloat") == 0)
14886     mips_opts.soft_float = 0;
14887   else if (strcmp (name, "singlefloat") == 0)
14888     mips_opts.single_float = 1;
14889   else if (strcmp (name, "doublefloat") == 0)
14890     mips_opts.single_float = 0;
14891   else if (strcmp (name, "mips16") == 0
14892            || strcmp (name, "MIPS-16") == 0)
14893     {
14894       if (mips_opts.micromips == 1)
14895         as_fatal (_("`mips16' cannot be used with `micromips'"));
14896       mips_opts.mips16 = 1;
14897     }
14898   else if (strcmp (name, "nomips16") == 0
14899            || strcmp (name, "noMIPS-16") == 0)
14900     mips_opts.mips16 = 0;
14901   else if (strcmp (name, "micromips") == 0)
14902     {
14903       if (mips_opts.mips16 == 1)
14904         as_fatal (_("`micromips' cannot be used with `mips16'"));
14905       mips_opts.micromips = 1;
14906     }
14907   else if (strcmp (name, "nomicromips") == 0)
14908     mips_opts.micromips = 0;
14909   else if (name[0] == 'n'
14910            && name[1] == 'o'
14911            && (ase = mips_lookup_ase (name + 2)))
14912     mips_set_ase (ase, FALSE);
14913   else if ((ase = mips_lookup_ase (name)))
14914     mips_set_ase (ase, TRUE);
14915   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
14916     {
14917       int reset = 0;
14918
14919       /* Permit the user to change the ISA and architecture on the fly.
14920          Needless to say, misuse can cause serious problems.  */
14921       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
14922         {
14923           reset = 1;
14924           mips_opts.isa = file_mips_isa;
14925           mips_opts.arch = file_mips_arch;
14926         }
14927       else if (strncmp (name, "arch=", 5) == 0)
14928         {
14929           const struct mips_cpu_info *p;
14930
14931           p = mips_parse_cpu("internal use", name + 5);
14932           if (!p)
14933             as_bad (_("unknown architecture %s"), name + 5);
14934           else
14935             {
14936               mips_opts.arch = p->cpu;
14937               mips_opts.isa = p->isa;
14938             }
14939         }
14940       else if (strncmp (name, "mips", 4) == 0)
14941         {
14942           const struct mips_cpu_info *p;
14943
14944           p = mips_parse_cpu("internal use", name);
14945           if (!p)
14946             as_bad (_("unknown ISA level %s"), name + 4);
14947           else
14948             {
14949               mips_opts.arch = p->cpu;
14950               mips_opts.isa = p->isa;
14951             }
14952         }
14953       else
14954         as_bad (_("unknown ISA or architecture %s"), name);
14955
14956       switch (mips_opts.isa)
14957         {
14958         case  0:
14959           break;
14960         case ISA_MIPS1:
14961         case ISA_MIPS2:
14962         case ISA_MIPS32:
14963         case ISA_MIPS32R2:
14964           mips_opts.gp32 = 1;
14965           mips_opts.fp32 = 1;
14966           break;
14967         case ISA_MIPS3:
14968         case ISA_MIPS4:
14969         case ISA_MIPS5:
14970         case ISA_MIPS64:
14971         case ISA_MIPS64R2:
14972           mips_opts.gp32 = 0;
14973           if (mips_opts.arch == CPU_R5900)
14974             {
14975                 mips_opts.fp32 = 1;
14976             }
14977           else
14978             {
14979           mips_opts.fp32 = 0;
14980             }
14981           break;
14982         default:
14983           as_bad (_("unknown ISA level %s"), name + 4);
14984           break;
14985         }
14986       if (reset)
14987         {
14988           mips_opts.gp32 = file_mips_gp32;
14989           mips_opts.fp32 = file_mips_fp32;
14990         }
14991     }
14992   else if (strcmp (name, "autoextend") == 0)
14993     mips_opts.noautoextend = 0;
14994   else if (strcmp (name, "noautoextend") == 0)
14995     mips_opts.noautoextend = 1;
14996   else if (strcmp (name, "insn32") == 0)
14997     mips_opts.insn32 = TRUE;
14998   else if (strcmp (name, "noinsn32") == 0)
14999     mips_opts.insn32 = FALSE;
15000   else if (strcmp (name, "push") == 0)
15001     {
15002       struct mips_option_stack *s;
15003
15004       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15005       s->next = mips_opts_stack;
15006       s->options = mips_opts;
15007       mips_opts_stack = s;
15008     }
15009   else if (strcmp (name, "pop") == 0)
15010     {
15011       struct mips_option_stack *s;
15012
15013       s = mips_opts_stack;
15014       if (s == NULL)
15015         as_bad (_(".set pop with no .set push"));
15016       else
15017         {
15018           /* If we're changing the reorder mode we need to handle
15019              delay slots correctly.  */
15020           if (s->options.noreorder && ! mips_opts.noreorder)
15021             start_noreorder ();
15022           else if (! s->options.noreorder && mips_opts.noreorder)
15023             end_noreorder ();
15024
15025           mips_opts = s->options;
15026           mips_opts_stack = s->next;
15027           free (s);
15028         }
15029     }
15030   else if (strcmp (name, "sym32") == 0)
15031     mips_opts.sym32 = TRUE;
15032   else if (strcmp (name, "nosym32") == 0)
15033     mips_opts.sym32 = FALSE;
15034   else if (strchr (name, ','))
15035     {
15036       /* Generic ".set" directive; use the generic handler.  */
15037       *input_line_pointer = ch;
15038       input_line_pointer = name;
15039       s_set (0);
15040       return;
15041     }
15042   else
15043     {
15044       as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15045     }
15046   mips_check_isa_supports_ases ();
15047   *input_line_pointer = ch;
15048   demand_empty_rest_of_line ();
15049 }
15050
15051 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15052    .option pic2.  It means to generate SVR4 PIC calls.  */
15053
15054 static void
15055 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15056 {
15057   mips_pic = SVR4_PIC;
15058   mips_abicalls = TRUE;
15059
15060   if (g_switch_seen && g_switch_value != 0)
15061     as_warn (_("-G may not be used with SVR4 PIC code"));
15062   g_switch_value = 0;
15063
15064   bfd_set_gp_size (stdoutput, 0);
15065   demand_empty_rest_of_line ();
15066 }
15067
15068 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15069    PIC code.  It sets the $gp register for the function based on the
15070    function address, which is in the register named in the argument.
15071    This uses a relocation against _gp_disp, which is handled specially
15072    by the linker.  The result is:
15073         lui     $gp,%hi(_gp_disp)
15074         addiu   $gp,$gp,%lo(_gp_disp)
15075         addu    $gp,$gp,.cpload argument
15076    The .cpload argument is normally $25 == $t9.
15077
15078    The -mno-shared option changes this to:
15079         lui     $gp,%hi(__gnu_local_gp)
15080         addiu   $gp,$gp,%lo(__gnu_local_gp)
15081    and the argument is ignored.  This saves an instruction, but the
15082    resulting code is not position independent; it uses an absolute
15083    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15084    can go into an ordinary executable, but not into a shared library.  */
15085
15086 static void
15087 s_cpload (int ignore ATTRIBUTE_UNUSED)
15088 {
15089   expressionS ex;
15090   int reg;
15091   int in_shared;
15092
15093   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15094      .cpload is ignored.  */
15095   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15096     {
15097       s_ignore (0);
15098       return;
15099     }
15100
15101   if (mips_opts.mips16)
15102     {
15103       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15104       ignore_rest_of_line ();
15105       return;
15106     }
15107
15108   /* .cpload should be in a .set noreorder section.  */
15109   if (mips_opts.noreorder == 0)
15110     as_warn (_(".cpload not in noreorder section"));
15111
15112   reg = tc_get_register (0);
15113
15114   /* If we need to produce a 64-bit address, we are better off using
15115      the default instruction sequence.  */
15116   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15117
15118   ex.X_op = O_symbol;
15119   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15120                                          "__gnu_local_gp");
15121   ex.X_op_symbol = NULL;
15122   ex.X_add_number = 0;
15123
15124   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15125   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15126
15127   mips_mark_labels ();
15128   mips_assembling_insn = TRUE;
15129
15130   macro_start ();
15131   macro_build_lui (&ex, mips_gp_register);
15132   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15133                mips_gp_register, BFD_RELOC_LO16);
15134   if (in_shared)
15135     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15136                  mips_gp_register, reg);
15137   macro_end ();
15138
15139   mips_assembling_insn = FALSE;
15140   demand_empty_rest_of_line ();
15141 }
15142
15143 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15144      .cpsetup $reg1, offset|$reg2, label
15145
15146    If offset is given, this results in:
15147      sd         $gp, offset($sp)
15148      lui        $gp, %hi(%neg(%gp_rel(label)))
15149      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15150      daddu      $gp, $gp, $reg1
15151
15152    If $reg2 is given, this results in:
15153      daddu      $reg2, $gp, $0
15154      lui        $gp, %hi(%neg(%gp_rel(label)))
15155      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15156      daddu      $gp, $gp, $reg1
15157    $reg1 is normally $25 == $t9.
15158
15159    The -mno-shared option replaces the last three instructions with
15160         lui     $gp,%hi(_gp)
15161         addiu   $gp,$gp,%lo(_gp)  */
15162
15163 static void
15164 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15165 {
15166   expressionS ex_off;
15167   expressionS ex_sym;
15168   int reg1;
15169
15170   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15171      We also need NewABI support.  */
15172   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15173     {
15174       s_ignore (0);
15175       return;
15176     }
15177
15178   if (mips_opts.mips16)
15179     {
15180       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15181       ignore_rest_of_line ();
15182       return;
15183     }
15184
15185   reg1 = tc_get_register (0);
15186   SKIP_WHITESPACE ();
15187   if (*input_line_pointer != ',')
15188     {
15189       as_bad (_("missing argument separator ',' for .cpsetup"));
15190       return;
15191     }
15192   else
15193     ++input_line_pointer;
15194   SKIP_WHITESPACE ();
15195   if (*input_line_pointer == '$')
15196     {
15197       mips_cpreturn_register = tc_get_register (0);
15198       mips_cpreturn_offset = -1;
15199     }
15200   else
15201     {
15202       mips_cpreturn_offset = get_absolute_expression ();
15203       mips_cpreturn_register = -1;
15204     }
15205   SKIP_WHITESPACE ();
15206   if (*input_line_pointer != ',')
15207     {
15208       as_bad (_("missing argument separator ',' for .cpsetup"));
15209       return;
15210     }
15211   else
15212     ++input_line_pointer;
15213   SKIP_WHITESPACE ();
15214   expression (&ex_sym);
15215
15216   mips_mark_labels ();
15217   mips_assembling_insn = TRUE;
15218
15219   macro_start ();
15220   if (mips_cpreturn_register == -1)
15221     {
15222       ex_off.X_op = O_constant;
15223       ex_off.X_add_symbol = NULL;
15224       ex_off.X_op_symbol = NULL;
15225       ex_off.X_add_number = mips_cpreturn_offset;
15226
15227       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15228                    BFD_RELOC_LO16, SP);
15229     }
15230   else
15231     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15232                  mips_gp_register, 0);
15233
15234   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15235     {
15236       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15237                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15238                    BFD_RELOC_HI16_S);
15239
15240       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15241                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15242                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15243
15244       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15245                    mips_gp_register, reg1);
15246     }
15247   else
15248     {
15249       expressionS ex;
15250
15251       ex.X_op = O_symbol;
15252       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15253       ex.X_op_symbol = NULL;
15254       ex.X_add_number = 0;
15255
15256       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15257       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15258
15259       macro_build_lui (&ex, mips_gp_register);
15260       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15261                    mips_gp_register, BFD_RELOC_LO16);
15262     }
15263
15264   macro_end ();
15265
15266   mips_assembling_insn = FALSE;
15267   demand_empty_rest_of_line ();
15268 }
15269
15270 static void
15271 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15272 {
15273   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15274      .cplocal is ignored.  */
15275   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15276     {
15277       s_ignore (0);
15278       return;
15279     }
15280
15281   if (mips_opts.mips16)
15282     {
15283       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15284       ignore_rest_of_line ();
15285       return;
15286     }
15287
15288   mips_gp_register = tc_get_register (0);
15289   demand_empty_rest_of_line ();
15290 }
15291
15292 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15293    offset from $sp.  The offset is remembered, and after making a PIC
15294    call $gp is restored from that location.  */
15295
15296 static void
15297 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15298 {
15299   expressionS ex;
15300
15301   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15302      .cprestore is ignored.  */
15303   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15304     {
15305       s_ignore (0);
15306       return;
15307     }
15308
15309   if (mips_opts.mips16)
15310     {
15311       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15312       ignore_rest_of_line ();
15313       return;
15314     }
15315
15316   mips_cprestore_offset = get_absolute_expression ();
15317   mips_cprestore_valid = 1;
15318
15319   ex.X_op = O_constant;
15320   ex.X_add_symbol = NULL;
15321   ex.X_op_symbol = NULL;
15322   ex.X_add_number = mips_cprestore_offset;
15323
15324   mips_mark_labels ();
15325   mips_assembling_insn = TRUE;
15326
15327   macro_start ();
15328   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15329                                 SP, HAVE_64BIT_ADDRESSES);
15330   macro_end ();
15331
15332   mips_assembling_insn = FALSE;
15333   demand_empty_rest_of_line ();
15334 }
15335
15336 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15337    was given in the preceding .cpsetup, it results in:
15338      ld         $gp, offset($sp)
15339
15340    If a register $reg2 was given there, it results in:
15341      daddu      $gp, $reg2, $0  */
15342
15343 static void
15344 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15345 {
15346   expressionS ex;
15347
15348   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15349      We also need NewABI support.  */
15350   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15351     {
15352       s_ignore (0);
15353       return;
15354     }
15355
15356   if (mips_opts.mips16)
15357     {
15358       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15359       ignore_rest_of_line ();
15360       return;
15361     }
15362
15363   mips_mark_labels ();
15364   mips_assembling_insn = TRUE;
15365
15366   macro_start ();
15367   if (mips_cpreturn_register == -1)
15368     {
15369       ex.X_op = O_constant;
15370       ex.X_add_symbol = NULL;
15371       ex.X_op_symbol = NULL;
15372       ex.X_add_number = mips_cpreturn_offset;
15373
15374       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15375     }
15376   else
15377     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15378                  mips_cpreturn_register, 0);
15379   macro_end ();
15380
15381   mips_assembling_insn = FALSE;
15382   demand_empty_rest_of_line ();
15383 }
15384
15385 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15386    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15387    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15388    debug information or MIPS16 TLS.  */
15389
15390 static void
15391 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15392                      bfd_reloc_code_real_type rtype)
15393 {
15394   expressionS ex;
15395   char *p;
15396
15397   expression (&ex);
15398
15399   if (ex.X_op != O_symbol)
15400     {
15401       as_bad (_("unsupported use of %s"), dirstr);
15402       ignore_rest_of_line ();
15403     }
15404
15405   p = frag_more (bytes);
15406   md_number_to_chars (p, 0, bytes);
15407   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15408   demand_empty_rest_of_line ();
15409   mips_clear_insn_labels ();
15410 }
15411
15412 /* Handle .dtprelword.  */
15413
15414 static void
15415 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15416 {
15417   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15418 }
15419
15420 /* Handle .dtpreldword.  */
15421
15422 static void
15423 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15424 {
15425   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15426 }
15427
15428 /* Handle .tprelword.  */
15429
15430 static void
15431 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15432 {
15433   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15434 }
15435
15436 /* Handle .tpreldword.  */
15437
15438 static void
15439 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15440 {
15441   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15442 }
15443
15444 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15445    code.  It sets the offset to use in gp_rel relocations.  */
15446
15447 static void
15448 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15449 {
15450   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15451      We also need NewABI support.  */
15452   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15453     {
15454       s_ignore (0);
15455       return;
15456     }
15457
15458   mips_gprel_offset = get_absolute_expression ();
15459
15460   demand_empty_rest_of_line ();
15461 }
15462
15463 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15464    code.  It generates a 32 bit GP relative reloc.  */
15465
15466 static void
15467 s_gpword (int ignore ATTRIBUTE_UNUSED)
15468 {
15469   segment_info_type *si;
15470   struct insn_label_list *l;
15471   expressionS ex;
15472   char *p;
15473
15474   /* When not generating PIC code, this is treated as .word.  */
15475   if (mips_pic != SVR4_PIC)
15476     {
15477       s_cons (2);
15478       return;
15479     }
15480
15481   si = seg_info (now_seg);
15482   l = si->label_list;
15483   mips_emit_delays ();
15484   if (auto_align)
15485     mips_align (2, 0, l);
15486
15487   expression (&ex);
15488   mips_clear_insn_labels ();
15489
15490   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15491     {
15492       as_bad (_("unsupported use of .gpword"));
15493       ignore_rest_of_line ();
15494     }
15495
15496   p = frag_more (4);
15497   md_number_to_chars (p, 0, 4);
15498   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15499                BFD_RELOC_GPREL32);
15500
15501   demand_empty_rest_of_line ();
15502 }
15503
15504 static void
15505 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15506 {
15507   segment_info_type *si;
15508   struct insn_label_list *l;
15509   expressionS ex;
15510   char *p;
15511
15512   /* When not generating PIC code, this is treated as .dword.  */
15513   if (mips_pic != SVR4_PIC)
15514     {
15515       s_cons (3);
15516       return;
15517     }
15518
15519   si = seg_info (now_seg);
15520   l = si->label_list;
15521   mips_emit_delays ();
15522   if (auto_align)
15523     mips_align (3, 0, l);
15524
15525   expression (&ex);
15526   mips_clear_insn_labels ();
15527
15528   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15529     {
15530       as_bad (_("unsupported use of .gpdword"));
15531       ignore_rest_of_line ();
15532     }
15533
15534   p = frag_more (8);
15535   md_number_to_chars (p, 0, 8);
15536   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15537                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15538
15539   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15540   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15541            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15542
15543   demand_empty_rest_of_line ();
15544 }
15545
15546 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15547    tables.  It generates a R_MIPS_EH reloc.  */
15548
15549 static void
15550 s_ehword (int ignore ATTRIBUTE_UNUSED)
15551 {
15552   expressionS ex;
15553   char *p;
15554
15555   mips_emit_delays ();
15556
15557   expression (&ex);
15558   mips_clear_insn_labels ();
15559
15560   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15561     {
15562       as_bad (_("unsupported use of .ehword"));
15563       ignore_rest_of_line ();
15564     }
15565
15566   p = frag_more (4);
15567   md_number_to_chars (p, 0, 4);
15568   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15569                BFD_RELOC_MIPS_EH);
15570
15571   demand_empty_rest_of_line ();
15572 }
15573
15574 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15575    tables in SVR4 PIC code.  */
15576
15577 static void
15578 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15579 {
15580   int reg;
15581
15582   /* This is ignored when not generating SVR4 PIC code.  */
15583   if (mips_pic != SVR4_PIC)
15584     {
15585       s_ignore (0);
15586       return;
15587     }
15588
15589   mips_mark_labels ();
15590   mips_assembling_insn = TRUE;
15591
15592   /* Add $gp to the register named as an argument.  */
15593   macro_start ();
15594   reg = tc_get_register (0);
15595   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15596   macro_end ();
15597
15598   mips_assembling_insn = FALSE;
15599   demand_empty_rest_of_line ();
15600 }
15601
15602 /* Handle the .insn pseudo-op.  This marks instruction labels in
15603    mips16/micromips mode.  This permits the linker to handle them specially,
15604    such as generating jalx instructions when needed.  We also make
15605    them odd for the duration of the assembly, in order to generate the
15606    right sort of code.  We will make them even in the adjust_symtab
15607    routine, while leaving them marked.  This is convenient for the
15608    debugger and the disassembler.  The linker knows to make them odd
15609    again.  */
15610
15611 static void
15612 s_insn (int ignore ATTRIBUTE_UNUSED)
15613 {
15614   mips_mark_labels ();
15615
15616   demand_empty_rest_of_line ();
15617 }
15618
15619 /* Handle the .nan pseudo-op.  */
15620
15621 static void
15622 s_nan (int ignore ATTRIBUTE_UNUSED)
15623 {
15624   static const char str_legacy[] = "legacy";
15625   static const char str_2008[] = "2008";
15626   size_t i;
15627
15628   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15629
15630   if (i == sizeof (str_2008) - 1
15631       && memcmp (input_line_pointer, str_2008, i) == 0)
15632     mips_flag_nan2008 = TRUE;
15633   else if (i == sizeof (str_legacy) - 1
15634            && memcmp (input_line_pointer, str_legacy, i) == 0)
15635     mips_flag_nan2008 = FALSE;
15636   else
15637     as_bad (_("bad .nan directive"));
15638
15639   input_line_pointer += i;
15640   demand_empty_rest_of_line ();
15641 }
15642
15643 /* Handle a .stab[snd] directive.  Ideally these directives would be
15644    implemented in a transparent way, so that removing them would not
15645    have any effect on the generated instructions.  However, s_stab
15646    internally changes the section, so in practice we need to decide
15647    now whether the preceding label marks compressed code.  We do not
15648    support changing the compression mode of a label after a .stab*
15649    directive, such as in:
15650
15651    foo:
15652         .stabs ...
15653         .set mips16
15654
15655    so the current mode wins.  */
15656
15657 static void
15658 s_mips_stab (int type)
15659 {
15660   mips_mark_labels ();
15661   s_stab (type);
15662 }
15663
15664 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15665
15666 static void
15667 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15668 {
15669   char *name;
15670   int c;
15671   symbolS *symbolP;
15672   expressionS exp;
15673
15674   name = input_line_pointer;
15675   c = get_symbol_end ();
15676   symbolP = symbol_find_or_make (name);
15677   S_SET_WEAK (symbolP);
15678   *input_line_pointer = c;
15679
15680   SKIP_WHITESPACE ();
15681
15682   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15683     {
15684       if (S_IS_DEFINED (symbolP))
15685         {
15686           as_bad (_("ignoring attempt to redefine symbol %s"),
15687                   S_GET_NAME (symbolP));
15688           ignore_rest_of_line ();
15689           return;
15690         }
15691
15692       if (*input_line_pointer == ',')
15693         {
15694           ++input_line_pointer;
15695           SKIP_WHITESPACE ();
15696         }
15697
15698       expression (&exp);
15699       if (exp.X_op != O_symbol)
15700         {
15701           as_bad (_("bad .weakext directive"));
15702           ignore_rest_of_line ();
15703           return;
15704         }
15705       symbol_set_value_expression (symbolP, &exp);
15706     }
15707
15708   demand_empty_rest_of_line ();
15709 }
15710
15711 /* Parse a register string into a number.  Called from the ECOFF code
15712    to parse .frame.  The argument is non-zero if this is the frame
15713    register, so that we can record it in mips_frame_reg.  */
15714
15715 int
15716 tc_get_register (int frame)
15717 {
15718   unsigned int reg;
15719
15720   SKIP_WHITESPACE ();
15721   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15722     reg = 0;
15723   if (frame)
15724     {
15725       mips_frame_reg = reg != 0 ? reg : SP;
15726       mips_frame_reg_valid = 1;
15727       mips_cprestore_valid = 0;
15728     }
15729   return reg;
15730 }
15731
15732 valueT
15733 md_section_align (asection *seg, valueT addr)
15734 {
15735   int align = bfd_get_section_alignment (stdoutput, seg);
15736
15737   /* We don't need to align ELF sections to the full alignment.
15738      However, Irix 5 may prefer that we align them at least to a 16
15739      byte boundary.  We don't bother to align the sections if we
15740      are targeted for an embedded system.  */
15741   if (strncmp (TARGET_OS, "elf", 3) == 0)
15742     return addr;
15743   if (align > 4)
15744     align = 4;
15745
15746   return ((addr + (1 << align) - 1) & (-1 << align));
15747 }
15748
15749 /* Utility routine, called from above as well.  If called while the
15750    input file is still being read, it's only an approximation.  (For
15751    example, a symbol may later become defined which appeared to be
15752    undefined earlier.)  */
15753
15754 static int
15755 nopic_need_relax (symbolS *sym, int before_relaxing)
15756 {
15757   if (sym == 0)
15758     return 0;
15759
15760   if (g_switch_value > 0)
15761     {
15762       const char *symname;
15763       int change;
15764
15765       /* Find out whether this symbol can be referenced off the $gp
15766          register.  It can be if it is smaller than the -G size or if
15767          it is in the .sdata or .sbss section.  Certain symbols can
15768          not be referenced off the $gp, although it appears as though
15769          they can.  */
15770       symname = S_GET_NAME (sym);
15771       if (symname != (const char *) NULL
15772           && (strcmp (symname, "eprol") == 0
15773               || strcmp (symname, "etext") == 0
15774               || strcmp (symname, "_gp") == 0
15775               || strcmp (symname, "edata") == 0
15776               || strcmp (symname, "_fbss") == 0
15777               || strcmp (symname, "_fdata") == 0
15778               || strcmp (symname, "_ftext") == 0
15779               || strcmp (symname, "end") == 0
15780               || strcmp (symname, "_gp_disp") == 0))
15781         change = 1;
15782       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15783                && (0
15784 #ifndef NO_ECOFF_DEBUGGING
15785                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15786                        && (symbol_get_obj (sym)->ecoff_extern_size
15787                            <= g_switch_value))
15788 #endif
15789                    /* We must defer this decision until after the whole
15790                       file has been read, since there might be a .extern
15791                       after the first use of this symbol.  */
15792                    || (before_relaxing
15793 #ifndef NO_ECOFF_DEBUGGING
15794                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15795 #endif
15796                        && S_GET_VALUE (sym) == 0)
15797                    || (S_GET_VALUE (sym) != 0
15798                        && S_GET_VALUE (sym) <= g_switch_value)))
15799         change = 0;
15800       else
15801         {
15802           const char *segname;
15803
15804           segname = segment_name (S_GET_SEGMENT (sym));
15805           gas_assert (strcmp (segname, ".lit8") != 0
15806                   && strcmp (segname, ".lit4") != 0);
15807           change = (strcmp (segname, ".sdata") != 0
15808                     && strcmp (segname, ".sbss") != 0
15809                     && strncmp (segname, ".sdata.", 7) != 0
15810                     && strncmp (segname, ".sbss.", 6) != 0
15811                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15812                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15813         }
15814       return change;
15815     }
15816   else
15817     /* We are not optimizing for the $gp register.  */
15818     return 1;
15819 }
15820
15821
15822 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15823
15824 static bfd_boolean
15825 pic_need_relax (symbolS *sym, asection *segtype)
15826 {
15827   asection *symsec;
15828
15829   /* Handle the case of a symbol equated to another symbol.  */
15830   while (symbol_equated_reloc_p (sym))
15831     {
15832       symbolS *n;
15833
15834       /* It's possible to get a loop here in a badly written program.  */
15835       n = symbol_get_value_expression (sym)->X_add_symbol;
15836       if (n == sym)
15837         break;
15838       sym = n;
15839     }
15840
15841   if (symbol_section_p (sym))
15842     return TRUE;
15843
15844   symsec = S_GET_SEGMENT (sym);
15845
15846   /* This must duplicate the test in adjust_reloc_syms.  */
15847   return (!bfd_is_und_section (symsec)
15848           && !bfd_is_abs_section (symsec)
15849           && !bfd_is_com_section (symsec)
15850           && !s_is_linkonce (sym, segtype)
15851           /* A global or weak symbol is treated as external.  */
15852           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15853 }
15854
15855
15856 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15857    extended opcode.  SEC is the section the frag is in.  */
15858
15859 static int
15860 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15861 {
15862   int type;
15863   const struct mips_int_operand *operand;
15864   offsetT val;
15865   segT symsec;
15866   fragS *sym_frag;
15867
15868   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15869     return 0;
15870   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15871     return 1;
15872
15873   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
15874   operand = mips16_immed_operand (type, FALSE);
15875
15876   sym_frag = symbol_get_frag (fragp->fr_symbol);
15877   val = S_GET_VALUE (fragp->fr_symbol);
15878   symsec = S_GET_SEGMENT (fragp->fr_symbol);
15879
15880   if (operand->root.type == OP_PCREL)
15881     {
15882       const struct mips_pcrel_operand *pcrel_op;
15883       addressT addr;
15884       offsetT maxtiny;
15885
15886       /* We won't have the section when we are called from
15887          mips_relax_frag.  However, we will always have been called
15888          from md_estimate_size_before_relax first.  If this is a
15889          branch to a different section, we mark it as such.  If SEC is
15890          NULL, and the frag is not marked, then it must be a branch to
15891          the same section.  */
15892       pcrel_op = (const struct mips_pcrel_operand *) operand;
15893       if (sec == NULL)
15894         {
15895           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
15896             return 1;
15897         }
15898       else
15899         {
15900           /* Must have been called from md_estimate_size_before_relax.  */
15901           if (symsec != sec)
15902             {
15903               fragp->fr_subtype =
15904                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15905
15906               /* FIXME: We should support this, and let the linker
15907                  catch branches and loads that are out of range.  */
15908               as_bad_where (fragp->fr_file, fragp->fr_line,
15909                             _("unsupported PC relative reference to different section"));
15910
15911               return 1;
15912             }
15913           if (fragp != sym_frag && sym_frag->fr_address == 0)
15914             /* Assume non-extended on the first relaxation pass.
15915                The address we have calculated will be bogus if this is
15916                a forward branch to another frag, as the forward frag
15917                will have fr_address == 0.  */
15918             return 0;
15919         }
15920
15921       /* In this case, we know for sure that the symbol fragment is in
15922          the same section.  If the relax_marker of the symbol fragment
15923          differs from the relax_marker of this fragment, we have not
15924          yet adjusted the symbol fragment fr_address.  We want to add
15925          in STRETCH in order to get a better estimate of the address.
15926          This particularly matters because of the shift bits.  */
15927       if (stretch != 0
15928           && sym_frag->relax_marker != fragp->relax_marker)
15929         {
15930           fragS *f;
15931
15932           /* Adjust stretch for any alignment frag.  Note that if have
15933              been expanding the earlier code, the symbol may be
15934              defined in what appears to be an earlier frag.  FIXME:
15935              This doesn't handle the fr_subtype field, which specifies
15936              a maximum number of bytes to skip when doing an
15937              alignment.  */
15938           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
15939             {
15940               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
15941                 {
15942                   if (stretch < 0)
15943                     stretch = - ((- stretch)
15944                                  & ~ ((1 << (int) f->fr_offset) - 1));
15945                   else
15946                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
15947                   if (stretch == 0)
15948                     break;
15949                 }
15950             }
15951           if (f != NULL)
15952             val += stretch;
15953         }
15954
15955       addr = fragp->fr_address + fragp->fr_fix;
15956
15957       /* The base address rules are complicated.  The base address of
15958          a branch is the following instruction.  The base address of a
15959          PC relative load or add is the instruction itself, but if it
15960          is in a delay slot (in which case it can not be extended) use
15961          the address of the instruction whose delay slot it is in.  */
15962       if (pcrel_op->include_isa_bit)
15963         {
15964           addr += 2;
15965
15966           /* If we are currently assuming that this frag should be
15967              extended, then, the current address is two bytes
15968              higher.  */
15969           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
15970             addr += 2;
15971
15972           /* Ignore the low bit in the target, since it will be set
15973              for a text label.  */
15974           val &= -2;
15975         }
15976       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
15977         addr -= 4;
15978       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
15979         addr -= 2;
15980
15981       val -= addr & -(1 << pcrel_op->align_log2);
15982
15983       /* If any of the shifted bits are set, we must use an extended
15984          opcode.  If the address depends on the size of this
15985          instruction, this can lead to a loop, so we arrange to always
15986          use an extended opcode.  We only check this when we are in
15987          the main relaxation loop, when SEC is NULL.  */
15988       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
15989         {
15990           fragp->fr_subtype =
15991             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
15992           return 1;
15993         }
15994
15995       /* If we are about to mark a frag as extended because the value
15996          is precisely the next value above maxtiny, then there is a
15997          chance of an infinite loop as in the following code:
15998              la $4,foo
15999              .skip      1020
16000              .align     2
16001            foo:
16002          In this case when the la is extended, foo is 0x3fc bytes
16003          away, so the la can be shrunk, but then foo is 0x400 away, so
16004          the la must be extended.  To avoid this loop, we mark the
16005          frag as extended if it was small, and is about to become
16006          extended with the next value above maxtiny.  */
16007       maxtiny = mips_int_operand_max (operand);
16008       if (val == maxtiny + (1 << operand->shift)
16009           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16010           && sec == NULL)
16011         {
16012           fragp->fr_subtype =
16013             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16014           return 1;
16015         }
16016     }
16017   else if (symsec != absolute_section && sec != NULL)
16018     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16019
16020   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16021 }
16022
16023 /* Compute the length of a branch sequence, and adjust the
16024    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16025    worst-case length is computed, with UPDATE being used to indicate
16026    whether an unconditional (-1), branch-likely (+1) or regular (0)
16027    branch is to be computed.  */
16028 static int
16029 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16030 {
16031   bfd_boolean toofar;
16032   int length;
16033
16034   if (fragp
16035       && S_IS_DEFINED (fragp->fr_symbol)
16036       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16037     {
16038       addressT addr;
16039       offsetT val;
16040
16041       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16042
16043       addr = fragp->fr_address + fragp->fr_fix + 4;
16044
16045       val -= addr;
16046
16047       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16048     }
16049   else if (fragp)
16050     /* If the symbol is not defined or it's in a different segment,
16051        assume the user knows what's going on and emit a short
16052        branch.  */
16053     toofar = FALSE;
16054   else
16055     toofar = TRUE;
16056
16057   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16058     fragp->fr_subtype
16059       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16060                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16061                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16062                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16063                              toofar);
16064
16065   length = 4;
16066   if (toofar)
16067     {
16068       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16069         length += 8;
16070
16071       if (mips_pic != NO_PIC)
16072         {
16073           /* Additional space for PIC loading of target address.  */
16074           length += 8;
16075           if (mips_opts.isa == ISA_MIPS1)
16076             /* Additional space for $at-stabilizing nop.  */
16077             length += 4;
16078         }
16079
16080       /* If branch is conditional.  */
16081       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16082         length += 8;
16083     }
16084
16085   return length;
16086 }
16087
16088 /* Compute the length of a branch sequence, and adjust the
16089    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16090    worst-case length is computed, with UPDATE being used to indicate
16091    whether an unconditional (-1), or regular (0) branch is to be
16092    computed.  */
16093
16094 static int
16095 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16096 {
16097   bfd_boolean toofar;
16098   int length;
16099
16100   if (fragp
16101       && S_IS_DEFINED (fragp->fr_symbol)
16102       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16103     {
16104       addressT addr;
16105       offsetT val;
16106
16107       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16108       /* Ignore the low bit in the target, since it will be set
16109          for a text label.  */
16110       if ((val & 1) != 0)
16111         --val;
16112
16113       addr = fragp->fr_address + fragp->fr_fix + 4;
16114
16115       val -= addr;
16116
16117       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16118     }
16119   else if (fragp)
16120     /* If the symbol is not defined or it's in a different segment,
16121        assume the user knows what's going on and emit a short
16122        branch.  */
16123     toofar = FALSE;
16124   else
16125     toofar = TRUE;
16126
16127   if (fragp && update
16128       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16129     fragp->fr_subtype = (toofar
16130                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16131                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16132
16133   length = 4;
16134   if (toofar)
16135     {
16136       bfd_boolean compact_known = fragp != NULL;
16137       bfd_boolean compact = FALSE;
16138       bfd_boolean uncond;
16139
16140       if (compact_known)
16141         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16142       if (fragp)
16143         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16144       else
16145         uncond = update < 0;
16146
16147       /* If label is out of range, we turn branch <br>:
16148
16149                 <br>    label                   # 4 bytes
16150             0:
16151
16152          into:
16153
16154                 j       label                   # 4 bytes
16155                 nop                             # 2 bytes if compact && !PIC
16156             0:
16157        */
16158       if (mips_pic == NO_PIC && (!compact_known || compact))
16159         length += 2;
16160
16161       /* If assembling PIC code, we further turn:
16162
16163                         j       label                   # 4 bytes
16164
16165          into:
16166
16167                         lw/ld   at, %got(label)(gp)     # 4 bytes
16168                         d/addiu at, %lo(label)          # 4 bytes
16169                         jr/c    at                      # 2 bytes
16170        */
16171       if (mips_pic != NO_PIC)
16172         length += 6;
16173
16174       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16175
16176                         <brneg> 0f                      # 4 bytes
16177                         nop                             # 2 bytes if !compact
16178        */
16179       if (!uncond)
16180         length += (compact_known && compact) ? 4 : 6;
16181     }
16182
16183   return length;
16184 }
16185
16186 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16187    bit accordingly.  */
16188
16189 static int
16190 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16191 {
16192   bfd_boolean toofar;
16193
16194   if (fragp
16195       && S_IS_DEFINED (fragp->fr_symbol)
16196       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16197     {
16198       addressT addr;
16199       offsetT val;
16200       int type;
16201
16202       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16203       /* Ignore the low bit in the target, since it will be set
16204          for a text label.  */
16205       if ((val & 1) != 0)
16206         --val;
16207
16208       /* Assume this is a 2-byte branch.  */
16209       addr = fragp->fr_address + fragp->fr_fix + 2;
16210
16211       /* We try to avoid the infinite loop by not adding 2 more bytes for
16212          long branches.  */
16213
16214       val -= addr;
16215
16216       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16217       if (type == 'D')
16218         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16219       else if (type == 'E')
16220         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16221       else
16222         abort ();
16223     }
16224   else
16225     /* If the symbol is not defined or it's in a different segment,
16226        we emit a normal 32-bit branch.  */
16227     toofar = TRUE;
16228
16229   if (fragp && update
16230       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16231     fragp->fr_subtype
16232       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16233                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16234
16235   if (toofar)
16236     return 4;
16237
16238   return 2;
16239 }
16240
16241 /* Estimate the size of a frag before relaxing.  Unless this is the
16242    mips16, we are not really relaxing here, and the final size is
16243    encoded in the subtype information.  For the mips16, we have to
16244    decide whether we are using an extended opcode or not.  */
16245
16246 int
16247 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16248 {
16249   int change;
16250
16251   if (RELAX_BRANCH_P (fragp->fr_subtype))
16252     {
16253
16254       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16255
16256       return fragp->fr_var;
16257     }
16258
16259   if (RELAX_MIPS16_P (fragp->fr_subtype))
16260     /* We don't want to modify the EXTENDED bit here; it might get us
16261        into infinite loops.  We change it only in mips_relax_frag().  */
16262     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16263
16264   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16265     {
16266       int length = 4;
16267
16268       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16269         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16270       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16271         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16272       fragp->fr_var = length;
16273
16274       return length;
16275     }
16276
16277   if (mips_pic == NO_PIC)
16278     change = nopic_need_relax (fragp->fr_symbol, 0);
16279   else if (mips_pic == SVR4_PIC)
16280     change = pic_need_relax (fragp->fr_symbol, segtype);
16281   else if (mips_pic == VXWORKS_PIC)
16282     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16283     change = 0;
16284   else
16285     abort ();
16286
16287   if (change)
16288     {
16289       fragp->fr_subtype |= RELAX_USE_SECOND;
16290       return -RELAX_FIRST (fragp->fr_subtype);
16291     }
16292   else
16293     return -RELAX_SECOND (fragp->fr_subtype);
16294 }
16295
16296 /* This is called to see whether a reloc against a defined symbol
16297    should be converted into a reloc against a section.  */
16298
16299 int
16300 mips_fix_adjustable (fixS *fixp)
16301 {
16302   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16303       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16304     return 0;
16305
16306   if (fixp->fx_addsy == NULL)
16307     return 1;
16308
16309   /* If symbol SYM is in a mergeable section, relocations of the form
16310      SYM + 0 can usually be made section-relative.  The mergeable data
16311      is then identified by the section offset rather than by the symbol.
16312
16313      However, if we're generating REL LO16 relocations, the offset is split
16314      between the LO16 and parterning high part relocation.  The linker will
16315      need to recalculate the complete offset in order to correctly identify
16316      the merge data.
16317
16318      The linker has traditionally not looked for the parterning high part
16319      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16320      placed anywhere.  Rather than break backwards compatibility by changing
16321      this, it seems better not to force the issue, and instead keep the
16322      original symbol.  This will work with either linker behavior.  */
16323   if ((lo16_reloc_p (fixp->fx_r_type)
16324        || reloc_needs_lo_p (fixp->fx_r_type))
16325       && HAVE_IN_PLACE_ADDENDS
16326       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16327     return 0;
16328
16329   /* There is no place to store an in-place offset for JALR relocations.
16330      Likewise an in-range offset of limited PC-relative relocations may
16331      overflow the in-place relocatable field if recalculated against the
16332      start address of the symbol's containing section.  */
16333   if (HAVE_IN_PLACE_ADDENDS
16334       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16335           || jalr_reloc_p (fixp->fx_r_type)))
16336     return 0;
16337
16338   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16339      to a floating-point stub.  The same is true for non-R_MIPS16_26
16340      relocations against MIPS16 functions; in this case, the stub becomes
16341      the function's canonical address.
16342
16343      Floating-point stubs are stored in unique .mips16.call.* or
16344      .mips16.fn.* sections.  If a stub T for function F is in section S,
16345      the first relocation in section S must be against F; this is how the
16346      linker determines the target function.  All relocations that might
16347      resolve to T must also be against F.  We therefore have the following
16348      restrictions, which are given in an intentionally-redundant way:
16349
16350        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16351           symbols.
16352
16353        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16354           if that stub might be used.
16355
16356        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16357           symbols.
16358
16359        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16360           that stub might be used.
16361
16362      There is a further restriction:
16363
16364        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16365           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16366           targets with in-place addends; the relocation field cannot
16367           encode the low bit.
16368
16369      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16370      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16371      such relocations on REL targets.
16372
16373      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16374      relocation against some symbol R, no relocation against R may be
16375      reduced.  (Note that this deals with (2) as well as (1) because
16376      relocations against global symbols will never be reduced on ELF
16377      targets.)  This approach is a little simpler than trying to detect
16378      stub sections, and gives the "all or nothing" per-symbol consistency
16379      that we have for MIPS16 symbols.  */
16380   if (fixp->fx_subsy == NULL
16381       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16382           || *symbol_get_tc (fixp->fx_addsy)
16383           || (HAVE_IN_PLACE_ADDENDS
16384               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16385               && jmp_reloc_p (fixp->fx_r_type))))
16386     return 0;
16387
16388   return 1;
16389 }
16390
16391 /* Translate internal representation of relocation info to BFD target
16392    format.  */
16393
16394 arelent **
16395 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16396 {
16397   static arelent *retval[4];
16398   arelent *reloc;
16399   bfd_reloc_code_real_type code;
16400
16401   memset (retval, 0, sizeof(retval));
16402   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16403   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16404   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16405   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16406
16407   if (fixp->fx_pcrel)
16408     {
16409       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16410                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16411                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16412                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16413                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16414
16415       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16416          Relocations want only the symbol offset.  */
16417       reloc->addend = fixp->fx_addnumber + reloc->address;
16418     }
16419   else
16420     reloc->addend = fixp->fx_addnumber;
16421
16422   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16423      entry to be used in the relocation's section offset.  */
16424   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16425     {
16426       reloc->address = reloc->addend;
16427       reloc->addend = 0;
16428     }
16429
16430   code = fixp->fx_r_type;
16431
16432   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16433   if (reloc->howto == NULL)
16434     {
16435       as_bad_where (fixp->fx_file, fixp->fx_line,
16436                     _("cannot represent %s relocation in this object file"
16437                       " format"),
16438                     bfd_get_reloc_code_name (code));
16439       retval[0] = NULL;
16440     }
16441
16442   return retval;
16443 }
16444
16445 /* Relax a machine dependent frag.  This returns the amount by which
16446    the current size of the frag should change.  */
16447
16448 int
16449 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16450 {
16451   if (RELAX_BRANCH_P (fragp->fr_subtype))
16452     {
16453       offsetT old_var = fragp->fr_var;
16454
16455       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16456
16457       return fragp->fr_var - old_var;
16458     }
16459
16460   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16461     {
16462       offsetT old_var = fragp->fr_var;
16463       offsetT new_var = 4;
16464
16465       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16466         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16467       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16468         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16469       fragp->fr_var = new_var;
16470
16471       return new_var - old_var;
16472     }
16473
16474   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16475     return 0;
16476
16477   if (mips16_extended_frag (fragp, NULL, stretch))
16478     {
16479       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16480         return 0;
16481       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16482       return 2;
16483     }
16484   else
16485     {
16486       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16487         return 0;
16488       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16489       return -2;
16490     }
16491
16492   return 0;
16493 }
16494
16495 /* Convert a machine dependent frag.  */
16496
16497 void
16498 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16499 {
16500   if (RELAX_BRANCH_P (fragp->fr_subtype))
16501     {
16502       char *buf;
16503       unsigned long insn;
16504       expressionS exp;
16505       fixS *fixp;
16506
16507       buf = fragp->fr_literal + fragp->fr_fix;
16508       insn = read_insn (buf);
16509
16510       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16511         {
16512           /* We generate a fixup instead of applying it right now
16513              because, if there are linker relaxations, we're going to
16514              need the relocations.  */
16515           exp.X_op = O_symbol;
16516           exp.X_add_symbol = fragp->fr_symbol;
16517           exp.X_add_number = fragp->fr_offset;
16518
16519           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16520                               BFD_RELOC_16_PCREL_S2);
16521           fixp->fx_file = fragp->fr_file;
16522           fixp->fx_line = fragp->fr_line;
16523
16524           buf = write_insn (buf, insn);
16525         }
16526       else
16527         {
16528           int i;
16529
16530           as_warn_where (fragp->fr_file, fragp->fr_line,
16531                          _("relaxed out-of-range branch into a jump"));
16532
16533           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16534             goto uncond;
16535
16536           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16537             {
16538               /* Reverse the branch.  */
16539               switch ((insn >> 28) & 0xf)
16540                 {
16541                 case 4:
16542                   /* bc[0-3][tf]l? instructions can have the condition
16543                      reversed by tweaking a single TF bit, and their
16544                      opcodes all have 0x4???????.  */
16545                   gas_assert ((insn & 0xf3e00000) == 0x41000000);
16546                   insn ^= 0x00010000;
16547                   break;
16548
16549                 case 0:
16550                   /* bltz       0x04000000      bgez    0x04010000
16551                      bltzal     0x04100000      bgezal  0x04110000  */
16552                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16553                   insn ^= 0x00010000;
16554                   break;
16555
16556                 case 1:
16557                   /* beq        0x10000000      bne     0x14000000
16558                      blez       0x18000000      bgtz    0x1c000000  */
16559                   insn ^= 0x04000000;
16560                   break;
16561
16562                 default:
16563                   abort ();
16564                 }
16565             }
16566
16567           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16568             {
16569               /* Clear the and-link bit.  */
16570               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16571
16572               /* bltzal         0x04100000      bgezal  0x04110000
16573                  bltzall        0x04120000      bgezall 0x04130000  */
16574               insn &= ~0x00100000;
16575             }
16576
16577           /* Branch over the branch (if the branch was likely) or the
16578              full jump (not likely case).  Compute the offset from the
16579              current instruction to branch to.  */
16580           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16581             i = 16;
16582           else
16583             {
16584               /* How many bytes in instructions we've already emitted?  */
16585               i = buf - fragp->fr_literal - fragp->fr_fix;
16586               /* How many bytes in instructions from here to the end?  */
16587               i = fragp->fr_var - i;
16588             }
16589           /* Convert to instruction count.  */
16590           i >>= 2;
16591           /* Branch counts from the next instruction.  */
16592           i--;
16593           insn |= i;
16594           /* Branch over the jump.  */
16595           buf = write_insn (buf, insn);
16596
16597           /* nop */
16598           buf = write_insn (buf, 0);
16599
16600           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16601             {
16602               /* beql $0, $0, 2f */
16603               insn = 0x50000000;
16604               /* Compute the PC offset from the current instruction to
16605                  the end of the variable frag.  */
16606               /* How many bytes in instructions we've already emitted?  */
16607               i = buf - fragp->fr_literal - fragp->fr_fix;
16608               /* How many bytes in instructions from here to the end?  */
16609               i = fragp->fr_var - i;
16610               /* Convert to instruction count.  */
16611               i >>= 2;
16612               /* Don't decrement i, because we want to branch over the
16613                  delay slot.  */
16614               insn |= i;
16615
16616               buf = write_insn (buf, insn);
16617               buf = write_insn (buf, 0);
16618             }
16619
16620         uncond:
16621           if (mips_pic == NO_PIC)
16622             {
16623               /* j or jal.  */
16624               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16625                       ? 0x0c000000 : 0x08000000);
16626               exp.X_op = O_symbol;
16627               exp.X_add_symbol = fragp->fr_symbol;
16628               exp.X_add_number = fragp->fr_offset;
16629
16630               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16631                                   FALSE, BFD_RELOC_MIPS_JMP);
16632               fixp->fx_file = fragp->fr_file;
16633               fixp->fx_line = fragp->fr_line;
16634
16635               buf = write_insn (buf, insn);
16636             }
16637           else
16638             {
16639               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16640
16641               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16642               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16643               insn |= at << OP_SH_RT;
16644               exp.X_op = O_symbol;
16645               exp.X_add_symbol = fragp->fr_symbol;
16646               exp.X_add_number = fragp->fr_offset;
16647
16648               if (fragp->fr_offset)
16649                 {
16650                   exp.X_add_symbol = make_expr_symbol (&exp);
16651                   exp.X_add_number = 0;
16652                 }
16653
16654               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16655                                   FALSE, BFD_RELOC_MIPS_GOT16);
16656               fixp->fx_file = fragp->fr_file;
16657               fixp->fx_line = fragp->fr_line;
16658
16659               buf = write_insn (buf, insn);
16660
16661               if (mips_opts.isa == ISA_MIPS1)
16662                 /* nop */
16663                 buf = write_insn (buf, 0);
16664
16665               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16666               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16667               insn |= at << OP_SH_RS | at << OP_SH_RT;
16668
16669               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16670                                   FALSE, BFD_RELOC_LO16);
16671               fixp->fx_file = fragp->fr_file;
16672               fixp->fx_line = fragp->fr_line;
16673
16674               buf = write_insn (buf, insn);
16675
16676               /* j(al)r $at.  */
16677               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16678                 insn = 0x0000f809;
16679               else
16680                 insn = 0x00000008;
16681               insn |= at << OP_SH_RS;
16682
16683               buf = write_insn (buf, insn);
16684             }
16685         }
16686
16687       fragp->fr_fix += fragp->fr_var;
16688       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16689       return;
16690     }
16691
16692   /* Relax microMIPS branches.  */
16693   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16694     {
16695       char *buf = fragp->fr_literal + fragp->fr_fix;
16696       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16697       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16698       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16699       bfd_boolean short_ds;
16700       unsigned long insn;
16701       expressionS exp;
16702       fixS *fixp;
16703
16704       exp.X_op = O_symbol;
16705       exp.X_add_symbol = fragp->fr_symbol;
16706       exp.X_add_number = fragp->fr_offset;
16707
16708       fragp->fr_fix += fragp->fr_var;
16709
16710       /* Handle 16-bit branches that fit or are forced to fit.  */
16711       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16712         {
16713           /* We generate a fixup instead of applying it right now,
16714              because if there is linker relaxation, we're going to
16715              need the relocations.  */
16716           if (type == 'D')
16717             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16718                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16719           else if (type == 'E')
16720             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16721                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16722           else
16723             abort ();
16724
16725           fixp->fx_file = fragp->fr_file;
16726           fixp->fx_line = fragp->fr_line;
16727
16728           /* These relocations can have an addend that won't fit in
16729              2 octets.  */
16730           fixp->fx_no_overflow = 1;
16731
16732           return;
16733         }
16734
16735       /* Handle 32-bit branches that fit or are forced to fit.  */
16736       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16737           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16738         {
16739           /* We generate a fixup instead of applying it right now,
16740              because if there is linker relaxation, we're going to
16741              need the relocations.  */
16742           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16743                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16744           fixp->fx_file = fragp->fr_file;
16745           fixp->fx_line = fragp->fr_line;
16746
16747           if (type == 0)
16748             return;
16749         }
16750
16751       /* Relax 16-bit branches to 32-bit branches.  */
16752       if (type != 0)
16753         {
16754           insn = read_compressed_insn (buf, 2);
16755
16756           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16757             insn = 0x94000000;                          /* beq  */
16758           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16759             {
16760               unsigned long regno;
16761
16762               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16763               regno = micromips_to_32_reg_d_map [regno];
16764               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16765               insn |= regno << MICROMIPSOP_SH_RS;
16766             }
16767           else
16768             abort ();
16769
16770           /* Nothing else to do, just write it out.  */
16771           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16772               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16773             {
16774               buf = write_compressed_insn (buf, insn, 4);
16775               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16776               return;
16777             }
16778         }
16779       else
16780         insn = read_compressed_insn (buf, 4);
16781
16782       /* Relax 32-bit branches to a sequence of instructions.  */
16783       as_warn_where (fragp->fr_file, fragp->fr_line,
16784                      _("relaxed out-of-range branch into a jump"));
16785
16786       /* Set the short-delay-slot bit.  */
16787       short_ds = al && (insn & 0x02000000) != 0;
16788
16789       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16790         {
16791           symbolS *l;
16792
16793           /* Reverse the branch.  */
16794           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16795               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16796             insn ^= 0x20000000;
16797           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16798                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16799                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16800                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16801                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16802                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16803                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16804                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16805                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16806                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16807             insn ^= 0x00400000;
16808           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16809                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16810                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16811                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16812             insn ^= 0x00200000;
16813           else
16814             abort ();
16815
16816           if (al)
16817             {
16818               /* Clear the and-link and short-delay-slot bits.  */
16819               gas_assert ((insn & 0xfda00000) == 0x40200000);
16820
16821               /* bltzal  0x40200000     bgezal  0x40600000  */
16822               /* bltzals 0x42200000     bgezals 0x42600000  */
16823               insn &= ~0x02200000;
16824             }
16825
16826           /* Make a label at the end for use with the branch.  */
16827           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16828           micromips_label_inc ();
16829           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16830
16831           /* Refer to it.  */
16832           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16833                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16834           fixp->fx_file = fragp->fr_file;
16835           fixp->fx_line = fragp->fr_line;
16836
16837           /* Branch over the jump.  */
16838           buf = write_compressed_insn (buf, insn, 4);
16839           if (!compact)
16840             /* nop */
16841             buf = write_compressed_insn (buf, 0x0c00, 2);
16842         }
16843
16844       if (mips_pic == NO_PIC)
16845         {
16846           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16847
16848           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16849           insn = al ? jal : 0xd4000000;
16850
16851           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16852                               BFD_RELOC_MICROMIPS_JMP);
16853           fixp->fx_file = fragp->fr_file;
16854           fixp->fx_line = fragp->fr_line;
16855
16856           buf = write_compressed_insn (buf, insn, 4);
16857           if (compact)
16858             /* nop */
16859             buf = write_compressed_insn (buf, 0x0c00, 2);
16860         }
16861       else
16862         {
16863           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
16864           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
16865           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
16866
16867           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
16868           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
16869           insn |= at << MICROMIPSOP_SH_RT;
16870
16871           if (exp.X_add_number)
16872             {
16873               exp.X_add_symbol = make_expr_symbol (&exp);
16874               exp.X_add_number = 0;
16875             }
16876
16877           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16878                               BFD_RELOC_MICROMIPS_GOT16);
16879           fixp->fx_file = fragp->fr_file;
16880           fixp->fx_line = fragp->fr_line;
16881
16882           buf = write_compressed_insn (buf, insn, 4);
16883
16884           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
16885           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
16886           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
16887
16888           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16889                               BFD_RELOC_MICROMIPS_LO16);
16890           fixp->fx_file = fragp->fr_file;
16891           fixp->fx_line = fragp->fr_line;
16892
16893           buf = write_compressed_insn (buf, insn, 4);
16894
16895           /* jr/jrc/jalr/jalrs $at  */
16896           insn = al ? jalr : jr;
16897           insn |= at << MICROMIPSOP_SH_MJ;
16898
16899           buf = write_compressed_insn (buf, insn, 2);
16900         }
16901
16902       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16903       return;
16904     }
16905
16906   if (RELAX_MIPS16_P (fragp->fr_subtype))
16907     {
16908       int type;
16909       const struct mips_int_operand *operand;
16910       offsetT val;
16911       char *buf;
16912       unsigned int user_length, length;
16913       unsigned long insn;
16914       bfd_boolean ext;
16915
16916       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16917       operand = mips16_immed_operand (type, FALSE);
16918
16919       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
16920       val = resolve_symbol_value (fragp->fr_symbol);
16921       if (operand->root.type == OP_PCREL)
16922         {
16923           const struct mips_pcrel_operand *pcrel_op;
16924           addressT addr;
16925
16926           pcrel_op = (const struct mips_pcrel_operand *) operand;
16927           addr = fragp->fr_address + fragp->fr_fix;
16928
16929           /* The rules for the base address of a PC relative reloc are
16930              complicated; see mips16_extended_frag.  */
16931           if (pcrel_op->include_isa_bit)
16932             {
16933               addr += 2;
16934               if (ext)
16935                 addr += 2;
16936               /* Ignore the low bit in the target, since it will be
16937                  set for a text label.  */
16938               val &= -2;
16939             }
16940           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16941             addr -= 4;
16942           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16943             addr -= 2;
16944
16945           addr &= -(1 << pcrel_op->align_log2);
16946           val -= addr;
16947
16948           /* Make sure the section winds up with the alignment we have
16949              assumed.  */
16950           if (operand->shift > 0)
16951             record_alignment (asec, operand->shift);
16952         }
16953
16954       if (ext
16955           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
16956               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
16957         as_warn_where (fragp->fr_file, fragp->fr_line,
16958                        _("extended instruction in delay slot"));
16959
16960       buf = fragp->fr_literal + fragp->fr_fix;
16961
16962       insn = read_compressed_insn (buf, 2);
16963       if (ext)
16964         insn |= MIPS16_EXTEND;
16965
16966       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16967         user_length = 4;
16968       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16969         user_length = 2;
16970       else
16971         user_length = 0;
16972
16973       mips16_immed (fragp->fr_file, fragp->fr_line, type,
16974                     BFD_RELOC_UNUSED, val, user_length, &insn);
16975
16976       length = (ext ? 4 : 2);
16977       gas_assert (mips16_opcode_length (insn) == length);
16978       write_compressed_insn (buf, insn, length);
16979       fragp->fr_fix += length;
16980     }
16981   else
16982     {
16983       relax_substateT subtype = fragp->fr_subtype;
16984       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
16985       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
16986       int first, second;
16987       fixS *fixp;
16988
16989       first = RELAX_FIRST (subtype);
16990       second = RELAX_SECOND (subtype);
16991       fixp = (fixS *) fragp->fr_opcode;
16992
16993       /* If the delay slot chosen does not match the size of the instruction,
16994          then emit a warning.  */
16995       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
16996            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
16997         {
16998           relax_substateT s;
16999           const char *msg;
17000
17001           s = subtype & (RELAX_DELAY_SLOT_16BIT
17002                          | RELAX_DELAY_SLOT_SIZE_FIRST
17003                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17004           msg = macro_warning (s);
17005           if (msg != NULL)
17006             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17007           subtype &= ~s;
17008         }
17009
17010       /* Possibly emit a warning if we've chosen the longer option.  */
17011       if (use_second == second_longer)
17012         {
17013           relax_substateT s;
17014           const char *msg;
17015
17016           s = (subtype
17017                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17018           msg = macro_warning (s);
17019           if (msg != NULL)
17020             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17021           subtype &= ~s;
17022         }
17023
17024       /* Go through all the fixups for the first sequence.  Disable them
17025          (by marking them as done) if we're going to use the second
17026          sequence instead.  */
17027       while (fixp
17028              && fixp->fx_frag == fragp
17029              && fixp->fx_where < fragp->fr_fix - second)
17030         {
17031           if (subtype & RELAX_USE_SECOND)
17032             fixp->fx_done = 1;
17033           fixp = fixp->fx_next;
17034         }
17035
17036       /* Go through the fixups for the second sequence.  Disable them if
17037          we're going to use the first sequence, otherwise adjust their
17038          addresses to account for the relaxation.  */
17039       while (fixp && fixp->fx_frag == fragp)
17040         {
17041           if (subtype & RELAX_USE_SECOND)
17042             fixp->fx_where -= first;
17043           else
17044             fixp->fx_done = 1;
17045           fixp = fixp->fx_next;
17046         }
17047
17048       /* Now modify the frag contents.  */
17049       if (subtype & RELAX_USE_SECOND)
17050         {
17051           char *start;
17052
17053           start = fragp->fr_literal + fragp->fr_fix - first - second;
17054           memmove (start, start + first, second);
17055           fragp->fr_fix -= first;
17056         }
17057       else
17058         fragp->fr_fix -= second;
17059     }
17060 }
17061
17062 /* This function is called after the relocs have been generated.
17063    We've been storing mips16 text labels as odd.  Here we convert them
17064    back to even for the convenience of the debugger.  */
17065
17066 void
17067 mips_frob_file_after_relocs (void)
17068 {
17069   asymbol **syms;
17070   unsigned int count, i;
17071
17072   syms = bfd_get_outsymbols (stdoutput);
17073   count = bfd_get_symcount (stdoutput);
17074   for (i = 0; i < count; i++, syms++)
17075     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17076         && ((*syms)->value & 1) != 0)
17077       {
17078         (*syms)->value &= ~1;
17079         /* If the symbol has an odd size, it was probably computed
17080            incorrectly, so adjust that as well.  */
17081         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17082           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17083       }
17084 }
17085
17086 /* This function is called whenever a label is defined, including fake
17087    labels instantiated off the dot special symbol.  It is used when
17088    handling branch delays; if a branch has a label, we assume we cannot
17089    move it.  This also bumps the value of the symbol by 1 in compressed
17090    code.  */
17091
17092 static void
17093 mips_record_label (symbolS *sym)
17094 {
17095   segment_info_type *si = seg_info (now_seg);
17096   struct insn_label_list *l;
17097
17098   if (free_insn_labels == NULL)
17099     l = (struct insn_label_list *) xmalloc (sizeof *l);
17100   else
17101     {
17102       l = free_insn_labels;
17103       free_insn_labels = l->next;
17104     }
17105
17106   l->label = sym;
17107   l->next = si->label_list;
17108   si->label_list = l;
17109 }
17110
17111 /* This function is called as tc_frob_label() whenever a label is defined
17112    and adds a DWARF-2 record we only want for true labels.  */
17113
17114 void
17115 mips_define_label (symbolS *sym)
17116 {
17117   mips_record_label (sym);
17118   dwarf2_emit_label (sym);
17119 }
17120
17121 /* This function is called by tc_new_dot_label whenever a new dot symbol
17122    is defined.  */
17123
17124 void
17125 mips_add_dot_label (symbolS *sym)
17126 {
17127   mips_record_label (sym);
17128   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17129     mips_compressed_mark_label (sym);
17130 }
17131 \f
17132 /* Some special processing for a MIPS ELF file.  */
17133
17134 void
17135 mips_elf_final_processing (void)
17136 {
17137   /* Write out the register information.  */
17138   if (mips_abi != N64_ABI)
17139     {
17140       Elf32_RegInfo s;
17141
17142       s.ri_gprmask = mips_gprmask;
17143       s.ri_cprmask[0] = mips_cprmask[0];
17144       s.ri_cprmask[1] = mips_cprmask[1];
17145       s.ri_cprmask[2] = mips_cprmask[2];
17146       s.ri_cprmask[3] = mips_cprmask[3];
17147       /* The gp_value field is set by the MIPS ELF backend.  */
17148
17149       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17150                                        ((Elf32_External_RegInfo *)
17151                                         mips_regmask_frag));
17152     }
17153   else
17154     {
17155       Elf64_Internal_RegInfo s;
17156
17157       s.ri_gprmask = mips_gprmask;
17158       s.ri_pad = 0;
17159       s.ri_cprmask[0] = mips_cprmask[0];
17160       s.ri_cprmask[1] = mips_cprmask[1];
17161       s.ri_cprmask[2] = mips_cprmask[2];
17162       s.ri_cprmask[3] = mips_cprmask[3];
17163       /* The gp_value field is set by the MIPS ELF backend.  */
17164
17165       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17166                                        ((Elf64_External_RegInfo *)
17167                                         mips_regmask_frag));
17168     }
17169
17170   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17171      sort of BFD interface for this.  */
17172   if (mips_any_noreorder)
17173     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17174   if (mips_pic != NO_PIC)
17175     {
17176       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17177       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17178     }
17179   if (mips_abicalls)
17180     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17181
17182   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17183      defined at present; this might need to change in future.  */
17184   if (file_ase_mips16)
17185     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17186   if (file_ase_micromips)
17187     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17188   if (file_ase & ASE_MDMX)
17189     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17190
17191   /* Set the MIPS ELF ABI flags.  */
17192   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17193     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17194   else if (mips_abi == O64_ABI)
17195     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17196   else if (mips_abi == EABI_ABI)
17197     {
17198       if (!file_mips_gp32)
17199         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17200       else
17201         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17202     }
17203   else if (mips_abi == N32_ABI)
17204     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17205
17206   /* Nothing to do for N64_ABI.  */
17207
17208   if (mips_32bitmode)
17209     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17210
17211   if (mips_flag_nan2008)
17212     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17213
17214 #if 0 /* XXX FIXME */
17215   /* 32 bit code with 64 bit FP registers.  */
17216   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17217     elf_elfheader (stdoutput)->e_flags |= ???;
17218 #endif
17219 }
17220 \f
17221 typedef struct proc {
17222   symbolS *func_sym;
17223   symbolS *func_end_sym;
17224   unsigned long reg_mask;
17225   unsigned long reg_offset;
17226   unsigned long fpreg_mask;
17227   unsigned long fpreg_offset;
17228   unsigned long frame_offset;
17229   unsigned long frame_reg;
17230   unsigned long pc_reg;
17231 } procS;
17232
17233 static procS cur_proc;
17234 static procS *cur_proc_ptr;
17235 static int numprocs;
17236
17237 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17238    as "2", and a normal nop as "0".  */
17239
17240 #define NOP_OPCODE_MIPS         0
17241 #define NOP_OPCODE_MIPS16       1
17242 #define NOP_OPCODE_MICROMIPS    2
17243
17244 char
17245 mips_nop_opcode (void)
17246 {
17247   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17248     return NOP_OPCODE_MICROMIPS;
17249   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17250     return NOP_OPCODE_MIPS16;
17251   else
17252     return NOP_OPCODE_MIPS;
17253 }
17254
17255 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17256    32-bit microMIPS NOPs here (if applicable).  */
17257
17258 void
17259 mips_handle_align (fragS *fragp)
17260 {
17261   char nop_opcode;
17262   char *p;
17263   int bytes, size, excess;
17264   valueT opcode;
17265
17266   if (fragp->fr_type != rs_align_code)
17267     return;
17268
17269   p = fragp->fr_literal + fragp->fr_fix;
17270   nop_opcode = *p;
17271   switch (nop_opcode)
17272     {
17273     case NOP_OPCODE_MICROMIPS:
17274       opcode = micromips_nop32_insn.insn_opcode;
17275       size = 4;
17276       break;
17277     case NOP_OPCODE_MIPS16:
17278       opcode = mips16_nop_insn.insn_opcode;
17279       size = 2;
17280       break;
17281     case NOP_OPCODE_MIPS:
17282     default:
17283       opcode = nop_insn.insn_opcode;
17284       size = 4;
17285       break;
17286     }
17287
17288   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17289   excess = bytes % size;
17290
17291   /* Handle the leading part if we're not inserting a whole number of
17292      instructions, and make it the end of the fixed part of the frag.
17293      Try to fit in a short microMIPS NOP if applicable and possible,
17294      and use zeroes otherwise.  */
17295   gas_assert (excess < 4);
17296   fragp->fr_fix += excess;
17297   switch (excess)
17298     {
17299     case 3:
17300       *p++ = '\0';
17301       /* Fall through.  */
17302     case 2:
17303       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17304         {
17305           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17306           break;
17307         }
17308       *p++ = '\0';
17309       /* Fall through.  */
17310     case 1:
17311       *p++ = '\0';
17312       /* Fall through.  */
17313     case 0:
17314       break;
17315     }
17316
17317   md_number_to_chars (p, opcode, size);
17318   fragp->fr_var = size;
17319 }
17320
17321 static void
17322 md_obj_begin (void)
17323 {
17324 }
17325
17326 static void
17327 md_obj_end (void)
17328 {
17329   /* Check for premature end, nesting errors, etc.  */
17330   if (cur_proc_ptr)
17331     as_warn (_("missing .end at end of assembly"));
17332 }
17333
17334 static long
17335 get_number (void)
17336 {
17337   int negative = 0;
17338   long val = 0;
17339
17340   if (*input_line_pointer == '-')
17341     {
17342       ++input_line_pointer;
17343       negative = 1;
17344     }
17345   if (!ISDIGIT (*input_line_pointer))
17346     as_bad (_("expected simple number"));
17347   if (input_line_pointer[0] == '0')
17348     {
17349       if (input_line_pointer[1] == 'x')
17350         {
17351           input_line_pointer += 2;
17352           while (ISXDIGIT (*input_line_pointer))
17353             {
17354               val <<= 4;
17355               val |= hex_value (*input_line_pointer++);
17356             }
17357           return negative ? -val : val;
17358         }
17359       else
17360         {
17361           ++input_line_pointer;
17362           while (ISDIGIT (*input_line_pointer))
17363             {
17364               val <<= 3;
17365               val |= *input_line_pointer++ - '0';
17366             }
17367           return negative ? -val : val;
17368         }
17369     }
17370   if (!ISDIGIT (*input_line_pointer))
17371     {
17372       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17373               *input_line_pointer, *input_line_pointer);
17374       as_warn (_("invalid number"));
17375       return -1;
17376     }
17377   while (ISDIGIT (*input_line_pointer))
17378     {
17379       val *= 10;
17380       val += *input_line_pointer++ - '0';
17381     }
17382   return negative ? -val : val;
17383 }
17384
17385 /* The .file directive; just like the usual .file directive, but there
17386    is an initial number which is the ECOFF file index.  In the non-ECOFF
17387    case .file implies DWARF-2.  */
17388
17389 static void
17390 s_mips_file (int x ATTRIBUTE_UNUSED)
17391 {
17392   static int first_file_directive = 0;
17393
17394   if (ECOFF_DEBUGGING)
17395     {
17396       get_number ();
17397       s_app_file (0);
17398     }
17399   else
17400     {
17401       char *filename;
17402
17403       filename = dwarf2_directive_file (0);
17404
17405       /* Versions of GCC up to 3.1 start files with a ".file"
17406          directive even for stabs output.  Make sure that this
17407          ".file" is handled.  Note that you need a version of GCC
17408          after 3.1 in order to support DWARF-2 on MIPS.  */
17409       if (filename != NULL && ! first_file_directive)
17410         {
17411           (void) new_logical_line (filename, -1);
17412           s_app_file_string (filename, 0);
17413         }
17414       first_file_directive = 1;
17415     }
17416 }
17417
17418 /* The .loc directive, implying DWARF-2.  */
17419
17420 static void
17421 s_mips_loc (int x ATTRIBUTE_UNUSED)
17422 {
17423   if (!ECOFF_DEBUGGING)
17424     dwarf2_directive_loc (0);
17425 }
17426
17427 /* The .end directive.  */
17428
17429 static void
17430 s_mips_end (int x ATTRIBUTE_UNUSED)
17431 {
17432   symbolS *p;
17433
17434   /* Following functions need their own .frame and .cprestore directives.  */
17435   mips_frame_reg_valid = 0;
17436   mips_cprestore_valid = 0;
17437
17438   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17439     {
17440       p = get_symbol ();
17441       demand_empty_rest_of_line ();
17442     }
17443   else
17444     p = NULL;
17445
17446   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17447     as_warn (_(".end not in text section"));
17448
17449   if (!cur_proc_ptr)
17450     {
17451       as_warn (_(".end directive without a preceding .ent directive"));
17452       demand_empty_rest_of_line ();
17453       return;
17454     }
17455
17456   if (p != NULL)
17457     {
17458       gas_assert (S_GET_NAME (p));
17459       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17460         as_warn (_(".end symbol does not match .ent symbol"));
17461
17462       if (debug_type == DEBUG_STABS)
17463         stabs_generate_asm_endfunc (S_GET_NAME (p),
17464                                     S_GET_NAME (p));
17465     }
17466   else
17467     as_warn (_(".end directive missing or unknown symbol"));
17468
17469   /* Create an expression to calculate the size of the function.  */
17470   if (p && cur_proc_ptr)
17471     {
17472       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17473       expressionS *exp = xmalloc (sizeof (expressionS));
17474
17475       obj->size = exp;
17476       exp->X_op = O_subtract;
17477       exp->X_add_symbol = symbol_temp_new_now ();
17478       exp->X_op_symbol = p;
17479       exp->X_add_number = 0;
17480
17481       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17482     }
17483
17484   /* Generate a .pdr section.  */
17485   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17486     {
17487       segT saved_seg = now_seg;
17488       subsegT saved_subseg = now_subseg;
17489       expressionS exp;
17490       char *fragp;
17491
17492 #ifdef md_flush_pending_output
17493       md_flush_pending_output ();
17494 #endif
17495
17496       gas_assert (pdr_seg);
17497       subseg_set (pdr_seg, 0);
17498
17499       /* Write the symbol.  */
17500       exp.X_op = O_symbol;
17501       exp.X_add_symbol = p;
17502       exp.X_add_number = 0;
17503       emit_expr (&exp, 4);
17504
17505       fragp = frag_more (7 * 4);
17506
17507       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17508       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17509       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17510       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17511       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17512       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17513       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17514
17515       subseg_set (saved_seg, saved_subseg);
17516     }
17517
17518   cur_proc_ptr = NULL;
17519 }
17520
17521 /* The .aent and .ent directives.  */
17522
17523 static void
17524 s_mips_ent (int aent)
17525 {
17526   symbolS *symbolP;
17527
17528   symbolP = get_symbol ();
17529   if (*input_line_pointer == ',')
17530     ++input_line_pointer;
17531   SKIP_WHITESPACE ();
17532   if (ISDIGIT (*input_line_pointer)
17533       || *input_line_pointer == '-')
17534     get_number ();
17535
17536   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17537     as_warn (_(".ent or .aent not in text section"));
17538
17539   if (!aent && cur_proc_ptr)
17540     as_warn (_("missing .end"));
17541
17542   if (!aent)
17543     {
17544       /* This function needs its own .frame and .cprestore directives.  */
17545       mips_frame_reg_valid = 0;
17546       mips_cprestore_valid = 0;
17547
17548       cur_proc_ptr = &cur_proc;
17549       memset (cur_proc_ptr, '\0', sizeof (procS));
17550
17551       cur_proc_ptr->func_sym = symbolP;
17552
17553       ++numprocs;
17554
17555       if (debug_type == DEBUG_STABS)
17556         stabs_generate_asm_func (S_GET_NAME (symbolP),
17557                                  S_GET_NAME (symbolP));
17558     }
17559
17560   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17561
17562   demand_empty_rest_of_line ();
17563 }
17564
17565 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17566    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17567    s_mips_frame is used so that we can set the PDR information correctly.
17568    We can't use the ecoff routines because they make reference to the ecoff
17569    symbol table (in the mdebug section).  */
17570
17571 static void
17572 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17573 {
17574   if (ECOFF_DEBUGGING)
17575     s_ignore (ignore);
17576   else
17577     {
17578       long val;
17579
17580       if (cur_proc_ptr == (procS *) NULL)
17581         {
17582           as_warn (_(".frame outside of .ent"));
17583           demand_empty_rest_of_line ();
17584           return;
17585         }
17586
17587       cur_proc_ptr->frame_reg = tc_get_register (1);
17588
17589       SKIP_WHITESPACE ();
17590       if (*input_line_pointer++ != ','
17591           || get_absolute_expression_and_terminator (&val) != ',')
17592         {
17593           as_warn (_("bad .frame directive"));
17594           --input_line_pointer;
17595           demand_empty_rest_of_line ();
17596           return;
17597         }
17598
17599       cur_proc_ptr->frame_offset = val;
17600       cur_proc_ptr->pc_reg = tc_get_register (0);
17601
17602       demand_empty_rest_of_line ();
17603     }
17604 }
17605
17606 /* The .fmask and .mask directives. If the mdebug section is present
17607    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17608    embedded targets, s_mips_mask is used so that we can set the PDR
17609    information correctly. We can't use the ecoff routines because they
17610    make reference to the ecoff symbol table (in the mdebug section).  */
17611
17612 static void
17613 s_mips_mask (int reg_type)
17614 {
17615   if (ECOFF_DEBUGGING)
17616     s_ignore (reg_type);
17617   else
17618     {
17619       long mask, off;
17620
17621       if (cur_proc_ptr == (procS *) NULL)
17622         {
17623           as_warn (_(".mask/.fmask outside of .ent"));
17624           demand_empty_rest_of_line ();
17625           return;
17626         }
17627
17628       if (get_absolute_expression_and_terminator (&mask) != ',')
17629         {
17630           as_warn (_("bad .mask/.fmask directive"));
17631           --input_line_pointer;
17632           demand_empty_rest_of_line ();
17633           return;
17634         }
17635
17636       off = get_absolute_expression ();
17637
17638       if (reg_type == 'F')
17639         {
17640           cur_proc_ptr->fpreg_mask = mask;
17641           cur_proc_ptr->fpreg_offset = off;
17642         }
17643       else
17644         {
17645           cur_proc_ptr->reg_mask = mask;
17646           cur_proc_ptr->reg_offset = off;
17647         }
17648
17649       demand_empty_rest_of_line ();
17650     }
17651 }
17652
17653 /* A table describing all the processors gas knows about.  Names are
17654    matched in the order listed.
17655
17656    To ease comparison, please keep this table in the same order as
17657    gcc's mips_cpu_info_table[].  */
17658 static const struct mips_cpu_info mips_cpu_info_table[] =
17659 {
17660   /* Entries for generic ISAs */
17661   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17662   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17663   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17664   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17665   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17666   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17667   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17668   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17669   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17670
17671   /* MIPS I */
17672   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17673   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17674   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17675
17676   /* MIPS II */
17677   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17678
17679   /* MIPS III */
17680   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17681   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17682   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17683   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17684   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17685   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17686   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17687   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17688   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17689   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17690   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17691   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17692   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17693   /* ST Microelectronics Loongson 2E and 2F cores */
17694   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17695   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17696
17697   /* MIPS IV */
17698   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17699   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17700   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17701   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17702   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17703   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17704   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17705   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17706   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17707   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17708   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17709   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17710   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17711   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17712   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17713
17714   /* MIPS 32 */
17715   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17716   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17717   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17718   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17719
17720   /* MIPS 32 Release 2 */
17721   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17722   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17723   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17724   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17725   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17726   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17727   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17728   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17729   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17730                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17731   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17732                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17733   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17734   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17735   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17736   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17737   /* Deprecated forms of the above.  */
17738   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17739   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17740   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17741   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17742   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17743   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17744   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17745   /* Deprecated forms of the above.  */
17746   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17747   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17748   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17749   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17750   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17751   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17752   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17753   /* Deprecated forms of the above.  */
17754   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17755   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17756   /* 34Kn is a 34kc without DSP.  */
17757   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17758   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17759   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17760   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17761   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17762   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17763   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17764   /* Deprecated forms of the above.  */
17765   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17766   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17767   /* 1004K cores are multiprocessor versions of the 34K.  */
17768   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17769   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17770   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17771   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17772
17773   /* MIPS 64 */
17774   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17775   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17776   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17777   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17778
17779   /* Broadcom SB-1 CPU core */
17780   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17781   /* Broadcom SB-1A CPU core */
17782   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17783   
17784   { "loongson3a",     0, 0,                     ISA_MIPS64,   CPU_LOONGSON_3A },
17785
17786   /* MIPS 64 Release 2 */
17787
17788   /* Cavium Networks Octeon CPU core */
17789   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17790   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17791   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17792
17793   /* RMI Xlr */
17794   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17795
17796   /* Broadcom XLP.
17797      XLP is mostly like XLR, with the prominent exception that it is
17798      MIPS64R2 rather than MIPS64.  */
17799   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17800
17801   /* End marker */
17802   { NULL, 0, 0, 0, 0 }
17803 };
17804
17805
17806 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17807    with a final "000" replaced by "k".  Ignore case.
17808
17809    Note: this function is shared between GCC and GAS.  */
17810
17811 static bfd_boolean
17812 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17813 {
17814   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17815     given++, canonical++;
17816
17817   return ((*given == 0 && *canonical == 0)
17818           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17819 }
17820
17821
17822 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17823    CPU name.  We've traditionally allowed a lot of variation here.
17824
17825    Note: this function is shared between GCC and GAS.  */
17826
17827 static bfd_boolean
17828 mips_matching_cpu_name_p (const char *canonical, const char *given)
17829 {
17830   /* First see if the name matches exactly, or with a final "000"
17831      turned into "k".  */
17832   if (mips_strict_matching_cpu_name_p (canonical, given))
17833     return TRUE;
17834
17835   /* If not, try comparing based on numerical designation alone.
17836      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17837   if (TOLOWER (*given) == 'r')
17838     given++;
17839   if (!ISDIGIT (*given))
17840     return FALSE;
17841
17842   /* Skip over some well-known prefixes in the canonical name,
17843      hoping to find a number there too.  */
17844   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17845     canonical += 2;
17846   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17847     canonical += 2;
17848   else if (TOLOWER (canonical[0]) == 'r')
17849     canonical += 1;
17850
17851   return mips_strict_matching_cpu_name_p (canonical, given);
17852 }
17853
17854
17855 /* Parse an option that takes the name of a processor as its argument.
17856    OPTION is the name of the option and CPU_STRING is the argument.
17857    Return the corresponding processor enumeration if the CPU_STRING is
17858    recognized, otherwise report an error and return null.
17859
17860    A similar function exists in GCC.  */
17861
17862 static const struct mips_cpu_info *
17863 mips_parse_cpu (const char *option, const char *cpu_string)
17864 {
17865   const struct mips_cpu_info *p;
17866
17867   /* 'from-abi' selects the most compatible architecture for the given
17868      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
17869      EABIs, we have to decide whether we're using the 32-bit or 64-bit
17870      version.  Look first at the -mgp options, if given, otherwise base
17871      the choice on MIPS_DEFAULT_64BIT.
17872
17873      Treat NO_ABI like the EABIs.  One reason to do this is that the
17874      plain 'mips' and 'mips64' configs have 'from-abi' as their default
17875      architecture.  This code picks MIPS I for 'mips' and MIPS III for
17876      'mips64', just as we did in the days before 'from-abi'.  */
17877   if (strcasecmp (cpu_string, "from-abi") == 0)
17878     {
17879       if (ABI_NEEDS_32BIT_REGS (mips_abi))
17880         return mips_cpu_info_from_isa (ISA_MIPS1);
17881
17882       if (ABI_NEEDS_64BIT_REGS (mips_abi))
17883         return mips_cpu_info_from_isa (ISA_MIPS3);
17884
17885       if (file_mips_gp32 >= 0)
17886         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
17887
17888       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
17889                                      ? ISA_MIPS3
17890                                      : ISA_MIPS1);
17891     }
17892
17893   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
17894   if (strcasecmp (cpu_string, "default") == 0)
17895     return 0;
17896
17897   for (p = mips_cpu_info_table; p->name != 0; p++)
17898     if (mips_matching_cpu_name_p (p->name, cpu_string))
17899       return p;
17900
17901   as_bad (_("bad value (%s) for %s"), cpu_string, option);
17902   return 0;
17903 }
17904
17905 /* Return the canonical processor information for ISA (a member of the
17906    ISA_MIPS* enumeration).  */
17907
17908 static const struct mips_cpu_info *
17909 mips_cpu_info_from_isa (int isa)
17910 {
17911   int i;
17912
17913   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17914     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
17915         && isa == mips_cpu_info_table[i].isa)
17916       return (&mips_cpu_info_table[i]);
17917
17918   return NULL;
17919 }
17920
17921 static const struct mips_cpu_info *
17922 mips_cpu_info_from_arch (int arch)
17923 {
17924   int i;
17925
17926   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17927     if (arch == mips_cpu_info_table[i].cpu)
17928       return (&mips_cpu_info_table[i]);
17929
17930   return NULL;
17931 }
17932 \f
17933 static void
17934 show (FILE *stream, const char *string, int *col_p, int *first_p)
17935 {
17936   if (*first_p)
17937     {
17938       fprintf (stream, "%24s", "");
17939       *col_p = 24;
17940     }
17941   else
17942     {
17943       fprintf (stream, ", ");
17944       *col_p += 2;
17945     }
17946
17947   if (*col_p + strlen (string) > 72)
17948     {
17949       fprintf (stream, "\n%24s", "");
17950       *col_p = 24;
17951     }
17952
17953   fprintf (stream, "%s", string);
17954   *col_p += strlen (string);
17955
17956   *first_p = 0;
17957 }
17958
17959 void
17960 md_show_usage (FILE *stream)
17961 {
17962   int column, first;
17963   size_t i;
17964
17965   fprintf (stream, _("\
17966 MIPS options:\n\
17967 -EB                     generate big endian output\n\
17968 -EL                     generate little endian output\n\
17969 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
17970 -G NUM                  allow referencing objects up to NUM bytes\n\
17971                         implicitly with the gp register [default 8]\n"));
17972   fprintf (stream, _("\
17973 -mips1                  generate MIPS ISA I instructions\n\
17974 -mips2                  generate MIPS ISA II instructions\n\
17975 -mips3                  generate MIPS ISA III instructions\n\
17976 -mips4                  generate MIPS ISA IV instructions\n\
17977 -mips5                  generate MIPS ISA V instructions\n\
17978 -mips32                 generate MIPS32 ISA instructions\n\
17979 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
17980 -mips64                 generate MIPS64 ISA instructions\n\
17981 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
17982 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
17983
17984   first = 1;
17985
17986   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
17987     show (stream, mips_cpu_info_table[i].name, &column, &first);
17988   show (stream, "from-abi", &column, &first);
17989   fputc ('\n', stream);
17990
17991   fprintf (stream, _("\
17992 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
17993 -no-mCPU                don't generate code specific to CPU.\n\
17994                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
17995
17996   first = 1;
17997
17998   show (stream, "3900", &column, &first);
17999   show (stream, "4010", &column, &first);
18000   show (stream, "4100", &column, &first);
18001   show (stream, "4650", &column, &first);
18002   fputc ('\n', stream);
18003
18004   fprintf (stream, _("\
18005 -mips16                 generate mips16 instructions\n\
18006 -no-mips16              do not generate mips16 instructions\n"));
18007   fprintf (stream, _("\
18008 -mmicromips             generate microMIPS instructions\n\
18009 -mno-micromips          do not generate microMIPS instructions\n"));
18010   fprintf (stream, _("\
18011 -msmartmips             generate smartmips instructions\n\
18012 -mno-smartmips          do not generate smartmips instructions\n"));  
18013   fprintf (stream, _("\
18014 -mdsp                   generate DSP instructions\n\
18015 -mno-dsp                do not generate DSP instructions\n"));
18016   fprintf (stream, _("\
18017 -mdspr2                 generate DSP R2 instructions\n\
18018 -mno-dspr2              do not generate DSP R2 instructions\n"));
18019   fprintf (stream, _("\
18020 -mmt                    generate MT instructions\n\
18021 -mno-mt                 do not generate MT instructions\n"));
18022   fprintf (stream, _("\
18023 -mmcu                   generate MCU instructions\n\
18024 -mno-mcu                do not generate MCU instructions\n"));
18025   fprintf (stream, _("\
18026 -mvirt                  generate Virtualization instructions\n\
18027 -mno-virt               do not generate Virtualization instructions\n"));
18028   fprintf (stream, _("\
18029 -minsn32                only generate 32-bit microMIPS instructions\n\
18030 -mno-insn32             generate all microMIPS instructions\n"));
18031   fprintf (stream, _("\
18032 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18033 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18034 -mfix-vr4120            work around certain VR4120 errata\n\
18035 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18036 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18037 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18038 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18039 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18040 -msym32                 assume all symbols have 32-bit values\n\
18041 -O0                     remove unneeded NOPs, do not swap branches\n\
18042 -O                      remove unneeded NOPs and swap branches\n\
18043 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18044 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18045   fprintf (stream, _("\
18046 -mhard-float            allow floating-point instructions\n\
18047 -msoft-float            do not allow floating-point instructions\n\
18048 -msingle-float          only allow 32-bit floating-point operations\n\
18049 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18050 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18051 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18052 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18053
18054   first = 1;
18055
18056   show (stream, "legacy", &column, &first);
18057   show (stream, "2008", &column, &first);
18058
18059   fputc ('\n', stream);
18060
18061   fprintf (stream, _("\
18062 -KPIC, -call_shared     generate SVR4 position independent code\n\
18063 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18064 -mvxworks-pic           generate VxWorks position independent code\n\
18065 -non_shared             do not generate code that can operate with DSOs\n\
18066 -xgot                   assume a 32 bit GOT\n\
18067 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18068 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18069                         position dependent (non shared) code\n\
18070 -mabi=ABI               create ABI conformant object file for:\n"));
18071
18072   first = 1;
18073
18074   show (stream, "32", &column, &first);
18075   show (stream, "o64", &column, &first);
18076   show (stream, "n32", &column, &first);
18077   show (stream, "64", &column, &first);
18078   show (stream, "eabi", &column, &first);
18079
18080   fputc ('\n', stream);
18081
18082   fprintf (stream, _("\
18083 -32                     create o32 ABI object file (default)\n\
18084 -n32                    create n32 ABI object file\n\
18085 -64                     create 64 ABI object file\n"));
18086 }
18087
18088 #ifdef TE_IRIX
18089 enum dwarf2_format
18090 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18091 {
18092   if (HAVE_64BIT_SYMBOLS)
18093     return dwarf2_format_64bit_irix;
18094   else
18095     return dwarf2_format_32bit;
18096 }
18097 #endif
18098
18099 int
18100 mips_dwarf2_addr_size (void)
18101 {
18102   if (HAVE_64BIT_OBJECTS)
18103     return 8;
18104   else
18105     return 4;
18106 }
18107
18108 /* Standard calling conventions leave the CFA at SP on entry.  */
18109 void
18110 mips_cfi_frame_initial_instructions (void)
18111 {
18112   cfi_add_CFA_def_cfa_register (SP);
18113 }
18114
18115 int
18116 tc_mips_regname_to_dw2regnum (char *regname)
18117 {
18118   unsigned int regnum = -1;
18119   unsigned int reg;
18120
18121   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18122     regnum = reg;
18123
18124   return regnum;
18125 }