Add support for the MIPS eXtended Physical Address (XPA) ASE.
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2014 Free Software Foundation, Inc.
3    Contributed by the OSF and Ralph Campbell.
4    Written by Keith Knowles and Ralph Campbell, working independently.
5    Modified for ECOFF and R4000 support by Ian Lance Taylor of Cygnus
6    Support.
7
8    This file is part of GAS.
9
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24
25 #include "as.h"
26 #include "config.h"
27 #include "subsegs.h"
28 #include "safe-ctype.h"
29
30 #include "opcode/mips.h"
31 #include "itbl-ops.h"
32 #include "dwarf2dbg.h"
33 #include "dw2gencfi.h"
34
35 /* Check assumptions made in this file.  */
36 typedef char static_assert1[sizeof (offsetT) < 8 ? -1 : 1];
37 typedef char static_assert2[sizeof (valueT) < 8 ? -1 : 1];
38
39 #ifdef DEBUG
40 #define DBG(x) printf x
41 #else
42 #define DBG(x)
43 #endif
44
45 #define SKIP_SPACE_TABS(S) \
46   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
47
48 /* Clean up namespace so we can include obj-elf.h too.  */
49 static int mips_output_flavor (void);
50 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
51 #undef OBJ_PROCESS_STAB
52 #undef OUTPUT_FLAVOR
53 #undef S_GET_ALIGN
54 #undef S_GET_SIZE
55 #undef S_SET_ALIGN
56 #undef S_SET_SIZE
57 #undef obj_frob_file
58 #undef obj_frob_file_after_relocs
59 #undef obj_frob_symbol
60 #undef obj_pop_insert
61 #undef obj_sec_sym_ok_for_reloc
62 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
63
64 #include "obj-elf.h"
65 /* Fix any of them that we actually care about.  */
66 #undef OUTPUT_FLAVOR
67 #define OUTPUT_FLAVOR mips_output_flavor()
68
69 #include "elf/mips.h"
70
71 #ifndef ECOFF_DEBUGGING
72 #define NO_ECOFF_DEBUGGING
73 #define ECOFF_DEBUGGING 0
74 #endif
75
76 int mips_flag_mdebug = -1;
77
78 /* Control generation of .pdr sections.  Off by default on IRIX: the native
79    linker doesn't know about and discards them, but relocations against them
80    remain, leading to rld crashes.  */
81 #ifdef TE_IRIX
82 int mips_flag_pdr = FALSE;
83 #else
84 int mips_flag_pdr = TRUE;
85 #endif
86
87 #include "ecoff.h"
88
89 static char *mips_regmask_frag;
90
91 #define ZERO 0
92 #define ATREG 1
93 #define S0  16
94 #define S7  23
95 #define TREG 24
96 #define PIC_CALL_REG 25
97 #define KT0 26
98 #define KT1 27
99 #define GP  28
100 #define SP  29
101 #define FP  30
102 #define RA  31
103
104 #define ILLEGAL_REG (32)
105
106 #define AT  mips_opts.at
107
108 extern int target_big_endian;
109
110 /* The name of the readonly data section.  */
111 #define RDATA_SECTION_NAME ".rodata"
112
113 /* Ways in which an instruction can be "appended" to the output.  */
114 enum append_method {
115   /* Just add it normally.  */
116   APPEND_ADD,
117
118   /* Add it normally and then add a nop.  */
119   APPEND_ADD_WITH_NOP,
120
121   /* Turn an instruction with a delay slot into a "compact" version.  */
122   APPEND_ADD_COMPACT,
123
124   /* Insert the instruction before the last one.  */
125   APPEND_SWAP
126 };
127
128 /* Information about an instruction, including its format, operands
129    and fixups.  */
130 struct mips_cl_insn
131 {
132   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
133   const struct mips_opcode *insn_mo;
134
135   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
136      a copy of INSN_MO->match with the operands filled in.  If we have
137      decided to use an extended MIPS16 instruction, this includes the
138      extension.  */
139   unsigned long insn_opcode;
140
141   /* The frag that contains the instruction.  */
142   struct frag *frag;
143
144   /* The offset into FRAG of the first instruction byte.  */
145   long where;
146
147   /* The relocs associated with the instruction, if any.  */
148   fixS *fixp[3];
149
150   /* True if this entry cannot be moved from its current position.  */
151   unsigned int fixed_p : 1;
152
153   /* True if this instruction occurred in a .set noreorder block.  */
154   unsigned int noreorder_p : 1;
155
156   /* True for mips16 instructions that jump to an absolute address.  */
157   unsigned int mips16_absolute_jump_p : 1;
158
159   /* True if this instruction is complete.  */
160   unsigned int complete_p : 1;
161
162   /* True if this instruction is cleared from history by unconditional
163      branch.  */
164   unsigned int cleared_p : 1;
165 };
166
167 /* The ABI to use.  */
168 enum mips_abi_level
169 {
170   NO_ABI = 0,
171   O32_ABI,
172   O64_ABI,
173   N32_ABI,
174   N64_ABI,
175   EABI_ABI
176 };
177
178 /* MIPS ABI we are using for this output file.  */
179 static enum mips_abi_level mips_abi = NO_ABI;
180
181 /* Whether or not we have code that can call pic code.  */
182 int mips_abicalls = FALSE;
183
184 /* Whether or not we have code which can be put into a shared
185    library.  */
186 static bfd_boolean mips_in_shared = TRUE;
187
188 /* This is the set of options which may be modified by the .set
189    pseudo-op.  We use a struct so that .set push and .set pop are more
190    reliable.  */
191
192 struct mips_set_options
193 {
194   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
195      if it has not been initialized.  Changed by `.set mipsN', and the
196      -mipsN command line option, and the default CPU.  */
197   int isa;
198   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
199      <asename>', by command line options, and based on the default
200      architecture.  */
201   int ase;
202   /* Whether we are assembling for the mips16 processor.  0 if we are
203      not, 1 if we are, and -1 if the value has not been initialized.
204      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
205      -nomips16 command line options, and the default CPU.  */
206   int mips16;
207   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
208      1 if we are, and -1 if the value has not been initialized.  Changed
209      by `.set micromips' and `.set nomicromips', and the -mmicromips
210      and -mno-micromips command line options, and the default CPU.  */
211   int micromips;
212   /* Non-zero if we should not reorder instructions.  Changed by `.set
213      reorder' and `.set noreorder'.  */
214   int noreorder;
215   /* Non-zero if we should not permit the register designated "assembler
216      temporary" to be used in instructions.  The value is the register
217      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
218      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
219   unsigned int at;
220   /* Non-zero if we should warn when a macro instruction expands into
221      more than one machine instruction.  Changed by `.set nomacro' and
222      `.set macro'.  */
223   int warn_about_macros;
224   /* Non-zero if we should not move instructions.  Changed by `.set
225      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
226   int nomove;
227   /* Non-zero if we should not optimize branches by moving the target
228      of the branch into the delay slot.  Actually, we don't perform
229      this optimization anyhow.  Changed by `.set bopt' and `.set
230      nobopt'.  */
231   int nobopt;
232   /* Non-zero if we should not autoextend mips16 instructions.
233      Changed by `.set autoextend' and `.set noautoextend'.  */
234   int noautoextend;
235   /* True if we should only emit 32-bit microMIPS instructions.
236      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
237      and -mno-insn32 command line options.  */
238   bfd_boolean insn32;
239   /* Restrict general purpose registers and floating point registers
240      to 32 bit.  This is initially determined when -mgp32 or -mfp32
241      is passed but can changed if the assembler code uses .set mipsN.  */
242   int gp32;
243   int fp32;
244   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
245      command line option, and the default CPU.  */
246   int arch;
247   /* True if ".set sym32" is in effect.  */
248   bfd_boolean sym32;
249   /* True if floating-point operations are not allowed.  Changed by .set
250      softfloat or .set hardfloat, by command line options -msoft-float or
251      -mhard-float.  The default is false.  */
252   bfd_boolean soft_float;
253
254   /* True if only single-precision floating-point operations are allowed.
255      Changed by .set singlefloat or .set doublefloat, command-line options
256      -msingle-float or -mdouble-float.  The default is false.  */
257   bfd_boolean single_float;
258 };
259
260 /* This is the struct we use to hold the current set of options.  Note
261    that we must set the isa field to ISA_UNKNOWN and the ASE fields to
262    -1 to indicate that they have not been initialized.  */
263
264 /* True if -mgp32 was passed.  */
265 static int file_mips_gp32 = -1;
266
267 /* True if -mfp32 was passed.  */
268 static int file_mips_fp32 = -1;
269
270 /* 1 if -msoft-float, 0 if -mhard-float.  The default is 0.  */
271 static int file_mips_soft_float = 0;
272
273 /* 1 if -msingle-float, 0 if -mdouble-float.  The default is 0.   */
274 static int file_mips_single_float = 0;
275
276 /* True if -mnan=2008, false if -mnan=legacy.  */
277 static bfd_boolean mips_flag_nan2008 = FALSE;
278
279 static struct mips_set_options mips_opts =
280 {
281   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
282   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
283   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
284   /* gp32 */ 0, /* fp32 */ 0, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
285   /* soft_float */ FALSE, /* single_float */ FALSE
286 };
287
288 /* The set of ASEs that were selected on the command line, either
289    explicitly via ASE options or implicitly through things like -march.  */
290 static unsigned int file_ase;
291
292 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
293 static unsigned int file_ase_explicit;
294
295 /* These variables are filled in with the masks of registers used.
296    The object format code reads them and puts them in the appropriate
297    place.  */
298 unsigned long mips_gprmask;
299 unsigned long mips_cprmask[4];
300
301 /* MIPS ISA we are using for this output file.  */
302 static int file_mips_isa = ISA_UNKNOWN;
303
304 /* True if any MIPS16 code was produced.  */
305 static int file_ase_mips16;
306
307 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
308                               || mips_opts.isa == ISA_MIPS32R2          \
309                               || mips_opts.isa == ISA_MIPS64            \
310                               || mips_opts.isa == ISA_MIPS64R2)
311
312 /* True if any microMIPS code was produced.  */
313 static int file_ase_micromips;
314
315 /* True if we want to create R_MIPS_JALR for jalr $25.  */
316 #ifdef TE_IRIX
317 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
318 #else
319 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
320    because there's no place for any addend, the only acceptable
321    expression is a bare symbol.  */
322 #define MIPS_JALR_HINT_P(EXPR) \
323   (!HAVE_IN_PLACE_ADDENDS \
324    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
325 #endif
326
327 /* The argument of the -march= flag.  The architecture we are assembling.  */
328 static int file_mips_arch = CPU_UNKNOWN;
329 static const char *mips_arch_string;
330
331 /* The argument of the -mtune= flag.  The architecture for which we
332    are optimizing.  */
333 static int mips_tune = CPU_UNKNOWN;
334 static const char *mips_tune_string;
335
336 /* True when generating 32-bit code for a 64-bit processor.  */
337 static int mips_32bitmode = 0;
338
339 /* True if the given ABI requires 32-bit registers.  */
340 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
341
342 /* Likewise 64-bit registers.  */
343 #define ABI_NEEDS_64BIT_REGS(ABI)       \
344   ((ABI) == N32_ABI                     \
345    || (ABI) == N64_ABI                  \
346    || (ABI) == O64_ABI)
347
348 /*  Return true if ISA supports 64 bit wide gp registers.  */
349 #define ISA_HAS_64BIT_REGS(ISA)         \
350   ((ISA) == ISA_MIPS3                   \
351    || (ISA) == ISA_MIPS4                \
352    || (ISA) == ISA_MIPS5                \
353    || (ISA) == ISA_MIPS64               \
354    || (ISA) == ISA_MIPS64R2)
355
356 /*  Return true if ISA supports 64 bit wide float registers.  */
357 #define ISA_HAS_64BIT_FPRS(ISA)         \
358   ((ISA) == ISA_MIPS3                   \
359    || (ISA) == ISA_MIPS4                \
360    || (ISA) == ISA_MIPS5                \
361    || (ISA) == ISA_MIPS32R2             \
362    || (ISA) == ISA_MIPS64               \
363    || (ISA) == ISA_MIPS64R2)
364
365 /* Return true if ISA supports 64-bit right rotate (dror et al.)
366    instructions.  */
367 #define ISA_HAS_DROR(ISA)               \
368   ((ISA) == ISA_MIPS64R2                \
369    || (mips_opts.micromips              \
370        && ISA_HAS_64BIT_REGS (ISA))     \
371    )
372
373 /* Return true if ISA supports 32-bit right rotate (ror et al.)
374    instructions.  */
375 #define ISA_HAS_ROR(ISA)                \
376   ((ISA) == ISA_MIPS32R2                \
377    || (ISA) == ISA_MIPS64R2             \
378    || (mips_opts.ase & ASE_SMARTMIPS)   \
379    || mips_opts.micromips               \
380    )
381
382 /* Return true if ISA supports single-precision floats in odd registers.  */
383 #define ISA_HAS_ODD_SINGLE_FPR(ISA)     \
384   ((ISA) == ISA_MIPS32                  \
385    || (ISA) == ISA_MIPS32R2             \
386    || (ISA) == ISA_MIPS64               \
387    || (ISA) == ISA_MIPS64R2)
388
389 /* Return true if ISA supports move to/from high part of a 64-bit
390    floating-point register. */
391 #define ISA_HAS_MXHC1(ISA)              \
392   ((ISA) == ISA_MIPS32R2                \
393    || (ISA) == ISA_MIPS64R2)
394
395 #define HAVE_32BIT_GPRS                            \
396     (mips_opts.gp32 || !ISA_HAS_64BIT_REGS (mips_opts.isa))
397
398 #define HAVE_32BIT_FPRS                            \
399     (mips_opts.fp32 || !ISA_HAS_64BIT_FPRS (mips_opts.isa))
400
401 #define HAVE_64BIT_GPRS (!HAVE_32BIT_GPRS)
402 #define HAVE_64BIT_FPRS (!HAVE_32BIT_FPRS)
403
404 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
405
406 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
407
408 /* True if relocations are stored in-place.  */
409 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
410
411 /* The ABI-derived address size.  */
412 #define HAVE_64BIT_ADDRESSES \
413   (HAVE_64BIT_GPRS && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
414 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
415
416 /* The size of symbolic constants (i.e., expressions of the form
417    "SYMBOL" or "SYMBOL + OFFSET").  */
418 #define HAVE_32BIT_SYMBOLS \
419   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
420 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
421
422 /* Addresses are loaded in different ways, depending on the address size
423    in use.  The n32 ABI Documentation also mandates the use of additions
424    with overflow checking, but existing implementations don't follow it.  */
425 #define ADDRESS_ADD_INSN                                                \
426    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
427
428 #define ADDRESS_ADDI_INSN                                               \
429    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
430
431 #define ADDRESS_LOAD_INSN                                               \
432    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
433
434 #define ADDRESS_STORE_INSN                                              \
435    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
436
437 /* Return true if the given CPU supports the MIPS16 ASE.  */
438 #define CPU_HAS_MIPS16(cpu)                                             \
439    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
440     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
441
442 /* Return true if the given CPU supports the microMIPS ASE.  */
443 #define CPU_HAS_MICROMIPS(cpu)  0
444
445 /* True if CPU has a dror instruction.  */
446 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
447
448 /* True if CPU has a ror instruction.  */
449 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
450
451 /* True if CPU is in the Octeon family */
452 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP || (CPU) == CPU_OCTEON2)
453
454 /* True if CPU has seq/sne and seqi/snei instructions.  */
455 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
456
457 /* True, if CPU has support for ldc1 and sdc1. */
458 #define CPU_HAS_LDC1_SDC1(CPU)  \
459    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
460
461 /* True if mflo and mfhi can be immediately followed by instructions
462    which write to the HI and LO registers.
463
464    According to MIPS specifications, MIPS ISAs I, II, and III need
465    (at least) two instructions between the reads of HI/LO and
466    instructions which write them, and later ISAs do not.  Contradicting
467    the MIPS specifications, some MIPS IV processor user manuals (e.g.
468    the UM for the NEC Vr5000) document needing the instructions between
469    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
470    MIPS64 and later ISAs to have the interlocks, plus any specific
471    earlier-ISA CPUs for which CPU documentation declares that the
472    instructions are really interlocked.  */
473 #define hilo_interlocks \
474   (mips_opts.isa == ISA_MIPS32                        \
475    || mips_opts.isa == ISA_MIPS32R2                   \
476    || mips_opts.isa == ISA_MIPS64                     \
477    || mips_opts.isa == ISA_MIPS64R2                   \
478    || mips_opts.arch == CPU_R4010                     \
479    || mips_opts.arch == CPU_R5900                     \
480    || mips_opts.arch == CPU_R10000                    \
481    || mips_opts.arch == CPU_R12000                    \
482    || mips_opts.arch == CPU_R14000                    \
483    || mips_opts.arch == CPU_R16000                    \
484    || mips_opts.arch == CPU_RM7000                    \
485    || mips_opts.arch == CPU_VR5500                    \
486    || mips_opts.micromips                             \
487    )
488
489 /* Whether the processor uses hardware interlocks to protect reads
490    from the GPRs after they are loaded from memory, and thus does not
491    require nops to be inserted.  This applies to instructions marked
492    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
493    level I and microMIPS mode instructions are always interlocked.  */
494 #define gpr_interlocks                                \
495   (mips_opts.isa != ISA_MIPS1                         \
496    || mips_opts.arch == CPU_R3900                     \
497    || mips_opts.arch == CPU_R5900                     \
498    || mips_opts.micromips                             \
499    )
500
501 /* Whether the processor uses hardware interlocks to avoid delays
502    required by coprocessor instructions, and thus does not require
503    nops to be inserted.  This applies to instructions marked
504    INSN_LOAD_COPROC_DELAY, INSN_COPROC_MOVE_DELAY, and to delays
505    between instructions marked INSN_WRITE_COND_CODE and ones marked
506    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
507    levels I, II, and III and microMIPS mode instructions are always
508    interlocked.  */
509 /* Itbl support may require additional care here.  */
510 #define cop_interlocks                                \
511   ((mips_opts.isa != ISA_MIPS1                        \
512     && mips_opts.isa != ISA_MIPS2                     \
513     && mips_opts.isa != ISA_MIPS3)                    \
514    || mips_opts.arch == CPU_R4300                     \
515    || mips_opts.micromips                             \
516    )
517
518 /* Whether the processor uses hardware interlocks to protect reads
519    from coprocessor registers after they are loaded from memory, and
520    thus does not require nops to be inserted.  This applies to
521    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
522    requires at MIPS ISA level I and microMIPS mode instructions are
523    always interlocked.  */
524 #define cop_mem_interlocks                            \
525   (mips_opts.isa != ISA_MIPS1                         \
526    || mips_opts.micromips                             \
527    )
528
529 /* Is this a mfhi or mflo instruction?  */
530 #define MF_HILO_INSN(PINFO) \
531   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
532
533 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
534    has been selected.  This implies, in particular, that addresses of text
535    labels have their LSB set.  */
536 #define HAVE_CODE_COMPRESSION                                           \
537   ((mips_opts.mips16 | mips_opts.micromips) != 0)
538
539 /* The minimum and maximum signed values that can be stored in a GPR.  */
540 #define GPR_SMAX ((offsetT) (((valueT) 1 << (HAVE_64BIT_GPRS ? 63 : 31)) - 1))
541 #define GPR_SMIN (-GPR_SMAX - 1)
542
543 /* MIPS PIC level.  */
544
545 enum mips_pic_level mips_pic;
546
547 /* 1 if we should generate 32 bit offsets from the $gp register in
548    SVR4_PIC mode.  Currently has no meaning in other modes.  */
549 static int mips_big_got = 0;
550
551 /* 1 if trap instructions should used for overflow rather than break
552    instructions.  */
553 static int mips_trap = 0;
554
555 /* 1 if double width floating point constants should not be constructed
556    by assembling two single width halves into two single width floating
557    point registers which just happen to alias the double width destination
558    register.  On some architectures this aliasing can be disabled by a bit
559    in the status register, and the setting of this bit cannot be determined
560    automatically at assemble time.  */
561 static int mips_disable_float_construction;
562
563 /* Non-zero if any .set noreorder directives were used.  */
564
565 static int mips_any_noreorder;
566
567 /* Non-zero if nops should be inserted when the register referenced in
568    an mfhi/mflo instruction is read in the next two instructions.  */
569 static int mips_7000_hilo_fix;
570
571 /* The size of objects in the small data section.  */
572 static unsigned int g_switch_value = 8;
573 /* Whether the -G option was used.  */
574 static int g_switch_seen = 0;
575
576 #define N_RMASK 0xc4
577 #define N_VFP   0xd4
578
579 /* If we can determine in advance that GP optimization won't be
580    possible, we can skip the relaxation stuff that tries to produce
581    GP-relative references.  This makes delay slot optimization work
582    better.
583
584    This function can only provide a guess, but it seems to work for
585    gcc output.  It needs to guess right for gcc, otherwise gcc
586    will put what it thinks is a GP-relative instruction in a branch
587    delay slot.
588
589    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
590    fixed it for the non-PIC mode.  KR 95/04/07  */
591 static int nopic_need_relax (symbolS *, int);
592
593 /* handle of the OPCODE hash table */
594 static struct hash_control *op_hash = NULL;
595
596 /* The opcode hash table we use for the mips16.  */
597 static struct hash_control *mips16_op_hash = NULL;
598
599 /* The opcode hash table we use for the microMIPS ASE.  */
600 static struct hash_control *micromips_op_hash = NULL;
601
602 /* This array holds the chars that always start a comment.  If the
603     pre-processor is disabled, these aren't very useful */
604 const char comment_chars[] = "#";
605
606 /* This array holds the chars that only start a comment at the beginning of
607    a line.  If the line seems to have the form '# 123 filename'
608    .line and .file directives will appear in the pre-processed output */
609 /* Note that input_file.c hand checks for '#' at the beginning of the
610    first line of the input file.  This is because the compiler outputs
611    #NO_APP at the beginning of its output.  */
612 /* Also note that C style comments are always supported.  */
613 const char line_comment_chars[] = "#";
614
615 /* This array holds machine specific line separator characters.  */
616 const char line_separator_chars[] = ";";
617
618 /* Chars that can be used to separate mant from exp in floating point nums */
619 const char EXP_CHARS[] = "eE";
620
621 /* Chars that mean this number is a floating point constant */
622 /* As in 0f12.456 */
623 /* or    0d1.2345e12 */
624 const char FLT_CHARS[] = "rRsSfFdDxXpP";
625
626 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
627    changed in read.c .  Ideally it shouldn't have to know about it at all,
628    but nothing is ideal around here.
629  */
630
631 /* Types of printf format used for instruction-related error messages.
632    "I" means int ("%d") and "S" means string ("%s"). */
633 enum mips_insn_error_format {
634   ERR_FMT_PLAIN,
635   ERR_FMT_I,
636   ERR_FMT_SS,
637 };
638
639 /* Information about an error that was found while assembling the current
640    instruction.  */
641 struct mips_insn_error {
642   /* We sometimes need to match an instruction against more than one
643      opcode table entry.  Errors found during this matching are reported
644      against a particular syntactic argument rather than against the
645      instruction as a whole.  We grade these messages so that errors
646      against argument N have a greater priority than an error against
647      any argument < N, since the former implies that arguments up to N
648      were acceptable and that the opcode entry was therefore a closer match.
649      If several matches report an error against the same argument,
650      we only use that error if it is the same in all cases.
651
652      min_argnum is the minimum argument number for which an error message
653      should be accepted.  It is 0 if MSG is against the instruction as
654      a whole.  */
655   int min_argnum;
656
657   /* The printf()-style message, including its format and arguments.  */
658   enum mips_insn_error_format format;
659   const char *msg;
660   union {
661     int i;
662     const char *ss[2];
663   } u;
664 };
665
666 /* The error that should be reported for the current instruction.  */
667 static struct mips_insn_error insn_error;
668
669 static int auto_align = 1;
670
671 /* When outputting SVR4 PIC code, the assembler needs to know the
672    offset in the stack frame from which to restore the $gp register.
673    This is set by the .cprestore pseudo-op, and saved in this
674    variable.  */
675 static offsetT mips_cprestore_offset = -1;
676
677 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
678    more optimizations, it can use a register value instead of a memory-saved
679    offset and even an other register than $gp as global pointer.  */
680 static offsetT mips_cpreturn_offset = -1;
681 static int mips_cpreturn_register = -1;
682 static int mips_gp_register = GP;
683 static int mips_gprel_offset = 0;
684
685 /* Whether mips_cprestore_offset has been set in the current function
686    (or whether it has already been warned about, if not).  */
687 static int mips_cprestore_valid = 0;
688
689 /* This is the register which holds the stack frame, as set by the
690    .frame pseudo-op.  This is needed to implement .cprestore.  */
691 static int mips_frame_reg = SP;
692
693 /* Whether mips_frame_reg has been set in the current function
694    (or whether it has already been warned about, if not).  */
695 static int mips_frame_reg_valid = 0;
696
697 /* To output NOP instructions correctly, we need to keep information
698    about the previous two instructions.  */
699
700 /* Whether we are optimizing.  The default value of 2 means to remove
701    unneeded NOPs and swap branch instructions when possible.  A value
702    of 1 means to not swap branches.  A value of 0 means to always
703    insert NOPs.  */
704 static int mips_optimize = 2;
705
706 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
707    equivalent to seeing no -g option at all.  */
708 static int mips_debug = 0;
709
710 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
711 #define MAX_VR4130_NOPS 4
712
713 /* The maximum number of NOPs needed to fill delay slots.  */
714 #define MAX_DELAY_NOPS 2
715
716 /* The maximum number of NOPs needed for any purpose.  */
717 #define MAX_NOPS 4
718
719 /* A list of previous instructions, with index 0 being the most recent.
720    We need to look back MAX_NOPS instructions when filling delay slots
721    or working around processor errata.  We need to look back one
722    instruction further if we're thinking about using history[0] to
723    fill a branch delay slot.  */
724 static struct mips_cl_insn history[1 + MAX_NOPS];
725
726 /* Arrays of operands for each instruction.  */
727 #define MAX_OPERANDS 6
728 struct mips_operand_array {
729   const struct mips_operand *operand[MAX_OPERANDS];
730 };
731 static struct mips_operand_array *mips_operands;
732 static struct mips_operand_array *mips16_operands;
733 static struct mips_operand_array *micromips_operands;
734
735 /* Nop instructions used by emit_nop.  */
736 static struct mips_cl_insn nop_insn;
737 static struct mips_cl_insn mips16_nop_insn;
738 static struct mips_cl_insn micromips_nop16_insn;
739 static struct mips_cl_insn micromips_nop32_insn;
740
741 /* The appropriate nop for the current mode.  */
742 #define NOP_INSN (mips_opts.mips16                                      \
743                   ? &mips16_nop_insn                                    \
744                   : (mips_opts.micromips                                \
745                      ? (mips_opts.insn32                                \
746                         ? &micromips_nop32_insn                         \
747                         : &micromips_nop16_insn)                        \
748                      : &nop_insn))
749
750 /* The size of NOP_INSN in bytes.  */
751 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
752                         || (mips_opts.micromips && !mips_opts.insn32))  \
753                        ? 2 : 4)
754
755 /* If this is set, it points to a frag holding nop instructions which
756    were inserted before the start of a noreorder section.  If those
757    nops turn out to be unnecessary, the size of the frag can be
758    decreased.  */
759 static fragS *prev_nop_frag;
760
761 /* The number of nop instructions we created in prev_nop_frag.  */
762 static int prev_nop_frag_holds;
763
764 /* The number of nop instructions that we know we need in
765    prev_nop_frag.  */
766 static int prev_nop_frag_required;
767
768 /* The number of instructions we've seen since prev_nop_frag.  */
769 static int prev_nop_frag_since;
770
771 /* Relocations against symbols are sometimes done in two parts, with a HI
772    relocation and a LO relocation.  Each relocation has only 16 bits of
773    space to store an addend.  This means that in order for the linker to
774    handle carries correctly, it must be able to locate both the HI and
775    the LO relocation.  This means that the relocations must appear in
776    order in the relocation table.
777
778    In order to implement this, we keep track of each unmatched HI
779    relocation.  We then sort them so that they immediately precede the
780    corresponding LO relocation.  */
781
782 struct mips_hi_fixup
783 {
784   /* Next HI fixup.  */
785   struct mips_hi_fixup *next;
786   /* This fixup.  */
787   fixS *fixp;
788   /* The section this fixup is in.  */
789   segT seg;
790 };
791
792 /* The list of unmatched HI relocs.  */
793
794 static struct mips_hi_fixup *mips_hi_fixup_list;
795
796 /* The frag containing the last explicit relocation operator.
797    Null if explicit relocations have not been used.  */
798
799 static fragS *prev_reloc_op_frag;
800
801 /* Map mips16 register numbers to normal MIPS register numbers.  */
802
803 static const unsigned int mips16_to_32_reg_map[] =
804 {
805   16, 17, 2, 3, 4, 5, 6, 7
806 };
807
808 /* Map microMIPS register numbers to normal MIPS register numbers.  */
809
810 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
811
812 /* The microMIPS registers with type h.  */
813 static const unsigned int micromips_to_32_reg_h_map1[] =
814 {
815   5, 5, 6, 4, 4, 4, 4, 4
816 };
817 static const unsigned int micromips_to_32_reg_h_map2[] =
818 {
819   6, 7, 7, 21, 22, 5, 6, 7
820 };
821
822 /* The microMIPS registers with type m.  */
823 static const unsigned int micromips_to_32_reg_m_map[] =
824 {
825   0, 17, 2, 3, 16, 18, 19, 20
826 };
827
828 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
829
830 /* Classifies the kind of instructions we're interested in when
831    implementing -mfix-vr4120.  */
832 enum fix_vr4120_class
833 {
834   FIX_VR4120_MACC,
835   FIX_VR4120_DMACC,
836   FIX_VR4120_MULT,
837   FIX_VR4120_DMULT,
838   FIX_VR4120_DIV,
839   FIX_VR4120_MTHILO,
840   NUM_FIX_VR4120_CLASSES
841 };
842
843 /* ...likewise -mfix-loongson2f-jump.  */
844 static bfd_boolean mips_fix_loongson2f_jump;
845
846 /* ...likewise -mfix-loongson2f-nop.  */
847 static bfd_boolean mips_fix_loongson2f_nop;
848
849 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
850 static bfd_boolean mips_fix_loongson2f;
851
852 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
853    there must be at least one other instruction between an instruction
854    of type X and an instruction of type Y.  */
855 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
856
857 /* True if -mfix-vr4120 is in force.  */
858 static int mips_fix_vr4120;
859
860 /* ...likewise -mfix-vr4130.  */
861 static int mips_fix_vr4130;
862
863 /* ...likewise -mfix-24k.  */
864 static int mips_fix_24k;
865
866 /* ...likewise -mfix-rm7000  */
867 static int mips_fix_rm7000;
868
869 /* ...likewise -mfix-cn63xxp1 */
870 static bfd_boolean mips_fix_cn63xxp1;
871
872 /* We don't relax branches by default, since this causes us to expand
873    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
874    fail to compute the offset before expanding the macro to the most
875    efficient expansion.  */
876
877 static int mips_relax_branch;
878 \f
879 /* The expansion of many macros depends on the type of symbol that
880    they refer to.  For example, when generating position-dependent code,
881    a macro that refers to a symbol may have two different expansions,
882    one which uses GP-relative addresses and one which uses absolute
883    addresses.  When generating SVR4-style PIC, a macro may have
884    different expansions for local and global symbols.
885
886    We handle these situations by generating both sequences and putting
887    them in variant frags.  In position-dependent code, the first sequence
888    will be the GP-relative one and the second sequence will be the
889    absolute one.  In SVR4 PIC, the first sequence will be for global
890    symbols and the second will be for local symbols.
891
892    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
893    SECOND are the lengths of the two sequences in bytes.  These fields
894    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
895    the subtype has the following flags:
896
897    RELAX_USE_SECOND
898         Set if it has been decided that we should use the second
899         sequence instead of the first.
900
901    RELAX_SECOND_LONGER
902         Set in the first variant frag if the macro's second implementation
903         is longer than its first.  This refers to the macro as a whole,
904         not an individual relaxation.
905
906    RELAX_NOMACRO
907         Set in the first variant frag if the macro appeared in a .set nomacro
908         block and if one alternative requires a warning but the other does not.
909
910    RELAX_DELAY_SLOT
911         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
912         delay slot.
913
914    RELAX_DELAY_SLOT_16BIT
915         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
916         16-bit instruction.
917
918    RELAX_DELAY_SLOT_SIZE_FIRST
919         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
920         the macro is of the wrong size for the branch delay slot.
921
922    RELAX_DELAY_SLOT_SIZE_SECOND
923         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
924         the macro is of the wrong size for the branch delay slot.
925
926    The frag's "opcode" points to the first fixup for relaxable code.
927
928    Relaxable macros are generated using a sequence such as:
929
930       relax_start (SYMBOL);
931       ... generate first expansion ...
932       relax_switch ();
933       ... generate second expansion ...
934       relax_end ();
935
936    The code and fixups for the unwanted alternative are discarded
937    by md_convert_frag.  */
938 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
939
940 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
941 #define RELAX_SECOND(X) ((X) & 0xff)
942 #define RELAX_USE_SECOND 0x10000
943 #define RELAX_SECOND_LONGER 0x20000
944 #define RELAX_NOMACRO 0x40000
945 #define RELAX_DELAY_SLOT 0x80000
946 #define RELAX_DELAY_SLOT_16BIT 0x100000
947 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
948 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
949
950 /* Branch without likely bit.  If label is out of range, we turn:
951
952         beq reg1, reg2, label
953         delay slot
954
955    into
956
957         bne reg1, reg2, 0f
958         nop
959         j label
960      0: delay slot
961
962    with the following opcode replacements:
963
964         beq <-> bne
965         blez <-> bgtz
966         bltz <-> bgez
967         bc1f <-> bc1t
968
969         bltzal <-> bgezal  (with jal label instead of j label)
970
971    Even though keeping the delay slot instruction in the delay slot of
972    the branch would be more efficient, it would be very tricky to do
973    correctly, because we'd have to introduce a variable frag *after*
974    the delay slot instruction, and expand that instead.  Let's do it
975    the easy way for now, even if the branch-not-taken case now costs
976    one additional instruction.  Out-of-range branches are not supposed
977    to be common, anyway.
978
979    Branch likely.  If label is out of range, we turn:
980
981         beql reg1, reg2, label
982         delay slot (annulled if branch not taken)
983
984    into
985
986         beql reg1, reg2, 1f
987         nop
988         beql $0, $0, 2f
989         nop
990      1: j[al] label
991         delay slot (executed only if branch taken)
992      2:
993
994    It would be possible to generate a shorter sequence by losing the
995    likely bit, generating something like:
996
997         bne reg1, reg2, 0f
998         nop
999         j[al] label
1000         delay slot (executed only if branch taken)
1001      0:
1002
1003         beql -> bne
1004         bnel -> beq
1005         blezl -> bgtz
1006         bgtzl -> blez
1007         bltzl -> bgez
1008         bgezl -> bltz
1009         bc1fl -> bc1t
1010         bc1tl -> bc1f
1011
1012         bltzall -> bgezal  (with jal label instead of j label)
1013         bgezall -> bltzal  (ditto)
1014
1015
1016    but it's not clear that it would actually improve performance.  */
1017 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1018   ((relax_substateT)                                            \
1019    (0xc0000000                                                  \
1020     | ((at) & 0x1f)                                             \
1021     | ((toofar) ? 0x20 : 0)                                     \
1022     | ((link) ? 0x40 : 0)                                       \
1023     | ((likely) ? 0x80 : 0)                                     \
1024     | ((uncond) ? 0x100 : 0)))
1025 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1026 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1027 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1028 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1029 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1030 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1031
1032 /* For mips16 code, we use an entirely different form of relaxation.
1033    mips16 supports two versions of most instructions which take
1034    immediate values: a small one which takes some small value, and a
1035    larger one which takes a 16 bit value.  Since branches also follow
1036    this pattern, relaxing these values is required.
1037
1038    We can assemble both mips16 and normal MIPS code in a single
1039    object.  Therefore, we need to support this type of relaxation at
1040    the same time that we support the relaxation described above.  We
1041    use the high bit of the subtype field to distinguish these cases.
1042
1043    The information we store for this type of relaxation is the
1044    argument code found in the opcode file for this relocation, whether
1045    the user explicitly requested a small or extended form, and whether
1046    the relocation is in a jump or jal delay slot.  That tells us the
1047    size of the value, and how it should be stored.  We also store
1048    whether the fragment is considered to be extended or not.  We also
1049    store whether this is known to be a branch to a different section,
1050    whether we have tried to relax this frag yet, and whether we have
1051    ever extended a PC relative fragment because of a shift count.  */
1052 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1053   (0x80000000                                                   \
1054    | ((type) & 0xff)                                            \
1055    | ((small) ? 0x100 : 0)                                      \
1056    | ((ext) ? 0x200 : 0)                                        \
1057    | ((dslot) ? 0x400 : 0)                                      \
1058    | ((jal_dslot) ? 0x800 : 0))
1059 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1060 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1061 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1062 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1063 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1064 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1065 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1066 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1067 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1068 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1069 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1070 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1071
1072 /* For microMIPS code, we use relaxation similar to one we use for
1073    MIPS16 code.  Some instructions that take immediate values support
1074    two encodings: a small one which takes some small value, and a
1075    larger one which takes a 16 bit value.  As some branches also follow
1076    this pattern, relaxing these values is required.
1077
1078    We can assemble both microMIPS and normal MIPS code in a single
1079    object.  Therefore, we need to support this type of relaxation at
1080    the same time that we support the relaxation described above.  We
1081    use one of the high bits of the subtype field to distinguish these
1082    cases.
1083
1084    The information we store for this type of relaxation is the argument
1085    code found in the opcode file for this relocation, the register
1086    selected as the assembler temporary, whether the branch is
1087    unconditional, whether it is compact, whether it stores the link
1088    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1089    branches to a sequence of instructions is enabled, and whether the
1090    displacement of a branch is too large to fit as an immediate argument
1091    of a 16-bit and a 32-bit branch, respectively.  */
1092 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1093                                relax32, toofar16, toofar32)     \
1094   (0x40000000                                                   \
1095    | ((type) & 0xff)                                            \
1096    | (((at) & 0x1f) << 8)                                       \
1097    | ((uncond) ? 0x2000 : 0)                                    \
1098    | ((compact) ? 0x4000 : 0)                                   \
1099    | ((link) ? 0x8000 : 0)                                      \
1100    | ((relax32) ? 0x10000 : 0)                                  \
1101    | ((toofar16) ? 0x20000 : 0)                                 \
1102    | ((toofar32) ? 0x40000 : 0))
1103 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1104 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1105 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1106 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1107 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1108 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1109 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1110
1111 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1112 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1113 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1114 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1115 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1116 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1117
1118 /* Sign-extend 16-bit value X.  */
1119 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1120
1121 /* Is the given value a sign-extended 32-bit value?  */
1122 #define IS_SEXT_32BIT_NUM(x)                                            \
1123   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1124    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1125
1126 /* Is the given value a sign-extended 16-bit value?  */
1127 #define IS_SEXT_16BIT_NUM(x)                                            \
1128   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1129    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1130
1131 /* Is the given value a sign-extended 12-bit value?  */
1132 #define IS_SEXT_12BIT_NUM(x)                                            \
1133   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1134
1135 /* Is the given value a sign-extended 9-bit value?  */
1136 #define IS_SEXT_9BIT_NUM(x)                                             \
1137   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1138
1139 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1140 #define IS_ZEXT_32BIT_NUM(x)                                            \
1141   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1142    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1143
1144 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1145    SHIFT places.  */
1146 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1147   (((STRUCT) >> (SHIFT)) & (MASK))
1148
1149 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1150 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1151   (!(MICROMIPS) \
1152    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1153    : EXTRACT_BITS ((INSN).insn_opcode, \
1154                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1155 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1156   EXTRACT_BITS ((INSN).insn_opcode, \
1157                 MIPS16OP_MASK_##FIELD, \
1158                 MIPS16OP_SH_##FIELD)
1159
1160 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1161 #define MIPS16_EXTEND (0xf000U << 16)
1162 \f
1163 /* Whether or not we are emitting a branch-likely macro.  */
1164 static bfd_boolean emit_branch_likely_macro = FALSE;
1165
1166 /* Global variables used when generating relaxable macros.  See the
1167    comment above RELAX_ENCODE for more details about how relaxation
1168    is used.  */
1169 static struct {
1170   /* 0 if we're not emitting a relaxable macro.
1171      1 if we're emitting the first of the two relaxation alternatives.
1172      2 if we're emitting the second alternative.  */
1173   int sequence;
1174
1175   /* The first relaxable fixup in the current frag.  (In other words,
1176      the first fixup that refers to relaxable code.)  */
1177   fixS *first_fixup;
1178
1179   /* sizes[0] says how many bytes of the first alternative are stored in
1180      the current frag.  Likewise sizes[1] for the second alternative.  */
1181   unsigned int sizes[2];
1182
1183   /* The symbol on which the choice of sequence depends.  */
1184   symbolS *symbol;
1185 } mips_relax;
1186 \f
1187 /* Global variables used to decide whether a macro needs a warning.  */
1188 static struct {
1189   /* True if the macro is in a branch delay slot.  */
1190   bfd_boolean delay_slot_p;
1191
1192   /* Set to the length in bytes required if the macro is in a delay slot
1193      that requires a specific length of instruction, otherwise zero.  */
1194   unsigned int delay_slot_length;
1195
1196   /* For relaxable macros, sizes[0] is the length of the first alternative
1197      in bytes and sizes[1] is the length of the second alternative.
1198      For non-relaxable macros, both elements give the length of the
1199      macro in bytes.  */
1200   unsigned int sizes[2];
1201
1202   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1203      instruction of the first alternative in bytes and first_insn_sizes[1]
1204      is the length of the first instruction of the second alternative.
1205      For non-relaxable macros, both elements give the length of the first
1206      instruction in bytes.
1207
1208      Set to zero if we haven't yet seen the first instruction.  */
1209   unsigned int first_insn_sizes[2];
1210
1211   /* For relaxable macros, insns[0] is the number of instructions for the
1212      first alternative and insns[1] is the number of instructions for the
1213      second alternative.
1214
1215      For non-relaxable macros, both elements give the number of
1216      instructions for the macro.  */
1217   unsigned int insns[2];
1218
1219   /* The first variant frag for this macro.  */
1220   fragS *first_frag;
1221 } mips_macro_warning;
1222 \f
1223 /* Prototypes for static functions.  */
1224
1225 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1226
1227 static void append_insn
1228   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1229    bfd_boolean expansionp);
1230 static void mips_no_prev_insn (void);
1231 static void macro_build (expressionS *, const char *, const char *, ...);
1232 static void mips16_macro_build
1233   (expressionS *, const char *, const char *, va_list *);
1234 static void load_register (int, expressionS *, int);
1235 static void macro_start (void);
1236 static void macro_end (void);
1237 static void macro (struct mips_cl_insn *ip, char *str);
1238 static void mips16_macro (struct mips_cl_insn * ip);
1239 static void mips_ip (char *str, struct mips_cl_insn * ip);
1240 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1241 static void mips16_immed
1242   (char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1243    unsigned int, unsigned long *);
1244 static size_t my_getSmallExpression
1245   (expressionS *, bfd_reloc_code_real_type *, char *);
1246 static void my_getExpression (expressionS *, char *);
1247 static void s_align (int);
1248 static void s_change_sec (int);
1249 static void s_change_section (int);
1250 static void s_cons (int);
1251 static void s_float_cons (int);
1252 static void s_mips_globl (int);
1253 static void s_option (int);
1254 static void s_mipsset (int);
1255 static void s_abicalls (int);
1256 static void s_cpload (int);
1257 static void s_cpsetup (int);
1258 static void s_cplocal (int);
1259 static void s_cprestore (int);
1260 static void s_cpreturn (int);
1261 static void s_dtprelword (int);
1262 static void s_dtpreldword (int);
1263 static void s_tprelword (int);
1264 static void s_tpreldword (int);
1265 static void s_gpvalue (int);
1266 static void s_gpword (int);
1267 static void s_gpdword (int);
1268 static void s_ehword (int);
1269 static void s_cpadd (int);
1270 static void s_insn (int);
1271 static void s_nan (int);
1272 static void md_obj_begin (void);
1273 static void md_obj_end (void);
1274 static void s_mips_ent (int);
1275 static void s_mips_end (int);
1276 static void s_mips_frame (int);
1277 static void s_mips_mask (int reg_type);
1278 static void s_mips_stab (int);
1279 static void s_mips_weakext (int);
1280 static void s_mips_file (int);
1281 static void s_mips_loc (int);
1282 static bfd_boolean pic_need_relax (symbolS *, asection *);
1283 static int relaxed_branch_length (fragS *, asection *, int);
1284 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1285 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1286
1287 /* Table and functions used to map between CPU/ISA names, and
1288    ISA levels, and CPU numbers.  */
1289
1290 struct mips_cpu_info
1291 {
1292   const char *name;           /* CPU or ISA name.  */
1293   int flags;                  /* MIPS_CPU_* flags.  */
1294   int ase;                    /* Set of ASEs implemented by the CPU.  */
1295   int isa;                    /* ISA level.  */
1296   int cpu;                    /* CPU number (default CPU if ISA).  */
1297 };
1298
1299 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1300
1301 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1302 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1303 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1304 \f
1305 /* Command-line options.  */
1306 const char *md_shortopts = "O::g::G:";
1307
1308 enum options
1309   {
1310     OPTION_MARCH = OPTION_MD_BASE,
1311     OPTION_MTUNE,
1312     OPTION_MIPS1,
1313     OPTION_MIPS2,
1314     OPTION_MIPS3,
1315     OPTION_MIPS4,
1316     OPTION_MIPS5,
1317     OPTION_MIPS32,
1318     OPTION_MIPS64,
1319     OPTION_MIPS32R2,
1320     OPTION_MIPS64R2,
1321     OPTION_MIPS16,
1322     OPTION_NO_MIPS16,
1323     OPTION_MIPS3D,
1324     OPTION_NO_MIPS3D,
1325     OPTION_MDMX,
1326     OPTION_NO_MDMX,
1327     OPTION_DSP,
1328     OPTION_NO_DSP,
1329     OPTION_MT,
1330     OPTION_NO_MT,
1331     OPTION_VIRT,
1332     OPTION_NO_VIRT,
1333     OPTION_MSA,
1334     OPTION_NO_MSA,
1335     OPTION_SMARTMIPS,
1336     OPTION_NO_SMARTMIPS,
1337     OPTION_DSPR2,
1338     OPTION_NO_DSPR2,
1339     OPTION_EVA,
1340     OPTION_NO_EVA,
1341     OPTION_XPA,
1342     OPTION_NO_XPA,
1343     OPTION_MICROMIPS,
1344     OPTION_NO_MICROMIPS,
1345     OPTION_MCU,
1346     OPTION_NO_MCU,
1347     OPTION_COMPAT_ARCH_BASE,
1348     OPTION_M4650,
1349     OPTION_NO_M4650,
1350     OPTION_M4010,
1351     OPTION_NO_M4010,
1352     OPTION_M4100,
1353     OPTION_NO_M4100,
1354     OPTION_M3900,
1355     OPTION_NO_M3900,
1356     OPTION_M7000_HILO_FIX,
1357     OPTION_MNO_7000_HILO_FIX,
1358     OPTION_FIX_24K,
1359     OPTION_NO_FIX_24K,
1360     OPTION_FIX_RM7000,
1361     OPTION_NO_FIX_RM7000,
1362     OPTION_FIX_LOONGSON2F_JUMP,
1363     OPTION_NO_FIX_LOONGSON2F_JUMP,
1364     OPTION_FIX_LOONGSON2F_NOP,
1365     OPTION_NO_FIX_LOONGSON2F_NOP,
1366     OPTION_FIX_VR4120,
1367     OPTION_NO_FIX_VR4120,
1368     OPTION_FIX_VR4130,
1369     OPTION_NO_FIX_VR4130,
1370     OPTION_FIX_CN63XXP1,
1371     OPTION_NO_FIX_CN63XXP1,
1372     OPTION_TRAP,
1373     OPTION_BREAK,
1374     OPTION_EB,
1375     OPTION_EL,
1376     OPTION_FP32,
1377     OPTION_GP32,
1378     OPTION_CONSTRUCT_FLOATS,
1379     OPTION_NO_CONSTRUCT_FLOATS,
1380     OPTION_FP64,
1381     OPTION_GP64,
1382     OPTION_RELAX_BRANCH,
1383     OPTION_NO_RELAX_BRANCH,
1384     OPTION_INSN32,
1385     OPTION_NO_INSN32,
1386     OPTION_MSHARED,
1387     OPTION_MNO_SHARED,
1388     OPTION_MSYM32,
1389     OPTION_MNO_SYM32,
1390     OPTION_SOFT_FLOAT,
1391     OPTION_HARD_FLOAT,
1392     OPTION_SINGLE_FLOAT,
1393     OPTION_DOUBLE_FLOAT,
1394     OPTION_32,
1395     OPTION_CALL_SHARED,
1396     OPTION_CALL_NONPIC,
1397     OPTION_NON_SHARED,
1398     OPTION_XGOT,
1399     OPTION_MABI,
1400     OPTION_N32,
1401     OPTION_64,
1402     OPTION_MDEBUG,
1403     OPTION_NO_MDEBUG,
1404     OPTION_PDR,
1405     OPTION_NO_PDR,
1406     OPTION_MVXWORKS_PIC,
1407     OPTION_NAN,
1408     OPTION_END_OF_ENUM
1409   };
1410
1411 struct option md_longopts[] =
1412 {
1413   /* Options which specify architecture.  */
1414   {"march", required_argument, NULL, OPTION_MARCH},
1415   {"mtune", required_argument, NULL, OPTION_MTUNE},
1416   {"mips0", no_argument, NULL, OPTION_MIPS1},
1417   {"mips1", no_argument, NULL, OPTION_MIPS1},
1418   {"mips2", no_argument, NULL, OPTION_MIPS2},
1419   {"mips3", no_argument, NULL, OPTION_MIPS3},
1420   {"mips4", no_argument, NULL, OPTION_MIPS4},
1421   {"mips5", no_argument, NULL, OPTION_MIPS5},
1422   {"mips32", no_argument, NULL, OPTION_MIPS32},
1423   {"mips64", no_argument, NULL, OPTION_MIPS64},
1424   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1425   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1426
1427   /* Options which specify Application Specific Extensions (ASEs).  */
1428   {"mips16", no_argument, NULL, OPTION_MIPS16},
1429   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1430   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1431   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1432   {"mdmx", no_argument, NULL, OPTION_MDMX},
1433   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1434   {"mdsp", no_argument, NULL, OPTION_DSP},
1435   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1436   {"mmt", no_argument, NULL, OPTION_MT},
1437   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1438   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1439   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1440   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1441   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1442   {"meva", no_argument, NULL, OPTION_EVA},
1443   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1444   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1445   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1446   {"mmcu", no_argument, NULL, OPTION_MCU},
1447   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1448   {"mvirt", no_argument, NULL, OPTION_VIRT},
1449   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1450   {"mmsa", no_argument, NULL, OPTION_MSA},
1451   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1452   {"mxpa", no_argument, NULL, OPTION_XPA},
1453   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1454
1455   /* Old-style architecture options.  Don't add more of these.  */
1456   {"m4650", no_argument, NULL, OPTION_M4650},
1457   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1458   {"m4010", no_argument, NULL, OPTION_M4010},
1459   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1460   {"m4100", no_argument, NULL, OPTION_M4100},
1461   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1462   {"m3900", no_argument, NULL, OPTION_M3900},
1463   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1464
1465   /* Options which enable bug fixes.  */
1466   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1467   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1468   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1469   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1470   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1471   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1472   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1473   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1474   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1475   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1476   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1477   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1478   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1479   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1480   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1481   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1482   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1483
1484   /* Miscellaneous options.  */
1485   {"trap", no_argument, NULL, OPTION_TRAP},
1486   {"no-break", no_argument, NULL, OPTION_TRAP},
1487   {"break", no_argument, NULL, OPTION_BREAK},
1488   {"no-trap", no_argument, NULL, OPTION_BREAK},
1489   {"EB", no_argument, NULL, OPTION_EB},
1490   {"EL", no_argument, NULL, OPTION_EL},
1491   {"mfp32", no_argument, NULL, OPTION_FP32},
1492   {"mgp32", no_argument, NULL, OPTION_GP32},
1493   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1494   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1495   {"mfp64", no_argument, NULL, OPTION_FP64},
1496   {"mgp64", no_argument, NULL, OPTION_GP64},
1497   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1498   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1499   {"minsn32", no_argument, NULL, OPTION_INSN32},
1500   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1501   {"mshared", no_argument, NULL, OPTION_MSHARED},
1502   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1503   {"msym32", no_argument, NULL, OPTION_MSYM32},
1504   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1505   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1506   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1507   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1508   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1509
1510   /* Strictly speaking this next option is ELF specific,
1511      but we allow it for other ports as well in order to
1512      make testing easier.  */
1513   {"32", no_argument, NULL, OPTION_32},
1514
1515   /* ELF-specific options.  */
1516   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1517   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1518   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1519   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1520   {"xgot", no_argument, NULL, OPTION_XGOT},
1521   {"mabi", required_argument, NULL, OPTION_MABI},
1522   {"n32", no_argument, NULL, OPTION_N32},
1523   {"64", no_argument, NULL, OPTION_64},
1524   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1525   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1526   {"mpdr", no_argument, NULL, OPTION_PDR},
1527   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1528   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1529   {"mnan", required_argument, NULL, OPTION_NAN},
1530
1531   {NULL, no_argument, NULL, 0}
1532 };
1533 size_t md_longopts_size = sizeof (md_longopts);
1534 \f
1535 /* Information about either an Application Specific Extension or an
1536    optional architecture feature that, for simplicity, we treat in the
1537    same way as an ASE.  */
1538 struct mips_ase
1539 {
1540   /* The name of the ASE, used in both the command-line and .set options.  */
1541   const char *name;
1542
1543   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1544      and 64-bit architectures, the flags here refer to the subset that
1545      is available on both.  */
1546   unsigned int flags;
1547
1548   /* The ASE_* flag used for instructions that are available on 64-bit
1549      architectures but that are not included in FLAGS.  */
1550   unsigned int flags64;
1551
1552   /* The command-line options that turn the ASE on and off.  */
1553   int option_on;
1554   int option_off;
1555
1556   /* The minimum required architecture revisions for MIPS32, MIPS64,
1557      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1558   int mips32_rev;
1559   int mips64_rev;
1560   int micromips32_rev;
1561   int micromips64_rev;
1562 };
1563
1564 /* A table of all supported ASEs.  */
1565 static const struct mips_ase mips_ases[] = {
1566   { "dsp", ASE_DSP, ASE_DSP64,
1567     OPTION_DSP, OPTION_NO_DSP,
1568     2, 2, 2, 2 },
1569
1570   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1571     OPTION_DSPR2, OPTION_NO_DSPR2,
1572     2, 2, 2, 2 },
1573
1574   { "eva", ASE_EVA, 0,
1575     OPTION_EVA, OPTION_NO_EVA,
1576     2, 2, 2, 2 },
1577
1578   { "mcu", ASE_MCU, 0,
1579     OPTION_MCU, OPTION_NO_MCU,
1580     2, 2, 2, 2 },
1581
1582   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1583   { "mdmx", ASE_MDMX, 0,
1584     OPTION_MDMX, OPTION_NO_MDMX,
1585     -1, 1, -1, -1 },
1586
1587   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1588   { "mips3d", ASE_MIPS3D, 0,
1589     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1590     2, 1, -1, -1 },
1591
1592   { "mt", ASE_MT, 0,
1593     OPTION_MT, OPTION_NO_MT,
1594     2, 2, -1, -1 },
1595
1596   { "smartmips", ASE_SMARTMIPS, 0,
1597     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1598     1, -1, -1, -1 },
1599
1600   { "virt", ASE_VIRT, ASE_VIRT64,
1601     OPTION_VIRT, OPTION_NO_VIRT,
1602     2, 2, 2, 2 },
1603
1604   { "msa", ASE_MSA, ASE_MSA64,
1605     OPTION_MSA, OPTION_NO_MSA,
1606     2, 2, 2, 2 },
1607
1608   { "xpa", ASE_XPA, 0,
1609     OPTION_XPA, OPTION_NO_XPA,
1610     2, 2, -1, -1 }
1611 };
1612
1613 /* The set of ASEs that require -mfp64.  */
1614 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX)
1615
1616 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1617 static const unsigned int mips_ase_groups[] = {
1618   ASE_DSP | ASE_DSPR2
1619 };
1620 \f
1621 /* Pseudo-op table.
1622
1623    The following pseudo-ops from the Kane and Heinrich MIPS book
1624    should be defined here, but are currently unsupported: .alias,
1625    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1626
1627    The following pseudo-ops from the Kane and Heinrich MIPS book are
1628    specific to the type of debugging information being generated, and
1629    should be defined by the object format: .aent, .begin, .bend,
1630    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1631    .vreg.
1632
1633    The following pseudo-ops from the Kane and Heinrich MIPS book are
1634    not MIPS CPU specific, but are also not specific to the object file
1635    format.  This file is probably the best place to define them, but
1636    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1637
1638 static const pseudo_typeS mips_pseudo_table[] =
1639 {
1640   /* MIPS specific pseudo-ops.  */
1641   {"option", s_option, 0},
1642   {"set", s_mipsset, 0},
1643   {"rdata", s_change_sec, 'r'},
1644   {"sdata", s_change_sec, 's'},
1645   {"livereg", s_ignore, 0},
1646   {"abicalls", s_abicalls, 0},
1647   {"cpload", s_cpload, 0},
1648   {"cpsetup", s_cpsetup, 0},
1649   {"cplocal", s_cplocal, 0},
1650   {"cprestore", s_cprestore, 0},
1651   {"cpreturn", s_cpreturn, 0},
1652   {"dtprelword", s_dtprelword, 0},
1653   {"dtpreldword", s_dtpreldword, 0},
1654   {"tprelword", s_tprelword, 0},
1655   {"tpreldword", s_tpreldword, 0},
1656   {"gpvalue", s_gpvalue, 0},
1657   {"gpword", s_gpword, 0},
1658   {"gpdword", s_gpdword, 0},
1659   {"ehword", s_ehword, 0},
1660   {"cpadd", s_cpadd, 0},
1661   {"insn", s_insn, 0},
1662   {"nan", s_nan, 0},
1663
1664   /* Relatively generic pseudo-ops that happen to be used on MIPS
1665      chips.  */
1666   {"asciiz", stringer, 8 + 1},
1667   {"bss", s_change_sec, 'b'},
1668   {"err", s_err, 0},
1669   {"half", s_cons, 1},
1670   {"dword", s_cons, 3},
1671   {"weakext", s_mips_weakext, 0},
1672   {"origin", s_org, 0},
1673   {"repeat", s_rept, 0},
1674
1675   /* For MIPS this is non-standard, but we define it for consistency.  */
1676   {"sbss", s_change_sec, 'B'},
1677
1678   /* These pseudo-ops are defined in read.c, but must be overridden
1679      here for one reason or another.  */
1680   {"align", s_align, 0},
1681   {"byte", s_cons, 0},
1682   {"data", s_change_sec, 'd'},
1683   {"double", s_float_cons, 'd'},
1684   {"float", s_float_cons, 'f'},
1685   {"globl", s_mips_globl, 0},
1686   {"global", s_mips_globl, 0},
1687   {"hword", s_cons, 1},
1688   {"int", s_cons, 2},
1689   {"long", s_cons, 2},
1690   {"octa", s_cons, 4},
1691   {"quad", s_cons, 3},
1692   {"section", s_change_section, 0},
1693   {"short", s_cons, 1},
1694   {"single", s_float_cons, 'f'},
1695   {"stabd", s_mips_stab, 'd'},
1696   {"stabn", s_mips_stab, 'n'},
1697   {"stabs", s_mips_stab, 's'},
1698   {"text", s_change_sec, 't'},
1699   {"word", s_cons, 2},
1700
1701   { "extern", ecoff_directive_extern, 0},
1702
1703   { NULL, NULL, 0 },
1704 };
1705
1706 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1707 {
1708   /* These pseudo-ops should be defined by the object file format.
1709      However, a.out doesn't support them, so we have versions here.  */
1710   {"aent", s_mips_ent, 1},
1711   {"bgnb", s_ignore, 0},
1712   {"end", s_mips_end, 0},
1713   {"endb", s_ignore, 0},
1714   {"ent", s_mips_ent, 0},
1715   {"file", s_mips_file, 0},
1716   {"fmask", s_mips_mask, 'F'},
1717   {"frame", s_mips_frame, 0},
1718   {"loc", s_mips_loc, 0},
1719   {"mask", s_mips_mask, 'R'},
1720   {"verstamp", s_ignore, 0},
1721   { NULL, NULL, 0 },
1722 };
1723
1724 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1725    purpose of the `.dc.a' internal pseudo-op.  */
1726
1727 int
1728 mips_address_bytes (void)
1729 {
1730   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1731 }
1732
1733 extern void pop_insert (const pseudo_typeS *);
1734
1735 void
1736 mips_pop_insert (void)
1737 {
1738   pop_insert (mips_pseudo_table);
1739   if (! ECOFF_DEBUGGING)
1740     pop_insert (mips_nonecoff_pseudo_table);
1741 }
1742 \f
1743 /* Symbols labelling the current insn.  */
1744
1745 struct insn_label_list
1746 {
1747   struct insn_label_list *next;
1748   symbolS *label;
1749 };
1750
1751 static struct insn_label_list *free_insn_labels;
1752 #define label_list tc_segment_info_data.labels
1753
1754 static void mips_clear_insn_labels (void);
1755 static void mips_mark_labels (void);
1756 static void mips_compressed_mark_labels (void);
1757
1758 static inline void
1759 mips_clear_insn_labels (void)
1760 {
1761   register struct insn_label_list **pl;
1762   segment_info_type *si;
1763
1764   if (now_seg)
1765     {
1766       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1767         ;
1768       
1769       si = seg_info (now_seg);
1770       *pl = si->label_list;
1771       si->label_list = NULL;
1772     }
1773 }
1774
1775 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1776
1777 static inline void
1778 mips_mark_labels (void)
1779 {
1780   if (HAVE_CODE_COMPRESSION)
1781     mips_compressed_mark_labels ();
1782 }
1783 \f
1784 static char *expr_end;
1785
1786 /* An expression in a macro instruction.  This is set by mips_ip and
1787    mips16_ip and when populated is always an O_constant.  */
1788
1789 static expressionS imm_expr;
1790
1791 /* The relocatable field in an instruction and the relocs associated
1792    with it.  These variables are used for instructions like LUI and
1793    JAL as well as true offsets.  They are also used for address
1794    operands in macros.  */
1795
1796 static expressionS offset_expr;
1797 static bfd_reloc_code_real_type offset_reloc[3]
1798   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1799
1800 /* This is set to the resulting size of the instruction to be produced
1801    by mips16_ip if an explicit extension is used or by mips_ip if an
1802    explicit size is supplied.  */
1803
1804 static unsigned int forced_insn_length;
1805
1806 /* True if we are assembling an instruction.  All dot symbols defined during
1807    this time should be treated as code labels.  */
1808
1809 static bfd_boolean mips_assembling_insn;
1810
1811 /* The pdr segment for per procedure frame/regmask info.  Not used for
1812    ECOFF debugging.  */
1813
1814 static segT pdr_seg;
1815
1816 /* The default target format to use.  */
1817
1818 #if defined (TE_FreeBSD)
1819 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1820 #elif defined (TE_TMIPS)
1821 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1822 #else
1823 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1824 #endif
1825
1826 const char *
1827 mips_target_format (void)
1828 {
1829   switch (OUTPUT_FLAVOR)
1830     {
1831     case bfd_target_elf_flavour:
1832 #ifdef TE_VXWORKS
1833       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1834         return (target_big_endian
1835                 ? "elf32-bigmips-vxworks"
1836                 : "elf32-littlemips-vxworks");
1837 #endif
1838       return (target_big_endian
1839               ? (HAVE_64BIT_OBJECTS
1840                  ? ELF_TARGET ("elf64-", "big")
1841                  : (HAVE_NEWABI
1842                     ? ELF_TARGET ("elf32-n", "big")
1843                     : ELF_TARGET ("elf32-", "big")))
1844               : (HAVE_64BIT_OBJECTS
1845                  ? ELF_TARGET ("elf64-", "little")
1846                  : (HAVE_NEWABI
1847                     ? ELF_TARGET ("elf32-n", "little")
1848                     : ELF_TARGET ("elf32-", "little"))));
1849     default:
1850       abort ();
1851       return NULL;
1852     }
1853 }
1854
1855 /* Return the ISA revision that is currently in use, or 0 if we are
1856    generating code for MIPS V or below.  */
1857
1858 static int
1859 mips_isa_rev (void)
1860 {
1861   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1862     return 2;
1863
1864   /* microMIPS implies revision 2 or above.  */
1865   if (mips_opts.micromips)
1866     return 2;
1867
1868   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1869     return 1;
1870
1871   return 0;
1872 }
1873
1874 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1875
1876 static unsigned int
1877 mips_ase_mask (unsigned int flags)
1878 {
1879   unsigned int i;
1880
1881   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
1882     if (flags & mips_ase_groups[i])
1883       flags |= mips_ase_groups[i];
1884   return flags;
1885 }
1886
1887 /* Check whether the current ISA supports ASE.  Issue a warning if
1888    appropriate.  */
1889
1890 static void
1891 mips_check_isa_supports_ase (const struct mips_ase *ase)
1892 {
1893   const char *base;
1894   int min_rev, size;
1895   static unsigned int warned_isa;
1896   static unsigned int warned_fp32;
1897
1898   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
1899     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
1900   else
1901     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
1902   if ((min_rev < 0 || mips_isa_rev () < min_rev)
1903       && (warned_isa & ase->flags) != ase->flags)
1904     {
1905       warned_isa |= ase->flags;
1906       base = mips_opts.micromips ? "microMIPS" : "MIPS";
1907       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
1908       if (min_rev < 0)
1909         as_warn (_("the %d-bit %s architecture does not support the"
1910                    " `%s' extension"), size, base, ase->name);
1911       else
1912         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
1913                  ase->name, base, size, min_rev);
1914     }
1915   if ((ase->flags & FP64_ASES)
1916       && mips_opts.fp32
1917       && (warned_fp32 & ase->flags) != ase->flags)
1918     {
1919       warned_fp32 |= ase->flags;
1920       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
1921     }
1922 }
1923
1924 /* Check all enabled ASEs to see whether they are supported by the
1925    chosen architecture.  */
1926
1927 static void
1928 mips_check_isa_supports_ases (void)
1929 {
1930   unsigned int i, mask;
1931
1932   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1933     {
1934       mask = mips_ase_mask (mips_ases[i].flags);
1935       if ((mips_opts.ase & mask) == mips_ases[i].flags)
1936         mips_check_isa_supports_ase (&mips_ases[i]);
1937     }
1938 }
1939
1940 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
1941    that were affected.  */
1942
1943 static unsigned int
1944 mips_set_ase (const struct mips_ase *ase, bfd_boolean enabled_p)
1945 {
1946   unsigned int mask;
1947
1948   mask = mips_ase_mask (ase->flags);
1949   mips_opts.ase &= ~mask;
1950   if (enabled_p)
1951     mips_opts.ase |= ase->flags;
1952   return mask;
1953 }
1954
1955 /* Return the ASE called NAME, or null if none.  */
1956
1957 static const struct mips_ase *
1958 mips_lookup_ase (const char *name)
1959 {
1960   unsigned int i;
1961
1962   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
1963     if (strcmp (name, mips_ases[i].name) == 0)
1964       return &mips_ases[i];
1965   return NULL;
1966 }
1967
1968 /* Return the length of a microMIPS instruction in bytes.  If bits of
1969    the mask beyond the low 16 are 0, then it is a 16-bit instruction.
1970    Otherwise assume a 32-bit instruction; 48-bit instructions (0x1f
1971    major opcode) will require further modifications to the opcode
1972    table.  */
1973
1974 static inline unsigned int
1975 micromips_insn_length (const struct mips_opcode *mo)
1976 {
1977   return (mo->mask >> 16) == 0 ? 2 : 4;
1978 }
1979
1980 /* Return the length of MIPS16 instruction OPCODE.  */
1981
1982 static inline unsigned int
1983 mips16_opcode_length (unsigned long opcode)
1984 {
1985   return (opcode >> 16) == 0 ? 2 : 4;
1986 }
1987
1988 /* Return the length of instruction INSN.  */
1989
1990 static inline unsigned int
1991 insn_length (const struct mips_cl_insn *insn)
1992 {
1993   if (mips_opts.micromips)
1994     return micromips_insn_length (insn->insn_mo);
1995   else if (mips_opts.mips16)
1996     return mips16_opcode_length (insn->insn_opcode);
1997   else
1998     return 4;
1999 }
2000
2001 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2002
2003 static void
2004 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2005 {
2006   size_t i;
2007
2008   insn->insn_mo = mo;
2009   insn->insn_opcode = mo->match;
2010   insn->frag = NULL;
2011   insn->where = 0;
2012   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2013     insn->fixp[i] = NULL;
2014   insn->fixed_p = (mips_opts.noreorder > 0);
2015   insn->noreorder_p = (mips_opts.noreorder > 0);
2016   insn->mips16_absolute_jump_p = 0;
2017   insn->complete_p = 0;
2018   insn->cleared_p = 0;
2019 }
2020
2021 /* Get a list of all the operands in INSN.  */
2022
2023 static const struct mips_operand_array *
2024 insn_operands (const struct mips_cl_insn *insn)
2025 {
2026   if (insn->insn_mo >= &mips_opcodes[0]
2027       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2028     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2029
2030   if (insn->insn_mo >= &mips16_opcodes[0]
2031       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2032     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2033
2034   if (insn->insn_mo >= &micromips_opcodes[0]
2035       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2036     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2037
2038   abort ();
2039 }
2040
2041 /* Get a description of operand OPNO of INSN.  */
2042
2043 static const struct mips_operand *
2044 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2045 {
2046   const struct mips_operand_array *operands;
2047
2048   operands = insn_operands (insn);
2049   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2050     abort ();
2051   return operands->operand[opno];
2052 }
2053
2054 /* Install UVAL as the value of OPERAND in INSN.  */
2055
2056 static inline void
2057 insn_insert_operand (struct mips_cl_insn *insn,
2058                      const struct mips_operand *operand, unsigned int uval)
2059 {
2060   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2061 }
2062
2063 /* Extract the value of OPERAND from INSN.  */
2064
2065 static inline unsigned
2066 insn_extract_operand (const struct mips_cl_insn *insn,
2067                       const struct mips_operand *operand)
2068 {
2069   return mips_extract_operand (operand, insn->insn_opcode);
2070 }
2071
2072 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2073
2074 static void
2075 mips_record_compressed_mode (void)
2076 {
2077   segment_info_type *si;
2078
2079   si = seg_info (now_seg);
2080   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2081     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2082   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2083     si->tc_segment_info_data.micromips = mips_opts.micromips;
2084 }
2085
2086 /* Read a standard MIPS instruction from BUF.  */
2087
2088 static unsigned long
2089 read_insn (char *buf)
2090 {
2091   if (target_big_endian)
2092     return bfd_getb32 ((bfd_byte *) buf);
2093   else
2094     return bfd_getl32 ((bfd_byte *) buf);
2095 }
2096
2097 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2098    the next byte.  */
2099
2100 static char *
2101 write_insn (char *buf, unsigned int insn)
2102 {
2103   md_number_to_chars (buf, insn, 4);
2104   return buf + 4;
2105 }
2106
2107 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2108    has length LENGTH.  */
2109
2110 static unsigned long
2111 read_compressed_insn (char *buf, unsigned int length)
2112 {
2113   unsigned long insn;
2114   unsigned int i;
2115
2116   insn = 0;
2117   for (i = 0; i < length; i += 2)
2118     {
2119       insn <<= 16;
2120       if (target_big_endian)
2121         insn |= bfd_getb16 ((char *) buf);
2122       else
2123         insn |= bfd_getl16 ((char *) buf);
2124       buf += 2;
2125     }
2126   return insn;
2127 }
2128
2129 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2130    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2131
2132 static char *
2133 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2134 {
2135   unsigned int i;
2136
2137   for (i = 0; i < length; i += 2)
2138     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2139   return buf + length;
2140 }
2141
2142 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2143
2144 static void
2145 install_insn (const struct mips_cl_insn *insn)
2146 {
2147   char *f = insn->frag->fr_literal + insn->where;
2148   if (HAVE_CODE_COMPRESSION)
2149     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2150   else
2151     write_insn (f, insn->insn_opcode);
2152   mips_record_compressed_mode ();
2153 }
2154
2155 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2156    and install the opcode in the new location.  */
2157
2158 static void
2159 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2160 {
2161   size_t i;
2162
2163   insn->frag = frag;
2164   insn->where = where;
2165   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2166     if (insn->fixp[i] != NULL)
2167       {
2168         insn->fixp[i]->fx_frag = frag;
2169         insn->fixp[i]->fx_where = where;
2170       }
2171   install_insn (insn);
2172 }
2173
2174 /* Add INSN to the end of the output.  */
2175
2176 static void
2177 add_fixed_insn (struct mips_cl_insn *insn)
2178 {
2179   char *f = frag_more (insn_length (insn));
2180   move_insn (insn, frag_now, f - frag_now->fr_literal);
2181 }
2182
2183 /* Start a variant frag and move INSN to the start of the variant part,
2184    marking it as fixed.  The other arguments are as for frag_var.  */
2185
2186 static void
2187 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2188                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2189 {
2190   frag_grow (max_chars);
2191   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2192   insn->fixed_p = 1;
2193   frag_var (rs_machine_dependent, max_chars, var,
2194             subtype, symbol, offset, NULL);
2195 }
2196
2197 /* Insert N copies of INSN into the history buffer, starting at
2198    position FIRST.  Neither FIRST nor N need to be clipped.  */
2199
2200 static void
2201 insert_into_history (unsigned int first, unsigned int n,
2202                      const struct mips_cl_insn *insn)
2203 {
2204   if (mips_relax.sequence != 2)
2205     {
2206       unsigned int i;
2207
2208       for (i = ARRAY_SIZE (history); i-- > first;)
2209         if (i >= first + n)
2210           history[i] = history[i - n];
2211         else
2212           history[i] = *insn;
2213     }
2214 }
2215
2216 /* Clear the error in insn_error.  */
2217
2218 static void
2219 clear_insn_error (void)
2220 {
2221   memset (&insn_error, 0, sizeof (insn_error));
2222 }
2223
2224 /* Possibly record error message MSG for the current instruction.
2225    If the error is about a particular argument, ARGNUM is the 1-based
2226    number of that argument, otherwise it is 0.  FORMAT is the format
2227    of MSG.  Return true if MSG was used, false if the current message
2228    was kept.  */
2229
2230 static bfd_boolean
2231 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2232                        const char *msg)
2233 {
2234   if (argnum == 0)
2235     {
2236       /* Give priority to errors against specific arguments, and to
2237          the first whole-instruction message.  */
2238       if (insn_error.msg)
2239         return FALSE;
2240     }
2241   else
2242     {
2243       /* Keep insn_error if it is against a later argument.  */
2244       if (argnum < insn_error.min_argnum)
2245         return FALSE;
2246
2247       /* If both errors are against the same argument but are different,
2248          give up on reporting a specific error for this argument.
2249          See the comment about mips_insn_error for details.  */
2250       if (argnum == insn_error.min_argnum
2251           && insn_error.msg
2252           && strcmp (insn_error.msg, msg) != 0)
2253         {
2254           insn_error.msg = 0;
2255           insn_error.min_argnum += 1;
2256           return FALSE;
2257         }
2258     }
2259   insn_error.min_argnum = argnum;
2260   insn_error.format = format;
2261   insn_error.msg = msg;
2262   return TRUE;
2263 }
2264
2265 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2266    as for set_insn_error_format.  */
2267
2268 static void
2269 set_insn_error (int argnum, const char *msg)
2270 {
2271   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2272 }
2273
2274 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2275    as for set_insn_error_format.  */
2276
2277 static void
2278 set_insn_error_i (int argnum, const char *msg, int i)
2279 {
2280   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2281     insn_error.u.i = i;
2282 }
2283
2284 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2285    are as for set_insn_error_format.  */
2286
2287 static void
2288 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2289 {
2290   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2291     {
2292       insn_error.u.ss[0] = s1;
2293       insn_error.u.ss[1] = s2;
2294     }
2295 }
2296
2297 /* Report the error in insn_error, which is against assembly code STR.  */
2298
2299 static void
2300 report_insn_error (const char *str)
2301 {
2302   const char *msg;
2303
2304   msg = ACONCAT ((insn_error.msg, " `%s'", NULL));
2305   switch (insn_error.format)
2306     {
2307     case ERR_FMT_PLAIN:
2308       as_bad (msg, str);
2309       break;
2310
2311     case ERR_FMT_I:
2312       as_bad (msg, insn_error.u.i, str);
2313       break;
2314
2315     case ERR_FMT_SS:
2316       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2317       break;
2318     }
2319 }
2320
2321 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2322    the idea is to make it obvious at a glance that each errata is
2323    included.  */
2324
2325 static void
2326 init_vr4120_conflicts (void)
2327 {
2328 #define CONFLICT(FIRST, SECOND) \
2329     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2330
2331   /* Errata 21 - [D]DIV[U] after [D]MACC */
2332   CONFLICT (MACC, DIV);
2333   CONFLICT (DMACC, DIV);
2334
2335   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2336   CONFLICT (DMULT, DMULT);
2337   CONFLICT (DMULT, DMACC);
2338   CONFLICT (DMACC, DMULT);
2339   CONFLICT (DMACC, DMACC);
2340
2341   /* Errata 24 - MT{LO,HI} after [D]MACC */
2342   CONFLICT (MACC, MTHILO);
2343   CONFLICT (DMACC, MTHILO);
2344
2345   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2346      instruction is executed immediately after a MACC or DMACC
2347      instruction, the result of [either instruction] is incorrect."  */
2348   CONFLICT (MACC, MULT);
2349   CONFLICT (MACC, DMULT);
2350   CONFLICT (DMACC, MULT);
2351   CONFLICT (DMACC, DMULT);
2352
2353   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2354      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2355      DDIV or DDIVU instruction, the result of the MACC or
2356      DMACC instruction is incorrect.".  */
2357   CONFLICT (DMULT, MACC);
2358   CONFLICT (DMULT, DMACC);
2359   CONFLICT (DIV, MACC);
2360   CONFLICT (DIV, DMACC);
2361
2362 #undef CONFLICT
2363 }
2364
2365 struct regname {
2366   const char *name;
2367   unsigned int num;
2368 };
2369
2370 #define RNUM_MASK       0x00000ff
2371 #define RTYPE_MASK      0x0ffff00
2372 #define RTYPE_NUM       0x0000100
2373 #define RTYPE_FPU       0x0000200
2374 #define RTYPE_FCC       0x0000400
2375 #define RTYPE_VEC       0x0000800
2376 #define RTYPE_GP        0x0001000
2377 #define RTYPE_CP0       0x0002000
2378 #define RTYPE_PC        0x0004000
2379 #define RTYPE_ACC       0x0008000
2380 #define RTYPE_CCC       0x0010000
2381 #define RTYPE_VI        0x0020000
2382 #define RTYPE_VF        0x0040000
2383 #define RTYPE_R5900_I   0x0080000
2384 #define RTYPE_R5900_Q   0x0100000
2385 #define RTYPE_R5900_R   0x0200000
2386 #define RTYPE_R5900_ACC 0x0400000
2387 #define RTYPE_MSA       0x0800000
2388 #define RWARN           0x8000000
2389
2390 #define GENERIC_REGISTER_NUMBERS \
2391     {"$0",      RTYPE_NUM | 0},  \
2392     {"$1",      RTYPE_NUM | 1},  \
2393     {"$2",      RTYPE_NUM | 2},  \
2394     {"$3",      RTYPE_NUM | 3},  \
2395     {"$4",      RTYPE_NUM | 4},  \
2396     {"$5",      RTYPE_NUM | 5},  \
2397     {"$6",      RTYPE_NUM | 6},  \
2398     {"$7",      RTYPE_NUM | 7},  \
2399     {"$8",      RTYPE_NUM | 8},  \
2400     {"$9",      RTYPE_NUM | 9},  \
2401     {"$10",     RTYPE_NUM | 10}, \
2402     {"$11",     RTYPE_NUM | 11}, \
2403     {"$12",     RTYPE_NUM | 12}, \
2404     {"$13",     RTYPE_NUM | 13}, \
2405     {"$14",     RTYPE_NUM | 14}, \
2406     {"$15",     RTYPE_NUM | 15}, \
2407     {"$16",     RTYPE_NUM | 16}, \
2408     {"$17",     RTYPE_NUM | 17}, \
2409     {"$18",     RTYPE_NUM | 18}, \
2410     {"$19",     RTYPE_NUM | 19}, \
2411     {"$20",     RTYPE_NUM | 20}, \
2412     {"$21",     RTYPE_NUM | 21}, \
2413     {"$22",     RTYPE_NUM | 22}, \
2414     {"$23",     RTYPE_NUM | 23}, \
2415     {"$24",     RTYPE_NUM | 24}, \
2416     {"$25",     RTYPE_NUM | 25}, \
2417     {"$26",     RTYPE_NUM | 26}, \
2418     {"$27",     RTYPE_NUM | 27}, \
2419     {"$28",     RTYPE_NUM | 28}, \
2420     {"$29",     RTYPE_NUM | 29}, \
2421     {"$30",     RTYPE_NUM | 30}, \
2422     {"$31",     RTYPE_NUM | 31} 
2423
2424 #define FPU_REGISTER_NAMES       \
2425     {"$f0",     RTYPE_FPU | 0},  \
2426     {"$f1",     RTYPE_FPU | 1},  \
2427     {"$f2",     RTYPE_FPU | 2},  \
2428     {"$f3",     RTYPE_FPU | 3},  \
2429     {"$f4",     RTYPE_FPU | 4},  \
2430     {"$f5",     RTYPE_FPU | 5},  \
2431     {"$f6",     RTYPE_FPU | 6},  \
2432     {"$f7",     RTYPE_FPU | 7},  \
2433     {"$f8",     RTYPE_FPU | 8},  \
2434     {"$f9",     RTYPE_FPU | 9},  \
2435     {"$f10",    RTYPE_FPU | 10}, \
2436     {"$f11",    RTYPE_FPU | 11}, \
2437     {"$f12",    RTYPE_FPU | 12}, \
2438     {"$f13",    RTYPE_FPU | 13}, \
2439     {"$f14",    RTYPE_FPU | 14}, \
2440     {"$f15",    RTYPE_FPU | 15}, \
2441     {"$f16",    RTYPE_FPU | 16}, \
2442     {"$f17",    RTYPE_FPU | 17}, \
2443     {"$f18",    RTYPE_FPU | 18}, \
2444     {"$f19",    RTYPE_FPU | 19}, \
2445     {"$f20",    RTYPE_FPU | 20}, \
2446     {"$f21",    RTYPE_FPU | 21}, \
2447     {"$f22",    RTYPE_FPU | 22}, \
2448     {"$f23",    RTYPE_FPU | 23}, \
2449     {"$f24",    RTYPE_FPU | 24}, \
2450     {"$f25",    RTYPE_FPU | 25}, \
2451     {"$f26",    RTYPE_FPU | 26}, \
2452     {"$f27",    RTYPE_FPU | 27}, \
2453     {"$f28",    RTYPE_FPU | 28}, \
2454     {"$f29",    RTYPE_FPU | 29}, \
2455     {"$f30",    RTYPE_FPU | 30}, \
2456     {"$f31",    RTYPE_FPU | 31}
2457
2458 #define FPU_CONDITION_CODE_NAMES \
2459     {"$fcc0",   RTYPE_FCC | 0},  \
2460     {"$fcc1",   RTYPE_FCC | 1},  \
2461     {"$fcc2",   RTYPE_FCC | 2},  \
2462     {"$fcc3",   RTYPE_FCC | 3},  \
2463     {"$fcc4",   RTYPE_FCC | 4},  \
2464     {"$fcc5",   RTYPE_FCC | 5},  \
2465     {"$fcc6",   RTYPE_FCC | 6},  \
2466     {"$fcc7",   RTYPE_FCC | 7}
2467
2468 #define COPROC_CONDITION_CODE_NAMES         \
2469     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2470     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2471     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2472     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2473     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2474     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2475     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2476     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2477
2478 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2479     {"$a4",     RTYPE_GP | 8},  \
2480     {"$a5",     RTYPE_GP | 9},  \
2481     {"$a6",     RTYPE_GP | 10}, \
2482     {"$a7",     RTYPE_GP | 11}, \
2483     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2484     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2485     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2486     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2487     {"$t0",     RTYPE_GP | 12}, \
2488     {"$t1",     RTYPE_GP | 13}, \
2489     {"$t2",     RTYPE_GP | 14}, \
2490     {"$t3",     RTYPE_GP | 15}
2491
2492 #define O32_SYMBOLIC_REGISTER_NAMES \
2493     {"$t0",     RTYPE_GP | 8},  \
2494     {"$t1",     RTYPE_GP | 9},  \
2495     {"$t2",     RTYPE_GP | 10}, \
2496     {"$t3",     RTYPE_GP | 11}, \
2497     {"$t4",     RTYPE_GP | 12}, \
2498     {"$t5",     RTYPE_GP | 13}, \
2499     {"$t6",     RTYPE_GP | 14}, \
2500     {"$t7",     RTYPE_GP | 15}, \
2501     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2502     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2503     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2504     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */ 
2505
2506 /* Remaining symbolic register names */
2507 #define SYMBOLIC_REGISTER_NAMES \
2508     {"$zero",   RTYPE_GP | 0},  \
2509     {"$at",     RTYPE_GP | 1},  \
2510     {"$AT",     RTYPE_GP | 1},  \
2511     {"$v0",     RTYPE_GP | 2},  \
2512     {"$v1",     RTYPE_GP | 3},  \
2513     {"$a0",     RTYPE_GP | 4},  \
2514     {"$a1",     RTYPE_GP | 5},  \
2515     {"$a2",     RTYPE_GP | 6},  \
2516     {"$a3",     RTYPE_GP | 7},  \
2517     {"$s0",     RTYPE_GP | 16}, \
2518     {"$s1",     RTYPE_GP | 17}, \
2519     {"$s2",     RTYPE_GP | 18}, \
2520     {"$s3",     RTYPE_GP | 19}, \
2521     {"$s4",     RTYPE_GP | 20}, \
2522     {"$s5",     RTYPE_GP | 21}, \
2523     {"$s6",     RTYPE_GP | 22}, \
2524     {"$s7",     RTYPE_GP | 23}, \
2525     {"$t8",     RTYPE_GP | 24}, \
2526     {"$t9",     RTYPE_GP | 25}, \
2527     {"$k0",     RTYPE_GP | 26}, \
2528     {"$kt0",    RTYPE_GP | 26}, \
2529     {"$k1",     RTYPE_GP | 27}, \
2530     {"$kt1",    RTYPE_GP | 27}, \
2531     {"$gp",     RTYPE_GP | 28}, \
2532     {"$sp",     RTYPE_GP | 29}, \
2533     {"$s8",     RTYPE_GP | 30}, \
2534     {"$fp",     RTYPE_GP | 30}, \
2535     {"$ra",     RTYPE_GP | 31}
2536
2537 #define MIPS16_SPECIAL_REGISTER_NAMES \
2538     {"$pc",     RTYPE_PC | 0}
2539
2540 #define MDMX_VECTOR_REGISTER_NAMES \
2541     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2542     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2543     {"$v2",     RTYPE_VEC | 2},  \
2544     {"$v3",     RTYPE_VEC | 3},  \
2545     {"$v4",     RTYPE_VEC | 4},  \
2546     {"$v5",     RTYPE_VEC | 5},  \
2547     {"$v6",     RTYPE_VEC | 6},  \
2548     {"$v7",     RTYPE_VEC | 7},  \
2549     {"$v8",     RTYPE_VEC | 8},  \
2550     {"$v9",     RTYPE_VEC | 9},  \
2551     {"$v10",    RTYPE_VEC | 10}, \
2552     {"$v11",    RTYPE_VEC | 11}, \
2553     {"$v12",    RTYPE_VEC | 12}, \
2554     {"$v13",    RTYPE_VEC | 13}, \
2555     {"$v14",    RTYPE_VEC | 14}, \
2556     {"$v15",    RTYPE_VEC | 15}, \
2557     {"$v16",    RTYPE_VEC | 16}, \
2558     {"$v17",    RTYPE_VEC | 17}, \
2559     {"$v18",    RTYPE_VEC | 18}, \
2560     {"$v19",    RTYPE_VEC | 19}, \
2561     {"$v20",    RTYPE_VEC | 20}, \
2562     {"$v21",    RTYPE_VEC | 21}, \
2563     {"$v22",    RTYPE_VEC | 22}, \
2564     {"$v23",    RTYPE_VEC | 23}, \
2565     {"$v24",    RTYPE_VEC | 24}, \
2566     {"$v25",    RTYPE_VEC | 25}, \
2567     {"$v26",    RTYPE_VEC | 26}, \
2568     {"$v27",    RTYPE_VEC | 27}, \
2569     {"$v28",    RTYPE_VEC | 28}, \
2570     {"$v29",    RTYPE_VEC | 29}, \
2571     {"$v30",    RTYPE_VEC | 30}, \
2572     {"$v31",    RTYPE_VEC | 31}
2573
2574 #define R5900_I_NAMES \
2575     {"$I",      RTYPE_R5900_I | 0}
2576
2577 #define R5900_Q_NAMES \
2578     {"$Q",      RTYPE_R5900_Q | 0}
2579
2580 #define R5900_R_NAMES \
2581     {"$R",      RTYPE_R5900_R | 0}
2582
2583 #define R5900_ACC_NAMES \
2584     {"$ACC",    RTYPE_R5900_ACC | 0 }
2585
2586 #define MIPS_DSP_ACCUMULATOR_NAMES \
2587     {"$ac0",    RTYPE_ACC | 0}, \
2588     {"$ac1",    RTYPE_ACC | 1}, \
2589     {"$ac2",    RTYPE_ACC | 2}, \
2590     {"$ac3",    RTYPE_ACC | 3}
2591
2592 static const struct regname reg_names[] = {
2593   GENERIC_REGISTER_NUMBERS,
2594   FPU_REGISTER_NAMES,
2595   FPU_CONDITION_CODE_NAMES,
2596   COPROC_CONDITION_CODE_NAMES,
2597
2598   /* The $txx registers depends on the abi,
2599      these will be added later into the symbol table from
2600      one of the tables below once mips_abi is set after 
2601      parsing of arguments from the command line. */
2602   SYMBOLIC_REGISTER_NAMES,
2603
2604   MIPS16_SPECIAL_REGISTER_NAMES,
2605   MDMX_VECTOR_REGISTER_NAMES,
2606   R5900_I_NAMES,
2607   R5900_Q_NAMES,
2608   R5900_R_NAMES,
2609   R5900_ACC_NAMES,
2610   MIPS_DSP_ACCUMULATOR_NAMES,
2611   {0, 0}
2612 };
2613
2614 static const struct regname reg_names_o32[] = {
2615   O32_SYMBOLIC_REGISTER_NAMES,
2616   {0, 0}
2617 };
2618
2619 static const struct regname reg_names_n32n64[] = {
2620   N32N64_SYMBOLIC_REGISTER_NAMES,
2621   {0, 0}
2622 };
2623
2624 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2625    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2626    of these register symbols, return the associated vector register,
2627    otherwise return SYMVAL itself.  */
2628
2629 static unsigned int
2630 mips_prefer_vec_regno (unsigned int symval)
2631 {
2632   if ((symval & -2) == (RTYPE_GP | 2))
2633     return RTYPE_VEC | (symval & 1);
2634   return symval;
2635 }
2636
2637 /* Return true if string [S, E) is a valid register name, storing its
2638    symbol value in *SYMVAL_PTR if so.  */
2639
2640 static bfd_boolean
2641 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2642 {
2643   char save_c;
2644   symbolS *symbol;
2645
2646   /* Terminate name.  */
2647   save_c = *e;
2648   *e = '\0';
2649
2650   /* Look up the name.  */
2651   symbol = symbol_find (s);
2652   *e = save_c;
2653
2654   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2655     return FALSE;
2656
2657   *symval_ptr = S_GET_VALUE (symbol);
2658   return TRUE;
2659 }
2660
2661 /* Return true if the string at *SPTR is a valid register name.  Allow it
2662    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2663    is nonnull.
2664
2665    When returning true, move *SPTR past the register, store the
2666    register's symbol value in *SYMVAL_PTR and the channel mask in
2667    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2668    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2669    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2670
2671 static bfd_boolean
2672 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2673                      unsigned int *channels_ptr)
2674 {
2675   char *s, *e, *m;
2676   const char *q;
2677   unsigned int channels, symval, bit;
2678
2679   /* Find end of name.  */
2680   s = e = *sptr;
2681   if (is_name_beginner (*e))
2682     ++e;
2683   while (is_part_of_name (*e))
2684     ++e;
2685
2686   channels = 0;
2687   if (!mips_parse_register_1 (s, e, &symval))
2688     {
2689       if (!channels_ptr)
2690         return FALSE;
2691
2692       /* Eat characters from the end of the string that are valid
2693          channel suffixes.  The preceding register must be $ACC or
2694          end with a digit, so there is no ambiguity.  */
2695       bit = 1;
2696       m = e;
2697       for (q = "wzyx"; *q; q++, bit <<= 1)
2698         if (m > s && m[-1] == *q)
2699           {
2700             --m;
2701             channels |= bit;
2702           }
2703
2704       if (channels == 0
2705           || !mips_parse_register_1 (s, m, &symval)
2706           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2707         return FALSE;
2708     }
2709
2710   *sptr = e;
2711   *symval_ptr = symval;
2712   if (channels_ptr)
2713     *channels_ptr = channels;
2714   return TRUE;
2715 }
2716
2717 /* Check if SPTR points at a valid register specifier according to TYPES.
2718    If so, then return 1, advance S to consume the specifier and store
2719    the register's number in REGNOP, otherwise return 0.  */
2720
2721 static int
2722 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2723 {
2724   unsigned int regno;
2725
2726   if (mips_parse_register (s, &regno, NULL))
2727     {
2728       if (types & RTYPE_VEC)
2729         regno = mips_prefer_vec_regno (regno);
2730       if (regno & types)
2731         regno &= RNUM_MASK;
2732       else
2733         regno = ~0;
2734     }
2735   else
2736     {
2737       if (types & RWARN)
2738         as_warn (_("unrecognized register name `%s'"), *s);
2739       regno = ~0;
2740     }
2741   if (regnop)
2742     *regnop = regno;
2743   return regno <= RNUM_MASK;
2744 }
2745
2746 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2747    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2748
2749 static char *
2750 mips_parse_vu0_channels (char *s, unsigned int *channels)
2751 {
2752   unsigned int i;
2753
2754   *channels = 0;
2755   for (i = 0; i < 4; i++)
2756     if (*s == "xyzw"[i])
2757       {
2758         *channels |= 1 << (3 - i);
2759         ++s;
2760       }
2761   return s;
2762 }
2763
2764 /* Token types for parsed operand lists.  */
2765 enum mips_operand_token_type {
2766   /* A plain register, e.g. $f2.  */
2767   OT_REG,
2768
2769   /* A 4-bit XYZW channel mask.  */
2770   OT_CHANNELS,
2771
2772   /* A constant vector index, e.g. [1].  */
2773   OT_INTEGER_INDEX,
2774
2775   /* A register vector index, e.g. [$2].  */
2776   OT_REG_INDEX,
2777
2778   /* A continuous range of registers, e.g. $s0-$s4.  */
2779   OT_REG_RANGE,
2780
2781   /* A (possibly relocated) expression.  */
2782   OT_INTEGER,
2783
2784   /* A floating-point value.  */
2785   OT_FLOAT,
2786
2787   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2788      before OT_REGs.  */
2789   OT_CHAR,
2790
2791   /* A doubled character, either "--" or "++".  */
2792   OT_DOUBLE_CHAR,
2793
2794   /* The end of the operand list.  */
2795   OT_END
2796 };
2797
2798 /* A parsed operand token.  */
2799 struct mips_operand_token
2800 {
2801   /* The type of token.  */
2802   enum mips_operand_token_type type;
2803   union
2804   {
2805     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2806     unsigned int regno;
2807
2808     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2809     unsigned int channels;
2810
2811     /* The integer value of an OT_INTEGER_INDEX.  */
2812     addressT index;
2813
2814     /* The two register symbol values involved in an OT_REG_RANGE.  */
2815     struct {
2816       unsigned int regno1;
2817       unsigned int regno2;
2818     } reg_range;
2819
2820     /* The value of an OT_INTEGER.  The value is represented as an
2821        expression and the relocation operators that were applied to
2822        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2823        relocation operators were used.  */
2824     struct {
2825       expressionS value;
2826       bfd_reloc_code_real_type relocs[3];
2827     } integer;
2828
2829     /* The binary data for an OT_FLOAT constant, and the number of bytes
2830        in the constant.  */
2831     struct {
2832       unsigned char data[8];
2833       int length;
2834     } flt;
2835
2836     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2837     char ch;
2838   } u;
2839 };
2840
2841 /* An obstack used to construct lists of mips_operand_tokens.  */
2842 static struct obstack mips_operand_tokens;
2843
2844 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2845
2846 static void
2847 mips_add_token (struct mips_operand_token *token,
2848                 enum mips_operand_token_type type)
2849 {
2850   token->type = type;
2851   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2852 }
2853
2854 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2855    and OT_REG tokens for them if so, and return a pointer to the first
2856    unconsumed character.  Return null otherwise.  */
2857
2858 static char *
2859 mips_parse_base_start (char *s)
2860 {
2861   struct mips_operand_token token;
2862   unsigned int regno, channels;
2863   bfd_boolean decrement_p;
2864
2865   if (*s != '(')
2866     return 0;
2867
2868   ++s;
2869   SKIP_SPACE_TABS (s);
2870
2871   /* Only match "--" as part of a base expression.  In other contexts "--X"
2872      is a double negative.  */
2873   decrement_p = (s[0] == '-' && s[1] == '-');
2874   if (decrement_p)
2875     {
2876       s += 2;
2877       SKIP_SPACE_TABS (s);
2878     }
2879
2880   /* Allow a channel specifier because that leads to better error messages
2881      than treating something like "$vf0x++" as an expression.  */
2882   if (!mips_parse_register (&s, &regno, &channels))
2883     return 0;
2884
2885   token.u.ch = '(';
2886   mips_add_token (&token, OT_CHAR);
2887
2888   if (decrement_p)
2889     {
2890       token.u.ch = '-';
2891       mips_add_token (&token, OT_DOUBLE_CHAR);
2892     }
2893
2894   token.u.regno = regno;
2895   mips_add_token (&token, OT_REG);
2896
2897   if (channels)
2898     {
2899       token.u.channels = channels;
2900       mips_add_token (&token, OT_CHANNELS);
2901     }
2902
2903   /* For consistency, only match "++" as part of base expressions too.  */
2904   SKIP_SPACE_TABS (s);
2905   if (s[0] == '+' && s[1] == '+')
2906     {
2907       s += 2;
2908       token.u.ch = '+';
2909       mips_add_token (&token, OT_DOUBLE_CHAR);
2910     }
2911
2912   return s;
2913 }
2914
2915 /* Parse one or more tokens from S.  Return a pointer to the first
2916    unconsumed character on success.  Return null if an error was found
2917    and store the error text in insn_error.  FLOAT_FORMAT is as for
2918    mips_parse_arguments.  */
2919
2920 static char *
2921 mips_parse_argument_token (char *s, char float_format)
2922 {
2923   char *end, *save_in, *err;
2924   unsigned int regno1, regno2, channels;
2925   struct mips_operand_token token;
2926
2927   /* First look for "($reg", since we want to treat that as an
2928      OT_CHAR and OT_REG rather than an expression.  */
2929   end = mips_parse_base_start (s);
2930   if (end)
2931     return end;
2932
2933   /* Handle other characters that end up as OT_CHARs.  */
2934   if (*s == ')' || *s == ',')
2935     {
2936       token.u.ch = *s;
2937       mips_add_token (&token, OT_CHAR);
2938       ++s;
2939       return s;
2940     }
2941
2942   /* Handle tokens that start with a register.  */
2943   if (mips_parse_register (&s, &regno1, &channels))
2944     {
2945       if (channels)
2946         {
2947           /* A register and a VU0 channel suffix.  */
2948           token.u.regno = regno1;
2949           mips_add_token (&token, OT_REG);
2950
2951           token.u.channels = channels;
2952           mips_add_token (&token, OT_CHANNELS);
2953           return s;
2954         }
2955
2956       SKIP_SPACE_TABS (s);
2957       if (*s == '-')
2958         {
2959           /* A register range.  */
2960           ++s;
2961           SKIP_SPACE_TABS (s);
2962           if (!mips_parse_register (&s, &regno2, NULL))
2963             {
2964               set_insn_error (0, _("invalid register range"));
2965               return 0;
2966             }
2967
2968           token.u.reg_range.regno1 = regno1;
2969           token.u.reg_range.regno2 = regno2;
2970           mips_add_token (&token, OT_REG_RANGE);
2971           return s;
2972         }
2973
2974       /* Add the register itself.  */
2975       token.u.regno = regno1;
2976       mips_add_token (&token, OT_REG);
2977
2978       /* Check for a vector index.  */
2979       if (*s == '[')
2980         {
2981           ++s;
2982           SKIP_SPACE_TABS (s);
2983           if (mips_parse_register (&s, &token.u.regno, NULL))
2984             mips_add_token (&token, OT_REG_INDEX);
2985           else
2986             {
2987               expressionS element;
2988
2989               my_getExpression (&element, s);
2990               if (element.X_op != O_constant)
2991                 {
2992                   set_insn_error (0, _("vector element must be constant"));
2993                   return 0;
2994                 }
2995               s = expr_end;
2996               token.u.index = element.X_add_number;
2997               mips_add_token (&token, OT_INTEGER_INDEX);
2998             }
2999           SKIP_SPACE_TABS (s);
3000           if (*s != ']')
3001             {
3002               set_insn_error (0, _("missing `]'"));
3003               return 0;
3004             }
3005           ++s;
3006         }
3007       return s;
3008     }
3009
3010   if (float_format)
3011     {
3012       /* First try to treat expressions as floats.  */
3013       save_in = input_line_pointer;
3014       input_line_pointer = s;
3015       err = md_atof (float_format, (char *) token.u.flt.data,
3016                      &token.u.flt.length);
3017       end = input_line_pointer;
3018       input_line_pointer = save_in;
3019       if (err && *err)
3020         {
3021           set_insn_error (0, err);
3022           return 0;
3023         }
3024       if (s != end)
3025         {
3026           mips_add_token (&token, OT_FLOAT);
3027           return end;
3028         }
3029     }
3030
3031   /* Treat everything else as an integer expression.  */
3032   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3033   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3034   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3035   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3036   s = expr_end;
3037   mips_add_token (&token, OT_INTEGER);
3038   return s;
3039 }
3040
3041 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3042    if expressions should be treated as 32-bit floating-point constants,
3043    'd' if they should be treated as 64-bit floating-point constants,
3044    or 0 if they should be treated as integer expressions (the usual case).
3045
3046    Return a list of tokens on success, otherwise return 0.  The caller
3047    must obstack_free the list after use.  */
3048
3049 static struct mips_operand_token *
3050 mips_parse_arguments (char *s, char float_format)
3051 {
3052   struct mips_operand_token token;
3053
3054   SKIP_SPACE_TABS (s);
3055   while (*s)
3056     {
3057       s = mips_parse_argument_token (s, float_format);
3058       if (!s)
3059         {
3060           obstack_free (&mips_operand_tokens,
3061                         obstack_finish (&mips_operand_tokens));
3062           return 0;
3063         }
3064       SKIP_SPACE_TABS (s);
3065     }
3066   mips_add_token (&token, OT_END);
3067   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3068 }
3069
3070 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3071    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3072
3073 static bfd_boolean
3074 is_opcode_valid (const struct mips_opcode *mo)
3075 {
3076   int isa = mips_opts.isa;
3077   int ase = mips_opts.ase;
3078   int fp_s, fp_d;
3079   unsigned int i;
3080
3081   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3082     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3083       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3084         ase |= mips_ases[i].flags64;
3085
3086   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3087     return FALSE;
3088
3089   /* Check whether the instruction or macro requires single-precision or
3090      double-precision floating-point support.  Note that this information is
3091      stored differently in the opcode table for insns and macros.  */
3092   if (mo->pinfo == INSN_MACRO)
3093     {
3094       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3095       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3096     }
3097   else
3098     {
3099       fp_s = mo->pinfo & FP_S;
3100       fp_d = mo->pinfo & FP_D;
3101     }
3102
3103   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3104     return FALSE;
3105
3106   if (fp_s && mips_opts.soft_float)
3107     return FALSE;
3108
3109   return TRUE;
3110 }
3111
3112 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3113    selected ISA and architecture.  */
3114
3115 static bfd_boolean
3116 is_opcode_valid_16 (const struct mips_opcode *mo)
3117 {
3118   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3119 }
3120
3121 /* Return TRUE if the size of the microMIPS opcode MO matches one
3122    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3123
3124 static bfd_boolean
3125 is_size_valid (const struct mips_opcode *mo)
3126 {
3127   if (!mips_opts.micromips)
3128     return TRUE;
3129
3130   if (mips_opts.insn32)
3131     {
3132       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3133         return FALSE;
3134       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3135         return FALSE;
3136     }
3137   if (!forced_insn_length)
3138     return TRUE;
3139   if (mo->pinfo == INSN_MACRO)
3140     return FALSE;
3141   return forced_insn_length == micromips_insn_length (mo);
3142 }
3143
3144 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3145    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3146
3147    We don't accept macros in 16-bit delay slots to avoid a case where
3148    a macro expansion fails because it relies on a preceding 32-bit real
3149    instruction to have matched and does not handle the operands correctly.
3150    The only macros that may expand to 16-bit instructions are JAL that
3151    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3152    and BGT (that likewise cannot be placed in a delay slot) that decay to
3153    a NOP.  In all these cases the macros precede any corresponding real
3154    instruction definitions in the opcode table, so they will match in the
3155    second pass where the size of the delay slot is ignored and therefore
3156    produce correct code.  */
3157
3158 static bfd_boolean
3159 is_delay_slot_valid (const struct mips_opcode *mo)
3160 {
3161   if (!mips_opts.micromips)
3162     return TRUE;
3163
3164   if (mo->pinfo == INSN_MACRO)
3165     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3166   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3167       && micromips_insn_length (mo) != 4)
3168     return FALSE;
3169   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3170       && micromips_insn_length (mo) != 2)
3171     return FALSE;
3172
3173   return TRUE;
3174 }
3175
3176 /* For consistency checking, verify that all bits of OPCODE are specified
3177    either by the match/mask part of the instruction definition, or by the
3178    operand list.  Also build up a list of operands in OPERANDS.
3179
3180    INSN_BITS says which bits of the instruction are significant.
3181    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3182    provides the mips_operand description of each operand.  DECODE_OPERAND
3183    is null for MIPS16 instructions.  */
3184
3185 static int
3186 validate_mips_insn (const struct mips_opcode *opcode,
3187                     unsigned long insn_bits,
3188                     const struct mips_operand *(*decode_operand) (const char *),
3189                     struct mips_operand_array *operands)
3190 {
3191   const char *s;
3192   unsigned long used_bits, doubled, undefined, opno, mask;
3193   const struct mips_operand *operand;
3194
3195   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3196   if ((mask & opcode->match) != opcode->match)
3197     {
3198       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3199               opcode->name, opcode->args);
3200       return 0;
3201     }
3202   used_bits = 0;
3203   opno = 0;
3204   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3205     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3206   for (s = opcode->args; *s; ++s)
3207     switch (*s)
3208       {
3209       case ',':
3210       case '(':
3211       case ')':
3212         break;
3213
3214       case '#':
3215         s++;
3216         break;
3217
3218       default:
3219         if (!decode_operand)
3220           operand = decode_mips16_operand (*s, FALSE);
3221         else
3222           operand = decode_operand (s);
3223         if (!operand && opcode->pinfo != INSN_MACRO)
3224           {
3225             as_bad (_("internal: unknown operand type: %s %s"),
3226                     opcode->name, opcode->args);
3227             return 0;
3228           }
3229         gas_assert (opno < MAX_OPERANDS);
3230         operands->operand[opno] = operand;
3231         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3232           {
3233             used_bits = mips_insert_operand (operand, used_bits, -1);
3234             if (operand->type == OP_MDMX_IMM_REG)
3235               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3236                  has separate entries for each format.  */
3237               used_bits &= ~(1 << (operand->lsb + 5));
3238             if (operand->type == OP_ENTRY_EXIT_LIST)
3239               used_bits &= ~(mask & 0x700);
3240           }
3241         /* Skip prefix characters.  */
3242         if (decode_operand && (*s == '+' || *s == 'm'))
3243           ++s;
3244         opno += 1;
3245         break;
3246       }
3247   doubled = used_bits & mask & insn_bits;
3248   if (doubled)
3249     {
3250       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3251                 " %s %s"), doubled, opcode->name, opcode->args);
3252       return 0;
3253     }
3254   used_bits |= mask;
3255   undefined = ~used_bits & insn_bits;
3256   if (opcode->pinfo != INSN_MACRO && undefined)
3257     {
3258       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3259               undefined, opcode->name, opcode->args);
3260       return 0;
3261     }
3262   used_bits &= ~insn_bits;
3263   if (used_bits)
3264     {
3265       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3266               used_bits, opcode->name, opcode->args);
3267       return 0;
3268     }
3269   return 1;
3270 }
3271
3272 /* The MIPS16 version of validate_mips_insn.  */
3273
3274 static int
3275 validate_mips16_insn (const struct mips_opcode *opcode,
3276                       struct mips_operand_array *operands)
3277 {
3278   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3279     {
3280       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3281          instruction.  Use TMP to describe the full instruction.  */
3282       struct mips_opcode tmp;
3283
3284       tmp = *opcode;
3285       tmp.match <<= 16;
3286       tmp.mask <<= 16;
3287       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3288     }
3289   return validate_mips_insn (opcode, 0xffff, 0, operands);
3290 }
3291
3292 /* The microMIPS version of validate_mips_insn.  */
3293
3294 static int
3295 validate_micromips_insn (const struct mips_opcode *opc,
3296                          struct mips_operand_array *operands)
3297 {
3298   unsigned long insn_bits;
3299   unsigned long major;
3300   unsigned int length;
3301
3302   if (opc->pinfo == INSN_MACRO)
3303     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3304                                operands);
3305
3306   length = micromips_insn_length (opc);
3307   if (length != 2 && length != 4)
3308     {
3309       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3310                 "%s %s"), length, opc->name, opc->args);
3311       return 0;
3312     }
3313   major = opc->match >> (10 + 8 * (length - 2));
3314   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3315       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3316     {
3317       as_bad (_("internal error: bad microMIPS opcode "
3318                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3319       return 0;
3320     }
3321
3322   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3323   insn_bits = 1 << 4 * length;
3324   insn_bits <<= 4 * length;
3325   insn_bits -= 1;
3326   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3327                              operands);
3328 }
3329
3330 /* This function is called once, at assembler startup time.  It should set up
3331    all the tables, etc. that the MD part of the assembler will need.  */
3332
3333 void
3334 md_begin (void)
3335 {
3336   const char *retval = NULL;
3337   int i = 0;
3338   int broken = 0;
3339
3340   if (mips_pic != NO_PIC)
3341     {
3342       if (g_switch_seen && g_switch_value != 0)
3343         as_bad (_("-G may not be used in position-independent code"));
3344       g_switch_value = 0;
3345     }
3346
3347   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_arch))
3348     as_warn (_("could not set architecture and machine"));
3349
3350   op_hash = hash_new ();
3351
3352   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3353   for (i = 0; i < NUMOPCODES;)
3354     {
3355       const char *name = mips_opcodes[i].name;
3356
3357       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3358       if (retval != NULL)
3359         {
3360           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3361                    mips_opcodes[i].name, retval);
3362           /* Probably a memory allocation problem?  Give up now.  */
3363           as_fatal (_("broken assembler, no assembly attempted"));
3364         }
3365       do
3366         {
3367           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3368                                    decode_mips_operand, &mips_operands[i]))
3369             broken = 1;
3370           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3371             {
3372               create_insn (&nop_insn, mips_opcodes + i);
3373               if (mips_fix_loongson2f_nop)
3374                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3375               nop_insn.fixed_p = 1;
3376             }
3377           ++i;
3378         }
3379       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3380     }
3381
3382   mips16_op_hash = hash_new ();
3383   mips16_operands = XCNEWVEC (struct mips_operand_array,
3384                               bfd_mips16_num_opcodes);
3385
3386   i = 0;
3387   while (i < bfd_mips16_num_opcodes)
3388     {
3389       const char *name = mips16_opcodes[i].name;
3390
3391       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3392       if (retval != NULL)
3393         as_fatal (_("internal: can't hash `%s': %s"),
3394                   mips16_opcodes[i].name, retval);
3395       do
3396         {
3397           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3398             broken = 1;
3399           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3400             {
3401               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3402               mips16_nop_insn.fixed_p = 1;
3403             }
3404           ++i;
3405         }
3406       while (i < bfd_mips16_num_opcodes
3407              && strcmp (mips16_opcodes[i].name, name) == 0);
3408     }
3409
3410   micromips_op_hash = hash_new ();
3411   micromips_operands = XCNEWVEC (struct mips_operand_array,
3412                                  bfd_micromips_num_opcodes);
3413
3414   i = 0;
3415   while (i < bfd_micromips_num_opcodes)
3416     {
3417       const char *name = micromips_opcodes[i].name;
3418
3419       retval = hash_insert (micromips_op_hash, name,
3420                             (void *) &micromips_opcodes[i]);
3421       if (retval != NULL)
3422         as_fatal (_("internal: can't hash `%s': %s"),
3423                   micromips_opcodes[i].name, retval);
3424       do
3425         {
3426           struct mips_cl_insn *micromips_nop_insn;
3427
3428           if (!validate_micromips_insn (&micromips_opcodes[i],
3429                                         &micromips_operands[i]))
3430             broken = 1;
3431
3432           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3433             {
3434               if (micromips_insn_length (micromips_opcodes + i) == 2)
3435                 micromips_nop_insn = &micromips_nop16_insn;
3436               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3437                 micromips_nop_insn = &micromips_nop32_insn;
3438               else
3439                 continue;
3440
3441               if (micromips_nop_insn->insn_mo == NULL
3442                   && strcmp (name, "nop") == 0)
3443                 {
3444                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3445                   micromips_nop_insn->fixed_p = 1;
3446                 }
3447             }
3448         }
3449       while (++i < bfd_micromips_num_opcodes
3450              && strcmp (micromips_opcodes[i].name, name) == 0);
3451     }
3452
3453   if (broken)
3454     as_fatal (_("broken assembler, no assembly attempted"));
3455
3456   /* We add all the general register names to the symbol table.  This
3457      helps us detect invalid uses of them.  */
3458   for (i = 0; reg_names[i].name; i++) 
3459     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3460                                      reg_names[i].num, /* & RNUM_MASK, */
3461                                      &zero_address_frag));
3462   if (HAVE_NEWABI)
3463     for (i = 0; reg_names_n32n64[i].name; i++) 
3464       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3465                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3466                                        &zero_address_frag));
3467   else
3468     for (i = 0; reg_names_o32[i].name; i++) 
3469       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3470                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3471                                        &zero_address_frag));
3472
3473   for (i = 0; i < 32; i++)
3474     {
3475       char regname[7];
3476
3477       /* R5900 VU0 floating-point register.  */
3478       regname[sizeof (rename) - 1] = 0;
3479       snprintf (regname, sizeof (regname) - 1, "$vf%d", i);
3480       symbol_table_insert (symbol_new (regname, reg_section,
3481                                        RTYPE_VF | i, &zero_address_frag));
3482
3483       /* R5900 VU0 integer register.  */
3484       snprintf (regname, sizeof (regname) - 1, "$vi%d", i);
3485       symbol_table_insert (symbol_new (regname, reg_section,
3486                                        RTYPE_VI | i, &zero_address_frag));
3487
3488       /* MSA register.  */
3489       snprintf (regname, sizeof (regname) - 1, "$w%d", i);
3490       symbol_table_insert (symbol_new (regname, reg_section,
3491                                        RTYPE_MSA | i, &zero_address_frag));
3492     }
3493
3494   obstack_init (&mips_operand_tokens);
3495
3496   mips_no_prev_insn ();
3497
3498   mips_gprmask = 0;
3499   mips_cprmask[0] = 0;
3500   mips_cprmask[1] = 0;
3501   mips_cprmask[2] = 0;
3502   mips_cprmask[3] = 0;
3503
3504   /* set the default alignment for the text section (2**2) */
3505   record_alignment (text_section, 2);
3506
3507   bfd_set_gp_size (stdoutput, g_switch_value);
3508
3509   /* On a native system other than VxWorks, sections must be aligned
3510      to 16 byte boundaries.  When configured for an embedded ELF
3511      target, we don't bother.  */
3512   if (strncmp (TARGET_OS, "elf", 3) != 0
3513       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3514     {
3515       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3516       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3517       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3518     }
3519
3520   /* Create a .reginfo section for register masks and a .mdebug
3521      section for debugging information.  */
3522   {
3523     segT seg;
3524     subsegT subseg;
3525     flagword flags;
3526     segT sec;
3527
3528     seg = now_seg;
3529     subseg = now_subseg;
3530
3531     /* The ABI says this section should be loaded so that the
3532        running program can access it.  However, we don't load it
3533        if we are configured for an embedded target */
3534     flags = SEC_READONLY | SEC_DATA;
3535     if (strncmp (TARGET_OS, "elf", 3) != 0)
3536       flags |= SEC_ALLOC | SEC_LOAD;
3537
3538     if (mips_abi != N64_ABI)
3539       {
3540         sec = subseg_new (".reginfo", (subsegT) 0);
3541
3542         bfd_set_section_flags (stdoutput, sec, flags);
3543         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3544
3545         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3546       }
3547     else
3548       {
3549         /* The 64-bit ABI uses a .MIPS.options section rather than
3550            .reginfo section.  */
3551         sec = subseg_new (".MIPS.options", (subsegT) 0);
3552         bfd_set_section_flags (stdoutput, sec, flags);
3553         bfd_set_section_alignment (stdoutput, sec, 3);
3554
3555         /* Set up the option header.  */
3556         {
3557           Elf_Internal_Options opthdr;
3558           char *f;
3559
3560           opthdr.kind = ODK_REGINFO;
3561           opthdr.size = (sizeof (Elf_External_Options)
3562                          + sizeof (Elf64_External_RegInfo));
3563           opthdr.section = 0;
3564           opthdr.info = 0;
3565           f = frag_more (sizeof (Elf_External_Options));
3566           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3567                                          (Elf_External_Options *) f);
3568
3569           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3570         }
3571       }
3572
3573     if (ECOFF_DEBUGGING)
3574       {
3575         sec = subseg_new (".mdebug", (subsegT) 0);
3576         (void) bfd_set_section_flags (stdoutput, sec,
3577                                       SEC_HAS_CONTENTS | SEC_READONLY);
3578         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3579       }
3580     else if (mips_flag_pdr)
3581       {
3582         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3583         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3584                                       SEC_READONLY | SEC_RELOC
3585                                       | SEC_DEBUGGING);
3586         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3587       }
3588
3589     subseg_set (seg, subseg);
3590   }
3591
3592   if (! ECOFF_DEBUGGING)
3593     md_obj_begin ();
3594
3595   if (mips_fix_vr4120)
3596     init_vr4120_conflicts ();
3597 }
3598
3599 void
3600 md_mips_end (void)
3601 {
3602   mips_emit_delays ();
3603   if (! ECOFF_DEBUGGING)
3604     md_obj_end ();
3605 }
3606
3607 void
3608 md_assemble (char *str)
3609 {
3610   struct mips_cl_insn insn;
3611   bfd_reloc_code_real_type unused_reloc[3]
3612     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
3613
3614   imm_expr.X_op = O_absent;
3615   offset_expr.X_op = O_absent;
3616   offset_reloc[0] = BFD_RELOC_UNUSED;
3617   offset_reloc[1] = BFD_RELOC_UNUSED;
3618   offset_reloc[2] = BFD_RELOC_UNUSED;
3619
3620   mips_mark_labels ();
3621   mips_assembling_insn = TRUE;
3622   clear_insn_error ();
3623
3624   if (mips_opts.mips16)
3625     mips16_ip (str, &insn);
3626   else
3627     {
3628       mips_ip (str, &insn);
3629       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
3630             str, insn.insn_opcode));
3631     }
3632
3633   if (insn_error.msg)
3634     report_insn_error (str);
3635   else if (insn.insn_mo->pinfo == INSN_MACRO)
3636     {
3637       macro_start ();
3638       if (mips_opts.mips16)
3639         mips16_macro (&insn);
3640       else
3641         macro (&insn, str);
3642       macro_end ();
3643     }
3644   else
3645     {
3646       if (offset_expr.X_op != O_absent)
3647         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
3648       else
3649         append_insn (&insn, NULL, unused_reloc, FALSE);
3650     }
3651
3652   mips_assembling_insn = FALSE;
3653 }
3654
3655 /* Convenience functions for abstracting away the differences between
3656    MIPS16 and non-MIPS16 relocations.  */
3657
3658 static inline bfd_boolean
3659 mips16_reloc_p (bfd_reloc_code_real_type reloc)
3660 {
3661   switch (reloc)
3662     {
3663     case BFD_RELOC_MIPS16_JMP:
3664     case BFD_RELOC_MIPS16_GPREL:
3665     case BFD_RELOC_MIPS16_GOT16:
3666     case BFD_RELOC_MIPS16_CALL16:
3667     case BFD_RELOC_MIPS16_HI16_S:
3668     case BFD_RELOC_MIPS16_HI16:
3669     case BFD_RELOC_MIPS16_LO16:
3670       return TRUE;
3671
3672     default:
3673       return FALSE;
3674     }
3675 }
3676
3677 static inline bfd_boolean
3678 micromips_reloc_p (bfd_reloc_code_real_type reloc)
3679 {
3680   switch (reloc)
3681     {
3682     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3683     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3684     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3685     case BFD_RELOC_MICROMIPS_GPREL16:
3686     case BFD_RELOC_MICROMIPS_JMP:
3687     case BFD_RELOC_MICROMIPS_HI16:
3688     case BFD_RELOC_MICROMIPS_HI16_S:
3689     case BFD_RELOC_MICROMIPS_LO16:
3690     case BFD_RELOC_MICROMIPS_LITERAL:
3691     case BFD_RELOC_MICROMIPS_GOT16:
3692     case BFD_RELOC_MICROMIPS_CALL16:
3693     case BFD_RELOC_MICROMIPS_GOT_HI16:
3694     case BFD_RELOC_MICROMIPS_GOT_LO16:
3695     case BFD_RELOC_MICROMIPS_CALL_HI16:
3696     case BFD_RELOC_MICROMIPS_CALL_LO16:
3697     case BFD_RELOC_MICROMIPS_SUB:
3698     case BFD_RELOC_MICROMIPS_GOT_PAGE:
3699     case BFD_RELOC_MICROMIPS_GOT_OFST:
3700     case BFD_RELOC_MICROMIPS_GOT_DISP:
3701     case BFD_RELOC_MICROMIPS_HIGHEST:
3702     case BFD_RELOC_MICROMIPS_HIGHER:
3703     case BFD_RELOC_MICROMIPS_SCN_DISP:
3704     case BFD_RELOC_MICROMIPS_JALR:
3705       return TRUE;
3706
3707     default:
3708       return FALSE;
3709     }
3710 }
3711
3712 static inline bfd_boolean
3713 jmp_reloc_p (bfd_reloc_code_real_type reloc)
3714 {
3715   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
3716 }
3717
3718 static inline bfd_boolean
3719 got16_reloc_p (bfd_reloc_code_real_type reloc)
3720 {
3721   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
3722           || reloc == BFD_RELOC_MICROMIPS_GOT16);
3723 }
3724
3725 static inline bfd_boolean
3726 hi16_reloc_p (bfd_reloc_code_real_type reloc)
3727 {
3728   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
3729           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
3730 }
3731
3732 static inline bfd_boolean
3733 lo16_reloc_p (bfd_reloc_code_real_type reloc)
3734 {
3735   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
3736           || reloc == BFD_RELOC_MICROMIPS_LO16);
3737 }
3738
3739 static inline bfd_boolean
3740 jalr_reloc_p (bfd_reloc_code_real_type reloc)
3741 {
3742   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
3743 }
3744
3745 static inline bfd_boolean
3746 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
3747 {
3748   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
3749           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
3750 }
3751
3752 /* Return true if RELOC is a PC-relative relocation that does not have
3753    full address range.  */
3754
3755 static inline bfd_boolean
3756 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
3757 {
3758   switch (reloc)
3759     {
3760     case BFD_RELOC_16_PCREL_S2:
3761     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
3762     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
3763     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
3764       return TRUE;
3765
3766     case BFD_RELOC_32_PCREL:
3767       return HAVE_64BIT_ADDRESSES;
3768
3769     default:
3770       return FALSE;
3771     }
3772 }
3773
3774 /* Return true if the given relocation might need a matching %lo().
3775    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
3776    need a matching %lo() when applied to local symbols.  */
3777
3778 static inline bfd_boolean
3779 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
3780 {
3781   return (HAVE_IN_PLACE_ADDENDS
3782           && (hi16_reloc_p (reloc)
3783               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
3784                  all GOT16 relocations evaluate to "G".  */
3785               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
3786 }
3787
3788 /* Return the type of %lo() reloc needed by RELOC, given that
3789    reloc_needs_lo_p.  */
3790
3791 static inline bfd_reloc_code_real_type
3792 matching_lo_reloc (bfd_reloc_code_real_type reloc)
3793 {
3794   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
3795           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
3796              : BFD_RELOC_LO16));
3797 }
3798
3799 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
3800    relocation.  */
3801
3802 static inline bfd_boolean
3803 fixup_has_matching_lo_p (fixS *fixp)
3804 {
3805   return (fixp->fx_next != NULL
3806           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
3807           && fixp->fx_addsy == fixp->fx_next->fx_addsy
3808           && fixp->fx_offset == fixp->fx_next->fx_offset);
3809 }
3810
3811 /* Move all labels in LABELS to the current insertion point.  TEXT_P
3812    says whether the labels refer to text or data.  */
3813
3814 static void
3815 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
3816 {
3817   struct insn_label_list *l;
3818   valueT val;
3819
3820   for (l = labels; l != NULL; l = l->next)
3821     {
3822       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
3823       symbol_set_frag (l->label, frag_now);
3824       val = (valueT) frag_now_fix ();
3825       /* MIPS16/microMIPS text labels are stored as odd.  */
3826       if (text_p && HAVE_CODE_COMPRESSION)
3827         ++val;
3828       S_SET_VALUE (l->label, val);
3829     }
3830 }
3831
3832 /* Move all labels in insn_labels to the current insertion point
3833    and treat them as text labels.  */
3834
3835 static void
3836 mips_move_text_labels (void)
3837 {
3838   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
3839 }
3840
3841 static bfd_boolean
3842 s_is_linkonce (symbolS *sym, segT from_seg)
3843 {
3844   bfd_boolean linkonce = FALSE;
3845   segT symseg = S_GET_SEGMENT (sym);
3846
3847   if (symseg != from_seg && !S_IS_LOCAL (sym))
3848     {
3849       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
3850         linkonce = TRUE;
3851       /* The GNU toolchain uses an extension for ELF: a section
3852          beginning with the magic string .gnu.linkonce is a
3853          linkonce section.  */
3854       if (strncmp (segment_name (symseg), ".gnu.linkonce",
3855                    sizeof ".gnu.linkonce" - 1) == 0)
3856         linkonce = TRUE;
3857     }
3858   return linkonce;
3859 }
3860
3861 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
3862    linker to handle them specially, such as generating jalx instructions
3863    when needed.  We also make them odd for the duration of the assembly,
3864    in order to generate the right sort of code.  We will make them even
3865    in the adjust_symtab routine, while leaving them marked.  This is
3866    convenient for the debugger and the disassembler.  The linker knows
3867    to make them odd again.  */
3868
3869 static void
3870 mips_compressed_mark_label (symbolS *label)
3871 {
3872   gas_assert (HAVE_CODE_COMPRESSION);
3873
3874   if (mips_opts.mips16)
3875     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
3876   else
3877     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
3878   if ((S_GET_VALUE (label) & 1) == 0
3879       /* Don't adjust the address if the label is global or weak, or
3880          in a link-once section, since we'll be emitting symbol reloc
3881          references to it which will be patched up by the linker, and
3882          the final value of the symbol may or may not be MIPS16/microMIPS.  */
3883       && !S_IS_WEAK (label)
3884       && !S_IS_EXTERNAL (label)
3885       && !s_is_linkonce (label, now_seg))
3886     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
3887 }
3888
3889 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
3890
3891 static void
3892 mips_compressed_mark_labels (void)
3893 {
3894   struct insn_label_list *l;
3895
3896   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
3897     mips_compressed_mark_label (l->label);
3898 }
3899
3900 /* End the current frag.  Make it a variant frag and record the
3901    relaxation info.  */
3902
3903 static void
3904 relax_close_frag (void)
3905 {
3906   mips_macro_warning.first_frag = frag_now;
3907   frag_var (rs_machine_dependent, 0, 0,
3908             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
3909             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
3910
3911   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
3912   mips_relax.first_fixup = 0;
3913 }
3914
3915 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
3916    See the comment above RELAX_ENCODE for more details.  */
3917
3918 static void
3919 relax_start (symbolS *symbol)
3920 {
3921   gas_assert (mips_relax.sequence == 0);
3922   mips_relax.sequence = 1;
3923   mips_relax.symbol = symbol;
3924 }
3925
3926 /* Start generating the second version of a relaxable sequence.
3927    See the comment above RELAX_ENCODE for more details.  */
3928
3929 static void
3930 relax_switch (void)
3931 {
3932   gas_assert (mips_relax.sequence == 1);
3933   mips_relax.sequence = 2;
3934 }
3935
3936 /* End the current relaxable sequence.  */
3937
3938 static void
3939 relax_end (void)
3940 {
3941   gas_assert (mips_relax.sequence == 2);
3942   relax_close_frag ();
3943   mips_relax.sequence = 0;
3944 }
3945
3946 /* Return true if IP is a delayed branch or jump.  */
3947
3948 static inline bfd_boolean
3949 delayed_branch_p (const struct mips_cl_insn *ip)
3950 {
3951   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
3952                                 | INSN_COND_BRANCH_DELAY
3953                                 | INSN_COND_BRANCH_LIKELY)) != 0;
3954 }
3955
3956 /* Return true if IP is a compact branch or jump.  */
3957
3958 static inline bfd_boolean
3959 compact_branch_p (const struct mips_cl_insn *ip)
3960 {
3961   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
3962                                  | INSN2_COND_BRANCH)) != 0;
3963 }
3964
3965 /* Return true if IP is an unconditional branch or jump.  */
3966
3967 static inline bfd_boolean
3968 uncond_branch_p (const struct mips_cl_insn *ip)
3969 {
3970   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
3971           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
3972 }
3973
3974 /* Return true if IP is a branch-likely instruction.  */
3975
3976 static inline bfd_boolean
3977 branch_likely_p (const struct mips_cl_insn *ip)
3978 {
3979   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
3980 }
3981
3982 /* Return the type of nop that should be used to fill the delay slot
3983    of delayed branch IP.  */
3984
3985 static struct mips_cl_insn *
3986 get_delay_slot_nop (const struct mips_cl_insn *ip)
3987 {
3988   if (mips_opts.micromips
3989       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
3990     return &micromips_nop32_insn;
3991   return NOP_INSN;
3992 }
3993
3994 /* Return a mask that has bit N set if OPCODE reads the register(s)
3995    in operand N.  */
3996
3997 static unsigned int
3998 insn_read_mask (const struct mips_opcode *opcode)
3999 {
4000   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4001 }
4002
4003 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4004    in operand N.  */
4005
4006 static unsigned int
4007 insn_write_mask (const struct mips_opcode *opcode)
4008 {
4009   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4010 }
4011
4012 /* Return a mask of the registers specified by operand OPERAND of INSN.
4013    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4014    is set.  */
4015
4016 static unsigned int
4017 operand_reg_mask (const struct mips_cl_insn *insn,
4018                   const struct mips_operand *operand,
4019                   unsigned int type_mask)
4020 {
4021   unsigned int uval, vsel;
4022
4023   switch (operand->type)
4024     {
4025     case OP_INT:
4026     case OP_MAPPED_INT:
4027     case OP_MSB:
4028     case OP_PCREL:
4029     case OP_PERF_REG:
4030     case OP_ADDIUSP_INT:
4031     case OP_ENTRY_EXIT_LIST:
4032     case OP_REPEAT_DEST_REG:
4033     case OP_REPEAT_PREV_REG:
4034     case OP_PC:
4035     case OP_VU0_SUFFIX:
4036     case OP_VU0_MATCH_SUFFIX:
4037     case OP_IMM_INDEX:
4038       abort ();
4039
4040     case OP_REG:
4041     case OP_OPTIONAL_REG:
4042       {
4043         const struct mips_reg_operand *reg_op;
4044
4045         reg_op = (const struct mips_reg_operand *) operand;
4046         if (!(type_mask & (1 << reg_op->reg_type)))
4047           return 0;
4048         uval = insn_extract_operand (insn, operand);
4049         return 1 << mips_decode_reg_operand (reg_op, uval);
4050       }
4051
4052     case OP_REG_PAIR:
4053       {
4054         const struct mips_reg_pair_operand *pair_op;
4055
4056         pair_op = (const struct mips_reg_pair_operand *) operand;
4057         if (!(type_mask & (1 << pair_op->reg_type)))
4058           return 0;
4059         uval = insn_extract_operand (insn, operand);
4060         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4061       }
4062
4063     case OP_CLO_CLZ_DEST:
4064       if (!(type_mask & (1 << OP_REG_GP)))
4065         return 0;
4066       uval = insn_extract_operand (insn, operand);
4067       return (1 << (uval & 31)) | (1 << (uval >> 5));
4068
4069     case OP_LWM_SWM_LIST:
4070       abort ();
4071
4072     case OP_SAVE_RESTORE_LIST:
4073       abort ();
4074
4075     case OP_MDMX_IMM_REG:
4076       if (!(type_mask & (1 << OP_REG_VEC)))
4077         return 0;
4078       uval = insn_extract_operand (insn, operand);
4079       vsel = uval >> 5;
4080       if ((vsel & 0x18) == 0x18)
4081         return 0;
4082       return 1 << (uval & 31);
4083
4084     case OP_REG_INDEX:
4085       if (!(type_mask & (1 << OP_REG_GP)))
4086         return 0;
4087       return 1 << insn_extract_operand (insn, operand);
4088     }
4089   abort ();
4090 }
4091
4092 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4093    where bit N of OPNO_MASK is set if operand N should be included.
4094    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4095    is set.  */
4096
4097 static unsigned int
4098 insn_reg_mask (const struct mips_cl_insn *insn,
4099                unsigned int type_mask, unsigned int opno_mask)
4100 {
4101   unsigned int opno, reg_mask;
4102
4103   opno = 0;
4104   reg_mask = 0;
4105   while (opno_mask != 0)
4106     {
4107       if (opno_mask & 1)
4108         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4109       opno_mask >>= 1;
4110       opno += 1;
4111     }
4112   return reg_mask;
4113 }
4114
4115 /* Return the mask of core registers that IP reads.  */
4116
4117 static unsigned int
4118 gpr_read_mask (const struct mips_cl_insn *ip)
4119 {
4120   unsigned long pinfo, pinfo2;
4121   unsigned int mask;
4122
4123   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4124   pinfo = ip->insn_mo->pinfo;
4125   pinfo2 = ip->insn_mo->pinfo2;
4126   if (pinfo & INSN_UDI)
4127     {
4128       /* UDI instructions have traditionally been assumed to read RS
4129          and RT.  */
4130       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4131       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4132     }
4133   if (pinfo & INSN_READ_GPR_24)
4134     mask |= 1 << 24;
4135   if (pinfo2 & INSN2_READ_GPR_16)
4136     mask |= 1 << 16;
4137   if (pinfo2 & INSN2_READ_SP)
4138     mask |= 1 << SP;
4139   if (pinfo2 & INSN2_READ_GPR_31)
4140     mask |= 1 << 31;
4141   /* Don't include register 0.  */
4142   return mask & ~1;
4143 }
4144
4145 /* Return the mask of core registers that IP writes.  */
4146
4147 static unsigned int
4148 gpr_write_mask (const struct mips_cl_insn *ip)
4149 {
4150   unsigned long pinfo, pinfo2;
4151   unsigned int mask;
4152
4153   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4154   pinfo = ip->insn_mo->pinfo;
4155   pinfo2 = ip->insn_mo->pinfo2;
4156   if (pinfo & INSN_WRITE_GPR_24)
4157     mask |= 1 << 24;
4158   if (pinfo & INSN_WRITE_GPR_31)
4159     mask |= 1 << 31;
4160   if (pinfo & INSN_UDI)
4161     /* UDI instructions have traditionally been assumed to write to RD.  */
4162     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4163   if (pinfo2 & INSN2_WRITE_SP)
4164     mask |= 1 << SP;
4165   /* Don't include register 0.  */
4166   return mask & ~1;
4167 }
4168
4169 /* Return the mask of floating-point registers that IP reads.  */
4170
4171 static unsigned int
4172 fpr_read_mask (const struct mips_cl_insn *ip)
4173 {
4174   unsigned long pinfo;
4175   unsigned int mask;
4176
4177   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4178                              | (1 << OP_REG_MSA)),
4179                         insn_read_mask (ip->insn_mo));
4180   pinfo = ip->insn_mo->pinfo;
4181   /* Conservatively treat all operands to an FP_D instruction are doubles.
4182      (This is overly pessimistic for things like cvt.d.s.)  */
4183   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4184     mask |= mask << 1;
4185   return mask;
4186 }
4187
4188 /* Return the mask of floating-point registers that IP writes.  */
4189
4190 static unsigned int
4191 fpr_write_mask (const struct mips_cl_insn *ip)
4192 {
4193   unsigned long pinfo;
4194   unsigned int mask;
4195
4196   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4197                              | (1 << OP_REG_MSA)),
4198                         insn_write_mask (ip->insn_mo));
4199   pinfo = ip->insn_mo->pinfo;
4200   /* Conservatively treat all operands to an FP_D instruction are doubles.
4201      (This is overly pessimistic for things like cvt.s.d.)  */
4202   if (HAVE_32BIT_FPRS && (pinfo & FP_D))
4203     mask |= mask << 1;
4204   return mask;
4205 }
4206
4207 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4208    Check whether that is allowed.  */
4209
4210 static bfd_boolean
4211 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4212 {
4213   const char *s = insn->name;
4214
4215   if (insn->pinfo == INSN_MACRO)
4216     /* Let a macro pass, we'll catch it later when it is expanded.  */
4217     return TRUE;
4218
4219   if (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa) || mips_opts.arch == CPU_R5900)
4220     {
4221       /* Allow odd registers for single-precision ops.  */
4222       switch (insn->pinfo & (FP_S | FP_D))
4223         {
4224         case FP_S:
4225         case 0:
4226           return TRUE;
4227         case FP_D:
4228           return FALSE;
4229         default:
4230           break;
4231         }
4232
4233       /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4234       s = strchr (insn->name, '.');
4235       if (s != NULL && opnum == 2)
4236         s = strchr (s + 1, '.');
4237       return (s != NULL && (s[1] == 'w' || s[1] == 's'));
4238     }
4239
4240   /* Single-precision coprocessor loads and moves are OK too.  */
4241   if ((insn->pinfo & FP_S)
4242       && (insn->pinfo & (INSN_COPROC_MEMORY_DELAY | INSN_STORE_MEMORY
4243                          | INSN_LOAD_COPROC_DELAY | INSN_COPROC_MOVE_DELAY)))
4244     return TRUE;
4245
4246   return FALSE;
4247 }
4248
4249 /* Information about an instruction argument that we're trying to match.  */
4250 struct mips_arg_info
4251 {
4252   /* The instruction so far.  */
4253   struct mips_cl_insn *insn;
4254
4255   /* The first unconsumed operand token.  */
4256   struct mips_operand_token *token;
4257
4258   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4259   int opnum;
4260
4261   /* The 1-based argument number, for error reporting.  This does not
4262      count elided optional registers, etc..  */
4263   int argnum;
4264
4265   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4266   unsigned int last_regno;
4267
4268   /* If the first operand was an OP_REG, this is the register that it
4269      specified, otherwise it is ILLEGAL_REG.  */
4270   unsigned int dest_regno;
4271
4272   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4273      where it gives the lsb position.  */
4274   unsigned int last_op_int;
4275
4276   /* If true, match routines should assume that no later instruction
4277      alternative matches and should therefore be as accomodating as
4278      possible.  Match routines should not report errors if something
4279      is only invalid for !LAX_MATCH.  */
4280   bfd_boolean lax_match;
4281
4282   /* True if a reference to the current AT register was seen.  */
4283   bfd_boolean seen_at;
4284 };
4285
4286 /* Record that the argument is out of range.  */
4287
4288 static void
4289 match_out_of_range (struct mips_arg_info *arg)
4290 {
4291   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4292 }
4293
4294 /* Record that the argument isn't constant but needs to be.  */
4295
4296 static void
4297 match_not_constant (struct mips_arg_info *arg)
4298 {
4299   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4300                     arg->argnum);
4301 }
4302
4303 /* Try to match an OT_CHAR token for character CH.  Consume the token
4304    and return true on success, otherwise return false.  */
4305
4306 static bfd_boolean
4307 match_char (struct mips_arg_info *arg, char ch)
4308 {
4309   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4310     {
4311       ++arg->token;
4312       if (ch == ',')
4313         arg->argnum += 1;
4314       return TRUE;
4315     }
4316   return FALSE;
4317 }
4318
4319 /* Try to get an expression from the next tokens in ARG.  Consume the
4320    tokens and return true on success, storing the expression value in
4321    VALUE and relocation types in R.  */
4322
4323 static bfd_boolean
4324 match_expression (struct mips_arg_info *arg, expressionS *value,
4325                   bfd_reloc_code_real_type *r)
4326 {
4327   /* If the next token is a '(' that was parsed as being part of a base
4328      expression, assume we have an elided offset.  The later match will fail
4329      if this turns out to be wrong.  */
4330   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4331     {
4332       value->X_op = O_constant;
4333       value->X_add_number = 0;
4334       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4335       return TRUE;
4336     }
4337
4338   /* Reject register-based expressions such as "0+$2" and "(($2))".
4339      For plain registers the default error seems more appropriate.  */
4340   if (arg->token->type == OT_INTEGER
4341       && arg->token->u.integer.value.X_op == O_register)
4342     {
4343       set_insn_error (arg->argnum, _("register value used as expression"));
4344       return FALSE;
4345     }
4346
4347   if (arg->token->type == OT_INTEGER)
4348     {
4349       *value = arg->token->u.integer.value;
4350       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4351       ++arg->token;
4352       return TRUE;
4353     }
4354
4355   set_insn_error_i
4356     (arg->argnum, _("operand %d must be an immediate expression"),
4357      arg->argnum);
4358   return FALSE;
4359 }
4360
4361 /* Try to get a constant expression from the next tokens in ARG.  Consume
4362    the tokens and return return true on success, storing the constant value
4363    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4364    error.  */
4365
4366 static bfd_boolean
4367 match_const_int (struct mips_arg_info *arg, offsetT *value)
4368 {
4369   expressionS ex;
4370   bfd_reloc_code_real_type r[3];
4371
4372   if (!match_expression (arg, &ex, r))
4373     return FALSE;
4374
4375   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4376     *value = ex.X_add_number;
4377   else
4378     {
4379       match_not_constant (arg);
4380       return FALSE;
4381     }
4382   return TRUE;
4383 }
4384
4385 /* Return the RTYPE_* flags for a register operand of type TYPE that
4386    appears in instruction OPCODE.  */
4387
4388 static unsigned int
4389 convert_reg_type (const struct mips_opcode *opcode,
4390                   enum mips_reg_operand_type type)
4391 {
4392   switch (type)
4393     {
4394     case OP_REG_GP:
4395       return RTYPE_NUM | RTYPE_GP;
4396
4397     case OP_REG_FP:
4398       /* Allow vector register names for MDMX if the instruction is a 64-bit
4399          FPR load, store or move (including moves to and from GPRs).  */
4400       if ((mips_opts.ase & ASE_MDMX)
4401           && (opcode->pinfo & FP_D)
4402           && (opcode->pinfo & (INSN_COPROC_MOVE_DELAY
4403                                | INSN_COPROC_MEMORY_DELAY
4404                                | INSN_LOAD_COPROC_DELAY
4405                                | INSN_LOAD_MEMORY
4406                                | INSN_STORE_MEMORY)))
4407         return RTYPE_FPU | RTYPE_VEC;
4408       return RTYPE_FPU;
4409
4410     case OP_REG_CCC:
4411       if (opcode->pinfo & (FP_D | FP_S))
4412         return RTYPE_CCC | RTYPE_FCC;
4413       return RTYPE_CCC;
4414
4415     case OP_REG_VEC:
4416       if (opcode->membership & INSN_5400)
4417         return RTYPE_FPU;
4418       return RTYPE_FPU | RTYPE_VEC;
4419
4420     case OP_REG_ACC:
4421       return RTYPE_ACC;
4422
4423     case OP_REG_COPRO:
4424       if (opcode->name[strlen (opcode->name) - 1] == '0')
4425         return RTYPE_NUM | RTYPE_CP0;
4426       return RTYPE_NUM;
4427
4428     case OP_REG_HW:
4429       return RTYPE_NUM;
4430
4431     case OP_REG_VI:
4432       return RTYPE_NUM | RTYPE_VI;
4433
4434     case OP_REG_VF:
4435       return RTYPE_NUM | RTYPE_VF;
4436
4437     case OP_REG_R5900_I:
4438       return RTYPE_R5900_I;
4439
4440     case OP_REG_R5900_Q:
4441       return RTYPE_R5900_Q;
4442
4443     case OP_REG_R5900_R:
4444       return RTYPE_R5900_R;
4445
4446     case OP_REG_R5900_ACC:
4447       return RTYPE_R5900_ACC;
4448
4449     case OP_REG_MSA:
4450       return RTYPE_MSA;
4451
4452     case OP_REG_MSA_CTRL:
4453       return RTYPE_NUM;
4454     }
4455   abort ();
4456 }
4457
4458 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4459
4460 static void
4461 check_regno (struct mips_arg_info *arg,
4462              enum mips_reg_operand_type type, unsigned int regno)
4463 {
4464   if (AT && type == OP_REG_GP && regno == AT)
4465     arg->seen_at = TRUE;
4466
4467   if (type == OP_REG_FP
4468       && (regno & 1) != 0
4469       && HAVE_32BIT_FPRS
4470       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4471     as_warn (_("float register should be even, was %d"), regno);
4472
4473   if (type == OP_REG_CCC)
4474     {
4475       const char *name;
4476       size_t length;
4477
4478       name = arg->insn->insn_mo->name;
4479       length = strlen (name);
4480       if ((regno & 1) != 0
4481           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4482               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4483         as_warn (_("condition code register should be even for %s, was %d"),
4484                  name, regno);
4485
4486       if ((regno & 3) != 0
4487           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4488         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4489                  name, regno);
4490     }
4491 }
4492
4493 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4494    a register of type TYPE.  Return true on success, storing the register
4495    number in *REGNO and warning about any dubious uses.  */
4496
4497 static bfd_boolean
4498 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4499              unsigned int symval, unsigned int *regno)
4500 {
4501   if (type == OP_REG_VEC)
4502     symval = mips_prefer_vec_regno (symval);
4503   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4504     return FALSE;
4505
4506   *regno = symval & RNUM_MASK;
4507   check_regno (arg, type, *regno);
4508   return TRUE;
4509 }
4510
4511 /* Try to interpret the next token in ARG as a register of type TYPE.
4512    Consume the token and return true on success, storing the register
4513    number in *REGNO.  Return false on failure.  */
4514
4515 static bfd_boolean
4516 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4517            unsigned int *regno)
4518 {
4519   if (arg->token->type == OT_REG
4520       && match_regno (arg, type, arg->token->u.regno, regno))
4521     {
4522       ++arg->token;
4523       return TRUE;
4524     }
4525   return FALSE;
4526 }
4527
4528 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4529    Consume the token and return true on success, storing the register numbers
4530    in *REGNO1 and *REGNO2.  Return false on failure.  */
4531
4532 static bfd_boolean
4533 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4534                  unsigned int *regno1, unsigned int *regno2)
4535 {
4536   if (match_reg (arg, type, regno1))
4537     {
4538       *regno2 = *regno1;
4539       return TRUE;
4540     }
4541   if (arg->token->type == OT_REG_RANGE
4542       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4543       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4544       && *regno1 <= *regno2)
4545     {
4546       ++arg->token;
4547       return TRUE;
4548     }
4549   return FALSE;
4550 }
4551
4552 /* OP_INT matcher.  */
4553
4554 static bfd_boolean
4555 match_int_operand (struct mips_arg_info *arg,
4556                    const struct mips_operand *operand_base)
4557 {
4558   const struct mips_int_operand *operand;
4559   unsigned int uval;
4560   int min_val, max_val, factor;
4561   offsetT sval;
4562
4563   operand = (const struct mips_int_operand *) operand_base;
4564   factor = 1 << operand->shift;
4565   min_val = mips_int_operand_min (operand);
4566   max_val = mips_int_operand_max (operand);
4567
4568   if (operand_base->lsb == 0
4569       && operand_base->size == 16
4570       && operand->shift == 0
4571       && operand->bias == 0
4572       && (operand->max_val == 32767 || operand->max_val == 65535))
4573     {
4574       /* The operand can be relocated.  */
4575       if (!match_expression (arg, &offset_expr, offset_reloc))
4576         return FALSE;
4577
4578       if (offset_reloc[0] != BFD_RELOC_UNUSED)
4579         /* Relocation operators were used.  Accept the arguent and
4580            leave the relocation value in offset_expr and offset_relocs
4581            for the caller to process.  */
4582         return TRUE;
4583
4584       if (offset_expr.X_op != O_constant)
4585         {
4586           /* Accept non-constant operands if no later alternative matches,
4587              leaving it for the caller to process.  */
4588           if (!arg->lax_match)
4589             return FALSE;
4590           offset_reloc[0] = BFD_RELOC_LO16;
4591           return TRUE;
4592         }
4593
4594       /* Clear the global state; we're going to install the operand
4595          ourselves.  */
4596       sval = offset_expr.X_add_number;
4597       offset_expr.X_op = O_absent;
4598
4599       /* For compatibility with older assemblers, we accept
4600          0x8000-0xffff as signed 16-bit numbers when only
4601          signed numbers are allowed.  */
4602       if (sval > max_val)
4603         {
4604           max_val = ((1 << operand_base->size) - 1) << operand->shift;
4605           if (!arg->lax_match && sval <= max_val)
4606             return FALSE;
4607         }
4608     }
4609   else
4610     {
4611       if (!match_const_int (arg, &sval))
4612         return FALSE;
4613     }
4614
4615   arg->last_op_int = sval;
4616
4617   if (sval < min_val || sval > max_val || sval % factor)
4618     {
4619       match_out_of_range (arg);
4620       return FALSE;
4621     }
4622
4623   uval = (unsigned int) sval >> operand->shift;
4624   uval -= operand->bias;
4625
4626   /* Handle -mfix-cn63xxp1.  */
4627   if (arg->opnum == 1
4628       && mips_fix_cn63xxp1
4629       && !mips_opts.micromips
4630       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
4631     switch (uval)
4632       {
4633       case 5:
4634       case 25:
4635       case 26:
4636       case 27:
4637       case 28:
4638       case 29:
4639       case 30:
4640       case 31:
4641         /* These are ok.  */
4642         break;
4643
4644       default:
4645         /* The rest must be changed to 28.  */
4646         uval = 28;
4647         break;
4648       }
4649
4650   insn_insert_operand (arg->insn, operand_base, uval);
4651   return TRUE;
4652 }
4653
4654 /* OP_MAPPED_INT matcher.  */
4655
4656 static bfd_boolean
4657 match_mapped_int_operand (struct mips_arg_info *arg,
4658                           const struct mips_operand *operand_base)
4659 {
4660   const struct mips_mapped_int_operand *operand;
4661   unsigned int uval, num_vals;
4662   offsetT sval;
4663
4664   operand = (const struct mips_mapped_int_operand *) operand_base;
4665   if (!match_const_int (arg, &sval))
4666     return FALSE;
4667
4668   num_vals = 1 << operand_base->size;
4669   for (uval = 0; uval < num_vals; uval++)
4670     if (operand->int_map[uval] == sval)
4671       break;
4672   if (uval == num_vals)
4673     {
4674       match_out_of_range (arg);
4675       return FALSE;
4676     }
4677
4678   insn_insert_operand (arg->insn, operand_base, uval);
4679   return TRUE;
4680 }
4681
4682 /* OP_MSB matcher.  */
4683
4684 static bfd_boolean
4685 match_msb_operand (struct mips_arg_info *arg,
4686                    const struct mips_operand *operand_base)
4687 {
4688   const struct mips_msb_operand *operand;
4689   int min_val, max_val, max_high;
4690   offsetT size, sval, high;
4691
4692   operand = (const struct mips_msb_operand *) operand_base;
4693   min_val = operand->bias;
4694   max_val = min_val + (1 << operand_base->size) - 1;
4695   max_high = operand->opsize;
4696
4697   if (!match_const_int (arg, &size))
4698     return FALSE;
4699
4700   high = size + arg->last_op_int;
4701   sval = operand->add_lsb ? high : size;
4702
4703   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
4704     {
4705       match_out_of_range (arg);
4706       return FALSE;
4707     }
4708   insn_insert_operand (arg->insn, operand_base, sval - min_val);
4709   return TRUE;
4710 }
4711
4712 /* OP_REG matcher.  */
4713
4714 static bfd_boolean
4715 match_reg_operand (struct mips_arg_info *arg,
4716                    const struct mips_operand *operand_base)
4717 {
4718   const struct mips_reg_operand *operand;
4719   unsigned int regno, uval, num_vals;
4720
4721   operand = (const struct mips_reg_operand *) operand_base;
4722   if (!match_reg (arg, operand->reg_type, &regno))
4723     return FALSE;
4724
4725   if (operand->reg_map)
4726     {
4727       num_vals = 1 << operand->root.size;
4728       for (uval = 0; uval < num_vals; uval++)
4729         if (operand->reg_map[uval] == regno)
4730           break;
4731       if (num_vals == uval)
4732         return FALSE;
4733     }
4734   else
4735     uval = regno;
4736
4737   arg->last_regno = regno;
4738   if (arg->opnum == 1)
4739     arg->dest_regno = regno;
4740   insn_insert_operand (arg->insn, operand_base, uval);
4741   return TRUE;
4742 }
4743
4744 /* OP_REG_PAIR matcher.  */
4745
4746 static bfd_boolean
4747 match_reg_pair_operand (struct mips_arg_info *arg,
4748                         const struct mips_operand *operand_base)
4749 {
4750   const struct mips_reg_pair_operand *operand;
4751   unsigned int regno1, regno2, uval, num_vals;
4752
4753   operand = (const struct mips_reg_pair_operand *) operand_base;
4754   if (!match_reg (arg, operand->reg_type, &regno1)
4755       || !match_char (arg, ',')
4756       || !match_reg (arg, operand->reg_type, &regno2))
4757     return FALSE;
4758
4759   num_vals = 1 << operand_base->size;
4760   for (uval = 0; uval < num_vals; uval++)
4761     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
4762       break;
4763   if (uval == num_vals)
4764     return FALSE;
4765
4766   insn_insert_operand (arg->insn, operand_base, uval);
4767   return TRUE;
4768 }
4769
4770 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
4771
4772 static bfd_boolean
4773 match_pcrel_operand (struct mips_arg_info *arg)
4774 {
4775   bfd_reloc_code_real_type r[3];
4776
4777   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
4778 }
4779
4780 /* OP_PERF_REG matcher.  */
4781
4782 static bfd_boolean
4783 match_perf_reg_operand (struct mips_arg_info *arg,
4784                         const struct mips_operand *operand)
4785 {
4786   offsetT sval;
4787
4788   if (!match_const_int (arg, &sval))
4789     return FALSE;
4790
4791   if (sval != 0
4792       && (sval != 1
4793           || (mips_opts.arch == CPU_R5900
4794               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
4795                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
4796     {
4797       set_insn_error (arg->argnum, _("invalid performance register"));
4798       return FALSE;
4799     }
4800
4801   insn_insert_operand (arg->insn, operand, sval);
4802   return TRUE;
4803 }
4804
4805 /* OP_ADDIUSP matcher.  */
4806
4807 static bfd_boolean
4808 match_addiusp_operand (struct mips_arg_info *arg,
4809                        const struct mips_operand *operand)
4810 {
4811   offsetT sval;
4812   unsigned int uval;
4813
4814   if (!match_const_int (arg, &sval))
4815     return FALSE;
4816
4817   if (sval % 4)
4818     {
4819       match_out_of_range (arg);
4820       return FALSE;
4821     }
4822
4823   sval /= 4;
4824   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
4825     {
4826       match_out_of_range (arg);
4827       return FALSE;
4828     }
4829
4830   uval = (unsigned int) sval;
4831   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
4832   insn_insert_operand (arg->insn, operand, uval);
4833   return TRUE;
4834 }
4835
4836 /* OP_CLO_CLZ_DEST matcher.  */
4837
4838 static bfd_boolean
4839 match_clo_clz_dest_operand (struct mips_arg_info *arg,
4840                             const struct mips_operand *operand)
4841 {
4842   unsigned int regno;
4843
4844   if (!match_reg (arg, OP_REG_GP, &regno))
4845     return FALSE;
4846
4847   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
4848   return TRUE;
4849 }
4850
4851 /* OP_LWM_SWM_LIST matcher.  */
4852
4853 static bfd_boolean
4854 match_lwm_swm_list_operand (struct mips_arg_info *arg,
4855                             const struct mips_operand *operand)
4856 {
4857   unsigned int reglist, sregs, ra, regno1, regno2;
4858   struct mips_arg_info reset;
4859
4860   reglist = 0;
4861   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4862     return FALSE;
4863   do
4864     {
4865       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
4866         {
4867           reglist |= 1 << FP;
4868           regno2 = S7;
4869         }
4870       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
4871       reset = *arg;
4872     }
4873   while (match_char (arg, ',')
4874          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
4875   *arg = reset;
4876
4877   if (operand->size == 2)
4878     {
4879       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
4880
4881          s0, ra
4882          s0, s1, ra, s2, s3
4883          s0-s2, ra
4884
4885          and any permutations of these.  */
4886       if ((reglist & 0xfff1ffff) != 0x80010000)
4887         return FALSE;
4888
4889       sregs = (reglist >> 17) & 7;
4890       ra = 0;
4891     }
4892   else
4893     {
4894       /* The list must include at least one of ra and s0-sN,
4895          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
4896          which are $23 and $30 respectively.)  E.g.:
4897
4898          ra
4899          s0
4900          ra, s0, s1, s2
4901          s0-s8
4902          s0-s5, ra
4903
4904          and any permutations of these.  */
4905       if ((reglist & 0x3f00ffff) != 0)
4906         return FALSE;
4907
4908       ra = (reglist >> 27) & 0x10;
4909       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
4910     }
4911   sregs += 1;
4912   if ((sregs & -sregs) != sregs)
4913     return FALSE;
4914
4915   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
4916   return TRUE;
4917 }
4918
4919 /* OP_ENTRY_EXIT_LIST matcher.  */
4920
4921 static unsigned int
4922 match_entry_exit_operand (struct mips_arg_info *arg,
4923                           const struct mips_operand *operand)
4924 {
4925   unsigned int mask;
4926   bfd_boolean is_exit;
4927
4928   /* The format is the same for both ENTRY and EXIT, but the constraints
4929      are different.  */
4930   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
4931   mask = (is_exit ? 7 << 3 : 0);
4932   do
4933     {
4934       unsigned int regno1, regno2;
4935       bfd_boolean is_freg;
4936
4937       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4938         is_freg = FALSE;
4939       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
4940         is_freg = TRUE;
4941       else
4942         return FALSE;
4943
4944       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
4945         {
4946           mask &= ~(7 << 3);
4947           mask |= (5 + regno2) << 3;
4948         }
4949       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
4950         mask |= (regno2 - 3) << 3;
4951       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
4952         mask |= (regno2 - 15) << 1;
4953       else if (regno1 == RA && regno2 == RA)
4954         mask |= 1;
4955       else
4956         return FALSE;
4957     }
4958   while (match_char (arg, ','));
4959
4960   insn_insert_operand (arg->insn, operand, mask);
4961   return TRUE;
4962 }
4963
4964 /* OP_SAVE_RESTORE_LIST matcher.  */
4965
4966 static bfd_boolean
4967 match_save_restore_list_operand (struct mips_arg_info *arg)
4968 {
4969   unsigned int opcode, args, statics, sregs;
4970   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
4971   offsetT frame_size;
4972
4973   opcode = arg->insn->insn_opcode;
4974   frame_size = 0;
4975   num_frame_sizes = 0;
4976   args = 0;
4977   statics = 0;
4978   sregs = 0;
4979   do
4980     {
4981       unsigned int regno1, regno2;
4982
4983       if (arg->token->type == OT_INTEGER)
4984         {
4985           /* Handle the frame size.  */
4986           if (!match_const_int (arg, &frame_size))
4987             return FALSE;
4988           num_frame_sizes += 1;
4989         }
4990       else
4991         {
4992           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
4993             return FALSE;
4994
4995           while (regno1 <= regno2)
4996             {
4997               if (regno1 >= 4 && regno1 <= 7)
4998                 {
4999                   if (num_frame_sizes == 0)
5000                     /* args $a0-$a3 */
5001                     args |= 1 << (regno1 - 4);
5002                   else
5003                     /* statics $a0-$a3 */
5004                     statics |= 1 << (regno1 - 4);
5005                 }
5006               else if (regno1 >= 16 && regno1 <= 23)
5007                 /* $s0-$s7 */
5008                 sregs |= 1 << (regno1 - 16);
5009               else if (regno1 == 30)
5010                 /* $s8 */
5011                 sregs |= 1 << 8;
5012               else if (regno1 == 31)
5013                 /* Add $ra to insn.  */
5014                 opcode |= 0x40;
5015               else
5016                 return FALSE;
5017               regno1 += 1;
5018               if (regno1 == 24)
5019                 regno1 = 30;
5020             }
5021         }
5022     }
5023   while (match_char (arg, ','));
5024
5025   /* Encode args/statics combination.  */
5026   if (args & statics)
5027     return FALSE;
5028   else if (args == 0xf)
5029     /* All $a0-$a3 are args.  */
5030     opcode |= MIPS16_ALL_ARGS << 16;
5031   else if (statics == 0xf)
5032     /* All $a0-$a3 are statics.  */
5033     opcode |= MIPS16_ALL_STATICS << 16;
5034   else
5035     {
5036       /* Count arg registers.  */
5037       num_args = 0;
5038       while (args & 0x1)
5039         {
5040           args >>= 1;
5041           num_args += 1;
5042         }
5043       if (args != 0)
5044         return FALSE;
5045
5046       /* Count static registers.  */
5047       num_statics = 0;
5048       while (statics & 0x8)
5049         {
5050           statics = (statics << 1) & 0xf;
5051           num_statics += 1;
5052         }
5053       if (statics != 0)
5054         return FALSE;
5055
5056       /* Encode args/statics.  */
5057       opcode |= ((num_args << 2) | num_statics) << 16;
5058     }
5059
5060   /* Encode $s0/$s1.  */
5061   if (sregs & (1 << 0))         /* $s0 */
5062     opcode |= 0x20;
5063   if (sregs & (1 << 1))         /* $s1 */
5064     opcode |= 0x10;
5065   sregs >>= 2;
5066
5067   /* Encode $s2-$s8. */
5068   num_sregs = 0;
5069   while (sregs & 1)
5070     {
5071       sregs >>= 1;
5072       num_sregs += 1;
5073     }
5074   if (sregs != 0)
5075     return FALSE;
5076   opcode |= num_sregs << 24;
5077
5078   /* Encode frame size.  */
5079   if (num_frame_sizes == 0)
5080     {
5081       set_insn_error (arg->argnum, _("missing frame size"));
5082       return FALSE;
5083     }
5084   if (num_frame_sizes > 1)
5085     {
5086       set_insn_error (arg->argnum, _("frame size specified twice"));
5087       return FALSE;
5088     }
5089   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5090     {
5091       set_insn_error (arg->argnum, _("invalid frame size"));
5092       return FALSE;
5093     }
5094   if (frame_size != 128 || (opcode >> 16) != 0)
5095     {
5096       frame_size /= 8;
5097       opcode |= (((frame_size & 0xf0) << 16)
5098                  | (frame_size & 0x0f));
5099     }
5100
5101   /* Finally build the instruction.  */
5102   if ((opcode >> 16) != 0 || frame_size == 0)
5103     opcode |= MIPS16_EXTEND;
5104   arg->insn->insn_opcode = opcode;
5105   return TRUE;
5106 }
5107
5108 /* OP_MDMX_IMM_REG matcher.  */
5109
5110 static bfd_boolean
5111 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5112                             const struct mips_operand *operand)
5113 {
5114   unsigned int regno, uval;
5115   bfd_boolean is_qh;
5116   const struct mips_opcode *opcode;
5117
5118   /* The mips_opcode records whether this is an octobyte or quadhalf
5119      instruction.  Start out with that bit in place.  */
5120   opcode = arg->insn->insn_mo;
5121   uval = mips_extract_operand (operand, opcode->match);
5122   is_qh = (uval != 0);
5123
5124   if (arg->token->type == OT_REG)
5125     {
5126       if ((opcode->membership & INSN_5400)
5127           && strcmp (opcode->name, "rzu.ob") == 0)
5128         {
5129           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5130                             arg->argnum);
5131           return FALSE;
5132         }
5133
5134       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5135         return FALSE;
5136       ++arg->token;
5137
5138       /* Check whether this is a vector register or a broadcast of
5139          a single element.  */
5140       if (arg->token->type == OT_INTEGER_INDEX)
5141         {
5142           if (arg->token->u.index > (is_qh ? 3 : 7))
5143             {
5144               set_insn_error (arg->argnum, _("invalid element selector"));
5145               return FALSE;
5146             }
5147           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5148           ++arg->token;
5149         }
5150       else
5151         {
5152           /* A full vector.  */
5153           if ((opcode->membership & INSN_5400)
5154               && (strcmp (opcode->name, "sll.ob") == 0
5155                   || strcmp (opcode->name, "srl.ob") == 0))
5156             {
5157               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5158                                 arg->argnum);
5159               return FALSE;
5160             }
5161
5162           if (is_qh)
5163             uval |= MDMX_FMTSEL_VEC_QH << 5;
5164           else
5165             uval |= MDMX_FMTSEL_VEC_OB << 5;
5166         }
5167       uval |= regno;
5168     }
5169   else
5170     {
5171       offsetT sval;
5172
5173       if (!match_const_int (arg, &sval))
5174         return FALSE;
5175       if (sval < 0 || sval > 31)
5176         {
5177           match_out_of_range (arg);
5178           return FALSE;
5179         }
5180       uval |= (sval & 31);
5181       if (is_qh)
5182         uval |= MDMX_FMTSEL_IMM_QH << 5;
5183       else
5184         uval |= MDMX_FMTSEL_IMM_OB << 5;
5185     }
5186   insn_insert_operand (arg->insn, operand, uval);
5187   return TRUE;
5188 }
5189
5190 /* OP_IMM_INDEX matcher.  */
5191
5192 static bfd_boolean
5193 match_imm_index_operand (struct mips_arg_info *arg,
5194                          const struct mips_operand *operand)
5195 {
5196   unsigned int max_val;
5197
5198   if (arg->token->type != OT_INTEGER_INDEX)
5199     return FALSE;
5200
5201   max_val = (1 << operand->size) - 1;
5202   if (arg->token->u.index > max_val)
5203     {
5204       match_out_of_range (arg);
5205       return FALSE;
5206     }
5207   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5208   ++arg->token;
5209   return TRUE;
5210 }
5211
5212 /* OP_REG_INDEX matcher.  */
5213
5214 static bfd_boolean
5215 match_reg_index_operand (struct mips_arg_info *arg,
5216                          const struct mips_operand *operand)
5217 {
5218   unsigned int regno;
5219
5220   if (arg->token->type != OT_REG_INDEX)
5221     return FALSE;
5222
5223   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5224     return FALSE;
5225
5226   insn_insert_operand (arg->insn, operand, regno);
5227   ++arg->token;
5228   return TRUE;
5229 }
5230
5231 /* OP_PC matcher.  */
5232
5233 static bfd_boolean
5234 match_pc_operand (struct mips_arg_info *arg)
5235 {
5236   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5237     {
5238       ++arg->token;
5239       return TRUE;
5240     }
5241   return FALSE;
5242 }
5243
5244 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5245    register that we need to match.  */
5246
5247 static bfd_boolean
5248 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5249 {
5250   unsigned int regno;
5251
5252   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5253 }
5254
5255 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5256    the length of the value in bytes (4 for float, 8 for double) and
5257    USING_GPRS says whether the destination is a GPR rather than an FPR.
5258
5259    Return the constant in IMM and OFFSET as follows:
5260
5261    - If the constant should be loaded via memory, set IMM to O_absent and
5262      OFFSET to the memory address.
5263
5264    - Otherwise, if the constant should be loaded into two 32-bit registers,
5265      set IMM to the O_constant to load into the high register and OFFSET
5266      to the corresponding value for the low register.
5267
5268    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5269
5270    These constants only appear as the last operand in an instruction,
5271    and every instruction that accepts them in any variant accepts them
5272    in all variants.  This means we don't have to worry about backing out
5273    any changes if the instruction does not match.  We just match
5274    unconditionally and report an error if the constant is invalid.  */
5275
5276 static bfd_boolean
5277 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5278                       expressionS *offset, int length, bfd_boolean using_gprs)
5279 {
5280   char *p;
5281   segT seg, new_seg;
5282   subsegT subseg;
5283   const char *newname;
5284   unsigned char *data;
5285
5286   /* Where the constant is placed is based on how the MIPS assembler
5287      does things:
5288
5289      length == 4 && using_gprs  -- immediate value only
5290      length == 8 && using_gprs  -- .rdata or immediate value
5291      length == 4 && !using_gprs -- .lit4 or immediate value
5292      length == 8 && !using_gprs -- .lit8 or immediate value
5293
5294      The .lit4 and .lit8 sections are only used if permitted by the
5295      -G argument.  */
5296   if (arg->token->type != OT_FLOAT)
5297     {
5298       set_insn_error (arg->argnum, _("floating-point expression required"));
5299       return FALSE;
5300     }
5301
5302   gas_assert (arg->token->u.flt.length == length);
5303   data = arg->token->u.flt.data;
5304   ++arg->token;
5305
5306   /* Handle 32-bit constants for which an immediate value is best.  */
5307   if (length == 4
5308       && (using_gprs
5309           || g_switch_value < 4
5310           || (data[0] == 0 && data[1] == 0)
5311           || (data[2] == 0 && data[3] == 0)))
5312     {
5313       imm->X_op = O_constant;
5314       if (!target_big_endian)
5315         imm->X_add_number = bfd_getl32 (data);
5316       else
5317         imm->X_add_number = bfd_getb32 (data);
5318       offset->X_op = O_absent;
5319       return TRUE;
5320     }
5321
5322   /* Handle 64-bit constants for which an immediate value is best.  */
5323   if (length == 8
5324       && !mips_disable_float_construction
5325       /* Constants can only be constructed in GPRs and copied
5326          to FPRs if the GPRs are at least as wide as the FPRs.
5327          Force the constant into memory if we are using 64-bit FPRs
5328          but the GPRs are only 32 bits wide.  */
5329       /* ??? No longer true with the addition of MTHC1, but this
5330          is legacy code...  */
5331       && (using_gprs || !(HAVE_64BIT_FPRS && HAVE_32BIT_GPRS))
5332       && ((data[0] == 0 && data[1] == 0)
5333           || (data[2] == 0 && data[3] == 0))
5334       && ((data[4] == 0 && data[5] == 0)
5335           || (data[6] == 0 && data[7] == 0)))
5336     {
5337       /* The value is simple enough to load with a couple of instructions.
5338          If using 32-bit registers, set IMM to the high order 32 bits and
5339          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5340          64 bit constant.  */
5341       if (using_gprs ? HAVE_32BIT_GPRS : HAVE_32BIT_FPRS)
5342         {
5343           imm->X_op = O_constant;
5344           offset->X_op = O_constant;
5345           if (!target_big_endian)
5346             {
5347               imm->X_add_number = bfd_getl32 (data + 4);
5348               offset->X_add_number = bfd_getl32 (data);
5349             }
5350           else
5351             {
5352               imm->X_add_number = bfd_getb32 (data);
5353               offset->X_add_number = bfd_getb32 (data + 4);
5354             }
5355           if (offset->X_add_number == 0)
5356             offset->X_op = O_absent;
5357         }
5358       else
5359         {
5360           imm->X_op = O_constant;
5361           if (!target_big_endian)
5362             imm->X_add_number = bfd_getl64 (data);
5363           else
5364             imm->X_add_number = bfd_getb64 (data);
5365           offset->X_op = O_absent;
5366         }
5367       return TRUE;
5368     }
5369
5370   /* Switch to the right section.  */
5371   seg = now_seg;
5372   subseg = now_subseg;
5373   if (length == 4)
5374     {
5375       gas_assert (!using_gprs && g_switch_value >= 4);
5376       newname = ".lit4";
5377     }
5378   else
5379     {
5380       if (using_gprs || g_switch_value < 8)
5381         newname = RDATA_SECTION_NAME;
5382       else
5383         newname = ".lit8";
5384     }
5385
5386   new_seg = subseg_new (newname, (subsegT) 0);
5387   bfd_set_section_flags (stdoutput, new_seg,
5388                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5389   frag_align (length == 4 ? 2 : 3, 0, 0);
5390   if (strncmp (TARGET_OS, "elf", 3) != 0)
5391     record_alignment (new_seg, 4);
5392   else
5393     record_alignment (new_seg, length == 4 ? 2 : 3);
5394   if (seg == now_seg)
5395     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5396
5397   /* Set the argument to the current address in the section.  */
5398   imm->X_op = O_absent;
5399   offset->X_op = O_symbol;
5400   offset->X_add_symbol = symbol_temp_new_now ();
5401   offset->X_add_number = 0;
5402
5403   /* Put the floating point number into the section.  */
5404   p = frag_more (length);
5405   memcpy (p, data, length);
5406
5407   /* Switch back to the original section.  */
5408   subseg_set (seg, subseg);
5409   return TRUE;
5410 }
5411
5412 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5413    them.  */
5414
5415 static bfd_boolean
5416 match_vu0_suffix_operand (struct mips_arg_info *arg,
5417                           const struct mips_operand *operand,
5418                           bfd_boolean match_p)
5419 {
5420   unsigned int uval;
5421
5422   /* The operand can be an XYZW mask or a single 2-bit channel index
5423      (with X being 0).  */
5424   gas_assert (operand->size == 2 || operand->size == 4);
5425
5426   /* The suffix can be omitted when it is already part of the opcode.  */
5427   if (arg->token->type != OT_CHANNELS)
5428     return match_p;
5429
5430   uval = arg->token->u.channels;
5431   if (operand->size == 2)
5432     {
5433       /* Check that a single bit is set and convert it into a 2-bit index.  */
5434       if ((uval & -uval) != uval)
5435         return FALSE;
5436       uval = 4 - ffs (uval);
5437     }
5438
5439   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5440     return FALSE;
5441
5442   ++arg->token;
5443   if (!match_p)
5444     insn_insert_operand (arg->insn, operand, uval);
5445   return TRUE;
5446 }
5447
5448 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5449    of the argument text if the match is successful, otherwise return null.  */
5450
5451 static bfd_boolean
5452 match_operand (struct mips_arg_info *arg,
5453                const struct mips_operand *operand)
5454 {
5455   switch (operand->type)
5456     {
5457     case OP_INT:
5458       return match_int_operand (arg, operand);
5459
5460     case OP_MAPPED_INT:
5461       return match_mapped_int_operand (arg, operand);
5462
5463     case OP_MSB:
5464       return match_msb_operand (arg, operand);
5465
5466     case OP_REG:
5467     case OP_OPTIONAL_REG:
5468       return match_reg_operand (arg, operand);
5469
5470     case OP_REG_PAIR:
5471       return match_reg_pair_operand (arg, operand);
5472
5473     case OP_PCREL:
5474       return match_pcrel_operand (arg);
5475
5476     case OP_PERF_REG:
5477       return match_perf_reg_operand (arg, operand);
5478
5479     case OP_ADDIUSP_INT:
5480       return match_addiusp_operand (arg, operand);
5481
5482     case OP_CLO_CLZ_DEST:
5483       return match_clo_clz_dest_operand (arg, operand);
5484
5485     case OP_LWM_SWM_LIST:
5486       return match_lwm_swm_list_operand (arg, operand);
5487
5488     case OP_ENTRY_EXIT_LIST:
5489       return match_entry_exit_operand (arg, operand);
5490
5491     case OP_SAVE_RESTORE_LIST:
5492       return match_save_restore_list_operand (arg);
5493
5494     case OP_MDMX_IMM_REG:
5495       return match_mdmx_imm_reg_operand (arg, operand);
5496
5497     case OP_REPEAT_DEST_REG:
5498       return match_tied_reg_operand (arg, arg->dest_regno);
5499
5500     case OP_REPEAT_PREV_REG:
5501       return match_tied_reg_operand (arg, arg->last_regno);
5502
5503     case OP_PC:
5504       return match_pc_operand (arg);
5505
5506     case OP_VU0_SUFFIX:
5507       return match_vu0_suffix_operand (arg, operand, FALSE);
5508
5509     case OP_VU0_MATCH_SUFFIX:
5510       return match_vu0_suffix_operand (arg, operand, TRUE);
5511
5512     case OP_IMM_INDEX:
5513       return match_imm_index_operand (arg, operand);
5514
5515     case OP_REG_INDEX:
5516       return match_reg_index_operand (arg, operand);
5517     }
5518   abort ();
5519 }
5520
5521 /* ARG is the state after successfully matching an instruction.
5522    Issue any queued-up warnings.  */
5523
5524 static void
5525 check_completed_insn (struct mips_arg_info *arg)
5526 {
5527   if (arg->seen_at)
5528     {
5529       if (AT == ATREG)
5530         as_warn (_("used $at without \".set noat\""));
5531       else
5532         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
5533     }
5534 }
5535
5536 /* Return true if modifying general-purpose register REG needs a delay.  */
5537
5538 static bfd_boolean
5539 reg_needs_delay (unsigned int reg)
5540 {
5541   unsigned long prev_pinfo;
5542
5543   prev_pinfo = history[0].insn_mo->pinfo;
5544   if (!mips_opts.noreorder
5545       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
5546           || ((prev_pinfo & INSN_LOAD_COPROC_DELAY) && !cop_interlocks))
5547       && (gpr_write_mask (&history[0]) & (1 << reg)))
5548     return TRUE;
5549
5550   return FALSE;
5551 }
5552
5553 /* Classify an instruction according to the FIX_VR4120_* enumeration.
5554    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
5555    by VR4120 errata.  */
5556
5557 static unsigned int
5558 classify_vr4120_insn (const char *name)
5559 {
5560   if (strncmp (name, "macc", 4) == 0)
5561     return FIX_VR4120_MACC;
5562   if (strncmp (name, "dmacc", 5) == 0)
5563     return FIX_VR4120_DMACC;
5564   if (strncmp (name, "mult", 4) == 0)
5565     return FIX_VR4120_MULT;
5566   if (strncmp (name, "dmult", 5) == 0)
5567     return FIX_VR4120_DMULT;
5568   if (strstr (name, "div"))
5569     return FIX_VR4120_DIV;
5570   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
5571     return FIX_VR4120_MTHILO;
5572   return NUM_FIX_VR4120_CLASSES;
5573 }
5574
5575 #define INSN_ERET       0x42000018
5576 #define INSN_DERET      0x4200001f
5577 #define INSN_DMULT      0x1c
5578 #define INSN_DMULTU     0x1d
5579
5580 /* Return the number of instructions that must separate INSN1 and INSN2,
5581    where INSN1 is the earlier instruction.  Return the worst-case value
5582    for any INSN2 if INSN2 is null.  */
5583
5584 static unsigned int
5585 insns_between (const struct mips_cl_insn *insn1,
5586                const struct mips_cl_insn *insn2)
5587 {
5588   unsigned long pinfo1, pinfo2;
5589   unsigned int mask;
5590
5591   /* If INFO2 is null, pessimistically assume that all flags are set for
5592      the second instruction.  */
5593   pinfo1 = insn1->insn_mo->pinfo;
5594   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
5595
5596   /* For most targets, write-after-read dependencies on the HI and LO
5597      registers must be separated by at least two instructions.  */
5598   if (!hilo_interlocks)
5599     {
5600       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
5601         return 2;
5602       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
5603         return 2;
5604     }
5605
5606   /* If we're working around r7000 errata, there must be two instructions
5607      between an mfhi or mflo and any instruction that uses the result.  */
5608   if (mips_7000_hilo_fix
5609       && !mips_opts.micromips
5610       && MF_HILO_INSN (pinfo1)
5611       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
5612     return 2;
5613
5614   /* If we're working around 24K errata, one instruction is required
5615      if an ERET or DERET is followed by a branch instruction.  */
5616   if (mips_fix_24k && !mips_opts.micromips)
5617     {
5618       if (insn1->insn_opcode == INSN_ERET
5619           || insn1->insn_opcode == INSN_DERET)
5620         {
5621           if (insn2 == NULL
5622               || insn2->insn_opcode == INSN_ERET
5623               || insn2->insn_opcode == INSN_DERET
5624               || delayed_branch_p (insn2))
5625             return 1;
5626         }
5627     }
5628
5629   /* If we're working around PMC RM7000 errata, there must be three
5630      nops between a dmult and a load instruction.  */
5631   if (mips_fix_rm7000 && !mips_opts.micromips)
5632     {
5633       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
5634           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
5635         {
5636           if (pinfo2 & INSN_LOAD_MEMORY)
5637            return 3;
5638         }
5639     }
5640
5641   /* If working around VR4120 errata, check for combinations that need
5642      a single intervening instruction.  */
5643   if (mips_fix_vr4120 && !mips_opts.micromips)
5644     {
5645       unsigned int class1, class2;
5646
5647       class1 = classify_vr4120_insn (insn1->insn_mo->name);
5648       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
5649         {
5650           if (insn2 == NULL)
5651             return 1;
5652           class2 = classify_vr4120_insn (insn2->insn_mo->name);
5653           if (vr4120_conflicts[class1] & (1 << class2))
5654             return 1;
5655         }
5656     }
5657
5658   if (!HAVE_CODE_COMPRESSION)
5659     {
5660       /* Check for GPR or coprocessor load delays.  All such delays
5661          are on the RT register.  */
5662       /* Itbl support may require additional care here.  */
5663       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
5664           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC_DELAY)))
5665         {
5666           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
5667             return 1;
5668         }
5669
5670       /* Check for generic coprocessor hazards.
5671
5672          This case is not handled very well.  There is no special
5673          knowledge of CP0 handling, and the coprocessors other than
5674          the floating point unit are not distinguished at all.  */
5675       /* Itbl support may require additional care here. FIXME!
5676          Need to modify this to include knowledge about
5677          user specified delays!  */
5678       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE_DELAY))
5679                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
5680         {
5681           /* Handle cases where INSN1 writes to a known general coprocessor
5682              register.  There must be a one instruction delay before INSN2
5683              if INSN2 reads that register, otherwise no delay is needed.  */
5684           mask = fpr_write_mask (insn1);
5685           if (mask != 0)
5686             {
5687               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
5688                 return 1;
5689             }
5690           else
5691             {
5692               /* Read-after-write dependencies on the control registers
5693                  require a two-instruction gap.  */
5694               if ((pinfo1 & INSN_WRITE_COND_CODE)
5695                   && (pinfo2 & INSN_READ_COND_CODE))
5696                 return 2;
5697
5698               /* We don't know exactly what INSN1 does.  If INSN2 is
5699                  also a coprocessor instruction, assume there must be
5700                  a one instruction gap.  */
5701               if (pinfo2 & INSN_COP)
5702                 return 1;
5703             }
5704         }
5705
5706       /* Check for read-after-write dependencies on the coprocessor
5707          control registers in cases where INSN1 does not need a general
5708          coprocessor delay.  This means that INSN1 is a floating point
5709          comparison instruction.  */
5710       /* Itbl support may require additional care here.  */
5711       else if (!cop_interlocks
5712                && (pinfo1 & INSN_WRITE_COND_CODE)
5713                && (pinfo2 & INSN_READ_COND_CODE))
5714         return 1;
5715     }
5716
5717   return 0;
5718 }
5719
5720 /* Return the number of nops that would be needed to work around the
5721    VR4130 mflo/mfhi errata if instruction INSN immediately followed
5722    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
5723    that are contained within the first IGNORE instructions of HIST.  */
5724
5725 static int
5726 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
5727                  const struct mips_cl_insn *insn)
5728 {
5729   int i, j;
5730   unsigned int mask;
5731
5732   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
5733      are not affected by the errata.  */
5734   if (insn != 0
5735       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
5736           || strcmp (insn->insn_mo->name, "mtlo") == 0
5737           || strcmp (insn->insn_mo->name, "mthi") == 0))
5738     return 0;
5739
5740   /* Search for the first MFLO or MFHI.  */
5741   for (i = 0; i < MAX_VR4130_NOPS; i++)
5742     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
5743       {
5744         /* Extract the destination register.  */
5745         mask = gpr_write_mask (&hist[i]);
5746
5747         /* No nops are needed if INSN reads that register.  */
5748         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
5749           return 0;
5750
5751         /* ...or if any of the intervening instructions do.  */
5752         for (j = 0; j < i; j++)
5753           if (gpr_read_mask (&hist[j]) & mask)
5754             return 0;
5755
5756         if (i >= ignore)
5757           return MAX_VR4130_NOPS - i;
5758       }
5759   return 0;
5760 }
5761
5762 #define BASE_REG_EQ(INSN1, INSN2)       \
5763   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
5764       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
5765
5766 /* Return the minimum alignment for this store instruction.  */
5767
5768 static int
5769 fix_24k_align_to (const struct mips_opcode *mo)
5770 {
5771   if (strcmp (mo->name, "sh") == 0)
5772     return 2;
5773
5774   if (strcmp (mo->name, "swc1") == 0
5775       || strcmp (mo->name, "swc2") == 0
5776       || strcmp (mo->name, "sw") == 0
5777       || strcmp (mo->name, "sc") == 0
5778       || strcmp (mo->name, "s.s") == 0)
5779     return 4;
5780
5781   if (strcmp (mo->name, "sdc1") == 0
5782       || strcmp (mo->name, "sdc2") == 0
5783       || strcmp (mo->name, "s.d") == 0)
5784     return 8;
5785
5786   /* sb, swl, swr */
5787   return 1;
5788 }
5789
5790 struct fix_24k_store_info
5791   {
5792     /* Immediate offset, if any, for this store instruction.  */
5793     short off;
5794     /* Alignment required by this store instruction.  */
5795     int align_to;
5796     /* True for register offsets.  */
5797     int register_offset;
5798   };
5799
5800 /* Comparison function used by qsort.  */
5801
5802 static int
5803 fix_24k_sort (const void *a, const void *b)
5804 {
5805   const struct fix_24k_store_info *pos1 = a;
5806   const struct fix_24k_store_info *pos2 = b;
5807
5808   return (pos1->off - pos2->off);
5809 }
5810
5811 /* INSN is a store instruction.  Try to record the store information
5812    in STINFO.  Return false if the information isn't known.  */
5813
5814 static bfd_boolean
5815 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
5816                            const struct mips_cl_insn *insn)
5817 {
5818   /* The instruction must have a known offset.  */
5819   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
5820     return FALSE;
5821
5822   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
5823   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
5824   return TRUE;
5825 }
5826
5827 /* Return the number of nops that would be needed to work around the 24k
5828    "lost data on stores during refill" errata if instruction INSN
5829    immediately followed the 2 instructions described by HIST.
5830    Ignore hazards that are contained within the first IGNORE
5831    instructions of HIST.
5832
5833    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
5834    for the data cache refills and store data. The following describes
5835    the scenario where the store data could be lost.
5836
5837    * A data cache miss, due to either a load or a store, causing fill
5838      data to be supplied by the memory subsystem
5839    * The first three doublewords of fill data are returned and written
5840      into the cache
5841    * A sequence of four stores occurs in consecutive cycles around the
5842      final doubleword of the fill:
5843    * Store A
5844    * Store B
5845    * Store C
5846    * Zero, One or more instructions
5847    * Store D
5848
5849    The four stores A-D must be to different doublewords of the line that
5850    is being filled. The fourth instruction in the sequence above permits
5851    the fill of the final doubleword to be transferred from the FSB into
5852    the cache. In the sequence above, the stores may be either integer
5853    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
5854    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
5855    different doublewords on the line. If the floating point unit is
5856    running in 1:2 mode, it is not possible to create the sequence above
5857    using only floating point store instructions.
5858
5859    In this case, the cache line being filled is incorrectly marked
5860    invalid, thereby losing the data from any store to the line that
5861    occurs between the original miss and the completion of the five
5862    cycle sequence shown above.
5863
5864    The workarounds are:
5865
5866    * Run the data cache in write-through mode.
5867    * Insert a non-store instruction between
5868      Store A and Store B or Store B and Store C.  */
5869   
5870 static int
5871 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
5872               const struct mips_cl_insn *insn)
5873 {
5874   struct fix_24k_store_info pos[3];
5875   int align, i, base_offset;
5876
5877   if (ignore >= 2)
5878     return 0;
5879
5880   /* If the previous instruction wasn't a store, there's nothing to
5881      worry about.  */
5882   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5883     return 0;
5884
5885   /* If the instructions after the previous one are unknown, we have
5886      to assume the worst.  */
5887   if (!insn)
5888     return 1;
5889
5890   /* Check whether we are dealing with three consecutive stores.  */
5891   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
5892       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
5893     return 0;
5894
5895   /* If we don't know the relationship between the store addresses,
5896      assume the worst.  */
5897   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
5898       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
5899     return 1;
5900
5901   if (!fix_24k_record_store_info (&pos[0], insn)
5902       || !fix_24k_record_store_info (&pos[1], &hist[0])
5903       || !fix_24k_record_store_info (&pos[2], &hist[1]))
5904     return 1;
5905
5906   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
5907
5908   /* Pick a value of ALIGN and X such that all offsets are adjusted by
5909      X bytes and such that the base register + X is known to be aligned
5910      to align bytes.  */
5911
5912   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
5913     align = 8;
5914   else
5915     {
5916       align = pos[0].align_to;
5917       base_offset = pos[0].off;
5918       for (i = 1; i < 3; i++)
5919         if (align < pos[i].align_to)
5920           {
5921             align = pos[i].align_to;
5922             base_offset = pos[i].off;
5923           }
5924       for (i = 0; i < 3; i++)
5925         pos[i].off -= base_offset;
5926     }
5927
5928   pos[0].off &= ~align + 1;
5929   pos[1].off &= ~align + 1;
5930   pos[2].off &= ~align + 1;
5931
5932   /* If any two stores write to the same chunk, they also write to the
5933      same doubleword.  The offsets are still sorted at this point.  */
5934   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
5935     return 0;
5936
5937   /* A range of at least 9 bytes is needed for the stores to be in
5938      non-overlapping doublewords.  */
5939   if (pos[2].off - pos[0].off <= 8)
5940     return 0;
5941
5942   if (pos[2].off - pos[1].off >= 24
5943       || pos[1].off - pos[0].off >= 24
5944       || pos[2].off - pos[0].off >= 32)
5945     return 0;
5946
5947   return 1;
5948 }
5949
5950 /* Return the number of nops that would be needed if instruction INSN
5951    immediately followed the MAX_NOPS instructions given by HIST,
5952    where HIST[0] is the most recent instruction.  Ignore hazards
5953    between INSN and the first IGNORE instructions in HIST.
5954
5955    If INSN is null, return the worse-case number of nops for any
5956    instruction.  */
5957
5958 static int
5959 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
5960                const struct mips_cl_insn *insn)
5961 {
5962   int i, nops, tmp_nops;
5963
5964   nops = 0;
5965   for (i = ignore; i < MAX_DELAY_NOPS; i++)
5966     {
5967       tmp_nops = insns_between (hist + i, insn) - i;
5968       if (tmp_nops > nops)
5969         nops = tmp_nops;
5970     }
5971
5972   if (mips_fix_vr4130 && !mips_opts.micromips)
5973     {
5974       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
5975       if (tmp_nops > nops)
5976         nops = tmp_nops;
5977     }
5978
5979   if (mips_fix_24k && !mips_opts.micromips)
5980     {
5981       tmp_nops = nops_for_24k (ignore, hist, insn);
5982       if (tmp_nops > nops)
5983         nops = tmp_nops;
5984     }
5985
5986   return nops;
5987 }
5988
5989 /* The variable arguments provide NUM_INSNS extra instructions that
5990    might be added to HIST.  Return the largest number of nops that
5991    would be needed after the extended sequence, ignoring hazards
5992    in the first IGNORE instructions.  */
5993
5994 static int
5995 nops_for_sequence (int num_insns, int ignore,
5996                    const struct mips_cl_insn *hist, ...)
5997 {
5998   va_list args;
5999   struct mips_cl_insn buffer[MAX_NOPS];
6000   struct mips_cl_insn *cursor;
6001   int nops;
6002
6003   va_start (args, hist);
6004   cursor = buffer + num_insns;
6005   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6006   while (cursor > buffer)
6007     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6008
6009   nops = nops_for_insn (ignore, buffer, NULL);
6010   va_end (args);
6011   return nops;
6012 }
6013
6014 /* Like nops_for_insn, but if INSN is a branch, take into account the
6015    worst-case delay for the branch target.  */
6016
6017 static int
6018 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6019                          const struct mips_cl_insn *insn)
6020 {
6021   int nops, tmp_nops;
6022
6023   nops = nops_for_insn (ignore, hist, insn);
6024   if (delayed_branch_p (insn))
6025     {
6026       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6027                                     hist, insn, get_delay_slot_nop (insn));
6028       if (tmp_nops > nops)
6029         nops = tmp_nops;
6030     }
6031   else if (compact_branch_p (insn))
6032     {
6033       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6034       if (tmp_nops > nops)
6035         nops = tmp_nops;
6036     }
6037   return nops;
6038 }
6039
6040 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6041
6042 static void
6043 fix_loongson2f_nop (struct mips_cl_insn * ip)
6044 {
6045   gas_assert (!HAVE_CODE_COMPRESSION);
6046   if (strcmp (ip->insn_mo->name, "nop") == 0)
6047     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6048 }
6049
6050 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6051                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6052
6053 static void
6054 fix_loongson2f_jump (struct mips_cl_insn * ip)
6055 {
6056   gas_assert (!HAVE_CODE_COMPRESSION);
6057   if (strcmp (ip->insn_mo->name, "j") == 0
6058       || strcmp (ip->insn_mo->name, "jr") == 0
6059       || strcmp (ip->insn_mo->name, "jalr") == 0)
6060     {
6061       int sreg;
6062       expressionS ep;
6063
6064       if (! mips_opts.at)
6065         return;
6066
6067       sreg = EXTRACT_OPERAND (0, RS, *ip);
6068       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6069         return;
6070
6071       ep.X_op = O_constant;
6072       ep.X_add_number = 0xcfff0000;
6073       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6074       ep.X_add_number = 0xffff;
6075       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6076       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6077     }
6078 }
6079
6080 static void
6081 fix_loongson2f (struct mips_cl_insn * ip)
6082 {
6083   if (mips_fix_loongson2f_nop)
6084     fix_loongson2f_nop (ip);
6085
6086   if (mips_fix_loongson2f_jump)
6087     fix_loongson2f_jump (ip);
6088 }
6089
6090 /* IP is a branch that has a delay slot, and we need to fill it
6091    automatically.   Return true if we can do that by swapping IP
6092    with the previous instruction.
6093    ADDRESS_EXPR is an operand of the instruction to be used with
6094    RELOC_TYPE.  */
6095
6096 static bfd_boolean
6097 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6098                    bfd_reloc_code_real_type *reloc_type)
6099 {
6100   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6101   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6102   unsigned int fpr_read, prev_fpr_write;
6103
6104   /* -O2 and above is required for this optimization.  */
6105   if (mips_optimize < 2)
6106     return FALSE;
6107
6108   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6109   if (mips_opts.nomove)
6110     return FALSE;
6111
6112   /* We can't swap if the previous instruction's position is fixed.  */
6113   if (history[0].fixed_p)
6114     return FALSE;
6115
6116   /* If the previous previous insn was in a .set noreorder, we can't
6117      swap.  Actually, the MIPS assembler will swap in this situation.
6118      However, gcc configured -with-gnu-as will generate code like
6119
6120         .set    noreorder
6121         lw      $4,XXX
6122         .set    reorder
6123         INSN
6124         bne     $4,$0,foo
6125
6126      in which we can not swap the bne and INSN.  If gcc is not configured
6127      -with-gnu-as, it does not output the .set pseudo-ops.  */
6128   if (history[1].noreorder_p)
6129     return FALSE;
6130
6131   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6132      This means that the previous instruction was a 4-byte one anyhow.  */
6133   if (mips_opts.mips16 && history[0].fixp[0])
6134     return FALSE;
6135
6136   /* If the branch is itself the target of a branch, we can not swap.
6137      We cheat on this; all we check for is whether there is a label on
6138      this instruction.  If there are any branches to anything other than
6139      a label, users must use .set noreorder.  */
6140   if (seg_info (now_seg)->label_list)
6141     return FALSE;
6142
6143   /* If the previous instruction is in a variant frag other than this
6144      branch's one, we cannot do the swap.  This does not apply to
6145      MIPS16 code, which uses variant frags for different purposes.  */
6146   if (!mips_opts.mips16
6147       && history[0].frag
6148       && history[0].frag->fr_type == rs_machine_dependent)
6149     return FALSE;
6150
6151   /* We do not swap with instructions that cannot architecturally
6152      be placed in a branch delay slot, such as SYNC or ERET.  We
6153      also refrain from swapping with a trap instruction, since it
6154      complicates trap handlers to have the trap instruction be in
6155      a delay slot.  */
6156   prev_pinfo = history[0].insn_mo->pinfo;
6157   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6158     return FALSE;
6159
6160   /* Check for conflicts between the branch and the instructions
6161      before the candidate delay slot.  */
6162   if (nops_for_insn (0, history + 1, ip) > 0)
6163     return FALSE;
6164
6165   /* Check for conflicts between the swapped sequence and the
6166      target of the branch.  */
6167   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6168     return FALSE;
6169
6170   /* If the branch reads a register that the previous
6171      instruction sets, we can not swap.  */
6172   gpr_read = gpr_read_mask (ip);
6173   prev_gpr_write = gpr_write_mask (&history[0]);
6174   if (gpr_read & prev_gpr_write)
6175     return FALSE;
6176
6177   fpr_read = fpr_read_mask (ip);
6178   prev_fpr_write = fpr_write_mask (&history[0]);
6179   if (fpr_read & prev_fpr_write)
6180     return FALSE;
6181
6182   /* If the branch writes a register that the previous
6183      instruction sets, we can not swap.  */
6184   gpr_write = gpr_write_mask (ip);
6185   if (gpr_write & prev_gpr_write)
6186     return FALSE;
6187
6188   /* If the branch writes a register that the previous
6189      instruction reads, we can not swap.  */
6190   prev_gpr_read = gpr_read_mask (&history[0]);
6191   if (gpr_write & prev_gpr_read)
6192     return FALSE;
6193
6194   /* If one instruction sets a condition code and the
6195      other one uses a condition code, we can not swap.  */
6196   pinfo = ip->insn_mo->pinfo;
6197   if ((pinfo & INSN_READ_COND_CODE)
6198       && (prev_pinfo & INSN_WRITE_COND_CODE))
6199     return FALSE;
6200   if ((pinfo & INSN_WRITE_COND_CODE)
6201       && (prev_pinfo & INSN_READ_COND_CODE))
6202     return FALSE;
6203
6204   /* If the previous instruction uses the PC, we can not swap.  */
6205   prev_pinfo2 = history[0].insn_mo->pinfo2;
6206   if (prev_pinfo2 & INSN2_READ_PC)
6207     return FALSE;
6208
6209   /* If the previous instruction has an incorrect size for a fixed
6210      branch delay slot in microMIPS mode, we cannot swap.  */
6211   pinfo2 = ip->insn_mo->pinfo2;
6212   if (mips_opts.micromips
6213       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6214       && insn_length (history) != 2)
6215     return FALSE;
6216   if (mips_opts.micromips
6217       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6218       && insn_length (history) != 4)
6219     return FALSE;
6220
6221   /* On R5900 short loops need to be fixed by inserting a nop in
6222      the branch delay slots.
6223      A short loop can be terminated too early.  */
6224   if (mips_opts.arch == CPU_R5900
6225       /* Check if instruction has a parameter, ignore "j $31". */
6226       && (address_expr != NULL)
6227       /* Parameter must be 16 bit. */
6228       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6229       /* Branch to same segment. */
6230       && (S_GET_SEGMENT(address_expr->X_add_symbol) == now_seg)
6231       /* Branch to same code fragment. */
6232       && (symbol_get_frag(address_expr->X_add_symbol) == frag_now)
6233       /* Can only calculate branch offset if value is known. */
6234       && symbol_constant_p(address_expr->X_add_symbol)
6235       /* Check if branch is really conditional. */
6236       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6237         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6238         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6239     {
6240       int distance;
6241       /* Check if loop is shorter than 6 instructions including
6242          branch and delay slot.  */
6243       distance = frag_now_fix() - S_GET_VALUE(address_expr->X_add_symbol);
6244       if (distance <= 20)
6245         {
6246           int i;
6247           int rv;
6248
6249           rv = FALSE;
6250           /* When the loop includes branches or jumps,
6251              it is not a short loop. */
6252           for (i = 0; i < (distance / 4); i++)
6253             {
6254               if ((history[i].cleared_p)
6255                   || delayed_branch_p(&history[i]))
6256                 {
6257                   rv = TRUE;
6258                   break;
6259                 }
6260             }
6261           if (rv == FALSE)
6262             {
6263               /* Insert nop after branch to fix short loop. */
6264               return FALSE;
6265             }
6266         }
6267     }
6268
6269   return TRUE;
6270 }
6271
6272 /* Decide how we should add IP to the instruction stream.
6273    ADDRESS_EXPR is an operand of the instruction to be used with
6274    RELOC_TYPE.  */
6275
6276 static enum append_method
6277 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6278                    bfd_reloc_code_real_type *reloc_type)
6279 {
6280   /* The relaxed version of a macro sequence must be inherently
6281      hazard-free.  */
6282   if (mips_relax.sequence == 2)
6283     return APPEND_ADD;
6284
6285   /* We must not dabble with instructions in a ".set norerorder" block.  */
6286   if (mips_opts.noreorder)
6287     return APPEND_ADD;
6288
6289   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6290   if (delayed_branch_p (ip))
6291     {
6292       if (!branch_likely_p (ip)
6293           && can_swap_branch_p (ip, address_expr, reloc_type))
6294         return APPEND_SWAP;
6295
6296       if (mips_opts.mips16
6297           && ISA_SUPPORTS_MIPS16E
6298           && gpr_read_mask (ip) != 0)
6299         return APPEND_ADD_COMPACT;
6300
6301       return APPEND_ADD_WITH_NOP;
6302     }
6303
6304   return APPEND_ADD;
6305 }
6306
6307 /* IP is a MIPS16 instruction whose opcode we have just changed.
6308    Point IP->insn_mo to the new opcode's definition.  */
6309
6310 static void
6311 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6312 {
6313   const struct mips_opcode *mo, *end;
6314
6315   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6316   for (mo = ip->insn_mo; mo < end; mo++)
6317     if ((ip->insn_opcode & mo->mask) == mo->match)
6318       {
6319         ip->insn_mo = mo;
6320         return;
6321       }
6322   abort ();
6323 }
6324
6325 /* For microMIPS macros, we need to generate a local number label
6326    as the target of branches.  */
6327 #define MICROMIPS_LABEL_CHAR            '\037'
6328 static unsigned long micromips_target_label;
6329 static char micromips_target_name[32];
6330
6331 static char *
6332 micromips_label_name (void)
6333 {
6334   char *p = micromips_target_name;
6335   char symbol_name_temporary[24];
6336   unsigned long l;
6337   int i;
6338
6339   if (*p)
6340     return p;
6341
6342   i = 0;
6343   l = micromips_target_label;
6344 #ifdef LOCAL_LABEL_PREFIX
6345   *p++ = LOCAL_LABEL_PREFIX;
6346 #endif
6347   *p++ = 'L';
6348   *p++ = MICROMIPS_LABEL_CHAR;
6349   do
6350     {
6351       symbol_name_temporary[i++] = l % 10 + '0';
6352       l /= 10;
6353     }
6354   while (l != 0);
6355   while (i > 0)
6356     *p++ = symbol_name_temporary[--i];
6357   *p = '\0';
6358
6359   return micromips_target_name;
6360 }
6361
6362 static void
6363 micromips_label_expr (expressionS *label_expr)
6364 {
6365   label_expr->X_op = O_symbol;
6366   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6367   label_expr->X_add_number = 0;
6368 }
6369
6370 static void
6371 micromips_label_inc (void)
6372 {
6373   micromips_target_label++;
6374   *micromips_target_name = '\0';
6375 }
6376
6377 static void
6378 micromips_add_label (void)
6379 {
6380   symbolS *s;
6381
6382   s = colon (micromips_label_name ());
6383   micromips_label_inc ();
6384   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6385 }
6386
6387 /* If assembling microMIPS code, then return the microMIPS reloc
6388    corresponding to the requested one if any.  Otherwise return
6389    the reloc unchanged.  */
6390
6391 static bfd_reloc_code_real_type
6392 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6393 {
6394   static const bfd_reloc_code_real_type relocs[][2] =
6395     {
6396       /* Keep sorted incrementally by the left-hand key.  */
6397       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6398       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6399       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6400       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6401       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6402       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6403       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6404       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6405       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6406       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6407       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6408       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6409       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6410       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6411       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6412       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6413       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6414       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6415       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6416       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6417       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6418       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6419       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6420       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6421       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6422       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6423       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6424     };
6425   bfd_reloc_code_real_type r;
6426   size_t i;
6427
6428   if (!mips_opts.micromips)
6429     return reloc;
6430   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6431     {
6432       r = relocs[i][0];
6433       if (r > reloc)
6434         return reloc;
6435       if (r == reloc)
6436         return relocs[i][1];
6437     }
6438   return reloc;
6439 }
6440
6441 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6442    Return true on success, storing the resolved value in RESULT.  */
6443
6444 static bfd_boolean
6445 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6446                  offsetT *result)
6447 {
6448   switch (reloc)
6449     {
6450     case BFD_RELOC_MIPS_HIGHEST:
6451     case BFD_RELOC_MICROMIPS_HIGHEST:
6452       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6453       return TRUE;
6454
6455     case BFD_RELOC_MIPS_HIGHER:
6456     case BFD_RELOC_MICROMIPS_HIGHER:
6457       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6458       return TRUE;
6459
6460     case BFD_RELOC_HI16_S:
6461     case BFD_RELOC_MICROMIPS_HI16_S:
6462     case BFD_RELOC_MIPS16_HI16_S:
6463       *result = ((operand + 0x8000) >> 16) & 0xffff;
6464       return TRUE;
6465
6466     case BFD_RELOC_HI16:
6467     case BFD_RELOC_MICROMIPS_HI16:
6468     case BFD_RELOC_MIPS16_HI16:
6469       *result = (operand >> 16) & 0xffff;
6470       return TRUE;
6471
6472     case BFD_RELOC_LO16:
6473     case BFD_RELOC_MICROMIPS_LO16:
6474     case BFD_RELOC_MIPS16_LO16:
6475       *result = operand & 0xffff;
6476       return TRUE;
6477
6478     case BFD_RELOC_UNUSED:
6479       *result = operand;
6480       return TRUE;
6481
6482     default:
6483       return FALSE;
6484     }
6485 }
6486
6487 /* Output an instruction.  IP is the instruction information.
6488    ADDRESS_EXPR is an operand of the instruction to be used with
6489    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
6490    a macro expansion.  */
6491
6492 static void
6493 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
6494              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
6495 {
6496   unsigned long prev_pinfo2, pinfo;
6497   bfd_boolean relaxed_branch = FALSE;
6498   enum append_method method;
6499   bfd_boolean relax32;
6500   int branch_disp;
6501
6502   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
6503     fix_loongson2f (ip);
6504
6505   file_ase_mips16 |= mips_opts.mips16;
6506   file_ase_micromips |= mips_opts.micromips;
6507
6508   prev_pinfo2 = history[0].insn_mo->pinfo2;
6509   pinfo = ip->insn_mo->pinfo;
6510
6511   if (mips_opts.micromips
6512       && !expansionp
6513       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
6514            && micromips_insn_length (ip->insn_mo) != 2)
6515           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
6516               && micromips_insn_length (ip->insn_mo) != 4)))
6517     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
6518              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
6519
6520   if (address_expr == NULL)
6521     ip->complete_p = 1;
6522   else if (reloc_type[0] <= BFD_RELOC_UNUSED
6523            && reloc_type[1] == BFD_RELOC_UNUSED
6524            && reloc_type[2] == BFD_RELOC_UNUSED
6525            && address_expr->X_op == O_constant)
6526     {
6527       switch (*reloc_type)
6528         {
6529         case BFD_RELOC_MIPS_JMP:
6530           {
6531             int shift;
6532
6533             shift = mips_opts.micromips ? 1 : 2;
6534             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6535               as_bad (_("jump to misaligned address (0x%lx)"),
6536                       (unsigned long) address_expr->X_add_number);
6537             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6538                                 & 0x3ffffff);
6539             ip->complete_p = 1;
6540           }
6541           break;
6542
6543         case BFD_RELOC_MIPS16_JMP:
6544           if ((address_expr->X_add_number & 3) != 0)
6545             as_bad (_("jump to misaligned address (0x%lx)"),
6546                     (unsigned long) address_expr->X_add_number);
6547           ip->insn_opcode |=
6548             (((address_expr->X_add_number & 0x7c0000) << 3)
6549                | ((address_expr->X_add_number & 0xf800000) >> 7)
6550                | ((address_expr->X_add_number & 0x3fffc) >> 2));
6551           ip->complete_p = 1;
6552           break;
6553
6554         case BFD_RELOC_16_PCREL_S2:
6555           {
6556             int shift;
6557
6558             shift = mips_opts.micromips ? 1 : 2;
6559             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
6560               as_bad (_("branch to misaligned address (0x%lx)"),
6561                       (unsigned long) address_expr->X_add_number);
6562             if (!mips_relax_branch)
6563               {
6564                 if ((address_expr->X_add_number + (1 << (shift + 15)))
6565                     & ~((1 << (shift + 16)) - 1))
6566                   as_bad (_("branch address range overflow (0x%lx)"),
6567                           (unsigned long) address_expr->X_add_number);
6568                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
6569                                     & 0xffff);
6570               }
6571           }
6572           break;
6573
6574         default:
6575           {
6576             offsetT value;
6577
6578             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
6579                                  &value))
6580               {
6581                 ip->insn_opcode |= value & 0xffff;
6582                 ip->complete_p = 1;
6583               }
6584           }
6585           break;
6586         }
6587     }
6588
6589   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
6590     {
6591       /* There are a lot of optimizations we could do that we don't.
6592          In particular, we do not, in general, reorder instructions.
6593          If you use gcc with optimization, it will reorder
6594          instructions and generally do much more optimization then we
6595          do here; repeating all that work in the assembler would only
6596          benefit hand written assembly code, and does not seem worth
6597          it.  */
6598       int nops = (mips_optimize == 0
6599                   ? nops_for_insn (0, history, NULL)
6600                   : nops_for_insn_or_target (0, history, ip));
6601       if (nops > 0)
6602         {
6603           fragS *old_frag;
6604           unsigned long old_frag_offset;
6605           int i;
6606
6607           old_frag = frag_now;
6608           old_frag_offset = frag_now_fix ();
6609
6610           for (i = 0; i < nops; i++)
6611             add_fixed_insn (NOP_INSN);
6612           insert_into_history (0, nops, NOP_INSN);
6613
6614           if (listing)
6615             {
6616               listing_prev_line ();
6617               /* We may be at the start of a variant frag.  In case we
6618                  are, make sure there is enough space for the frag
6619                  after the frags created by listing_prev_line.  The
6620                  argument to frag_grow here must be at least as large
6621                  as the argument to all other calls to frag_grow in
6622                  this file.  We don't have to worry about being in the
6623                  middle of a variant frag, because the variants insert
6624                  all needed nop instructions themselves.  */
6625               frag_grow (40);
6626             }
6627
6628           mips_move_text_labels ();
6629
6630 #ifndef NO_ECOFF_DEBUGGING
6631           if (ECOFF_DEBUGGING)
6632             ecoff_fix_loc (old_frag, old_frag_offset);
6633 #endif
6634         }
6635     }
6636   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
6637     {
6638       int nops;
6639
6640       /* Work out how many nops in prev_nop_frag are needed by IP,
6641          ignoring hazards generated by the first prev_nop_frag_since
6642          instructions.  */
6643       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
6644       gas_assert (nops <= prev_nop_frag_holds);
6645
6646       /* Enforce NOPS as a minimum.  */
6647       if (nops > prev_nop_frag_required)
6648         prev_nop_frag_required = nops;
6649
6650       if (prev_nop_frag_holds == prev_nop_frag_required)
6651         {
6652           /* Settle for the current number of nops.  Update the history
6653              accordingly (for the benefit of any future .set reorder code).  */
6654           prev_nop_frag = NULL;
6655           insert_into_history (prev_nop_frag_since,
6656                                prev_nop_frag_holds, NOP_INSN);
6657         }
6658       else
6659         {
6660           /* Allow this instruction to replace one of the nops that was
6661              tentatively added to prev_nop_frag.  */
6662           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
6663           prev_nop_frag_holds--;
6664           prev_nop_frag_since++;
6665         }
6666     }
6667
6668   method = get_append_method (ip, address_expr, reloc_type);
6669   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
6670
6671   dwarf2_emit_insn (0);
6672   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
6673      so "move" the instruction address accordingly.
6674
6675      Also, it doesn't seem appropriate for the assembler to reorder .loc
6676      entries.  If this instruction is a branch that we are going to swap
6677      with the previous instruction, the two instructions should be
6678      treated as a unit, and the debug information for both instructions
6679      should refer to the start of the branch sequence.  Using the
6680      current position is certainly wrong when swapping a 32-bit branch
6681      and a 16-bit delay slot, since the current position would then be
6682      in the middle of a branch.  */
6683   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
6684
6685   relax32 = (mips_relax_branch
6686              /* Don't try branch relaxation within .set nomacro, or within
6687                 .set noat if we use $at for PIC computations.  If it turns
6688                 out that the branch was out-of-range, we'll get an error.  */
6689              && !mips_opts.warn_about_macros
6690              && (mips_opts.at || mips_pic == NO_PIC)
6691              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
6692                 as they have no complementing branches.  */
6693              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
6694
6695   if (!HAVE_CODE_COMPRESSION
6696       && address_expr
6697       && relax32
6698       && *reloc_type == BFD_RELOC_16_PCREL_S2
6699       && delayed_branch_p (ip))
6700     {
6701       relaxed_branch = TRUE;
6702       add_relaxed_insn (ip, (relaxed_branch_length
6703                              (NULL, NULL,
6704                               uncond_branch_p (ip) ? -1
6705                               : branch_likely_p (ip) ? 1
6706                               : 0)), 4,
6707                         RELAX_BRANCH_ENCODE
6708                         (AT,
6709                          uncond_branch_p (ip),
6710                          branch_likely_p (ip),
6711                          pinfo & INSN_WRITE_GPR_31,
6712                          0),
6713                         address_expr->X_add_symbol,
6714                         address_expr->X_add_number);
6715       *reloc_type = BFD_RELOC_UNUSED;
6716     }
6717   else if (mips_opts.micromips
6718            && address_expr
6719            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
6720                || *reloc_type > BFD_RELOC_UNUSED)
6721            && (delayed_branch_p (ip) || compact_branch_p (ip))
6722            /* Don't try branch relaxation when users specify
6723               16-bit/32-bit instructions.  */
6724            && !forced_insn_length)
6725     {
6726       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
6727       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
6728       int uncond = uncond_branch_p (ip) ? -1 : 0;
6729       int compact = compact_branch_p (ip);
6730       int al = pinfo & INSN_WRITE_GPR_31;
6731       int length32;
6732
6733       gas_assert (address_expr != NULL);
6734       gas_assert (!mips_relax.sequence);
6735
6736       relaxed_branch = TRUE;
6737       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
6738       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
6739                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
6740                                                 relax32, 0, 0),
6741                         address_expr->X_add_symbol,
6742                         address_expr->X_add_number);
6743       *reloc_type = BFD_RELOC_UNUSED;
6744     }
6745   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
6746     {
6747       /* We need to set up a variant frag.  */
6748       gas_assert (address_expr != NULL);
6749       add_relaxed_insn (ip, 4, 0,
6750                         RELAX_MIPS16_ENCODE
6751                         (*reloc_type - BFD_RELOC_UNUSED,
6752                          forced_insn_length == 2, forced_insn_length == 4,
6753                          delayed_branch_p (&history[0]),
6754                          history[0].mips16_absolute_jump_p),
6755                         make_expr_symbol (address_expr), 0);
6756     }
6757   else if (mips_opts.mips16 && insn_length (ip) == 2)
6758     {
6759       if (!delayed_branch_p (ip))
6760         /* Make sure there is enough room to swap this instruction with
6761            a following jump instruction.  */
6762         frag_grow (6);
6763       add_fixed_insn (ip);
6764     }
6765   else
6766     {
6767       if (mips_opts.mips16
6768           && mips_opts.noreorder
6769           && delayed_branch_p (&history[0]))
6770         as_warn (_("extended instruction in delay slot"));
6771
6772       if (mips_relax.sequence)
6773         {
6774           /* If we've reached the end of this frag, turn it into a variant
6775              frag and record the information for the instructions we've
6776              written so far.  */
6777           if (frag_room () < 4)
6778             relax_close_frag ();
6779           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
6780         }
6781
6782       if (mips_relax.sequence != 2)
6783         {
6784           if (mips_macro_warning.first_insn_sizes[0] == 0)
6785             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
6786           mips_macro_warning.sizes[0] += insn_length (ip);
6787           mips_macro_warning.insns[0]++;
6788         }
6789       if (mips_relax.sequence != 1)
6790         {
6791           if (mips_macro_warning.first_insn_sizes[1] == 0)
6792             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
6793           mips_macro_warning.sizes[1] += insn_length (ip);
6794           mips_macro_warning.insns[1]++;
6795         }
6796
6797       if (mips_opts.mips16)
6798         {
6799           ip->fixed_p = 1;
6800           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
6801         }
6802       add_fixed_insn (ip);
6803     }
6804
6805   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
6806     {
6807       bfd_reloc_code_real_type final_type[3];
6808       reloc_howto_type *howto0;
6809       reloc_howto_type *howto;
6810       int i;
6811
6812       /* Perform any necessary conversion to microMIPS relocations
6813          and find out how many relocations there actually are.  */
6814       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
6815         final_type[i] = micromips_map_reloc (reloc_type[i]);
6816
6817       /* In a compound relocation, it is the final (outermost)
6818          operator that determines the relocated field.  */
6819       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
6820       if (!howto)
6821         abort ();
6822
6823       if (i > 1)
6824         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
6825       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
6826                                  bfd_get_reloc_size (howto),
6827                                  address_expr,
6828                                  howto0 && howto0->pc_relative,
6829                                  final_type[0]);
6830
6831       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
6832       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
6833         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
6834
6835       /* These relocations can have an addend that won't fit in
6836          4 octets for 64bit assembly.  */
6837       if (HAVE_64BIT_GPRS
6838           && ! howto->partial_inplace
6839           && (reloc_type[0] == BFD_RELOC_16
6840               || reloc_type[0] == BFD_RELOC_32
6841               || reloc_type[0] == BFD_RELOC_MIPS_JMP
6842               || reloc_type[0] == BFD_RELOC_GPREL16
6843               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
6844               || reloc_type[0] == BFD_RELOC_GPREL32
6845               || reloc_type[0] == BFD_RELOC_64
6846               || reloc_type[0] == BFD_RELOC_CTOR
6847               || reloc_type[0] == BFD_RELOC_MIPS_SUB
6848               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
6849               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
6850               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
6851               || reloc_type[0] == BFD_RELOC_MIPS_REL16
6852               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
6853               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
6854               || hi16_reloc_p (reloc_type[0])
6855               || lo16_reloc_p (reloc_type[0])))
6856         ip->fixp[0]->fx_no_overflow = 1;
6857
6858       /* These relocations can have an addend that won't fit in 2 octets.  */
6859       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
6860           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
6861         ip->fixp[0]->fx_no_overflow = 1;
6862
6863       if (mips_relax.sequence)
6864         {
6865           if (mips_relax.first_fixup == 0)
6866             mips_relax.first_fixup = ip->fixp[0];
6867         }
6868       else if (reloc_needs_lo_p (*reloc_type))
6869         {
6870           struct mips_hi_fixup *hi_fixup;
6871
6872           /* Reuse the last entry if it already has a matching %lo.  */
6873           hi_fixup = mips_hi_fixup_list;
6874           if (hi_fixup == 0
6875               || !fixup_has_matching_lo_p (hi_fixup->fixp))
6876             {
6877               hi_fixup = ((struct mips_hi_fixup *)
6878                           xmalloc (sizeof (struct mips_hi_fixup)));
6879               hi_fixup->next = mips_hi_fixup_list;
6880               mips_hi_fixup_list = hi_fixup;
6881             }
6882           hi_fixup->fixp = ip->fixp[0];
6883           hi_fixup->seg = now_seg;
6884         }
6885
6886       /* Add fixups for the second and third relocations, if given.
6887          Note that the ABI allows the second relocation to be
6888          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
6889          moment we only use RSS_UNDEF, but we could add support
6890          for the others if it ever becomes necessary.  */
6891       for (i = 1; i < 3; i++)
6892         if (reloc_type[i] != BFD_RELOC_UNUSED)
6893           {
6894             ip->fixp[i] = fix_new (ip->frag, ip->where,
6895                                    ip->fixp[0]->fx_size, NULL, 0,
6896                                    FALSE, final_type[i]);
6897
6898             /* Use fx_tcbit to mark compound relocs.  */
6899             ip->fixp[0]->fx_tcbit = 1;
6900             ip->fixp[i]->fx_tcbit = 1;
6901           }
6902     }
6903   install_insn (ip);
6904
6905   /* Update the register mask information.  */
6906   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
6907   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
6908
6909   switch (method)
6910     {
6911     case APPEND_ADD:
6912       insert_into_history (0, 1, ip);
6913       break;
6914
6915     case APPEND_ADD_WITH_NOP:
6916       {
6917         struct mips_cl_insn *nop;
6918
6919         insert_into_history (0, 1, ip);
6920         nop = get_delay_slot_nop (ip);
6921         add_fixed_insn (nop);
6922         insert_into_history (0, 1, nop);
6923         if (mips_relax.sequence)
6924           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
6925       }
6926       break;
6927
6928     case APPEND_ADD_COMPACT:
6929       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
6930       gas_assert (mips_opts.mips16);
6931       ip->insn_opcode |= 0x0080;
6932       find_altered_mips16_opcode (ip);
6933       install_insn (ip);
6934       insert_into_history (0, 1, ip);
6935       break;
6936
6937     case APPEND_SWAP:
6938       {
6939         struct mips_cl_insn delay = history[0];
6940         if (mips_opts.mips16)
6941           {
6942             know (delay.frag == ip->frag);
6943             move_insn (ip, delay.frag, delay.where);
6944             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
6945           }
6946         else if (relaxed_branch || delay.frag != ip->frag)
6947           {
6948             /* Add the delay slot instruction to the end of the
6949                current frag and shrink the fixed part of the
6950                original frag.  If the branch occupies the tail of
6951                the latter, move it backwards to cover the gap.  */
6952             delay.frag->fr_fix -= branch_disp;
6953             if (delay.frag == ip->frag)
6954               move_insn (ip, ip->frag, ip->where - branch_disp);
6955             add_fixed_insn (&delay);
6956           }
6957         else
6958           {
6959             move_insn (&delay, ip->frag,
6960                        ip->where - branch_disp + insn_length (ip));
6961             move_insn (ip, history[0].frag, history[0].where);
6962           }
6963         history[0] = *ip;
6964         delay.fixed_p = 1;
6965         insert_into_history (0, 1, &delay);
6966       }
6967       break;
6968     }
6969
6970   /* If we have just completed an unconditional branch, clear the history.  */
6971   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
6972       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
6973     {
6974       unsigned int i;
6975
6976       mips_no_prev_insn ();
6977
6978       for (i = 0; i < ARRAY_SIZE (history); i++)
6979         history[i].cleared_p = 1;
6980     }
6981
6982   /* We need to emit a label at the end of branch-likely macros.  */
6983   if (emit_branch_likely_macro)
6984     {
6985       emit_branch_likely_macro = FALSE;
6986       micromips_add_label ();
6987     }
6988
6989   /* We just output an insn, so the next one doesn't have a label.  */
6990   mips_clear_insn_labels ();
6991 }
6992
6993 /* Forget that there was any previous instruction or label.
6994    When BRANCH is true, the branch history is also flushed.  */
6995
6996 static void
6997 mips_no_prev_insn (void)
6998 {
6999   prev_nop_frag = NULL;
7000   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7001   mips_clear_insn_labels ();
7002 }
7003
7004 /* This function must be called before we emit something other than
7005    instructions.  It is like mips_no_prev_insn except that it inserts
7006    any NOPS that might be needed by previous instructions.  */
7007
7008 void
7009 mips_emit_delays (void)
7010 {
7011   if (! mips_opts.noreorder)
7012     {
7013       int nops = nops_for_insn (0, history, NULL);
7014       if (nops > 0)
7015         {
7016           while (nops-- > 0)
7017             add_fixed_insn (NOP_INSN);
7018           mips_move_text_labels ();
7019         }
7020     }
7021   mips_no_prev_insn ();
7022 }
7023
7024 /* Start a (possibly nested) noreorder block.  */
7025
7026 static void
7027 start_noreorder (void)
7028 {
7029   if (mips_opts.noreorder == 0)
7030     {
7031       unsigned int i;
7032       int nops;
7033
7034       /* None of the instructions before the .set noreorder can be moved.  */
7035       for (i = 0; i < ARRAY_SIZE (history); i++)
7036         history[i].fixed_p = 1;
7037
7038       /* Insert any nops that might be needed between the .set noreorder
7039          block and the previous instructions.  We will later remove any
7040          nops that turn out not to be needed.  */
7041       nops = nops_for_insn (0, history, NULL);
7042       if (nops > 0)
7043         {
7044           if (mips_optimize != 0)
7045             {
7046               /* Record the frag which holds the nop instructions, so
7047                  that we can remove them if we don't need them.  */
7048               frag_grow (nops * NOP_INSN_SIZE);
7049               prev_nop_frag = frag_now;
7050               prev_nop_frag_holds = nops;
7051               prev_nop_frag_required = 0;
7052               prev_nop_frag_since = 0;
7053             }
7054
7055           for (; nops > 0; --nops)
7056             add_fixed_insn (NOP_INSN);
7057
7058           /* Move on to a new frag, so that it is safe to simply
7059              decrease the size of prev_nop_frag.  */
7060           frag_wane (frag_now);
7061           frag_new (0);
7062           mips_move_text_labels ();
7063         }
7064       mips_mark_labels ();
7065       mips_clear_insn_labels ();
7066     }
7067   mips_opts.noreorder++;
7068   mips_any_noreorder = 1;
7069 }
7070
7071 /* End a nested noreorder block.  */
7072
7073 static void
7074 end_noreorder (void)
7075 {
7076   mips_opts.noreorder--;
7077   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7078     {
7079       /* Commit to inserting prev_nop_frag_required nops and go back to
7080          handling nop insertion the .set reorder way.  */
7081       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7082                                 * NOP_INSN_SIZE);
7083       insert_into_history (prev_nop_frag_since,
7084                            prev_nop_frag_required, NOP_INSN);
7085       prev_nop_frag = NULL;
7086     }
7087 }
7088
7089 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7090    higher bits unset.  */
7091
7092 static void
7093 normalize_constant_expr (expressionS *ex)
7094 {
7095   if (ex->X_op == O_constant
7096       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7097     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7098                         - 0x80000000);
7099 }
7100
7101 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7102    all higher bits unset.  */
7103
7104 static void
7105 normalize_address_expr (expressionS *ex)
7106 {
7107   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7108         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7109       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7110     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7111                         - 0x80000000);
7112 }
7113
7114 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7115    Return true if the match was successful.
7116
7117    OPCODE_EXTRA is a value that should be ORed into the opcode
7118    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7119    there are more alternatives after OPCODE and SOFT_MATCH is
7120    as for mips_arg_info.  */
7121
7122 static bfd_boolean
7123 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7124             struct mips_operand_token *tokens, unsigned int opcode_extra,
7125             bfd_boolean lax_match, bfd_boolean complete_p)
7126 {
7127   const char *args;
7128   struct mips_arg_info arg;
7129   const struct mips_operand *operand;
7130   char c;
7131
7132   imm_expr.X_op = O_absent;
7133   offset_expr.X_op = O_absent;
7134   offset_reloc[0] = BFD_RELOC_UNUSED;
7135   offset_reloc[1] = BFD_RELOC_UNUSED;
7136   offset_reloc[2] = BFD_RELOC_UNUSED;
7137
7138   create_insn (insn, opcode);
7139   /* When no opcode suffix is specified, assume ".xyzw". */
7140   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7141     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7142   else
7143     insn->insn_opcode |= opcode_extra;
7144   memset (&arg, 0, sizeof (arg));
7145   arg.insn = insn;
7146   arg.token = tokens;
7147   arg.argnum = 1;
7148   arg.last_regno = ILLEGAL_REG;
7149   arg.dest_regno = ILLEGAL_REG;
7150   arg.lax_match = lax_match;
7151   for (args = opcode->args;; ++args)
7152     {
7153       if (arg.token->type == OT_END)
7154         {
7155           /* Handle unary instructions in which only one operand is given.
7156              The source is then the same as the destination.  */
7157           if (arg.opnum == 1 && *args == ',')
7158             {
7159               operand = (mips_opts.micromips
7160                          ? decode_micromips_operand (args + 1)
7161                          : decode_mips_operand (args + 1));
7162               if (operand && mips_optional_operand_p (operand))
7163                 {
7164                   arg.token = tokens;
7165                   arg.argnum = 1;
7166                   continue;
7167                 }
7168             }
7169
7170           /* Treat elided base registers as $0.  */
7171           if (strcmp (args, "(b)") == 0)
7172             args += 3;
7173
7174           if (args[0] == '+')
7175             switch (args[1])
7176               {
7177               case 'K':
7178               case 'N':
7179                 /* The register suffix is optional. */
7180                 args += 2;
7181                 break;
7182               }
7183
7184           /* Fail the match if there were too few operands.  */
7185           if (*args)
7186             return FALSE;
7187
7188           /* Successful match.  */
7189           if (!complete_p)
7190             return TRUE;
7191           clear_insn_error ();
7192           if (arg.dest_regno == arg.last_regno
7193               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7194             {
7195               if (arg.opnum == 2)
7196                 set_insn_error
7197                   (0, _("source and destination must be different"));
7198               else if (arg.last_regno == 31)
7199                 set_insn_error
7200                   (0, _("a destination register must be supplied"));
7201             }
7202           else if (arg.last_regno == 31
7203                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7204                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7205             set_insn_error (0, _("the source register must not be $31"));
7206           check_completed_insn (&arg);
7207           return TRUE;
7208         }
7209
7210       /* Fail the match if the line has too many operands.   */
7211       if (*args == 0)
7212         return FALSE;
7213
7214       /* Handle characters that need to match exactly.  */
7215       if (*args == '(' || *args == ')' || *args == ',')
7216         {
7217           if (match_char (&arg, *args))
7218             continue;
7219           return FALSE;
7220         }
7221       if (*args == '#')
7222         {
7223           ++args;
7224           if (arg.token->type == OT_DOUBLE_CHAR
7225               && arg.token->u.ch == *args)
7226             {
7227               ++arg.token;
7228               continue;
7229             }
7230           return FALSE;
7231         }
7232
7233       /* Handle special macro operands.  Work out the properties of
7234          other operands.  */
7235       arg.opnum += 1;
7236       switch (*args)
7237         {
7238         case '+':
7239           switch (args[1])
7240             {
7241             case 'i':
7242               *offset_reloc = BFD_RELOC_MIPS_JMP;
7243               break;
7244             }
7245           break;
7246
7247         case 'I':
7248           if (!match_const_int (&arg, &imm_expr.X_add_number))
7249             return FALSE;
7250           imm_expr.X_op = O_constant;
7251           if (HAVE_32BIT_GPRS)
7252             normalize_constant_expr (&imm_expr);
7253           continue;
7254
7255         case 'A':
7256           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7257             {
7258               /* Assume that the offset has been elided and that what
7259                  we saw was a base register.  The match will fail later
7260                  if that assumption turns out to be wrong.  */
7261               offset_expr.X_op = O_constant;
7262               offset_expr.X_add_number = 0;
7263             }
7264           else
7265             {
7266               if (!match_expression (&arg, &offset_expr, offset_reloc))
7267                 return FALSE;
7268               normalize_address_expr (&offset_expr);
7269             }
7270           continue;
7271
7272         case 'F':
7273           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7274                                      8, TRUE))
7275             return FALSE;
7276           continue;
7277
7278         case 'L':
7279           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7280                                      8, FALSE))
7281             return FALSE;
7282           continue;
7283
7284         case 'f':
7285           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7286                                      4, TRUE))
7287             return FALSE;
7288           continue;
7289
7290         case 'l':
7291           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7292                                      4, FALSE))
7293             return FALSE;
7294           continue;
7295
7296         case 'p':
7297           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7298           break;
7299
7300         case 'a':
7301           *offset_reloc = BFD_RELOC_MIPS_JMP;
7302           break;
7303
7304         case 'm':
7305           gas_assert (mips_opts.micromips);
7306           c = args[1];
7307           switch (c)
7308             {
7309             case 'D':
7310             case 'E':
7311               if (!forced_insn_length)
7312                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7313               else if (c == 'D')
7314                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7315               else
7316                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7317               break;
7318             }
7319           break;
7320         }
7321
7322       operand = (mips_opts.micromips
7323                  ? decode_micromips_operand (args)
7324                  : decode_mips_operand (args));
7325       if (!operand)
7326         abort ();
7327
7328       /* Skip prefixes.  */
7329       if (*args == '+' || *args == 'm')
7330         args++;
7331
7332       if (mips_optional_operand_p (operand)
7333           && args[1] == ','
7334           && (arg.token[0].type != OT_REG
7335               || arg.token[1].type == OT_END))
7336         {
7337           /* Assume that the register has been elided and is the
7338              same as the first operand.  */
7339           arg.token = tokens;
7340           arg.argnum = 1;
7341         }
7342
7343       if (!match_operand (&arg, operand))
7344         return FALSE;
7345     }
7346 }
7347
7348 /* Like match_insn, but for MIPS16.  */
7349
7350 static bfd_boolean
7351 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7352                    struct mips_operand_token *tokens)
7353 {
7354   const char *args;
7355   const struct mips_operand *operand;
7356   const struct mips_operand *ext_operand;
7357   struct mips_arg_info arg;
7358   int relax_char;
7359
7360   create_insn (insn, opcode);
7361   imm_expr.X_op = O_absent;
7362   offset_expr.X_op = O_absent;
7363   offset_reloc[0] = BFD_RELOC_UNUSED;
7364   offset_reloc[1] = BFD_RELOC_UNUSED;
7365   offset_reloc[2] = BFD_RELOC_UNUSED;
7366   relax_char = 0;
7367
7368   memset (&arg, 0, sizeof (arg));
7369   arg.insn = insn;
7370   arg.token = tokens;
7371   arg.argnum = 1;
7372   arg.last_regno = ILLEGAL_REG;
7373   arg.dest_regno = ILLEGAL_REG;
7374   relax_char = 0;
7375   for (args = opcode->args;; ++args)
7376     {
7377       int c;
7378
7379       if (arg.token->type == OT_END)
7380         {
7381           offsetT value;
7382
7383           /* Handle unary instructions in which only one operand is given.
7384              The source is then the same as the destination.  */
7385           if (arg.opnum == 1 && *args == ',')
7386             {
7387               operand = decode_mips16_operand (args[1], FALSE);
7388               if (operand && mips_optional_operand_p (operand))
7389                 {
7390                   arg.token = tokens;
7391                   arg.argnum = 1;
7392                   continue;
7393                 }
7394             }
7395
7396           /* Fail the match if there were too few operands.  */
7397           if (*args)
7398             return FALSE;
7399
7400           /* Successful match.  Stuff the immediate value in now, if
7401              we can.  */
7402           clear_insn_error ();
7403           if (opcode->pinfo == INSN_MACRO)
7404             {
7405               gas_assert (relax_char == 0 || relax_char == 'p');
7406               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
7407             }
7408           else if (relax_char
7409                    && offset_expr.X_op == O_constant
7410                    && calculate_reloc (*offset_reloc,
7411                                        offset_expr.X_add_number,
7412                                        &value))
7413             {
7414               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
7415                             forced_insn_length, &insn->insn_opcode);
7416               offset_expr.X_op = O_absent;
7417               *offset_reloc = BFD_RELOC_UNUSED;
7418             }
7419           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
7420             {
7421               if (forced_insn_length == 2)
7422                 set_insn_error (0, _("invalid unextended operand value"));
7423               forced_insn_length = 4;
7424               insn->insn_opcode |= MIPS16_EXTEND;
7425             }
7426           else if (relax_char)
7427             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
7428
7429           check_completed_insn (&arg);
7430           return TRUE;
7431         }
7432
7433       /* Fail the match if the line has too many operands.   */
7434       if (*args == 0)
7435         return FALSE;
7436
7437       /* Handle characters that need to match exactly.  */
7438       if (*args == '(' || *args == ')' || *args == ',')
7439         {
7440           if (match_char (&arg, *args))
7441             continue;
7442           return FALSE;
7443         }
7444
7445       arg.opnum += 1;
7446       c = *args;
7447       switch (c)
7448         {
7449         case 'p':
7450         case 'q':
7451         case 'A':
7452         case 'B':
7453         case 'E':
7454           relax_char = c;
7455           break;
7456
7457         case 'I':
7458           if (!match_const_int (&arg, &imm_expr.X_add_number))
7459             return FALSE;
7460           imm_expr.X_op = O_constant;
7461           if (HAVE_32BIT_GPRS)
7462             normalize_constant_expr (&imm_expr);
7463           continue;
7464
7465         case 'a':
7466         case 'i':
7467           *offset_reloc = BFD_RELOC_MIPS16_JMP;
7468           insn->insn_opcode <<= 16;
7469           break;
7470         }
7471
7472       operand = decode_mips16_operand (c, FALSE);
7473       if (!operand)
7474         abort ();
7475
7476       /* '6' is a special case.  It is used for BREAK and SDBBP,
7477          whose operands are only meaningful to the software that decodes
7478          them.  This means that there is no architectural reason why
7479          they cannot be prefixed by EXTEND, but in practice,
7480          exception handlers will only look at the instruction
7481          itself.  We therefore allow '6' to be extended when
7482          disassembling but not when assembling.  */
7483       if (operand->type != OP_PCREL && c != '6')
7484         {
7485           ext_operand = decode_mips16_operand (c, TRUE);
7486           if (operand != ext_operand)
7487             {
7488               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7489                 {
7490                   offset_expr.X_op = O_constant;
7491                   offset_expr.X_add_number = 0;
7492                   relax_char = c;
7493                   continue;
7494                 }
7495
7496               /* We need the OT_INTEGER check because some MIPS16
7497                  immediate variants are listed before the register ones.  */
7498               if (arg.token->type != OT_INTEGER
7499                   || !match_expression (&arg, &offset_expr, offset_reloc))
7500                 return FALSE;
7501
7502               /* '8' is used for SLTI(U) and has traditionally not
7503                  been allowed to take relocation operators.  */
7504               if (offset_reloc[0] != BFD_RELOC_UNUSED
7505                   && (ext_operand->size != 16 || c == '8'))
7506                 return FALSE;
7507
7508               relax_char = c;
7509               continue;
7510             }
7511         }
7512
7513       if (mips_optional_operand_p (operand)
7514           && args[1] == ','
7515           && (arg.token[0].type != OT_REG
7516               || arg.token[1].type == OT_END))
7517         {
7518           /* Assume that the register has been elided and is the
7519              same as the first operand.  */
7520           arg.token = tokens;
7521           arg.argnum = 1;
7522         }
7523
7524       if (!match_operand (&arg, operand))
7525         return FALSE;
7526     }
7527 }
7528
7529 /* Record that the current instruction is invalid for the current ISA.  */
7530
7531 static void
7532 match_invalid_for_isa (void)
7533 {
7534   set_insn_error_ss
7535     (0, _("opcode not supported on this processor: %s (%s)"),
7536      mips_cpu_info_from_arch (mips_opts.arch)->name,
7537      mips_cpu_info_from_isa (mips_opts.isa)->name);
7538 }
7539
7540 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
7541    Return true if a definite match or failure was found, storing any match
7542    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
7543    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
7544    tried and failed to match under normal conditions and now want to try a
7545    more relaxed match.  */
7546
7547 static bfd_boolean
7548 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7549              const struct mips_opcode *past, struct mips_operand_token *tokens,
7550              int opcode_extra, bfd_boolean lax_match)
7551 {
7552   const struct mips_opcode *opcode;
7553   const struct mips_opcode *invalid_delay_slot;
7554   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
7555
7556   /* Search for a match, ignoring alternatives that don't satisfy the
7557      current ISA or forced_length.  */
7558   invalid_delay_slot = 0;
7559   seen_valid_for_isa = FALSE;
7560   seen_valid_for_size = FALSE;
7561   opcode = first;
7562   do
7563     {
7564       gas_assert (strcmp (opcode->name, first->name) == 0);
7565       if (is_opcode_valid (opcode))
7566         {
7567           seen_valid_for_isa = TRUE;
7568           if (is_size_valid (opcode))
7569             {
7570               bfd_boolean delay_slot_ok;
7571
7572               seen_valid_for_size = TRUE;
7573               delay_slot_ok = is_delay_slot_valid (opcode);
7574               if (match_insn (insn, opcode, tokens, opcode_extra,
7575                               lax_match, delay_slot_ok))
7576                 {
7577                   if (!delay_slot_ok)
7578                     {
7579                       if (!invalid_delay_slot)
7580                         invalid_delay_slot = opcode;
7581                     }
7582                   else
7583                     return TRUE;
7584                 }
7585             }
7586         }
7587       ++opcode;
7588     }
7589   while (opcode < past && strcmp (opcode->name, first->name) == 0);
7590
7591   /* If the only matches we found had the wrong length for the delay slot,
7592      pick the first such match.  We'll issue an appropriate warning later.  */
7593   if (invalid_delay_slot)
7594     {
7595       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
7596                       lax_match, TRUE))
7597         return TRUE;
7598       abort ();
7599     }
7600
7601   /* Handle the case where we didn't try to match an instruction because
7602      all the alternatives were incompatible with the current ISA.  */
7603   if (!seen_valid_for_isa)
7604     {
7605       match_invalid_for_isa ();
7606       return TRUE;
7607     }
7608
7609   /* Handle the case where we didn't try to match an instruction because
7610      all the alternatives were of the wrong size.  */
7611   if (!seen_valid_for_size)
7612     {
7613       if (mips_opts.insn32)
7614         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
7615       else
7616         set_insn_error_i
7617           (0, _("unrecognized %d-bit version of microMIPS opcode"),
7618            8 * forced_insn_length);
7619       return TRUE;
7620     }
7621
7622   return FALSE;
7623 }
7624
7625 /* Like match_insns, but for MIPS16.  */
7626
7627 static bfd_boolean
7628 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
7629                     struct mips_operand_token *tokens)
7630 {
7631   const struct mips_opcode *opcode;
7632   bfd_boolean seen_valid_for_isa;
7633
7634   /* Search for a match, ignoring alternatives that don't satisfy the
7635      current ISA.  There are no separate entries for extended forms so
7636      we deal with forced_length later.  */
7637   seen_valid_for_isa = FALSE;
7638   opcode = first;
7639   do
7640     {
7641       gas_assert (strcmp (opcode->name, first->name) == 0);
7642       if (is_opcode_valid_16 (opcode))
7643         {
7644           seen_valid_for_isa = TRUE;
7645           if (match_mips16_insn (insn, opcode, tokens))
7646             return TRUE;
7647         }
7648       ++opcode;
7649     }
7650   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
7651          && strcmp (opcode->name, first->name) == 0);
7652
7653   /* Handle the case where we didn't try to match an instruction because
7654      all the alternatives were incompatible with the current ISA.  */
7655   if (!seen_valid_for_isa)
7656     {
7657       match_invalid_for_isa ();
7658       return TRUE;
7659     }
7660
7661   return FALSE;
7662 }
7663
7664 /* Set up global variables for the start of a new macro.  */
7665
7666 static void
7667 macro_start (void)
7668 {
7669   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
7670   memset (&mips_macro_warning.first_insn_sizes, 0,
7671           sizeof (mips_macro_warning.first_insn_sizes));
7672   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
7673   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
7674                                      && delayed_branch_p (&history[0]));
7675   switch (history[0].insn_mo->pinfo2
7676           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
7677     {
7678     case INSN2_BRANCH_DELAY_32BIT:
7679       mips_macro_warning.delay_slot_length = 4;
7680       break;
7681     case INSN2_BRANCH_DELAY_16BIT:
7682       mips_macro_warning.delay_slot_length = 2;
7683       break;
7684     default:
7685       mips_macro_warning.delay_slot_length = 0;
7686       break;
7687     }
7688   mips_macro_warning.first_frag = NULL;
7689 }
7690
7691 /* Given that a macro is longer than one instruction or of the wrong size,
7692    return the appropriate warning for it.  Return null if no warning is
7693    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
7694    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
7695    and RELAX_NOMACRO.  */
7696
7697 static const char *
7698 macro_warning (relax_substateT subtype)
7699 {
7700   if (subtype & RELAX_DELAY_SLOT)
7701     return _("macro instruction expanded into multiple instructions"
7702              " in a branch delay slot");
7703   else if (subtype & RELAX_NOMACRO)
7704     return _("macro instruction expanded into multiple instructions");
7705   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
7706                       | RELAX_DELAY_SLOT_SIZE_SECOND))
7707     return ((subtype & RELAX_DELAY_SLOT_16BIT)
7708             ? _("macro instruction expanded into a wrong size instruction"
7709                 " in a 16-bit branch delay slot")
7710             : _("macro instruction expanded into a wrong size instruction"
7711                 " in a 32-bit branch delay slot"));
7712   else
7713     return 0;
7714 }
7715
7716 /* Finish up a macro.  Emit warnings as appropriate.  */
7717
7718 static void
7719 macro_end (void)
7720 {
7721   /* Relaxation warning flags.  */
7722   relax_substateT subtype = 0;
7723
7724   /* Check delay slot size requirements.  */
7725   if (mips_macro_warning.delay_slot_length == 2)
7726     subtype |= RELAX_DELAY_SLOT_16BIT;
7727   if (mips_macro_warning.delay_slot_length != 0)
7728     {
7729       if (mips_macro_warning.delay_slot_length
7730           != mips_macro_warning.first_insn_sizes[0])
7731         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
7732       if (mips_macro_warning.delay_slot_length
7733           != mips_macro_warning.first_insn_sizes[1])
7734         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
7735     }
7736
7737   /* Check instruction count requirements.  */
7738   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
7739     {
7740       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
7741         subtype |= RELAX_SECOND_LONGER;
7742       if (mips_opts.warn_about_macros)
7743         subtype |= RELAX_NOMACRO;
7744       if (mips_macro_warning.delay_slot_p)
7745         subtype |= RELAX_DELAY_SLOT;
7746     }
7747
7748   /* If both alternatives fail to fill a delay slot correctly,
7749      emit the warning now.  */
7750   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
7751       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
7752     {
7753       relax_substateT s;
7754       const char *msg;
7755
7756       s = subtype & (RELAX_DELAY_SLOT_16BIT
7757                      | RELAX_DELAY_SLOT_SIZE_FIRST
7758                      | RELAX_DELAY_SLOT_SIZE_SECOND);
7759       msg = macro_warning (s);
7760       if (msg != NULL)
7761         as_warn ("%s", msg);
7762       subtype &= ~s;
7763     }
7764
7765   /* If both implementations are longer than 1 instruction, then emit the
7766      warning now.  */
7767   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
7768     {
7769       relax_substateT s;
7770       const char *msg;
7771
7772       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
7773       msg = macro_warning (s);
7774       if (msg != NULL)
7775         as_warn ("%s", msg);
7776       subtype &= ~s;
7777     }
7778
7779   /* If any flags still set, then one implementation might need a warning
7780      and the other either will need one of a different kind or none at all.
7781      Pass any remaining flags over to relaxation.  */
7782   if (mips_macro_warning.first_frag != NULL)
7783     mips_macro_warning.first_frag->fr_subtype |= subtype;
7784 }
7785
7786 /* Instruction operand formats used in macros that vary between
7787    standard MIPS and microMIPS code.  */
7788
7789 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
7790 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
7791 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
7792 static const char * const lui_fmt[2] = { "t,u", "s,u" };
7793 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
7794 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
7795 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
7796 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
7797
7798 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
7799 #define COP12_FMT (cop12_fmt[mips_opts.micromips])
7800 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
7801 #define LUI_FMT (lui_fmt[mips_opts.micromips])
7802 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
7803 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
7804 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
7805 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
7806
7807 /* Read a macro's relocation codes from *ARGS and store them in *R.
7808    The first argument in *ARGS will be either the code for a single
7809    relocation or -1 followed by the three codes that make up a
7810    composite relocation.  */
7811
7812 static void
7813 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
7814 {
7815   int i, next;
7816
7817   next = va_arg (*args, int);
7818   if (next >= 0)
7819     r[0] = (bfd_reloc_code_real_type) next;
7820   else
7821     {
7822       for (i = 0; i < 3; i++)
7823         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
7824       /* This function is only used for 16-bit relocation fields.
7825          To make the macro code simpler, treat an unrelocated value
7826          in the same way as BFD_RELOC_LO16.  */
7827       if (r[0] == BFD_RELOC_UNUSED)
7828         r[0] = BFD_RELOC_LO16;
7829     }
7830 }
7831
7832 /* Build an instruction created by a macro expansion.  This is passed
7833    a pointer to the count of instructions created so far, an
7834    expression, the name of the instruction to build, an operand format
7835    string, and corresponding arguments.  */
7836
7837 static void
7838 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
7839 {
7840   const struct mips_opcode *mo = NULL;
7841   bfd_reloc_code_real_type r[3];
7842   const struct mips_opcode *amo;
7843   const struct mips_operand *operand;
7844   struct hash_control *hash;
7845   struct mips_cl_insn insn;
7846   va_list args;
7847   unsigned int uval;
7848
7849   va_start (args, fmt);
7850
7851   if (mips_opts.mips16)
7852     {
7853       mips16_macro_build (ep, name, fmt, &args);
7854       va_end (args);
7855       return;
7856     }
7857
7858   r[0] = BFD_RELOC_UNUSED;
7859   r[1] = BFD_RELOC_UNUSED;
7860   r[2] = BFD_RELOC_UNUSED;
7861   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
7862   amo = (struct mips_opcode *) hash_find (hash, name);
7863   gas_assert (amo);
7864   gas_assert (strcmp (name, amo->name) == 0);
7865
7866   do
7867     {
7868       /* Search until we get a match for NAME.  It is assumed here that
7869          macros will never generate MDMX, MIPS-3D, or MT instructions.
7870          We try to match an instruction that fulfils the branch delay
7871          slot instruction length requirement (if any) of the previous
7872          instruction.  While doing this we record the first instruction
7873          seen that matches all the other conditions and use it anyway
7874          if the requirement cannot be met; we will issue an appropriate
7875          warning later on.  */
7876       if (strcmp (fmt, amo->args) == 0
7877           && amo->pinfo != INSN_MACRO
7878           && is_opcode_valid (amo)
7879           && is_size_valid (amo))
7880         {
7881           if (is_delay_slot_valid (amo))
7882             {
7883               mo = amo;
7884               break;
7885             }
7886           else if (!mo)
7887             mo = amo;
7888         }
7889
7890       ++amo;
7891       gas_assert (amo->name);
7892     }
7893   while (strcmp (name, amo->name) == 0);
7894
7895   gas_assert (mo);
7896   create_insn (&insn, mo);
7897   for (; *fmt; ++fmt)
7898     {
7899       switch (*fmt)
7900         {
7901         case ',':
7902         case '(':
7903         case ')':
7904         case 'z':
7905           break;
7906
7907         case 'i':
7908         case 'j':
7909           macro_read_relocs (&args, r);
7910           gas_assert (*r == BFD_RELOC_GPREL16
7911                       || *r == BFD_RELOC_MIPS_HIGHER
7912                       || *r == BFD_RELOC_HI16_S
7913                       || *r == BFD_RELOC_LO16
7914                       || *r == BFD_RELOC_MIPS_GOT_OFST);
7915           break;
7916
7917         case 'o':
7918           macro_read_relocs (&args, r);
7919           break;
7920
7921         case 'u':
7922           macro_read_relocs (&args, r);
7923           gas_assert (ep != NULL
7924                       && (ep->X_op == O_constant
7925                           || (ep->X_op == O_symbol
7926                               && (*r == BFD_RELOC_MIPS_HIGHEST
7927                                   || *r == BFD_RELOC_HI16_S
7928                                   || *r == BFD_RELOC_HI16
7929                                   || *r == BFD_RELOC_GPREL16
7930                                   || *r == BFD_RELOC_MIPS_GOT_HI16
7931                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
7932           break;
7933
7934         case 'p':
7935           gas_assert (ep != NULL);
7936
7937           /*
7938            * This allows macro() to pass an immediate expression for
7939            * creating short branches without creating a symbol.
7940            *
7941            * We don't allow branch relaxation for these branches, as
7942            * they should only appear in ".set nomacro" anyway.
7943            */
7944           if (ep->X_op == O_constant)
7945             {
7946               /* For microMIPS we always use relocations for branches.
7947                  So we should not resolve immediate values.  */
7948               gas_assert (!mips_opts.micromips);
7949
7950               if ((ep->X_add_number & 3) != 0)
7951                 as_bad (_("branch to misaligned address (0x%lx)"),
7952                         (unsigned long) ep->X_add_number);
7953               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
7954                 as_bad (_("branch address range overflow (0x%lx)"),
7955                         (unsigned long) ep->X_add_number);
7956               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
7957               ep = NULL;
7958             }
7959           else
7960             *r = BFD_RELOC_16_PCREL_S2;
7961           break;
7962
7963         case 'a':
7964           gas_assert (ep != NULL);
7965           *r = BFD_RELOC_MIPS_JMP;
7966           break;
7967
7968         default:
7969           operand = (mips_opts.micromips
7970                      ? decode_micromips_operand (fmt)
7971                      : decode_mips_operand (fmt));
7972           if (!operand)
7973             abort ();
7974
7975           uval = va_arg (args, int);
7976           if (operand->type == OP_CLO_CLZ_DEST)
7977             uval |= (uval << 5);
7978           insn_insert_operand (&insn, operand, uval);
7979
7980           if (*fmt == '+' || *fmt == 'm')
7981             ++fmt;
7982           break;
7983         }
7984     }
7985   va_end (args);
7986   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
7987
7988   append_insn (&insn, ep, r, TRUE);
7989 }
7990
7991 static void
7992 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
7993                     va_list *args)
7994 {
7995   struct mips_opcode *mo;
7996   struct mips_cl_insn insn;
7997   const struct mips_operand *operand;
7998   bfd_reloc_code_real_type r[3]
7999     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8000
8001   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8002   gas_assert (mo);
8003   gas_assert (strcmp (name, mo->name) == 0);
8004
8005   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8006     {
8007       ++mo;
8008       gas_assert (mo->name);
8009       gas_assert (strcmp (name, mo->name) == 0);
8010     }
8011
8012   create_insn (&insn, mo);
8013   for (; *fmt; ++fmt)
8014     {
8015       int c;
8016
8017       c = *fmt;
8018       switch (c)
8019         {
8020         case ',':
8021         case '(':
8022         case ')':
8023           break;
8024
8025         case '0':
8026         case 'S':
8027         case 'P':
8028         case 'R':
8029           break;
8030
8031         case '<':
8032         case '>':
8033         case '4':
8034         case '5':
8035         case 'H':
8036         case 'W':
8037         case 'D':
8038         case 'j':
8039         case '8':
8040         case 'V':
8041         case 'C':
8042         case 'U':
8043         case 'k':
8044         case 'K':
8045         case 'p':
8046         case 'q':
8047           {
8048             offsetT value;
8049
8050             gas_assert (ep != NULL);
8051
8052             if (ep->X_op != O_constant)
8053               *r = (int) BFD_RELOC_UNUSED + c;
8054             else if (calculate_reloc (*r, ep->X_add_number, &value))
8055               {
8056                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8057                 ep = NULL;
8058                 *r = BFD_RELOC_UNUSED;
8059               }
8060           }
8061           break;
8062
8063         default:
8064           operand = decode_mips16_operand (c, FALSE);
8065           if (!operand)
8066             abort ();
8067
8068           insn_insert_operand (&insn, operand, va_arg (*args, int));
8069           break;
8070         }
8071     }
8072
8073   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8074
8075   append_insn (&insn, ep, r, TRUE);
8076 }
8077
8078 /*
8079  * Generate a "jalr" instruction with a relocation hint to the called
8080  * function.  This occurs in NewABI PIC code.
8081  */
8082 static void
8083 macro_build_jalr (expressionS *ep, int cprestore)
8084 {
8085   static const bfd_reloc_code_real_type jalr_relocs[2]
8086     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8087   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8088   const char *jalr;
8089   char *f = NULL;
8090
8091   if (MIPS_JALR_HINT_P (ep))
8092     {
8093       frag_grow (8);
8094       f = frag_more (0);
8095     }
8096   if (mips_opts.micromips)
8097     {
8098       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8099               ? "jalr" : "jalrs");
8100       if (MIPS_JALR_HINT_P (ep)
8101           || mips_opts.insn32
8102           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8103         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8104       else
8105         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8106     }
8107   else
8108     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8109   if (MIPS_JALR_HINT_P (ep))
8110     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8111 }
8112
8113 /*
8114  * Generate a "lui" instruction.
8115  */
8116 static void
8117 macro_build_lui (expressionS *ep, int regnum)
8118 {
8119   gas_assert (! mips_opts.mips16);
8120
8121   if (ep->X_op != O_constant)
8122     {
8123       gas_assert (ep->X_op == O_symbol);
8124       /* _gp_disp is a special case, used from s_cpload.
8125          __gnu_local_gp is used if mips_no_shared.  */
8126       gas_assert (mips_pic == NO_PIC
8127               || (! HAVE_NEWABI
8128                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8129               || (! mips_in_shared
8130                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8131                              "__gnu_local_gp") == 0));
8132     }
8133
8134   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8135 }
8136
8137 /* Generate a sequence of instructions to do a load or store from a constant
8138    offset off of a base register (breg) into/from a target register (treg),
8139    using AT if necessary.  */
8140 static void
8141 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8142                               int treg, int breg, int dbl)
8143 {
8144   gas_assert (ep->X_op == O_constant);
8145
8146   /* Sign-extending 32-bit constants makes their handling easier.  */
8147   if (!dbl)
8148     normalize_constant_expr (ep);
8149
8150   /* Right now, this routine can only handle signed 32-bit constants.  */
8151   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8152     as_warn (_("operand overflow"));
8153
8154   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8155     {
8156       /* Signed 16-bit offset will fit in the op.  Easy!  */
8157       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8158     }
8159   else
8160     {
8161       /* 32-bit offset, need multiple instructions and AT, like:
8162            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8163            addu     $tempreg,$tempreg,$breg
8164            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8165          to handle the complete offset.  */
8166       macro_build_lui (ep, AT);
8167       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8168       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8169
8170       if (!mips_opts.at)
8171         as_bad (_("macro used $at after \".set noat\""));
8172     }
8173 }
8174
8175 /*                      set_at()
8176  * Generates code to set the $at register to true (one)
8177  * if reg is less than the immediate expression.
8178  */
8179 static void
8180 set_at (int reg, int unsignedp)
8181 {
8182   if (imm_expr.X_add_number >= -0x8000
8183       && imm_expr.X_add_number < 0x8000)
8184     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8185                  AT, reg, BFD_RELOC_LO16);
8186   else
8187     {
8188       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
8189       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8190     }
8191 }
8192
8193 /* Count the leading zeroes by performing a binary chop. This is a
8194    bulky bit of source, but performance is a LOT better for the
8195    majority of values than a simple loop to count the bits:
8196        for (lcnt = 0; (lcnt < 32); lcnt++)
8197          if ((v) & (1 << (31 - lcnt)))
8198            break;
8199   However it is not code size friendly, and the gain will drop a bit
8200   on certain cached systems.
8201 */
8202 #define COUNT_TOP_ZEROES(v)             \
8203   (((v) & ~0xffff) == 0                 \
8204    ? ((v) & ~0xff) == 0                 \
8205      ? ((v) & ~0xf) == 0                \
8206        ? ((v) & ~0x3) == 0              \
8207          ? ((v) & ~0x1) == 0            \
8208            ? !(v)                       \
8209              ? 32                       \
8210              : 31                       \
8211            : 30                         \
8212          : ((v) & ~0x7) == 0            \
8213            ? 29                         \
8214            : 28                         \
8215        : ((v) & ~0x3f) == 0             \
8216          ? ((v) & ~0x1f) == 0           \
8217            ? 27                         \
8218            : 26                         \
8219          : ((v) & ~0x7f) == 0           \
8220            ? 25                         \
8221            : 24                         \
8222      : ((v) & ~0xfff) == 0              \
8223        ? ((v) & ~0x3ff) == 0            \
8224          ? ((v) & ~0x1ff) == 0          \
8225            ? 23                         \
8226            : 22                         \
8227          : ((v) & ~0x7ff) == 0          \
8228            ? 21                         \
8229            : 20                         \
8230        : ((v) & ~0x3fff) == 0           \
8231          ? ((v) & ~0x1fff) == 0         \
8232            ? 19                         \
8233            : 18                         \
8234          : ((v) & ~0x7fff) == 0         \
8235            ? 17                         \
8236            : 16                         \
8237    : ((v) & ~0xffffff) == 0             \
8238      ? ((v) & ~0xfffff) == 0            \
8239        ? ((v) & ~0x3ffff) == 0          \
8240          ? ((v) & ~0x1ffff) == 0        \
8241            ? 15                         \
8242            : 14                         \
8243          : ((v) & ~0x7ffff) == 0        \
8244            ? 13                         \
8245            : 12                         \
8246        : ((v) & ~0x3fffff) == 0         \
8247          ? ((v) & ~0x1fffff) == 0       \
8248            ? 11                         \
8249            : 10                         \
8250          : ((v) & ~0x7fffff) == 0       \
8251            ? 9                          \
8252            : 8                          \
8253      : ((v) & ~0xfffffff) == 0          \
8254        ? ((v) & ~0x3ffffff) == 0        \
8255          ? ((v) & ~0x1ffffff) == 0      \
8256            ? 7                          \
8257            : 6                          \
8258          : ((v) & ~0x7ffffff) == 0      \
8259            ? 5                          \
8260            : 4                          \
8261        : ((v) & ~0x3fffffff) == 0       \
8262          ? ((v) & ~0x1fffffff) == 0     \
8263            ? 3                          \
8264            : 2                          \
8265          : ((v) & ~0x7fffffff) == 0     \
8266            ? 1                          \
8267            : 0)
8268
8269 /*                      load_register()
8270  *  This routine generates the least number of instructions necessary to load
8271  *  an absolute expression value into a register.
8272  */
8273 static void
8274 load_register (int reg, expressionS *ep, int dbl)
8275 {
8276   int freg;
8277   expressionS hi32, lo32;
8278
8279   if (ep->X_op != O_big)
8280     {
8281       gas_assert (ep->X_op == O_constant);
8282
8283       /* Sign-extending 32-bit constants makes their handling easier.  */
8284       if (!dbl)
8285         normalize_constant_expr (ep);
8286
8287       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8288         {
8289           /* We can handle 16 bit signed values with an addiu to
8290              $zero.  No need to ever use daddiu here, since $zero and
8291              the result are always correct in 32 bit mode.  */
8292           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8293           return;
8294         }
8295       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8296         {
8297           /* We can handle 16 bit unsigned values with an ori to
8298              $zero.  */
8299           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8300           return;
8301         }
8302       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8303         {
8304           /* 32 bit values require an lui.  */
8305           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8306           if ((ep->X_add_number & 0xffff) != 0)
8307             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8308           return;
8309         }
8310     }
8311
8312   /* The value is larger than 32 bits.  */
8313
8314   if (!dbl || HAVE_32BIT_GPRS)
8315     {
8316       char value[32];
8317
8318       sprintf_vma (value, ep->X_add_number);
8319       as_bad (_("number (0x%s) larger than 32 bits"), value);
8320       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8321       return;
8322     }
8323
8324   if (ep->X_op != O_big)
8325     {
8326       hi32 = *ep;
8327       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8328       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8329       hi32.X_add_number &= 0xffffffff;
8330       lo32 = *ep;
8331       lo32.X_add_number &= 0xffffffff;
8332     }
8333   else
8334     {
8335       gas_assert (ep->X_add_number > 2);
8336       if (ep->X_add_number == 3)
8337         generic_bignum[3] = 0;
8338       else if (ep->X_add_number > 4)
8339         as_bad (_("number larger than 64 bits"));
8340       lo32.X_op = O_constant;
8341       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8342       hi32.X_op = O_constant;
8343       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8344     }
8345
8346   if (hi32.X_add_number == 0)
8347     freg = 0;
8348   else
8349     {
8350       int shift, bit;
8351       unsigned long hi, lo;
8352
8353       if (hi32.X_add_number == (offsetT) 0xffffffff)
8354         {
8355           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8356             {
8357               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8358               return;
8359             }
8360           if (lo32.X_add_number & 0x80000000)
8361             {
8362               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8363               if (lo32.X_add_number & 0xffff)
8364                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8365               return;
8366             }
8367         }
8368
8369       /* Check for 16bit shifted constant.  We know that hi32 is
8370          non-zero, so start the mask on the first bit of the hi32
8371          value.  */
8372       shift = 17;
8373       do
8374         {
8375           unsigned long himask, lomask;
8376
8377           if (shift < 32)
8378             {
8379               himask = 0xffff >> (32 - shift);
8380               lomask = (0xffff << shift) & 0xffffffff;
8381             }
8382           else
8383             {
8384               himask = 0xffff << (shift - 32);
8385               lomask = 0;
8386             }
8387           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8388               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8389             {
8390               expressionS tmp;
8391
8392               tmp.X_op = O_constant;
8393               if (shift < 32)
8394                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8395                                     | (lo32.X_add_number >> shift));
8396               else
8397                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8398               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8399               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8400                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8401               return;
8402             }
8403           ++shift;
8404         }
8405       while (shift <= (64 - 16));
8406
8407       /* Find the bit number of the lowest one bit, and store the
8408          shifted value in hi/lo.  */
8409       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
8410       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
8411       if (lo != 0)
8412         {
8413           bit = 0;
8414           while ((lo & 1) == 0)
8415             {
8416               lo >>= 1;
8417               ++bit;
8418             }
8419           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
8420           hi >>= bit;
8421         }
8422       else
8423         {
8424           bit = 32;
8425           while ((hi & 1) == 0)
8426             {
8427               hi >>= 1;
8428               ++bit;
8429             }
8430           lo = hi;
8431           hi = 0;
8432         }
8433
8434       /* Optimize if the shifted value is a (power of 2) - 1.  */
8435       if ((hi == 0 && ((lo + 1) & lo) == 0)
8436           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
8437         {
8438           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
8439           if (shift != 0)
8440             {
8441               expressionS tmp;
8442
8443               /* This instruction will set the register to be all
8444                  ones.  */
8445               tmp.X_op = O_constant;
8446               tmp.X_add_number = (offsetT) -1;
8447               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8448               if (bit != 0)
8449                 {
8450                   bit += shift;
8451                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
8452                                reg, reg, (bit >= 32) ? bit - 32 : bit);
8453                 }
8454               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
8455                            reg, reg, (shift >= 32) ? shift - 32 : shift);
8456               return;
8457             }
8458         }
8459
8460       /* Sign extend hi32 before calling load_register, because we can
8461          generally get better code when we load a sign extended value.  */
8462       if ((hi32.X_add_number & 0x80000000) != 0)
8463         hi32.X_add_number |= ~(offsetT) 0xffffffff;
8464       load_register (reg, &hi32, 0);
8465       freg = reg;
8466     }
8467   if ((lo32.X_add_number & 0xffff0000) == 0)
8468     {
8469       if (freg != 0)
8470         {
8471           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
8472           freg = reg;
8473         }
8474     }
8475   else
8476     {
8477       expressionS mid16;
8478
8479       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
8480         {
8481           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8482           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
8483           return;
8484         }
8485
8486       if (freg != 0)
8487         {
8488           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
8489           freg = reg;
8490         }
8491       mid16 = lo32;
8492       mid16.X_add_number >>= 16;
8493       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8494       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8495       freg = reg;
8496     }
8497   if ((lo32.X_add_number & 0xffff) != 0)
8498     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
8499 }
8500
8501 static inline void
8502 load_delay_nop (void)
8503 {
8504   if (!gpr_interlocks)
8505     macro_build (NULL, "nop", "");
8506 }
8507
8508 /* Load an address into a register.  */
8509
8510 static void
8511 load_address (int reg, expressionS *ep, int *used_at)
8512 {
8513   if (ep->X_op != O_constant
8514       && ep->X_op != O_symbol)
8515     {
8516       as_bad (_("expression too complex"));
8517       ep->X_op = O_constant;
8518     }
8519
8520   if (ep->X_op == O_constant)
8521     {
8522       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
8523       return;
8524     }
8525
8526   if (mips_pic == NO_PIC)
8527     {
8528       /* If this is a reference to a GP relative symbol, we want
8529            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
8530          Otherwise we want
8531            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
8532            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8533          If we have an addend, we always use the latter form.
8534
8535          With 64bit address space and a usable $at we want
8536            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8537            lui          $at,<sym>               (BFD_RELOC_HI16_S)
8538            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8539            daddiu       $at,<sym>               (BFD_RELOC_LO16)
8540            dsll32       $reg,0
8541            daddu        $reg,$reg,$at
8542
8543          If $at is already in use, we use a path which is suboptimal
8544          on superscalar processors.
8545            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
8546            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
8547            dsll         $reg,16
8548            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
8549            dsll         $reg,16
8550            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
8551
8552          For GP relative symbols in 64bit address space we can use
8553          the same sequence as in 32bit address space.  */
8554       if (HAVE_64BIT_SYMBOLS)
8555         {
8556           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8557               && !nopic_need_relax (ep->X_add_symbol, 1))
8558             {
8559               relax_start (ep->X_add_symbol);
8560               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8561                            mips_gp_register, BFD_RELOC_GPREL16);
8562               relax_switch ();
8563             }
8564
8565           if (*used_at == 0 && mips_opts.at)
8566             {
8567               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8568               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
8569               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8570                            BFD_RELOC_MIPS_HIGHER);
8571               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
8572               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
8573               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
8574               *used_at = 1;
8575             }
8576           else
8577             {
8578               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
8579               macro_build (ep, "daddiu", "t,r,j", reg, reg,
8580                            BFD_RELOC_MIPS_HIGHER);
8581               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8582               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
8583               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
8584               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
8585             }
8586
8587           if (mips_relax.sequence)
8588             relax_end ();
8589         }
8590       else
8591         {
8592           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
8593               && !nopic_need_relax (ep->X_add_symbol, 1))
8594             {
8595               relax_start (ep->X_add_symbol);
8596               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
8597                            mips_gp_register, BFD_RELOC_GPREL16);
8598               relax_switch ();
8599             }
8600           macro_build_lui (ep, reg);
8601           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
8602                        reg, reg, BFD_RELOC_LO16);
8603           if (mips_relax.sequence)
8604             relax_end ();
8605         }
8606     }
8607   else if (!mips_big_got)
8608     {
8609       expressionS ex;
8610
8611       /* If this is a reference to an external symbol, we want
8612            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8613          Otherwise we want
8614            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8615            nop
8616            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8617          If there is a constant, it must be added in after.
8618
8619          If we have NewABI, we want
8620            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
8621          unless we're referencing a global symbol with a non-zero
8622          offset, in which case cst must be added separately.  */
8623       if (HAVE_NEWABI)
8624         {
8625           if (ep->X_add_number)
8626             {
8627               ex.X_add_number = ep->X_add_number;
8628               ep->X_add_number = 0;
8629               relax_start (ep->X_add_symbol);
8630               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8631                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8632               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8633                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8634               ex.X_op = O_constant;
8635               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8636                            reg, reg, BFD_RELOC_LO16);
8637               ep->X_add_number = ex.X_add_number;
8638               relax_switch ();
8639             }
8640           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8641                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
8642           if (mips_relax.sequence)
8643             relax_end ();
8644         }
8645       else
8646         {
8647           ex.X_add_number = ep->X_add_number;
8648           ep->X_add_number = 0;
8649           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8650                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8651           load_delay_nop ();
8652           relax_start (ep->X_add_symbol);
8653           relax_switch ();
8654           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8655                        BFD_RELOC_LO16);
8656           relax_end ();
8657
8658           if (ex.X_add_number != 0)
8659             {
8660               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8661                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8662               ex.X_op = O_constant;
8663               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
8664                            reg, reg, BFD_RELOC_LO16);
8665             }
8666         }
8667     }
8668   else if (mips_big_got)
8669     {
8670       expressionS ex;
8671
8672       /* This is the large GOT case.  If this is a reference to an
8673          external symbol, we want
8674            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
8675            addu         $reg,$reg,$gp
8676            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
8677
8678          Otherwise, for a reference to a local symbol in old ABI, we want
8679            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
8680            nop
8681            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
8682          If there is a constant, it must be added in after.
8683
8684          In the NewABI, for local symbols, with or without offsets, we want:
8685            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
8686            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
8687       */
8688       if (HAVE_NEWABI)
8689         {
8690           ex.X_add_number = ep->X_add_number;
8691           ep->X_add_number = 0;
8692           relax_start (ep->X_add_symbol);
8693           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8694           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8695                        reg, reg, mips_gp_register);
8696           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8697                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8698           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8699             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8700           else if (ex.X_add_number)
8701             {
8702               ex.X_op = O_constant;
8703               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8704                            BFD_RELOC_LO16);
8705             }
8706
8707           ep->X_add_number = ex.X_add_number;
8708           relax_switch ();
8709           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8710                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
8711           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8712                        BFD_RELOC_MIPS_GOT_OFST);
8713           relax_end ();
8714         }
8715       else
8716         {
8717           ex.X_add_number = ep->X_add_number;
8718           ep->X_add_number = 0;
8719           relax_start (ep->X_add_symbol);
8720           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
8721           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
8722                        reg, reg, mips_gp_register);
8723           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
8724                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
8725           relax_switch ();
8726           if (reg_needs_delay (mips_gp_register))
8727             {
8728               /* We need a nop before loading from $gp.  This special
8729                  check is required because the lui which starts the main
8730                  instruction stream does not refer to $gp, and so will not
8731                  insert the nop which may be required.  */
8732               macro_build (NULL, "nop", "");
8733             }
8734           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
8735                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
8736           load_delay_nop ();
8737           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8738                        BFD_RELOC_LO16);
8739           relax_end ();
8740
8741           if (ex.X_add_number != 0)
8742             {
8743               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
8744                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
8745               ex.X_op = O_constant;
8746               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
8747                            BFD_RELOC_LO16);
8748             }
8749         }
8750     }
8751   else
8752     abort ();
8753
8754   if (!mips_opts.at && *used_at == 1)
8755     as_bad (_("macro used $at after \".set noat\""));
8756 }
8757
8758 /* Move the contents of register SOURCE into register DEST.  */
8759
8760 static void
8761 move_register (int dest, int source)
8762 {
8763   /* Prefer to use a 16-bit microMIPS instruction unless the previous
8764      instruction specifically requires a 32-bit one.  */
8765   if (mips_opts.micromips
8766       && !mips_opts.insn32
8767       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8768     macro_build (NULL, "move", "mp,mj", dest, source);
8769   else
8770     macro_build (NULL, HAVE_32BIT_GPRS ? "addu" : "daddu", "d,v,t",
8771                  dest, source, 0);
8772 }
8773
8774 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
8775    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
8776    The two alternatives are:
8777
8778    Global symbol                Local sybmol
8779    -------------                ------------
8780    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
8781    ...                          ...
8782    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
8783
8784    load_got_offset emits the first instruction and add_got_offset
8785    emits the second for a 16-bit offset or add_got_offset_hilo emits
8786    a sequence to add a 32-bit offset using a scratch register.  */
8787
8788 static void
8789 load_got_offset (int dest, expressionS *local)
8790 {
8791   expressionS global;
8792
8793   global = *local;
8794   global.X_add_number = 0;
8795
8796   relax_start (local->X_add_symbol);
8797   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8798                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8799   relax_switch ();
8800   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
8801                BFD_RELOC_MIPS_GOT16, mips_gp_register);
8802   relax_end ();
8803 }
8804
8805 static void
8806 add_got_offset (int dest, expressionS *local)
8807 {
8808   expressionS global;
8809
8810   global.X_op = O_constant;
8811   global.X_op_symbol = NULL;
8812   global.X_add_symbol = NULL;
8813   global.X_add_number = local->X_add_number;
8814
8815   relax_start (local->X_add_symbol);
8816   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
8817                dest, dest, BFD_RELOC_LO16);
8818   relax_switch ();
8819   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
8820   relax_end ();
8821 }
8822
8823 static void
8824 add_got_offset_hilo (int dest, expressionS *local, int tmp)
8825 {
8826   expressionS global;
8827   int hold_mips_optimize;
8828
8829   global.X_op = O_constant;
8830   global.X_op_symbol = NULL;
8831   global.X_add_symbol = NULL;
8832   global.X_add_number = local->X_add_number;
8833
8834   relax_start (local->X_add_symbol);
8835   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
8836   relax_switch ();
8837   /* Set mips_optimize around the lui instruction to avoid
8838      inserting an unnecessary nop after the lw.  */
8839   hold_mips_optimize = mips_optimize;
8840   mips_optimize = 2;
8841   macro_build_lui (&global, tmp);
8842   mips_optimize = hold_mips_optimize;
8843   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
8844   relax_end ();
8845
8846   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
8847 }
8848
8849 /* Emit a sequence of instructions to emulate a branch likely operation.
8850    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
8851    is its complementing branch with the original condition negated.
8852    CALL is set if the original branch specified the link operation.
8853    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
8854
8855    Code like this is produced in the noreorder mode:
8856
8857         BRNEG   <args>, 1f
8858          nop
8859         b       <sym>
8860          delay slot (executed only if branch taken)
8861     1:
8862
8863    or, if CALL is set:
8864
8865         BRNEG   <args>, 1f
8866          nop
8867         bal     <sym>
8868          delay slot (executed only if branch taken)
8869     1:
8870
8871    In the reorder mode the delay slot would be filled with a nop anyway,
8872    so code produced is simply:
8873
8874         BR      <args>, <sym>
8875          nop
8876
8877    This function is used when producing code for the microMIPS ASE that
8878    does not implement branch likely instructions in hardware.  */
8879
8880 static void
8881 macro_build_branch_likely (const char *br, const char *brneg,
8882                            int call, expressionS *ep, const char *fmt,
8883                            unsigned int sreg, unsigned int treg)
8884 {
8885   int noreorder = mips_opts.noreorder;
8886   expressionS expr1;
8887
8888   gas_assert (mips_opts.micromips);
8889   start_noreorder ();
8890   if (noreorder)
8891     {
8892       micromips_label_expr (&expr1);
8893       macro_build (&expr1, brneg, fmt, sreg, treg);
8894       macro_build (NULL, "nop", "");
8895       macro_build (ep, call ? "bal" : "b", "p");
8896
8897       /* Set to true so that append_insn adds a label.  */
8898       emit_branch_likely_macro = TRUE;
8899     }
8900   else
8901     {
8902       macro_build (ep, br, fmt, sreg, treg);
8903       macro_build (NULL, "nop", "");
8904     }
8905   end_noreorder ();
8906 }
8907
8908 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
8909    the condition code tested.  EP specifies the branch target.  */
8910
8911 static void
8912 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
8913 {
8914   const int call = 0;
8915   const char *brneg;
8916   const char *br;
8917
8918   switch (type)
8919     {
8920     case M_BC1FL:
8921       br = "bc1f";
8922       brneg = "bc1t";
8923       break;
8924     case M_BC1TL:
8925       br = "bc1t";
8926       brneg = "bc1f";
8927       break;
8928     case M_BC2FL:
8929       br = "bc2f";
8930       brneg = "bc2t";
8931       break;
8932     case M_BC2TL:
8933       br = "bc2t";
8934       brneg = "bc2f";
8935       break;
8936     default:
8937       abort ();
8938     }
8939   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
8940 }
8941
8942 /* Emit a two-argument branch macro specified by TYPE, using SREG as
8943    the register tested.  EP specifies the branch target.  */
8944
8945 static void
8946 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
8947 {
8948   const char *brneg = NULL;
8949   const char *br;
8950   int call = 0;
8951
8952   switch (type)
8953     {
8954     case M_BGEZ:
8955       br = "bgez";
8956       break;
8957     case M_BGEZL:
8958       br = mips_opts.micromips ? "bgez" : "bgezl";
8959       brneg = "bltz";
8960       break;
8961     case M_BGEZALL:
8962       gas_assert (mips_opts.micromips);
8963       br = mips_opts.insn32 ? "bgezal" : "bgezals";
8964       brneg = "bltz";
8965       call = 1;
8966       break;
8967     case M_BGTZ:
8968       br = "bgtz";
8969       break;
8970     case M_BGTZL:
8971       br = mips_opts.micromips ? "bgtz" : "bgtzl";
8972       brneg = "blez";
8973       break;
8974     case M_BLEZ:
8975       br = "blez";
8976       break;
8977     case M_BLEZL:
8978       br = mips_opts.micromips ? "blez" : "blezl";
8979       brneg = "bgtz";
8980       break;
8981     case M_BLTZ:
8982       br = "bltz";
8983       break;
8984     case M_BLTZL:
8985       br = mips_opts.micromips ? "bltz" : "bltzl";
8986       brneg = "bgez";
8987       break;
8988     case M_BLTZALL:
8989       gas_assert (mips_opts.micromips);
8990       br = mips_opts.insn32 ? "bltzal" : "bltzals";
8991       brneg = "bgez";
8992       call = 1;
8993       break;
8994     default:
8995       abort ();
8996     }
8997   if (mips_opts.micromips && brneg)
8998     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
8999   else
9000     macro_build (ep, br, "s,p", sreg);
9001 }
9002
9003 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9004    TREG as the registers tested.  EP specifies the branch target.  */
9005
9006 static void
9007 macro_build_branch_rsrt (int type, expressionS *ep,
9008                          unsigned int sreg, unsigned int treg)
9009 {
9010   const char *brneg = NULL;
9011   const int call = 0;
9012   const char *br;
9013
9014   switch (type)
9015     {
9016     case M_BEQ:
9017     case M_BEQ_I:
9018       br = "beq";
9019       break;
9020     case M_BEQL:
9021     case M_BEQL_I:
9022       br = mips_opts.micromips ? "beq" : "beql";
9023       brneg = "bne";
9024       break;
9025     case M_BNE:
9026     case M_BNE_I:
9027       br = "bne";
9028       break;
9029     case M_BNEL:
9030     case M_BNEL_I:
9031       br = mips_opts.micromips ? "bne" : "bnel";
9032       brneg = "beq";
9033       break;
9034     default:
9035       abort ();
9036     }
9037   if (mips_opts.micromips && brneg)
9038     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9039   else
9040     macro_build (ep, br, "s,t,p", sreg, treg);
9041 }
9042
9043 /* Return the high part that should be loaded in order to make the low
9044    part of VALUE accessible using an offset of OFFBITS bits.  */
9045
9046 static offsetT
9047 offset_high_part (offsetT value, unsigned int offbits)
9048 {
9049   offsetT bias;
9050   addressT low_mask;
9051
9052   if (offbits == 0)
9053     return value;
9054   bias = 1 << (offbits - 1);
9055   low_mask = bias * 2 - 1;
9056   return (value + bias) & ~low_mask;
9057 }
9058
9059 /* Return true if the value stored in offset_expr and offset_reloc
9060    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9061    amount that the caller wants to add without inducing overflow
9062    and ALIGN is the known alignment of the value in bytes.  */
9063
9064 static bfd_boolean
9065 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9066 {
9067   if (offbits == 16)
9068     {
9069       /* Accept any relocation operator if overflow isn't a concern.  */
9070       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9071         return TRUE;
9072
9073       /* These relocations are guaranteed not to overflow in correct links.  */
9074       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9075           || gprel16_reloc_p (*offset_reloc))
9076         return TRUE;
9077     }
9078   if (offset_expr.X_op == O_constant
9079       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9080       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9081     return TRUE;
9082   return FALSE;
9083 }
9084
9085 /*
9086  *                      Build macros
9087  *   This routine implements the seemingly endless macro or synthesized
9088  * instructions and addressing modes in the mips assembly language. Many
9089  * of these macros are simple and are similar to each other. These could
9090  * probably be handled by some kind of table or grammar approach instead of
9091  * this verbose method. Others are not simple macros but are more like
9092  * optimizing code generation.
9093  *   One interesting optimization is when several store macros appear
9094  * consecutively that would load AT with the upper half of the same address.
9095  * The ensuing load upper instructions are ommited. This implies some kind
9096  * of global optimization. We currently only optimize within a single macro.
9097  *   For many of the load and store macros if the address is specified as a
9098  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9099  * first load register 'at' with zero and use it as the base register. The
9100  * mips assembler simply uses register $zero. Just one tiny optimization
9101  * we're missing.
9102  */
9103 static void
9104 macro (struct mips_cl_insn *ip, char *str)
9105 {
9106   const struct mips_operand_array *operands;
9107   unsigned int breg, i;
9108   unsigned int tempreg;
9109   int mask;
9110   int used_at = 0;
9111   expressionS label_expr;
9112   expressionS expr1;
9113   expressionS *ep;
9114   const char *s;
9115   const char *s2;
9116   const char *fmt;
9117   int likely = 0;
9118   int coproc = 0;
9119   int offbits = 16;
9120   int call = 0;
9121   int jals = 0;
9122   int dbl = 0;
9123   int imm = 0;
9124   int ust = 0;
9125   int lp = 0;
9126   bfd_boolean large_offset;
9127   int off;
9128   int hold_mips_optimize;
9129   unsigned int align;
9130   unsigned int op[MAX_OPERANDS];
9131
9132   gas_assert (! mips_opts.mips16);
9133
9134   operands = insn_operands (ip);
9135   for (i = 0; i < MAX_OPERANDS; i++)
9136     if (operands->operand[i])
9137       op[i] = insn_extract_operand (ip, operands->operand[i]);
9138     else
9139       op[i] = -1;
9140
9141   mask = ip->insn_mo->mask;
9142
9143   label_expr.X_op = O_constant;
9144   label_expr.X_op_symbol = NULL;
9145   label_expr.X_add_symbol = NULL;
9146   label_expr.X_add_number = 0;
9147
9148   expr1.X_op = O_constant;
9149   expr1.X_op_symbol = NULL;
9150   expr1.X_add_symbol = NULL;
9151   expr1.X_add_number = 1;
9152   align = 1;
9153
9154   switch (mask)
9155     {
9156     case M_DABS:
9157       dbl = 1;
9158     case M_ABS:
9159       /*    bgez    $a0,1f
9160             move    v0,$a0
9161             sub     v0,$zero,$a0
9162          1:
9163        */
9164
9165       start_noreorder ();
9166
9167       if (mips_opts.micromips)
9168         micromips_label_expr (&label_expr);
9169       else
9170         label_expr.X_add_number = 8;
9171       macro_build (&label_expr, "bgez", "s,p", op[1]);
9172       if (op[0] == op[1])
9173         macro_build (NULL, "nop", "");
9174       else
9175         move_register (op[0], op[1]);
9176       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9177       if (mips_opts.micromips)
9178         micromips_add_label ();
9179
9180       end_noreorder ();
9181       break;
9182
9183     case M_ADD_I:
9184       s = "addi";
9185       s2 = "add";
9186       goto do_addi;
9187     case M_ADDU_I:
9188       s = "addiu";
9189       s2 = "addu";
9190       goto do_addi;
9191     case M_DADD_I:
9192       dbl = 1;
9193       s = "daddi";
9194       s2 = "dadd";
9195       if (!mips_opts.micromips)
9196         goto do_addi;
9197       if (imm_expr.X_add_number >= -0x200
9198           && imm_expr.X_add_number < 0x200)
9199         {
9200           macro_build (NULL, s, "t,r,.", op[0], op[1],
9201                        (int) imm_expr.X_add_number);
9202           break;
9203         }
9204       goto do_addi_i;
9205     case M_DADDU_I:
9206       dbl = 1;
9207       s = "daddiu";
9208       s2 = "daddu";
9209     do_addi:
9210       if (imm_expr.X_add_number >= -0x8000
9211           && imm_expr.X_add_number < 0x8000)
9212         {
9213           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9214           break;
9215         }
9216     do_addi_i:
9217       used_at = 1;
9218       load_register (AT, &imm_expr, dbl);
9219       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9220       break;
9221
9222     case M_AND_I:
9223       s = "andi";
9224       s2 = "and";
9225       goto do_bit;
9226     case M_OR_I:
9227       s = "ori";
9228       s2 = "or";
9229       goto do_bit;
9230     case M_NOR_I:
9231       s = "";
9232       s2 = "nor";
9233       goto do_bit;
9234     case M_XOR_I:
9235       s = "xori";
9236       s2 = "xor";
9237     do_bit:
9238       if (imm_expr.X_add_number >= 0
9239           && imm_expr.X_add_number < 0x10000)
9240         {
9241           if (mask != M_NOR_I)
9242             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9243           else
9244             {
9245               macro_build (&imm_expr, "ori", "t,r,i",
9246                            op[0], op[1], BFD_RELOC_LO16);
9247               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9248             }
9249           break;
9250         }
9251
9252       used_at = 1;
9253       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
9254       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9255       break;
9256
9257     case M_BALIGN:
9258       switch (imm_expr.X_add_number)
9259         {
9260         case 0:
9261           macro_build (NULL, "nop", "");
9262           break;
9263         case 2:
9264           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9265           break;
9266         case 1:
9267         case 3:
9268           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9269                        (int) imm_expr.X_add_number);
9270           break;
9271         default:
9272           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9273                   (unsigned long) imm_expr.X_add_number);
9274           break;
9275         }
9276       break;
9277
9278     case M_BC1FL:
9279     case M_BC1TL:
9280     case M_BC2FL:
9281     case M_BC2TL:
9282       gas_assert (mips_opts.micromips);
9283       macro_build_branch_ccl (mask, &offset_expr,
9284                               EXTRACT_OPERAND (1, BCC, *ip));
9285       break;
9286
9287     case M_BEQ_I:
9288     case M_BEQL_I:
9289     case M_BNE_I:
9290     case M_BNEL_I:
9291       if (imm_expr.X_add_number == 0)
9292         op[1] = 0;
9293       else
9294         {
9295           op[1] = AT;
9296           used_at = 1;
9297           load_register (op[1], &imm_expr, HAVE_64BIT_GPRS);
9298         }
9299       /* Fall through.  */
9300     case M_BEQL:
9301     case M_BNEL:
9302       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9303       break;
9304
9305     case M_BGEL:
9306       likely = 1;
9307     case M_BGE:
9308       if (op[1] == 0)
9309         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9310       else if (op[0] == 0)
9311         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9312       else
9313         {
9314           used_at = 1;
9315           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9316           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9317                                    &offset_expr, AT, ZERO);
9318         }
9319       break;
9320
9321     case M_BGEZL:
9322     case M_BGEZALL:
9323     case M_BGTZL:
9324     case M_BLEZL:
9325     case M_BLTZL:
9326     case M_BLTZALL:
9327       macro_build_branch_rs (mask, &offset_expr, op[0]);
9328       break;
9329
9330     case M_BGTL_I:
9331       likely = 1;
9332     case M_BGT_I:
9333       /* Check for > max integer.  */
9334       if (imm_expr.X_add_number >= GPR_SMAX)
9335         {
9336         do_false:
9337           /* Result is always false.  */
9338           if (! likely)
9339             macro_build (NULL, "nop", "");
9340           else
9341             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9342           break;
9343         }
9344       ++imm_expr.X_add_number;
9345       /* FALLTHROUGH */
9346     case M_BGE_I:
9347     case M_BGEL_I:
9348       if (mask == M_BGEL_I)
9349         likely = 1;
9350       if (imm_expr.X_add_number == 0)
9351         {
9352           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9353                                  &offset_expr, op[0]);
9354           break;
9355         }
9356       if (imm_expr.X_add_number == 1)
9357         {
9358           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9359                                  &offset_expr, op[0]);
9360           break;
9361         }
9362       if (imm_expr.X_add_number <= GPR_SMIN)
9363         {
9364         do_true:
9365           /* result is always true */
9366           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9367           macro_build (&offset_expr, "b", "p");
9368           break;
9369         }
9370       used_at = 1;
9371       set_at (op[0], 0);
9372       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9373                                &offset_expr, AT, ZERO);
9374       break;
9375
9376     case M_BGEUL:
9377       likely = 1;
9378     case M_BGEU:
9379       if (op[1] == 0)
9380         goto do_true;
9381       else if (op[0] == 0)
9382         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9383                                  &offset_expr, ZERO, op[1]);
9384       else
9385         {
9386           used_at = 1;
9387           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9388           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9389                                    &offset_expr, AT, ZERO);
9390         }
9391       break;
9392
9393     case M_BGTUL_I:
9394       likely = 1;
9395     case M_BGTU_I:
9396       if (op[0] == 0
9397           || (HAVE_32BIT_GPRS
9398               && imm_expr.X_add_number == -1))
9399         goto do_false;
9400       ++imm_expr.X_add_number;
9401       /* FALLTHROUGH */
9402     case M_BGEU_I:
9403     case M_BGEUL_I:
9404       if (mask == M_BGEUL_I)
9405         likely = 1;
9406       if (imm_expr.X_add_number == 0)
9407         goto do_true;
9408       else if (imm_expr.X_add_number == 1)
9409         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9410                                  &offset_expr, op[0], ZERO);
9411       else
9412         {
9413           used_at = 1;
9414           set_at (op[0], 1);
9415           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9416                                    &offset_expr, AT, ZERO);
9417         }
9418       break;
9419
9420     case M_BGTL:
9421       likely = 1;
9422     case M_BGT:
9423       if (op[1] == 0)
9424         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
9425       else if (op[0] == 0)
9426         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
9427       else
9428         {
9429           used_at = 1;
9430           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9431           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9432                                    &offset_expr, AT, ZERO);
9433         }
9434       break;
9435
9436     case M_BGTUL:
9437       likely = 1;
9438     case M_BGTU:
9439       if (op[1] == 0)
9440         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9441                                  &offset_expr, op[0], ZERO);
9442       else if (op[0] == 0)
9443         goto do_false;
9444       else
9445         {
9446           used_at = 1;
9447           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9448           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9449                                    &offset_expr, AT, ZERO);
9450         }
9451       break;
9452
9453     case M_BLEL:
9454       likely = 1;
9455     case M_BLE:
9456       if (op[1] == 0)
9457         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9458       else if (op[0] == 0)
9459         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
9460       else
9461         {
9462           used_at = 1;
9463           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
9464           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9465                                    &offset_expr, AT, ZERO);
9466         }
9467       break;
9468
9469     case M_BLEL_I:
9470       likely = 1;
9471     case M_BLE_I:
9472       if (imm_expr.X_add_number >= GPR_SMAX)
9473         goto do_true;
9474       ++imm_expr.X_add_number;
9475       /* FALLTHROUGH */
9476     case M_BLT_I:
9477     case M_BLTL_I:
9478       if (mask == M_BLTL_I)
9479         likely = 1;
9480       if (imm_expr.X_add_number == 0)
9481         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9482       else if (imm_expr.X_add_number == 1)
9483         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
9484       else
9485         {
9486           used_at = 1;
9487           set_at (op[0], 0);
9488           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9489                                    &offset_expr, AT, ZERO);
9490         }
9491       break;
9492
9493     case M_BLEUL:
9494       likely = 1;
9495     case M_BLEU:
9496       if (op[1] == 0)
9497         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9498                                  &offset_expr, op[0], ZERO);
9499       else if (op[0] == 0)
9500         goto do_true;
9501       else
9502         {
9503           used_at = 1;
9504           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
9505           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9506                                    &offset_expr, AT, ZERO);
9507         }
9508       break;
9509
9510     case M_BLEUL_I:
9511       likely = 1;
9512     case M_BLEU_I:
9513       if (op[0] == 0
9514           || (HAVE_32BIT_GPRS
9515               && imm_expr.X_add_number == -1))
9516         goto do_true;
9517       ++imm_expr.X_add_number;
9518       /* FALLTHROUGH */
9519     case M_BLTU_I:
9520     case M_BLTUL_I:
9521       if (mask == M_BLTUL_I)
9522         likely = 1;
9523       if (imm_expr.X_add_number == 0)
9524         goto do_false;
9525       else if (imm_expr.X_add_number == 1)
9526         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9527                                  &offset_expr, op[0], ZERO);
9528       else
9529         {
9530           used_at = 1;
9531           set_at (op[0], 1);
9532           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9533                                    &offset_expr, AT, ZERO);
9534         }
9535       break;
9536
9537     case M_BLTL:
9538       likely = 1;
9539     case M_BLT:
9540       if (op[1] == 0)
9541         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
9542       else if (op[0] == 0)
9543         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
9544       else
9545         {
9546           used_at = 1;
9547           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9548           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9549                                    &offset_expr, AT, ZERO);
9550         }
9551       break;
9552
9553     case M_BLTUL:
9554       likely = 1;
9555     case M_BLTU:
9556       if (op[1] == 0)
9557         goto do_false;
9558       else if (op[0] == 0)
9559         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9560                                  &offset_expr, ZERO, op[1]);
9561       else
9562         {
9563           used_at = 1;
9564           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9565           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
9566                                    &offset_expr, AT, ZERO);
9567         }
9568       break;
9569
9570     case M_DDIV_3:
9571       dbl = 1;
9572     case M_DIV_3:
9573       s = "mflo";
9574       goto do_div3;
9575     case M_DREM_3:
9576       dbl = 1;
9577     case M_REM_3:
9578       s = "mfhi";
9579     do_div3:
9580       if (op[2] == 0)
9581         {
9582           as_warn (_("divide by zero"));
9583           if (mips_trap)
9584             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9585           else
9586             macro_build (NULL, "break", BRK_FMT, 7);
9587           break;
9588         }
9589
9590       start_noreorder ();
9591       if (mips_trap)
9592         {
9593           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9594           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9595         }
9596       else
9597         {
9598           if (mips_opts.micromips)
9599             micromips_label_expr (&label_expr);
9600           else
9601             label_expr.X_add_number = 8;
9602           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9603           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
9604           macro_build (NULL, "break", BRK_FMT, 7);
9605           if (mips_opts.micromips)
9606             micromips_add_label ();
9607         }
9608       expr1.X_add_number = -1;
9609       used_at = 1;
9610       load_register (AT, &expr1, dbl);
9611       if (mips_opts.micromips)
9612         micromips_label_expr (&label_expr);
9613       else
9614         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
9615       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
9616       if (dbl)
9617         {
9618           expr1.X_add_number = 1;
9619           load_register (AT, &expr1, dbl);
9620           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
9621         }
9622       else
9623         {
9624           expr1.X_add_number = 0x80000000;
9625           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
9626         }
9627       if (mips_trap)
9628         {
9629           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
9630           /* We want to close the noreorder block as soon as possible, so
9631              that later insns are available for delay slot filling.  */
9632           end_noreorder ();
9633         }
9634       else
9635         {
9636           if (mips_opts.micromips)
9637             micromips_label_expr (&label_expr);
9638           else
9639             label_expr.X_add_number = 8;
9640           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
9641           macro_build (NULL, "nop", "");
9642
9643           /* We want to close the noreorder block as soon as possible, so
9644              that later insns are available for delay slot filling.  */
9645           end_noreorder ();
9646
9647           macro_build (NULL, "break", BRK_FMT, 6);
9648         }
9649       if (mips_opts.micromips)
9650         micromips_add_label ();
9651       macro_build (NULL, s, MFHL_FMT, op[0]);
9652       break;
9653
9654     case M_DIV_3I:
9655       s = "div";
9656       s2 = "mflo";
9657       goto do_divi;
9658     case M_DIVU_3I:
9659       s = "divu";
9660       s2 = "mflo";
9661       goto do_divi;
9662     case M_REM_3I:
9663       s = "div";
9664       s2 = "mfhi";
9665       goto do_divi;
9666     case M_REMU_3I:
9667       s = "divu";
9668       s2 = "mfhi";
9669       goto do_divi;
9670     case M_DDIV_3I:
9671       dbl = 1;
9672       s = "ddiv";
9673       s2 = "mflo";
9674       goto do_divi;
9675     case M_DDIVU_3I:
9676       dbl = 1;
9677       s = "ddivu";
9678       s2 = "mflo";
9679       goto do_divi;
9680     case M_DREM_3I:
9681       dbl = 1;
9682       s = "ddiv";
9683       s2 = "mfhi";
9684       goto do_divi;
9685     case M_DREMU_3I:
9686       dbl = 1;
9687       s = "ddivu";
9688       s2 = "mfhi";
9689     do_divi:
9690       if (imm_expr.X_add_number == 0)
9691         {
9692           as_warn (_("divide by zero"));
9693           if (mips_trap)
9694             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
9695           else
9696             macro_build (NULL, "break", BRK_FMT, 7);
9697           break;
9698         }
9699       if (imm_expr.X_add_number == 1)
9700         {
9701           if (strcmp (s2, "mflo") == 0)
9702             move_register (op[0], op[1]);
9703           else
9704             move_register (op[0], ZERO);
9705           break;
9706         }
9707       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
9708         {
9709           if (strcmp (s2, "mflo") == 0)
9710             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
9711           else
9712             move_register (op[0], ZERO);
9713           break;
9714         }
9715
9716       used_at = 1;
9717       load_register (AT, &imm_expr, dbl);
9718       macro_build (NULL, s, "z,s,t", op[1], AT);
9719       macro_build (NULL, s2, MFHL_FMT, op[0]);
9720       break;
9721
9722     case M_DIVU_3:
9723       s = "divu";
9724       s2 = "mflo";
9725       goto do_divu3;
9726     case M_REMU_3:
9727       s = "divu";
9728       s2 = "mfhi";
9729       goto do_divu3;
9730     case M_DDIVU_3:
9731       s = "ddivu";
9732       s2 = "mflo";
9733       goto do_divu3;
9734     case M_DREMU_3:
9735       s = "ddivu";
9736       s2 = "mfhi";
9737     do_divu3:
9738       start_noreorder ();
9739       if (mips_trap)
9740         {
9741           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
9742           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9743           /* We want to close the noreorder block as soon as possible, so
9744              that later insns are available for delay slot filling.  */
9745           end_noreorder ();
9746         }
9747       else
9748         {
9749           if (mips_opts.micromips)
9750             micromips_label_expr (&label_expr);
9751           else
9752             label_expr.X_add_number = 8;
9753           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
9754           macro_build (NULL, s, "z,s,t", op[1], op[2]);
9755
9756           /* We want to close the noreorder block as soon as possible, so
9757              that later insns are available for delay slot filling.  */
9758           end_noreorder ();
9759           macro_build (NULL, "break", BRK_FMT, 7);
9760           if (mips_opts.micromips)
9761             micromips_add_label ();
9762         }
9763       macro_build (NULL, s2, MFHL_FMT, op[0]);
9764       break;
9765
9766     case M_DLCA_AB:
9767       dbl = 1;
9768     case M_LCA_AB:
9769       call = 1;
9770       goto do_la;
9771     case M_DLA_AB:
9772       dbl = 1;
9773     case M_LA_AB:
9774     do_la:
9775       /* Load the address of a symbol into a register.  If breg is not
9776          zero, we then add a base register to it.  */
9777
9778       breg = op[2];
9779       if (dbl && HAVE_32BIT_GPRS)
9780         as_warn (_("dla used to load 32-bit register"));
9781
9782       if (!dbl && HAVE_64BIT_OBJECTS)
9783         as_warn (_("la used to load 64-bit address"));
9784
9785       if (small_offset_p (0, align, 16))
9786         {
9787           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
9788                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
9789           break;
9790         }
9791
9792       if (mips_opts.at && (op[0] == breg))
9793         {
9794           tempreg = AT;
9795           used_at = 1;
9796         }
9797       else
9798         tempreg = op[0];
9799
9800       if (offset_expr.X_op != O_symbol
9801           && offset_expr.X_op != O_constant)
9802         {
9803           as_bad (_("expression too complex"));
9804           offset_expr.X_op = O_constant;
9805         }
9806
9807       if (offset_expr.X_op == O_constant)
9808         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
9809       else if (mips_pic == NO_PIC)
9810         {
9811           /* If this is a reference to a GP relative symbol, we want
9812                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
9813              Otherwise we want
9814                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
9815                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9816              If we have a constant, we need two instructions anyhow,
9817              so we may as well always use the latter form.
9818
9819              With 64bit address space and a usable $at we want
9820                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9821                lui      $at,<sym>               (BFD_RELOC_HI16_S)
9822                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9823                daddiu   $at,<sym>               (BFD_RELOC_LO16)
9824                dsll32   $tempreg,0
9825                daddu    $tempreg,$tempreg,$at
9826
9827              If $at is already in use, we use a path which is suboptimal
9828              on superscalar processors.
9829                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
9830                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
9831                dsll     $tempreg,16
9832                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
9833                dsll     $tempreg,16
9834                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
9835
9836              For GP relative symbols in 64bit address space we can use
9837              the same sequence as in 32bit address space.  */
9838           if (HAVE_64BIT_SYMBOLS)
9839             {
9840               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9841                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9842                 {
9843                   relax_start (offset_expr.X_add_symbol);
9844                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9845                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9846                   relax_switch ();
9847                 }
9848
9849               if (used_at == 0 && mips_opts.at)
9850                 {
9851                   macro_build (&offset_expr, "lui", LUI_FMT,
9852                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9853                   macro_build (&offset_expr, "lui", LUI_FMT,
9854                                AT, BFD_RELOC_HI16_S);
9855                   macro_build (&offset_expr, "daddiu", "t,r,j",
9856                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9857                   macro_build (&offset_expr, "daddiu", "t,r,j",
9858                                AT, AT, BFD_RELOC_LO16);
9859                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
9860                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
9861                   used_at = 1;
9862                 }
9863               else
9864                 {
9865                   macro_build (&offset_expr, "lui", LUI_FMT,
9866                                tempreg, BFD_RELOC_MIPS_HIGHEST);
9867                   macro_build (&offset_expr, "daddiu", "t,r,j",
9868                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
9869                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9870                   macro_build (&offset_expr, "daddiu", "t,r,j",
9871                                tempreg, tempreg, BFD_RELOC_HI16_S);
9872                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
9873                   macro_build (&offset_expr, "daddiu", "t,r,j",
9874                                tempreg, tempreg, BFD_RELOC_LO16);
9875                 }
9876
9877               if (mips_relax.sequence)
9878                 relax_end ();
9879             }
9880           else
9881             {
9882               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
9883                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
9884                 {
9885                   relax_start (offset_expr.X_add_symbol);
9886                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9887                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
9888                   relax_switch ();
9889                 }
9890               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
9891                 as_bad (_("offset too large"));
9892               macro_build_lui (&offset_expr, tempreg);
9893               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9894                            tempreg, tempreg, BFD_RELOC_LO16);
9895               if (mips_relax.sequence)
9896                 relax_end ();
9897             }
9898         }
9899       else if (!mips_big_got && !HAVE_NEWABI)
9900         {
9901           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
9902
9903           /* If this is a reference to an external symbol, and there
9904              is no constant, we want
9905                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9906              or for lca or if tempreg is PIC_CALL_REG
9907                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
9908              For a local symbol, we want
9909                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9910                nop
9911                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
9912
9913              If we have a small constant, and this is a reference to
9914              an external symbol, we want
9915                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9916                nop
9917                addiu    $tempreg,$tempreg,<constant>
9918              For a local symbol, we want the same instruction
9919              sequence, but we output a BFD_RELOC_LO16 reloc on the
9920              addiu instruction.
9921
9922              If we have a large constant, and this is a reference to
9923              an external symbol, we want
9924                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
9925                lui      $at,<hiconstant>
9926                addiu    $at,$at,<loconstant>
9927                addu     $tempreg,$tempreg,$at
9928              For a local symbol, we want the same instruction
9929              sequence, but we output a BFD_RELOC_LO16 reloc on the
9930              addiu instruction.
9931            */
9932
9933           if (offset_expr.X_add_number == 0)
9934             {
9935               if (mips_pic == SVR4_PIC
9936                   && breg == 0
9937                   && (call || tempreg == PIC_CALL_REG))
9938                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
9939
9940               relax_start (offset_expr.X_add_symbol);
9941               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
9942                            lw_reloc_type, mips_gp_register);
9943               if (breg != 0)
9944                 {
9945                   /* We're going to put in an addu instruction using
9946                      tempreg, so we may as well insert the nop right
9947                      now.  */
9948                   load_delay_nop ();
9949                 }
9950               relax_switch ();
9951               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
9952                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
9953               load_delay_nop ();
9954               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
9955                            tempreg, tempreg, BFD_RELOC_LO16);
9956               relax_end ();
9957               /* FIXME: If breg == 0, and the next instruction uses
9958                  $tempreg, then if this variant case is used an extra
9959                  nop will be generated.  */
9960             }
9961           else if (offset_expr.X_add_number >= -0x8000
9962                    && offset_expr.X_add_number < 0x8000)
9963             {
9964               load_got_offset (tempreg, &offset_expr);
9965               load_delay_nop ();
9966               add_got_offset (tempreg, &offset_expr);
9967             }
9968           else
9969             {
9970               expr1.X_add_number = offset_expr.X_add_number;
9971               offset_expr.X_add_number =
9972                 SEXT_16BIT (offset_expr.X_add_number);
9973               load_got_offset (tempreg, &offset_expr);
9974               offset_expr.X_add_number = expr1.X_add_number;
9975               /* If we are going to add in a base register, and the
9976                  target register and the base register are the same,
9977                  then we are using AT as a temporary register.  Since
9978                  we want to load the constant into AT, we add our
9979                  current AT (from the global offset table) and the
9980                  register into the register now, and pretend we were
9981                  not using a base register.  */
9982               if (breg == op[0])
9983                 {
9984                   load_delay_nop ();
9985                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9986                                op[0], AT, breg);
9987                   breg = 0;
9988                   tempreg = op[0];
9989                 }
9990               add_got_offset_hilo (tempreg, &offset_expr, AT);
9991               used_at = 1;
9992             }
9993         }
9994       else if (!mips_big_got && HAVE_NEWABI)
9995         {
9996           int add_breg_early = 0;
9997
9998           /* If this is a reference to an external, and there is no
9999              constant, or local symbol (*), with or without a
10000              constant, we want
10001                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10002              or for lca or if tempreg is PIC_CALL_REG
10003                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10004
10005              If we have a small constant, and this is a reference to
10006              an external symbol, we want
10007                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10008                addiu    $tempreg,$tempreg,<constant>
10009
10010              If we have a large constant, and this is a reference to
10011              an external symbol, we want
10012                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10013                lui      $at,<hiconstant>
10014                addiu    $at,$at,<loconstant>
10015                addu     $tempreg,$tempreg,$at
10016
10017              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10018              local symbols, even though it introduces an additional
10019              instruction.  */
10020
10021           if (offset_expr.X_add_number)
10022             {
10023               expr1.X_add_number = offset_expr.X_add_number;
10024               offset_expr.X_add_number = 0;
10025
10026               relax_start (offset_expr.X_add_symbol);
10027               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10028                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10029
10030               if (expr1.X_add_number >= -0x8000
10031                   && expr1.X_add_number < 0x8000)
10032                 {
10033                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10034                                tempreg, tempreg, BFD_RELOC_LO16);
10035                 }
10036               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10037                 {
10038                   unsigned int dreg;
10039
10040                   /* If we are going to add in a base register, and the
10041                      target register and the base register are the same,
10042                      then we are using AT as a temporary register.  Since
10043                      we want to load the constant into AT, we add our
10044                      current AT (from the global offset table) and the
10045                      register into the register now, and pretend we were
10046                      not using a base register.  */
10047                   if (breg != op[0])
10048                     dreg = tempreg;
10049                   else
10050                     {
10051                       gas_assert (tempreg == AT);
10052                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10053                                    op[0], AT, breg);
10054                       dreg = op[0];
10055                       add_breg_early = 1;
10056                     }
10057
10058                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10059                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10060                                dreg, dreg, AT);
10061
10062                   used_at = 1;
10063                 }
10064               else
10065                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10066
10067               relax_switch ();
10068               offset_expr.X_add_number = expr1.X_add_number;
10069
10070               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10071                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10072               if (add_breg_early)
10073                 {
10074                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10075                                op[0], tempreg, breg);
10076                   breg = 0;
10077                   tempreg = op[0];
10078                 }
10079               relax_end ();
10080             }
10081           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10082             {
10083               relax_start (offset_expr.X_add_symbol);
10084               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10085                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10086               relax_switch ();
10087               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10088                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10089               relax_end ();
10090             }
10091           else
10092             {
10093               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10094                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10095             }
10096         }
10097       else if (mips_big_got && !HAVE_NEWABI)
10098         {
10099           int gpdelay;
10100           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10101           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10102           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10103
10104           /* This is the large GOT case.  If this is a reference to an
10105              external symbol, and there is no constant, we want
10106                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10107                addu     $tempreg,$tempreg,$gp
10108                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10109              or for lca or if tempreg is PIC_CALL_REG
10110                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10111                addu     $tempreg,$tempreg,$gp
10112                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10113              For a local symbol, we want
10114                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10115                nop
10116                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10117
10118              If we have a small constant, and this is a reference to
10119              an external symbol, we want
10120                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10121                addu     $tempreg,$tempreg,$gp
10122                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10123                nop
10124                addiu    $tempreg,$tempreg,<constant>
10125              For a local symbol, we want
10126                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10127                nop
10128                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10129
10130              If we have a large constant, and this is a reference to
10131              an external symbol, we want
10132                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10133                addu     $tempreg,$tempreg,$gp
10134                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10135                lui      $at,<hiconstant>
10136                addiu    $at,$at,<loconstant>
10137                addu     $tempreg,$tempreg,$at
10138              For a local symbol, we want
10139                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10140                lui      $at,<hiconstant>
10141                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10142                addu     $tempreg,$tempreg,$at
10143           */
10144
10145           expr1.X_add_number = offset_expr.X_add_number;
10146           offset_expr.X_add_number = 0;
10147           relax_start (offset_expr.X_add_symbol);
10148           gpdelay = reg_needs_delay (mips_gp_register);
10149           if (expr1.X_add_number == 0 && breg == 0
10150               && (call || tempreg == PIC_CALL_REG))
10151             {
10152               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10153               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10154             }
10155           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10156           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10157                        tempreg, tempreg, mips_gp_register);
10158           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10159                        tempreg, lw_reloc_type, tempreg);
10160           if (expr1.X_add_number == 0)
10161             {
10162               if (breg != 0)
10163                 {
10164                   /* We're going to put in an addu instruction using
10165                      tempreg, so we may as well insert the nop right
10166                      now.  */
10167                   load_delay_nop ();
10168                 }
10169             }
10170           else if (expr1.X_add_number >= -0x8000
10171                    && expr1.X_add_number < 0x8000)
10172             {
10173               load_delay_nop ();
10174               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10175                            tempreg, tempreg, BFD_RELOC_LO16);
10176             }
10177           else
10178             {
10179               unsigned int dreg;
10180
10181               /* If we are going to add in a base register, and the
10182                  target register and the base register are the same,
10183                  then we are using AT as a temporary register.  Since
10184                  we want to load the constant into AT, we add our
10185                  current AT (from the global offset table) and the
10186                  register into the register now, and pretend we were
10187                  not using a base register.  */
10188               if (breg != op[0])
10189                 dreg = tempreg;
10190               else
10191                 {
10192                   gas_assert (tempreg == AT);
10193                   load_delay_nop ();
10194                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10195                                op[0], AT, breg);
10196                   dreg = op[0];
10197                 }
10198
10199               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10200               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10201
10202               used_at = 1;
10203             }
10204           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10205           relax_switch ();
10206
10207           if (gpdelay)
10208             {
10209               /* This is needed because this instruction uses $gp, but
10210                  the first instruction on the main stream does not.  */
10211               macro_build (NULL, "nop", "");
10212             }
10213
10214           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10215                        local_reloc_type, mips_gp_register);
10216           if (expr1.X_add_number >= -0x8000
10217               && expr1.X_add_number < 0x8000)
10218             {
10219               load_delay_nop ();
10220               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10221                            tempreg, tempreg, BFD_RELOC_LO16);
10222               /* FIXME: If add_number is 0, and there was no base
10223                  register, the external symbol case ended with a load,
10224                  so if the symbol turns out to not be external, and
10225                  the next instruction uses tempreg, an unnecessary nop
10226                  will be inserted.  */
10227             }
10228           else
10229             {
10230               if (breg == op[0])
10231                 {
10232                   /* We must add in the base register now, as in the
10233                      external symbol case.  */
10234                   gas_assert (tempreg == AT);
10235                   load_delay_nop ();
10236                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10237                                op[0], AT, breg);
10238                   tempreg = op[0];
10239                   /* We set breg to 0 because we have arranged to add
10240                      it in in both cases.  */
10241                   breg = 0;
10242                 }
10243
10244               macro_build_lui (&expr1, AT);
10245               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10246                            AT, AT, BFD_RELOC_LO16);
10247               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10248                            tempreg, tempreg, AT);
10249               used_at = 1;
10250             }
10251           relax_end ();
10252         }
10253       else if (mips_big_got && HAVE_NEWABI)
10254         {
10255           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10256           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10257           int add_breg_early = 0;
10258
10259           /* This is the large GOT case.  If this is a reference to an
10260              external symbol, and there is no constant, we want
10261                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10262                add      $tempreg,$tempreg,$gp
10263                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10264              or for lca or if tempreg is PIC_CALL_REG
10265                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10266                add      $tempreg,$tempreg,$gp
10267                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10268
10269              If we have a small constant, and this is a reference to
10270              an external symbol, we want
10271                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10272                add      $tempreg,$tempreg,$gp
10273                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10274                addi     $tempreg,$tempreg,<constant>
10275
10276              If we have a large constant, and this is a reference to
10277              an external symbol, we want
10278                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10279                addu     $tempreg,$tempreg,$gp
10280                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10281                lui      $at,<hiconstant>
10282                addi     $at,$at,<loconstant>
10283                add      $tempreg,$tempreg,$at
10284
10285              If we have NewABI, and we know it's a local symbol, we want
10286                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10287                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10288              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10289
10290           relax_start (offset_expr.X_add_symbol);
10291
10292           expr1.X_add_number = offset_expr.X_add_number;
10293           offset_expr.X_add_number = 0;
10294
10295           if (expr1.X_add_number == 0 && breg == 0
10296               && (call || tempreg == PIC_CALL_REG))
10297             {
10298               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10299               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10300             }
10301           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10302           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10303                        tempreg, tempreg, mips_gp_register);
10304           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10305                        tempreg, lw_reloc_type, tempreg);
10306
10307           if (expr1.X_add_number == 0)
10308             ;
10309           else if (expr1.X_add_number >= -0x8000
10310                    && expr1.X_add_number < 0x8000)
10311             {
10312               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10313                            tempreg, tempreg, BFD_RELOC_LO16);
10314             }
10315           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10316             {
10317               unsigned int dreg;
10318
10319               /* If we are going to add in a base register, and the
10320                  target register and the base register are the same,
10321                  then we are using AT as a temporary register.  Since
10322                  we want to load the constant into AT, we add our
10323                  current AT (from the global offset table) and the
10324                  register into the register now, and pretend we were
10325                  not using a base register.  */
10326               if (breg != op[0])
10327                 dreg = tempreg;
10328               else
10329                 {
10330                   gas_assert (tempreg == AT);
10331                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10332                                op[0], AT, breg);
10333                   dreg = op[0];
10334                   add_breg_early = 1;
10335                 }
10336
10337               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10338               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10339
10340               used_at = 1;
10341             }
10342           else
10343             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10344
10345           relax_switch ();
10346           offset_expr.X_add_number = expr1.X_add_number;
10347           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10348                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10349           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10350                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10351           if (add_breg_early)
10352             {
10353               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10354                            op[0], tempreg, breg);
10355               breg = 0;
10356               tempreg = op[0];
10357             }
10358           relax_end ();
10359         }
10360       else
10361         abort ();
10362
10363       if (breg != 0)
10364         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10365       break;
10366
10367     case M_MSGSND:
10368       gas_assert (!mips_opts.micromips);
10369       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10370       break;
10371
10372     case M_MSGLD:
10373       gas_assert (!mips_opts.micromips);
10374       macro_build (NULL, "c2", "C", 0x02);
10375       break;
10376
10377     case M_MSGLD_T:
10378       gas_assert (!mips_opts.micromips);
10379       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10380       break;
10381
10382     case M_MSGWAIT:
10383       gas_assert (!mips_opts.micromips);
10384       macro_build (NULL, "c2", "C", 3);
10385       break;
10386
10387     case M_MSGWAIT_T:
10388       gas_assert (!mips_opts.micromips);
10389       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10390       break;
10391
10392     case M_J_A:
10393       /* The j instruction may not be used in PIC code, since it
10394          requires an absolute address.  We convert it to a b
10395          instruction.  */
10396       if (mips_pic == NO_PIC)
10397         macro_build (&offset_expr, "j", "a");
10398       else
10399         macro_build (&offset_expr, "b", "p");
10400       break;
10401
10402       /* The jal instructions must be handled as macros because when
10403          generating PIC code they expand to multi-instruction
10404          sequences.  Normally they are simple instructions.  */
10405     case M_JALS_1:
10406       op[1] = op[0];
10407       op[0] = RA;
10408       /* Fall through.  */
10409     case M_JALS_2:
10410       gas_assert (mips_opts.micromips);
10411       if (mips_opts.insn32)
10412         {
10413           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10414           break;
10415         }
10416       jals = 1;
10417       goto jal;
10418     case M_JAL_1:
10419       op[1] = op[0];
10420       op[0] = RA;
10421       /* Fall through.  */
10422     case M_JAL_2:
10423     jal:
10424       if (mips_pic == NO_PIC)
10425         {
10426           s = jals ? "jalrs" : "jalr";
10427           if (mips_opts.micromips
10428               && !mips_opts.insn32
10429               && op[0] == RA
10430               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10431             macro_build (NULL, s, "mj", op[1]);
10432           else
10433             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10434         }
10435       else
10436         {
10437           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
10438                            && mips_cprestore_offset >= 0);
10439
10440           if (op[1] != PIC_CALL_REG)
10441             as_warn (_("MIPS PIC call to register other than $25"));
10442
10443           s = ((mips_opts.micromips
10444                 && !mips_opts.insn32
10445                 && (!mips_opts.noreorder || cprestore))
10446                ? "jalrs" : "jalr");
10447           if (mips_opts.micromips
10448               && !mips_opts.insn32
10449               && op[0] == RA
10450               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
10451             macro_build (NULL, s, "mj", op[1]);
10452           else
10453             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
10454           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
10455             {
10456               if (mips_cprestore_offset < 0)
10457                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10458               else
10459                 {
10460                   if (!mips_frame_reg_valid)
10461                     {
10462                       as_warn (_("no .frame pseudo-op used in PIC code"));
10463                       /* Quiet this warning.  */
10464                       mips_frame_reg_valid = 1;
10465                     }
10466                   if (!mips_cprestore_valid)
10467                     {
10468                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10469                       /* Quiet this warning.  */
10470                       mips_cprestore_valid = 1;
10471                     }
10472                   if (mips_opts.noreorder)
10473                     macro_build (NULL, "nop", "");
10474                   expr1.X_add_number = mips_cprestore_offset;
10475                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10476                                                 mips_gp_register,
10477                                                 mips_frame_reg,
10478                                                 HAVE_64BIT_ADDRESSES);
10479                 }
10480             }
10481         }
10482
10483       break;
10484
10485     case M_JALS_A:
10486       gas_assert (mips_opts.micromips);
10487       if (mips_opts.insn32)
10488         {
10489           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
10490           break;
10491         }
10492       jals = 1;
10493       /* Fall through.  */
10494     case M_JAL_A:
10495       if (mips_pic == NO_PIC)
10496         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
10497       else if (mips_pic == SVR4_PIC)
10498         {
10499           /* If this is a reference to an external symbol, and we are
10500              using a small GOT, we want
10501                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
10502                nop
10503                jalr     $ra,$25
10504                nop
10505                lw       $gp,cprestore($sp)
10506              The cprestore value is set using the .cprestore
10507              pseudo-op.  If we are using a big GOT, we want
10508                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
10509                addu     $25,$25,$gp
10510                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
10511                nop
10512                jalr     $ra,$25
10513                nop
10514                lw       $gp,cprestore($sp)
10515              If the symbol is not external, we want
10516                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
10517                nop
10518                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
10519                jalr     $ra,$25
10520                nop
10521                lw $gp,cprestore($sp)
10522
10523              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
10524              sequences above, minus nops, unless the symbol is local,
10525              which enables us to use GOT_PAGE/GOT_OFST (big got) or
10526              GOT_DISP.  */
10527           if (HAVE_NEWABI)
10528             {
10529               if (!mips_big_got)
10530                 {
10531                   relax_start (offset_expr.X_add_symbol);
10532                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10533                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10534                                mips_gp_register);
10535                   relax_switch ();
10536                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10537                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
10538                                mips_gp_register);
10539                   relax_end ();
10540                 }
10541               else
10542                 {
10543                   relax_start (offset_expr.X_add_symbol);
10544                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10545                                BFD_RELOC_MIPS_CALL_HI16);
10546                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10547                                PIC_CALL_REG, mips_gp_register);
10548                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10549                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10550                                PIC_CALL_REG);
10551                   relax_switch ();
10552                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10553                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
10554                                mips_gp_register);
10555                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10556                                PIC_CALL_REG, PIC_CALL_REG,
10557                                BFD_RELOC_MIPS_GOT_OFST);
10558                   relax_end ();
10559                 }
10560
10561               macro_build_jalr (&offset_expr, 0);
10562             }
10563           else
10564             {
10565               relax_start (offset_expr.X_add_symbol);
10566               if (!mips_big_got)
10567                 {
10568                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10569                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
10570                                mips_gp_register);
10571                   load_delay_nop ();
10572                   relax_switch ();
10573                 }
10574               else
10575                 {
10576                   int gpdelay;
10577
10578                   gpdelay = reg_needs_delay (mips_gp_register);
10579                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
10580                                BFD_RELOC_MIPS_CALL_HI16);
10581                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
10582                                PIC_CALL_REG, mips_gp_register);
10583                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10584                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
10585                                PIC_CALL_REG);
10586                   load_delay_nop ();
10587                   relax_switch ();
10588                   if (gpdelay)
10589                     macro_build (NULL, "nop", "");
10590                 }
10591               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10592                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
10593                            mips_gp_register);
10594               load_delay_nop ();
10595               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10596                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
10597               relax_end ();
10598               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
10599
10600               if (mips_cprestore_offset < 0)
10601                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
10602               else
10603                 {
10604                   if (!mips_frame_reg_valid)
10605                     {
10606                       as_warn (_("no .frame pseudo-op used in PIC code"));
10607                       /* Quiet this warning.  */
10608                       mips_frame_reg_valid = 1;
10609                     }
10610                   if (!mips_cprestore_valid)
10611                     {
10612                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
10613                       /* Quiet this warning.  */
10614                       mips_cprestore_valid = 1;
10615                     }
10616                   if (mips_opts.noreorder)
10617                     macro_build (NULL, "nop", "");
10618                   expr1.X_add_number = mips_cprestore_offset;
10619                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
10620                                                 mips_gp_register,
10621                                                 mips_frame_reg,
10622                                                 HAVE_64BIT_ADDRESSES);
10623                 }
10624             }
10625         }
10626       else if (mips_pic == VXWORKS_PIC)
10627         as_bad (_("non-PIC jump used in PIC library"));
10628       else
10629         abort ();
10630
10631       break;
10632
10633     case M_LBUE_AB:
10634       s = "lbue";
10635       fmt = "t,+j(b)";
10636       offbits = 9;
10637       goto ld_st;
10638     case M_LHUE_AB:
10639       s = "lhue";
10640       fmt = "t,+j(b)";
10641       offbits = 9;
10642       goto ld_st;
10643     case M_LBE_AB:
10644       s = "lbe";
10645       fmt = "t,+j(b)";
10646       offbits = 9;
10647       goto ld_st;
10648     case M_LHE_AB:
10649       s = "lhe";
10650       fmt = "t,+j(b)";
10651       offbits = 9;
10652       goto ld_st;
10653     case M_LLE_AB:
10654       s = "lle";
10655       fmt = "t,+j(b)";
10656       offbits = 9;
10657       goto ld_st;
10658     case M_LWE_AB:
10659       s = "lwe";
10660       fmt = "t,+j(b)";
10661       offbits = 9;
10662       goto ld_st;
10663     case M_LWLE_AB:
10664       s = "lwle";
10665       fmt = "t,+j(b)";
10666       offbits = 9;
10667       goto ld_st;
10668     case M_LWRE_AB:
10669       s = "lwre";
10670       fmt = "t,+j(b)";
10671       offbits = 9;
10672       goto ld_st;
10673     case M_SBE_AB:
10674       s = "sbe";
10675       fmt = "t,+j(b)";
10676       offbits = 9;
10677       goto ld_st;
10678     case M_SCE_AB:
10679       s = "sce";
10680       fmt = "t,+j(b)";
10681       offbits = 9;
10682       goto ld_st;
10683     case M_SHE_AB:
10684       s = "she";
10685       fmt = "t,+j(b)";
10686       offbits = 9;
10687       goto ld_st;
10688     case M_SWE_AB:
10689       s = "swe";
10690       fmt = "t,+j(b)";
10691       offbits = 9;
10692       goto ld_st;
10693     case M_SWLE_AB:
10694       s = "swle";
10695       fmt = "t,+j(b)";
10696       offbits = 9;
10697       goto ld_st;
10698     case M_SWRE_AB:
10699       s = "swre";
10700       fmt = "t,+j(b)";
10701       offbits = 9;
10702       goto ld_st;
10703     case M_ACLR_AB:
10704       s = "aclr";
10705       fmt = "\\,~(b)";
10706       offbits = 12;
10707       goto ld_st;
10708     case M_ASET_AB:
10709       s = "aset";
10710       fmt = "\\,~(b)";
10711       offbits = 12;
10712       goto ld_st;
10713     case M_LB_AB:
10714       s = "lb";
10715       fmt = "t,o(b)";
10716       goto ld;
10717     case M_LBU_AB:
10718       s = "lbu";
10719       fmt = "t,o(b)";
10720       goto ld;
10721     case M_LH_AB:
10722       s = "lh";
10723       fmt = "t,o(b)";
10724       goto ld;
10725     case M_LHU_AB:
10726       s = "lhu";
10727       fmt = "t,o(b)";
10728       goto ld;
10729     case M_LW_AB:
10730       s = "lw";
10731       fmt = "t,o(b)";
10732       goto ld;
10733     case M_LWC0_AB:
10734       gas_assert (!mips_opts.micromips);
10735       s = "lwc0";
10736       fmt = "E,o(b)";
10737       /* Itbl support may require additional care here.  */
10738       coproc = 1;
10739       goto ld_st;
10740     case M_LWC1_AB:
10741       s = "lwc1";
10742       fmt = "T,o(b)";
10743       /* Itbl support may require additional care here.  */
10744       coproc = 1;
10745       goto ld_st;
10746     case M_LWC2_AB:
10747       s = "lwc2";
10748       fmt = COP12_FMT;
10749       offbits = (mips_opts.micromips ? 12 : 16);
10750       /* Itbl support may require additional care here.  */
10751       coproc = 1;
10752       goto ld_st;
10753     case M_LWC3_AB:
10754       gas_assert (!mips_opts.micromips);
10755       s = "lwc3";
10756       fmt = "E,o(b)";
10757       /* Itbl support may require additional care here.  */
10758       coproc = 1;
10759       goto ld_st;
10760     case M_LWL_AB:
10761       s = "lwl";
10762       fmt = MEM12_FMT;
10763       offbits = (mips_opts.micromips ? 12 : 16);
10764       goto ld_st;
10765     case M_LWR_AB:
10766       s = "lwr";
10767       fmt = MEM12_FMT;
10768       offbits = (mips_opts.micromips ? 12 : 16);
10769       goto ld_st;
10770     case M_LDC1_AB:
10771       s = "ldc1";
10772       fmt = "T,o(b)";
10773       /* Itbl support may require additional care here.  */
10774       coproc = 1;
10775       goto ld_st;
10776     case M_LDC2_AB:
10777       s = "ldc2";
10778       fmt = COP12_FMT;
10779       offbits = (mips_opts.micromips ? 12 : 16);
10780       /* Itbl support may require additional care here.  */
10781       coproc = 1;
10782       goto ld_st;
10783     case M_LQC2_AB:
10784       s = "lqc2";
10785       fmt = "+7,o(b)";
10786       /* Itbl support may require additional care here.  */
10787       coproc = 1;
10788       goto ld_st;
10789     case M_LDC3_AB:
10790       s = "ldc3";
10791       fmt = "E,o(b)";
10792       /* Itbl support may require additional care here.  */
10793       coproc = 1;
10794       goto ld_st;
10795     case M_LDL_AB:
10796       s = "ldl";
10797       fmt = MEM12_FMT;
10798       offbits = (mips_opts.micromips ? 12 : 16);
10799       goto ld_st;
10800     case M_LDR_AB:
10801       s = "ldr";
10802       fmt = MEM12_FMT;
10803       offbits = (mips_opts.micromips ? 12 : 16);
10804       goto ld_st;
10805     case M_LL_AB:
10806       s = "ll";
10807       fmt = MEM12_FMT;
10808       offbits = (mips_opts.micromips ? 12 : 16);
10809       goto ld;
10810     case M_LLD_AB:
10811       s = "lld";
10812       fmt = MEM12_FMT;
10813       offbits = (mips_opts.micromips ? 12 : 16);
10814       goto ld;
10815     case M_LWU_AB:
10816       s = "lwu";
10817       fmt = MEM12_FMT;
10818       offbits = (mips_opts.micromips ? 12 : 16);
10819       goto ld;
10820     case M_LWP_AB:
10821       gas_assert (mips_opts.micromips);
10822       s = "lwp";
10823       fmt = "t,~(b)";
10824       offbits = 12;
10825       lp = 1;
10826       goto ld;
10827     case M_LDP_AB:
10828       gas_assert (mips_opts.micromips);
10829       s = "ldp";
10830       fmt = "t,~(b)";
10831       offbits = 12;
10832       lp = 1;
10833       goto ld;
10834     case M_LWM_AB:
10835       gas_assert (mips_opts.micromips);
10836       s = "lwm";
10837       fmt = "n,~(b)";
10838       offbits = 12;
10839       goto ld_st;
10840     case M_LDM_AB:
10841       gas_assert (mips_opts.micromips);
10842       s = "ldm";
10843       fmt = "n,~(b)";
10844       offbits = 12;
10845       goto ld_st;
10846
10847     ld:
10848       /* We don't want to use $0 as tempreg.  */
10849       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
10850         goto ld_st;
10851       else
10852         tempreg = op[0] + lp;
10853       goto ld_noat;
10854
10855     case M_SB_AB:
10856       s = "sb";
10857       fmt = "t,o(b)";
10858       goto ld_st;
10859     case M_SH_AB:
10860       s = "sh";
10861       fmt = "t,o(b)";
10862       goto ld_st;
10863     case M_SW_AB:
10864       s = "sw";
10865       fmt = "t,o(b)";
10866       goto ld_st;
10867     case M_SWC0_AB:
10868       gas_assert (!mips_opts.micromips);
10869       s = "swc0";
10870       fmt = "E,o(b)";
10871       /* Itbl support may require additional care here.  */
10872       coproc = 1;
10873       goto ld_st;
10874     case M_SWC1_AB:
10875       s = "swc1";
10876       fmt = "T,o(b)";
10877       /* Itbl support may require additional care here.  */
10878       coproc = 1;
10879       goto ld_st;
10880     case M_SWC2_AB:
10881       s = "swc2";
10882       fmt = COP12_FMT;
10883       offbits = (mips_opts.micromips ? 12 : 16);
10884       /* Itbl support may require additional care here.  */
10885       coproc = 1;
10886       goto ld_st;
10887     case M_SWC3_AB:
10888       gas_assert (!mips_opts.micromips);
10889       s = "swc3";
10890       fmt = "E,o(b)";
10891       /* Itbl support may require additional care here.  */
10892       coproc = 1;
10893       goto ld_st;
10894     case M_SWL_AB:
10895       s = "swl";
10896       fmt = MEM12_FMT;
10897       offbits = (mips_opts.micromips ? 12 : 16);
10898       goto ld_st;
10899     case M_SWR_AB:
10900       s = "swr";
10901       fmt = MEM12_FMT;
10902       offbits = (mips_opts.micromips ? 12 : 16);
10903       goto ld_st;
10904     case M_SC_AB:
10905       s = "sc";
10906       fmt = MEM12_FMT;
10907       offbits = (mips_opts.micromips ? 12 : 16);
10908       goto ld_st;
10909     case M_SCD_AB:
10910       s = "scd";
10911       fmt = MEM12_FMT;
10912       offbits = (mips_opts.micromips ? 12 : 16);
10913       goto ld_st;
10914     case M_CACHE_AB:
10915       s = "cache";
10916       fmt = mips_opts.micromips ? "k,~(b)" : "k,o(b)";
10917       offbits = (mips_opts.micromips ? 12 : 16);
10918       goto ld_st;
10919     case M_CACHEE_AB:
10920       s = "cachee";
10921       fmt = "k,+j(b)";
10922       offbits = 9;
10923       goto ld_st;
10924     case M_PREF_AB:
10925       s = "pref";
10926       fmt = !mips_opts.micromips ? "k,o(b)" : "k,~(b)";
10927       offbits = (mips_opts.micromips ? 12 : 16);
10928       goto ld_st;
10929     case M_PREFE_AB:
10930       s = "prefe";
10931       fmt = "k,+j(b)";
10932       offbits = 9;
10933       goto ld_st;
10934     case M_SDC1_AB:
10935       s = "sdc1";
10936       fmt = "T,o(b)";
10937       coproc = 1;
10938       /* Itbl support may require additional care here.  */
10939       goto ld_st;
10940     case M_SDC2_AB:
10941       s = "sdc2";
10942       fmt = COP12_FMT;
10943       offbits = (mips_opts.micromips ? 12 : 16);
10944       /* Itbl support may require additional care here.  */
10945       coproc = 1;
10946       goto ld_st;
10947     case M_SQC2_AB:
10948       s = "sqc2";
10949       fmt = "+7,o(b)";
10950       /* Itbl support may require additional care here.  */
10951       coproc = 1;
10952       goto ld_st;
10953     case M_SDC3_AB:
10954       gas_assert (!mips_opts.micromips);
10955       s = "sdc3";
10956       fmt = "E,o(b)";
10957       /* Itbl support may require additional care here.  */
10958       coproc = 1;
10959       goto ld_st;
10960     case M_SDL_AB:
10961       s = "sdl";
10962       fmt = MEM12_FMT;
10963       offbits = (mips_opts.micromips ? 12 : 16);
10964       goto ld_st;
10965     case M_SDR_AB:
10966       s = "sdr";
10967       fmt = MEM12_FMT;
10968       offbits = (mips_opts.micromips ? 12 : 16);
10969       goto ld_st;
10970     case M_SWP_AB:
10971       gas_assert (mips_opts.micromips);
10972       s = "swp";
10973       fmt = "t,~(b)";
10974       offbits = 12;
10975       goto ld_st;
10976     case M_SDP_AB:
10977       gas_assert (mips_opts.micromips);
10978       s = "sdp";
10979       fmt = "t,~(b)";
10980       offbits = 12;
10981       goto ld_st;
10982     case M_SWM_AB:
10983       gas_assert (mips_opts.micromips);
10984       s = "swm";
10985       fmt = "n,~(b)";
10986       offbits = 12;
10987       goto ld_st;
10988     case M_SDM_AB:
10989       gas_assert (mips_opts.micromips);
10990       s = "sdm";
10991       fmt = "n,~(b)";
10992       offbits = 12;
10993
10994     ld_st:
10995       tempreg = AT;
10996     ld_noat:
10997       breg = op[2];
10998       if (small_offset_p (0, align, 16))
10999         {
11000           /* The first case exists for M_LD_AB and M_SD_AB, which are
11001              macros for o32 but which should act like normal instructions
11002              otherwise.  */
11003           if (offbits == 16)
11004             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11005                          offset_reloc[1], offset_reloc[2], breg);
11006           else if (small_offset_p (0, align, offbits))
11007             {
11008               if (offbits == 0)
11009                 macro_build (NULL, s, fmt, op[0], breg);
11010               else
11011                 macro_build (NULL, s, fmt, op[0],
11012                              (int) offset_expr.X_add_number, breg);
11013             }
11014           else
11015             {
11016               if (tempreg == AT)
11017                 used_at = 1;
11018               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11019                            tempreg, breg, -1, offset_reloc[0],
11020                            offset_reloc[1], offset_reloc[2]);
11021               if (offbits == 0)
11022                 macro_build (NULL, s, fmt, op[0], tempreg);
11023               else
11024                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11025             }
11026           break;
11027         }
11028
11029       if (tempreg == AT)
11030         used_at = 1;
11031
11032       if (offset_expr.X_op != O_constant
11033           && offset_expr.X_op != O_symbol)
11034         {
11035           as_bad (_("expression too complex"));
11036           offset_expr.X_op = O_constant;
11037         }
11038
11039       if (HAVE_32BIT_ADDRESSES
11040           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11041         {
11042           char value [32];
11043
11044           sprintf_vma (value, offset_expr.X_add_number);
11045           as_bad (_("number (0x%s) larger than 32 bits"), value);
11046         }
11047
11048       /* A constant expression in PIC code can be handled just as it
11049          is in non PIC code.  */
11050       if (offset_expr.X_op == O_constant)
11051         {
11052           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11053                                                  offbits == 0 ? 16 : offbits);
11054           offset_expr.X_add_number -= expr1.X_add_number;
11055
11056           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11057           if (breg != 0)
11058             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11059                          tempreg, tempreg, breg);
11060           if (offbits == 0)
11061             {
11062               if (offset_expr.X_add_number != 0)
11063                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11064                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11065               macro_build (NULL, s, fmt, op[0], tempreg);
11066             }
11067           else if (offbits == 16)
11068             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11069           else
11070             macro_build (NULL, s, fmt, op[0],
11071                          (int) offset_expr.X_add_number, tempreg);
11072         }
11073       else if (offbits != 16)
11074         {
11075           /* The offset field is too narrow to be used for a low-part
11076              relocation, so load the whole address into the auxillary
11077              register.  */
11078           load_address (tempreg, &offset_expr, &used_at);
11079           if (breg != 0)
11080             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11081                          tempreg, tempreg, breg);
11082           if (offbits == 0)
11083             macro_build (NULL, s, fmt, op[0], tempreg);
11084           else
11085             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11086         }
11087       else if (mips_pic == NO_PIC)
11088         {
11089           /* If this is a reference to a GP relative symbol, and there
11090              is no base register, we want
11091                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11092              Otherwise, if there is no base register, we want
11093                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11094                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11095              If we have a constant, we need two instructions anyhow,
11096              so we always use the latter form.
11097
11098              If we have a base register, and this is a reference to a
11099              GP relative symbol, we want
11100                addu     $tempreg,$breg,$gp
11101                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11102              Otherwise we want
11103                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11104                addu     $tempreg,$tempreg,$breg
11105                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11106              With a constant we always use the latter case.
11107
11108              With 64bit address space and no base register and $at usable,
11109              we want
11110                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11111                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11112                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11113                dsll32   $tempreg,0
11114                daddu    $tempreg,$at
11115                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11116              If we have a base register, we want
11117                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11118                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11119                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11120                daddu    $at,$breg
11121                dsll32   $tempreg,0
11122                daddu    $tempreg,$at
11123                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11124
11125              Without $at we can't generate the optimal path for superscalar
11126              processors here since this would require two temporary registers.
11127                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11128                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11129                dsll     $tempreg,16
11130                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11131                dsll     $tempreg,16
11132                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11133              If we have a base register, we want
11134                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11135                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11136                dsll     $tempreg,16
11137                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11138                dsll     $tempreg,16
11139                daddu    $tempreg,$tempreg,$breg
11140                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11141
11142              For GP relative symbols in 64bit address space we can use
11143              the same sequence as in 32bit address space.  */
11144           if (HAVE_64BIT_SYMBOLS)
11145             {
11146               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11147                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11148                 {
11149                   relax_start (offset_expr.X_add_symbol);
11150                   if (breg == 0)
11151                     {
11152                       macro_build (&offset_expr, s, fmt, op[0],
11153                                    BFD_RELOC_GPREL16, mips_gp_register);
11154                     }
11155                   else
11156                     {
11157                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11158                                    tempreg, breg, mips_gp_register);
11159                       macro_build (&offset_expr, s, fmt, op[0],
11160                                    BFD_RELOC_GPREL16, tempreg);
11161                     }
11162                   relax_switch ();
11163                 }
11164
11165               if (used_at == 0 && mips_opts.at)
11166                 {
11167                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11168                                BFD_RELOC_MIPS_HIGHEST);
11169                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11170                                BFD_RELOC_HI16_S);
11171                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11172                                tempreg, BFD_RELOC_MIPS_HIGHER);
11173                   if (breg != 0)
11174                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11175                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11176                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11177                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11178                                tempreg);
11179                   used_at = 1;
11180                 }
11181               else
11182                 {
11183                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11184                                BFD_RELOC_MIPS_HIGHEST);
11185                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11186                                tempreg, BFD_RELOC_MIPS_HIGHER);
11187                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11188                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11189                                tempreg, BFD_RELOC_HI16_S);
11190                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11191                   if (breg != 0)
11192                     macro_build (NULL, "daddu", "d,v,t",
11193                                  tempreg, tempreg, breg);
11194                   macro_build (&offset_expr, s, fmt, op[0],
11195                                BFD_RELOC_LO16, tempreg);
11196                 }
11197
11198               if (mips_relax.sequence)
11199                 relax_end ();
11200               break;
11201             }
11202
11203           if (breg == 0)
11204             {
11205               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11206                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11207                 {
11208                   relax_start (offset_expr.X_add_symbol);
11209                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11210                                mips_gp_register);
11211                   relax_switch ();
11212                 }
11213               macro_build_lui (&offset_expr, tempreg);
11214               macro_build (&offset_expr, s, fmt, op[0],
11215                            BFD_RELOC_LO16, tempreg);
11216               if (mips_relax.sequence)
11217                 relax_end ();
11218             }
11219           else
11220             {
11221               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11222                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11223                 {
11224                   relax_start (offset_expr.X_add_symbol);
11225                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11226                                tempreg, breg, mips_gp_register);
11227                   macro_build (&offset_expr, s, fmt, op[0],
11228                                BFD_RELOC_GPREL16, tempreg);
11229                   relax_switch ();
11230                 }
11231               macro_build_lui (&offset_expr, tempreg);
11232               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11233                            tempreg, tempreg, breg);
11234               macro_build (&offset_expr, s, fmt, op[0],
11235                            BFD_RELOC_LO16, tempreg);
11236               if (mips_relax.sequence)
11237                 relax_end ();
11238             }
11239         }
11240       else if (!mips_big_got)
11241         {
11242           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11243
11244           /* If this is a reference to an external symbol, we want
11245                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11246                nop
11247                <op>     op[0],0($tempreg)
11248              Otherwise we want
11249                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11250                nop
11251                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11252                <op>     op[0],0($tempreg)
11253
11254              For NewABI, we want
11255                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11256                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11257
11258              If there is a base register, we add it to $tempreg before
11259              the <op>.  If there is a constant, we stick it in the
11260              <op> instruction.  We don't handle constants larger than
11261              16 bits, because we have no way to load the upper 16 bits
11262              (actually, we could handle them for the subset of cases
11263              in which we are not using $at).  */
11264           gas_assert (offset_expr.X_op == O_symbol);
11265           if (HAVE_NEWABI)
11266             {
11267               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11268                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11269               if (breg != 0)
11270                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11271                              tempreg, tempreg, breg);
11272               macro_build (&offset_expr, s, fmt, op[0],
11273                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11274               break;
11275             }
11276           expr1.X_add_number = offset_expr.X_add_number;
11277           offset_expr.X_add_number = 0;
11278           if (expr1.X_add_number < -0x8000
11279               || expr1.X_add_number >= 0x8000)
11280             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11281           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11282                        lw_reloc_type, mips_gp_register);
11283           load_delay_nop ();
11284           relax_start (offset_expr.X_add_symbol);
11285           relax_switch ();
11286           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11287                        tempreg, BFD_RELOC_LO16);
11288           relax_end ();
11289           if (breg != 0)
11290             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11291                          tempreg, tempreg, breg);
11292           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11293         }
11294       else if (mips_big_got && !HAVE_NEWABI)
11295         {
11296           int gpdelay;
11297
11298           /* If this is a reference to an external symbol, we want
11299                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11300                addu     $tempreg,$tempreg,$gp
11301                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11302                <op>     op[0],0($tempreg)
11303              Otherwise we want
11304                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11305                nop
11306                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11307                <op>     op[0],0($tempreg)
11308              If there is a base register, we add it to $tempreg before
11309              the <op>.  If there is a constant, we stick it in the
11310              <op> instruction.  We don't handle constants larger than
11311              16 bits, because we have no way to load the upper 16 bits
11312              (actually, we could handle them for the subset of cases
11313              in which we are not using $at).  */
11314           gas_assert (offset_expr.X_op == O_symbol);
11315           expr1.X_add_number = offset_expr.X_add_number;
11316           offset_expr.X_add_number = 0;
11317           if (expr1.X_add_number < -0x8000
11318               || expr1.X_add_number >= 0x8000)
11319             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11320           gpdelay = reg_needs_delay (mips_gp_register);
11321           relax_start (offset_expr.X_add_symbol);
11322           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11323                        BFD_RELOC_MIPS_GOT_HI16);
11324           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11325                        mips_gp_register);
11326           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11327                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11328           relax_switch ();
11329           if (gpdelay)
11330             macro_build (NULL, "nop", "");
11331           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11332                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11333           load_delay_nop ();
11334           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11335                        tempreg, BFD_RELOC_LO16);
11336           relax_end ();
11337
11338           if (breg != 0)
11339             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11340                          tempreg, tempreg, breg);
11341           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11342         }
11343       else if (mips_big_got && HAVE_NEWABI)
11344         {
11345           /* If this is a reference to an external symbol, we want
11346                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11347                add      $tempreg,$tempreg,$gp
11348                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11349                <op>     op[0],<ofst>($tempreg)
11350              Otherwise, for local symbols, we want:
11351                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11352                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11353           gas_assert (offset_expr.X_op == O_symbol);
11354           expr1.X_add_number = offset_expr.X_add_number;
11355           offset_expr.X_add_number = 0;
11356           if (expr1.X_add_number < -0x8000
11357               || expr1.X_add_number >= 0x8000)
11358             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11359           relax_start (offset_expr.X_add_symbol);
11360           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11361                        BFD_RELOC_MIPS_GOT_HI16);
11362           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11363                        mips_gp_register);
11364           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11365                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11366           if (breg != 0)
11367             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11368                          tempreg, tempreg, breg);
11369           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11370
11371           relax_switch ();
11372           offset_expr.X_add_number = expr1.X_add_number;
11373           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11374                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11375           if (breg != 0)
11376             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11377                          tempreg, tempreg, breg);
11378           macro_build (&offset_expr, s, fmt, op[0],
11379                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
11380           relax_end ();
11381         }
11382       else
11383         abort ();
11384
11385       break;
11386
11387     case M_JRADDIUSP:
11388       gas_assert (mips_opts.micromips);
11389       gas_assert (mips_opts.insn32);
11390       start_noreorder ();
11391       macro_build (NULL, "jr", "s", RA);
11392       expr1.X_add_number = op[0] << 2;
11393       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
11394       end_noreorder ();
11395       break;
11396
11397     case M_JRC:
11398       gas_assert (mips_opts.micromips);
11399       gas_assert (mips_opts.insn32);
11400       macro_build (NULL, "jr", "s", op[0]);
11401       if (mips_opts.noreorder)
11402         macro_build (NULL, "nop", "");
11403       break;
11404
11405     case M_LI:
11406     case M_LI_S:
11407       load_register (op[0], &imm_expr, 0);
11408       break;
11409
11410     case M_DLI:
11411       load_register (op[0], &imm_expr, 1);
11412       break;
11413
11414     case M_LI_SS:
11415       if (imm_expr.X_op == O_constant)
11416         {
11417           used_at = 1;
11418           load_register (AT, &imm_expr, 0);
11419           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11420           break;
11421         }
11422       else
11423         {
11424           gas_assert (imm_expr.X_op == O_absent
11425                       && offset_expr.X_op == O_symbol
11426                       && strcmp (segment_name (S_GET_SEGMENT
11427                                                (offset_expr.X_add_symbol)),
11428                                  ".lit4") == 0
11429                       && offset_expr.X_add_number == 0);
11430           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
11431                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
11432           break;
11433         }
11434
11435     case M_LI_D:
11436       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
11437          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
11438          order 32 bits of the value and the low order 32 bits are either
11439          zero or in OFFSET_EXPR.  */
11440       if (imm_expr.X_op == O_constant)
11441         {
11442           if (HAVE_64BIT_GPRS)
11443             load_register (op[0], &imm_expr, 1);
11444           else
11445             {
11446               int hreg, lreg;
11447
11448               if (target_big_endian)
11449                 {
11450                   hreg = op[0];
11451                   lreg = op[0] + 1;
11452                 }
11453               else
11454                 {
11455                   hreg = op[0] + 1;
11456                   lreg = op[0];
11457                 }
11458
11459               if (hreg <= 31)
11460                 load_register (hreg, &imm_expr, 0);
11461               if (lreg <= 31)
11462                 {
11463                   if (offset_expr.X_op == O_absent)
11464                     move_register (lreg, 0);
11465                   else
11466                     {
11467                       gas_assert (offset_expr.X_op == O_constant);
11468                       load_register (lreg, &offset_expr, 0);
11469                     }
11470                 }
11471             }
11472           break;
11473         }
11474       gas_assert (imm_expr.X_op == O_absent);
11475
11476       /* We know that sym is in the .rdata section.  First we get the
11477          upper 16 bits of the address.  */
11478       if (mips_pic == NO_PIC)
11479         {
11480           macro_build_lui (&offset_expr, AT);
11481           used_at = 1;
11482         }
11483       else
11484         {
11485           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11486                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11487           used_at = 1;
11488         }
11489
11490       /* Now we load the register(s).  */
11491       if (HAVE_64BIT_GPRS)
11492         {
11493           used_at = 1;
11494           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
11495                        BFD_RELOC_LO16, AT);
11496         }
11497       else
11498         {
11499           used_at = 1;
11500           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
11501                        BFD_RELOC_LO16, AT);
11502           if (op[0] != RA)
11503             {
11504               /* FIXME: How in the world do we deal with the possible
11505                  overflow here?  */
11506               offset_expr.X_add_number += 4;
11507               macro_build (&offset_expr, "lw", "t,o(b)",
11508                            op[0] + 1, BFD_RELOC_LO16, AT);
11509             }
11510         }
11511       break;
11512
11513     case M_LI_DD:
11514       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
11515          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
11516          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
11517          the value and the low order 32 bits are either zero or in
11518          OFFSET_EXPR.  */
11519       if (imm_expr.X_op == O_constant)
11520         {
11521           used_at = 1;
11522           load_register (AT, &imm_expr, HAVE_64BIT_FPRS);
11523           if (HAVE_64BIT_FPRS)
11524             {
11525               gas_assert (HAVE_64BIT_GPRS);
11526               macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
11527             }
11528           else
11529             {
11530               macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
11531               if (offset_expr.X_op == O_absent)
11532                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
11533               else
11534                 {
11535                   gas_assert (offset_expr.X_op == O_constant);
11536                   load_register (AT, &offset_expr, 0);
11537                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
11538                 }
11539             }
11540           break;
11541         }
11542
11543       gas_assert (imm_expr.X_op == O_absent
11544                   && offset_expr.X_op == O_symbol
11545                   && offset_expr.X_add_number == 0);
11546       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
11547       if (strcmp (s, ".lit8") == 0)
11548         {
11549           op[2] = mips_gp_register;
11550           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
11551           offset_reloc[1] = BFD_RELOC_UNUSED;
11552           offset_reloc[2] = BFD_RELOC_UNUSED;
11553         }
11554       else
11555         {
11556           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
11557           used_at = 1;
11558           if (mips_pic != NO_PIC)
11559             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11560                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
11561           else
11562             {
11563               /* FIXME: This won't work for a 64 bit address.  */
11564               macro_build_lui (&offset_expr, AT);
11565             }
11566
11567           op[2] = AT;
11568           offset_reloc[0] = BFD_RELOC_LO16;
11569           offset_reloc[1] = BFD_RELOC_UNUSED;
11570           offset_reloc[2] = BFD_RELOC_UNUSED;
11571         }
11572       align = 8;
11573       /* Fall through */
11574
11575     case M_L_DAB:
11576       /*
11577        * The MIPS assembler seems to check for X_add_number not
11578        * being double aligned and generating:
11579        *        lui     at,%hi(foo+1)
11580        *        addu    at,at,v1
11581        *        addiu   at,at,%lo(foo+1)
11582        *        lwc1    f2,0(at)
11583        *        lwc1    f3,4(at)
11584        * But, the resulting address is the same after relocation so why
11585        * generate the extra instruction?
11586        */
11587       /* Itbl support may require additional care here.  */
11588       coproc = 1;
11589       fmt = "T,o(b)";
11590       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11591         {
11592           s = "ldc1";
11593           goto ld_st;
11594         }
11595       s = "lwc1";
11596       goto ldd_std;
11597
11598     case M_S_DAB:
11599       gas_assert (!mips_opts.micromips);
11600       /* Itbl support may require additional care here.  */
11601       coproc = 1;
11602       fmt = "T,o(b)";
11603       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
11604         {
11605           s = "sdc1";
11606           goto ld_st;
11607         }
11608       s = "swc1";
11609       goto ldd_std;
11610
11611     case M_LQ_AB:
11612       fmt = "t,o(b)";
11613       s = "lq";
11614       goto ld;
11615
11616     case M_SQ_AB:
11617       fmt = "t,o(b)";
11618       s = "sq";
11619       goto ld_st;
11620
11621     case M_LD_AB:
11622       fmt = "t,o(b)";
11623       if (HAVE_64BIT_GPRS)
11624         {
11625           s = "ld";
11626           goto ld;
11627         }
11628       s = "lw";
11629       goto ldd_std;
11630
11631     case M_SD_AB:
11632       fmt = "t,o(b)";
11633       if (HAVE_64BIT_GPRS)
11634         {
11635           s = "sd";
11636           goto ld_st;
11637         }
11638       s = "sw";
11639
11640     ldd_std:
11641       /* Even on a big endian machine $fn comes before $fn+1.  We have
11642          to adjust when loading from memory.  We set coproc if we must
11643          load $fn+1 first.  */
11644       /* Itbl support may require additional care here.  */
11645       if (!target_big_endian)
11646         coproc = 0;
11647
11648       breg = op[2];
11649       if (small_offset_p (0, align, 16))
11650         {
11651           ep = &offset_expr;
11652           if (!small_offset_p (4, align, 16))
11653             {
11654               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
11655                            -1, offset_reloc[0], offset_reloc[1],
11656                            offset_reloc[2]);
11657               expr1.X_add_number = 0;
11658               ep = &expr1;
11659               breg = AT;
11660               used_at = 1;
11661               offset_reloc[0] = BFD_RELOC_LO16;
11662               offset_reloc[1] = BFD_RELOC_UNUSED;
11663               offset_reloc[2] = BFD_RELOC_UNUSED;
11664             }
11665           if (strcmp (s, "lw") == 0 && op[0] == breg)
11666             {
11667               ep->X_add_number += 4;
11668               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
11669                            offset_reloc[1], offset_reloc[2], breg);
11670               ep->X_add_number -= 4;
11671               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
11672                            offset_reloc[1], offset_reloc[2], breg);
11673             }
11674           else
11675             {
11676               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
11677                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11678                            breg);
11679               ep->X_add_number += 4;
11680               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
11681                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
11682                            breg);
11683             }
11684           break;
11685         }
11686
11687       if (offset_expr.X_op != O_symbol
11688           && offset_expr.X_op != O_constant)
11689         {
11690           as_bad (_("expression too complex"));
11691           offset_expr.X_op = O_constant;
11692         }
11693
11694       if (HAVE_32BIT_ADDRESSES
11695           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11696         {
11697           char value [32];
11698
11699           sprintf_vma (value, offset_expr.X_add_number);
11700           as_bad (_("number (0x%s) larger than 32 bits"), value);
11701         }
11702
11703       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
11704         {
11705           /* If this is a reference to a GP relative symbol, we want
11706                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11707                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
11708              If we have a base register, we use this
11709                addu     $at,$breg,$gp
11710                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
11711                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
11712              If this is not a GP relative symbol, we want
11713                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11714                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11715                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11716              If there is a base register, we add it to $at after the
11717              lui instruction.  If there is a constant, we always use
11718              the last case.  */
11719           if (offset_expr.X_op == O_symbol
11720               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11721               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11722             {
11723               relax_start (offset_expr.X_add_symbol);
11724               if (breg == 0)
11725                 {
11726                   tempreg = mips_gp_register;
11727                 }
11728               else
11729                 {
11730                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11731                                AT, breg, mips_gp_register);
11732                   tempreg = AT;
11733                   used_at = 1;
11734                 }
11735
11736               /* Itbl support may require additional care here.  */
11737               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11738                            BFD_RELOC_GPREL16, tempreg);
11739               offset_expr.X_add_number += 4;
11740
11741               /* Set mips_optimize to 2 to avoid inserting an
11742                  undesired nop.  */
11743               hold_mips_optimize = mips_optimize;
11744               mips_optimize = 2;
11745               /* Itbl support may require additional care here.  */
11746               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11747                            BFD_RELOC_GPREL16, tempreg);
11748               mips_optimize = hold_mips_optimize;
11749
11750               relax_switch ();
11751
11752               offset_expr.X_add_number -= 4;
11753             }
11754           used_at = 1;
11755           if (offset_high_part (offset_expr.X_add_number, 16)
11756               != offset_high_part (offset_expr.X_add_number + 4, 16))
11757             {
11758               load_address (AT, &offset_expr, &used_at);
11759               offset_expr.X_op = O_constant;
11760               offset_expr.X_add_number = 0;
11761             }
11762           else
11763             macro_build_lui (&offset_expr, AT);
11764           if (breg != 0)
11765             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11766           /* Itbl support may require additional care here.  */
11767           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11768                        BFD_RELOC_LO16, AT);
11769           /* FIXME: How do we handle overflow here?  */
11770           offset_expr.X_add_number += 4;
11771           /* Itbl support may require additional care here.  */
11772           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11773                        BFD_RELOC_LO16, AT);
11774           if (mips_relax.sequence)
11775             relax_end ();
11776         }
11777       else if (!mips_big_got)
11778         {
11779           /* If this is a reference to an external symbol, we want
11780                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11781                nop
11782                <op>     op[0],0($at)
11783                <op>     op[0]+1,4($at)
11784              Otherwise we want
11785                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11786                nop
11787                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11788                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11789              If there is a base register we add it to $at before the
11790              lwc1 instructions.  If there is a constant we include it
11791              in the lwc1 instructions.  */
11792           used_at = 1;
11793           expr1.X_add_number = offset_expr.X_add_number;
11794           if (expr1.X_add_number < -0x8000
11795               || expr1.X_add_number >= 0x8000 - 4)
11796             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11797           load_got_offset (AT, &offset_expr);
11798           load_delay_nop ();
11799           if (breg != 0)
11800             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11801
11802           /* Set mips_optimize to 2 to avoid inserting an undesired
11803              nop.  */
11804           hold_mips_optimize = mips_optimize;
11805           mips_optimize = 2;
11806
11807           /* Itbl support may require additional care here.  */
11808           relax_start (offset_expr.X_add_symbol);
11809           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11810                        BFD_RELOC_LO16, AT);
11811           expr1.X_add_number += 4;
11812           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11813                        BFD_RELOC_LO16, AT);
11814           relax_switch ();
11815           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11816                        BFD_RELOC_LO16, AT);
11817           offset_expr.X_add_number += 4;
11818           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11819                        BFD_RELOC_LO16, AT);
11820           relax_end ();
11821
11822           mips_optimize = hold_mips_optimize;
11823         }
11824       else if (mips_big_got)
11825         {
11826           int gpdelay;
11827
11828           /* If this is a reference to an external symbol, we want
11829                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
11830                addu     $at,$at,$gp
11831                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
11832                nop
11833                <op>     op[0],0($at)
11834                <op>     op[0]+1,4($at)
11835              Otherwise we want
11836                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11837                nop
11838                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
11839                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
11840              If there is a base register we add it to $at before the
11841              lwc1 instructions.  If there is a constant we include it
11842              in the lwc1 instructions.  */
11843           used_at = 1;
11844           expr1.X_add_number = offset_expr.X_add_number;
11845           offset_expr.X_add_number = 0;
11846           if (expr1.X_add_number < -0x8000
11847               || expr1.X_add_number >= 0x8000 - 4)
11848             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11849           gpdelay = reg_needs_delay (mips_gp_register);
11850           relax_start (offset_expr.X_add_symbol);
11851           macro_build (&offset_expr, "lui", LUI_FMT,
11852                        AT, BFD_RELOC_MIPS_GOT_HI16);
11853           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11854                        AT, AT, mips_gp_register);
11855           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11856                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
11857           load_delay_nop ();
11858           if (breg != 0)
11859             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11860           /* Itbl support may require additional care here.  */
11861           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
11862                        BFD_RELOC_LO16, AT);
11863           expr1.X_add_number += 4;
11864
11865           /* Set mips_optimize to 2 to avoid inserting an undesired
11866              nop.  */
11867           hold_mips_optimize = mips_optimize;
11868           mips_optimize = 2;
11869           /* Itbl support may require additional care here.  */
11870           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
11871                        BFD_RELOC_LO16, AT);
11872           mips_optimize = hold_mips_optimize;
11873           expr1.X_add_number -= 4;
11874
11875           relax_switch ();
11876           offset_expr.X_add_number = expr1.X_add_number;
11877           if (gpdelay)
11878             macro_build (NULL, "nop", "");
11879           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
11880                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11881           load_delay_nop ();
11882           if (breg != 0)
11883             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
11884           /* Itbl support may require additional care here.  */
11885           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
11886                        BFD_RELOC_LO16, AT);
11887           offset_expr.X_add_number += 4;
11888
11889           /* Set mips_optimize to 2 to avoid inserting an undesired
11890              nop.  */
11891           hold_mips_optimize = mips_optimize;
11892           mips_optimize = 2;
11893           /* Itbl support may require additional care here.  */
11894           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
11895                        BFD_RELOC_LO16, AT);
11896           mips_optimize = hold_mips_optimize;
11897           relax_end ();
11898         }
11899       else
11900         abort ();
11901
11902       break;
11903         
11904     case M_SAA_AB:
11905       s = "saa";
11906       offbits = 0;
11907       fmt = "t,(b)";
11908       goto ld_st;
11909     case M_SAAD_AB:
11910       s = "saad";
11911       offbits = 0;
11912       fmt = "t,(b)";
11913       goto ld_st;
11914
11915    /* New code added to support COPZ instructions.
11916       This code builds table entries out of the macros in mip_opcodes.
11917       R4000 uses interlocks to handle coproc delays.
11918       Other chips (like the R3000) require nops to be inserted for delays.
11919
11920       FIXME: Currently, we require that the user handle delays.
11921       In order to fill delay slots for non-interlocked chips,
11922       we must have a way to specify delays based on the coprocessor.
11923       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
11924       What are the side-effects of the cop instruction?
11925       What cache support might we have and what are its effects?
11926       Both coprocessor & memory require delays. how long???
11927       What registers are read/set/modified?
11928
11929       If an itbl is provided to interpret cop instructions,
11930       this knowledge can be encoded in the itbl spec.  */
11931
11932     case M_COP0:
11933       s = "c0";
11934       goto copz;
11935     case M_COP1:
11936       s = "c1";
11937       goto copz;
11938     case M_COP2:
11939       s = "c2";
11940       goto copz;
11941     case M_COP3:
11942       s = "c3";
11943     copz:
11944       gas_assert (!mips_opts.micromips);
11945       /* For now we just do C (same as Cz).  The parameter will be
11946          stored in insn_opcode by mips_ip.  */
11947       macro_build (NULL, s, "C", (int) ip->insn_opcode);
11948       break;
11949
11950     case M_MOVE:
11951       move_register (op[0], op[1]);
11952       break;
11953
11954     case M_MOVEP:
11955       gas_assert (mips_opts.micromips);
11956       gas_assert (mips_opts.insn32);
11957       move_register (micromips_to_32_reg_h_map1[op[0]],
11958                      micromips_to_32_reg_m_map[op[1]]);
11959       move_register (micromips_to_32_reg_h_map2[op[0]],
11960                      micromips_to_32_reg_n_map[op[2]]);
11961       break;
11962
11963     case M_DMUL:
11964       dbl = 1;
11965     case M_MUL:
11966       if (mips_opts.arch == CPU_R5900)
11967         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
11968                      op[2]);
11969       else
11970         {
11971           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
11972           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11973         }
11974       break;
11975
11976     case M_DMUL_I:
11977       dbl = 1;
11978     case M_MUL_I:
11979       /* The MIPS assembler some times generates shifts and adds.  I'm
11980          not trying to be that fancy. GCC should do this for us
11981          anyway.  */
11982       used_at = 1;
11983       load_register (AT, &imm_expr, dbl);
11984       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
11985       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
11986       break;
11987
11988     case M_DMULO_I:
11989       dbl = 1;
11990     case M_MULO_I:
11991       imm = 1;
11992       goto do_mulo;
11993
11994     case M_DMULO:
11995       dbl = 1;
11996     case M_MULO:
11997     do_mulo:
11998       start_noreorder ();
11999       used_at = 1;
12000       if (imm)
12001         load_register (AT, &imm_expr, dbl);
12002       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12003                    op[1], imm ? AT : op[2]);
12004       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12005       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12006       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12007       if (mips_trap)
12008         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12009       else
12010         {
12011           if (mips_opts.micromips)
12012             micromips_label_expr (&label_expr);
12013           else
12014             label_expr.X_add_number = 8;
12015           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12016           macro_build (NULL, "nop", "");
12017           macro_build (NULL, "break", BRK_FMT, 6);
12018           if (mips_opts.micromips)
12019             micromips_add_label ();
12020         }
12021       end_noreorder ();
12022       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12023       break;
12024
12025     case M_DMULOU_I:
12026       dbl = 1;
12027     case M_MULOU_I:
12028       imm = 1;
12029       goto do_mulou;
12030
12031     case M_DMULOU:
12032       dbl = 1;
12033     case M_MULOU:
12034     do_mulou:
12035       start_noreorder ();
12036       used_at = 1;
12037       if (imm)
12038         load_register (AT, &imm_expr, dbl);
12039       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12040                    op[1], imm ? AT : op[2]);
12041       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12042       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12043       if (mips_trap)
12044         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12045       else
12046         {
12047           if (mips_opts.micromips)
12048             micromips_label_expr (&label_expr);
12049           else
12050             label_expr.X_add_number = 8;
12051           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12052           macro_build (NULL, "nop", "");
12053           macro_build (NULL, "break", BRK_FMT, 6);
12054           if (mips_opts.micromips)
12055             micromips_add_label ();
12056         }
12057       end_noreorder ();
12058       break;
12059
12060     case M_DROL:
12061       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12062         {
12063           if (op[0] == op[1])
12064             {
12065               tempreg = AT;
12066               used_at = 1;
12067             }
12068           else
12069             tempreg = op[0];
12070           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12071           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12072           break;
12073         }
12074       used_at = 1;
12075       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12076       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12077       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12078       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12079       break;
12080
12081     case M_ROL:
12082       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12083         {
12084           if (op[0] == op[1])
12085             {
12086               tempreg = AT;
12087               used_at = 1;
12088             }
12089           else
12090             tempreg = op[0];
12091           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12092           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12093           break;
12094         }
12095       used_at = 1;
12096       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12097       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12098       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12099       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12100       break;
12101
12102     case M_DROL_I:
12103       {
12104         unsigned int rot;
12105         char *l;
12106         char *rr;
12107
12108         rot = imm_expr.X_add_number & 0x3f;
12109         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12110           {
12111             rot = (64 - rot) & 0x3f;
12112             if (rot >= 32)
12113               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12114             else
12115               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12116             break;
12117           }
12118         if (rot == 0)
12119           {
12120             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12121             break;
12122           }
12123         l = (rot < 0x20) ? "dsll" : "dsll32";
12124         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12125         rot &= 0x1f;
12126         used_at = 1;
12127         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12128         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12129         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12130       }
12131       break;
12132
12133     case M_ROL_I:
12134       {
12135         unsigned int rot;
12136
12137         rot = imm_expr.X_add_number & 0x1f;
12138         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12139           {
12140             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12141                          (32 - rot) & 0x1f);
12142             break;
12143           }
12144         if (rot == 0)
12145           {
12146             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12147             break;
12148           }
12149         used_at = 1;
12150         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12151         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12152         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12153       }
12154       break;
12155
12156     case M_DROR:
12157       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12158         {
12159           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12160           break;
12161         }
12162       used_at = 1;
12163       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12164       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12165       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12166       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12167       break;
12168
12169     case M_ROR:
12170       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12171         {
12172           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12173           break;
12174         }
12175       used_at = 1;
12176       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12177       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12178       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12179       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12180       break;
12181
12182     case M_DROR_I:
12183       {
12184         unsigned int rot;
12185         char *l;
12186         char *rr;
12187
12188         rot = imm_expr.X_add_number & 0x3f;
12189         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12190           {
12191             if (rot >= 32)
12192               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12193             else
12194               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12195             break;
12196           }
12197         if (rot == 0)
12198           {
12199             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12200             break;
12201           }
12202         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12203         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12204         rot &= 0x1f;
12205         used_at = 1;
12206         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12207         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12208         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12209       }
12210       break;
12211
12212     case M_ROR_I:
12213       {
12214         unsigned int rot;
12215
12216         rot = imm_expr.X_add_number & 0x1f;
12217         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12218           {
12219             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12220             break;
12221           }
12222         if (rot == 0)
12223           {
12224             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12225             break;
12226           }
12227         used_at = 1;
12228         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12229         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12230         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12231       }
12232       break;
12233
12234     case M_SEQ:
12235       if (op[1] == 0)
12236         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12237       else if (op[2] == 0)
12238         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12239       else
12240         {
12241           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12242           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12243         }
12244       break;
12245
12246     case M_SEQ_I:
12247       if (imm_expr.X_add_number == 0)
12248         {
12249           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12250           break;
12251         }
12252       if (op[1] == 0)
12253         {
12254           as_warn (_("instruction %s: result is always false"),
12255                    ip->insn_mo->name);
12256           move_register (op[0], 0);
12257           break;
12258         }
12259       if (CPU_HAS_SEQ (mips_opts.arch)
12260           && -512 <= imm_expr.X_add_number
12261           && imm_expr.X_add_number < 512)
12262         {
12263           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12264                        (int) imm_expr.X_add_number);
12265           break;
12266         }
12267       if (imm_expr.X_add_number >= 0
12268           && imm_expr.X_add_number < 0x10000)
12269         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12270       else if (imm_expr.X_add_number > -0x8000
12271                && imm_expr.X_add_number < 0)
12272         {
12273           imm_expr.X_add_number = -imm_expr.X_add_number;
12274           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12275                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12276         }
12277       else if (CPU_HAS_SEQ (mips_opts.arch))
12278         {
12279           used_at = 1;
12280           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12281           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12282           break;
12283         }
12284       else
12285         {
12286           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12287           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12288           used_at = 1;
12289         }
12290       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12291       break;
12292
12293     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12294       s = "slt";
12295       goto sge;
12296     case M_SGEU:
12297       s = "sltu";
12298     sge:
12299       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12300       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12301       break;
12302
12303     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12304     case M_SGEU_I:
12305       if (imm_expr.X_add_number >= -0x8000
12306           && imm_expr.X_add_number < 0x8000)
12307         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12308                      op[0], op[1], BFD_RELOC_LO16);
12309       else
12310         {
12311           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12312           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12313                        op[0], op[1], AT);
12314           used_at = 1;
12315         }
12316       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12317       break;
12318
12319     case M_SGT:         /* X > Y  <==>  Y < X */
12320       s = "slt";
12321       goto sgt;
12322     case M_SGTU:
12323       s = "sltu";
12324     sgt:
12325       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12326       break;
12327
12328     case M_SGT_I:       /* X > I  <==>  I < X */
12329       s = "slt";
12330       goto sgti;
12331     case M_SGTU_I:
12332       s = "sltu";
12333     sgti:
12334       used_at = 1;
12335       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12336       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12337       break;
12338
12339     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12340       s = "slt";
12341       goto sle;
12342     case M_SLEU:
12343       s = "sltu";
12344     sle:
12345       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12346       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12347       break;
12348
12349     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12350       s = "slt";
12351       goto slei;
12352     case M_SLEU_I:
12353       s = "sltu";
12354     slei:
12355       used_at = 1;
12356       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12357       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12358       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12359       break;
12360
12361     case M_SLT_I:
12362       if (imm_expr.X_add_number >= -0x8000
12363           && imm_expr.X_add_number < 0x8000)
12364         {
12365           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12366                        BFD_RELOC_LO16);
12367           break;
12368         }
12369       used_at = 1;
12370       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12371       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
12372       break;
12373
12374     case M_SLTU_I:
12375       if (imm_expr.X_add_number >= -0x8000
12376           && imm_expr.X_add_number < 0x8000)
12377         {
12378           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
12379                        BFD_RELOC_LO16);
12380           break;
12381         }
12382       used_at = 1;
12383       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12384       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
12385       break;
12386
12387     case M_SNE:
12388       if (op[1] == 0)
12389         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
12390       else if (op[2] == 0)
12391         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12392       else
12393         {
12394           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12395           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12396         }
12397       break;
12398
12399     case M_SNE_I:
12400       if (imm_expr.X_add_number == 0)
12401         {
12402           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
12403           break;
12404         }
12405       if (op[1] == 0)
12406         {
12407           as_warn (_("instruction %s: result is always true"),
12408                    ip->insn_mo->name);
12409           macro_build (&expr1, HAVE_32BIT_GPRS ? "addiu" : "daddiu", "t,r,j",
12410                        op[0], 0, BFD_RELOC_LO16);
12411           break;
12412         }
12413       if (CPU_HAS_SEQ (mips_opts.arch)
12414           && -512 <= imm_expr.X_add_number
12415           && imm_expr.X_add_number < 512)
12416         {
12417           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
12418                        (int) imm_expr.X_add_number);
12419           break;
12420         }
12421       if (imm_expr.X_add_number >= 0
12422           && imm_expr.X_add_number < 0x10000)
12423         {
12424           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
12425                        BFD_RELOC_LO16);
12426         }
12427       else if (imm_expr.X_add_number > -0x8000
12428                && imm_expr.X_add_number < 0)
12429         {
12430           imm_expr.X_add_number = -imm_expr.X_add_number;
12431           macro_build (&imm_expr, HAVE_32BIT_GPRS ? "addiu" : "daddiu",
12432                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12433         }
12434       else if (CPU_HAS_SEQ (mips_opts.arch))
12435         {
12436           used_at = 1;
12437           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12438           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
12439           break;
12440         }
12441       else
12442         {
12443           load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12444           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12445           used_at = 1;
12446         }
12447       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
12448       break;
12449
12450     case M_SUB_I:
12451       s = "addi";
12452       s2 = "sub";
12453       goto do_subi;
12454     case M_SUBU_I:
12455       s = "addiu";
12456       s2 = "subu";
12457       goto do_subi;
12458     case M_DSUB_I:
12459       dbl = 1;
12460       s = "daddi";
12461       s2 = "dsub";
12462       if (!mips_opts.micromips)
12463         goto do_subi;
12464       if (imm_expr.X_add_number > -0x200
12465           && imm_expr.X_add_number <= 0x200)
12466         {
12467           macro_build (NULL, s, "t,r,.", op[0], op[1],
12468                        (int) -imm_expr.X_add_number);
12469           break;
12470         }
12471       goto do_subi_i;
12472     case M_DSUBU_I:
12473       dbl = 1;
12474       s = "daddiu";
12475       s2 = "dsubu";
12476     do_subi:
12477       if (imm_expr.X_add_number > -0x8000
12478           && imm_expr.X_add_number <= 0x8000)
12479         {
12480           imm_expr.X_add_number = -imm_expr.X_add_number;
12481           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12482           break;
12483         }
12484     do_subi_i:
12485       used_at = 1;
12486       load_register (AT, &imm_expr, dbl);
12487       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
12488       break;
12489
12490     case M_TEQ_I:
12491       s = "teq";
12492       goto trap;
12493     case M_TGE_I:
12494       s = "tge";
12495       goto trap;
12496     case M_TGEU_I:
12497       s = "tgeu";
12498       goto trap;
12499     case M_TLT_I:
12500       s = "tlt";
12501       goto trap;
12502     case M_TLTU_I:
12503       s = "tltu";
12504       goto trap;
12505     case M_TNE_I:
12506       s = "tne";
12507     trap:
12508       used_at = 1;
12509       load_register (AT, &imm_expr, HAVE_64BIT_GPRS);
12510       macro_build (NULL, s, "s,t", op[0], AT);
12511       break;
12512
12513     case M_TRUNCWS:
12514     case M_TRUNCWD:
12515       gas_assert (!mips_opts.micromips);
12516       gas_assert (mips_opts.isa == ISA_MIPS1);
12517       used_at = 1;
12518
12519       /*
12520        * Is the double cfc1 instruction a bug in the mips assembler;
12521        * or is there a reason for it?
12522        */
12523       start_noreorder ();
12524       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12525       macro_build (NULL, "cfc1", "t,G", op[2], RA);
12526       macro_build (NULL, "nop", "");
12527       expr1.X_add_number = 3;
12528       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
12529       expr1.X_add_number = 2;
12530       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
12531       macro_build (NULL, "ctc1", "t,G", AT, RA);
12532       macro_build (NULL, "nop", "");
12533       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
12534                    op[0], op[1]);
12535       macro_build (NULL, "ctc1", "t,G", op[2], RA);
12536       macro_build (NULL, "nop", "");
12537       end_noreorder ();
12538       break;
12539
12540     case M_ULH_AB:
12541       s = "lb";
12542       s2 = "lbu";
12543       off = 1;
12544       goto uld_st;
12545     case M_ULHU_AB:
12546       s = "lbu";
12547       s2 = "lbu";
12548       off = 1;
12549       goto uld_st;
12550     case M_ULW_AB:
12551       s = "lwl";
12552       s2 = "lwr";
12553       offbits = (mips_opts.micromips ? 12 : 16);
12554       off = 3;
12555       goto uld_st;
12556     case M_ULD_AB:
12557       s = "ldl";
12558       s2 = "ldr";
12559       offbits = (mips_opts.micromips ? 12 : 16);
12560       off = 7;
12561       goto uld_st;
12562     case M_USH_AB:
12563       s = "sb";
12564       s2 = "sb";
12565       off = 1;
12566       ust = 1;
12567       goto uld_st;
12568     case M_USW_AB:
12569       s = "swl";
12570       s2 = "swr";
12571       offbits = (mips_opts.micromips ? 12 : 16);
12572       off = 3;
12573       ust = 1;
12574       goto uld_st;
12575     case M_USD_AB:
12576       s = "sdl";
12577       s2 = "sdr";
12578       offbits = (mips_opts.micromips ? 12 : 16);
12579       off = 7;
12580       ust = 1;
12581
12582     uld_st:
12583       breg = op[2];
12584       large_offset = !small_offset_p (off, align, offbits);
12585       ep = &offset_expr;
12586       expr1.X_add_number = 0;
12587       if (large_offset)
12588         {
12589           used_at = 1;
12590           tempreg = AT;
12591           if (small_offset_p (0, align, 16))
12592             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
12593                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
12594           else
12595             {
12596               load_address (tempreg, ep, &used_at);
12597               if (breg != 0)
12598                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12599                              tempreg, tempreg, breg);
12600             }
12601           offset_reloc[0] = BFD_RELOC_LO16;
12602           offset_reloc[1] = BFD_RELOC_UNUSED;
12603           offset_reloc[2] = BFD_RELOC_UNUSED;
12604           breg = tempreg;
12605           tempreg = op[0];
12606           ep = &expr1;
12607         }
12608       else if (!ust && op[0] == breg)
12609         {
12610           used_at = 1;
12611           tempreg = AT;
12612         }
12613       else
12614         tempreg = op[0];
12615
12616       if (off == 1)
12617         goto ulh_sh;
12618
12619       if (!target_big_endian)
12620         ep->X_add_number += off;
12621       if (offbits == 12)
12622         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
12623       else
12624         macro_build (ep, s, "t,o(b)", tempreg, -1,
12625                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12626
12627       if (!target_big_endian)
12628         ep->X_add_number -= off;
12629       else
12630         ep->X_add_number += off;
12631       if (offbits == 12)
12632         macro_build (NULL, s2, "t,~(b)",
12633                      tempreg, (int) ep->X_add_number, breg);
12634       else
12635         macro_build (ep, s2, "t,o(b)", tempreg, -1,
12636                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12637
12638       /* If necessary, move the result in tempreg to the final destination.  */
12639       if (!ust && op[0] != tempreg)
12640         {
12641           /* Protect second load's delay slot.  */
12642           load_delay_nop ();
12643           move_register (op[0], tempreg);
12644         }
12645       break;
12646
12647     ulh_sh:
12648       used_at = 1;
12649       if (target_big_endian == ust)
12650         ep->X_add_number += off;
12651       tempreg = ust || large_offset ? op[0] : AT;
12652       macro_build (ep, s, "t,o(b)", tempreg, -1,
12653                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12654
12655       /* For halfword transfers we need a temporary register to shuffle
12656          bytes.  Unfortunately for M_USH_A we have none available before
12657          the next store as AT holds the base address.  We deal with this
12658          case by clobbering TREG and then restoring it as with ULH.  */
12659       tempreg = ust == large_offset ? op[0] : AT;
12660       if (ust)
12661         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
12662
12663       if (target_big_endian == ust)
12664         ep->X_add_number -= off;
12665       else
12666         ep->X_add_number += off;
12667       macro_build (ep, s2, "t,o(b)", tempreg, -1,
12668                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
12669
12670       /* For M_USH_A re-retrieve the LSB.  */
12671       if (ust && large_offset)
12672         {
12673           if (target_big_endian)
12674             ep->X_add_number += off;
12675           else
12676             ep->X_add_number -= off;
12677           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
12678                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
12679         }
12680       /* For ULH and M_USH_A OR the LSB in.  */
12681       if (!ust || large_offset)
12682         {
12683           tempreg = !large_offset ? AT : op[0];
12684           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
12685           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12686         }
12687       break;
12688
12689     default:
12690       /* FIXME: Check if this is one of the itbl macros, since they
12691          are added dynamically.  */
12692       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
12693       break;
12694     }
12695   if (!mips_opts.at && used_at)
12696     as_bad (_("macro used $at after \".set noat\""));
12697 }
12698
12699 /* Implement macros in mips16 mode.  */
12700
12701 static void
12702 mips16_macro (struct mips_cl_insn *ip)
12703 {
12704   const struct mips_operand_array *operands;
12705   int mask;
12706   int tmp;
12707   expressionS expr1;
12708   int dbl;
12709   const char *s, *s2, *s3;
12710   unsigned int op[MAX_OPERANDS];
12711   unsigned int i;
12712
12713   mask = ip->insn_mo->mask;
12714
12715   operands = insn_operands (ip);
12716   for (i = 0; i < MAX_OPERANDS; i++)
12717     if (operands->operand[i])
12718       op[i] = insn_extract_operand (ip, operands->operand[i]);
12719     else
12720       op[i] = -1;
12721
12722   expr1.X_op = O_constant;
12723   expr1.X_op_symbol = NULL;
12724   expr1.X_add_symbol = NULL;
12725   expr1.X_add_number = 1;
12726
12727   dbl = 0;
12728
12729   switch (mask)
12730     {
12731     default:
12732       abort ();
12733
12734     case M_DDIV_3:
12735       dbl = 1;
12736     case M_DIV_3:
12737       s = "mflo";
12738       goto do_div3;
12739     case M_DREM_3:
12740       dbl = 1;
12741     case M_REM_3:
12742       s = "mfhi";
12743     do_div3:
12744       start_noreorder ();
12745       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
12746       expr1.X_add_number = 2;
12747       macro_build (&expr1, "bnez", "x,p", op[2]);
12748       macro_build (NULL, "break", "6", 7);
12749
12750       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
12751          since that causes an overflow.  We should do that as well,
12752          but I don't see how to do the comparisons without a temporary
12753          register.  */
12754       end_noreorder ();
12755       macro_build (NULL, s, "x", op[0]);
12756       break;
12757
12758     case M_DIVU_3:
12759       s = "divu";
12760       s2 = "mflo";
12761       goto do_divu3;
12762     case M_REMU_3:
12763       s = "divu";
12764       s2 = "mfhi";
12765       goto do_divu3;
12766     case M_DDIVU_3:
12767       s = "ddivu";
12768       s2 = "mflo";
12769       goto do_divu3;
12770     case M_DREMU_3:
12771       s = "ddivu";
12772       s2 = "mfhi";
12773     do_divu3:
12774       start_noreorder ();
12775       macro_build (NULL, s, "0,x,y", op[1], op[2]);
12776       expr1.X_add_number = 2;
12777       macro_build (&expr1, "bnez", "x,p", op[2]);
12778       macro_build (NULL, "break", "6", 7);
12779       end_noreorder ();
12780       macro_build (NULL, s2, "x", op[0]);
12781       break;
12782
12783     case M_DMUL:
12784       dbl = 1;
12785     case M_MUL:
12786       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
12787       macro_build (NULL, "mflo", "x", op[0]);
12788       break;
12789
12790     case M_DSUBU_I:
12791       dbl = 1;
12792       goto do_subu;
12793     case M_SUBU_I:
12794     do_subu:
12795       imm_expr.X_add_number = -imm_expr.X_add_number;
12796       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
12797       break;
12798
12799     case M_SUBU_I_2:
12800       imm_expr.X_add_number = -imm_expr.X_add_number;
12801       macro_build (&imm_expr, "addiu", "x,k", op[0]);
12802       break;
12803
12804     case M_DSUBU_I_2:
12805       imm_expr.X_add_number = -imm_expr.X_add_number;
12806       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
12807       break;
12808
12809     case M_BEQ:
12810       s = "cmp";
12811       s2 = "bteqz";
12812       goto do_branch;
12813     case M_BNE:
12814       s = "cmp";
12815       s2 = "btnez";
12816       goto do_branch;
12817     case M_BLT:
12818       s = "slt";
12819       s2 = "btnez";
12820       goto do_branch;
12821     case M_BLTU:
12822       s = "sltu";
12823       s2 = "btnez";
12824       goto do_branch;
12825     case M_BLE:
12826       s = "slt";
12827       s2 = "bteqz";
12828       goto do_reverse_branch;
12829     case M_BLEU:
12830       s = "sltu";
12831       s2 = "bteqz";
12832       goto do_reverse_branch;
12833     case M_BGE:
12834       s = "slt";
12835       s2 = "bteqz";
12836       goto do_branch;
12837     case M_BGEU:
12838       s = "sltu";
12839       s2 = "bteqz";
12840       goto do_branch;
12841     case M_BGT:
12842       s = "slt";
12843       s2 = "btnez";
12844       goto do_reverse_branch;
12845     case M_BGTU:
12846       s = "sltu";
12847       s2 = "btnez";
12848
12849     do_reverse_branch:
12850       tmp = op[1];
12851       op[1] = op[0];
12852       op[0] = tmp;
12853
12854     do_branch:
12855       macro_build (NULL, s, "x,y", op[0], op[1]);
12856       macro_build (&offset_expr, s2, "p");
12857       break;
12858
12859     case M_BEQ_I:
12860       s = "cmpi";
12861       s2 = "bteqz";
12862       s3 = "x,U";
12863       goto do_branch_i;
12864     case M_BNE_I:
12865       s = "cmpi";
12866       s2 = "btnez";
12867       s3 = "x,U";
12868       goto do_branch_i;
12869     case M_BLT_I:
12870       s = "slti";
12871       s2 = "btnez";
12872       s3 = "x,8";
12873       goto do_branch_i;
12874     case M_BLTU_I:
12875       s = "sltiu";
12876       s2 = "btnez";
12877       s3 = "x,8";
12878       goto do_branch_i;
12879     case M_BLE_I:
12880       s = "slti";
12881       s2 = "btnez";
12882       s3 = "x,8";
12883       goto do_addone_branch_i;
12884     case M_BLEU_I:
12885       s = "sltiu";
12886       s2 = "btnez";
12887       s3 = "x,8";
12888       goto do_addone_branch_i;
12889     case M_BGE_I:
12890       s = "slti";
12891       s2 = "bteqz";
12892       s3 = "x,8";
12893       goto do_branch_i;
12894     case M_BGEU_I:
12895       s = "sltiu";
12896       s2 = "bteqz";
12897       s3 = "x,8";
12898       goto do_branch_i;
12899     case M_BGT_I:
12900       s = "slti";
12901       s2 = "bteqz";
12902       s3 = "x,8";
12903       goto do_addone_branch_i;
12904     case M_BGTU_I:
12905       s = "sltiu";
12906       s2 = "bteqz";
12907       s3 = "x,8";
12908
12909     do_addone_branch_i:
12910       ++imm_expr.X_add_number;
12911
12912     do_branch_i:
12913       macro_build (&imm_expr, s, s3, op[0]);
12914       macro_build (&offset_expr, s2, "p");
12915       break;
12916
12917     case M_ABS:
12918       expr1.X_add_number = 0;
12919       macro_build (&expr1, "slti", "x,8", op[1]);
12920       if (op[0] != op[1])
12921         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
12922       expr1.X_add_number = 2;
12923       macro_build (&expr1, "bteqz", "p");
12924       macro_build (NULL, "neg", "x,w", op[0], op[0]);
12925       break;
12926     }
12927 }
12928
12929 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
12930    opcode bits in *OPCODE_EXTRA.  */
12931
12932 static struct mips_opcode *
12933 mips_lookup_insn (struct hash_control *hash, const char *start,
12934                   ssize_t length, unsigned int *opcode_extra)
12935 {
12936   char *name, *dot, *p;
12937   unsigned int mask, suffix;
12938   ssize_t opend;
12939   struct mips_opcode *insn;
12940
12941   /* Make a copy of the instruction so that we can fiddle with it.  */
12942   name = alloca (length + 1);
12943   memcpy (name, start, length);
12944   name[length] = '\0';
12945
12946   /* Look up the instruction as-is.  */
12947   insn = (struct mips_opcode *) hash_find (hash, name);
12948   if (insn)
12949     return insn;
12950
12951   dot = strchr (name, '.');
12952   if (dot && dot[1])
12953     {
12954       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
12955       p = mips_parse_vu0_channels (dot + 1, &mask);
12956       if (*p == 0 && mask != 0)
12957         {
12958           *dot = 0;
12959           insn = (struct mips_opcode *) hash_find (hash, name);
12960           *dot = '.';
12961           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
12962             {
12963               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
12964               return insn;
12965             }
12966         }
12967     }
12968
12969   if (mips_opts.micromips)
12970     {
12971       /* See if there's an instruction size override suffix,
12972          either `16' or `32', at the end of the mnemonic proper,
12973          that defines the operation, i.e. before the first `.'
12974          character if any.  Strip it and retry.  */
12975       opend = dot != NULL ? dot - name : length;
12976       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
12977         suffix = 2;
12978       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
12979         suffix = 4;
12980       else
12981         suffix = 0;
12982       if (suffix)
12983         {
12984           memcpy (name + opend - 2, name + opend, length - opend + 1);
12985           insn = (struct mips_opcode *) hash_find (hash, name);
12986           if (insn)
12987             {
12988               forced_insn_length = suffix;
12989               return insn;
12990             }
12991         }
12992     }
12993
12994   return NULL;
12995 }
12996
12997 /* Assemble an instruction into its binary format.  If the instruction
12998    is a macro, set imm_expr and offset_expr to the values associated
12999    with "I" and "A" operands respectively.  Otherwise store the value
13000    of the relocatable field (if any) in offset_expr.  In both cases
13001    set offset_reloc to the relocation operators applied to offset_expr.  */
13002
13003 static void
13004 mips_ip (char *str, struct mips_cl_insn *insn)
13005 {
13006   const struct mips_opcode *first, *past;
13007   struct hash_control *hash;
13008   char format;
13009   size_t end;
13010   struct mips_operand_token *tokens;
13011   unsigned int opcode_extra;
13012
13013   if (mips_opts.micromips)
13014     {
13015       hash = micromips_op_hash;
13016       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13017     }
13018   else
13019     {
13020       hash = op_hash;
13021       past = &mips_opcodes[NUMOPCODES];
13022     }
13023   forced_insn_length = 0;
13024   opcode_extra = 0;
13025
13026   /* We first try to match an instruction up to a space or to the end.  */
13027   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13028     continue;
13029
13030   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13031   if (first == NULL)
13032     {
13033       set_insn_error (0, _("unrecognized opcode"));
13034       return;
13035     }
13036
13037   if (strcmp (first->name, "li.s") == 0)
13038     format = 'f';
13039   else if (strcmp (first->name, "li.d") == 0)
13040     format = 'd';
13041   else
13042     format = 0;
13043   tokens = mips_parse_arguments (str + end, format);
13044   if (!tokens)
13045     return;
13046
13047   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13048       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13049     set_insn_error (0, _("invalid operands"));
13050
13051   obstack_free (&mips_operand_tokens, tokens);
13052 }
13053
13054 /* As for mips_ip, but used when assembling MIPS16 code.
13055    Also set forced_insn_length to the resulting instruction size in
13056    bytes if the user explicitly requested a small or extended instruction.  */
13057
13058 static void
13059 mips16_ip (char *str, struct mips_cl_insn *insn)
13060 {
13061   char *end, *s, c;
13062   struct mips_opcode *first;
13063   struct mips_operand_token *tokens;
13064
13065   forced_insn_length = 0;
13066
13067   for (s = str; ISLOWER (*s); ++s)
13068     ;
13069   end = s;
13070   c = *end;
13071   switch (c)
13072     {
13073     case '\0':
13074       break;
13075
13076     case ' ':
13077       s++;
13078       break;
13079
13080     case '.':
13081       if (s[1] == 't' && s[2] == ' ')
13082         {
13083           forced_insn_length = 2;
13084           s += 3;
13085           break;
13086         }
13087       else if (s[1] == 'e' && s[2] == ' ')
13088         {
13089           forced_insn_length = 4;
13090           s += 3;
13091           break;
13092         }
13093       /* Fall through.  */
13094     default:
13095       set_insn_error (0, _("unrecognized opcode"));
13096       return;
13097     }
13098
13099   if (mips_opts.noautoextend && !forced_insn_length)
13100     forced_insn_length = 2;
13101
13102   *end = 0;
13103   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13104   *end = c;
13105
13106   if (!first)
13107     {
13108       set_insn_error (0, _("unrecognized opcode"));
13109       return;
13110     }
13111
13112   tokens = mips_parse_arguments (s, 0);
13113   if (!tokens)
13114     return;
13115
13116   if (!match_mips16_insns (insn, first, tokens))
13117     set_insn_error (0, _("invalid operands"));
13118
13119   obstack_free (&mips_operand_tokens, tokens);
13120 }
13121
13122 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13123    NBITS is the number of significant bits in VAL.  */
13124
13125 static unsigned long
13126 mips16_immed_extend (offsetT val, unsigned int nbits)
13127 {
13128   int extval;
13129   if (nbits == 16)
13130     {
13131       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13132       val &= 0x1f;
13133     }
13134   else if (nbits == 15)
13135     {
13136       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13137       val &= 0xf;
13138     }
13139   else
13140     {
13141       extval = ((val & 0x1f) << 6) | (val & 0x20);
13142       val = 0;
13143     }
13144   return (extval << 16) | val;
13145 }
13146
13147 /* Like decode_mips16_operand, but require the operand to be defined and
13148    require it to be an integer.  */
13149
13150 static const struct mips_int_operand *
13151 mips16_immed_operand (int type, bfd_boolean extended_p)
13152 {
13153   const struct mips_operand *operand;
13154
13155   operand = decode_mips16_operand (type, extended_p);
13156   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13157     abort ();
13158   return (const struct mips_int_operand *) operand;
13159 }
13160
13161 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13162
13163 static bfd_boolean
13164 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13165                          bfd_reloc_code_real_type reloc, offsetT sval)
13166 {
13167   int min_val, max_val;
13168
13169   min_val = mips_int_operand_min (operand);
13170   max_val = mips_int_operand_max (operand);
13171   if (reloc != BFD_RELOC_UNUSED)
13172     {
13173       if (min_val < 0)
13174         sval = SEXT_16BIT (sval);
13175       else
13176         sval &= 0xffff;
13177     }
13178
13179   return (sval >= min_val
13180           && sval <= max_val
13181           && (sval & ((1 << operand->shift) - 1)) == 0);
13182 }
13183
13184 /* Install immediate value VAL into MIPS16 instruction *INSN,
13185    extending it if necessary.  The instruction in *INSN may
13186    already be extended.
13187
13188    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13189    if none.  In the former case, VAL is a 16-bit number with no
13190    defined signedness.
13191
13192    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13193    is the length that the user requested, or 0 if none.  */
13194
13195 static void
13196 mips16_immed (char *file, unsigned int line, int type,
13197               bfd_reloc_code_real_type reloc, offsetT val,
13198               unsigned int user_insn_length, unsigned long *insn)
13199 {
13200   const struct mips_int_operand *operand;
13201   unsigned int uval, length;
13202
13203   operand = mips16_immed_operand (type, FALSE);
13204   if (!mips16_immed_in_range_p (operand, reloc, val))
13205     {
13206       /* We need an extended instruction.  */
13207       if (user_insn_length == 2)
13208         as_bad_where (file, line, _("invalid unextended operand value"));
13209       else
13210         *insn |= MIPS16_EXTEND;
13211     }
13212   else if (user_insn_length == 4)
13213     {
13214       /* The operand doesn't force an unextended instruction to be extended.
13215          Warn if the user wanted an extended instruction anyway.  */
13216       *insn |= MIPS16_EXTEND;
13217       as_warn_where (file, line,
13218                      _("extended operand requested but not required"));
13219     }
13220
13221   length = mips16_opcode_length (*insn);
13222   if (length == 4)
13223     {
13224       operand = mips16_immed_operand (type, TRUE);
13225       if (!mips16_immed_in_range_p (operand, reloc, val))
13226         as_bad_where (file, line,
13227                       _("operand value out of range for instruction"));
13228     }
13229   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13230   if (length == 2)
13231     *insn = mips_insert_operand (&operand->root, *insn, uval);
13232   else
13233     *insn |= mips16_immed_extend (uval, operand->root.size);
13234 }
13235 \f
13236 struct percent_op_match
13237 {
13238   const char *str;
13239   bfd_reloc_code_real_type reloc;
13240 };
13241
13242 static const struct percent_op_match mips_percent_op[] =
13243 {
13244   {"%lo", BFD_RELOC_LO16},
13245   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13246   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13247   {"%call16", BFD_RELOC_MIPS_CALL16},
13248   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13249   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13250   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13251   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13252   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13253   {"%got", BFD_RELOC_MIPS_GOT16},
13254   {"%gp_rel", BFD_RELOC_GPREL16},
13255   {"%half", BFD_RELOC_16},
13256   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13257   {"%higher", BFD_RELOC_MIPS_HIGHER},
13258   {"%neg", BFD_RELOC_MIPS_SUB},
13259   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13260   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13261   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13262   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13263   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13264   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13265   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13266   {"%hi", BFD_RELOC_HI16_S}
13267 };
13268
13269 static const struct percent_op_match mips16_percent_op[] =
13270 {
13271   {"%lo", BFD_RELOC_MIPS16_LO16},
13272   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13273   {"%got", BFD_RELOC_MIPS16_GOT16},
13274   {"%call16", BFD_RELOC_MIPS16_CALL16},
13275   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13276   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13277   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13278   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13279   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13280   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13281   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13282   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13283 };
13284
13285
13286 /* Return true if *STR points to a relocation operator.  When returning true,
13287    move *STR over the operator and store its relocation code in *RELOC.
13288    Leave both *STR and *RELOC alone when returning false.  */
13289
13290 static bfd_boolean
13291 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13292 {
13293   const struct percent_op_match *percent_op;
13294   size_t limit, i;
13295
13296   if (mips_opts.mips16)
13297     {
13298       percent_op = mips16_percent_op;
13299       limit = ARRAY_SIZE (mips16_percent_op);
13300     }
13301   else
13302     {
13303       percent_op = mips_percent_op;
13304       limit = ARRAY_SIZE (mips_percent_op);
13305     }
13306
13307   for (i = 0; i < limit; i++)
13308     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13309       {
13310         int len = strlen (percent_op[i].str);
13311
13312         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13313           continue;
13314
13315         *str += strlen (percent_op[i].str);
13316         *reloc = percent_op[i].reloc;
13317
13318         /* Check whether the output BFD supports this relocation.
13319            If not, issue an error and fall back on something safe.  */
13320         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13321           {
13322             as_bad (_("relocation %s isn't supported by the current ABI"),
13323                     percent_op[i].str);
13324             *reloc = BFD_RELOC_UNUSED;
13325           }
13326         return TRUE;
13327       }
13328   return FALSE;
13329 }
13330
13331
13332 /* Parse string STR as a 16-bit relocatable operand.  Store the
13333    expression in *EP and the relocations in the array starting
13334    at RELOC.  Return the number of relocation operators used.
13335
13336    On exit, EXPR_END points to the first character after the expression.  */
13337
13338 static size_t
13339 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13340                        char *str)
13341 {
13342   bfd_reloc_code_real_type reversed_reloc[3];
13343   size_t reloc_index, i;
13344   int crux_depth, str_depth;
13345   char *crux;
13346
13347   /* Search for the start of the main expression, recoding relocations
13348      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13349      of the main expression and with CRUX_DEPTH containing the number
13350      of open brackets at that point.  */
13351   reloc_index = -1;
13352   str_depth = 0;
13353   do
13354     {
13355       reloc_index++;
13356       crux = str;
13357       crux_depth = str_depth;
13358
13359       /* Skip over whitespace and brackets, keeping count of the number
13360          of brackets.  */
13361       while (*str == ' ' || *str == '\t' || *str == '(')
13362         if (*str++ == '(')
13363           str_depth++;
13364     }
13365   while (*str == '%'
13366          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13367          && parse_relocation (&str, &reversed_reloc[reloc_index]));
13368
13369   my_getExpression (ep, crux);
13370   str = expr_end;
13371
13372   /* Match every open bracket.  */
13373   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
13374     if (*str++ == ')')
13375       crux_depth--;
13376
13377   if (crux_depth > 0)
13378     as_bad (_("unclosed '('"));
13379
13380   expr_end = str;
13381
13382   if (reloc_index != 0)
13383     {
13384       prev_reloc_op_frag = frag_now;
13385       for (i = 0; i < reloc_index; i++)
13386         reloc[i] = reversed_reloc[reloc_index - 1 - i];
13387     }
13388
13389   return reloc_index;
13390 }
13391
13392 static void
13393 my_getExpression (expressionS *ep, char *str)
13394 {
13395   char *save_in;
13396
13397   save_in = input_line_pointer;
13398   input_line_pointer = str;
13399   expression (ep);
13400   expr_end = input_line_pointer;
13401   input_line_pointer = save_in;
13402 }
13403
13404 char *
13405 md_atof (int type, char *litP, int *sizeP)
13406 {
13407   return ieee_md_atof (type, litP, sizeP, target_big_endian);
13408 }
13409
13410 void
13411 md_number_to_chars (char *buf, valueT val, int n)
13412 {
13413   if (target_big_endian)
13414     number_to_chars_bigendian (buf, val, n);
13415   else
13416     number_to_chars_littleendian (buf, val, n);
13417 }
13418 \f
13419 static int support_64bit_objects(void)
13420 {
13421   const char **list, **l;
13422   int yes;
13423
13424   list = bfd_target_list ();
13425   for (l = list; *l != NULL; l++)
13426     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
13427         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
13428       break;
13429   yes = (*l != NULL);
13430   free (list);
13431   return yes;
13432 }
13433
13434 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
13435    NEW_VALUE.  Warn if another value was already specified.  Note:
13436    we have to defer parsing the -march and -mtune arguments in order
13437    to handle 'from-abi' correctly, since the ABI might be specified
13438    in a later argument.  */
13439
13440 static void
13441 mips_set_option_string (const char **string_ptr, const char *new_value)
13442 {
13443   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
13444     as_warn (_("a different %s was already specified, is now %s"),
13445              string_ptr == &mips_arch_string ? "-march" : "-mtune",
13446              new_value);
13447
13448   *string_ptr = new_value;
13449 }
13450
13451 int
13452 md_parse_option (int c, char *arg)
13453 {
13454   unsigned int i;
13455
13456   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
13457     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
13458       {
13459         file_ase_explicit |= mips_set_ase (&mips_ases[i],
13460                                            c == mips_ases[i].option_on);
13461         return 1;
13462       }
13463
13464   switch (c)
13465     {
13466     case OPTION_CONSTRUCT_FLOATS:
13467       mips_disable_float_construction = 0;
13468       break;
13469
13470     case OPTION_NO_CONSTRUCT_FLOATS:
13471       mips_disable_float_construction = 1;
13472       break;
13473
13474     case OPTION_TRAP:
13475       mips_trap = 1;
13476       break;
13477
13478     case OPTION_BREAK:
13479       mips_trap = 0;
13480       break;
13481
13482     case OPTION_EB:
13483       target_big_endian = 1;
13484       break;
13485
13486     case OPTION_EL:
13487       target_big_endian = 0;
13488       break;
13489
13490     case 'O':
13491       if (arg == NULL)
13492         mips_optimize = 1;
13493       else if (arg[0] == '0')
13494         mips_optimize = 0;
13495       else if (arg[0] == '1')
13496         mips_optimize = 1;
13497       else
13498         mips_optimize = 2;
13499       break;
13500
13501     case 'g':
13502       if (arg == NULL)
13503         mips_debug = 2;
13504       else
13505         mips_debug = atoi (arg);
13506       break;
13507
13508     case OPTION_MIPS1:
13509       file_mips_isa = ISA_MIPS1;
13510       break;
13511
13512     case OPTION_MIPS2:
13513       file_mips_isa = ISA_MIPS2;
13514       break;
13515
13516     case OPTION_MIPS3:
13517       file_mips_isa = ISA_MIPS3;
13518       break;
13519
13520     case OPTION_MIPS4:
13521       file_mips_isa = ISA_MIPS4;
13522       break;
13523
13524     case OPTION_MIPS5:
13525       file_mips_isa = ISA_MIPS5;
13526       break;
13527
13528     case OPTION_MIPS32:
13529       file_mips_isa = ISA_MIPS32;
13530       break;
13531
13532     case OPTION_MIPS32R2:
13533       file_mips_isa = ISA_MIPS32R2;
13534       break;
13535
13536     case OPTION_MIPS64R2:
13537       file_mips_isa = ISA_MIPS64R2;
13538       break;
13539
13540     case OPTION_MIPS64:
13541       file_mips_isa = ISA_MIPS64;
13542       break;
13543
13544     case OPTION_MTUNE:
13545       mips_set_option_string (&mips_tune_string, arg);
13546       break;
13547
13548     case OPTION_MARCH:
13549       mips_set_option_string (&mips_arch_string, arg);
13550       break;
13551
13552     case OPTION_M4650:
13553       mips_set_option_string (&mips_arch_string, "4650");
13554       mips_set_option_string (&mips_tune_string, "4650");
13555       break;
13556
13557     case OPTION_NO_M4650:
13558       break;
13559
13560     case OPTION_M4010:
13561       mips_set_option_string (&mips_arch_string, "4010");
13562       mips_set_option_string (&mips_tune_string, "4010");
13563       break;
13564
13565     case OPTION_NO_M4010:
13566       break;
13567
13568     case OPTION_M4100:
13569       mips_set_option_string (&mips_arch_string, "4100");
13570       mips_set_option_string (&mips_tune_string, "4100");
13571       break;
13572
13573     case OPTION_NO_M4100:
13574       break;
13575
13576     case OPTION_M3900:
13577       mips_set_option_string (&mips_arch_string, "3900");
13578       mips_set_option_string (&mips_tune_string, "3900");
13579       break;
13580
13581     case OPTION_NO_M3900:
13582       break;
13583
13584     case OPTION_MICROMIPS:
13585       if (mips_opts.mips16 == 1)
13586         {
13587           as_bad (_("-mmicromips cannot be used with -mips16"));
13588           return 0;
13589         }
13590       mips_opts.micromips = 1;
13591       mips_no_prev_insn ();
13592       break;
13593
13594     case OPTION_NO_MICROMIPS:
13595       mips_opts.micromips = 0;
13596       mips_no_prev_insn ();
13597       break;
13598
13599     case OPTION_MIPS16:
13600       if (mips_opts.micromips == 1)
13601         {
13602           as_bad (_("-mips16 cannot be used with -micromips"));
13603           return 0;
13604         }
13605       mips_opts.mips16 = 1;
13606       mips_no_prev_insn ();
13607       break;
13608
13609     case OPTION_NO_MIPS16:
13610       mips_opts.mips16 = 0;
13611       mips_no_prev_insn ();
13612       break;
13613
13614     case OPTION_FIX_24K:
13615       mips_fix_24k = 1;
13616       break;
13617
13618     case OPTION_NO_FIX_24K:
13619       mips_fix_24k = 0;
13620       break;
13621
13622     case OPTION_FIX_RM7000:
13623       mips_fix_rm7000 = 1;
13624       break;
13625
13626     case OPTION_NO_FIX_RM7000:
13627       mips_fix_rm7000 = 0;
13628       break;
13629
13630     case OPTION_FIX_LOONGSON2F_JUMP:
13631       mips_fix_loongson2f_jump = TRUE;
13632       break;
13633
13634     case OPTION_NO_FIX_LOONGSON2F_JUMP:
13635       mips_fix_loongson2f_jump = FALSE;
13636       break;
13637
13638     case OPTION_FIX_LOONGSON2F_NOP:
13639       mips_fix_loongson2f_nop = TRUE;
13640       break;
13641
13642     case OPTION_NO_FIX_LOONGSON2F_NOP:
13643       mips_fix_loongson2f_nop = FALSE;
13644       break;
13645
13646     case OPTION_FIX_VR4120:
13647       mips_fix_vr4120 = 1;
13648       break;
13649
13650     case OPTION_NO_FIX_VR4120:
13651       mips_fix_vr4120 = 0;
13652       break;
13653
13654     case OPTION_FIX_VR4130:
13655       mips_fix_vr4130 = 1;
13656       break;
13657
13658     case OPTION_NO_FIX_VR4130:
13659       mips_fix_vr4130 = 0;
13660       break;
13661
13662     case OPTION_FIX_CN63XXP1:
13663       mips_fix_cn63xxp1 = TRUE;
13664       break;
13665
13666     case OPTION_NO_FIX_CN63XXP1:
13667       mips_fix_cn63xxp1 = FALSE;
13668       break;
13669
13670     case OPTION_RELAX_BRANCH:
13671       mips_relax_branch = 1;
13672       break;
13673
13674     case OPTION_NO_RELAX_BRANCH:
13675       mips_relax_branch = 0;
13676       break;
13677
13678     case OPTION_INSN32:
13679       mips_opts.insn32 = TRUE;
13680       break;
13681
13682     case OPTION_NO_INSN32:
13683       mips_opts.insn32 = FALSE;
13684       break;
13685
13686     case OPTION_MSHARED:
13687       mips_in_shared = TRUE;
13688       break;
13689
13690     case OPTION_MNO_SHARED:
13691       mips_in_shared = FALSE;
13692       break;
13693
13694     case OPTION_MSYM32:
13695       mips_opts.sym32 = TRUE;
13696       break;
13697
13698     case OPTION_MNO_SYM32:
13699       mips_opts.sym32 = FALSE;
13700       break;
13701
13702       /* When generating ELF code, we permit -KPIC and -call_shared to
13703          select SVR4_PIC, and -non_shared to select no PIC.  This is
13704          intended to be compatible with Irix 5.  */
13705     case OPTION_CALL_SHARED:
13706       mips_pic = SVR4_PIC;
13707       mips_abicalls = TRUE;
13708       break;
13709
13710     case OPTION_CALL_NONPIC:
13711       mips_pic = NO_PIC;
13712       mips_abicalls = TRUE;
13713       break;
13714
13715     case OPTION_NON_SHARED:
13716       mips_pic = NO_PIC;
13717       mips_abicalls = FALSE;
13718       break;
13719
13720       /* The -xgot option tells the assembler to use 32 bit offsets
13721          when accessing the got in SVR4_PIC mode.  It is for Irix
13722          compatibility.  */
13723     case OPTION_XGOT:
13724       mips_big_got = 1;
13725       break;
13726
13727     case 'G':
13728       g_switch_value = atoi (arg);
13729       g_switch_seen = 1;
13730       break;
13731
13732       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
13733          and -mabi=64.  */
13734     case OPTION_32:
13735       mips_abi = O32_ABI;
13736       break;
13737
13738     case OPTION_N32:
13739       mips_abi = N32_ABI;
13740       break;
13741
13742     case OPTION_64:
13743       mips_abi = N64_ABI;
13744       if (!support_64bit_objects())
13745         as_fatal (_("no compiled in support for 64 bit object file format"));
13746       break;
13747
13748     case OPTION_GP32:
13749       file_mips_gp32 = 1;
13750       break;
13751
13752     case OPTION_GP64:
13753       file_mips_gp32 = 0;
13754       break;
13755
13756     case OPTION_FP32:
13757       file_mips_fp32 = 1;
13758       break;
13759
13760     case OPTION_FP64:
13761       file_mips_fp32 = 0;
13762       break;
13763
13764     case OPTION_SINGLE_FLOAT:
13765       file_mips_single_float = 1;
13766       break;
13767
13768     case OPTION_DOUBLE_FLOAT:
13769       file_mips_single_float = 0;
13770       break;
13771
13772     case OPTION_SOFT_FLOAT:
13773       file_mips_soft_float = 1;
13774       break;
13775
13776     case OPTION_HARD_FLOAT:
13777       file_mips_soft_float = 0;
13778       break;
13779
13780     case OPTION_MABI:
13781       if (strcmp (arg, "32") == 0)
13782         mips_abi = O32_ABI;
13783       else if (strcmp (arg, "o64") == 0)
13784         mips_abi = O64_ABI;
13785       else if (strcmp (arg, "n32") == 0)
13786         mips_abi = N32_ABI;
13787       else if (strcmp (arg, "64") == 0)
13788         {
13789           mips_abi = N64_ABI;
13790           if (! support_64bit_objects())
13791             as_fatal (_("no compiled in support for 64 bit object file "
13792                         "format"));
13793         }
13794       else if (strcmp (arg, "eabi") == 0)
13795         mips_abi = EABI_ABI;
13796       else
13797         {
13798           as_fatal (_("invalid abi -mabi=%s"), arg);
13799           return 0;
13800         }
13801       break;
13802
13803     case OPTION_M7000_HILO_FIX:
13804       mips_7000_hilo_fix = TRUE;
13805       break;
13806
13807     case OPTION_MNO_7000_HILO_FIX:
13808       mips_7000_hilo_fix = FALSE;
13809       break;
13810
13811     case OPTION_MDEBUG:
13812       mips_flag_mdebug = TRUE;
13813       break;
13814
13815     case OPTION_NO_MDEBUG:
13816       mips_flag_mdebug = FALSE;
13817       break;
13818
13819     case OPTION_PDR:
13820       mips_flag_pdr = TRUE;
13821       break;
13822
13823     case OPTION_NO_PDR:
13824       mips_flag_pdr = FALSE;
13825       break;
13826
13827     case OPTION_MVXWORKS_PIC:
13828       mips_pic = VXWORKS_PIC;
13829       break;
13830
13831     case OPTION_NAN:
13832       if (strcmp (arg, "2008") == 0)
13833         mips_flag_nan2008 = TRUE;
13834       else if (strcmp (arg, "legacy") == 0)
13835         mips_flag_nan2008 = FALSE;
13836       else
13837         {
13838           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
13839           return 0;
13840         }
13841       break;
13842
13843     default:
13844       return 0;
13845     }
13846
13847     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
13848
13849   return 1;
13850 }
13851 \f
13852 /* Set up globals to generate code for the ISA or processor
13853    described by INFO.  */
13854
13855 static void
13856 mips_set_architecture (const struct mips_cpu_info *info)
13857 {
13858   if (info != 0)
13859     {
13860       file_mips_arch = info->cpu;
13861       mips_opts.arch = info->cpu;
13862       mips_opts.isa = info->isa;
13863     }
13864 }
13865
13866
13867 /* Likewise for tuning.  */
13868
13869 static void
13870 mips_set_tune (const struct mips_cpu_info *info)
13871 {
13872   if (info != 0)
13873     mips_tune = info->cpu;
13874 }
13875
13876
13877 void
13878 mips_after_parse_args (void)
13879 {
13880   const struct mips_cpu_info *arch_info = 0;
13881   const struct mips_cpu_info *tune_info = 0;
13882
13883   /* GP relative stuff not working for PE */
13884   if (strncmp (TARGET_OS, "pe", 2) == 0)
13885     {
13886       if (g_switch_seen && g_switch_value != 0)
13887         as_bad (_("-G not supported in this configuration"));
13888       g_switch_value = 0;
13889     }
13890
13891   if (mips_abi == NO_ABI)
13892     mips_abi = MIPS_DEFAULT_ABI;
13893
13894   /* The following code determines the architecture and register size.
13895      Similar code was added to GCC 3.3 (see override_options() in
13896      config/mips/mips.c).  The GAS and GCC code should be kept in sync
13897      as much as possible.  */
13898
13899   if (mips_arch_string != 0)
13900     arch_info = mips_parse_cpu ("-march", mips_arch_string);
13901
13902   if (file_mips_isa != ISA_UNKNOWN)
13903     {
13904       /* Handle -mipsN.  At this point, file_mips_isa contains the
13905          ISA level specified by -mipsN, while arch_info->isa contains
13906          the -march selection (if any).  */
13907       if (arch_info != 0)
13908         {
13909           /* -march takes precedence over -mipsN, since it is more descriptive.
13910              There's no harm in specifying both as long as the ISA levels
13911              are the same.  */
13912           if (file_mips_isa != arch_info->isa)
13913             as_bad (_("-%s conflicts with the other architecture options,"
13914                       " which imply -%s"),
13915                     mips_cpu_info_from_isa (file_mips_isa)->name,
13916                     mips_cpu_info_from_isa (arch_info->isa)->name);
13917         }
13918       else
13919         arch_info = mips_cpu_info_from_isa (file_mips_isa);
13920     }
13921
13922   if (arch_info == 0)
13923     {
13924       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
13925       gas_assert (arch_info);
13926     }
13927
13928   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
13929     as_bad (_("-march=%s is not compatible with the selected ABI"),
13930             arch_info->name);
13931
13932   mips_set_architecture (arch_info);
13933
13934   /* Optimize for file_mips_arch, unless -mtune selects a different processor.  */
13935   if (mips_tune_string != 0)
13936     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
13937
13938   if (tune_info == 0)
13939     mips_set_tune (arch_info);
13940   else
13941     mips_set_tune (tune_info);
13942
13943   if (file_mips_gp32 >= 0)
13944     {
13945       /* The user specified the size of the integer registers.  Make sure
13946          it agrees with the ABI and ISA.  */
13947       if (file_mips_gp32 == 0 && !ISA_HAS_64BIT_REGS (mips_opts.isa))
13948         as_bad (_("-mgp64 used with a 32-bit processor"));
13949       else if (file_mips_gp32 == 1 && ABI_NEEDS_64BIT_REGS (mips_abi))
13950         as_bad (_("-mgp32 used with a 64-bit ABI"));
13951       else if (file_mips_gp32 == 0 && ABI_NEEDS_32BIT_REGS (mips_abi))
13952         as_bad (_("-mgp64 used with a 32-bit ABI"));
13953     }
13954   else
13955     {
13956       /* Infer the integer register size from the ABI and processor.
13957          Restrict ourselves to 32-bit registers if that's all the
13958          processor has, or if the ABI cannot handle 64-bit registers.  */
13959       file_mips_gp32 = (ABI_NEEDS_32BIT_REGS (mips_abi)
13960                         || !ISA_HAS_64BIT_REGS (mips_opts.isa));
13961     }
13962
13963   switch (file_mips_fp32)
13964     {
13965     default:
13966     case -1:
13967       /* No user specified float register size.
13968          ??? GAS treats single-float processors as though they had 64-bit
13969          float registers (although it complains when double-precision
13970          instructions are used).  As things stand, saying they have 32-bit
13971          registers would lead to spurious "register must be even" messages.
13972          So here we assume float registers are never smaller than the
13973          integer ones.  */
13974       if (file_mips_gp32 == 0)
13975         /* 64-bit integer registers implies 64-bit float registers.  */
13976         file_mips_fp32 = 0;
13977       else if ((mips_opts.ase & FP64_ASES)
13978                && ISA_HAS_64BIT_FPRS (mips_opts.isa))
13979         /* -mips3d and -mdmx imply 64-bit float registers, if possible.  */
13980         file_mips_fp32 = 0;
13981       else
13982         /* 32-bit float registers.  */
13983         file_mips_fp32 = 1;
13984       break;
13985
13986     /* The user specified the size of the float registers.  Check if it
13987        agrees with the ABI and ISA.  */
13988     case 0:
13989       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
13990         as_bad (_("-mfp64 used with a 32-bit fpu"));
13991       else if (ABI_NEEDS_32BIT_REGS (mips_abi)
13992                && !ISA_HAS_MXHC1 (mips_opts.isa))
13993         as_warn (_("-mfp64 used with a 32-bit ABI"));
13994       break;
13995     case 1:
13996       if (ABI_NEEDS_64BIT_REGS (mips_abi))
13997         as_warn (_("-mfp32 used with a 64-bit ABI"));
13998       break;
13999     }
14000
14001   /* End of GCC-shared inference code.  */
14002
14003   /* This flag is set when we have a 64-bit capable CPU but use only
14004      32-bit wide registers.  Note that EABI does not use it.  */
14005   if (ISA_HAS_64BIT_REGS (mips_opts.isa)
14006       && ((mips_abi == NO_ABI && file_mips_gp32 == 1)
14007           || mips_abi == O32_ABI))
14008     mips_32bitmode = 1;
14009
14010   if (mips_opts.isa == ISA_MIPS1 && mips_trap)
14011     as_bad (_("trap exception not supported at ISA 1"));
14012
14013   /* If the selected architecture includes support for ASEs, enable
14014      generation of code for them.  */
14015   if (mips_opts.mips16 == -1)
14016     mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_arch)) ? 1 : 0;
14017   if (mips_opts.micromips == -1)
14018     mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_arch)) ? 1 : 0;
14019
14020   /* MIPS3D and MDMX require 64-bit FPRs, so -mfp32 should stop those
14021      ASEs from being selected implicitly.  */
14022   if (file_mips_fp32 == 1)
14023     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX;
14024
14025   /* If the user didn't explicitly select or deselect a particular ASE,
14026      use the default setting for the CPU.  */
14027   mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
14028
14029   file_mips_isa = mips_opts.isa;
14030   file_ase = mips_opts.ase;
14031   mips_opts.gp32 = file_mips_gp32;
14032   mips_opts.fp32 = file_mips_fp32;
14033   mips_opts.soft_float = file_mips_soft_float;
14034   mips_opts.single_float = file_mips_single_float;
14035
14036   mips_check_isa_supports_ases ();
14037
14038   if (mips_flag_mdebug < 0)
14039     mips_flag_mdebug = 0;
14040 }
14041 \f
14042 void
14043 mips_init_after_args (void)
14044 {
14045   /* initialize opcodes */
14046   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14047   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14048 }
14049
14050 long
14051 md_pcrel_from (fixS *fixP)
14052 {
14053   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14054   switch (fixP->fx_r_type)
14055     {
14056     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14057     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14058       /* Return the address of the delay slot.  */
14059       return addr + 2;
14060
14061     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14062     case BFD_RELOC_MICROMIPS_JMP:
14063     case BFD_RELOC_16_PCREL_S2:
14064     case BFD_RELOC_MIPS_JMP:
14065       /* Return the address of the delay slot.  */
14066       return addr + 4;
14067
14068     default:
14069       return addr;
14070     }
14071 }
14072
14073 /* This is called before the symbol table is processed.  In order to
14074    work with gcc when using mips-tfile, we must keep all local labels.
14075    However, in other cases, we want to discard them.  If we were
14076    called with -g, but we didn't see any debugging information, it may
14077    mean that gcc is smuggling debugging information through to
14078    mips-tfile, in which case we must generate all local labels.  */
14079
14080 void
14081 mips_frob_file_before_adjust (void)
14082 {
14083 #ifndef NO_ECOFF_DEBUGGING
14084   if (ECOFF_DEBUGGING
14085       && mips_debug != 0
14086       && ! ecoff_debugging_seen)
14087     flag_keep_locals = 1;
14088 #endif
14089 }
14090
14091 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14092    the corresponding LO16 reloc.  This is called before md_apply_fix and
14093    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14094    relocation operators.
14095
14096    For our purposes, a %lo() expression matches a %got() or %hi()
14097    expression if:
14098
14099       (a) it refers to the same symbol; and
14100       (b) the offset applied in the %lo() expression is no lower than
14101           the offset applied in the %got() or %hi().
14102
14103    (b) allows us to cope with code like:
14104
14105         lui     $4,%hi(foo)
14106         lh      $4,%lo(foo+2)($4)
14107
14108    ...which is legal on RELA targets, and has a well-defined behaviour
14109    if the user knows that adding 2 to "foo" will not induce a carry to
14110    the high 16 bits.
14111
14112    When several %lo()s match a particular %got() or %hi(), we use the
14113    following rules to distinguish them:
14114
14115      (1) %lo()s with smaller offsets are a better match than %lo()s with
14116          higher offsets.
14117
14118      (2) %lo()s with no matching %got() or %hi() are better than those
14119          that already have a matching %got() or %hi().
14120
14121      (3) later %lo()s are better than earlier %lo()s.
14122
14123    These rules are applied in order.
14124
14125    (1) means, among other things, that %lo()s with identical offsets are
14126    chosen if they exist.
14127
14128    (2) means that we won't associate several high-part relocations with
14129    the same low-part relocation unless there's no alternative.  Having
14130    several high parts for the same low part is a GNU extension; this rule
14131    allows careful users to avoid it.
14132
14133    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14134    with the last high-part relocation being at the front of the list.
14135    It therefore makes sense to choose the last matching low-part
14136    relocation, all other things being equal.  It's also easier
14137    to code that way.  */
14138
14139 void
14140 mips_frob_file (void)
14141 {
14142   struct mips_hi_fixup *l;
14143   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14144
14145   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14146     {
14147       segment_info_type *seginfo;
14148       bfd_boolean matched_lo_p;
14149       fixS **hi_pos, **lo_pos, **pos;
14150
14151       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14152
14153       /* If a GOT16 relocation turns out to be against a global symbol,
14154          there isn't supposed to be a matching LO.  Ignore %gots against
14155          constants; we'll report an error for those later.  */
14156       if (got16_reloc_p (l->fixp->fx_r_type)
14157           && !(l->fixp->fx_addsy
14158                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14159         continue;
14160
14161       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14162       if (fixup_has_matching_lo_p (l->fixp))
14163         continue;
14164
14165       seginfo = seg_info (l->seg);
14166
14167       /* Set HI_POS to the position of this relocation in the chain.
14168          Set LO_POS to the position of the chosen low-part relocation.
14169          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14170          relocation that matches an immediately-preceding high-part
14171          relocation.  */
14172       hi_pos = NULL;
14173       lo_pos = NULL;
14174       matched_lo_p = FALSE;
14175       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14176
14177       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14178         {
14179           if (*pos == l->fixp)
14180             hi_pos = pos;
14181
14182           if ((*pos)->fx_r_type == looking_for_rtype
14183               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14184               && (*pos)->fx_offset >= l->fixp->fx_offset
14185               && (lo_pos == NULL
14186                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14187                   || (!matched_lo_p
14188                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14189             lo_pos = pos;
14190
14191           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14192                           && fixup_has_matching_lo_p (*pos));
14193         }
14194
14195       /* If we found a match, remove the high-part relocation from its
14196          current position and insert it before the low-part relocation.
14197          Make the offsets match so that fixup_has_matching_lo_p()
14198          will return true.
14199
14200          We don't warn about unmatched high-part relocations since some
14201          versions of gcc have been known to emit dead "lui ...%hi(...)"
14202          instructions.  */
14203       if (lo_pos != NULL)
14204         {
14205           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14206           if (l->fixp->fx_next != *lo_pos)
14207             {
14208               *hi_pos = l->fixp->fx_next;
14209               l->fixp->fx_next = *lo_pos;
14210               *lo_pos = l->fixp;
14211             }
14212         }
14213     }
14214 }
14215
14216 int
14217 mips_force_relocation (fixS *fixp)
14218 {
14219   if (generic_force_reloc (fixp))
14220     return 1;
14221
14222   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14223      so that the linker relaxation can update targets.  */
14224   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14225       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14226       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14227     return 1;
14228
14229   return 0;
14230 }
14231
14232 /* Read the instruction associated with RELOC from BUF.  */
14233
14234 static unsigned int
14235 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14236 {
14237   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14238     return read_compressed_insn (buf, 4);
14239   else
14240     return read_insn (buf);
14241 }
14242
14243 /* Write instruction INSN to BUF, given that it has been relocated
14244    by RELOC.  */
14245
14246 static void
14247 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14248                   unsigned long insn)
14249 {
14250   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14251     write_compressed_insn (buf, insn, 4);
14252   else
14253     write_insn (buf, insn);
14254 }
14255
14256 /* Apply a fixup to the object file.  */
14257
14258 void
14259 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
14260 {
14261   char *buf;
14262   unsigned long insn;
14263   reloc_howto_type *howto;
14264
14265   if (fixP->fx_pcrel)
14266     switch (fixP->fx_r_type)
14267       {
14268       case BFD_RELOC_16_PCREL_S2:
14269       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14270       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14271       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14272       case BFD_RELOC_32_PCREL:
14273         break;
14274
14275       case BFD_RELOC_32:
14276         fixP->fx_r_type = BFD_RELOC_32_PCREL;
14277         break;
14278
14279       default:
14280         as_bad_where (fixP->fx_file, fixP->fx_line,
14281                       _("PC-relative reference to a different section"));
14282         break;
14283       }
14284
14285   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
14286      that have no MIPS ELF equivalent.  */
14287   if (fixP->fx_r_type != BFD_RELOC_8)
14288     {
14289       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
14290       if (!howto)
14291         return;
14292     }
14293
14294   gas_assert (fixP->fx_size == 2
14295               || fixP->fx_size == 4
14296               || fixP->fx_r_type == BFD_RELOC_8
14297               || fixP->fx_r_type == BFD_RELOC_16
14298               || fixP->fx_r_type == BFD_RELOC_64
14299               || fixP->fx_r_type == BFD_RELOC_CTOR
14300               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
14301               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
14302               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
14303               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
14304               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64);
14305
14306   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14307
14308   /* Don't treat parts of a composite relocation as done.  There are two
14309      reasons for this:
14310
14311      (1) The second and third parts will be against 0 (RSS_UNDEF) but
14312          should nevertheless be emitted if the first part is.
14313
14314      (2) In normal usage, composite relocations are never assembly-time
14315          constants.  The easiest way of dealing with the pathological
14316          exceptions is to generate a relocation against STN_UNDEF and
14317          leave everything up to the linker.  */
14318   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
14319     fixP->fx_done = 1;
14320
14321   switch (fixP->fx_r_type)
14322     {
14323     case BFD_RELOC_MIPS_TLS_GD:
14324     case BFD_RELOC_MIPS_TLS_LDM:
14325     case BFD_RELOC_MIPS_TLS_DTPREL32:
14326     case BFD_RELOC_MIPS_TLS_DTPREL64:
14327     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
14328     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
14329     case BFD_RELOC_MIPS_TLS_GOTTPREL:
14330     case BFD_RELOC_MIPS_TLS_TPREL32:
14331     case BFD_RELOC_MIPS_TLS_TPREL64:
14332     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
14333     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
14334     case BFD_RELOC_MICROMIPS_TLS_GD:
14335     case BFD_RELOC_MICROMIPS_TLS_LDM:
14336     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
14337     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
14338     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
14339     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
14340     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
14341     case BFD_RELOC_MIPS16_TLS_GD:
14342     case BFD_RELOC_MIPS16_TLS_LDM:
14343     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
14344     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
14345     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
14346     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
14347     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
14348       if (!fixP->fx_addsy)
14349         {
14350           as_bad_where (fixP->fx_file, fixP->fx_line,
14351                         _("TLS relocation against a constant"));
14352           break;
14353         }
14354       S_SET_THREAD_LOCAL (fixP->fx_addsy);
14355       /* fall through */
14356
14357     case BFD_RELOC_MIPS_JMP:
14358     case BFD_RELOC_MIPS_SHIFT5:
14359     case BFD_RELOC_MIPS_SHIFT6:
14360     case BFD_RELOC_MIPS_GOT_DISP:
14361     case BFD_RELOC_MIPS_GOT_PAGE:
14362     case BFD_RELOC_MIPS_GOT_OFST:
14363     case BFD_RELOC_MIPS_SUB:
14364     case BFD_RELOC_MIPS_INSERT_A:
14365     case BFD_RELOC_MIPS_INSERT_B:
14366     case BFD_RELOC_MIPS_DELETE:
14367     case BFD_RELOC_MIPS_HIGHEST:
14368     case BFD_RELOC_MIPS_HIGHER:
14369     case BFD_RELOC_MIPS_SCN_DISP:
14370     case BFD_RELOC_MIPS_REL16:
14371     case BFD_RELOC_MIPS_RELGOT:
14372     case BFD_RELOC_MIPS_JALR:
14373     case BFD_RELOC_HI16:
14374     case BFD_RELOC_HI16_S:
14375     case BFD_RELOC_LO16:
14376     case BFD_RELOC_GPREL16:
14377     case BFD_RELOC_MIPS_LITERAL:
14378     case BFD_RELOC_MIPS_CALL16:
14379     case BFD_RELOC_MIPS_GOT16:
14380     case BFD_RELOC_GPREL32:
14381     case BFD_RELOC_MIPS_GOT_HI16:
14382     case BFD_RELOC_MIPS_GOT_LO16:
14383     case BFD_RELOC_MIPS_CALL_HI16:
14384     case BFD_RELOC_MIPS_CALL_LO16:
14385     case BFD_RELOC_MIPS16_GPREL:
14386     case BFD_RELOC_MIPS16_GOT16:
14387     case BFD_RELOC_MIPS16_CALL16:
14388     case BFD_RELOC_MIPS16_HI16:
14389     case BFD_RELOC_MIPS16_HI16_S:
14390     case BFD_RELOC_MIPS16_LO16:
14391     case BFD_RELOC_MIPS16_JMP:
14392     case BFD_RELOC_MICROMIPS_JMP:
14393     case BFD_RELOC_MICROMIPS_GOT_DISP:
14394     case BFD_RELOC_MICROMIPS_GOT_PAGE:
14395     case BFD_RELOC_MICROMIPS_GOT_OFST:
14396     case BFD_RELOC_MICROMIPS_SUB:
14397     case BFD_RELOC_MICROMIPS_HIGHEST:
14398     case BFD_RELOC_MICROMIPS_HIGHER:
14399     case BFD_RELOC_MICROMIPS_SCN_DISP:
14400     case BFD_RELOC_MICROMIPS_JALR:
14401     case BFD_RELOC_MICROMIPS_HI16:
14402     case BFD_RELOC_MICROMIPS_HI16_S:
14403     case BFD_RELOC_MICROMIPS_LO16:
14404     case BFD_RELOC_MICROMIPS_GPREL16:
14405     case BFD_RELOC_MICROMIPS_LITERAL:
14406     case BFD_RELOC_MICROMIPS_CALL16:
14407     case BFD_RELOC_MICROMIPS_GOT16:
14408     case BFD_RELOC_MICROMIPS_GOT_HI16:
14409     case BFD_RELOC_MICROMIPS_GOT_LO16:
14410     case BFD_RELOC_MICROMIPS_CALL_HI16:
14411     case BFD_RELOC_MICROMIPS_CALL_LO16:
14412     case BFD_RELOC_MIPS_EH:
14413       if (fixP->fx_done)
14414         {
14415           offsetT value;
14416
14417           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
14418             {
14419               insn = read_reloc_insn (buf, fixP->fx_r_type);
14420               if (mips16_reloc_p (fixP->fx_r_type))
14421                 insn |= mips16_immed_extend (value, 16);
14422               else
14423                 insn |= (value & 0xffff);
14424               write_reloc_insn (buf, fixP->fx_r_type, insn);
14425             }
14426           else
14427             as_bad_where (fixP->fx_file, fixP->fx_line,
14428                           _("unsupported constant in relocation"));
14429         }
14430       break;
14431
14432     case BFD_RELOC_64:
14433       /* This is handled like BFD_RELOC_32, but we output a sign
14434          extended value if we are only 32 bits.  */
14435       if (fixP->fx_done)
14436         {
14437           if (8 <= sizeof (valueT))
14438             md_number_to_chars (buf, *valP, 8);
14439           else
14440             {
14441               valueT hiv;
14442
14443               if ((*valP & 0x80000000) != 0)
14444                 hiv = 0xffffffff;
14445               else
14446                 hiv = 0;
14447               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
14448               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
14449             }
14450         }
14451       break;
14452
14453     case BFD_RELOC_RVA:
14454     case BFD_RELOC_32:
14455     case BFD_RELOC_32_PCREL:
14456     case BFD_RELOC_16:
14457     case BFD_RELOC_8:
14458       /* If we are deleting this reloc entry, we must fill in the
14459          value now.  This can happen if we have a .word which is not
14460          resolved when it appears but is later defined.  */
14461       if (fixP->fx_done)
14462         md_number_to_chars (buf, *valP, fixP->fx_size);
14463       break;
14464
14465     case BFD_RELOC_16_PCREL_S2:
14466       if ((*valP & 0x3) != 0)
14467         as_bad_where (fixP->fx_file, fixP->fx_line,
14468                       _("branch to misaligned address (%lx)"), (long) *valP);
14469
14470       /* We need to save the bits in the instruction since fixup_segment()
14471          might be deleting the relocation entry (i.e., a branch within
14472          the current segment).  */
14473       if (! fixP->fx_done)
14474         break;
14475
14476       /* Update old instruction data.  */
14477       insn = read_insn (buf);
14478
14479       if (*valP + 0x20000 <= 0x3ffff)
14480         {
14481           insn |= (*valP >> 2) & 0xffff;
14482           write_insn (buf, insn);
14483         }
14484       else if (mips_pic == NO_PIC
14485                && fixP->fx_done
14486                && fixP->fx_frag->fr_address >= text_section->vma
14487                && (fixP->fx_frag->fr_address
14488                    < text_section->vma + bfd_get_section_size (text_section))
14489                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
14490                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
14491                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
14492         {
14493           /* The branch offset is too large.  If this is an
14494              unconditional branch, and we are not generating PIC code,
14495              we can convert it to an absolute jump instruction.  */
14496           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
14497             insn = 0x0c000000;  /* jal */
14498           else
14499             insn = 0x08000000;  /* j */
14500           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
14501           fixP->fx_done = 0;
14502           fixP->fx_addsy = section_symbol (text_section);
14503           *valP += md_pcrel_from (fixP);
14504           write_insn (buf, insn);
14505         }
14506       else
14507         {
14508           /* If we got here, we have branch-relaxation disabled,
14509              and there's nothing we can do to fix this instruction
14510              without turning it into a longer sequence.  */
14511           as_bad_where (fixP->fx_file, fixP->fx_line,
14512                         _("branch out of range"));
14513         }
14514       break;
14515
14516     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14517     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14518     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14519       /* We adjust the offset back to even.  */
14520       if ((*valP & 0x1) != 0)
14521         --(*valP);
14522
14523       if (! fixP->fx_done)
14524         break;
14525
14526       /* Should never visit here, because we keep the relocation.  */
14527       abort ();
14528       break;
14529
14530     case BFD_RELOC_VTABLE_INHERIT:
14531       fixP->fx_done = 0;
14532       if (fixP->fx_addsy
14533           && !S_IS_DEFINED (fixP->fx_addsy)
14534           && !S_IS_WEAK (fixP->fx_addsy))
14535         S_SET_WEAK (fixP->fx_addsy);
14536       break;
14537
14538     case BFD_RELOC_VTABLE_ENTRY:
14539       fixP->fx_done = 0;
14540       break;
14541
14542     default:
14543       abort ();
14544     }
14545
14546   /* Remember value for tc_gen_reloc.  */
14547   fixP->fx_addnumber = *valP;
14548 }
14549
14550 static symbolS *
14551 get_symbol (void)
14552 {
14553   int c;
14554   char *name;
14555   symbolS *p;
14556
14557   name = input_line_pointer;
14558   c = get_symbol_end ();
14559   p = (symbolS *) symbol_find_or_make (name);
14560   *input_line_pointer = c;
14561   return p;
14562 }
14563
14564 /* Align the current frag to a given power of two.  If a particular
14565    fill byte should be used, FILL points to an integer that contains
14566    that byte, otherwise FILL is null.
14567
14568    This function used to have the comment:
14569
14570       The MIPS assembler also automatically adjusts any preceding label.
14571
14572    The implementation therefore applied the adjustment to a maximum of
14573    one label.  However, other label adjustments are applied to batches
14574    of labels, and adjusting just one caused problems when new labels
14575    were added for the sake of debugging or unwind information.
14576    We therefore adjust all preceding labels (given as LABELS) instead.  */
14577
14578 static void
14579 mips_align (int to, int *fill, struct insn_label_list *labels)
14580 {
14581   mips_emit_delays ();
14582   mips_record_compressed_mode ();
14583   if (fill == NULL && subseg_text_p (now_seg))
14584     frag_align_code (to, 0);
14585   else
14586     frag_align (to, fill ? *fill : 0, 0);
14587   record_alignment (now_seg, to);
14588   mips_move_labels (labels, FALSE);
14589 }
14590
14591 /* Align to a given power of two.  .align 0 turns off the automatic
14592    alignment used by the data creating pseudo-ops.  */
14593
14594 static void
14595 s_align (int x ATTRIBUTE_UNUSED)
14596 {
14597   int temp, fill_value, *fill_ptr;
14598   long max_alignment = 28;
14599
14600   /* o Note that the assembler pulls down any immediately preceding label
14601        to the aligned address.
14602      o It's not documented but auto alignment is reinstated by
14603        a .align pseudo instruction.
14604      o Note also that after auto alignment is turned off the mips assembler
14605        issues an error on attempt to assemble an improperly aligned data item.
14606        We don't.  */
14607
14608   temp = get_absolute_expression ();
14609   if (temp > max_alignment)
14610     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
14611   else if (temp < 0)
14612     {
14613       as_warn (_("alignment negative, 0 assumed"));
14614       temp = 0;
14615     }
14616   if (*input_line_pointer == ',')
14617     {
14618       ++input_line_pointer;
14619       fill_value = get_absolute_expression ();
14620       fill_ptr = &fill_value;
14621     }
14622   else
14623     fill_ptr = 0;
14624   if (temp)
14625     {
14626       segment_info_type *si = seg_info (now_seg);
14627       struct insn_label_list *l = si->label_list;
14628       /* Auto alignment should be switched on by next section change.  */
14629       auto_align = 1;
14630       mips_align (temp, fill_ptr, l);
14631     }
14632   else
14633     {
14634       auto_align = 0;
14635     }
14636
14637   demand_empty_rest_of_line ();
14638 }
14639
14640 static void
14641 s_change_sec (int sec)
14642 {
14643   segT seg;
14644
14645   /* The ELF backend needs to know that we are changing sections, so
14646      that .previous works correctly.  We could do something like check
14647      for an obj_section_change_hook macro, but that might be confusing
14648      as it would not be appropriate to use it in the section changing
14649      functions in read.c, since obj-elf.c intercepts those.  FIXME:
14650      This should be cleaner, somehow.  */
14651   obj_elf_section_change_hook ();
14652
14653   mips_emit_delays ();
14654
14655   switch (sec)
14656     {
14657     case 't':
14658       s_text (0);
14659       break;
14660     case 'd':
14661       s_data (0);
14662       break;
14663     case 'b':
14664       subseg_set (bss_section, (subsegT) get_absolute_expression ());
14665       demand_empty_rest_of_line ();
14666       break;
14667
14668     case 'r':
14669       seg = subseg_new (RDATA_SECTION_NAME,
14670                         (subsegT) get_absolute_expression ());
14671       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
14672                                               | SEC_READONLY | SEC_RELOC
14673                                               | SEC_DATA));
14674       if (strncmp (TARGET_OS, "elf", 3) != 0)
14675         record_alignment (seg, 4);
14676       demand_empty_rest_of_line ();
14677       break;
14678
14679     case 's':
14680       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
14681       bfd_set_section_flags (stdoutput, seg,
14682                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
14683       if (strncmp (TARGET_OS, "elf", 3) != 0)
14684         record_alignment (seg, 4);
14685       demand_empty_rest_of_line ();
14686       break;
14687
14688     case 'B':
14689       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
14690       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
14691       if (strncmp (TARGET_OS, "elf", 3) != 0)
14692         record_alignment (seg, 4);
14693       demand_empty_rest_of_line ();
14694       break;
14695     }
14696
14697   auto_align = 1;
14698 }
14699
14700 void
14701 s_change_section (int ignore ATTRIBUTE_UNUSED)
14702 {
14703   char *section_name;
14704   char c;
14705   char next_c = 0;
14706   int section_type;
14707   int section_flag;
14708   int section_entry_size;
14709   int section_alignment;
14710
14711   section_name = input_line_pointer;
14712   c = get_symbol_end ();
14713   if (c)
14714     next_c = *(input_line_pointer + 1);
14715
14716   /* Do we have .section Name<,"flags">?  */
14717   if (c != ',' || (c == ',' && next_c == '"'))
14718     {
14719       /* just after name is now '\0'.  */
14720       *input_line_pointer = c;
14721       input_line_pointer = section_name;
14722       obj_elf_section (ignore);
14723       return;
14724     }
14725   input_line_pointer++;
14726
14727   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
14728   if (c == ',')
14729     section_type = get_absolute_expression ();
14730   else
14731     section_type = 0;
14732   if (*input_line_pointer++ == ',')
14733     section_flag = get_absolute_expression ();
14734   else
14735     section_flag = 0;
14736   if (*input_line_pointer++ == ',')
14737     section_entry_size = get_absolute_expression ();
14738   else
14739     section_entry_size = 0;
14740   if (*input_line_pointer++ == ',')
14741     section_alignment = get_absolute_expression ();
14742   else
14743     section_alignment = 0;
14744   /* FIXME: really ignore?  */
14745   (void) section_alignment;
14746
14747   section_name = xstrdup (section_name);
14748
14749   /* When using the generic form of .section (as implemented by obj-elf.c),
14750      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
14751      traditionally had to fall back on the more common @progbits instead.
14752
14753      There's nothing really harmful in this, since bfd will correct
14754      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
14755      means that, for backwards compatibility, the special_section entries
14756      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
14757
14758      Even so, we shouldn't force users of the MIPS .section syntax to
14759      incorrectly label the sections as SHT_PROGBITS.  The best compromise
14760      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
14761      generic type-checking code.  */
14762   if (section_type == SHT_MIPS_DWARF)
14763     section_type = SHT_PROGBITS;
14764
14765   obj_elf_change_section (section_name, section_type, section_flag,
14766                           section_entry_size, 0, 0, 0);
14767
14768   if (now_seg->name != section_name)
14769     free (section_name);
14770 }
14771
14772 void
14773 mips_enable_auto_align (void)
14774 {
14775   auto_align = 1;
14776 }
14777
14778 static void
14779 s_cons (int log_size)
14780 {
14781   segment_info_type *si = seg_info (now_seg);
14782   struct insn_label_list *l = si->label_list;
14783
14784   mips_emit_delays ();
14785   if (log_size > 0 && auto_align)
14786     mips_align (log_size, 0, l);
14787   cons (1 << log_size);
14788   mips_clear_insn_labels ();
14789 }
14790
14791 static void
14792 s_float_cons (int type)
14793 {
14794   segment_info_type *si = seg_info (now_seg);
14795   struct insn_label_list *l = si->label_list;
14796
14797   mips_emit_delays ();
14798
14799   if (auto_align)
14800     {
14801       if (type == 'd')
14802         mips_align (3, 0, l);
14803       else
14804         mips_align (2, 0, l);
14805     }
14806
14807   float_cons (type);
14808   mips_clear_insn_labels ();
14809 }
14810
14811 /* Handle .globl.  We need to override it because on Irix 5 you are
14812    permitted to say
14813        .globl foo .text
14814    where foo is an undefined symbol, to mean that foo should be
14815    considered to be the address of a function.  */
14816
14817 static void
14818 s_mips_globl (int x ATTRIBUTE_UNUSED)
14819 {
14820   char *name;
14821   int c;
14822   symbolS *symbolP;
14823   flagword flag;
14824
14825   do
14826     {
14827       name = input_line_pointer;
14828       c = get_symbol_end ();
14829       symbolP = symbol_find_or_make (name);
14830       S_SET_EXTERNAL (symbolP);
14831
14832       *input_line_pointer = c;
14833       SKIP_WHITESPACE ();
14834
14835       /* On Irix 5, every global symbol that is not explicitly labelled as
14836          being a function is apparently labelled as being an object.  */
14837       flag = BSF_OBJECT;
14838
14839       if (!is_end_of_line[(unsigned char) *input_line_pointer]
14840           && (*input_line_pointer != ','))
14841         {
14842           char *secname;
14843           asection *sec;
14844
14845           secname = input_line_pointer;
14846           c = get_symbol_end ();
14847           sec = bfd_get_section_by_name (stdoutput, secname);
14848           if (sec == NULL)
14849             as_bad (_("%s: no such section"), secname);
14850           *input_line_pointer = c;
14851
14852           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
14853             flag = BSF_FUNCTION;
14854         }
14855
14856       symbol_get_bfdsym (symbolP)->flags |= flag;
14857
14858       c = *input_line_pointer;
14859       if (c == ',')
14860         {
14861           input_line_pointer++;
14862           SKIP_WHITESPACE ();
14863           if (is_end_of_line[(unsigned char) *input_line_pointer])
14864             c = '\n';
14865         }
14866     }
14867   while (c == ',');
14868
14869   demand_empty_rest_of_line ();
14870 }
14871
14872 static void
14873 s_option (int x ATTRIBUTE_UNUSED)
14874 {
14875   char *opt;
14876   char c;
14877
14878   opt = input_line_pointer;
14879   c = get_symbol_end ();
14880
14881   if (*opt == 'O')
14882     {
14883       /* FIXME: What does this mean?  */
14884     }
14885   else if (strncmp (opt, "pic", 3) == 0)
14886     {
14887       int i;
14888
14889       i = atoi (opt + 3);
14890       if (i == 0)
14891         mips_pic = NO_PIC;
14892       else if (i == 2)
14893         {
14894           mips_pic = SVR4_PIC;
14895           mips_abicalls = TRUE;
14896         }
14897       else
14898         as_bad (_(".option pic%d not supported"), i);
14899
14900       if (mips_pic == SVR4_PIC)
14901         {
14902           if (g_switch_seen && g_switch_value != 0)
14903             as_warn (_("-G may not be used with SVR4 PIC code"));
14904           g_switch_value = 0;
14905           bfd_set_gp_size (stdoutput, 0);
14906         }
14907     }
14908   else
14909     as_warn (_("unrecognized option \"%s\""), opt);
14910
14911   *input_line_pointer = c;
14912   demand_empty_rest_of_line ();
14913 }
14914
14915 /* This structure is used to hold a stack of .set values.  */
14916
14917 struct mips_option_stack
14918 {
14919   struct mips_option_stack *next;
14920   struct mips_set_options options;
14921 };
14922
14923 static struct mips_option_stack *mips_opts_stack;
14924
14925 /* Handle the .set pseudo-op.  */
14926
14927 static void
14928 s_mipsset (int x ATTRIBUTE_UNUSED)
14929 {
14930   char *name = input_line_pointer, ch;
14931   const struct mips_ase *ase;
14932
14933   while (!is_end_of_line[(unsigned char) *input_line_pointer])
14934     ++input_line_pointer;
14935   ch = *input_line_pointer;
14936   *input_line_pointer = '\0';
14937
14938   if (strcmp (name, "reorder") == 0)
14939     {
14940       if (mips_opts.noreorder)
14941         end_noreorder ();
14942     }
14943   else if (strcmp (name, "noreorder") == 0)
14944     {
14945       if (!mips_opts.noreorder)
14946         start_noreorder ();
14947     }
14948   else if (strncmp (name, "at=", 3) == 0)
14949     {
14950       char *s = name + 3;
14951
14952       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
14953         as_bad (_("unrecognized register name `%s'"), s);
14954     }
14955   else if (strcmp (name, "at") == 0)
14956     {
14957       mips_opts.at = ATREG;
14958     }
14959   else if (strcmp (name, "noat") == 0)
14960     {
14961       mips_opts.at = ZERO;
14962     }
14963   else if (strcmp (name, "macro") == 0)
14964     {
14965       mips_opts.warn_about_macros = 0;
14966     }
14967   else if (strcmp (name, "nomacro") == 0)
14968     {
14969       if (mips_opts.noreorder == 0)
14970         as_bad (_("`noreorder' must be set before `nomacro'"));
14971       mips_opts.warn_about_macros = 1;
14972     }
14973   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
14974     {
14975       mips_opts.nomove = 0;
14976     }
14977   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
14978     {
14979       mips_opts.nomove = 1;
14980     }
14981   else if (strcmp (name, "bopt") == 0)
14982     {
14983       mips_opts.nobopt = 0;
14984     }
14985   else if (strcmp (name, "nobopt") == 0)
14986     {
14987       mips_opts.nobopt = 1;
14988     }
14989   else if (strcmp (name, "gp=default") == 0)
14990     mips_opts.gp32 = file_mips_gp32;
14991   else if (strcmp (name, "gp=32") == 0)
14992     mips_opts.gp32 = 1;
14993   else if (strcmp (name, "gp=64") == 0)
14994     {
14995       if (!ISA_HAS_64BIT_REGS (mips_opts.isa))
14996         as_warn (_("%s isa does not support 64-bit registers"),
14997                  mips_cpu_info_from_isa (mips_opts.isa)->name);
14998       mips_opts.gp32 = 0;
14999     }
15000   else if (strcmp (name, "fp=default") == 0)
15001     mips_opts.fp32 = file_mips_fp32;
15002   else if (strcmp (name, "fp=32") == 0)
15003     mips_opts.fp32 = 1;
15004   else if (strcmp (name, "fp=64") == 0)
15005     {
15006       if (!ISA_HAS_64BIT_FPRS (mips_opts.isa))
15007         as_warn (_("%s isa does not support 64-bit floating point registers"),
15008                  mips_cpu_info_from_isa (mips_opts.isa)->name);
15009       mips_opts.fp32 = 0;
15010     }
15011   else if (strcmp (name, "softfloat") == 0)
15012     mips_opts.soft_float = 1;
15013   else if (strcmp (name, "hardfloat") == 0)
15014     mips_opts.soft_float = 0;
15015   else if (strcmp (name, "singlefloat") == 0)
15016     mips_opts.single_float = 1;
15017   else if (strcmp (name, "doublefloat") == 0)
15018     mips_opts.single_float = 0;
15019   else if (strcmp (name, "mips16") == 0
15020            || strcmp (name, "MIPS-16") == 0)
15021     {
15022       if (mips_opts.micromips == 1)
15023         as_fatal (_("`mips16' cannot be used with `micromips'"));
15024       mips_opts.mips16 = 1;
15025     }
15026   else if (strcmp (name, "nomips16") == 0
15027            || strcmp (name, "noMIPS-16") == 0)
15028     mips_opts.mips16 = 0;
15029   else if (strcmp (name, "micromips") == 0)
15030     {
15031       if (mips_opts.mips16 == 1)
15032         as_fatal (_("`micromips' cannot be used with `mips16'"));
15033       mips_opts.micromips = 1;
15034     }
15035   else if (strcmp (name, "nomicromips") == 0)
15036     mips_opts.micromips = 0;
15037   else if (name[0] == 'n'
15038            && name[1] == 'o'
15039            && (ase = mips_lookup_ase (name + 2)))
15040     mips_set_ase (ase, FALSE);
15041   else if ((ase = mips_lookup_ase (name)))
15042     mips_set_ase (ase, TRUE);
15043   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15044     {
15045       int reset = 0;
15046
15047       /* Permit the user to change the ISA and architecture on the fly.
15048          Needless to say, misuse can cause serious problems.  */
15049       if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
15050         {
15051           reset = 1;
15052           mips_opts.isa = file_mips_isa;
15053           mips_opts.arch = file_mips_arch;
15054         }
15055       else if (strncmp (name, "arch=", 5) == 0)
15056         {
15057           const struct mips_cpu_info *p;
15058
15059           p = mips_parse_cpu("internal use", name + 5);
15060           if (!p)
15061             as_bad (_("unknown architecture %s"), name + 5);
15062           else
15063             {
15064               mips_opts.arch = p->cpu;
15065               mips_opts.isa = p->isa;
15066             }
15067         }
15068       else if (strncmp (name, "mips", 4) == 0)
15069         {
15070           const struct mips_cpu_info *p;
15071
15072           p = mips_parse_cpu("internal use", name);
15073           if (!p)
15074             as_bad (_("unknown ISA level %s"), name + 4);
15075           else
15076             {
15077               mips_opts.arch = p->cpu;
15078               mips_opts.isa = p->isa;
15079             }
15080         }
15081       else
15082         as_bad (_("unknown ISA or architecture %s"), name);
15083
15084       switch (mips_opts.isa)
15085         {
15086         case  0:
15087           break;
15088         case ISA_MIPS1:
15089         case ISA_MIPS2:
15090         case ISA_MIPS32:
15091         case ISA_MIPS32R2:
15092           mips_opts.gp32 = 1;
15093           mips_opts.fp32 = 1;
15094           break;
15095         case ISA_MIPS3:
15096         case ISA_MIPS4:
15097         case ISA_MIPS5:
15098         case ISA_MIPS64:
15099         case ISA_MIPS64R2:
15100           mips_opts.gp32 = 0;
15101           if (mips_opts.arch == CPU_R5900)
15102             {
15103                 mips_opts.fp32 = 1;
15104             }
15105           else
15106             {
15107           mips_opts.fp32 = 0;
15108             }
15109           break;
15110         default:
15111           as_bad (_("unknown ISA level %s"), name + 4);
15112           break;
15113         }
15114       if (reset)
15115         {
15116           mips_opts.gp32 = file_mips_gp32;
15117           mips_opts.fp32 = file_mips_fp32;
15118         }
15119     }
15120   else if (strcmp (name, "autoextend") == 0)
15121     mips_opts.noautoextend = 0;
15122   else if (strcmp (name, "noautoextend") == 0)
15123     mips_opts.noautoextend = 1;
15124   else if (strcmp (name, "insn32") == 0)
15125     mips_opts.insn32 = TRUE;
15126   else if (strcmp (name, "noinsn32") == 0)
15127     mips_opts.insn32 = FALSE;
15128   else if (strcmp (name, "push") == 0)
15129     {
15130       struct mips_option_stack *s;
15131
15132       s = (struct mips_option_stack *) xmalloc (sizeof *s);
15133       s->next = mips_opts_stack;
15134       s->options = mips_opts;
15135       mips_opts_stack = s;
15136     }
15137   else if (strcmp (name, "pop") == 0)
15138     {
15139       struct mips_option_stack *s;
15140
15141       s = mips_opts_stack;
15142       if (s == NULL)
15143         as_bad (_(".set pop with no .set push"));
15144       else
15145         {
15146           /* If we're changing the reorder mode we need to handle
15147              delay slots correctly.  */
15148           if (s->options.noreorder && ! mips_opts.noreorder)
15149             start_noreorder ();
15150           else if (! s->options.noreorder && mips_opts.noreorder)
15151             end_noreorder ();
15152
15153           mips_opts = s->options;
15154           mips_opts_stack = s->next;
15155           free (s);
15156         }
15157     }
15158   else if (strcmp (name, "sym32") == 0)
15159     mips_opts.sym32 = TRUE;
15160   else if (strcmp (name, "nosym32") == 0)
15161     mips_opts.sym32 = FALSE;
15162   else if (strchr (name, ','))
15163     {
15164       /* Generic ".set" directive; use the generic handler.  */
15165       *input_line_pointer = ch;
15166       input_line_pointer = name;
15167       s_set (0);
15168       return;
15169     }
15170   else
15171     {
15172       as_warn (_("tried to set unrecognized symbol: %s\n"), name);
15173     }
15174   mips_check_isa_supports_ases ();
15175   *input_line_pointer = ch;
15176   demand_empty_rest_of_line ();
15177 }
15178
15179 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
15180    .option pic2.  It means to generate SVR4 PIC calls.  */
15181
15182 static void
15183 s_abicalls (int ignore ATTRIBUTE_UNUSED)
15184 {
15185   mips_pic = SVR4_PIC;
15186   mips_abicalls = TRUE;
15187
15188   if (g_switch_seen && g_switch_value != 0)
15189     as_warn (_("-G may not be used with SVR4 PIC code"));
15190   g_switch_value = 0;
15191
15192   bfd_set_gp_size (stdoutput, 0);
15193   demand_empty_rest_of_line ();
15194 }
15195
15196 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
15197    PIC code.  It sets the $gp register for the function based on the
15198    function address, which is in the register named in the argument.
15199    This uses a relocation against _gp_disp, which is handled specially
15200    by the linker.  The result is:
15201         lui     $gp,%hi(_gp_disp)
15202         addiu   $gp,$gp,%lo(_gp_disp)
15203         addu    $gp,$gp,.cpload argument
15204    The .cpload argument is normally $25 == $t9.
15205
15206    The -mno-shared option changes this to:
15207         lui     $gp,%hi(__gnu_local_gp)
15208         addiu   $gp,$gp,%lo(__gnu_local_gp)
15209    and the argument is ignored.  This saves an instruction, but the
15210    resulting code is not position independent; it uses an absolute
15211    address for __gnu_local_gp.  Thus code assembled with -mno-shared
15212    can go into an ordinary executable, but not into a shared library.  */
15213
15214 static void
15215 s_cpload (int ignore ATTRIBUTE_UNUSED)
15216 {
15217   expressionS ex;
15218   int reg;
15219   int in_shared;
15220
15221   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15222      .cpload is ignored.  */
15223   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15224     {
15225       s_ignore (0);
15226       return;
15227     }
15228
15229   if (mips_opts.mips16)
15230     {
15231       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
15232       ignore_rest_of_line ();
15233       return;
15234     }
15235
15236   /* .cpload should be in a .set noreorder section.  */
15237   if (mips_opts.noreorder == 0)
15238     as_warn (_(".cpload not in noreorder section"));
15239
15240   reg = tc_get_register (0);
15241
15242   /* If we need to produce a 64-bit address, we are better off using
15243      the default instruction sequence.  */
15244   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
15245
15246   ex.X_op = O_symbol;
15247   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
15248                                          "__gnu_local_gp");
15249   ex.X_op_symbol = NULL;
15250   ex.X_add_number = 0;
15251
15252   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15253   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15254
15255   mips_mark_labels ();
15256   mips_assembling_insn = TRUE;
15257
15258   macro_start ();
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   if (in_shared)
15263     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
15264                  mips_gp_register, reg);
15265   macro_end ();
15266
15267   mips_assembling_insn = FALSE;
15268   demand_empty_rest_of_line ();
15269 }
15270
15271 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
15272      .cpsetup $reg1, offset|$reg2, label
15273
15274    If offset is given, this results in:
15275      sd         $gp, offset($sp)
15276      lui        $gp, %hi(%neg(%gp_rel(label)))
15277      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15278      daddu      $gp, $gp, $reg1
15279
15280    If $reg2 is given, this results in:
15281      daddu      $reg2, $gp, $0
15282      lui        $gp, %hi(%neg(%gp_rel(label)))
15283      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
15284      daddu      $gp, $gp, $reg1
15285    $reg1 is normally $25 == $t9.
15286
15287    The -mno-shared option replaces the last three instructions with
15288         lui     $gp,%hi(_gp)
15289         addiu   $gp,$gp,%lo(_gp)  */
15290
15291 static void
15292 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
15293 {
15294   expressionS ex_off;
15295   expressionS ex_sym;
15296   int reg1;
15297
15298   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
15299      We also need NewABI support.  */
15300   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15301     {
15302       s_ignore (0);
15303       return;
15304     }
15305
15306   if (mips_opts.mips16)
15307     {
15308       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
15309       ignore_rest_of_line ();
15310       return;
15311     }
15312
15313   reg1 = tc_get_register (0);
15314   SKIP_WHITESPACE ();
15315   if (*input_line_pointer != ',')
15316     {
15317       as_bad (_("missing argument separator ',' for .cpsetup"));
15318       return;
15319     }
15320   else
15321     ++input_line_pointer;
15322   SKIP_WHITESPACE ();
15323   if (*input_line_pointer == '$')
15324     {
15325       mips_cpreturn_register = tc_get_register (0);
15326       mips_cpreturn_offset = -1;
15327     }
15328   else
15329     {
15330       mips_cpreturn_offset = get_absolute_expression ();
15331       mips_cpreturn_register = -1;
15332     }
15333   SKIP_WHITESPACE ();
15334   if (*input_line_pointer != ',')
15335     {
15336       as_bad (_("missing argument separator ',' for .cpsetup"));
15337       return;
15338     }
15339   else
15340     ++input_line_pointer;
15341   SKIP_WHITESPACE ();
15342   expression (&ex_sym);
15343
15344   mips_mark_labels ();
15345   mips_assembling_insn = TRUE;
15346
15347   macro_start ();
15348   if (mips_cpreturn_register == -1)
15349     {
15350       ex_off.X_op = O_constant;
15351       ex_off.X_add_symbol = NULL;
15352       ex_off.X_op_symbol = NULL;
15353       ex_off.X_add_number = mips_cpreturn_offset;
15354
15355       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
15356                    BFD_RELOC_LO16, SP);
15357     }
15358   else
15359     macro_build (NULL, "daddu", "d,v,t", mips_cpreturn_register,
15360                  mips_gp_register, 0);
15361
15362   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
15363     {
15364       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
15365                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
15366                    BFD_RELOC_HI16_S);
15367
15368       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
15369                    mips_gp_register, -1, BFD_RELOC_GPREL16,
15370                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
15371
15372       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
15373                    mips_gp_register, reg1);
15374     }
15375   else
15376     {
15377       expressionS ex;
15378
15379       ex.X_op = O_symbol;
15380       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
15381       ex.X_op_symbol = NULL;
15382       ex.X_add_number = 0;
15383
15384       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
15385       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
15386
15387       macro_build_lui (&ex, mips_gp_register);
15388       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
15389                    mips_gp_register, BFD_RELOC_LO16);
15390     }
15391
15392   macro_end ();
15393
15394   mips_assembling_insn = FALSE;
15395   demand_empty_rest_of_line ();
15396 }
15397
15398 static void
15399 s_cplocal (int ignore ATTRIBUTE_UNUSED)
15400 {
15401   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
15402      .cplocal is ignored.  */
15403   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15404     {
15405       s_ignore (0);
15406       return;
15407     }
15408
15409   if (mips_opts.mips16)
15410     {
15411       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
15412       ignore_rest_of_line ();
15413       return;
15414     }
15415
15416   mips_gp_register = tc_get_register (0);
15417   demand_empty_rest_of_line ();
15418 }
15419
15420 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
15421    offset from $sp.  The offset is remembered, and after making a PIC
15422    call $gp is restored from that location.  */
15423
15424 static void
15425 s_cprestore (int ignore ATTRIBUTE_UNUSED)
15426 {
15427   expressionS ex;
15428
15429   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
15430      .cprestore is ignored.  */
15431   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
15432     {
15433       s_ignore (0);
15434       return;
15435     }
15436
15437   if (mips_opts.mips16)
15438     {
15439       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
15440       ignore_rest_of_line ();
15441       return;
15442     }
15443
15444   mips_cprestore_offset = get_absolute_expression ();
15445   mips_cprestore_valid = 1;
15446
15447   ex.X_op = O_constant;
15448   ex.X_add_symbol = NULL;
15449   ex.X_op_symbol = NULL;
15450   ex.X_add_number = mips_cprestore_offset;
15451
15452   mips_mark_labels ();
15453   mips_assembling_insn = TRUE;
15454
15455   macro_start ();
15456   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
15457                                 SP, HAVE_64BIT_ADDRESSES);
15458   macro_end ();
15459
15460   mips_assembling_insn = FALSE;
15461   demand_empty_rest_of_line ();
15462 }
15463
15464 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
15465    was given in the preceding .cpsetup, it results in:
15466      ld         $gp, offset($sp)
15467
15468    If a register $reg2 was given there, it results in:
15469      daddu      $gp, $reg2, $0  */
15470
15471 static void
15472 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
15473 {
15474   expressionS ex;
15475
15476   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
15477      We also need NewABI support.  */
15478   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15479     {
15480       s_ignore (0);
15481       return;
15482     }
15483
15484   if (mips_opts.mips16)
15485     {
15486       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
15487       ignore_rest_of_line ();
15488       return;
15489     }
15490
15491   mips_mark_labels ();
15492   mips_assembling_insn = TRUE;
15493
15494   macro_start ();
15495   if (mips_cpreturn_register == -1)
15496     {
15497       ex.X_op = O_constant;
15498       ex.X_add_symbol = NULL;
15499       ex.X_op_symbol = NULL;
15500       ex.X_add_number = mips_cpreturn_offset;
15501
15502       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
15503     }
15504   else
15505     macro_build (NULL, "daddu", "d,v,t", mips_gp_register,
15506                  mips_cpreturn_register, 0);
15507   macro_end ();
15508
15509   mips_assembling_insn = FALSE;
15510   demand_empty_rest_of_line ();
15511 }
15512
15513 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
15514    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
15515    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
15516    debug information or MIPS16 TLS.  */
15517
15518 static void
15519 s_tls_rel_directive (const size_t bytes, const char *dirstr,
15520                      bfd_reloc_code_real_type rtype)
15521 {
15522   expressionS ex;
15523   char *p;
15524
15525   expression (&ex);
15526
15527   if (ex.X_op != O_symbol)
15528     {
15529       as_bad (_("unsupported use of %s"), dirstr);
15530       ignore_rest_of_line ();
15531     }
15532
15533   p = frag_more (bytes);
15534   md_number_to_chars (p, 0, bytes);
15535   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
15536   demand_empty_rest_of_line ();
15537   mips_clear_insn_labels ();
15538 }
15539
15540 /* Handle .dtprelword.  */
15541
15542 static void
15543 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
15544 {
15545   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
15546 }
15547
15548 /* Handle .dtpreldword.  */
15549
15550 static void
15551 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
15552 {
15553   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
15554 }
15555
15556 /* Handle .tprelword.  */
15557
15558 static void
15559 s_tprelword (int ignore ATTRIBUTE_UNUSED)
15560 {
15561   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
15562 }
15563
15564 /* Handle .tpreldword.  */
15565
15566 static void
15567 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
15568 {
15569   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
15570 }
15571
15572 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
15573    code.  It sets the offset to use in gp_rel relocations.  */
15574
15575 static void
15576 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
15577 {
15578   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
15579      We also need NewABI support.  */
15580   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
15581     {
15582       s_ignore (0);
15583       return;
15584     }
15585
15586   mips_gprel_offset = get_absolute_expression ();
15587
15588   demand_empty_rest_of_line ();
15589 }
15590
15591 /* Handle the .gpword pseudo-op.  This is used when generating PIC
15592    code.  It generates a 32 bit GP relative reloc.  */
15593
15594 static void
15595 s_gpword (int ignore ATTRIBUTE_UNUSED)
15596 {
15597   segment_info_type *si;
15598   struct insn_label_list *l;
15599   expressionS ex;
15600   char *p;
15601
15602   /* When not generating PIC code, this is treated as .word.  */
15603   if (mips_pic != SVR4_PIC)
15604     {
15605       s_cons (2);
15606       return;
15607     }
15608
15609   si = seg_info (now_seg);
15610   l = si->label_list;
15611   mips_emit_delays ();
15612   if (auto_align)
15613     mips_align (2, 0, l);
15614
15615   expression (&ex);
15616   mips_clear_insn_labels ();
15617
15618   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15619     {
15620       as_bad (_("unsupported use of .gpword"));
15621       ignore_rest_of_line ();
15622     }
15623
15624   p = frag_more (4);
15625   md_number_to_chars (p, 0, 4);
15626   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15627                BFD_RELOC_GPREL32);
15628
15629   demand_empty_rest_of_line ();
15630 }
15631
15632 static void
15633 s_gpdword (int ignore ATTRIBUTE_UNUSED)
15634 {
15635   segment_info_type *si;
15636   struct insn_label_list *l;
15637   expressionS ex;
15638   char *p;
15639
15640   /* When not generating PIC code, this is treated as .dword.  */
15641   if (mips_pic != SVR4_PIC)
15642     {
15643       s_cons (3);
15644       return;
15645     }
15646
15647   si = seg_info (now_seg);
15648   l = si->label_list;
15649   mips_emit_delays ();
15650   if (auto_align)
15651     mips_align (3, 0, l);
15652
15653   expression (&ex);
15654   mips_clear_insn_labels ();
15655
15656   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15657     {
15658       as_bad (_("unsupported use of .gpdword"));
15659       ignore_rest_of_line ();
15660     }
15661
15662   p = frag_more (8);
15663   md_number_to_chars (p, 0, 8);
15664   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15665                BFD_RELOC_GPREL32)->fx_tcbit = 1;
15666
15667   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
15668   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
15669            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
15670
15671   demand_empty_rest_of_line ();
15672 }
15673
15674 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
15675    tables.  It generates a R_MIPS_EH reloc.  */
15676
15677 static void
15678 s_ehword (int ignore ATTRIBUTE_UNUSED)
15679 {
15680   expressionS ex;
15681   char *p;
15682
15683   mips_emit_delays ();
15684
15685   expression (&ex);
15686   mips_clear_insn_labels ();
15687
15688   if (ex.X_op != O_symbol || ex.X_add_number != 0)
15689     {
15690       as_bad (_("unsupported use of .ehword"));
15691       ignore_rest_of_line ();
15692     }
15693
15694   p = frag_more (4);
15695   md_number_to_chars (p, 0, 4);
15696   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
15697                BFD_RELOC_MIPS_EH);
15698
15699   demand_empty_rest_of_line ();
15700 }
15701
15702 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
15703    tables in SVR4 PIC code.  */
15704
15705 static void
15706 s_cpadd (int ignore ATTRIBUTE_UNUSED)
15707 {
15708   int reg;
15709
15710   /* This is ignored when not generating SVR4 PIC code.  */
15711   if (mips_pic != SVR4_PIC)
15712     {
15713       s_ignore (0);
15714       return;
15715     }
15716
15717   mips_mark_labels ();
15718   mips_assembling_insn = TRUE;
15719
15720   /* Add $gp to the register named as an argument.  */
15721   macro_start ();
15722   reg = tc_get_register (0);
15723   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
15724   macro_end ();
15725
15726   mips_assembling_insn = FALSE;
15727   demand_empty_rest_of_line ();
15728 }
15729
15730 /* Handle the .insn pseudo-op.  This marks instruction labels in
15731    mips16/micromips mode.  This permits the linker to handle them specially,
15732    such as generating jalx instructions when needed.  We also make
15733    them odd for the duration of the assembly, in order to generate the
15734    right sort of code.  We will make them even in the adjust_symtab
15735    routine, while leaving them marked.  This is convenient for the
15736    debugger and the disassembler.  The linker knows to make them odd
15737    again.  */
15738
15739 static void
15740 s_insn (int ignore ATTRIBUTE_UNUSED)
15741 {
15742   mips_mark_labels ();
15743
15744   demand_empty_rest_of_line ();
15745 }
15746
15747 /* Handle the .nan pseudo-op.  */
15748
15749 static void
15750 s_nan (int ignore ATTRIBUTE_UNUSED)
15751 {
15752   static const char str_legacy[] = "legacy";
15753   static const char str_2008[] = "2008";
15754   size_t i;
15755
15756   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
15757
15758   if (i == sizeof (str_2008) - 1
15759       && memcmp (input_line_pointer, str_2008, i) == 0)
15760     mips_flag_nan2008 = TRUE;
15761   else if (i == sizeof (str_legacy) - 1
15762            && memcmp (input_line_pointer, str_legacy, i) == 0)
15763     mips_flag_nan2008 = FALSE;
15764   else
15765     as_bad (_("bad .nan directive"));
15766
15767   input_line_pointer += i;
15768   demand_empty_rest_of_line ();
15769 }
15770
15771 /* Handle a .stab[snd] directive.  Ideally these directives would be
15772    implemented in a transparent way, so that removing them would not
15773    have any effect on the generated instructions.  However, s_stab
15774    internally changes the section, so in practice we need to decide
15775    now whether the preceding label marks compressed code.  We do not
15776    support changing the compression mode of a label after a .stab*
15777    directive, such as in:
15778
15779    foo:
15780         .stabs ...
15781         .set mips16
15782
15783    so the current mode wins.  */
15784
15785 static void
15786 s_mips_stab (int type)
15787 {
15788   mips_mark_labels ();
15789   s_stab (type);
15790 }
15791
15792 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
15793
15794 static void
15795 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
15796 {
15797   char *name;
15798   int c;
15799   symbolS *symbolP;
15800   expressionS exp;
15801
15802   name = input_line_pointer;
15803   c = get_symbol_end ();
15804   symbolP = symbol_find_or_make (name);
15805   S_SET_WEAK (symbolP);
15806   *input_line_pointer = c;
15807
15808   SKIP_WHITESPACE ();
15809
15810   if (! is_end_of_line[(unsigned char) *input_line_pointer])
15811     {
15812       if (S_IS_DEFINED (symbolP))
15813         {
15814           as_bad (_("ignoring attempt to redefine symbol %s"),
15815                   S_GET_NAME (symbolP));
15816           ignore_rest_of_line ();
15817           return;
15818         }
15819
15820       if (*input_line_pointer == ',')
15821         {
15822           ++input_line_pointer;
15823           SKIP_WHITESPACE ();
15824         }
15825
15826       expression (&exp);
15827       if (exp.X_op != O_symbol)
15828         {
15829           as_bad (_("bad .weakext directive"));
15830           ignore_rest_of_line ();
15831           return;
15832         }
15833       symbol_set_value_expression (symbolP, &exp);
15834     }
15835
15836   demand_empty_rest_of_line ();
15837 }
15838
15839 /* Parse a register string into a number.  Called from the ECOFF code
15840    to parse .frame.  The argument is non-zero if this is the frame
15841    register, so that we can record it in mips_frame_reg.  */
15842
15843 int
15844 tc_get_register (int frame)
15845 {
15846   unsigned int reg;
15847
15848   SKIP_WHITESPACE ();
15849   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
15850     reg = 0;
15851   if (frame)
15852     {
15853       mips_frame_reg = reg != 0 ? reg : SP;
15854       mips_frame_reg_valid = 1;
15855       mips_cprestore_valid = 0;
15856     }
15857   return reg;
15858 }
15859
15860 valueT
15861 md_section_align (asection *seg, valueT addr)
15862 {
15863   int align = bfd_get_section_alignment (stdoutput, seg);
15864
15865   /* We don't need to align ELF sections to the full alignment.
15866      However, Irix 5 may prefer that we align them at least to a 16
15867      byte boundary.  We don't bother to align the sections if we
15868      are targeted for an embedded system.  */
15869   if (strncmp (TARGET_OS, "elf", 3) == 0)
15870     return addr;
15871   if (align > 4)
15872     align = 4;
15873
15874   return ((addr + (1 << align) - 1) & (-1 << align));
15875 }
15876
15877 /* Utility routine, called from above as well.  If called while the
15878    input file is still being read, it's only an approximation.  (For
15879    example, a symbol may later become defined which appeared to be
15880    undefined earlier.)  */
15881
15882 static int
15883 nopic_need_relax (symbolS *sym, int before_relaxing)
15884 {
15885   if (sym == 0)
15886     return 0;
15887
15888   if (g_switch_value > 0)
15889     {
15890       const char *symname;
15891       int change;
15892
15893       /* Find out whether this symbol can be referenced off the $gp
15894          register.  It can be if it is smaller than the -G size or if
15895          it is in the .sdata or .sbss section.  Certain symbols can
15896          not be referenced off the $gp, although it appears as though
15897          they can.  */
15898       symname = S_GET_NAME (sym);
15899       if (symname != (const char *) NULL
15900           && (strcmp (symname, "eprol") == 0
15901               || strcmp (symname, "etext") == 0
15902               || strcmp (symname, "_gp") == 0
15903               || strcmp (symname, "edata") == 0
15904               || strcmp (symname, "_fbss") == 0
15905               || strcmp (symname, "_fdata") == 0
15906               || strcmp (symname, "_ftext") == 0
15907               || strcmp (symname, "end") == 0
15908               || strcmp (symname, "_gp_disp") == 0))
15909         change = 1;
15910       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
15911                && (0
15912 #ifndef NO_ECOFF_DEBUGGING
15913                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
15914                        && (symbol_get_obj (sym)->ecoff_extern_size
15915                            <= g_switch_value))
15916 #endif
15917                    /* We must defer this decision until after the whole
15918                       file has been read, since there might be a .extern
15919                       after the first use of this symbol.  */
15920                    || (before_relaxing
15921 #ifndef NO_ECOFF_DEBUGGING
15922                        && symbol_get_obj (sym)->ecoff_extern_size == 0
15923 #endif
15924                        && S_GET_VALUE (sym) == 0)
15925                    || (S_GET_VALUE (sym) != 0
15926                        && S_GET_VALUE (sym) <= g_switch_value)))
15927         change = 0;
15928       else
15929         {
15930           const char *segname;
15931
15932           segname = segment_name (S_GET_SEGMENT (sym));
15933           gas_assert (strcmp (segname, ".lit8") != 0
15934                   && strcmp (segname, ".lit4") != 0);
15935           change = (strcmp (segname, ".sdata") != 0
15936                     && strcmp (segname, ".sbss") != 0
15937                     && strncmp (segname, ".sdata.", 7) != 0
15938                     && strncmp (segname, ".sbss.", 6) != 0
15939                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
15940                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
15941         }
15942       return change;
15943     }
15944   else
15945     /* We are not optimizing for the $gp register.  */
15946     return 1;
15947 }
15948
15949
15950 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
15951
15952 static bfd_boolean
15953 pic_need_relax (symbolS *sym, asection *segtype)
15954 {
15955   asection *symsec;
15956
15957   /* Handle the case of a symbol equated to another symbol.  */
15958   while (symbol_equated_reloc_p (sym))
15959     {
15960       symbolS *n;
15961
15962       /* It's possible to get a loop here in a badly written program.  */
15963       n = symbol_get_value_expression (sym)->X_add_symbol;
15964       if (n == sym)
15965         break;
15966       sym = n;
15967     }
15968
15969   if (symbol_section_p (sym))
15970     return TRUE;
15971
15972   symsec = S_GET_SEGMENT (sym);
15973
15974   /* This must duplicate the test in adjust_reloc_syms.  */
15975   return (!bfd_is_und_section (symsec)
15976           && !bfd_is_abs_section (symsec)
15977           && !bfd_is_com_section (symsec)
15978           && !s_is_linkonce (sym, segtype)
15979           /* A global or weak symbol is treated as external.  */
15980           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
15981 }
15982
15983
15984 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
15985    extended opcode.  SEC is the section the frag is in.  */
15986
15987 static int
15988 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
15989 {
15990   int type;
15991   const struct mips_int_operand *operand;
15992   offsetT val;
15993   segT symsec;
15994   fragS *sym_frag;
15995
15996   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
15997     return 0;
15998   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
15999     return 1;
16000
16001   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16002   operand = mips16_immed_operand (type, FALSE);
16003
16004   sym_frag = symbol_get_frag (fragp->fr_symbol);
16005   val = S_GET_VALUE (fragp->fr_symbol);
16006   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16007
16008   if (operand->root.type == OP_PCREL)
16009     {
16010       const struct mips_pcrel_operand *pcrel_op;
16011       addressT addr;
16012       offsetT maxtiny;
16013
16014       /* We won't have the section when we are called from
16015          mips_relax_frag.  However, we will always have been called
16016          from md_estimate_size_before_relax first.  If this is a
16017          branch to a different section, we mark it as such.  If SEC is
16018          NULL, and the frag is not marked, then it must be a branch to
16019          the same section.  */
16020       pcrel_op = (const struct mips_pcrel_operand *) operand;
16021       if (sec == NULL)
16022         {
16023           if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
16024             return 1;
16025         }
16026       else
16027         {
16028           /* Must have been called from md_estimate_size_before_relax.  */
16029           if (symsec != sec)
16030             {
16031               fragp->fr_subtype =
16032                 RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16033
16034               /* FIXME: We should support this, and let the linker
16035                  catch branches and loads that are out of range.  */
16036               as_bad_where (fragp->fr_file, fragp->fr_line,
16037                             _("unsupported PC relative reference to different section"));
16038
16039               return 1;
16040             }
16041           if (fragp != sym_frag && sym_frag->fr_address == 0)
16042             /* Assume non-extended on the first relaxation pass.
16043                The address we have calculated will be bogus if this is
16044                a forward branch to another frag, as the forward frag
16045                will have fr_address == 0.  */
16046             return 0;
16047         }
16048
16049       /* In this case, we know for sure that the symbol fragment is in
16050          the same section.  If the relax_marker of the symbol fragment
16051          differs from the relax_marker of this fragment, we have not
16052          yet adjusted the symbol fragment fr_address.  We want to add
16053          in STRETCH in order to get a better estimate of the address.
16054          This particularly matters because of the shift bits.  */
16055       if (stretch != 0
16056           && sym_frag->relax_marker != fragp->relax_marker)
16057         {
16058           fragS *f;
16059
16060           /* Adjust stretch for any alignment frag.  Note that if have
16061              been expanding the earlier code, the symbol may be
16062              defined in what appears to be an earlier frag.  FIXME:
16063              This doesn't handle the fr_subtype field, which specifies
16064              a maximum number of bytes to skip when doing an
16065              alignment.  */
16066           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
16067             {
16068               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
16069                 {
16070                   if (stretch < 0)
16071                     stretch = - ((- stretch)
16072                                  & ~ ((1 << (int) f->fr_offset) - 1));
16073                   else
16074                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
16075                   if (stretch == 0)
16076                     break;
16077                 }
16078             }
16079           if (f != NULL)
16080             val += stretch;
16081         }
16082
16083       addr = fragp->fr_address + fragp->fr_fix;
16084
16085       /* The base address rules are complicated.  The base address of
16086          a branch is the following instruction.  The base address of a
16087          PC relative load or add is the instruction itself, but if it
16088          is in a delay slot (in which case it can not be extended) use
16089          the address of the instruction whose delay slot it is in.  */
16090       if (pcrel_op->include_isa_bit)
16091         {
16092           addr += 2;
16093
16094           /* If we are currently assuming that this frag should be
16095              extended, then, the current address is two bytes
16096              higher.  */
16097           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16098             addr += 2;
16099
16100           /* Ignore the low bit in the target, since it will be set
16101              for a text label.  */
16102           val &= -2;
16103         }
16104       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
16105         addr -= 4;
16106       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
16107         addr -= 2;
16108
16109       val -= addr & -(1 << pcrel_op->align_log2);
16110
16111       /* If any of the shifted bits are set, we must use an extended
16112          opcode.  If the address depends on the size of this
16113          instruction, this can lead to a loop, so we arrange to always
16114          use an extended opcode.  We only check this when we are in
16115          the main relaxation loop, when SEC is NULL.  */
16116       if ((val & ((1 << operand->shift) - 1)) != 0 && sec == NULL)
16117         {
16118           fragp->fr_subtype =
16119             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16120           return 1;
16121         }
16122
16123       /* If we are about to mark a frag as extended because the value
16124          is precisely the next value above maxtiny, then there is a
16125          chance of an infinite loop as in the following code:
16126              la $4,foo
16127              .skip      1020
16128              .align     2
16129            foo:
16130          In this case when the la is extended, foo is 0x3fc bytes
16131          away, so the la can be shrunk, but then foo is 0x400 away, so
16132          the la must be extended.  To avoid this loop, we mark the
16133          frag as extended if it was small, and is about to become
16134          extended with the next value above maxtiny.  */
16135       maxtiny = mips_int_operand_max (operand);
16136       if (val == maxtiny + (1 << operand->shift)
16137           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype)
16138           && sec == NULL)
16139         {
16140           fragp->fr_subtype =
16141             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
16142           return 1;
16143         }
16144     }
16145   else if (symsec != absolute_section && sec != NULL)
16146     as_bad_where (fragp->fr_file, fragp->fr_line, _("unsupported relocation"));
16147
16148   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
16149 }
16150
16151 /* Compute the length of a branch sequence, and adjust the
16152    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
16153    worst-case length is computed, with UPDATE being used to indicate
16154    whether an unconditional (-1), branch-likely (+1) or regular (0)
16155    branch is to be computed.  */
16156 static int
16157 relaxed_branch_length (fragS *fragp, asection *sec, int update)
16158 {
16159   bfd_boolean toofar;
16160   int length;
16161
16162   if (fragp
16163       && S_IS_DEFINED (fragp->fr_symbol)
16164       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16165     {
16166       addressT addr;
16167       offsetT val;
16168
16169       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16170
16171       addr = fragp->fr_address + fragp->fr_fix + 4;
16172
16173       val -= addr;
16174
16175       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
16176     }
16177   else if (fragp)
16178     /* If the symbol is not defined or it's in a different segment,
16179        assume the user knows what's going on and emit a short
16180        branch.  */
16181     toofar = FALSE;
16182   else
16183     toofar = TRUE;
16184
16185   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16186     fragp->fr_subtype
16187       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
16188                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
16189                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
16190                              RELAX_BRANCH_LINK (fragp->fr_subtype),
16191                              toofar);
16192
16193   length = 4;
16194   if (toofar)
16195     {
16196       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
16197         length += 8;
16198
16199       if (mips_pic != NO_PIC)
16200         {
16201           /* Additional space for PIC loading of target address.  */
16202           length += 8;
16203           if (mips_opts.isa == ISA_MIPS1)
16204             /* Additional space for $at-stabilizing nop.  */
16205             length += 4;
16206         }
16207
16208       /* If branch is conditional.  */
16209       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
16210         length += 8;
16211     }
16212
16213   return length;
16214 }
16215
16216 /* Compute the length of a branch sequence, and adjust the
16217    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
16218    worst-case length is computed, with UPDATE being used to indicate
16219    whether an unconditional (-1), or regular (0) branch is to be
16220    computed.  */
16221
16222 static int
16223 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
16224 {
16225   bfd_boolean toofar;
16226   int length;
16227
16228   if (fragp
16229       && S_IS_DEFINED (fragp->fr_symbol)
16230       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16231     {
16232       addressT addr;
16233       offsetT val;
16234
16235       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16236       /* Ignore the low bit in the target, since it will be set
16237          for a text label.  */
16238       if ((val & 1) != 0)
16239         --val;
16240
16241       addr = fragp->fr_address + fragp->fr_fix + 4;
16242
16243       val -= addr;
16244
16245       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
16246     }
16247   else if (fragp)
16248     /* If the symbol is not defined or it's in a different segment,
16249        assume the user knows what's going on and emit a short
16250        branch.  */
16251     toofar = FALSE;
16252   else
16253     toofar = TRUE;
16254
16255   if (fragp && update
16256       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16257     fragp->fr_subtype = (toofar
16258                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
16259                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
16260
16261   length = 4;
16262   if (toofar)
16263     {
16264       bfd_boolean compact_known = fragp != NULL;
16265       bfd_boolean compact = FALSE;
16266       bfd_boolean uncond;
16267
16268       if (compact_known)
16269         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16270       if (fragp)
16271         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
16272       else
16273         uncond = update < 0;
16274
16275       /* If label is out of range, we turn branch <br>:
16276
16277                 <br>    label                   # 4 bytes
16278             0:
16279
16280          into:
16281
16282                 j       label                   # 4 bytes
16283                 nop                             # 2 bytes if compact && !PIC
16284             0:
16285        */
16286       if (mips_pic == NO_PIC && (!compact_known || compact))
16287         length += 2;
16288
16289       /* If assembling PIC code, we further turn:
16290
16291                         j       label                   # 4 bytes
16292
16293          into:
16294
16295                         lw/ld   at, %got(label)(gp)     # 4 bytes
16296                         d/addiu at, %lo(label)          # 4 bytes
16297                         jr/c    at                      # 2 bytes
16298        */
16299       if (mips_pic != NO_PIC)
16300         length += 6;
16301
16302       /* If branch <br> is conditional, we prepend negated branch <brneg>:
16303
16304                         <brneg> 0f                      # 4 bytes
16305                         nop                             # 2 bytes if !compact
16306        */
16307       if (!uncond)
16308         length += (compact_known && compact) ? 4 : 6;
16309     }
16310
16311   return length;
16312 }
16313
16314 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
16315    bit accordingly.  */
16316
16317 static int
16318 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
16319 {
16320   bfd_boolean toofar;
16321
16322   if (fragp
16323       && S_IS_DEFINED (fragp->fr_symbol)
16324       && sec == S_GET_SEGMENT (fragp->fr_symbol))
16325     {
16326       addressT addr;
16327       offsetT val;
16328       int type;
16329
16330       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
16331       /* Ignore the low bit in the target, since it will be set
16332          for a text label.  */
16333       if ((val & 1) != 0)
16334         --val;
16335
16336       /* Assume this is a 2-byte branch.  */
16337       addr = fragp->fr_address + fragp->fr_fix + 2;
16338
16339       /* We try to avoid the infinite loop by not adding 2 more bytes for
16340          long branches.  */
16341
16342       val -= addr;
16343
16344       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16345       if (type == 'D')
16346         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
16347       else if (type == 'E')
16348         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
16349       else
16350         abort ();
16351     }
16352   else
16353     /* If the symbol is not defined or it's in a different segment,
16354        we emit a normal 32-bit branch.  */
16355     toofar = TRUE;
16356
16357   if (fragp && update
16358       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16359     fragp->fr_subtype
16360       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
16361                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
16362
16363   if (toofar)
16364     return 4;
16365
16366   return 2;
16367 }
16368
16369 /* Estimate the size of a frag before relaxing.  Unless this is the
16370    mips16, we are not really relaxing here, and the final size is
16371    encoded in the subtype information.  For the mips16, we have to
16372    decide whether we are using an extended opcode or not.  */
16373
16374 int
16375 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
16376 {
16377   int change;
16378
16379   if (RELAX_BRANCH_P (fragp->fr_subtype))
16380     {
16381
16382       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
16383
16384       return fragp->fr_var;
16385     }
16386
16387   if (RELAX_MIPS16_P (fragp->fr_subtype))
16388     /* We don't want to modify the EXTENDED bit here; it might get us
16389        into infinite loops.  We change it only in mips_relax_frag().  */
16390     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
16391
16392   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16393     {
16394       int length = 4;
16395
16396       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16397         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
16398       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16399         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
16400       fragp->fr_var = length;
16401
16402       return length;
16403     }
16404
16405   if (mips_pic == NO_PIC)
16406     change = nopic_need_relax (fragp->fr_symbol, 0);
16407   else if (mips_pic == SVR4_PIC)
16408     change = pic_need_relax (fragp->fr_symbol, segtype);
16409   else if (mips_pic == VXWORKS_PIC)
16410     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
16411     change = 0;
16412   else
16413     abort ();
16414
16415   if (change)
16416     {
16417       fragp->fr_subtype |= RELAX_USE_SECOND;
16418       return -RELAX_FIRST (fragp->fr_subtype);
16419     }
16420   else
16421     return -RELAX_SECOND (fragp->fr_subtype);
16422 }
16423
16424 /* This is called to see whether a reloc against a defined symbol
16425    should be converted into a reloc against a section.  */
16426
16427 int
16428 mips_fix_adjustable (fixS *fixp)
16429 {
16430   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
16431       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16432     return 0;
16433
16434   if (fixp->fx_addsy == NULL)
16435     return 1;
16436
16437   /* If symbol SYM is in a mergeable section, relocations of the form
16438      SYM + 0 can usually be made section-relative.  The mergeable data
16439      is then identified by the section offset rather than by the symbol.
16440
16441      However, if we're generating REL LO16 relocations, the offset is split
16442      between the LO16 and parterning high part relocation.  The linker will
16443      need to recalculate the complete offset in order to correctly identify
16444      the merge data.
16445
16446      The linker has traditionally not looked for the parterning high part
16447      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
16448      placed anywhere.  Rather than break backwards compatibility by changing
16449      this, it seems better not to force the issue, and instead keep the
16450      original symbol.  This will work with either linker behavior.  */
16451   if ((lo16_reloc_p (fixp->fx_r_type)
16452        || reloc_needs_lo_p (fixp->fx_r_type))
16453       && HAVE_IN_PLACE_ADDENDS
16454       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
16455     return 0;
16456
16457   /* There is no place to store an in-place offset for JALR relocations.
16458      Likewise an in-range offset of limited PC-relative relocations may
16459      overflow the in-place relocatable field if recalculated against the
16460      start address of the symbol's containing section.  */
16461   if (HAVE_IN_PLACE_ADDENDS
16462       && (limited_pcrel_reloc_p (fixp->fx_r_type)
16463           || jalr_reloc_p (fixp->fx_r_type)))
16464     return 0;
16465
16466   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
16467      to a floating-point stub.  The same is true for non-R_MIPS16_26
16468      relocations against MIPS16 functions; in this case, the stub becomes
16469      the function's canonical address.
16470
16471      Floating-point stubs are stored in unique .mips16.call.* or
16472      .mips16.fn.* sections.  If a stub T for function F is in section S,
16473      the first relocation in section S must be against F; this is how the
16474      linker determines the target function.  All relocations that might
16475      resolve to T must also be against F.  We therefore have the following
16476      restrictions, which are given in an intentionally-redundant way:
16477
16478        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
16479           symbols.
16480
16481        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
16482           if that stub might be used.
16483
16484        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
16485           symbols.
16486
16487        4. We cannot reduce a stub's relocations against MIPS16 symbols if
16488           that stub might be used.
16489
16490      There is a further restriction:
16491
16492        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
16493           R_MICROMIPS_26_S1) against MIPS16 or microMIPS symbols on
16494           targets with in-place addends; the relocation field cannot
16495           encode the low bit.
16496
16497      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
16498      against a MIPS16 symbol.  We deal with (5) by by not reducing any
16499      such relocations on REL targets.
16500
16501      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
16502      relocation against some symbol R, no relocation against R may be
16503      reduced.  (Note that this deals with (2) as well as (1) because
16504      relocations against global symbols will never be reduced on ELF
16505      targets.)  This approach is a little simpler than trying to detect
16506      stub sections, and gives the "all or nothing" per-symbol consistency
16507      that we have for MIPS16 symbols.  */
16508   if (fixp->fx_subsy == NULL
16509       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
16510           || *symbol_get_tc (fixp->fx_addsy)
16511           || (HAVE_IN_PLACE_ADDENDS
16512               && ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
16513               && jmp_reloc_p (fixp->fx_r_type))))
16514     return 0;
16515
16516   return 1;
16517 }
16518
16519 /* Translate internal representation of relocation info to BFD target
16520    format.  */
16521
16522 arelent **
16523 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
16524 {
16525   static arelent *retval[4];
16526   arelent *reloc;
16527   bfd_reloc_code_real_type code;
16528
16529   memset (retval, 0, sizeof(retval));
16530   reloc = retval[0] = (arelent *) xcalloc (1, sizeof (arelent));
16531   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
16532   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
16533   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
16534
16535   if (fixp->fx_pcrel)
16536     {
16537       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
16538                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
16539                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
16540                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
16541                   || fixp->fx_r_type == BFD_RELOC_32_PCREL);
16542
16543       /* At this point, fx_addnumber is "symbol offset - pcrel address".
16544          Relocations want only the symbol offset.  */
16545       reloc->addend = fixp->fx_addnumber + reloc->address;
16546     }
16547   else
16548     reloc->addend = fixp->fx_addnumber;
16549
16550   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
16551      entry to be used in the relocation's section offset.  */
16552   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
16553     {
16554       reloc->address = reloc->addend;
16555       reloc->addend = 0;
16556     }
16557
16558   code = fixp->fx_r_type;
16559
16560   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
16561   if (reloc->howto == NULL)
16562     {
16563       as_bad_where (fixp->fx_file, fixp->fx_line,
16564                     _("cannot represent %s relocation in this object file"
16565                       " format"),
16566                     bfd_get_reloc_code_name (code));
16567       retval[0] = NULL;
16568     }
16569
16570   return retval;
16571 }
16572
16573 /* Relax a machine dependent frag.  This returns the amount by which
16574    the current size of the frag should change.  */
16575
16576 int
16577 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
16578 {
16579   if (RELAX_BRANCH_P (fragp->fr_subtype))
16580     {
16581       offsetT old_var = fragp->fr_var;
16582
16583       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
16584
16585       return fragp->fr_var - old_var;
16586     }
16587
16588   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16589     {
16590       offsetT old_var = fragp->fr_var;
16591       offsetT new_var = 4;
16592
16593       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
16594         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
16595       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
16596         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
16597       fragp->fr_var = new_var;
16598
16599       return new_var - old_var;
16600     }
16601
16602   if (! RELAX_MIPS16_P (fragp->fr_subtype))
16603     return 0;
16604
16605   if (mips16_extended_frag (fragp, NULL, stretch))
16606     {
16607       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16608         return 0;
16609       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
16610       return 2;
16611     }
16612   else
16613     {
16614       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
16615         return 0;
16616       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
16617       return -2;
16618     }
16619
16620   return 0;
16621 }
16622
16623 /* Convert a machine dependent frag.  */
16624
16625 void
16626 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
16627 {
16628   if (RELAX_BRANCH_P (fragp->fr_subtype))
16629     {
16630       char *buf;
16631       unsigned long insn;
16632       expressionS exp;
16633       fixS *fixp;
16634
16635       buf = fragp->fr_literal + fragp->fr_fix;
16636       insn = read_insn (buf);
16637
16638       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
16639         {
16640           /* We generate a fixup instead of applying it right now
16641              because, if there are linker relaxations, we're going to
16642              need the relocations.  */
16643           exp.X_op = O_symbol;
16644           exp.X_add_symbol = fragp->fr_symbol;
16645           exp.X_add_number = fragp->fr_offset;
16646
16647           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16648                               BFD_RELOC_16_PCREL_S2);
16649           fixp->fx_file = fragp->fr_file;
16650           fixp->fx_line = fragp->fr_line;
16651
16652           buf = write_insn (buf, insn);
16653         }
16654       else
16655         {
16656           int i;
16657
16658           as_warn_where (fragp->fr_file, fragp->fr_line,
16659                          _("relaxed out-of-range branch into a jump"));
16660
16661           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
16662             goto uncond;
16663
16664           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16665             {
16666               /* Reverse the branch.  */
16667               switch ((insn >> 28) & 0xf)
16668                 {
16669                 case 4:
16670                   if ((insn & 0xff000000) == 0x47000000
16671                       || (insn & 0xff600000) == 0x45600000)
16672                     {
16673                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
16674                          reversed by tweaking bit 23.  */
16675                       insn ^= 0x00800000;
16676                     }
16677                   else
16678                     {
16679                       /* bc[0-3][tf]l? instructions can have the condition
16680                          reversed by tweaking a single TF bit, and their
16681                          opcodes all have 0x4???????.  */
16682                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
16683                       insn ^= 0x00010000;
16684                     }
16685                   break;
16686
16687                 case 0:
16688                   /* bltz       0x04000000      bgez    0x04010000
16689                      bltzal     0x04100000      bgezal  0x04110000  */
16690                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
16691                   insn ^= 0x00010000;
16692                   break;
16693
16694                 case 1:
16695                   /* beq        0x10000000      bne     0x14000000
16696                      blez       0x18000000      bgtz    0x1c000000  */
16697                   insn ^= 0x04000000;
16698                   break;
16699
16700                 default:
16701                   abort ();
16702                 }
16703             }
16704
16705           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16706             {
16707               /* Clear the and-link bit.  */
16708               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
16709
16710               /* bltzal         0x04100000      bgezal  0x04110000
16711                  bltzall        0x04120000      bgezall 0x04130000  */
16712               insn &= ~0x00100000;
16713             }
16714
16715           /* Branch over the branch (if the branch was likely) or the
16716              full jump (not likely case).  Compute the offset from the
16717              current instruction to branch to.  */
16718           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16719             i = 16;
16720           else
16721             {
16722               /* How many bytes in instructions we've already emitted?  */
16723               i = buf - fragp->fr_literal - fragp->fr_fix;
16724               /* How many bytes in instructions from here to the end?  */
16725               i = fragp->fr_var - i;
16726             }
16727           /* Convert to instruction count.  */
16728           i >>= 2;
16729           /* Branch counts from the next instruction.  */
16730           i--;
16731           insn |= i;
16732           /* Branch over the jump.  */
16733           buf = write_insn (buf, insn);
16734
16735           /* nop */
16736           buf = write_insn (buf, 0);
16737
16738           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
16739             {
16740               /* beql $0, $0, 2f */
16741               insn = 0x50000000;
16742               /* Compute the PC offset from the current instruction to
16743                  the end of the variable frag.  */
16744               /* How many bytes in instructions we've already emitted?  */
16745               i = buf - fragp->fr_literal - fragp->fr_fix;
16746               /* How many bytes in instructions from here to the end?  */
16747               i = fragp->fr_var - i;
16748               /* Convert to instruction count.  */
16749               i >>= 2;
16750               /* Don't decrement i, because we want to branch over the
16751                  delay slot.  */
16752               insn |= i;
16753
16754               buf = write_insn (buf, insn);
16755               buf = write_insn (buf, 0);
16756             }
16757
16758         uncond:
16759           if (mips_pic == NO_PIC)
16760             {
16761               /* j or jal.  */
16762               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
16763                       ? 0x0c000000 : 0x08000000);
16764               exp.X_op = O_symbol;
16765               exp.X_add_symbol = fragp->fr_symbol;
16766               exp.X_add_number = fragp->fr_offset;
16767
16768               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16769                                   FALSE, BFD_RELOC_MIPS_JMP);
16770               fixp->fx_file = fragp->fr_file;
16771               fixp->fx_line = fragp->fr_line;
16772
16773               buf = write_insn (buf, insn);
16774             }
16775           else
16776             {
16777               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
16778
16779               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
16780               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
16781               insn |= at << OP_SH_RT;
16782               exp.X_op = O_symbol;
16783               exp.X_add_symbol = fragp->fr_symbol;
16784               exp.X_add_number = fragp->fr_offset;
16785
16786               if (fragp->fr_offset)
16787                 {
16788                   exp.X_add_symbol = make_expr_symbol (&exp);
16789                   exp.X_add_number = 0;
16790                 }
16791
16792               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16793                                   FALSE, BFD_RELOC_MIPS_GOT16);
16794               fixp->fx_file = fragp->fr_file;
16795               fixp->fx_line = fragp->fr_line;
16796
16797               buf = write_insn (buf, insn);
16798
16799               if (mips_opts.isa == ISA_MIPS1)
16800                 /* nop */
16801                 buf = write_insn (buf, 0);
16802
16803               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
16804               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
16805               insn |= at << OP_SH_RS | at << OP_SH_RT;
16806
16807               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
16808                                   FALSE, BFD_RELOC_LO16);
16809               fixp->fx_file = fragp->fr_file;
16810               fixp->fx_line = fragp->fr_line;
16811
16812               buf = write_insn (buf, insn);
16813
16814               /* j(al)r $at.  */
16815               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
16816                 insn = 0x0000f809;
16817               else
16818                 insn = 0x00000008;
16819               insn |= at << OP_SH_RS;
16820
16821               buf = write_insn (buf, insn);
16822             }
16823         }
16824
16825       fragp->fr_fix += fragp->fr_var;
16826       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16827       return;
16828     }
16829
16830   /* Relax microMIPS branches.  */
16831   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
16832     {
16833       char *buf = fragp->fr_literal + fragp->fr_fix;
16834       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
16835       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
16836       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
16837       bfd_boolean short_ds;
16838       unsigned long insn;
16839       expressionS exp;
16840       fixS *fixp;
16841
16842       exp.X_op = O_symbol;
16843       exp.X_add_symbol = fragp->fr_symbol;
16844       exp.X_add_number = fragp->fr_offset;
16845
16846       fragp->fr_fix += fragp->fr_var;
16847
16848       /* Handle 16-bit branches that fit or are forced to fit.  */
16849       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
16850         {
16851           /* We generate a fixup instead of applying it right now,
16852              because if there is linker relaxation, we're going to
16853              need the relocations.  */
16854           if (type == 'D')
16855             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16856                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
16857           else if (type == 'E')
16858             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
16859                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
16860           else
16861             abort ();
16862
16863           fixp->fx_file = fragp->fr_file;
16864           fixp->fx_line = fragp->fr_line;
16865
16866           /* These relocations can have an addend that won't fit in
16867              2 octets.  */
16868           fixp->fx_no_overflow = 1;
16869
16870           return;
16871         }
16872
16873       /* Handle 32-bit branches that fit or are forced to fit.  */
16874       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16875           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16876         {
16877           /* We generate a fixup instead of applying it right now,
16878              because if there is linker relaxation, we're going to
16879              need the relocations.  */
16880           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
16881                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
16882           fixp->fx_file = fragp->fr_file;
16883           fixp->fx_line = fragp->fr_line;
16884
16885           if (type == 0)
16886             return;
16887         }
16888
16889       /* Relax 16-bit branches to 32-bit branches.  */
16890       if (type != 0)
16891         {
16892           insn = read_compressed_insn (buf, 2);
16893
16894           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
16895             insn = 0x94000000;                          /* beq  */
16896           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
16897             {
16898               unsigned long regno;
16899
16900               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
16901               regno = micromips_to_32_reg_d_map [regno];
16902               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
16903               insn |= regno << MICROMIPSOP_SH_RS;
16904             }
16905           else
16906             abort ();
16907
16908           /* Nothing else to do, just write it out.  */
16909           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
16910               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
16911             {
16912               buf = write_compressed_insn (buf, insn, 4);
16913               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
16914               return;
16915             }
16916         }
16917       else
16918         insn = read_compressed_insn (buf, 4);
16919
16920       /* Relax 32-bit branches to a sequence of instructions.  */
16921       as_warn_where (fragp->fr_file, fragp->fr_line,
16922                      _("relaxed out-of-range branch into a jump"));
16923
16924       /* Set the short-delay-slot bit.  */
16925       short_ds = al && (insn & 0x02000000) != 0;
16926
16927       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
16928         {
16929           symbolS *l;
16930
16931           /* Reverse the branch.  */
16932           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
16933               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
16934             insn ^= 0x20000000;
16935           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
16936                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
16937                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
16938                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
16939                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
16940                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
16941                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
16942                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
16943                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
16944                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
16945             insn ^= 0x00400000;
16946           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
16947                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
16948                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
16949                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
16950             insn ^= 0x00200000;
16951           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
16952                                                                    BNZ.df  */
16953                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
16954                                                                    BNZ.V */
16955             insn ^= 0x00800000;
16956           else
16957             abort ();
16958
16959           if (al)
16960             {
16961               /* Clear the and-link and short-delay-slot bits.  */
16962               gas_assert ((insn & 0xfda00000) == 0x40200000);
16963
16964               /* bltzal  0x40200000     bgezal  0x40600000  */
16965               /* bltzals 0x42200000     bgezals 0x42600000  */
16966               insn &= ~0x02200000;
16967             }
16968
16969           /* Make a label at the end for use with the branch.  */
16970           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
16971           micromips_label_inc ();
16972           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
16973
16974           /* Refer to it.  */
16975           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
16976                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
16977           fixp->fx_file = fragp->fr_file;
16978           fixp->fx_line = fragp->fr_line;
16979
16980           /* Branch over the jump.  */
16981           buf = write_compressed_insn (buf, insn, 4);
16982           if (!compact)
16983             /* nop */
16984             buf = write_compressed_insn (buf, 0x0c00, 2);
16985         }
16986
16987       if (mips_pic == NO_PIC)
16988         {
16989           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
16990
16991           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
16992           insn = al ? jal : 0xd4000000;
16993
16994           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
16995                               BFD_RELOC_MICROMIPS_JMP);
16996           fixp->fx_file = fragp->fr_file;
16997           fixp->fx_line = fragp->fr_line;
16998
16999           buf = write_compressed_insn (buf, insn, 4);
17000           if (compact)
17001             /* nop */
17002             buf = write_compressed_insn (buf, 0x0c00, 2);
17003         }
17004       else
17005         {
17006           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
17007           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
17008           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
17009
17010           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
17011           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
17012           insn |= at << MICROMIPSOP_SH_RT;
17013
17014           if (exp.X_add_number)
17015             {
17016               exp.X_add_symbol = make_expr_symbol (&exp);
17017               exp.X_add_number = 0;
17018             }
17019
17020           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17021                               BFD_RELOC_MICROMIPS_GOT16);
17022           fixp->fx_file = fragp->fr_file;
17023           fixp->fx_line = fragp->fr_line;
17024
17025           buf = write_compressed_insn (buf, insn, 4);
17026
17027           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
17028           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
17029           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
17030
17031           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17032                               BFD_RELOC_MICROMIPS_LO16);
17033           fixp->fx_file = fragp->fr_file;
17034           fixp->fx_line = fragp->fr_line;
17035
17036           buf = write_compressed_insn (buf, insn, 4);
17037
17038           /* jr/jrc/jalr/jalrs $at  */
17039           insn = al ? jalr : jr;
17040           insn |= at << MICROMIPSOP_SH_MJ;
17041
17042           buf = write_compressed_insn (buf, insn, 2);
17043         }
17044
17045       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17046       return;
17047     }
17048
17049   if (RELAX_MIPS16_P (fragp->fr_subtype))
17050     {
17051       int type;
17052       const struct mips_int_operand *operand;
17053       offsetT val;
17054       char *buf;
17055       unsigned int user_length, length;
17056       unsigned long insn;
17057       bfd_boolean ext;
17058
17059       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
17060       operand = mips16_immed_operand (type, FALSE);
17061
17062       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
17063       val = resolve_symbol_value (fragp->fr_symbol);
17064       if (operand->root.type == OP_PCREL)
17065         {
17066           const struct mips_pcrel_operand *pcrel_op;
17067           addressT addr;
17068
17069           pcrel_op = (const struct mips_pcrel_operand *) operand;
17070           addr = fragp->fr_address + fragp->fr_fix;
17071
17072           /* The rules for the base address of a PC relative reloc are
17073              complicated; see mips16_extended_frag.  */
17074           if (pcrel_op->include_isa_bit)
17075             {
17076               addr += 2;
17077               if (ext)
17078                 addr += 2;
17079               /* Ignore the low bit in the target, since it will be
17080                  set for a text label.  */
17081               val &= -2;
17082             }
17083           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17084             addr -= 4;
17085           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17086             addr -= 2;
17087
17088           addr &= -(1 << pcrel_op->align_log2);
17089           val -= addr;
17090
17091           /* Make sure the section winds up with the alignment we have
17092              assumed.  */
17093           if (operand->shift > 0)
17094             record_alignment (asec, operand->shift);
17095         }
17096
17097       if (ext
17098           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
17099               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
17100         as_warn_where (fragp->fr_file, fragp->fr_line,
17101                        _("extended instruction in delay slot"));
17102
17103       buf = fragp->fr_literal + fragp->fr_fix;
17104
17105       insn = read_compressed_insn (buf, 2);
17106       if (ext)
17107         insn |= MIPS16_EXTEND;
17108
17109       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
17110         user_length = 4;
17111       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
17112         user_length = 2;
17113       else
17114         user_length = 0;
17115
17116       mips16_immed (fragp->fr_file, fragp->fr_line, type,
17117                     BFD_RELOC_UNUSED, val, user_length, &insn);
17118
17119       length = (ext ? 4 : 2);
17120       gas_assert (mips16_opcode_length (insn) == length);
17121       write_compressed_insn (buf, insn, length);
17122       fragp->fr_fix += length;
17123     }
17124   else
17125     {
17126       relax_substateT subtype = fragp->fr_subtype;
17127       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
17128       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
17129       int first, second;
17130       fixS *fixp;
17131
17132       first = RELAX_FIRST (subtype);
17133       second = RELAX_SECOND (subtype);
17134       fixp = (fixS *) fragp->fr_opcode;
17135
17136       /* If the delay slot chosen does not match the size of the instruction,
17137          then emit a warning.  */
17138       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
17139            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
17140         {
17141           relax_substateT s;
17142           const char *msg;
17143
17144           s = subtype & (RELAX_DELAY_SLOT_16BIT
17145                          | RELAX_DELAY_SLOT_SIZE_FIRST
17146                          | RELAX_DELAY_SLOT_SIZE_SECOND);
17147           msg = macro_warning (s);
17148           if (msg != NULL)
17149             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17150           subtype &= ~s;
17151         }
17152
17153       /* Possibly emit a warning if we've chosen the longer option.  */
17154       if (use_second == second_longer)
17155         {
17156           relax_substateT s;
17157           const char *msg;
17158
17159           s = (subtype
17160                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
17161           msg = macro_warning (s);
17162           if (msg != NULL)
17163             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
17164           subtype &= ~s;
17165         }
17166
17167       /* Go through all the fixups for the first sequence.  Disable them
17168          (by marking them as done) if we're going to use the second
17169          sequence instead.  */
17170       while (fixp
17171              && fixp->fx_frag == fragp
17172              && fixp->fx_where < fragp->fr_fix - second)
17173         {
17174           if (subtype & RELAX_USE_SECOND)
17175             fixp->fx_done = 1;
17176           fixp = fixp->fx_next;
17177         }
17178
17179       /* Go through the fixups for the second sequence.  Disable them if
17180          we're going to use the first sequence, otherwise adjust their
17181          addresses to account for the relaxation.  */
17182       while (fixp && fixp->fx_frag == fragp)
17183         {
17184           if (subtype & RELAX_USE_SECOND)
17185             fixp->fx_where -= first;
17186           else
17187             fixp->fx_done = 1;
17188           fixp = fixp->fx_next;
17189         }
17190
17191       /* Now modify the frag contents.  */
17192       if (subtype & RELAX_USE_SECOND)
17193         {
17194           char *start;
17195
17196           start = fragp->fr_literal + fragp->fr_fix - first - second;
17197           memmove (start, start + first, second);
17198           fragp->fr_fix -= first;
17199         }
17200       else
17201         fragp->fr_fix -= second;
17202     }
17203 }
17204
17205 /* This function is called after the relocs have been generated.
17206    We've been storing mips16 text labels as odd.  Here we convert them
17207    back to even for the convenience of the debugger.  */
17208
17209 void
17210 mips_frob_file_after_relocs (void)
17211 {
17212   asymbol **syms;
17213   unsigned int count, i;
17214
17215   syms = bfd_get_outsymbols (stdoutput);
17216   count = bfd_get_symcount (stdoutput);
17217   for (i = 0; i < count; i++, syms++)
17218     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
17219         && ((*syms)->value & 1) != 0)
17220       {
17221         (*syms)->value &= ~1;
17222         /* If the symbol has an odd size, it was probably computed
17223            incorrectly, so adjust that as well.  */
17224         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
17225           ++elf_symbol (*syms)->internal_elf_sym.st_size;
17226       }
17227 }
17228
17229 /* This function is called whenever a label is defined, including fake
17230    labels instantiated off the dot special symbol.  It is used when
17231    handling branch delays; if a branch has a label, we assume we cannot
17232    move it.  This also bumps the value of the symbol by 1 in compressed
17233    code.  */
17234
17235 static void
17236 mips_record_label (symbolS *sym)
17237 {
17238   segment_info_type *si = seg_info (now_seg);
17239   struct insn_label_list *l;
17240
17241   if (free_insn_labels == NULL)
17242     l = (struct insn_label_list *) xmalloc (sizeof *l);
17243   else
17244     {
17245       l = free_insn_labels;
17246       free_insn_labels = l->next;
17247     }
17248
17249   l->label = sym;
17250   l->next = si->label_list;
17251   si->label_list = l;
17252 }
17253
17254 /* This function is called as tc_frob_label() whenever a label is defined
17255    and adds a DWARF-2 record we only want for true labels.  */
17256
17257 void
17258 mips_define_label (symbolS *sym)
17259 {
17260   mips_record_label (sym);
17261   dwarf2_emit_label (sym);
17262 }
17263
17264 /* This function is called by tc_new_dot_label whenever a new dot symbol
17265    is defined.  */
17266
17267 void
17268 mips_add_dot_label (symbolS *sym)
17269 {
17270   mips_record_label (sym);
17271   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
17272     mips_compressed_mark_label (sym);
17273 }
17274 \f
17275 /* Some special processing for a MIPS ELF file.  */
17276
17277 void
17278 mips_elf_final_processing (void)
17279 {
17280   /* Write out the register information.  */
17281   if (mips_abi != N64_ABI)
17282     {
17283       Elf32_RegInfo s;
17284
17285       s.ri_gprmask = mips_gprmask;
17286       s.ri_cprmask[0] = mips_cprmask[0];
17287       s.ri_cprmask[1] = mips_cprmask[1];
17288       s.ri_cprmask[2] = mips_cprmask[2];
17289       s.ri_cprmask[3] = mips_cprmask[3];
17290       /* The gp_value field is set by the MIPS ELF backend.  */
17291
17292       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
17293                                        ((Elf32_External_RegInfo *)
17294                                         mips_regmask_frag));
17295     }
17296   else
17297     {
17298       Elf64_Internal_RegInfo s;
17299
17300       s.ri_gprmask = mips_gprmask;
17301       s.ri_pad = 0;
17302       s.ri_cprmask[0] = mips_cprmask[0];
17303       s.ri_cprmask[1] = mips_cprmask[1];
17304       s.ri_cprmask[2] = mips_cprmask[2];
17305       s.ri_cprmask[3] = mips_cprmask[3];
17306       /* The gp_value field is set by the MIPS ELF backend.  */
17307
17308       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
17309                                        ((Elf64_External_RegInfo *)
17310                                         mips_regmask_frag));
17311     }
17312
17313   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
17314      sort of BFD interface for this.  */
17315   if (mips_any_noreorder)
17316     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
17317   if (mips_pic != NO_PIC)
17318     {
17319       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
17320       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17321     }
17322   if (mips_abicalls)
17323     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
17324
17325   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
17326      defined at present; this might need to change in future.  */
17327   if (file_ase_mips16)
17328     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
17329   if (file_ase_micromips)
17330     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
17331   if (file_ase & ASE_MDMX)
17332     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
17333
17334   /* Set the MIPS ELF ABI flags.  */
17335   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
17336     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
17337   else if (mips_abi == O64_ABI)
17338     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
17339   else if (mips_abi == EABI_ABI)
17340     {
17341       if (!file_mips_gp32)
17342         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
17343       else
17344         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
17345     }
17346   else if (mips_abi == N32_ABI)
17347     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
17348
17349   /* Nothing to do for N64_ABI.  */
17350
17351   if (mips_32bitmode)
17352     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
17353
17354   if (mips_flag_nan2008)
17355     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
17356
17357   /* 32 bit code with 64 bit FP registers.  */
17358   if (!file_mips_fp32 && ABI_NEEDS_32BIT_REGS (mips_abi))
17359     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
17360 }
17361 \f
17362 typedef struct proc {
17363   symbolS *func_sym;
17364   symbolS *func_end_sym;
17365   unsigned long reg_mask;
17366   unsigned long reg_offset;
17367   unsigned long fpreg_mask;
17368   unsigned long fpreg_offset;
17369   unsigned long frame_offset;
17370   unsigned long frame_reg;
17371   unsigned long pc_reg;
17372 } procS;
17373
17374 static procS cur_proc;
17375 static procS *cur_proc_ptr;
17376 static int numprocs;
17377
17378 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
17379    as "2", and a normal nop as "0".  */
17380
17381 #define NOP_OPCODE_MIPS         0
17382 #define NOP_OPCODE_MIPS16       1
17383 #define NOP_OPCODE_MICROMIPS    2
17384
17385 char
17386 mips_nop_opcode (void)
17387 {
17388   if (seg_info (now_seg)->tc_segment_info_data.micromips)
17389     return NOP_OPCODE_MICROMIPS;
17390   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
17391     return NOP_OPCODE_MIPS16;
17392   else
17393     return NOP_OPCODE_MIPS;
17394 }
17395
17396 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
17397    32-bit microMIPS NOPs here (if applicable).  */
17398
17399 void
17400 mips_handle_align (fragS *fragp)
17401 {
17402   char nop_opcode;
17403   char *p;
17404   int bytes, size, excess;
17405   valueT opcode;
17406
17407   if (fragp->fr_type != rs_align_code)
17408     return;
17409
17410   p = fragp->fr_literal + fragp->fr_fix;
17411   nop_opcode = *p;
17412   switch (nop_opcode)
17413     {
17414     case NOP_OPCODE_MICROMIPS:
17415       opcode = micromips_nop32_insn.insn_opcode;
17416       size = 4;
17417       break;
17418     case NOP_OPCODE_MIPS16:
17419       opcode = mips16_nop_insn.insn_opcode;
17420       size = 2;
17421       break;
17422     case NOP_OPCODE_MIPS:
17423     default:
17424       opcode = nop_insn.insn_opcode;
17425       size = 4;
17426       break;
17427     }
17428
17429   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
17430   excess = bytes % size;
17431
17432   /* Handle the leading part if we're not inserting a whole number of
17433      instructions, and make it the end of the fixed part of the frag.
17434      Try to fit in a short microMIPS NOP if applicable and possible,
17435      and use zeroes otherwise.  */
17436   gas_assert (excess < 4);
17437   fragp->fr_fix += excess;
17438   switch (excess)
17439     {
17440     case 3:
17441       *p++ = '\0';
17442       /* Fall through.  */
17443     case 2:
17444       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
17445         {
17446           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
17447           break;
17448         }
17449       *p++ = '\0';
17450       /* Fall through.  */
17451     case 1:
17452       *p++ = '\0';
17453       /* Fall through.  */
17454     case 0:
17455       break;
17456     }
17457
17458   md_number_to_chars (p, opcode, size);
17459   fragp->fr_var = size;
17460 }
17461
17462 static void
17463 md_obj_begin (void)
17464 {
17465 }
17466
17467 static void
17468 md_obj_end (void)
17469 {
17470   /* Check for premature end, nesting errors, etc.  */
17471   if (cur_proc_ptr)
17472     as_warn (_("missing .end at end of assembly"));
17473 }
17474
17475 static long
17476 get_number (void)
17477 {
17478   int negative = 0;
17479   long val = 0;
17480
17481   if (*input_line_pointer == '-')
17482     {
17483       ++input_line_pointer;
17484       negative = 1;
17485     }
17486   if (!ISDIGIT (*input_line_pointer))
17487     as_bad (_("expected simple number"));
17488   if (input_line_pointer[0] == '0')
17489     {
17490       if (input_line_pointer[1] == 'x')
17491         {
17492           input_line_pointer += 2;
17493           while (ISXDIGIT (*input_line_pointer))
17494             {
17495               val <<= 4;
17496               val |= hex_value (*input_line_pointer++);
17497             }
17498           return negative ? -val : val;
17499         }
17500       else
17501         {
17502           ++input_line_pointer;
17503           while (ISDIGIT (*input_line_pointer))
17504             {
17505               val <<= 3;
17506               val |= *input_line_pointer++ - '0';
17507             }
17508           return negative ? -val : val;
17509         }
17510     }
17511   if (!ISDIGIT (*input_line_pointer))
17512     {
17513       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
17514               *input_line_pointer, *input_line_pointer);
17515       as_warn (_("invalid number"));
17516       return -1;
17517     }
17518   while (ISDIGIT (*input_line_pointer))
17519     {
17520       val *= 10;
17521       val += *input_line_pointer++ - '0';
17522     }
17523   return negative ? -val : val;
17524 }
17525
17526 /* The .file directive; just like the usual .file directive, but there
17527    is an initial number which is the ECOFF file index.  In the non-ECOFF
17528    case .file implies DWARF-2.  */
17529
17530 static void
17531 s_mips_file (int x ATTRIBUTE_UNUSED)
17532 {
17533   static int first_file_directive = 0;
17534
17535   if (ECOFF_DEBUGGING)
17536     {
17537       get_number ();
17538       s_app_file (0);
17539     }
17540   else
17541     {
17542       char *filename;
17543
17544       filename = dwarf2_directive_file (0);
17545
17546       /* Versions of GCC up to 3.1 start files with a ".file"
17547          directive even for stabs output.  Make sure that this
17548          ".file" is handled.  Note that you need a version of GCC
17549          after 3.1 in order to support DWARF-2 on MIPS.  */
17550       if (filename != NULL && ! first_file_directive)
17551         {
17552           (void) new_logical_line (filename, -1);
17553           s_app_file_string (filename, 0);
17554         }
17555       first_file_directive = 1;
17556     }
17557 }
17558
17559 /* The .loc directive, implying DWARF-2.  */
17560
17561 static void
17562 s_mips_loc (int x ATTRIBUTE_UNUSED)
17563 {
17564   if (!ECOFF_DEBUGGING)
17565     dwarf2_directive_loc (0);
17566 }
17567
17568 /* The .end directive.  */
17569
17570 static void
17571 s_mips_end (int x ATTRIBUTE_UNUSED)
17572 {
17573   symbolS *p;
17574
17575   /* Following functions need their own .frame and .cprestore directives.  */
17576   mips_frame_reg_valid = 0;
17577   mips_cprestore_valid = 0;
17578
17579   if (!is_end_of_line[(unsigned char) *input_line_pointer])
17580     {
17581       p = get_symbol ();
17582       demand_empty_rest_of_line ();
17583     }
17584   else
17585     p = NULL;
17586
17587   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17588     as_warn (_(".end not in text section"));
17589
17590   if (!cur_proc_ptr)
17591     {
17592       as_warn (_(".end directive without a preceding .ent directive"));
17593       demand_empty_rest_of_line ();
17594       return;
17595     }
17596
17597   if (p != NULL)
17598     {
17599       gas_assert (S_GET_NAME (p));
17600       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
17601         as_warn (_(".end symbol does not match .ent symbol"));
17602
17603       if (debug_type == DEBUG_STABS)
17604         stabs_generate_asm_endfunc (S_GET_NAME (p),
17605                                     S_GET_NAME (p));
17606     }
17607   else
17608     as_warn (_(".end directive missing or unknown symbol"));
17609
17610   /* Create an expression to calculate the size of the function.  */
17611   if (p && cur_proc_ptr)
17612     {
17613       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
17614       expressionS *exp = xmalloc (sizeof (expressionS));
17615
17616       obj->size = exp;
17617       exp->X_op = O_subtract;
17618       exp->X_add_symbol = symbol_temp_new_now ();
17619       exp->X_op_symbol = p;
17620       exp->X_add_number = 0;
17621
17622       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
17623     }
17624
17625   /* Generate a .pdr section.  */
17626   if (!ECOFF_DEBUGGING && mips_flag_pdr)
17627     {
17628       segT saved_seg = now_seg;
17629       subsegT saved_subseg = now_subseg;
17630       expressionS exp;
17631       char *fragp;
17632
17633 #ifdef md_flush_pending_output
17634       md_flush_pending_output ();
17635 #endif
17636
17637       gas_assert (pdr_seg);
17638       subseg_set (pdr_seg, 0);
17639
17640       /* Write the symbol.  */
17641       exp.X_op = O_symbol;
17642       exp.X_add_symbol = p;
17643       exp.X_add_number = 0;
17644       emit_expr (&exp, 4);
17645
17646       fragp = frag_more (7 * 4);
17647
17648       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
17649       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
17650       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
17651       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
17652       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
17653       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
17654       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
17655
17656       subseg_set (saved_seg, saved_subseg);
17657     }
17658
17659   cur_proc_ptr = NULL;
17660 }
17661
17662 /* The .aent and .ent directives.  */
17663
17664 static void
17665 s_mips_ent (int aent)
17666 {
17667   symbolS *symbolP;
17668
17669   symbolP = get_symbol ();
17670   if (*input_line_pointer == ',')
17671     ++input_line_pointer;
17672   SKIP_WHITESPACE ();
17673   if (ISDIGIT (*input_line_pointer)
17674       || *input_line_pointer == '-')
17675     get_number ();
17676
17677   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
17678     as_warn (_(".ent or .aent not in text section"));
17679
17680   if (!aent && cur_proc_ptr)
17681     as_warn (_("missing .end"));
17682
17683   if (!aent)
17684     {
17685       /* This function needs its own .frame and .cprestore directives.  */
17686       mips_frame_reg_valid = 0;
17687       mips_cprestore_valid = 0;
17688
17689       cur_proc_ptr = &cur_proc;
17690       memset (cur_proc_ptr, '\0', sizeof (procS));
17691
17692       cur_proc_ptr->func_sym = symbolP;
17693
17694       ++numprocs;
17695
17696       if (debug_type == DEBUG_STABS)
17697         stabs_generate_asm_func (S_GET_NAME (symbolP),
17698                                  S_GET_NAME (symbolP));
17699     }
17700
17701   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
17702
17703   demand_empty_rest_of_line ();
17704 }
17705
17706 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
17707    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
17708    s_mips_frame is used so that we can set the PDR information correctly.
17709    We can't use the ecoff routines because they make reference to the ecoff
17710    symbol table (in the mdebug section).  */
17711
17712 static void
17713 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
17714 {
17715   if (ECOFF_DEBUGGING)
17716     s_ignore (ignore);
17717   else
17718     {
17719       long val;
17720
17721       if (cur_proc_ptr == (procS *) NULL)
17722         {
17723           as_warn (_(".frame outside of .ent"));
17724           demand_empty_rest_of_line ();
17725           return;
17726         }
17727
17728       cur_proc_ptr->frame_reg = tc_get_register (1);
17729
17730       SKIP_WHITESPACE ();
17731       if (*input_line_pointer++ != ','
17732           || get_absolute_expression_and_terminator (&val) != ',')
17733         {
17734           as_warn (_("bad .frame directive"));
17735           --input_line_pointer;
17736           demand_empty_rest_of_line ();
17737           return;
17738         }
17739
17740       cur_proc_ptr->frame_offset = val;
17741       cur_proc_ptr->pc_reg = tc_get_register (0);
17742
17743       demand_empty_rest_of_line ();
17744     }
17745 }
17746
17747 /* The .fmask and .mask directives. If the mdebug section is present
17748    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
17749    embedded targets, s_mips_mask is used so that we can set the PDR
17750    information correctly. We can't use the ecoff routines because they
17751    make reference to the ecoff symbol table (in the mdebug section).  */
17752
17753 static void
17754 s_mips_mask (int reg_type)
17755 {
17756   if (ECOFF_DEBUGGING)
17757     s_ignore (reg_type);
17758   else
17759     {
17760       long mask, off;
17761
17762       if (cur_proc_ptr == (procS *) NULL)
17763         {
17764           as_warn (_(".mask/.fmask outside of .ent"));
17765           demand_empty_rest_of_line ();
17766           return;
17767         }
17768
17769       if (get_absolute_expression_and_terminator (&mask) != ',')
17770         {
17771           as_warn (_("bad .mask/.fmask directive"));
17772           --input_line_pointer;
17773           demand_empty_rest_of_line ();
17774           return;
17775         }
17776
17777       off = get_absolute_expression ();
17778
17779       if (reg_type == 'F')
17780         {
17781           cur_proc_ptr->fpreg_mask = mask;
17782           cur_proc_ptr->fpreg_offset = off;
17783         }
17784       else
17785         {
17786           cur_proc_ptr->reg_mask = mask;
17787           cur_proc_ptr->reg_offset = off;
17788         }
17789
17790       demand_empty_rest_of_line ();
17791     }
17792 }
17793
17794 /* A table describing all the processors gas knows about.  Names are
17795    matched in the order listed.
17796
17797    To ease comparison, please keep this table in the same order as
17798    gcc's mips_cpu_info_table[].  */
17799 static const struct mips_cpu_info mips_cpu_info_table[] =
17800 {
17801   /* Entries for generic ISAs */
17802   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
17803   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
17804   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
17805   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
17806   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
17807   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
17808   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
17809   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
17810   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
17811
17812   /* MIPS I */
17813   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17814   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
17815   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
17816
17817   /* MIPS II */
17818   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
17819
17820   /* MIPS III */
17821   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
17822   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
17823   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
17824   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17825   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17826   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
17827   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
17828   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
17829   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
17830   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17831   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
17832   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
17833   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
17834   /* ST Microelectronics Loongson 2E and 2F cores */
17835   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
17836   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
17837
17838   /* MIPS IV */
17839   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
17840   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
17841   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
17842   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
17843   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
17844   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17845   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
17846   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
17847   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17848   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17849   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17850   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17851   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
17852   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
17853   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
17854
17855   /* MIPS 32 */
17856   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17857   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17858   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
17859   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
17860
17861   /* MIPS 32 Release 2 */
17862   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17863   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17864   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17865   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
17866   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17867   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17868   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17869   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
17870   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17871                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17872   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
17873                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
17874   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17875   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17876   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17877   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17878   /* Deprecated forms of the above.  */
17879   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17880   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
17881   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
17882   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17883   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17884   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17885   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17886   /* Deprecated forms of the above.  */
17887   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17888   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
17889   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
17890   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17891   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17892   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17893   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17894   /* Deprecated forms of the above.  */
17895   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17896   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17897   /* 34Kn is a 34kc without DSP.  */
17898   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
17899   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
17900   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17901   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17902   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17903   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17904   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17905   /* Deprecated forms of the above.  */
17906   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17907   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
17908   /* 1004K cores are multiprocessor versions of the 34K.  */
17909   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17910   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17911   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17912   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
17913   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
17914   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R2, CPU_MIPS32R2 },
17915
17916   /* MIPS 64 */
17917   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17918   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
17919   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17920   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
17921
17922   /* Broadcom SB-1 CPU core */
17923   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17924   /* Broadcom SB-1A CPU core */
17925   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
17926   
17927   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
17928
17929   /* MIPS 64 Release 2 */
17930
17931   /* Cavium Networks Octeon CPU core */
17932   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
17933   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
17934   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
17935
17936   /* RMI Xlr */
17937   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
17938
17939   /* Broadcom XLP.
17940      XLP is mostly like XLR, with the prominent exception that it is
17941      MIPS64R2 rather than MIPS64.  */
17942   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
17943
17944   /* End marker */
17945   { NULL, 0, 0, 0, 0 }
17946 };
17947
17948
17949 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
17950    with a final "000" replaced by "k".  Ignore case.
17951
17952    Note: this function is shared between GCC and GAS.  */
17953
17954 static bfd_boolean
17955 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
17956 {
17957   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
17958     given++, canonical++;
17959
17960   return ((*given == 0 && *canonical == 0)
17961           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
17962 }
17963
17964
17965 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
17966    CPU name.  We've traditionally allowed a lot of variation here.
17967
17968    Note: this function is shared between GCC and GAS.  */
17969
17970 static bfd_boolean
17971 mips_matching_cpu_name_p (const char *canonical, const char *given)
17972 {
17973   /* First see if the name matches exactly, or with a final "000"
17974      turned into "k".  */
17975   if (mips_strict_matching_cpu_name_p (canonical, given))
17976     return TRUE;
17977
17978   /* If not, try comparing based on numerical designation alone.
17979      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
17980   if (TOLOWER (*given) == 'r')
17981     given++;
17982   if (!ISDIGIT (*given))
17983     return FALSE;
17984
17985   /* Skip over some well-known prefixes in the canonical name,
17986      hoping to find a number there too.  */
17987   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
17988     canonical += 2;
17989   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
17990     canonical += 2;
17991   else if (TOLOWER (canonical[0]) == 'r')
17992     canonical += 1;
17993
17994   return mips_strict_matching_cpu_name_p (canonical, given);
17995 }
17996
17997
17998 /* Parse an option that takes the name of a processor as its argument.
17999    OPTION is the name of the option and CPU_STRING is the argument.
18000    Return the corresponding processor enumeration if the CPU_STRING is
18001    recognized, otherwise report an error and return null.
18002
18003    A similar function exists in GCC.  */
18004
18005 static const struct mips_cpu_info *
18006 mips_parse_cpu (const char *option, const char *cpu_string)
18007 {
18008   const struct mips_cpu_info *p;
18009
18010   /* 'from-abi' selects the most compatible architecture for the given
18011      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
18012      EABIs, we have to decide whether we're using the 32-bit or 64-bit
18013      version.  Look first at the -mgp options, if given, otherwise base
18014      the choice on MIPS_DEFAULT_64BIT.
18015
18016      Treat NO_ABI like the EABIs.  One reason to do this is that the
18017      plain 'mips' and 'mips64' configs have 'from-abi' as their default
18018      architecture.  This code picks MIPS I for 'mips' and MIPS III for
18019      'mips64', just as we did in the days before 'from-abi'.  */
18020   if (strcasecmp (cpu_string, "from-abi") == 0)
18021     {
18022       if (ABI_NEEDS_32BIT_REGS (mips_abi))
18023         return mips_cpu_info_from_isa (ISA_MIPS1);
18024
18025       if (ABI_NEEDS_64BIT_REGS (mips_abi))
18026         return mips_cpu_info_from_isa (ISA_MIPS3);
18027
18028       if (file_mips_gp32 >= 0)
18029         return mips_cpu_info_from_isa (file_mips_gp32 ? ISA_MIPS1 : ISA_MIPS3);
18030
18031       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
18032                                      ? ISA_MIPS3
18033                                      : ISA_MIPS1);
18034     }
18035
18036   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
18037   if (strcasecmp (cpu_string, "default") == 0)
18038     return 0;
18039
18040   for (p = mips_cpu_info_table; p->name != 0; p++)
18041     if (mips_matching_cpu_name_p (p->name, cpu_string))
18042       return p;
18043
18044   as_bad (_("bad value (%s) for %s"), cpu_string, option);
18045   return 0;
18046 }
18047
18048 /* Return the canonical processor information for ISA (a member of the
18049    ISA_MIPS* enumeration).  */
18050
18051 static const struct mips_cpu_info *
18052 mips_cpu_info_from_isa (int isa)
18053 {
18054   int i;
18055
18056   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18057     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
18058         && isa == mips_cpu_info_table[i].isa)
18059       return (&mips_cpu_info_table[i]);
18060
18061   return NULL;
18062 }
18063
18064 static const struct mips_cpu_info *
18065 mips_cpu_info_from_arch (int arch)
18066 {
18067   int i;
18068
18069   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18070     if (arch == mips_cpu_info_table[i].cpu)
18071       return (&mips_cpu_info_table[i]);
18072
18073   return NULL;
18074 }
18075 \f
18076 static void
18077 show (FILE *stream, const char *string, int *col_p, int *first_p)
18078 {
18079   if (*first_p)
18080     {
18081       fprintf (stream, "%24s", "");
18082       *col_p = 24;
18083     }
18084   else
18085     {
18086       fprintf (stream, ", ");
18087       *col_p += 2;
18088     }
18089
18090   if (*col_p + strlen (string) > 72)
18091     {
18092       fprintf (stream, "\n%24s", "");
18093       *col_p = 24;
18094     }
18095
18096   fprintf (stream, "%s", string);
18097   *col_p += strlen (string);
18098
18099   *first_p = 0;
18100 }
18101
18102 void
18103 md_show_usage (FILE *stream)
18104 {
18105   int column, first;
18106   size_t i;
18107
18108   fprintf (stream, _("\
18109 MIPS options:\n\
18110 -EB                     generate big endian output\n\
18111 -EL                     generate little endian output\n\
18112 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
18113 -G NUM                  allow referencing objects up to NUM bytes\n\
18114                         implicitly with the gp register [default 8]\n"));
18115   fprintf (stream, _("\
18116 -mips1                  generate MIPS ISA I instructions\n\
18117 -mips2                  generate MIPS ISA II instructions\n\
18118 -mips3                  generate MIPS ISA III instructions\n\
18119 -mips4                  generate MIPS ISA IV instructions\n\
18120 -mips5                  generate MIPS ISA V instructions\n\
18121 -mips32                 generate MIPS32 ISA instructions\n\
18122 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
18123 -mips64                 generate MIPS64 ISA instructions\n\
18124 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
18125 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
18126
18127   first = 1;
18128
18129   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
18130     show (stream, mips_cpu_info_table[i].name, &column, &first);
18131   show (stream, "from-abi", &column, &first);
18132   fputc ('\n', stream);
18133
18134   fprintf (stream, _("\
18135 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
18136 -no-mCPU                don't generate code specific to CPU.\n\
18137                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
18138
18139   first = 1;
18140
18141   show (stream, "3900", &column, &first);
18142   show (stream, "4010", &column, &first);
18143   show (stream, "4100", &column, &first);
18144   show (stream, "4650", &column, &first);
18145   fputc ('\n', stream);
18146
18147   fprintf (stream, _("\
18148 -mips16                 generate mips16 instructions\n\
18149 -no-mips16              do not generate mips16 instructions\n"));
18150   fprintf (stream, _("\
18151 -mmicromips             generate microMIPS instructions\n\
18152 -mno-micromips          do not generate microMIPS instructions\n"));
18153   fprintf (stream, _("\
18154 -msmartmips             generate smartmips instructions\n\
18155 -mno-smartmips          do not generate smartmips instructions\n"));  
18156   fprintf (stream, _("\
18157 -mdsp                   generate DSP instructions\n\
18158 -mno-dsp                do not generate DSP instructions\n"));
18159   fprintf (stream, _("\
18160 -mdspr2                 generate DSP R2 instructions\n\
18161 -mno-dspr2              do not generate DSP R2 instructions\n"));
18162   fprintf (stream, _("\
18163 -mmt                    generate MT instructions\n\
18164 -mno-mt                 do not generate MT instructions\n"));
18165   fprintf (stream, _("\
18166 -mmcu                   generate MCU instructions\n\
18167 -mno-mcu                do not generate MCU instructions\n"));
18168   fprintf (stream, _("\
18169 -mmsa                   generate MSA instructions\n\
18170 -mno-msa                do not generate MSA instructions\n"));
18171   fprintf (stream, _("\
18172 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
18173 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
18174   fprintf (stream, _("\
18175 -mvirt                  generate Virtualization instructions\n\
18176 -mno-virt               do not generate Virtualization instructions\n"));
18177   fprintf (stream, _("\
18178 -minsn32                only generate 32-bit microMIPS instructions\n\
18179 -mno-insn32             generate all microMIPS instructions\n"));
18180   fprintf (stream, _("\
18181 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
18182 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
18183 -mfix-vr4120            work around certain VR4120 errata\n\
18184 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
18185 -mfix-24k               insert a nop after ERET and DERET instructions\n\
18186 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
18187 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
18188 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
18189 -msym32                 assume all symbols have 32-bit values\n\
18190 -O0                     remove unneeded NOPs, do not swap branches\n\
18191 -O                      remove unneeded NOPs and swap branches\n\
18192 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
18193 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
18194   fprintf (stream, _("\
18195 -mhard-float            allow floating-point instructions\n\
18196 -msoft-float            do not allow floating-point instructions\n\
18197 -msingle-float          only allow 32-bit floating-point operations\n\
18198 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
18199 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
18200 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
18201 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
18202
18203   first = 1;
18204
18205   show (stream, "legacy", &column, &first);
18206   show (stream, "2008", &column, &first);
18207
18208   fputc ('\n', stream);
18209
18210   fprintf (stream, _("\
18211 -KPIC, -call_shared     generate SVR4 position independent code\n\
18212 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
18213 -mvxworks-pic           generate VxWorks position independent code\n\
18214 -non_shared             do not generate code that can operate with DSOs\n\
18215 -xgot                   assume a 32 bit GOT\n\
18216 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
18217 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
18218                         position dependent (non shared) code\n\
18219 -mabi=ABI               create ABI conformant object file for:\n"));
18220
18221   first = 1;
18222
18223   show (stream, "32", &column, &first);
18224   show (stream, "o64", &column, &first);
18225   show (stream, "n32", &column, &first);
18226   show (stream, "64", &column, &first);
18227   show (stream, "eabi", &column, &first);
18228
18229   fputc ('\n', stream);
18230
18231   fprintf (stream, _("\
18232 -32                     create o32 ABI object file (default)\n\
18233 -n32                    create n32 ABI object file\n\
18234 -64                     create 64 ABI object file\n"));
18235 }
18236
18237 #ifdef TE_IRIX
18238 enum dwarf2_format
18239 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
18240 {
18241   if (HAVE_64BIT_SYMBOLS)
18242     return dwarf2_format_64bit_irix;
18243   else
18244     return dwarf2_format_32bit;
18245 }
18246 #endif
18247
18248 int
18249 mips_dwarf2_addr_size (void)
18250 {
18251   if (HAVE_64BIT_OBJECTS)
18252     return 8;
18253   else
18254     return 4;
18255 }
18256
18257 /* Standard calling conventions leave the CFA at SP on entry.  */
18258 void
18259 mips_cfi_frame_initial_instructions (void)
18260 {
18261   cfi_add_CFA_def_cfa_register (SP);
18262 }
18263
18264 int
18265 tc_mips_regname_to_dw2regnum (char *regname)
18266 {
18267   unsigned int regnum = -1;
18268   unsigned int reg;
18269
18270   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
18271     regnum = reg;
18272
18273   return regnum;
18274 }