MIPS: Verify the ISA mode and alignment of branch and jump targets
[external/binutils.git] / gas / config / tc-mips.c
1 /* tc-mips.c -- assemble code for a MIPS chip.
2    Copyright (C) 1993-2016 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 streq(a, b)           (strcmp (a, b) == 0)
46
47 #define SKIP_SPACE_TABS(S) \
48   do { while (*(S) == ' ' || *(S) == '\t') ++(S); } while (0)
49
50 /* Clean up namespace so we can include obj-elf.h too.  */
51 static int mips_output_flavor (void);
52 static int mips_output_flavor (void) { return OUTPUT_FLAVOR; }
53 #undef OBJ_PROCESS_STAB
54 #undef OUTPUT_FLAVOR
55 #undef S_GET_ALIGN
56 #undef S_GET_SIZE
57 #undef S_SET_ALIGN
58 #undef S_SET_SIZE
59 #undef obj_frob_file
60 #undef obj_frob_file_after_relocs
61 #undef obj_frob_symbol
62 #undef obj_pop_insert
63 #undef obj_sec_sym_ok_for_reloc
64 #undef OBJ_COPY_SYMBOL_ATTRIBUTES
65
66 #include "obj-elf.h"
67 /* Fix any of them that we actually care about.  */
68 #undef OUTPUT_FLAVOR
69 #define OUTPUT_FLAVOR mips_output_flavor()
70
71 #include "elf/mips.h"
72
73 #ifndef ECOFF_DEBUGGING
74 #define NO_ECOFF_DEBUGGING
75 #define ECOFF_DEBUGGING 0
76 #endif
77
78 int mips_flag_mdebug = -1;
79
80 /* Control generation of .pdr sections.  Off by default on IRIX: the native
81    linker doesn't know about and discards them, but relocations against them
82    remain, leading to rld crashes.  */
83 #ifdef TE_IRIX
84 int mips_flag_pdr = FALSE;
85 #else
86 int mips_flag_pdr = TRUE;
87 #endif
88
89 #include "ecoff.h"
90
91 static char *mips_regmask_frag;
92 static char *mips_flags_frag;
93
94 #define ZERO 0
95 #define ATREG 1
96 #define S0  16
97 #define S7  23
98 #define TREG 24
99 #define PIC_CALL_REG 25
100 #define KT0 26
101 #define KT1 27
102 #define GP  28
103 #define SP  29
104 #define FP  30
105 #define RA  31
106
107 #define ILLEGAL_REG (32)
108
109 #define AT  mips_opts.at
110
111 extern int target_big_endian;
112
113 /* The name of the readonly data section.  */
114 #define RDATA_SECTION_NAME ".rodata"
115
116 /* Ways in which an instruction can be "appended" to the output.  */
117 enum append_method {
118   /* Just add it normally.  */
119   APPEND_ADD,
120
121   /* Add it normally and then add a nop.  */
122   APPEND_ADD_WITH_NOP,
123
124   /* Turn an instruction with a delay slot into a "compact" version.  */
125   APPEND_ADD_COMPACT,
126
127   /* Insert the instruction before the last one.  */
128   APPEND_SWAP
129 };
130
131 /* Information about an instruction, including its format, operands
132    and fixups.  */
133 struct mips_cl_insn
134 {
135   /* The opcode's entry in mips_opcodes or mips16_opcodes.  */
136   const struct mips_opcode *insn_mo;
137
138   /* The 16-bit or 32-bit bitstring of the instruction itself.  This is
139      a copy of INSN_MO->match with the operands filled in.  If we have
140      decided to use an extended MIPS16 instruction, this includes the
141      extension.  */
142   unsigned long insn_opcode;
143
144   /* The frag that contains the instruction.  */
145   struct frag *frag;
146
147   /* The offset into FRAG of the first instruction byte.  */
148   long where;
149
150   /* The relocs associated with the instruction, if any.  */
151   fixS *fixp[3];
152
153   /* True if this entry cannot be moved from its current position.  */
154   unsigned int fixed_p : 1;
155
156   /* True if this instruction occurred in a .set noreorder block.  */
157   unsigned int noreorder_p : 1;
158
159   /* True for mips16 instructions that jump to an absolute address.  */
160   unsigned int mips16_absolute_jump_p : 1;
161
162   /* True if this instruction is complete.  */
163   unsigned int complete_p : 1;
164
165   /* True if this instruction is cleared from history by unconditional
166      branch.  */
167   unsigned int cleared_p : 1;
168 };
169
170 /* The ABI to use.  */
171 enum mips_abi_level
172 {
173   NO_ABI = 0,
174   O32_ABI,
175   O64_ABI,
176   N32_ABI,
177   N64_ABI,
178   EABI_ABI
179 };
180
181 /* MIPS ABI we are using for this output file.  */
182 static enum mips_abi_level mips_abi = NO_ABI;
183
184 /* Whether or not we have code that can call pic code.  */
185 int mips_abicalls = FALSE;
186
187 /* Whether or not we have code which can be put into a shared
188    library.  */
189 static bfd_boolean mips_in_shared = TRUE;
190
191 /* This is the set of options which may be modified by the .set
192    pseudo-op.  We use a struct so that .set push and .set pop are more
193    reliable.  */
194
195 struct mips_set_options
196 {
197   /* MIPS ISA (Instruction Set Architecture) level.  This is set to -1
198      if it has not been initialized.  Changed by `.set mipsN', and the
199      -mipsN command line option, and the default CPU.  */
200   int isa;
201   /* Enabled Application Specific Extensions (ASEs).  Changed by `.set
202      <asename>', by command line options, and based on the default
203      architecture.  */
204   int ase;
205   /* Whether we are assembling for the mips16 processor.  0 if we are
206      not, 1 if we are, and -1 if the value has not been initialized.
207      Changed by `.set mips16' and `.set nomips16', and the -mips16 and
208      -nomips16 command line options, and the default CPU.  */
209   int mips16;
210   /* Whether we are assembling for the mipsMIPS ASE.  0 if we are not,
211      1 if we are, and -1 if the value has not been initialized.  Changed
212      by `.set micromips' and `.set nomicromips', and the -mmicromips
213      and -mno-micromips command line options, and the default CPU.  */
214   int micromips;
215   /* Non-zero if we should not reorder instructions.  Changed by `.set
216      reorder' and `.set noreorder'.  */
217   int noreorder;
218   /* Non-zero if we should not permit the register designated "assembler
219      temporary" to be used in instructions.  The value is the register
220      number, normally $at ($1).  Changed by `.set at=REG', `.set noat'
221      (same as `.set at=$0') and `.set at' (same as `.set at=$1').  */
222   unsigned int at;
223   /* Non-zero if we should warn when a macro instruction expands into
224      more than one machine instruction.  Changed by `.set nomacro' and
225      `.set macro'.  */
226   int warn_about_macros;
227   /* Non-zero if we should not move instructions.  Changed by `.set
228      move', `.set volatile', `.set nomove', and `.set novolatile'.  */
229   int nomove;
230   /* Non-zero if we should not optimize branches by moving the target
231      of the branch into the delay slot.  Actually, we don't perform
232      this optimization anyhow.  Changed by `.set bopt' and `.set
233      nobopt'.  */
234   int nobopt;
235   /* Non-zero if we should not autoextend mips16 instructions.
236      Changed by `.set autoextend' and `.set noautoextend'.  */
237   int noautoextend;
238   /* True if we should only emit 32-bit microMIPS instructions.
239      Changed by `.set insn32' and `.set noinsn32', and the -minsn32
240      and -mno-insn32 command line options.  */
241   bfd_boolean insn32;
242   /* Restrict general purpose registers and floating point registers
243      to 32 bit.  This is initially determined when -mgp32 or -mfp32
244      is passed but can changed if the assembler code uses .set mipsN.  */
245   int gp;
246   int fp;
247   /* MIPS architecture (CPU) type.  Changed by .set arch=FOO, the -march
248      command line option, and the default CPU.  */
249   int arch;
250   /* True if ".set sym32" is in effect.  */
251   bfd_boolean sym32;
252   /* True if floating-point operations are not allowed.  Changed by .set
253      softfloat or .set hardfloat, by command line options -msoft-float or
254      -mhard-float.  The default is false.  */
255   bfd_boolean soft_float;
256
257   /* True if only single-precision floating-point operations are allowed.
258      Changed by .set singlefloat or .set doublefloat, command-line options
259      -msingle-float or -mdouble-float.  The default is false.  */
260   bfd_boolean single_float;
261
262   /* 1 if single-precision operations on odd-numbered registers are
263      allowed.  */
264   int oddspreg;
265 };
266
267 /* Specifies whether module level options have been checked yet.  */
268 static bfd_boolean file_mips_opts_checked = FALSE;
269
270 /* Do we support nan2008?  0 if we don't, 1 if we do, and -1 if the
271    value has not been initialized.  Changed by `.nan legacy' and
272    `.nan 2008', and the -mnan=legacy and -mnan=2008 command line
273    options, and the default CPU.  */
274 static int mips_nan2008 = -1;
275
276 /* This is the struct we use to hold the module level set of options.
277    Note that we must set the isa field to ISA_UNKNOWN and the ASE, gp and
278    fp fields to -1 to indicate that they have not been initialized.  */
279
280 static struct mips_set_options file_mips_opts =
281 {
282   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
283   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
284   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
285   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
286   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
287 };
288
289 /* This is similar to file_mips_opts, but for the current set of options.  */
290
291 static struct mips_set_options mips_opts =
292 {
293   /* isa */ ISA_UNKNOWN, /* ase */ 0, /* mips16 */ -1, /* micromips */ -1,
294   /* noreorder */ 0,  /* at */ ATREG, /* warn_about_macros */ 0,
295   /* nomove */ 0, /* nobopt */ 0, /* noautoextend */ 0, /* insn32 */ FALSE,
296   /* gp */ -1, /* fp */ -1, /* arch */ CPU_UNKNOWN, /* sym32 */ FALSE,
297   /* soft_float */ FALSE, /* single_float */ FALSE, /* oddspreg */ -1
298 };
299
300 /* Which bits of file_ase were explicitly set or cleared by ASE options.  */
301 static unsigned int file_ase_explicit;
302
303 /* These variables are filled in with the masks of registers used.
304    The object format code reads them and puts them in the appropriate
305    place.  */
306 unsigned long mips_gprmask;
307 unsigned long mips_cprmask[4];
308
309 /* True if any MIPS16 code was produced.  */
310 static int file_ase_mips16;
311
312 #define ISA_SUPPORTS_MIPS16E (mips_opts.isa == ISA_MIPS32               \
313                               || mips_opts.isa == ISA_MIPS32R2          \
314                               || mips_opts.isa == ISA_MIPS32R3          \
315                               || mips_opts.isa == ISA_MIPS32R5          \
316                               || mips_opts.isa == ISA_MIPS64            \
317                               || mips_opts.isa == ISA_MIPS64R2          \
318                               || mips_opts.isa == ISA_MIPS64R3          \
319                               || mips_opts.isa == ISA_MIPS64R5)
320
321 /* True if any microMIPS code was produced.  */
322 static int file_ase_micromips;
323
324 /* True if we want to create R_MIPS_JALR for jalr $25.  */
325 #ifdef TE_IRIX
326 #define MIPS_JALR_HINT_P(EXPR) HAVE_NEWABI
327 #else
328 /* As a GNU extension, we use R_MIPS_JALR for o32 too.  However,
329    because there's no place for any addend, the only acceptable
330    expression is a bare symbol.  */
331 #define MIPS_JALR_HINT_P(EXPR) \
332   (!HAVE_IN_PLACE_ADDENDS \
333    || ((EXPR)->X_op == O_symbol && (EXPR)->X_add_number == 0))
334 #endif
335
336 /* The argument of the -march= flag.  The architecture we are assembling.  */
337 static const char *mips_arch_string;
338
339 /* The argument of the -mtune= flag.  The architecture for which we
340    are optimizing.  */
341 static int mips_tune = CPU_UNKNOWN;
342 static const char *mips_tune_string;
343
344 /* True when generating 32-bit code for a 64-bit processor.  */
345 static int mips_32bitmode = 0;
346
347 /* True if the given ABI requires 32-bit registers.  */
348 #define ABI_NEEDS_32BIT_REGS(ABI) ((ABI) == O32_ABI)
349
350 /* Likewise 64-bit registers.  */
351 #define ABI_NEEDS_64BIT_REGS(ABI)       \
352   ((ABI) == N32_ABI                     \
353    || (ABI) == N64_ABI                  \
354    || (ABI) == O64_ABI)
355
356 #define ISA_IS_R6(ISA)                  \
357   ((ISA) == ISA_MIPS32R6                \
358    || (ISA) == ISA_MIPS64R6)
359
360 /*  Return true if ISA supports 64 bit wide gp registers.  */
361 #define ISA_HAS_64BIT_REGS(ISA)         \
362   ((ISA) == ISA_MIPS3                   \
363    || (ISA) == ISA_MIPS4                \
364    || (ISA) == ISA_MIPS5                \
365    || (ISA) == ISA_MIPS64               \
366    || (ISA) == ISA_MIPS64R2             \
367    || (ISA) == ISA_MIPS64R3             \
368    || (ISA) == ISA_MIPS64R5             \
369    || (ISA) == ISA_MIPS64R6)
370
371 /*  Return true if ISA supports 64 bit wide float registers.  */
372 #define ISA_HAS_64BIT_FPRS(ISA)         \
373   ((ISA) == ISA_MIPS3                   \
374    || (ISA) == ISA_MIPS4                \
375    || (ISA) == ISA_MIPS5                \
376    || (ISA) == ISA_MIPS32R2             \
377    || (ISA) == ISA_MIPS32R3             \
378    || (ISA) == ISA_MIPS32R5             \
379    || (ISA) == ISA_MIPS32R6             \
380    || (ISA) == ISA_MIPS64               \
381    || (ISA) == ISA_MIPS64R2             \
382    || (ISA) == ISA_MIPS64R3             \
383    || (ISA) == ISA_MIPS64R5             \
384    || (ISA) == ISA_MIPS64R6)
385
386 /* Return true if ISA supports 64-bit right rotate (dror et al.)
387    instructions.  */
388 #define ISA_HAS_DROR(ISA)               \
389   ((ISA) == ISA_MIPS64R2                \
390    || (ISA) == ISA_MIPS64R3             \
391    || (ISA) == ISA_MIPS64R5             \
392    || (ISA) == ISA_MIPS64R6             \
393    || (mips_opts.micromips              \
394        && ISA_HAS_64BIT_REGS (ISA))     \
395    )
396
397 /* Return true if ISA supports 32-bit right rotate (ror et al.)
398    instructions.  */
399 #define ISA_HAS_ROR(ISA)                \
400   ((ISA) == ISA_MIPS32R2                \
401    || (ISA) == ISA_MIPS32R3             \
402    || (ISA) == ISA_MIPS32R5             \
403    || (ISA) == ISA_MIPS32R6             \
404    || (ISA) == ISA_MIPS64R2             \
405    || (ISA) == ISA_MIPS64R3             \
406    || (ISA) == ISA_MIPS64R5             \
407    || (ISA) == ISA_MIPS64R6             \
408    || (mips_opts.ase & ASE_SMARTMIPS)   \
409    || mips_opts.micromips               \
410    )
411
412 /* Return true if ISA supports single-precision floats in odd registers.  */
413 #define ISA_HAS_ODD_SINGLE_FPR(ISA, CPU)\
414   (((ISA) == ISA_MIPS32                 \
415     || (ISA) == ISA_MIPS32R2            \
416     || (ISA) == ISA_MIPS32R3            \
417     || (ISA) == ISA_MIPS32R5            \
418     || (ISA) == ISA_MIPS32R6            \
419     || (ISA) == ISA_MIPS64              \
420     || (ISA) == ISA_MIPS64R2            \
421     || (ISA) == ISA_MIPS64R3            \
422     || (ISA) == ISA_MIPS64R5            \
423     || (ISA) == ISA_MIPS64R6            \
424     || (CPU) == CPU_R5900)              \
425    && (CPU) != CPU_LOONGSON_3A)
426
427 /* Return true if ISA supports move to/from high part of a 64-bit
428    floating-point register. */
429 #define ISA_HAS_MXHC1(ISA)              \
430   ((ISA) == ISA_MIPS32R2                \
431    || (ISA) == ISA_MIPS32R3             \
432    || (ISA) == ISA_MIPS32R5             \
433    || (ISA) == ISA_MIPS32R6             \
434    || (ISA) == ISA_MIPS64R2             \
435    || (ISA) == ISA_MIPS64R3             \
436    || (ISA) == ISA_MIPS64R5             \
437    || (ISA) == ISA_MIPS64R6)
438
439 /*  Return true if ISA supports legacy NAN.  */
440 #define ISA_HAS_LEGACY_NAN(ISA)         \
441   ((ISA) == ISA_MIPS1                   \
442    || (ISA) == ISA_MIPS2                \
443    || (ISA) == ISA_MIPS3                \
444    || (ISA) == ISA_MIPS4                \
445    || (ISA) == ISA_MIPS5                \
446    || (ISA) == ISA_MIPS32               \
447    || (ISA) == ISA_MIPS32R2             \
448    || (ISA) == ISA_MIPS32R3             \
449    || (ISA) == ISA_MIPS32R5             \
450    || (ISA) == ISA_MIPS64               \
451    || (ISA) == ISA_MIPS64R2             \
452    || (ISA) == ISA_MIPS64R3             \
453    || (ISA) == ISA_MIPS64R5)
454
455 #define GPR_SIZE \
456     (mips_opts.gp == 64 && !ISA_HAS_64BIT_REGS (mips_opts.isa) \
457      ? 32 \
458      : mips_opts.gp)
459
460 #define FPR_SIZE \
461     (mips_opts.fp == 64 && !ISA_HAS_64BIT_FPRS (mips_opts.isa) \
462      ? 32 \
463      : mips_opts.fp)
464
465 #define HAVE_NEWABI (mips_abi == N32_ABI || mips_abi == N64_ABI)
466
467 #define HAVE_64BIT_OBJECTS (mips_abi == N64_ABI)
468
469 /* True if relocations are stored in-place.  */
470 #define HAVE_IN_PLACE_ADDENDS (!HAVE_NEWABI)
471
472 /* The ABI-derived address size.  */
473 #define HAVE_64BIT_ADDRESSES \
474   (GPR_SIZE == 64 && (mips_abi == EABI_ABI || mips_abi == N64_ABI))
475 #define HAVE_32BIT_ADDRESSES (!HAVE_64BIT_ADDRESSES)
476
477 /* The size of symbolic constants (i.e., expressions of the form
478    "SYMBOL" or "SYMBOL + OFFSET").  */
479 #define HAVE_32BIT_SYMBOLS \
480   (HAVE_32BIT_ADDRESSES || !HAVE_64BIT_OBJECTS || mips_opts.sym32)
481 #define HAVE_64BIT_SYMBOLS (!HAVE_32BIT_SYMBOLS)
482
483 /* Addresses are loaded in different ways, depending on the address size
484    in use.  The n32 ABI Documentation also mandates the use of additions
485    with overflow checking, but existing implementations don't follow it.  */
486 #define ADDRESS_ADD_INSN                                                \
487    (HAVE_32BIT_ADDRESSES ? "addu" : "daddu")
488
489 #define ADDRESS_ADDI_INSN                                               \
490    (HAVE_32BIT_ADDRESSES ? "addiu" : "daddiu")
491
492 #define ADDRESS_LOAD_INSN                                               \
493    (HAVE_32BIT_ADDRESSES ? "lw" : "ld")
494
495 #define ADDRESS_STORE_INSN                                              \
496    (HAVE_32BIT_ADDRESSES ? "sw" : "sd")
497
498 /* Return true if the given CPU supports the MIPS16 ASE.  */
499 #define CPU_HAS_MIPS16(cpu)                                             \
500    (strncmp (TARGET_CPU, "mips16", sizeof ("mips16") - 1) == 0          \
501     || strncmp (TARGET_CANONICAL, "mips-lsi-elf", sizeof ("mips-lsi-elf") - 1) == 0)
502
503 /* Return true if the given CPU supports the microMIPS ASE.  */
504 #define CPU_HAS_MICROMIPS(cpu)  0
505
506 /* True if CPU has a dror instruction.  */
507 #define CPU_HAS_DROR(CPU)       ((CPU) == CPU_VR5400 || (CPU) == CPU_VR5500)
508
509 /* True if CPU has a ror instruction.  */
510 #define CPU_HAS_ROR(CPU)        CPU_HAS_DROR (CPU)
511
512 /* True if CPU is in the Octeon family */
513 #define CPU_IS_OCTEON(CPU) ((CPU) == CPU_OCTEON || (CPU) == CPU_OCTEONP \
514                             || (CPU) == CPU_OCTEON2 || (CPU) == CPU_OCTEON3)
515
516 /* True if CPU has seq/sne and seqi/snei instructions.  */
517 #define CPU_HAS_SEQ(CPU)        (CPU_IS_OCTEON (CPU))
518
519 /* True, if CPU has support for ldc1 and sdc1. */
520 #define CPU_HAS_LDC1_SDC1(CPU)  \
521    ((mips_opts.isa != ISA_MIPS1) && ((CPU) != CPU_R5900))
522
523 /* True if mflo and mfhi can be immediately followed by instructions
524    which write to the HI and LO registers.
525
526    According to MIPS specifications, MIPS ISAs I, II, and III need
527    (at least) two instructions between the reads of HI/LO and
528    instructions which write them, and later ISAs do not.  Contradicting
529    the MIPS specifications, some MIPS IV processor user manuals (e.g.
530    the UM for the NEC Vr5000) document needing the instructions between
531    HI/LO reads and writes, as well.  Therefore, we declare only MIPS32,
532    MIPS64 and later ISAs to have the interlocks, plus any specific
533    earlier-ISA CPUs for which CPU documentation declares that the
534    instructions are really interlocked.  */
535 #define hilo_interlocks \
536   (mips_opts.isa == ISA_MIPS32                        \
537    || mips_opts.isa == ISA_MIPS32R2                   \
538    || mips_opts.isa == ISA_MIPS32R3                   \
539    || mips_opts.isa == ISA_MIPS32R5                   \
540    || mips_opts.isa == ISA_MIPS32R6                   \
541    || mips_opts.isa == ISA_MIPS64                     \
542    || mips_opts.isa == ISA_MIPS64R2                   \
543    || mips_opts.isa == ISA_MIPS64R3                   \
544    || mips_opts.isa == ISA_MIPS64R5                   \
545    || mips_opts.isa == ISA_MIPS64R6                   \
546    || mips_opts.arch == CPU_R4010                     \
547    || mips_opts.arch == CPU_R5900                     \
548    || mips_opts.arch == CPU_R10000                    \
549    || mips_opts.arch == CPU_R12000                    \
550    || mips_opts.arch == CPU_R14000                    \
551    || mips_opts.arch == CPU_R16000                    \
552    || mips_opts.arch == CPU_RM7000                    \
553    || mips_opts.arch == CPU_VR5500                    \
554    || mips_opts.micromips                             \
555    )
556
557 /* Whether the processor uses hardware interlocks to protect reads
558    from the GPRs after they are loaded from memory, and thus does not
559    require nops to be inserted.  This applies to instructions marked
560    INSN_LOAD_MEMORY.  These nops are only required at MIPS ISA
561    level I and microMIPS mode instructions are always interlocked.  */
562 #define gpr_interlocks                                \
563   (mips_opts.isa != ISA_MIPS1                         \
564    || mips_opts.arch == CPU_R3900                     \
565    || mips_opts.arch == CPU_R5900                     \
566    || mips_opts.micromips                             \
567    )
568
569 /* Whether the processor uses hardware interlocks to avoid delays
570    required by coprocessor instructions, and thus does not require
571    nops to be inserted.  This applies to instructions marked
572    INSN_LOAD_COPROC, INSN_COPROC_MOVE, and to delays between
573    instructions marked INSN_WRITE_COND_CODE and ones marked
574    INSN_READ_COND_CODE.  These nops are only required at MIPS ISA
575    levels I, II, and III and microMIPS mode instructions are always
576    interlocked.  */
577 /* Itbl support may require additional care here.  */
578 #define cop_interlocks                                \
579   ((mips_opts.isa != ISA_MIPS1                        \
580     && mips_opts.isa != ISA_MIPS2                     \
581     && mips_opts.isa != ISA_MIPS3)                    \
582    || mips_opts.arch == CPU_R4300                     \
583    || mips_opts.micromips                             \
584    )
585
586 /* Whether the processor uses hardware interlocks to protect reads
587    from coprocessor registers after they are loaded from memory, and
588    thus does not require nops to be inserted.  This applies to
589    instructions marked INSN_COPROC_MEMORY_DELAY.  These nops are only
590    requires at MIPS ISA level I and microMIPS mode instructions are
591    always interlocked.  */
592 #define cop_mem_interlocks                            \
593   (mips_opts.isa != ISA_MIPS1                         \
594    || mips_opts.micromips                             \
595    )
596
597 /* Is this a mfhi or mflo instruction?  */
598 #define MF_HILO_INSN(PINFO) \
599   ((PINFO & INSN_READ_HI) || (PINFO & INSN_READ_LO))
600
601 /* Whether code compression (either of the MIPS16 or the microMIPS ASEs)
602    has been selected.  This implies, in particular, that addresses of text
603    labels have their LSB set.  */
604 #define HAVE_CODE_COMPRESSION                                           \
605   ((mips_opts.mips16 | mips_opts.micromips) != 0)
606
607 /* The minimum and maximum signed values that can be stored in a GPR.  */
608 #define GPR_SMAX ((offsetT) (((valueT) 1 << (GPR_SIZE - 1)) - 1))
609 #define GPR_SMIN (-GPR_SMAX - 1)
610
611 /* MIPS PIC level.  */
612
613 enum mips_pic_level mips_pic;
614
615 /* 1 if we should generate 32 bit offsets from the $gp register in
616    SVR4_PIC mode.  Currently has no meaning in other modes.  */
617 static int mips_big_got = 0;
618
619 /* 1 if trap instructions should used for overflow rather than break
620    instructions.  */
621 static int mips_trap = 0;
622
623 /* 1 if double width floating point constants should not be constructed
624    by assembling two single width halves into two single width floating
625    point registers which just happen to alias the double width destination
626    register.  On some architectures this aliasing can be disabled by a bit
627    in the status register, and the setting of this bit cannot be determined
628    automatically at assemble time.  */
629 static int mips_disable_float_construction;
630
631 /* Non-zero if any .set noreorder directives were used.  */
632
633 static int mips_any_noreorder;
634
635 /* Non-zero if nops should be inserted when the register referenced in
636    an mfhi/mflo instruction is read in the next two instructions.  */
637 static int mips_7000_hilo_fix;
638
639 /* The size of objects in the small data section.  */
640 static unsigned int g_switch_value = 8;
641 /* Whether the -G option was used.  */
642 static int g_switch_seen = 0;
643
644 #define N_RMASK 0xc4
645 #define N_VFP   0xd4
646
647 /* If we can determine in advance that GP optimization won't be
648    possible, we can skip the relaxation stuff that tries to produce
649    GP-relative references.  This makes delay slot optimization work
650    better.
651
652    This function can only provide a guess, but it seems to work for
653    gcc output.  It needs to guess right for gcc, otherwise gcc
654    will put what it thinks is a GP-relative instruction in a branch
655    delay slot.
656
657    I don't know if a fix is needed for the SVR4_PIC mode.  I've only
658    fixed it for the non-PIC mode.  KR 95/04/07  */
659 static int nopic_need_relax (symbolS *, int);
660
661 /* handle of the OPCODE hash table */
662 static struct hash_control *op_hash = NULL;
663
664 /* The opcode hash table we use for the mips16.  */
665 static struct hash_control *mips16_op_hash = NULL;
666
667 /* The opcode hash table we use for the microMIPS ASE.  */
668 static struct hash_control *micromips_op_hash = NULL;
669
670 /* This array holds the chars that always start a comment.  If the
671     pre-processor is disabled, these aren't very useful */
672 const char comment_chars[] = "#";
673
674 /* This array holds the chars that only start a comment at the beginning of
675    a line.  If the line seems to have the form '# 123 filename'
676    .line and .file directives will appear in the pre-processed output */
677 /* Note that input_file.c hand checks for '#' at the beginning of the
678    first line of the input file.  This is because the compiler outputs
679    #NO_APP at the beginning of its output.  */
680 /* Also note that C style comments are always supported.  */
681 const char line_comment_chars[] = "#";
682
683 /* This array holds machine specific line separator characters.  */
684 const char line_separator_chars[] = ";";
685
686 /* Chars that can be used to separate mant from exp in floating point nums */
687 const char EXP_CHARS[] = "eE";
688
689 /* Chars that mean this number is a floating point constant */
690 /* As in 0f12.456 */
691 /* or    0d1.2345e12 */
692 const char FLT_CHARS[] = "rRsSfFdDxXpP";
693
694 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
695    changed in read.c .  Ideally it shouldn't have to know about it at all,
696    but nothing is ideal around here.
697  */
698
699 /* Types of printf format used for instruction-related error messages.
700    "I" means int ("%d") and "S" means string ("%s"). */
701 enum mips_insn_error_format {
702   ERR_FMT_PLAIN,
703   ERR_FMT_I,
704   ERR_FMT_SS,
705 };
706
707 /* Information about an error that was found while assembling the current
708    instruction.  */
709 struct mips_insn_error {
710   /* We sometimes need to match an instruction against more than one
711      opcode table entry.  Errors found during this matching are reported
712      against a particular syntactic argument rather than against the
713      instruction as a whole.  We grade these messages so that errors
714      against argument N have a greater priority than an error against
715      any argument < N, since the former implies that arguments up to N
716      were acceptable and that the opcode entry was therefore a closer match.
717      If several matches report an error against the same argument,
718      we only use that error if it is the same in all cases.
719
720      min_argnum is the minimum argument number for which an error message
721      should be accepted.  It is 0 if MSG is against the instruction as
722      a whole.  */
723   int min_argnum;
724
725   /* The printf()-style message, including its format and arguments.  */
726   enum mips_insn_error_format format;
727   const char *msg;
728   union {
729     int i;
730     const char *ss[2];
731   } u;
732 };
733
734 /* The error that should be reported for the current instruction.  */
735 static struct mips_insn_error insn_error;
736
737 static int auto_align = 1;
738
739 /* When outputting SVR4 PIC code, the assembler needs to know the
740    offset in the stack frame from which to restore the $gp register.
741    This is set by the .cprestore pseudo-op, and saved in this
742    variable.  */
743 static offsetT mips_cprestore_offset = -1;
744
745 /* Similar for NewABI PIC code, where $gp is callee-saved.  NewABI has some
746    more optimizations, it can use a register value instead of a memory-saved
747    offset and even an other register than $gp as global pointer.  */
748 static offsetT mips_cpreturn_offset = -1;
749 static int mips_cpreturn_register = -1;
750 static int mips_gp_register = GP;
751 static int mips_gprel_offset = 0;
752
753 /* Whether mips_cprestore_offset has been set in the current function
754    (or whether it has already been warned about, if not).  */
755 static int mips_cprestore_valid = 0;
756
757 /* This is the register which holds the stack frame, as set by the
758    .frame pseudo-op.  This is needed to implement .cprestore.  */
759 static int mips_frame_reg = SP;
760
761 /* Whether mips_frame_reg has been set in the current function
762    (or whether it has already been warned about, if not).  */
763 static int mips_frame_reg_valid = 0;
764
765 /* To output NOP instructions correctly, we need to keep information
766    about the previous two instructions.  */
767
768 /* Whether we are optimizing.  The default value of 2 means to remove
769    unneeded NOPs and swap branch instructions when possible.  A value
770    of 1 means to not swap branches.  A value of 0 means to always
771    insert NOPs.  */
772 static int mips_optimize = 2;
773
774 /* Debugging level.  -g sets this to 2.  -gN sets this to N.  -g0 is
775    equivalent to seeing no -g option at all.  */
776 static int mips_debug = 0;
777
778 /* The maximum number of NOPs needed to avoid the VR4130 mflo/mfhi errata.  */
779 #define MAX_VR4130_NOPS 4
780
781 /* The maximum number of NOPs needed to fill delay slots.  */
782 #define MAX_DELAY_NOPS 2
783
784 /* The maximum number of NOPs needed for any purpose.  */
785 #define MAX_NOPS 4
786
787 /* A list of previous instructions, with index 0 being the most recent.
788    We need to look back MAX_NOPS instructions when filling delay slots
789    or working around processor errata.  We need to look back one
790    instruction further if we're thinking about using history[0] to
791    fill a branch delay slot.  */
792 static struct mips_cl_insn history[1 + MAX_NOPS];
793
794 /* Arrays of operands for each instruction.  */
795 #define MAX_OPERANDS 6
796 struct mips_operand_array {
797   const struct mips_operand *operand[MAX_OPERANDS];
798 };
799 static struct mips_operand_array *mips_operands;
800 static struct mips_operand_array *mips16_operands;
801 static struct mips_operand_array *micromips_operands;
802
803 /* Nop instructions used by emit_nop.  */
804 static struct mips_cl_insn nop_insn;
805 static struct mips_cl_insn mips16_nop_insn;
806 static struct mips_cl_insn micromips_nop16_insn;
807 static struct mips_cl_insn micromips_nop32_insn;
808
809 /* The appropriate nop for the current mode.  */
810 #define NOP_INSN (mips_opts.mips16                                      \
811                   ? &mips16_nop_insn                                    \
812                   : (mips_opts.micromips                                \
813                      ? (mips_opts.insn32                                \
814                         ? &micromips_nop32_insn                         \
815                         : &micromips_nop16_insn)                        \
816                      : &nop_insn))
817
818 /* The size of NOP_INSN in bytes.  */
819 #define NOP_INSN_SIZE ((mips_opts.mips16                                \
820                         || (mips_opts.micromips && !mips_opts.insn32))  \
821                        ? 2 : 4)
822
823 /* If this is set, it points to a frag holding nop instructions which
824    were inserted before the start of a noreorder section.  If those
825    nops turn out to be unnecessary, the size of the frag can be
826    decreased.  */
827 static fragS *prev_nop_frag;
828
829 /* The number of nop instructions we created in prev_nop_frag.  */
830 static int prev_nop_frag_holds;
831
832 /* The number of nop instructions that we know we need in
833    prev_nop_frag.  */
834 static int prev_nop_frag_required;
835
836 /* The number of instructions we've seen since prev_nop_frag.  */
837 static int prev_nop_frag_since;
838
839 /* Relocations against symbols are sometimes done in two parts, with a HI
840    relocation and a LO relocation.  Each relocation has only 16 bits of
841    space to store an addend.  This means that in order for the linker to
842    handle carries correctly, it must be able to locate both the HI and
843    the LO relocation.  This means that the relocations must appear in
844    order in the relocation table.
845
846    In order to implement this, we keep track of each unmatched HI
847    relocation.  We then sort them so that they immediately precede the
848    corresponding LO relocation.  */
849
850 struct mips_hi_fixup
851 {
852   /* Next HI fixup.  */
853   struct mips_hi_fixup *next;
854   /* This fixup.  */
855   fixS *fixp;
856   /* The section this fixup is in.  */
857   segT seg;
858 };
859
860 /* The list of unmatched HI relocs.  */
861
862 static struct mips_hi_fixup *mips_hi_fixup_list;
863
864 /* The frag containing the last explicit relocation operator.
865    Null if explicit relocations have not been used.  */
866
867 static fragS *prev_reloc_op_frag;
868
869 /* Map mips16 register numbers to normal MIPS register numbers.  */
870
871 static const unsigned int mips16_to_32_reg_map[] =
872 {
873   16, 17, 2, 3, 4, 5, 6, 7
874 };
875
876 /* Map microMIPS register numbers to normal MIPS register numbers.  */
877
878 #define micromips_to_32_reg_d_map       mips16_to_32_reg_map
879
880 /* The microMIPS registers with type h.  */
881 static const unsigned int micromips_to_32_reg_h_map1[] =
882 {
883   5, 5, 6, 4, 4, 4, 4, 4
884 };
885 static const unsigned int micromips_to_32_reg_h_map2[] =
886 {
887   6, 7, 7, 21, 22, 5, 6, 7
888 };
889
890 /* The microMIPS registers with type m.  */
891 static const unsigned int micromips_to_32_reg_m_map[] =
892 {
893   0, 17, 2, 3, 16, 18, 19, 20
894 };
895
896 #define micromips_to_32_reg_n_map      micromips_to_32_reg_m_map
897
898 /* Classifies the kind of instructions we're interested in when
899    implementing -mfix-vr4120.  */
900 enum fix_vr4120_class
901 {
902   FIX_VR4120_MACC,
903   FIX_VR4120_DMACC,
904   FIX_VR4120_MULT,
905   FIX_VR4120_DMULT,
906   FIX_VR4120_DIV,
907   FIX_VR4120_MTHILO,
908   NUM_FIX_VR4120_CLASSES
909 };
910
911 /* ...likewise -mfix-loongson2f-jump.  */
912 static bfd_boolean mips_fix_loongson2f_jump;
913
914 /* ...likewise -mfix-loongson2f-nop.  */
915 static bfd_boolean mips_fix_loongson2f_nop;
916
917 /* True if -mfix-loongson2f-nop or -mfix-loongson2f-jump passed.  */
918 static bfd_boolean mips_fix_loongson2f;
919
920 /* Given two FIX_VR4120_* values X and Y, bit Y of element X is set if
921    there must be at least one other instruction between an instruction
922    of type X and an instruction of type Y.  */
923 static unsigned int vr4120_conflicts[NUM_FIX_VR4120_CLASSES];
924
925 /* True if -mfix-vr4120 is in force.  */
926 static int mips_fix_vr4120;
927
928 /* ...likewise -mfix-vr4130.  */
929 static int mips_fix_vr4130;
930
931 /* ...likewise -mfix-24k.  */
932 static int mips_fix_24k;
933
934 /* ...likewise -mfix-rm7000  */
935 static int mips_fix_rm7000;
936
937 /* ...likewise -mfix-cn63xxp1 */
938 static bfd_boolean mips_fix_cn63xxp1;
939
940 /* We don't relax branches by default, since this causes us to expand
941    `la .l2 - .l1' if there's a branch between .l1 and .l2, because we
942    fail to compute the offset before expanding the macro to the most
943    efficient expansion.  */
944
945 static int mips_relax_branch;
946 \f
947 /* The expansion of many macros depends on the type of symbol that
948    they refer to.  For example, when generating position-dependent code,
949    a macro that refers to a symbol may have two different expansions,
950    one which uses GP-relative addresses and one which uses absolute
951    addresses.  When generating SVR4-style PIC, a macro may have
952    different expansions for local and global symbols.
953
954    We handle these situations by generating both sequences and putting
955    them in variant frags.  In position-dependent code, the first sequence
956    will be the GP-relative one and the second sequence will be the
957    absolute one.  In SVR4 PIC, the first sequence will be for global
958    symbols and the second will be for local symbols.
959
960    The frag's "subtype" is RELAX_ENCODE (FIRST, SECOND), where FIRST and
961    SECOND are the lengths of the two sequences in bytes.  These fields
962    can be extracted using RELAX_FIRST() and RELAX_SECOND().  In addition,
963    the subtype has the following flags:
964
965    RELAX_USE_SECOND
966         Set if it has been decided that we should use the second
967         sequence instead of the first.
968
969    RELAX_SECOND_LONGER
970         Set in the first variant frag if the macro's second implementation
971         is longer than its first.  This refers to the macro as a whole,
972         not an individual relaxation.
973
974    RELAX_NOMACRO
975         Set in the first variant frag if the macro appeared in a .set nomacro
976         block and if one alternative requires a warning but the other does not.
977
978    RELAX_DELAY_SLOT
979         Like RELAX_NOMACRO, but indicates that the macro appears in a branch
980         delay slot.
981
982    RELAX_DELAY_SLOT_16BIT
983         Like RELAX_DELAY_SLOT, but indicates that the delay slot requires a
984         16-bit instruction.
985
986    RELAX_DELAY_SLOT_SIZE_FIRST
987         Like RELAX_DELAY_SLOT, but indicates that the first implementation of
988         the macro is of the wrong size for the branch delay slot.
989
990    RELAX_DELAY_SLOT_SIZE_SECOND
991         Like RELAX_DELAY_SLOT, but indicates that the second implementation of
992         the macro is of the wrong size for the branch delay slot.
993
994    The frag's "opcode" points to the first fixup for relaxable code.
995
996    Relaxable macros are generated using a sequence such as:
997
998       relax_start (SYMBOL);
999       ... generate first expansion ...
1000       relax_switch ();
1001       ... generate second expansion ...
1002       relax_end ();
1003
1004    The code and fixups for the unwanted alternative are discarded
1005    by md_convert_frag.  */
1006 #define RELAX_ENCODE(FIRST, SECOND) (((FIRST) << 8) | (SECOND))
1007
1008 #define RELAX_FIRST(X) (((X) >> 8) & 0xff)
1009 #define RELAX_SECOND(X) ((X) & 0xff)
1010 #define RELAX_USE_SECOND 0x10000
1011 #define RELAX_SECOND_LONGER 0x20000
1012 #define RELAX_NOMACRO 0x40000
1013 #define RELAX_DELAY_SLOT 0x80000
1014 #define RELAX_DELAY_SLOT_16BIT 0x100000
1015 #define RELAX_DELAY_SLOT_SIZE_FIRST 0x200000
1016 #define RELAX_DELAY_SLOT_SIZE_SECOND 0x400000
1017
1018 /* Branch without likely bit.  If label is out of range, we turn:
1019
1020         beq reg1, reg2, label
1021         delay slot
1022
1023    into
1024
1025         bne reg1, reg2, 0f
1026         nop
1027         j label
1028      0: delay slot
1029
1030    with the following opcode replacements:
1031
1032         beq <-> bne
1033         blez <-> bgtz
1034         bltz <-> bgez
1035         bc1f <-> bc1t
1036
1037         bltzal <-> bgezal  (with jal label instead of j label)
1038
1039    Even though keeping the delay slot instruction in the delay slot of
1040    the branch would be more efficient, it would be very tricky to do
1041    correctly, because we'd have to introduce a variable frag *after*
1042    the delay slot instruction, and expand that instead.  Let's do it
1043    the easy way for now, even if the branch-not-taken case now costs
1044    one additional instruction.  Out-of-range branches are not supposed
1045    to be common, anyway.
1046
1047    Branch likely.  If label is out of range, we turn:
1048
1049         beql reg1, reg2, label
1050         delay slot (annulled if branch not taken)
1051
1052    into
1053
1054         beql reg1, reg2, 1f
1055         nop
1056         beql $0, $0, 2f
1057         nop
1058      1: j[al] label
1059         delay slot (executed only if branch taken)
1060      2:
1061
1062    It would be possible to generate a shorter sequence by losing the
1063    likely bit, generating something like:
1064
1065         bne reg1, reg2, 0f
1066         nop
1067         j[al] label
1068         delay slot (executed only if branch taken)
1069      0:
1070
1071         beql -> bne
1072         bnel -> beq
1073         blezl -> bgtz
1074         bgtzl -> blez
1075         bltzl -> bgez
1076         bgezl -> bltz
1077         bc1fl -> bc1t
1078         bc1tl -> bc1f
1079
1080         bltzall -> bgezal  (with jal label instead of j label)
1081         bgezall -> bltzal  (ditto)
1082
1083
1084    but it's not clear that it would actually improve performance.  */
1085 #define RELAX_BRANCH_ENCODE(at, uncond, likely, link, toofar)   \
1086   ((relax_substateT)                                            \
1087    (0xc0000000                                                  \
1088     | ((at) & 0x1f)                                             \
1089     | ((toofar) ? 0x20 : 0)                                     \
1090     | ((link) ? 0x40 : 0)                                       \
1091     | ((likely) ? 0x80 : 0)                                     \
1092     | ((uncond) ? 0x100 : 0)))
1093 #define RELAX_BRANCH_P(i) (((i) & 0xf0000000) == 0xc0000000)
1094 #define RELAX_BRANCH_UNCOND(i) (((i) & 0x100) != 0)
1095 #define RELAX_BRANCH_LIKELY(i) (((i) & 0x80) != 0)
1096 #define RELAX_BRANCH_LINK(i) (((i) & 0x40) != 0)
1097 #define RELAX_BRANCH_TOOFAR(i) (((i) & 0x20) != 0)
1098 #define RELAX_BRANCH_AT(i) ((i) & 0x1f)
1099
1100 /* For mips16 code, we use an entirely different form of relaxation.
1101    mips16 supports two versions of most instructions which take
1102    immediate values: a small one which takes some small value, and a
1103    larger one which takes a 16 bit value.  Since branches also follow
1104    this pattern, relaxing these values is required.
1105
1106    We can assemble both mips16 and normal MIPS code in a single
1107    object.  Therefore, we need to support this type of relaxation at
1108    the same time that we support the relaxation described above.  We
1109    use the high bit of the subtype field to distinguish these cases.
1110
1111    The information we store for this type of relaxation is the
1112    argument code found in the opcode file for this relocation, whether
1113    the user explicitly requested a small or extended form, and whether
1114    the relocation is in a jump or jal delay slot.  That tells us the
1115    size of the value, and how it should be stored.  We also store
1116    whether the fragment is considered to be extended or not.  We also
1117    store whether this is known to be a branch to a different section,
1118    whether we have tried to relax this frag yet, and whether we have
1119    ever extended a PC relative fragment because of a shift count.  */
1120 #define RELAX_MIPS16_ENCODE(type, small, ext, dslot, jal_dslot) \
1121   (0x80000000                                                   \
1122    | ((type) & 0xff)                                            \
1123    | ((small) ? 0x100 : 0)                                      \
1124    | ((ext) ? 0x200 : 0)                                        \
1125    | ((dslot) ? 0x400 : 0)                                      \
1126    | ((jal_dslot) ? 0x800 : 0))
1127 #define RELAX_MIPS16_P(i) (((i) & 0xc0000000) == 0x80000000)
1128 #define RELAX_MIPS16_TYPE(i) ((i) & 0xff)
1129 #define RELAX_MIPS16_USER_SMALL(i) (((i) & 0x100) != 0)
1130 #define RELAX_MIPS16_USER_EXT(i) (((i) & 0x200) != 0)
1131 #define RELAX_MIPS16_DSLOT(i) (((i) & 0x400) != 0)
1132 #define RELAX_MIPS16_JAL_DSLOT(i) (((i) & 0x800) != 0)
1133 #define RELAX_MIPS16_EXTENDED(i) (((i) & 0x1000) != 0)
1134 #define RELAX_MIPS16_MARK_EXTENDED(i) ((i) | 0x1000)
1135 #define RELAX_MIPS16_CLEAR_EXTENDED(i) ((i) &~ 0x1000)
1136 #define RELAX_MIPS16_LONG_BRANCH(i) (((i) & 0x2000) != 0)
1137 #define RELAX_MIPS16_MARK_LONG_BRANCH(i) ((i) | 0x2000)
1138 #define RELAX_MIPS16_CLEAR_LONG_BRANCH(i) ((i) &~ 0x2000)
1139
1140 /* For microMIPS code, we use relaxation similar to one we use for
1141    MIPS16 code.  Some instructions that take immediate values support
1142    two encodings: a small one which takes some small value, and a
1143    larger one which takes a 16 bit value.  As some branches also follow
1144    this pattern, relaxing these values is required.
1145
1146    We can assemble both microMIPS and normal MIPS code in a single
1147    object.  Therefore, we need to support this type of relaxation at
1148    the same time that we support the relaxation described above.  We
1149    use one of the high bits of the subtype field to distinguish these
1150    cases.
1151
1152    The information we store for this type of relaxation is the argument
1153    code found in the opcode file for this relocation, the register
1154    selected as the assembler temporary, whether the branch is
1155    unconditional, whether it is compact, whether it stores the link
1156    address implicitly in $ra, whether relaxation of out-of-range 32-bit
1157    branches to a sequence of instructions is enabled, and whether the
1158    displacement of a branch is too large to fit as an immediate argument
1159    of a 16-bit and a 32-bit branch, respectively.  */
1160 #define RELAX_MICROMIPS_ENCODE(type, at, uncond, compact, link, \
1161                                relax32, toofar16, toofar32)     \
1162   (0x40000000                                                   \
1163    | ((type) & 0xff)                                            \
1164    | (((at) & 0x1f) << 8)                                       \
1165    | ((uncond) ? 0x2000 : 0)                                    \
1166    | ((compact) ? 0x4000 : 0)                                   \
1167    | ((link) ? 0x8000 : 0)                                      \
1168    | ((relax32) ? 0x10000 : 0)                                  \
1169    | ((toofar16) ? 0x20000 : 0)                                 \
1170    | ((toofar32) ? 0x40000 : 0))
1171 #define RELAX_MICROMIPS_P(i) (((i) & 0xc0000000) == 0x40000000)
1172 #define RELAX_MICROMIPS_TYPE(i) ((i) & 0xff)
1173 #define RELAX_MICROMIPS_AT(i) (((i) >> 8) & 0x1f)
1174 #define RELAX_MICROMIPS_UNCOND(i) (((i) & 0x2000) != 0)
1175 #define RELAX_MICROMIPS_COMPACT(i) (((i) & 0x4000) != 0)
1176 #define RELAX_MICROMIPS_LINK(i) (((i) & 0x8000) != 0)
1177 #define RELAX_MICROMIPS_RELAX32(i) (((i) & 0x10000) != 0)
1178
1179 #define RELAX_MICROMIPS_TOOFAR16(i) (((i) & 0x20000) != 0)
1180 #define RELAX_MICROMIPS_MARK_TOOFAR16(i) ((i) | 0x20000)
1181 #define RELAX_MICROMIPS_CLEAR_TOOFAR16(i) ((i) & ~0x20000)
1182 #define RELAX_MICROMIPS_TOOFAR32(i) (((i) & 0x40000) != 0)
1183 #define RELAX_MICROMIPS_MARK_TOOFAR32(i) ((i) | 0x40000)
1184 #define RELAX_MICROMIPS_CLEAR_TOOFAR32(i) ((i) & ~0x40000)
1185
1186 /* Sign-extend 16-bit value X.  */
1187 #define SEXT_16BIT(X) ((((X) + 0x8000) & 0xffff) - 0x8000)
1188
1189 /* Is the given value a sign-extended 32-bit value?  */
1190 #define IS_SEXT_32BIT_NUM(x)                                            \
1191   (((x) &~ (offsetT) 0x7fffffff) == 0                                   \
1192    || (((x) &~ (offsetT) 0x7fffffff) == ~ (offsetT) 0x7fffffff))
1193
1194 /* Is the given value a sign-extended 16-bit value?  */
1195 #define IS_SEXT_16BIT_NUM(x)                                            \
1196   (((x) &~ (offsetT) 0x7fff) == 0                                       \
1197    || (((x) &~ (offsetT) 0x7fff) == ~ (offsetT) 0x7fff))
1198
1199 /* Is the given value a sign-extended 12-bit value?  */
1200 #define IS_SEXT_12BIT_NUM(x)                                            \
1201   (((((x) & 0xfff) ^ 0x800LL) - 0x800LL) == (x))
1202
1203 /* Is the given value a sign-extended 9-bit value?  */
1204 #define IS_SEXT_9BIT_NUM(x)                                             \
1205   (((((x) & 0x1ff) ^ 0x100LL) - 0x100LL) == (x))
1206
1207 /* Is the given value a zero-extended 32-bit value?  Or a negated one?  */
1208 #define IS_ZEXT_32BIT_NUM(x)                                            \
1209   (((x) &~ (offsetT) 0xffffffff) == 0                                   \
1210    || (((x) &~ (offsetT) 0xffffffff) == ~ (offsetT) 0xffffffff))
1211
1212 /* Extract bits MASK << SHIFT from STRUCT and shift them right
1213    SHIFT places.  */
1214 #define EXTRACT_BITS(STRUCT, MASK, SHIFT) \
1215   (((STRUCT) >> (SHIFT)) & (MASK))
1216
1217 /* Extract the operand given by FIELD from mips_cl_insn INSN.  */
1218 #define EXTRACT_OPERAND(MICROMIPS, FIELD, INSN) \
1219   (!(MICROMIPS) \
1220    ? EXTRACT_BITS ((INSN).insn_opcode, OP_MASK_##FIELD, OP_SH_##FIELD) \
1221    : EXTRACT_BITS ((INSN).insn_opcode, \
1222                    MICROMIPSOP_MASK_##FIELD, MICROMIPSOP_SH_##FIELD))
1223 #define MIPS16_EXTRACT_OPERAND(FIELD, INSN) \
1224   EXTRACT_BITS ((INSN).insn_opcode, \
1225                 MIPS16OP_MASK_##FIELD, \
1226                 MIPS16OP_SH_##FIELD)
1227
1228 /* The MIPS16 EXTEND opcode, shifted left 16 places.  */
1229 #define MIPS16_EXTEND (0xf000U << 16)
1230 \f
1231 /* Whether or not we are emitting a branch-likely macro.  */
1232 static bfd_boolean emit_branch_likely_macro = FALSE;
1233
1234 /* Global variables used when generating relaxable macros.  See the
1235    comment above RELAX_ENCODE for more details about how relaxation
1236    is used.  */
1237 static struct {
1238   /* 0 if we're not emitting a relaxable macro.
1239      1 if we're emitting the first of the two relaxation alternatives.
1240      2 if we're emitting the second alternative.  */
1241   int sequence;
1242
1243   /* The first relaxable fixup in the current frag.  (In other words,
1244      the first fixup that refers to relaxable code.)  */
1245   fixS *first_fixup;
1246
1247   /* sizes[0] says how many bytes of the first alternative are stored in
1248      the current frag.  Likewise sizes[1] for the second alternative.  */
1249   unsigned int sizes[2];
1250
1251   /* The symbol on which the choice of sequence depends.  */
1252   symbolS *symbol;
1253 } mips_relax;
1254 \f
1255 /* Global variables used to decide whether a macro needs a warning.  */
1256 static struct {
1257   /* True if the macro is in a branch delay slot.  */
1258   bfd_boolean delay_slot_p;
1259
1260   /* Set to the length in bytes required if the macro is in a delay slot
1261      that requires a specific length of instruction, otherwise zero.  */
1262   unsigned int delay_slot_length;
1263
1264   /* For relaxable macros, sizes[0] is the length of the first alternative
1265      in bytes and sizes[1] is the length of the second alternative.
1266      For non-relaxable macros, both elements give the length of the
1267      macro in bytes.  */
1268   unsigned int sizes[2];
1269
1270   /* For relaxable macros, first_insn_sizes[0] is the length of the first
1271      instruction of the first alternative in bytes and first_insn_sizes[1]
1272      is the length of the first instruction of the second alternative.
1273      For non-relaxable macros, both elements give the length of the first
1274      instruction in bytes.
1275
1276      Set to zero if we haven't yet seen the first instruction.  */
1277   unsigned int first_insn_sizes[2];
1278
1279   /* For relaxable macros, insns[0] is the number of instructions for the
1280      first alternative and insns[1] is the number of instructions for the
1281      second alternative.
1282
1283      For non-relaxable macros, both elements give the number of
1284      instructions for the macro.  */
1285   unsigned int insns[2];
1286
1287   /* The first variant frag for this macro.  */
1288   fragS *first_frag;
1289 } mips_macro_warning;
1290 \f
1291 /* Prototypes for static functions.  */
1292
1293 enum mips_regclass { MIPS_GR_REG, MIPS_FP_REG, MIPS16_REG };
1294
1295 static void append_insn
1296   (struct mips_cl_insn *, expressionS *, bfd_reloc_code_real_type *,
1297    bfd_boolean expansionp);
1298 static void mips_no_prev_insn (void);
1299 static void macro_build (expressionS *, const char *, const char *, ...);
1300 static void mips16_macro_build
1301   (expressionS *, const char *, const char *, va_list *);
1302 static void load_register (int, expressionS *, int);
1303 static void macro_start (void);
1304 static void macro_end (void);
1305 static void macro (struct mips_cl_insn *ip, char *str);
1306 static void mips16_macro (struct mips_cl_insn * ip);
1307 static void mips_ip (char *str, struct mips_cl_insn * ip);
1308 static void mips16_ip (char *str, struct mips_cl_insn * ip);
1309 static void mips16_immed
1310   (const char *, unsigned int, int, bfd_reloc_code_real_type, offsetT,
1311    unsigned int, unsigned long *);
1312 static size_t my_getSmallExpression
1313   (expressionS *, bfd_reloc_code_real_type *, char *);
1314 static void my_getExpression (expressionS *, char *);
1315 static void s_align (int);
1316 static void s_change_sec (int);
1317 static void s_change_section (int);
1318 static void s_cons (int);
1319 static void s_float_cons (int);
1320 static void s_mips_globl (int);
1321 static void s_option (int);
1322 static void s_mipsset (int);
1323 static void s_abicalls (int);
1324 static void s_cpload (int);
1325 static void s_cpsetup (int);
1326 static void s_cplocal (int);
1327 static void s_cprestore (int);
1328 static void s_cpreturn (int);
1329 static void s_dtprelword (int);
1330 static void s_dtpreldword (int);
1331 static void s_tprelword (int);
1332 static void s_tpreldword (int);
1333 static void s_gpvalue (int);
1334 static void s_gpword (int);
1335 static void s_gpdword (int);
1336 static void s_ehword (int);
1337 static void s_cpadd (int);
1338 static void s_insn (int);
1339 static void s_nan (int);
1340 static void s_module (int);
1341 static void s_mips_ent (int);
1342 static void s_mips_end (int);
1343 static void s_mips_frame (int);
1344 static void s_mips_mask (int reg_type);
1345 static void s_mips_stab (int);
1346 static void s_mips_weakext (int);
1347 static void s_mips_file (int);
1348 static void s_mips_loc (int);
1349 static bfd_boolean pic_need_relax (symbolS *, asection *);
1350 static int relaxed_branch_length (fragS *, asection *, int);
1351 static int relaxed_micromips_16bit_branch_length (fragS *, asection *, int);
1352 static int relaxed_micromips_32bit_branch_length (fragS *, asection *, int);
1353 static void file_mips_check_options (void);
1354
1355 /* Table and functions used to map between CPU/ISA names, and
1356    ISA levels, and CPU numbers.  */
1357
1358 struct mips_cpu_info
1359 {
1360   const char *name;           /* CPU or ISA name.  */
1361   int flags;                  /* MIPS_CPU_* flags.  */
1362   int ase;                    /* Set of ASEs implemented by the CPU.  */
1363   int isa;                    /* ISA level.  */
1364   int cpu;                    /* CPU number (default CPU if ISA).  */
1365 };
1366
1367 #define MIPS_CPU_IS_ISA         0x0001  /* Is this an ISA?  (If 0, a CPU.) */
1368
1369 static const struct mips_cpu_info *mips_parse_cpu (const char *, const char *);
1370 static const struct mips_cpu_info *mips_cpu_info_from_isa (int);
1371 static const struct mips_cpu_info *mips_cpu_info_from_arch (int);
1372 \f
1373 /* Command-line options.  */
1374 const char *md_shortopts = "O::g::G:";
1375
1376 enum options
1377   {
1378     OPTION_MARCH = OPTION_MD_BASE,
1379     OPTION_MTUNE,
1380     OPTION_MIPS1,
1381     OPTION_MIPS2,
1382     OPTION_MIPS3,
1383     OPTION_MIPS4,
1384     OPTION_MIPS5,
1385     OPTION_MIPS32,
1386     OPTION_MIPS64,
1387     OPTION_MIPS32R2,
1388     OPTION_MIPS32R3,
1389     OPTION_MIPS32R5,
1390     OPTION_MIPS32R6,
1391     OPTION_MIPS64R2,
1392     OPTION_MIPS64R3,
1393     OPTION_MIPS64R5,
1394     OPTION_MIPS64R6,
1395     OPTION_MIPS16,
1396     OPTION_NO_MIPS16,
1397     OPTION_MIPS3D,
1398     OPTION_NO_MIPS3D,
1399     OPTION_MDMX,
1400     OPTION_NO_MDMX,
1401     OPTION_DSP,
1402     OPTION_NO_DSP,
1403     OPTION_MT,
1404     OPTION_NO_MT,
1405     OPTION_VIRT,
1406     OPTION_NO_VIRT,
1407     OPTION_MSA,
1408     OPTION_NO_MSA,
1409     OPTION_SMARTMIPS,
1410     OPTION_NO_SMARTMIPS,
1411     OPTION_DSPR2,
1412     OPTION_NO_DSPR2,
1413     OPTION_DSPR3,
1414     OPTION_NO_DSPR3,
1415     OPTION_EVA,
1416     OPTION_NO_EVA,
1417     OPTION_XPA,
1418     OPTION_NO_XPA,
1419     OPTION_MICROMIPS,
1420     OPTION_NO_MICROMIPS,
1421     OPTION_MCU,
1422     OPTION_NO_MCU,
1423     OPTION_COMPAT_ARCH_BASE,
1424     OPTION_M4650,
1425     OPTION_NO_M4650,
1426     OPTION_M4010,
1427     OPTION_NO_M4010,
1428     OPTION_M4100,
1429     OPTION_NO_M4100,
1430     OPTION_M3900,
1431     OPTION_NO_M3900,
1432     OPTION_M7000_HILO_FIX,
1433     OPTION_MNO_7000_HILO_FIX,
1434     OPTION_FIX_24K,
1435     OPTION_NO_FIX_24K,
1436     OPTION_FIX_RM7000,
1437     OPTION_NO_FIX_RM7000,
1438     OPTION_FIX_LOONGSON2F_JUMP,
1439     OPTION_NO_FIX_LOONGSON2F_JUMP,
1440     OPTION_FIX_LOONGSON2F_NOP,
1441     OPTION_NO_FIX_LOONGSON2F_NOP,
1442     OPTION_FIX_VR4120,
1443     OPTION_NO_FIX_VR4120,
1444     OPTION_FIX_VR4130,
1445     OPTION_NO_FIX_VR4130,
1446     OPTION_FIX_CN63XXP1,
1447     OPTION_NO_FIX_CN63XXP1,
1448     OPTION_TRAP,
1449     OPTION_BREAK,
1450     OPTION_EB,
1451     OPTION_EL,
1452     OPTION_FP32,
1453     OPTION_GP32,
1454     OPTION_CONSTRUCT_FLOATS,
1455     OPTION_NO_CONSTRUCT_FLOATS,
1456     OPTION_FP64,
1457     OPTION_FPXX,
1458     OPTION_GP64,
1459     OPTION_RELAX_BRANCH,
1460     OPTION_NO_RELAX_BRANCH,
1461     OPTION_INSN32,
1462     OPTION_NO_INSN32,
1463     OPTION_MSHARED,
1464     OPTION_MNO_SHARED,
1465     OPTION_MSYM32,
1466     OPTION_MNO_SYM32,
1467     OPTION_SOFT_FLOAT,
1468     OPTION_HARD_FLOAT,
1469     OPTION_SINGLE_FLOAT,
1470     OPTION_DOUBLE_FLOAT,
1471     OPTION_32,
1472     OPTION_CALL_SHARED,
1473     OPTION_CALL_NONPIC,
1474     OPTION_NON_SHARED,
1475     OPTION_XGOT,
1476     OPTION_MABI,
1477     OPTION_N32,
1478     OPTION_64,
1479     OPTION_MDEBUG,
1480     OPTION_NO_MDEBUG,
1481     OPTION_PDR,
1482     OPTION_NO_PDR,
1483     OPTION_MVXWORKS_PIC,
1484     OPTION_NAN,
1485     OPTION_ODD_SPREG,
1486     OPTION_NO_ODD_SPREG,
1487     OPTION_END_OF_ENUM
1488   };
1489
1490 struct option md_longopts[] =
1491 {
1492   /* Options which specify architecture.  */
1493   {"march", required_argument, NULL, OPTION_MARCH},
1494   {"mtune", required_argument, NULL, OPTION_MTUNE},
1495   {"mips0", no_argument, NULL, OPTION_MIPS1},
1496   {"mips1", no_argument, NULL, OPTION_MIPS1},
1497   {"mips2", no_argument, NULL, OPTION_MIPS2},
1498   {"mips3", no_argument, NULL, OPTION_MIPS3},
1499   {"mips4", no_argument, NULL, OPTION_MIPS4},
1500   {"mips5", no_argument, NULL, OPTION_MIPS5},
1501   {"mips32", no_argument, NULL, OPTION_MIPS32},
1502   {"mips64", no_argument, NULL, OPTION_MIPS64},
1503   {"mips32r2", no_argument, NULL, OPTION_MIPS32R2},
1504   {"mips32r3", no_argument, NULL, OPTION_MIPS32R3},
1505   {"mips32r5", no_argument, NULL, OPTION_MIPS32R5},
1506   {"mips32r6", no_argument, NULL, OPTION_MIPS32R6},
1507   {"mips64r2", no_argument, NULL, OPTION_MIPS64R2},
1508   {"mips64r3", no_argument, NULL, OPTION_MIPS64R3},
1509   {"mips64r5", no_argument, NULL, OPTION_MIPS64R5},
1510   {"mips64r6", no_argument, NULL, OPTION_MIPS64R6},
1511
1512   /* Options which specify Application Specific Extensions (ASEs).  */
1513   {"mips16", no_argument, NULL, OPTION_MIPS16},
1514   {"no-mips16", no_argument, NULL, OPTION_NO_MIPS16},
1515   {"mips3d", no_argument, NULL, OPTION_MIPS3D},
1516   {"no-mips3d", no_argument, NULL, OPTION_NO_MIPS3D},
1517   {"mdmx", no_argument, NULL, OPTION_MDMX},
1518   {"no-mdmx", no_argument, NULL, OPTION_NO_MDMX},
1519   {"mdsp", no_argument, NULL, OPTION_DSP},
1520   {"mno-dsp", no_argument, NULL, OPTION_NO_DSP},
1521   {"mmt", no_argument, NULL, OPTION_MT},
1522   {"mno-mt", no_argument, NULL, OPTION_NO_MT},
1523   {"msmartmips", no_argument, NULL, OPTION_SMARTMIPS},
1524   {"mno-smartmips", no_argument, NULL, OPTION_NO_SMARTMIPS},
1525   {"mdspr2", no_argument, NULL, OPTION_DSPR2},
1526   {"mno-dspr2", no_argument, NULL, OPTION_NO_DSPR2},
1527   {"mdspr3", no_argument, NULL, OPTION_DSPR3},
1528   {"mno-dspr3", no_argument, NULL, OPTION_NO_DSPR3},
1529   {"meva", no_argument, NULL, OPTION_EVA},
1530   {"mno-eva", no_argument, NULL, OPTION_NO_EVA},
1531   {"mmicromips", no_argument, NULL, OPTION_MICROMIPS},
1532   {"mno-micromips", no_argument, NULL, OPTION_NO_MICROMIPS},
1533   {"mmcu", no_argument, NULL, OPTION_MCU},
1534   {"mno-mcu", no_argument, NULL, OPTION_NO_MCU},
1535   {"mvirt", no_argument, NULL, OPTION_VIRT},
1536   {"mno-virt", no_argument, NULL, OPTION_NO_VIRT},
1537   {"mmsa", no_argument, NULL, OPTION_MSA},
1538   {"mno-msa", no_argument, NULL, OPTION_NO_MSA},
1539   {"mxpa", no_argument, NULL, OPTION_XPA},
1540   {"mno-xpa", no_argument, NULL, OPTION_NO_XPA},
1541
1542   /* Old-style architecture options.  Don't add more of these.  */
1543   {"m4650", no_argument, NULL, OPTION_M4650},
1544   {"no-m4650", no_argument, NULL, OPTION_NO_M4650},
1545   {"m4010", no_argument, NULL, OPTION_M4010},
1546   {"no-m4010", no_argument, NULL, OPTION_NO_M4010},
1547   {"m4100", no_argument, NULL, OPTION_M4100},
1548   {"no-m4100", no_argument, NULL, OPTION_NO_M4100},
1549   {"m3900", no_argument, NULL, OPTION_M3900},
1550   {"no-m3900", no_argument, NULL, OPTION_NO_M3900},
1551
1552   /* Options which enable bug fixes.  */
1553   {"mfix7000", no_argument, NULL, OPTION_M7000_HILO_FIX},
1554   {"no-fix-7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1555   {"mno-fix7000", no_argument, NULL, OPTION_MNO_7000_HILO_FIX},
1556   {"mfix-loongson2f-jump", no_argument, NULL, OPTION_FIX_LOONGSON2F_JUMP},
1557   {"mno-fix-loongson2f-jump", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_JUMP},
1558   {"mfix-loongson2f-nop", no_argument, NULL, OPTION_FIX_LOONGSON2F_NOP},
1559   {"mno-fix-loongson2f-nop", no_argument, NULL, OPTION_NO_FIX_LOONGSON2F_NOP},
1560   {"mfix-vr4120",    no_argument, NULL, OPTION_FIX_VR4120},
1561   {"mno-fix-vr4120", no_argument, NULL, OPTION_NO_FIX_VR4120},
1562   {"mfix-vr4130",    no_argument, NULL, OPTION_FIX_VR4130},
1563   {"mno-fix-vr4130", no_argument, NULL, OPTION_NO_FIX_VR4130},
1564   {"mfix-24k",    no_argument, NULL, OPTION_FIX_24K},
1565   {"mno-fix-24k", no_argument, NULL, OPTION_NO_FIX_24K},
1566   {"mfix-rm7000",    no_argument, NULL, OPTION_FIX_RM7000},
1567   {"mno-fix-rm7000", no_argument, NULL, OPTION_NO_FIX_RM7000},
1568   {"mfix-cn63xxp1", no_argument, NULL, OPTION_FIX_CN63XXP1},
1569   {"mno-fix-cn63xxp1", no_argument, NULL, OPTION_NO_FIX_CN63XXP1},
1570
1571   /* Miscellaneous options.  */
1572   {"trap", no_argument, NULL, OPTION_TRAP},
1573   {"no-break", no_argument, NULL, OPTION_TRAP},
1574   {"break", no_argument, NULL, OPTION_BREAK},
1575   {"no-trap", no_argument, NULL, OPTION_BREAK},
1576   {"EB", no_argument, NULL, OPTION_EB},
1577   {"EL", no_argument, NULL, OPTION_EL},
1578   {"mfp32", no_argument, NULL, OPTION_FP32},
1579   {"mgp32", no_argument, NULL, OPTION_GP32},
1580   {"construct-floats", no_argument, NULL, OPTION_CONSTRUCT_FLOATS},
1581   {"no-construct-floats", no_argument, NULL, OPTION_NO_CONSTRUCT_FLOATS},
1582   {"mfp64", no_argument, NULL, OPTION_FP64},
1583   {"mfpxx", no_argument, NULL, OPTION_FPXX},
1584   {"mgp64", no_argument, NULL, OPTION_GP64},
1585   {"relax-branch", no_argument, NULL, OPTION_RELAX_BRANCH},
1586   {"no-relax-branch", no_argument, NULL, OPTION_NO_RELAX_BRANCH},
1587   {"minsn32", no_argument, NULL, OPTION_INSN32},
1588   {"mno-insn32", no_argument, NULL, OPTION_NO_INSN32},
1589   {"mshared", no_argument, NULL, OPTION_MSHARED},
1590   {"mno-shared", no_argument, NULL, OPTION_MNO_SHARED},
1591   {"msym32", no_argument, NULL, OPTION_MSYM32},
1592   {"mno-sym32", no_argument, NULL, OPTION_MNO_SYM32},
1593   {"msoft-float", no_argument, NULL, OPTION_SOFT_FLOAT},
1594   {"mhard-float", no_argument, NULL, OPTION_HARD_FLOAT},
1595   {"msingle-float", no_argument, NULL, OPTION_SINGLE_FLOAT},
1596   {"mdouble-float", no_argument, NULL, OPTION_DOUBLE_FLOAT},
1597   {"modd-spreg", no_argument, NULL, OPTION_ODD_SPREG},
1598   {"mno-odd-spreg", no_argument, NULL, OPTION_NO_ODD_SPREG},
1599
1600   /* Strictly speaking this next option is ELF specific,
1601      but we allow it for other ports as well in order to
1602      make testing easier.  */
1603   {"32", no_argument, NULL, OPTION_32},
1604
1605   /* ELF-specific options.  */
1606   {"KPIC", no_argument, NULL, OPTION_CALL_SHARED},
1607   {"call_shared", no_argument, NULL, OPTION_CALL_SHARED},
1608   {"call_nonpic", no_argument, NULL, OPTION_CALL_NONPIC},
1609   {"non_shared",  no_argument, NULL, OPTION_NON_SHARED},
1610   {"xgot", no_argument, NULL, OPTION_XGOT},
1611   {"mabi", required_argument, NULL, OPTION_MABI},
1612   {"n32", no_argument, NULL, OPTION_N32},
1613   {"64", no_argument, NULL, OPTION_64},
1614   {"mdebug", no_argument, NULL, OPTION_MDEBUG},
1615   {"no-mdebug", no_argument, NULL, OPTION_NO_MDEBUG},
1616   {"mpdr", no_argument, NULL, OPTION_PDR},
1617   {"mno-pdr", no_argument, NULL, OPTION_NO_PDR},
1618   {"mvxworks-pic", no_argument, NULL, OPTION_MVXWORKS_PIC},
1619   {"mnan", required_argument, NULL, OPTION_NAN},
1620
1621   {NULL, no_argument, NULL, 0}
1622 };
1623 size_t md_longopts_size = sizeof (md_longopts);
1624 \f
1625 /* Information about either an Application Specific Extension or an
1626    optional architecture feature that, for simplicity, we treat in the
1627    same way as an ASE.  */
1628 struct mips_ase
1629 {
1630   /* The name of the ASE, used in both the command-line and .set options.  */
1631   const char *name;
1632
1633   /* The associated ASE_* flags.  If the ASE is available on both 32-bit
1634      and 64-bit architectures, the flags here refer to the subset that
1635      is available on both.  */
1636   unsigned int flags;
1637
1638   /* The ASE_* flag used for instructions that are available on 64-bit
1639      architectures but that are not included in FLAGS.  */
1640   unsigned int flags64;
1641
1642   /* The command-line options that turn the ASE on and off.  */
1643   int option_on;
1644   int option_off;
1645
1646   /* The minimum required architecture revisions for MIPS32, MIPS64,
1647      microMIPS32 and microMIPS64, or -1 if the extension isn't supported.  */
1648   int mips32_rev;
1649   int mips64_rev;
1650   int micromips32_rev;
1651   int micromips64_rev;
1652
1653   /* The architecture where the ASE was removed or -1 if the extension has not
1654      been removed.  */
1655   int rem_rev;
1656 };
1657
1658 /* A table of all supported ASEs.  */
1659 static const struct mips_ase mips_ases[] = {
1660   { "dsp", ASE_DSP, ASE_DSP64,
1661     OPTION_DSP, OPTION_NO_DSP,
1662     2, 2, 2, 2,
1663     -1 },
1664
1665   { "dspr2", ASE_DSP | ASE_DSPR2, 0,
1666     OPTION_DSPR2, OPTION_NO_DSPR2,
1667     2, 2, 2, 2,
1668     -1 },
1669
1670   { "dspr3", ASE_DSP | ASE_DSPR2 | ASE_DSPR3, 0,
1671     OPTION_DSPR3, OPTION_NO_DSPR3,
1672     6, 6, -1, -1,
1673     -1 },
1674
1675   { "eva", ASE_EVA, 0,
1676     OPTION_EVA, OPTION_NO_EVA,
1677      2,  2,  2,  2,
1678     -1 },
1679
1680   { "mcu", ASE_MCU, 0,
1681     OPTION_MCU, OPTION_NO_MCU,
1682      2,  2,  2,  2,
1683     -1 },
1684
1685   /* Deprecated in MIPS64r5, but we don't implement that yet.  */
1686   { "mdmx", ASE_MDMX, 0,
1687     OPTION_MDMX, OPTION_NO_MDMX,
1688     -1, 1, -1, -1,
1689      6 },
1690
1691   /* Requires 64-bit FPRs, so the minimum MIPS32 revision is 2.  */
1692   { "mips3d", ASE_MIPS3D, 0,
1693     OPTION_MIPS3D, OPTION_NO_MIPS3D,
1694     2, 1, -1, -1,
1695     6 },
1696
1697   { "mt", ASE_MT, 0,
1698     OPTION_MT, OPTION_NO_MT,
1699      2,  2, -1, -1,
1700     -1 },
1701
1702   { "smartmips", ASE_SMARTMIPS, 0,
1703     OPTION_SMARTMIPS, OPTION_NO_SMARTMIPS,
1704     1, -1, -1, -1,
1705     6 },
1706
1707   { "virt", ASE_VIRT, ASE_VIRT64,
1708     OPTION_VIRT, OPTION_NO_VIRT,
1709      2,  2,  2,  2,
1710     -1 },
1711
1712   { "msa", ASE_MSA, ASE_MSA64,
1713     OPTION_MSA, OPTION_NO_MSA,
1714      2,  2,  2,  2,
1715     -1 },
1716
1717   { "xpa", ASE_XPA, 0,
1718     OPTION_XPA, OPTION_NO_XPA,
1719      2,  2, -1, -1,
1720     -1 },
1721 };
1722
1723 /* The set of ASEs that require -mfp64.  */
1724 #define FP64_ASES (ASE_MIPS3D | ASE_MDMX | ASE_MSA)
1725
1726 /* Groups of ASE_* flags that represent different revisions of an ASE.  */
1727 static const unsigned int mips_ase_groups[] = {
1728   ASE_DSP | ASE_DSPR2 | ASE_DSPR3
1729 };
1730 \f
1731 /* Pseudo-op table.
1732
1733    The following pseudo-ops from the Kane and Heinrich MIPS book
1734    should be defined here, but are currently unsupported: .alias,
1735    .galive, .gjaldef, .gjrlive, .livereg, .noalias.
1736
1737    The following pseudo-ops from the Kane and Heinrich MIPS book are
1738    specific to the type of debugging information being generated, and
1739    should be defined by the object format: .aent, .begin, .bend,
1740    .bgnb, .end, .endb, .ent, .fmask, .frame, .loc, .mask, .verstamp,
1741    .vreg.
1742
1743    The following pseudo-ops from the Kane and Heinrich MIPS book are
1744    not MIPS CPU specific, but are also not specific to the object file
1745    format.  This file is probably the best place to define them, but
1746    they are not currently supported: .asm0, .endr, .lab, .struct.  */
1747
1748 static const pseudo_typeS mips_pseudo_table[] =
1749 {
1750   /* MIPS specific pseudo-ops.  */
1751   {"option", s_option, 0},
1752   {"set", s_mipsset, 0},
1753   {"rdata", s_change_sec, 'r'},
1754   {"sdata", s_change_sec, 's'},
1755   {"livereg", s_ignore, 0},
1756   {"abicalls", s_abicalls, 0},
1757   {"cpload", s_cpload, 0},
1758   {"cpsetup", s_cpsetup, 0},
1759   {"cplocal", s_cplocal, 0},
1760   {"cprestore", s_cprestore, 0},
1761   {"cpreturn", s_cpreturn, 0},
1762   {"dtprelword", s_dtprelword, 0},
1763   {"dtpreldword", s_dtpreldword, 0},
1764   {"tprelword", s_tprelword, 0},
1765   {"tpreldword", s_tpreldword, 0},
1766   {"gpvalue", s_gpvalue, 0},
1767   {"gpword", s_gpword, 0},
1768   {"gpdword", s_gpdword, 0},
1769   {"ehword", s_ehword, 0},
1770   {"cpadd", s_cpadd, 0},
1771   {"insn", s_insn, 0},
1772   {"nan", s_nan, 0},
1773   {"module", s_module, 0},
1774
1775   /* Relatively generic pseudo-ops that happen to be used on MIPS
1776      chips.  */
1777   {"asciiz", stringer, 8 + 1},
1778   {"bss", s_change_sec, 'b'},
1779   {"err", s_err, 0},
1780   {"half", s_cons, 1},
1781   {"dword", s_cons, 3},
1782   {"weakext", s_mips_weakext, 0},
1783   {"origin", s_org, 0},
1784   {"repeat", s_rept, 0},
1785
1786   /* For MIPS this is non-standard, but we define it for consistency.  */
1787   {"sbss", s_change_sec, 'B'},
1788
1789   /* These pseudo-ops are defined in read.c, but must be overridden
1790      here for one reason or another.  */
1791   {"align", s_align, 0},
1792   {"byte", s_cons, 0},
1793   {"data", s_change_sec, 'd'},
1794   {"double", s_float_cons, 'd'},
1795   {"float", s_float_cons, 'f'},
1796   {"globl", s_mips_globl, 0},
1797   {"global", s_mips_globl, 0},
1798   {"hword", s_cons, 1},
1799   {"int", s_cons, 2},
1800   {"long", s_cons, 2},
1801   {"octa", s_cons, 4},
1802   {"quad", s_cons, 3},
1803   {"section", s_change_section, 0},
1804   {"short", s_cons, 1},
1805   {"single", s_float_cons, 'f'},
1806   {"stabd", s_mips_stab, 'd'},
1807   {"stabn", s_mips_stab, 'n'},
1808   {"stabs", s_mips_stab, 's'},
1809   {"text", s_change_sec, 't'},
1810   {"word", s_cons, 2},
1811
1812   { "extern", ecoff_directive_extern, 0},
1813
1814   { NULL, NULL, 0 },
1815 };
1816
1817 static const pseudo_typeS mips_nonecoff_pseudo_table[] =
1818 {
1819   /* These pseudo-ops should be defined by the object file format.
1820      However, a.out doesn't support them, so we have versions here.  */
1821   {"aent", s_mips_ent, 1},
1822   {"bgnb", s_ignore, 0},
1823   {"end", s_mips_end, 0},
1824   {"endb", s_ignore, 0},
1825   {"ent", s_mips_ent, 0},
1826   {"file", s_mips_file, 0},
1827   {"fmask", s_mips_mask, 'F'},
1828   {"frame", s_mips_frame, 0},
1829   {"loc", s_mips_loc, 0},
1830   {"mask", s_mips_mask, 'R'},
1831   {"verstamp", s_ignore, 0},
1832   { NULL, NULL, 0 },
1833 };
1834
1835 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
1836    purpose of the `.dc.a' internal pseudo-op.  */
1837
1838 int
1839 mips_address_bytes (void)
1840 {
1841   file_mips_check_options ();
1842   return HAVE_64BIT_ADDRESSES ? 8 : 4;
1843 }
1844
1845 extern void pop_insert (const pseudo_typeS *);
1846
1847 void
1848 mips_pop_insert (void)
1849 {
1850   pop_insert (mips_pseudo_table);
1851   if (! ECOFF_DEBUGGING)
1852     pop_insert (mips_nonecoff_pseudo_table);
1853 }
1854 \f
1855 /* Symbols labelling the current insn.  */
1856
1857 struct insn_label_list
1858 {
1859   struct insn_label_list *next;
1860   symbolS *label;
1861 };
1862
1863 static struct insn_label_list *free_insn_labels;
1864 #define label_list tc_segment_info_data.labels
1865
1866 static void mips_clear_insn_labels (void);
1867 static void mips_mark_labels (void);
1868 static void mips_compressed_mark_labels (void);
1869
1870 static inline void
1871 mips_clear_insn_labels (void)
1872 {
1873   struct insn_label_list **pl;
1874   segment_info_type *si;
1875
1876   if (now_seg)
1877     {
1878       for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1879         ;
1880
1881       si = seg_info (now_seg);
1882       *pl = si->label_list;
1883       si->label_list = NULL;
1884     }
1885 }
1886
1887 /* Mark instruction labels in MIPS16/microMIPS mode.  */
1888
1889 static inline void
1890 mips_mark_labels (void)
1891 {
1892   if (HAVE_CODE_COMPRESSION)
1893     mips_compressed_mark_labels ();
1894 }
1895 \f
1896 static char *expr_end;
1897
1898 /* An expression in a macro instruction.  This is set by mips_ip and
1899    mips16_ip and when populated is always an O_constant.  */
1900
1901 static expressionS imm_expr;
1902
1903 /* The relocatable field in an instruction and the relocs associated
1904    with it.  These variables are used for instructions like LUI and
1905    JAL as well as true offsets.  They are also used for address
1906    operands in macros.  */
1907
1908 static expressionS offset_expr;
1909 static bfd_reloc_code_real_type offset_reloc[3]
1910   = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
1911
1912 /* This is set to the resulting size of the instruction to be produced
1913    by mips16_ip if an explicit extension is used or by mips_ip if an
1914    explicit size is supplied.  */
1915
1916 static unsigned int forced_insn_length;
1917
1918 /* True if we are assembling an instruction.  All dot symbols defined during
1919    this time should be treated as code labels.  */
1920
1921 static bfd_boolean mips_assembling_insn;
1922
1923 /* The pdr segment for per procedure frame/regmask info.  Not used for
1924    ECOFF debugging.  */
1925
1926 static segT pdr_seg;
1927
1928 /* The default target format to use.  */
1929
1930 #if defined (TE_FreeBSD)
1931 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips-freebsd"
1932 #elif defined (TE_TMIPS)
1933 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX "trad" ENDIAN "mips"
1934 #else
1935 #define ELF_TARGET(PREFIX, ENDIAN) PREFIX ENDIAN "mips"
1936 #endif
1937
1938 const char *
1939 mips_target_format (void)
1940 {
1941   switch (OUTPUT_FLAVOR)
1942     {
1943     case bfd_target_elf_flavour:
1944 #ifdef TE_VXWORKS
1945       if (!HAVE_64BIT_OBJECTS && !HAVE_NEWABI)
1946         return (target_big_endian
1947                 ? "elf32-bigmips-vxworks"
1948                 : "elf32-littlemips-vxworks");
1949 #endif
1950       return (target_big_endian
1951               ? (HAVE_64BIT_OBJECTS
1952                  ? ELF_TARGET ("elf64-", "big")
1953                  : (HAVE_NEWABI
1954                     ? ELF_TARGET ("elf32-n", "big")
1955                     : ELF_TARGET ("elf32-", "big")))
1956               : (HAVE_64BIT_OBJECTS
1957                  ? ELF_TARGET ("elf64-", "little")
1958                  : (HAVE_NEWABI
1959                     ? ELF_TARGET ("elf32-n", "little")
1960                     : ELF_TARGET ("elf32-", "little"))));
1961     default:
1962       abort ();
1963       return NULL;
1964     }
1965 }
1966
1967 /* Return the ISA revision that is currently in use, or 0 if we are
1968    generating code for MIPS V or below.  */
1969
1970 static int
1971 mips_isa_rev (void)
1972 {
1973   if (mips_opts.isa == ISA_MIPS32R2 || mips_opts.isa == ISA_MIPS64R2)
1974     return 2;
1975
1976   if (mips_opts.isa == ISA_MIPS32R3 || mips_opts.isa == ISA_MIPS64R3)
1977     return 3;
1978
1979   if (mips_opts.isa == ISA_MIPS32R5 || mips_opts.isa == ISA_MIPS64R5)
1980     return 5;
1981
1982   if (mips_opts.isa == ISA_MIPS32R6 || mips_opts.isa == ISA_MIPS64R6)
1983     return 6;
1984
1985   /* microMIPS implies revision 2 or above.  */
1986   if (mips_opts.micromips)
1987     return 2;
1988
1989   if (mips_opts.isa == ISA_MIPS32 || mips_opts.isa == ISA_MIPS64)
1990     return 1;
1991
1992   return 0;
1993 }
1994
1995 /* Return the mask of all ASEs that are revisions of those in FLAGS.  */
1996
1997 static unsigned int
1998 mips_ase_mask (unsigned int flags)
1999 {
2000   unsigned int i;
2001
2002   for (i = 0; i < ARRAY_SIZE (mips_ase_groups); i++)
2003     if (flags & mips_ase_groups[i])
2004       flags |= mips_ase_groups[i];
2005   return flags;
2006 }
2007
2008 /* Check whether the current ISA supports ASE.  Issue a warning if
2009    appropriate.  */
2010
2011 static void
2012 mips_check_isa_supports_ase (const struct mips_ase *ase)
2013 {
2014   const char *base;
2015   int min_rev, size;
2016   static unsigned int warned_isa;
2017   static unsigned int warned_fp32;
2018
2019   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
2020     min_rev = mips_opts.micromips ? ase->micromips64_rev : ase->mips64_rev;
2021   else
2022     min_rev = mips_opts.micromips ? ase->micromips32_rev : ase->mips32_rev;
2023   if ((min_rev < 0 || mips_isa_rev () < min_rev)
2024       && (warned_isa & ase->flags) != ase->flags)
2025     {
2026       warned_isa |= ase->flags;
2027       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2028       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2029       if (min_rev < 0)
2030         as_warn (_("the %d-bit %s architecture does not support the"
2031                    " `%s' extension"), size, base, ase->name);
2032       else
2033         as_warn (_("the `%s' extension requires %s%d revision %d or greater"),
2034                  ase->name, base, size, min_rev);
2035     }
2036   else if ((ase->rem_rev > 0 && mips_isa_rev () >= ase->rem_rev)
2037            && (warned_isa & ase->flags) != ase->flags)
2038     {
2039       warned_isa |= ase->flags;
2040       base = mips_opts.micromips ? "microMIPS" : "MIPS";
2041       size = ISA_HAS_64BIT_REGS (mips_opts.isa) ? 64 : 32;
2042       as_warn (_("the `%s' extension was removed in %s%d revision %d"),
2043                ase->name, base, size, ase->rem_rev);
2044     }
2045
2046   if ((ase->flags & FP64_ASES)
2047       && mips_opts.fp != 64
2048       && (warned_fp32 & ase->flags) != ase->flags)
2049     {
2050       warned_fp32 |= ase->flags;
2051       as_warn (_("the `%s' extension requires 64-bit FPRs"), ase->name);
2052     }
2053 }
2054
2055 /* Check all enabled ASEs to see whether they are supported by the
2056    chosen architecture.  */
2057
2058 static void
2059 mips_check_isa_supports_ases (void)
2060 {
2061   unsigned int i, mask;
2062
2063   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2064     {
2065       mask = mips_ase_mask (mips_ases[i].flags);
2066       if ((mips_opts.ase & mask) == mips_ases[i].flags)
2067         mips_check_isa_supports_ase (&mips_ases[i]);
2068     }
2069 }
2070
2071 /* Set the state of ASE to ENABLED_P.  Return the mask of ASE_* flags
2072    that were affected.  */
2073
2074 static unsigned int
2075 mips_set_ase (const struct mips_ase *ase, struct mips_set_options *opts,
2076               bfd_boolean enabled_p)
2077 {
2078   unsigned int mask;
2079
2080   mask = mips_ase_mask (ase->flags);
2081   opts->ase &= ~mask;
2082   if (enabled_p)
2083     opts->ase |= ase->flags;
2084   return mask;
2085 }
2086
2087 /* Return the ASE called NAME, or null if none.  */
2088
2089 static const struct mips_ase *
2090 mips_lookup_ase (const char *name)
2091 {
2092   unsigned int i;
2093
2094   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
2095     if (strcmp (name, mips_ases[i].name) == 0)
2096       return &mips_ases[i];
2097   return NULL;
2098 }
2099
2100 /* Return the length of a microMIPS instruction in bytes.  If bits of
2101    the mask beyond the low 16 are 0, then it is a 16-bit instruction,
2102    otherwise it is a 32-bit instruction.  */
2103
2104 static inline unsigned int
2105 micromips_insn_length (const struct mips_opcode *mo)
2106 {
2107   return (mo->mask >> 16) == 0 ? 2 : 4;
2108 }
2109
2110 /* Return the length of MIPS16 instruction OPCODE.  */
2111
2112 static inline unsigned int
2113 mips16_opcode_length (unsigned long opcode)
2114 {
2115   return (opcode >> 16) == 0 ? 2 : 4;
2116 }
2117
2118 /* Return the length of instruction INSN.  */
2119
2120 static inline unsigned int
2121 insn_length (const struct mips_cl_insn *insn)
2122 {
2123   if (mips_opts.micromips)
2124     return micromips_insn_length (insn->insn_mo);
2125   else if (mips_opts.mips16)
2126     return mips16_opcode_length (insn->insn_opcode);
2127   else
2128     return 4;
2129 }
2130
2131 /* Initialise INSN from opcode entry MO.  Leave its position unspecified.  */
2132
2133 static void
2134 create_insn (struct mips_cl_insn *insn, const struct mips_opcode *mo)
2135 {
2136   size_t i;
2137
2138   insn->insn_mo = mo;
2139   insn->insn_opcode = mo->match;
2140   insn->frag = NULL;
2141   insn->where = 0;
2142   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2143     insn->fixp[i] = NULL;
2144   insn->fixed_p = (mips_opts.noreorder > 0);
2145   insn->noreorder_p = (mips_opts.noreorder > 0);
2146   insn->mips16_absolute_jump_p = 0;
2147   insn->complete_p = 0;
2148   insn->cleared_p = 0;
2149 }
2150
2151 /* Get a list of all the operands in INSN.  */
2152
2153 static const struct mips_operand_array *
2154 insn_operands (const struct mips_cl_insn *insn)
2155 {
2156   if (insn->insn_mo >= &mips_opcodes[0]
2157       && insn->insn_mo < &mips_opcodes[NUMOPCODES])
2158     return &mips_operands[insn->insn_mo - &mips_opcodes[0]];
2159
2160   if (insn->insn_mo >= &mips16_opcodes[0]
2161       && insn->insn_mo < &mips16_opcodes[bfd_mips16_num_opcodes])
2162     return &mips16_operands[insn->insn_mo - &mips16_opcodes[0]];
2163
2164   if (insn->insn_mo >= &micromips_opcodes[0]
2165       && insn->insn_mo < &micromips_opcodes[bfd_micromips_num_opcodes])
2166     return &micromips_operands[insn->insn_mo - &micromips_opcodes[0]];
2167
2168   abort ();
2169 }
2170
2171 /* Get a description of operand OPNO of INSN.  */
2172
2173 static const struct mips_operand *
2174 insn_opno (const struct mips_cl_insn *insn, unsigned opno)
2175 {
2176   const struct mips_operand_array *operands;
2177
2178   operands = insn_operands (insn);
2179   if (opno >= MAX_OPERANDS || !operands->operand[opno])
2180     abort ();
2181   return operands->operand[opno];
2182 }
2183
2184 /* Install UVAL as the value of OPERAND in INSN.  */
2185
2186 static inline void
2187 insn_insert_operand (struct mips_cl_insn *insn,
2188                      const struct mips_operand *operand, unsigned int uval)
2189 {
2190   insn->insn_opcode = mips_insert_operand (operand, insn->insn_opcode, uval);
2191 }
2192
2193 /* Extract the value of OPERAND from INSN.  */
2194
2195 static inline unsigned
2196 insn_extract_operand (const struct mips_cl_insn *insn,
2197                       const struct mips_operand *operand)
2198 {
2199   return mips_extract_operand (operand, insn->insn_opcode);
2200 }
2201
2202 /* Record the current MIPS16/microMIPS mode in now_seg.  */
2203
2204 static void
2205 mips_record_compressed_mode (void)
2206 {
2207   segment_info_type *si;
2208
2209   si = seg_info (now_seg);
2210   if (si->tc_segment_info_data.mips16 != mips_opts.mips16)
2211     si->tc_segment_info_data.mips16 = mips_opts.mips16;
2212   if (si->tc_segment_info_data.micromips != mips_opts.micromips)
2213     si->tc_segment_info_data.micromips = mips_opts.micromips;
2214 }
2215
2216 /* Read a standard MIPS instruction from BUF.  */
2217
2218 static unsigned long
2219 read_insn (char *buf)
2220 {
2221   if (target_big_endian)
2222     return bfd_getb32 ((bfd_byte *) buf);
2223   else
2224     return bfd_getl32 ((bfd_byte *) buf);
2225 }
2226
2227 /* Write standard MIPS instruction INSN to BUF.  Return a pointer to
2228    the next byte.  */
2229
2230 static char *
2231 write_insn (char *buf, unsigned int insn)
2232 {
2233   md_number_to_chars (buf, insn, 4);
2234   return buf + 4;
2235 }
2236
2237 /* Read a microMIPS or MIPS16 opcode from BUF, given that it
2238    has length LENGTH.  */
2239
2240 static unsigned long
2241 read_compressed_insn (char *buf, unsigned int length)
2242 {
2243   unsigned long insn;
2244   unsigned int i;
2245
2246   insn = 0;
2247   for (i = 0; i < length; i += 2)
2248     {
2249       insn <<= 16;
2250       if (target_big_endian)
2251         insn |= bfd_getb16 ((char *) buf);
2252       else
2253         insn |= bfd_getl16 ((char *) buf);
2254       buf += 2;
2255     }
2256   return insn;
2257 }
2258
2259 /* Write microMIPS or MIPS16 instruction INSN to BUF, given that the
2260    instruction is LENGTH bytes long.  Return a pointer to the next byte.  */
2261
2262 static char *
2263 write_compressed_insn (char *buf, unsigned int insn, unsigned int length)
2264 {
2265   unsigned int i;
2266
2267   for (i = 0; i < length; i += 2)
2268     md_number_to_chars (buf + i, insn >> ((length - i - 2) * 8), 2);
2269   return buf + length;
2270 }
2271
2272 /* Install INSN at the location specified by its "frag" and "where" fields.  */
2273
2274 static void
2275 install_insn (const struct mips_cl_insn *insn)
2276 {
2277   char *f = insn->frag->fr_literal + insn->where;
2278   if (HAVE_CODE_COMPRESSION)
2279     write_compressed_insn (f, insn->insn_opcode, insn_length (insn));
2280   else
2281     write_insn (f, insn->insn_opcode);
2282   mips_record_compressed_mode ();
2283 }
2284
2285 /* Move INSN to offset WHERE in FRAG.  Adjust the fixups accordingly
2286    and install the opcode in the new location.  */
2287
2288 static void
2289 move_insn (struct mips_cl_insn *insn, fragS *frag, long where)
2290 {
2291   size_t i;
2292
2293   insn->frag = frag;
2294   insn->where = where;
2295   for (i = 0; i < ARRAY_SIZE (insn->fixp); i++)
2296     if (insn->fixp[i] != NULL)
2297       {
2298         insn->fixp[i]->fx_frag = frag;
2299         insn->fixp[i]->fx_where = where;
2300       }
2301   install_insn (insn);
2302 }
2303
2304 /* Add INSN to the end of the output.  */
2305
2306 static void
2307 add_fixed_insn (struct mips_cl_insn *insn)
2308 {
2309   char *f = frag_more (insn_length (insn));
2310   move_insn (insn, frag_now, f - frag_now->fr_literal);
2311 }
2312
2313 /* Start a variant frag and move INSN to the start of the variant part,
2314    marking it as fixed.  The other arguments are as for frag_var.  */
2315
2316 static void
2317 add_relaxed_insn (struct mips_cl_insn *insn, int max_chars, int var,
2318                   relax_substateT subtype, symbolS *symbol, offsetT offset)
2319 {
2320   frag_grow (max_chars);
2321   move_insn (insn, frag_now, frag_more (0) - frag_now->fr_literal);
2322   insn->fixed_p = 1;
2323   frag_var (rs_machine_dependent, max_chars, var,
2324             subtype, symbol, offset, NULL);
2325 }
2326
2327 /* Insert N copies of INSN into the history buffer, starting at
2328    position FIRST.  Neither FIRST nor N need to be clipped.  */
2329
2330 static void
2331 insert_into_history (unsigned int first, unsigned int n,
2332                      const struct mips_cl_insn *insn)
2333 {
2334   if (mips_relax.sequence != 2)
2335     {
2336       unsigned int i;
2337
2338       for (i = ARRAY_SIZE (history); i-- > first;)
2339         if (i >= first + n)
2340           history[i] = history[i - n];
2341         else
2342           history[i] = *insn;
2343     }
2344 }
2345
2346 /* Clear the error in insn_error.  */
2347
2348 static void
2349 clear_insn_error (void)
2350 {
2351   memset (&insn_error, 0, sizeof (insn_error));
2352 }
2353
2354 /* Possibly record error message MSG for the current instruction.
2355    If the error is about a particular argument, ARGNUM is the 1-based
2356    number of that argument, otherwise it is 0.  FORMAT is the format
2357    of MSG.  Return true if MSG was used, false if the current message
2358    was kept.  */
2359
2360 static bfd_boolean
2361 set_insn_error_format (int argnum, enum mips_insn_error_format format,
2362                        const char *msg)
2363 {
2364   if (argnum == 0)
2365     {
2366       /* Give priority to errors against specific arguments, and to
2367          the first whole-instruction message.  */
2368       if (insn_error.msg)
2369         return FALSE;
2370     }
2371   else
2372     {
2373       /* Keep insn_error if it is against a later argument.  */
2374       if (argnum < insn_error.min_argnum)
2375         return FALSE;
2376
2377       /* If both errors are against the same argument but are different,
2378          give up on reporting a specific error for this argument.
2379          See the comment about mips_insn_error for details.  */
2380       if (argnum == insn_error.min_argnum
2381           && insn_error.msg
2382           && strcmp (insn_error.msg, msg) != 0)
2383         {
2384           insn_error.msg = 0;
2385           insn_error.min_argnum += 1;
2386           return FALSE;
2387         }
2388     }
2389   insn_error.min_argnum = argnum;
2390   insn_error.format = format;
2391   insn_error.msg = msg;
2392   return TRUE;
2393 }
2394
2395 /* Record an instruction error with no % format fields.  ARGNUM and MSG are
2396    as for set_insn_error_format.  */
2397
2398 static void
2399 set_insn_error (int argnum, const char *msg)
2400 {
2401   set_insn_error_format (argnum, ERR_FMT_PLAIN, msg);
2402 }
2403
2404 /* Record an instruction error with one %d field I.  ARGNUM and MSG are
2405    as for set_insn_error_format.  */
2406
2407 static void
2408 set_insn_error_i (int argnum, const char *msg, int i)
2409 {
2410   if (set_insn_error_format (argnum, ERR_FMT_I, msg))
2411     insn_error.u.i = i;
2412 }
2413
2414 /* Record an instruction error with two %s fields S1 and S2.  ARGNUM and MSG
2415    are as for set_insn_error_format.  */
2416
2417 static void
2418 set_insn_error_ss (int argnum, const char *msg, const char *s1, const char *s2)
2419 {
2420   if (set_insn_error_format (argnum, ERR_FMT_SS, msg))
2421     {
2422       insn_error.u.ss[0] = s1;
2423       insn_error.u.ss[1] = s2;
2424     }
2425 }
2426
2427 /* Report the error in insn_error, which is against assembly code STR.  */
2428
2429 static void
2430 report_insn_error (const char *str)
2431 {
2432   const char *msg = concat (insn_error.msg, " `%s'", NULL);
2433
2434   switch (insn_error.format)
2435     {
2436     case ERR_FMT_PLAIN:
2437       as_bad (msg, str);
2438       break;
2439
2440     case ERR_FMT_I:
2441       as_bad (msg, insn_error.u.i, str);
2442       break;
2443
2444     case ERR_FMT_SS:
2445       as_bad (msg, insn_error.u.ss[0], insn_error.u.ss[1], str);
2446       break;
2447     }
2448
2449   free ((char *) msg);
2450 }
2451
2452 /* Initialize vr4120_conflicts.  There is a bit of duplication here:
2453    the idea is to make it obvious at a glance that each errata is
2454    included.  */
2455
2456 static void
2457 init_vr4120_conflicts (void)
2458 {
2459 #define CONFLICT(FIRST, SECOND) \
2460     vr4120_conflicts[FIX_VR4120_##FIRST] |= 1 << FIX_VR4120_##SECOND
2461
2462   /* Errata 21 - [D]DIV[U] after [D]MACC */
2463   CONFLICT (MACC, DIV);
2464   CONFLICT (DMACC, DIV);
2465
2466   /* Errata 23 - Continuous DMULT[U]/DMACC instructions.  */
2467   CONFLICT (DMULT, DMULT);
2468   CONFLICT (DMULT, DMACC);
2469   CONFLICT (DMACC, DMULT);
2470   CONFLICT (DMACC, DMACC);
2471
2472   /* Errata 24 - MT{LO,HI} after [D]MACC */
2473   CONFLICT (MACC, MTHILO);
2474   CONFLICT (DMACC, MTHILO);
2475
2476   /* VR4181A errata MD(1): "If a MULT, MULTU, DMULT or DMULTU
2477      instruction is executed immediately after a MACC or DMACC
2478      instruction, the result of [either instruction] is incorrect."  */
2479   CONFLICT (MACC, MULT);
2480   CONFLICT (MACC, DMULT);
2481   CONFLICT (DMACC, MULT);
2482   CONFLICT (DMACC, DMULT);
2483
2484   /* VR4181A errata MD(4): "If a MACC or DMACC instruction is
2485      executed immediately after a DMULT, DMULTU, DIV, DIVU,
2486      DDIV or DDIVU instruction, the result of the MACC or
2487      DMACC instruction is incorrect.".  */
2488   CONFLICT (DMULT, MACC);
2489   CONFLICT (DMULT, DMACC);
2490   CONFLICT (DIV, MACC);
2491   CONFLICT (DIV, DMACC);
2492
2493 #undef CONFLICT
2494 }
2495
2496 struct regname {
2497   const char *name;
2498   unsigned int num;
2499 };
2500
2501 #define RNUM_MASK       0x00000ff
2502 #define RTYPE_MASK      0x0ffff00
2503 #define RTYPE_NUM       0x0000100
2504 #define RTYPE_FPU       0x0000200
2505 #define RTYPE_FCC       0x0000400
2506 #define RTYPE_VEC       0x0000800
2507 #define RTYPE_GP        0x0001000
2508 #define RTYPE_CP0       0x0002000
2509 #define RTYPE_PC        0x0004000
2510 #define RTYPE_ACC       0x0008000
2511 #define RTYPE_CCC       0x0010000
2512 #define RTYPE_VI        0x0020000
2513 #define RTYPE_VF        0x0040000
2514 #define RTYPE_R5900_I   0x0080000
2515 #define RTYPE_R5900_Q   0x0100000
2516 #define RTYPE_R5900_R   0x0200000
2517 #define RTYPE_R5900_ACC 0x0400000
2518 #define RTYPE_MSA       0x0800000
2519 #define RWARN           0x8000000
2520
2521 #define GENERIC_REGISTER_NUMBERS \
2522     {"$0",      RTYPE_NUM | 0},  \
2523     {"$1",      RTYPE_NUM | 1},  \
2524     {"$2",      RTYPE_NUM | 2},  \
2525     {"$3",      RTYPE_NUM | 3},  \
2526     {"$4",      RTYPE_NUM | 4},  \
2527     {"$5",      RTYPE_NUM | 5},  \
2528     {"$6",      RTYPE_NUM | 6},  \
2529     {"$7",      RTYPE_NUM | 7},  \
2530     {"$8",      RTYPE_NUM | 8},  \
2531     {"$9",      RTYPE_NUM | 9},  \
2532     {"$10",     RTYPE_NUM | 10}, \
2533     {"$11",     RTYPE_NUM | 11}, \
2534     {"$12",     RTYPE_NUM | 12}, \
2535     {"$13",     RTYPE_NUM | 13}, \
2536     {"$14",     RTYPE_NUM | 14}, \
2537     {"$15",     RTYPE_NUM | 15}, \
2538     {"$16",     RTYPE_NUM | 16}, \
2539     {"$17",     RTYPE_NUM | 17}, \
2540     {"$18",     RTYPE_NUM | 18}, \
2541     {"$19",     RTYPE_NUM | 19}, \
2542     {"$20",     RTYPE_NUM | 20}, \
2543     {"$21",     RTYPE_NUM | 21}, \
2544     {"$22",     RTYPE_NUM | 22}, \
2545     {"$23",     RTYPE_NUM | 23}, \
2546     {"$24",     RTYPE_NUM | 24}, \
2547     {"$25",     RTYPE_NUM | 25}, \
2548     {"$26",     RTYPE_NUM | 26}, \
2549     {"$27",     RTYPE_NUM | 27}, \
2550     {"$28",     RTYPE_NUM | 28}, \
2551     {"$29",     RTYPE_NUM | 29}, \
2552     {"$30",     RTYPE_NUM | 30}, \
2553     {"$31",     RTYPE_NUM | 31}
2554
2555 #define FPU_REGISTER_NAMES       \
2556     {"$f0",     RTYPE_FPU | 0},  \
2557     {"$f1",     RTYPE_FPU | 1},  \
2558     {"$f2",     RTYPE_FPU | 2},  \
2559     {"$f3",     RTYPE_FPU | 3},  \
2560     {"$f4",     RTYPE_FPU | 4},  \
2561     {"$f5",     RTYPE_FPU | 5},  \
2562     {"$f6",     RTYPE_FPU | 6},  \
2563     {"$f7",     RTYPE_FPU | 7},  \
2564     {"$f8",     RTYPE_FPU | 8},  \
2565     {"$f9",     RTYPE_FPU | 9},  \
2566     {"$f10",    RTYPE_FPU | 10}, \
2567     {"$f11",    RTYPE_FPU | 11}, \
2568     {"$f12",    RTYPE_FPU | 12}, \
2569     {"$f13",    RTYPE_FPU | 13}, \
2570     {"$f14",    RTYPE_FPU | 14}, \
2571     {"$f15",    RTYPE_FPU | 15}, \
2572     {"$f16",    RTYPE_FPU | 16}, \
2573     {"$f17",    RTYPE_FPU | 17}, \
2574     {"$f18",    RTYPE_FPU | 18}, \
2575     {"$f19",    RTYPE_FPU | 19}, \
2576     {"$f20",    RTYPE_FPU | 20}, \
2577     {"$f21",    RTYPE_FPU | 21}, \
2578     {"$f22",    RTYPE_FPU | 22}, \
2579     {"$f23",    RTYPE_FPU | 23}, \
2580     {"$f24",    RTYPE_FPU | 24}, \
2581     {"$f25",    RTYPE_FPU | 25}, \
2582     {"$f26",    RTYPE_FPU | 26}, \
2583     {"$f27",    RTYPE_FPU | 27}, \
2584     {"$f28",    RTYPE_FPU | 28}, \
2585     {"$f29",    RTYPE_FPU | 29}, \
2586     {"$f30",    RTYPE_FPU | 30}, \
2587     {"$f31",    RTYPE_FPU | 31}
2588
2589 #define FPU_CONDITION_CODE_NAMES \
2590     {"$fcc0",   RTYPE_FCC | 0},  \
2591     {"$fcc1",   RTYPE_FCC | 1},  \
2592     {"$fcc2",   RTYPE_FCC | 2},  \
2593     {"$fcc3",   RTYPE_FCC | 3},  \
2594     {"$fcc4",   RTYPE_FCC | 4},  \
2595     {"$fcc5",   RTYPE_FCC | 5},  \
2596     {"$fcc6",   RTYPE_FCC | 6},  \
2597     {"$fcc7",   RTYPE_FCC | 7}
2598
2599 #define COPROC_CONDITION_CODE_NAMES         \
2600     {"$cc0",    RTYPE_FCC | RTYPE_CCC | 0}, \
2601     {"$cc1",    RTYPE_FCC | RTYPE_CCC | 1}, \
2602     {"$cc2",    RTYPE_FCC | RTYPE_CCC | 2}, \
2603     {"$cc3",    RTYPE_FCC | RTYPE_CCC | 3}, \
2604     {"$cc4",    RTYPE_FCC | RTYPE_CCC | 4}, \
2605     {"$cc5",    RTYPE_FCC | RTYPE_CCC | 5}, \
2606     {"$cc6",    RTYPE_FCC | RTYPE_CCC | 6}, \
2607     {"$cc7",    RTYPE_FCC | RTYPE_CCC | 7}
2608
2609 #define N32N64_SYMBOLIC_REGISTER_NAMES \
2610     {"$a4",     RTYPE_GP | 8},  \
2611     {"$a5",     RTYPE_GP | 9},  \
2612     {"$a6",     RTYPE_GP | 10}, \
2613     {"$a7",     RTYPE_GP | 11}, \
2614     {"$ta0",    RTYPE_GP | 8},  /* alias for $a4 */ \
2615     {"$ta1",    RTYPE_GP | 9},  /* alias for $a5 */ \
2616     {"$ta2",    RTYPE_GP | 10}, /* alias for $a6 */ \
2617     {"$ta3",    RTYPE_GP | 11}, /* alias for $a7 */ \
2618     {"$t0",     RTYPE_GP | 12}, \
2619     {"$t1",     RTYPE_GP | 13}, \
2620     {"$t2",     RTYPE_GP | 14}, \
2621     {"$t3",     RTYPE_GP | 15}
2622
2623 #define O32_SYMBOLIC_REGISTER_NAMES \
2624     {"$t0",     RTYPE_GP | 8},  \
2625     {"$t1",     RTYPE_GP | 9},  \
2626     {"$t2",     RTYPE_GP | 10}, \
2627     {"$t3",     RTYPE_GP | 11}, \
2628     {"$t4",     RTYPE_GP | 12}, \
2629     {"$t5",     RTYPE_GP | 13}, \
2630     {"$t6",     RTYPE_GP | 14}, \
2631     {"$t7",     RTYPE_GP | 15}, \
2632     {"$ta0",    RTYPE_GP | 12}, /* alias for $t4 */ \
2633     {"$ta1",    RTYPE_GP | 13}, /* alias for $t5 */ \
2634     {"$ta2",    RTYPE_GP | 14}, /* alias for $t6 */ \
2635     {"$ta3",    RTYPE_GP | 15}  /* alias for $t7 */
2636
2637 /* Remaining symbolic register names */
2638 #define SYMBOLIC_REGISTER_NAMES \
2639     {"$zero",   RTYPE_GP | 0},  \
2640     {"$at",     RTYPE_GP | 1},  \
2641     {"$AT",     RTYPE_GP | 1},  \
2642     {"$v0",     RTYPE_GP | 2},  \
2643     {"$v1",     RTYPE_GP | 3},  \
2644     {"$a0",     RTYPE_GP | 4},  \
2645     {"$a1",     RTYPE_GP | 5},  \
2646     {"$a2",     RTYPE_GP | 6},  \
2647     {"$a3",     RTYPE_GP | 7},  \
2648     {"$s0",     RTYPE_GP | 16}, \
2649     {"$s1",     RTYPE_GP | 17}, \
2650     {"$s2",     RTYPE_GP | 18}, \
2651     {"$s3",     RTYPE_GP | 19}, \
2652     {"$s4",     RTYPE_GP | 20}, \
2653     {"$s5",     RTYPE_GP | 21}, \
2654     {"$s6",     RTYPE_GP | 22}, \
2655     {"$s7",     RTYPE_GP | 23}, \
2656     {"$t8",     RTYPE_GP | 24}, \
2657     {"$t9",     RTYPE_GP | 25}, \
2658     {"$k0",     RTYPE_GP | 26}, \
2659     {"$kt0",    RTYPE_GP | 26}, \
2660     {"$k1",     RTYPE_GP | 27}, \
2661     {"$kt1",    RTYPE_GP | 27}, \
2662     {"$gp",     RTYPE_GP | 28}, \
2663     {"$sp",     RTYPE_GP | 29}, \
2664     {"$s8",     RTYPE_GP | 30}, \
2665     {"$fp",     RTYPE_GP | 30}, \
2666     {"$ra",     RTYPE_GP | 31}
2667
2668 #define MIPS16_SPECIAL_REGISTER_NAMES \
2669     {"$pc",     RTYPE_PC | 0}
2670
2671 #define MDMX_VECTOR_REGISTER_NAMES \
2672     /* {"$v0",  RTYPE_VEC | 0},  clash with REG 2 above */ \
2673     /* {"$v1",  RTYPE_VEC | 1},  clash with REG 3 above */ \
2674     {"$v2",     RTYPE_VEC | 2},  \
2675     {"$v3",     RTYPE_VEC | 3},  \
2676     {"$v4",     RTYPE_VEC | 4},  \
2677     {"$v5",     RTYPE_VEC | 5},  \
2678     {"$v6",     RTYPE_VEC | 6},  \
2679     {"$v7",     RTYPE_VEC | 7},  \
2680     {"$v8",     RTYPE_VEC | 8},  \
2681     {"$v9",     RTYPE_VEC | 9},  \
2682     {"$v10",    RTYPE_VEC | 10}, \
2683     {"$v11",    RTYPE_VEC | 11}, \
2684     {"$v12",    RTYPE_VEC | 12}, \
2685     {"$v13",    RTYPE_VEC | 13}, \
2686     {"$v14",    RTYPE_VEC | 14}, \
2687     {"$v15",    RTYPE_VEC | 15}, \
2688     {"$v16",    RTYPE_VEC | 16}, \
2689     {"$v17",    RTYPE_VEC | 17}, \
2690     {"$v18",    RTYPE_VEC | 18}, \
2691     {"$v19",    RTYPE_VEC | 19}, \
2692     {"$v20",    RTYPE_VEC | 20}, \
2693     {"$v21",    RTYPE_VEC | 21}, \
2694     {"$v22",    RTYPE_VEC | 22}, \
2695     {"$v23",    RTYPE_VEC | 23}, \
2696     {"$v24",    RTYPE_VEC | 24}, \
2697     {"$v25",    RTYPE_VEC | 25}, \
2698     {"$v26",    RTYPE_VEC | 26}, \
2699     {"$v27",    RTYPE_VEC | 27}, \
2700     {"$v28",    RTYPE_VEC | 28}, \
2701     {"$v29",    RTYPE_VEC | 29}, \
2702     {"$v30",    RTYPE_VEC | 30}, \
2703     {"$v31",    RTYPE_VEC | 31}
2704
2705 #define R5900_I_NAMES \
2706     {"$I",      RTYPE_R5900_I | 0}
2707
2708 #define R5900_Q_NAMES \
2709     {"$Q",      RTYPE_R5900_Q | 0}
2710
2711 #define R5900_R_NAMES \
2712     {"$R",      RTYPE_R5900_R | 0}
2713
2714 #define R5900_ACC_NAMES \
2715     {"$ACC",    RTYPE_R5900_ACC | 0 }
2716
2717 #define MIPS_DSP_ACCUMULATOR_NAMES \
2718     {"$ac0",    RTYPE_ACC | 0}, \
2719     {"$ac1",    RTYPE_ACC | 1}, \
2720     {"$ac2",    RTYPE_ACC | 2}, \
2721     {"$ac3",    RTYPE_ACC | 3}
2722
2723 static const struct regname reg_names[] = {
2724   GENERIC_REGISTER_NUMBERS,
2725   FPU_REGISTER_NAMES,
2726   FPU_CONDITION_CODE_NAMES,
2727   COPROC_CONDITION_CODE_NAMES,
2728
2729   /* The $txx registers depends on the abi,
2730      these will be added later into the symbol table from
2731      one of the tables below once mips_abi is set after
2732      parsing of arguments from the command line. */
2733   SYMBOLIC_REGISTER_NAMES,
2734
2735   MIPS16_SPECIAL_REGISTER_NAMES,
2736   MDMX_VECTOR_REGISTER_NAMES,
2737   R5900_I_NAMES,
2738   R5900_Q_NAMES,
2739   R5900_R_NAMES,
2740   R5900_ACC_NAMES,
2741   MIPS_DSP_ACCUMULATOR_NAMES,
2742   {0, 0}
2743 };
2744
2745 static const struct regname reg_names_o32[] = {
2746   O32_SYMBOLIC_REGISTER_NAMES,
2747   {0, 0}
2748 };
2749
2750 static const struct regname reg_names_n32n64[] = {
2751   N32N64_SYMBOLIC_REGISTER_NAMES,
2752   {0, 0}
2753 };
2754
2755 /* Register symbols $v0 and $v1 map to GPRs 2 and 3, but they can also be
2756    interpreted as vector registers 0 and 1.  If SYMVAL is the value of one
2757    of these register symbols, return the associated vector register,
2758    otherwise return SYMVAL itself.  */
2759
2760 static unsigned int
2761 mips_prefer_vec_regno (unsigned int symval)
2762 {
2763   if ((symval & -2) == (RTYPE_GP | 2))
2764     return RTYPE_VEC | (symval & 1);
2765   return symval;
2766 }
2767
2768 /* Return true if string [S, E) is a valid register name, storing its
2769    symbol value in *SYMVAL_PTR if so.  */
2770
2771 static bfd_boolean
2772 mips_parse_register_1 (char *s, char *e, unsigned int *symval_ptr)
2773 {
2774   char save_c;
2775   symbolS *symbol;
2776
2777   /* Terminate name.  */
2778   save_c = *e;
2779   *e = '\0';
2780
2781   /* Look up the name.  */
2782   symbol = symbol_find (s);
2783   *e = save_c;
2784
2785   if (!symbol || S_GET_SEGMENT (symbol) != reg_section)
2786     return FALSE;
2787
2788   *symval_ptr = S_GET_VALUE (symbol);
2789   return TRUE;
2790 }
2791
2792 /* Return true if the string at *SPTR is a valid register name.  Allow it
2793    to have a VU0-style channel suffix of the form x?y?z?w? if CHANNELS_PTR
2794    is nonnull.
2795
2796    When returning true, move *SPTR past the register, store the
2797    register's symbol value in *SYMVAL_PTR and the channel mask in
2798    *CHANNELS_PTR (if nonnull).  The symbol value includes the register
2799    number (RNUM_MASK) and register type (RTYPE_MASK).  The channel mask
2800    is a 4-bit value of the form XYZW and is 0 if no suffix was given.  */
2801
2802 static bfd_boolean
2803 mips_parse_register (char **sptr, unsigned int *symval_ptr,
2804                      unsigned int *channels_ptr)
2805 {
2806   char *s, *e, *m;
2807   const char *q;
2808   unsigned int channels, symval, bit;
2809
2810   /* Find end of name.  */
2811   s = e = *sptr;
2812   if (is_name_beginner (*e))
2813     ++e;
2814   while (is_part_of_name (*e))
2815     ++e;
2816
2817   channels = 0;
2818   if (!mips_parse_register_1 (s, e, &symval))
2819     {
2820       if (!channels_ptr)
2821         return FALSE;
2822
2823       /* Eat characters from the end of the string that are valid
2824          channel suffixes.  The preceding register must be $ACC or
2825          end with a digit, so there is no ambiguity.  */
2826       bit = 1;
2827       m = e;
2828       for (q = "wzyx"; *q; q++, bit <<= 1)
2829         if (m > s && m[-1] == *q)
2830           {
2831             --m;
2832             channels |= bit;
2833           }
2834
2835       if (channels == 0
2836           || !mips_parse_register_1 (s, m, &symval)
2837           || (symval & (RTYPE_VI | RTYPE_VF | RTYPE_R5900_ACC)) == 0)
2838         return FALSE;
2839     }
2840
2841   *sptr = e;
2842   *symval_ptr = symval;
2843   if (channels_ptr)
2844     *channels_ptr = channels;
2845   return TRUE;
2846 }
2847
2848 /* Check if SPTR points at a valid register specifier according to TYPES.
2849    If so, then return 1, advance S to consume the specifier and store
2850    the register's number in REGNOP, otherwise return 0.  */
2851
2852 static int
2853 reg_lookup (char **s, unsigned int types, unsigned int *regnop)
2854 {
2855   unsigned int regno;
2856
2857   if (mips_parse_register (s, &regno, NULL))
2858     {
2859       if (types & RTYPE_VEC)
2860         regno = mips_prefer_vec_regno (regno);
2861       if (regno & types)
2862         regno &= RNUM_MASK;
2863       else
2864         regno = ~0;
2865     }
2866   else
2867     {
2868       if (types & RWARN)
2869         as_warn (_("unrecognized register name `%s'"), *s);
2870       regno = ~0;
2871     }
2872   if (regnop)
2873     *regnop = regno;
2874   return regno <= RNUM_MASK;
2875 }
2876
2877 /* Parse a VU0 "x?y?z?w?" channel mask at S and store the associated
2878    mask in *CHANNELS.  Return a pointer to the first unconsumed character.  */
2879
2880 static char *
2881 mips_parse_vu0_channels (char *s, unsigned int *channels)
2882 {
2883   unsigned int i;
2884
2885   *channels = 0;
2886   for (i = 0; i < 4; i++)
2887     if (*s == "xyzw"[i])
2888       {
2889         *channels |= 1 << (3 - i);
2890         ++s;
2891       }
2892   return s;
2893 }
2894
2895 /* Token types for parsed operand lists.  */
2896 enum mips_operand_token_type {
2897   /* A plain register, e.g. $f2.  */
2898   OT_REG,
2899
2900   /* A 4-bit XYZW channel mask.  */
2901   OT_CHANNELS,
2902
2903   /* A constant vector index, e.g. [1].  */
2904   OT_INTEGER_INDEX,
2905
2906   /* A register vector index, e.g. [$2].  */
2907   OT_REG_INDEX,
2908
2909   /* A continuous range of registers, e.g. $s0-$s4.  */
2910   OT_REG_RANGE,
2911
2912   /* A (possibly relocated) expression.  */
2913   OT_INTEGER,
2914
2915   /* A floating-point value.  */
2916   OT_FLOAT,
2917
2918   /* A single character.  This can be '(', ')' or ',', but '(' only appears
2919      before OT_REGs.  */
2920   OT_CHAR,
2921
2922   /* A doubled character, either "--" or "++".  */
2923   OT_DOUBLE_CHAR,
2924
2925   /* The end of the operand list.  */
2926   OT_END
2927 };
2928
2929 /* A parsed operand token.  */
2930 struct mips_operand_token
2931 {
2932   /* The type of token.  */
2933   enum mips_operand_token_type type;
2934   union
2935   {
2936     /* The register symbol value for an OT_REG or OT_REG_INDEX.  */
2937     unsigned int regno;
2938
2939     /* The 4-bit channel mask for an OT_CHANNEL_SUFFIX.  */
2940     unsigned int channels;
2941
2942     /* The integer value of an OT_INTEGER_INDEX.  */
2943     addressT index;
2944
2945     /* The two register symbol values involved in an OT_REG_RANGE.  */
2946     struct {
2947       unsigned int regno1;
2948       unsigned int regno2;
2949     } reg_range;
2950
2951     /* The value of an OT_INTEGER.  The value is represented as an
2952        expression and the relocation operators that were applied to
2953        that expression.  The reloc entries are BFD_RELOC_UNUSED if no
2954        relocation operators were used.  */
2955     struct {
2956       expressionS value;
2957       bfd_reloc_code_real_type relocs[3];
2958     } integer;
2959
2960     /* The binary data for an OT_FLOAT constant, and the number of bytes
2961        in the constant.  */
2962     struct {
2963       unsigned char data[8];
2964       int length;
2965     } flt;
2966
2967     /* The character represented by an OT_CHAR or OT_DOUBLE_CHAR.  */
2968     char ch;
2969   } u;
2970 };
2971
2972 /* An obstack used to construct lists of mips_operand_tokens.  */
2973 static struct obstack mips_operand_tokens;
2974
2975 /* Give TOKEN type TYPE and add it to mips_operand_tokens.  */
2976
2977 static void
2978 mips_add_token (struct mips_operand_token *token,
2979                 enum mips_operand_token_type type)
2980 {
2981   token->type = type;
2982   obstack_grow (&mips_operand_tokens, token, sizeof (*token));
2983 }
2984
2985 /* Check whether S is '(' followed by a register name.  Add OT_CHAR
2986    and OT_REG tokens for them if so, and return a pointer to the first
2987    unconsumed character.  Return null otherwise.  */
2988
2989 static char *
2990 mips_parse_base_start (char *s)
2991 {
2992   struct mips_operand_token token;
2993   unsigned int regno, channels;
2994   bfd_boolean decrement_p;
2995
2996   if (*s != '(')
2997     return 0;
2998
2999   ++s;
3000   SKIP_SPACE_TABS (s);
3001
3002   /* Only match "--" as part of a base expression.  In other contexts "--X"
3003      is a double negative.  */
3004   decrement_p = (s[0] == '-' && s[1] == '-');
3005   if (decrement_p)
3006     {
3007       s += 2;
3008       SKIP_SPACE_TABS (s);
3009     }
3010
3011   /* Allow a channel specifier because that leads to better error messages
3012      than treating something like "$vf0x++" as an expression.  */
3013   if (!mips_parse_register (&s, &regno, &channels))
3014     return 0;
3015
3016   token.u.ch = '(';
3017   mips_add_token (&token, OT_CHAR);
3018
3019   if (decrement_p)
3020     {
3021       token.u.ch = '-';
3022       mips_add_token (&token, OT_DOUBLE_CHAR);
3023     }
3024
3025   token.u.regno = regno;
3026   mips_add_token (&token, OT_REG);
3027
3028   if (channels)
3029     {
3030       token.u.channels = channels;
3031       mips_add_token (&token, OT_CHANNELS);
3032     }
3033
3034   /* For consistency, only match "++" as part of base expressions too.  */
3035   SKIP_SPACE_TABS (s);
3036   if (s[0] == '+' && s[1] == '+')
3037     {
3038       s += 2;
3039       token.u.ch = '+';
3040       mips_add_token (&token, OT_DOUBLE_CHAR);
3041     }
3042
3043   return s;
3044 }
3045
3046 /* Parse one or more tokens from S.  Return a pointer to the first
3047    unconsumed character on success.  Return null if an error was found
3048    and store the error text in insn_error.  FLOAT_FORMAT is as for
3049    mips_parse_arguments.  */
3050
3051 static char *
3052 mips_parse_argument_token (char *s, char float_format)
3053 {
3054   char *end, *save_in;
3055   const char *err;
3056   unsigned int regno1, regno2, channels;
3057   struct mips_operand_token token;
3058
3059   /* First look for "($reg", since we want to treat that as an
3060      OT_CHAR and OT_REG rather than an expression.  */
3061   end = mips_parse_base_start (s);
3062   if (end)
3063     return end;
3064
3065   /* Handle other characters that end up as OT_CHARs.  */
3066   if (*s == ')' || *s == ',')
3067     {
3068       token.u.ch = *s;
3069       mips_add_token (&token, OT_CHAR);
3070       ++s;
3071       return s;
3072     }
3073
3074   /* Handle tokens that start with a register.  */
3075   if (mips_parse_register (&s, &regno1, &channels))
3076     {
3077       if (channels)
3078         {
3079           /* A register and a VU0 channel suffix.  */
3080           token.u.regno = regno1;
3081           mips_add_token (&token, OT_REG);
3082
3083           token.u.channels = channels;
3084           mips_add_token (&token, OT_CHANNELS);
3085           return s;
3086         }
3087
3088       SKIP_SPACE_TABS (s);
3089       if (*s == '-')
3090         {
3091           /* A register range.  */
3092           ++s;
3093           SKIP_SPACE_TABS (s);
3094           if (!mips_parse_register (&s, &regno2, NULL))
3095             {
3096               set_insn_error (0, _("invalid register range"));
3097               return 0;
3098             }
3099
3100           token.u.reg_range.regno1 = regno1;
3101           token.u.reg_range.regno2 = regno2;
3102           mips_add_token (&token, OT_REG_RANGE);
3103           return s;
3104         }
3105
3106       /* Add the register itself.  */
3107       token.u.regno = regno1;
3108       mips_add_token (&token, OT_REG);
3109
3110       /* Check for a vector index.  */
3111       if (*s == '[')
3112         {
3113           ++s;
3114           SKIP_SPACE_TABS (s);
3115           if (mips_parse_register (&s, &token.u.regno, NULL))
3116             mips_add_token (&token, OT_REG_INDEX);
3117           else
3118             {
3119               expressionS element;
3120
3121               my_getExpression (&element, s);
3122               if (element.X_op != O_constant)
3123                 {
3124                   set_insn_error (0, _("vector element must be constant"));
3125                   return 0;
3126                 }
3127               s = expr_end;
3128               token.u.index = element.X_add_number;
3129               mips_add_token (&token, OT_INTEGER_INDEX);
3130             }
3131           SKIP_SPACE_TABS (s);
3132           if (*s != ']')
3133             {
3134               set_insn_error (0, _("missing `]'"));
3135               return 0;
3136             }
3137           ++s;
3138         }
3139       return s;
3140     }
3141
3142   if (float_format)
3143     {
3144       /* First try to treat expressions as floats.  */
3145       save_in = input_line_pointer;
3146       input_line_pointer = s;
3147       err = md_atof (float_format, (char *) token.u.flt.data,
3148                      &token.u.flt.length);
3149       end = input_line_pointer;
3150       input_line_pointer = save_in;
3151       if (err && *err)
3152         {
3153           set_insn_error (0, err);
3154           return 0;
3155         }
3156       if (s != end)
3157         {
3158           mips_add_token (&token, OT_FLOAT);
3159           return end;
3160         }
3161     }
3162
3163   /* Treat everything else as an integer expression.  */
3164   token.u.integer.relocs[0] = BFD_RELOC_UNUSED;
3165   token.u.integer.relocs[1] = BFD_RELOC_UNUSED;
3166   token.u.integer.relocs[2] = BFD_RELOC_UNUSED;
3167   my_getSmallExpression (&token.u.integer.value, token.u.integer.relocs, s);
3168   s = expr_end;
3169   mips_add_token (&token, OT_INTEGER);
3170   return s;
3171 }
3172
3173 /* S points to the operand list for an instruction.  FLOAT_FORMAT is 'f'
3174    if expressions should be treated as 32-bit floating-point constants,
3175    'd' if they should be treated as 64-bit floating-point constants,
3176    or 0 if they should be treated as integer expressions (the usual case).
3177
3178    Return a list of tokens on success, otherwise return 0.  The caller
3179    must obstack_free the list after use.  */
3180
3181 static struct mips_operand_token *
3182 mips_parse_arguments (char *s, char float_format)
3183 {
3184   struct mips_operand_token token;
3185
3186   SKIP_SPACE_TABS (s);
3187   while (*s)
3188     {
3189       s = mips_parse_argument_token (s, float_format);
3190       if (!s)
3191         {
3192           obstack_free (&mips_operand_tokens,
3193                         obstack_finish (&mips_operand_tokens));
3194           return 0;
3195         }
3196       SKIP_SPACE_TABS (s);
3197     }
3198   mips_add_token (&token, OT_END);
3199   return (struct mips_operand_token *) obstack_finish (&mips_operand_tokens);
3200 }
3201
3202 /* Return TRUE if opcode MO is valid on the currently selected ISA, ASE
3203    and architecture.  Use is_opcode_valid_16 for MIPS16 opcodes.  */
3204
3205 static bfd_boolean
3206 is_opcode_valid (const struct mips_opcode *mo)
3207 {
3208   int isa = mips_opts.isa;
3209   int ase = mips_opts.ase;
3210   int fp_s, fp_d;
3211   unsigned int i;
3212
3213   if (ISA_HAS_64BIT_REGS (mips_opts.isa))
3214     for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
3215       if ((ase & mips_ases[i].flags) == mips_ases[i].flags)
3216         ase |= mips_ases[i].flags64;
3217
3218   if (!opcode_is_member (mo, isa, ase, mips_opts.arch))
3219     return FALSE;
3220
3221   /* Check whether the instruction or macro requires single-precision or
3222      double-precision floating-point support.  Note that this information is
3223      stored differently in the opcode table for insns and macros.  */
3224   if (mo->pinfo == INSN_MACRO)
3225     {
3226       fp_s = mo->pinfo2 & INSN2_M_FP_S;
3227       fp_d = mo->pinfo2 & INSN2_M_FP_D;
3228     }
3229   else
3230     {
3231       fp_s = mo->pinfo & FP_S;
3232       fp_d = mo->pinfo & FP_D;
3233     }
3234
3235   if (fp_d && (mips_opts.soft_float || mips_opts.single_float))
3236     return FALSE;
3237
3238   if (fp_s && mips_opts.soft_float)
3239     return FALSE;
3240
3241   return TRUE;
3242 }
3243
3244 /* Return TRUE if the MIPS16 opcode MO is valid on the currently
3245    selected ISA and architecture.  */
3246
3247 static bfd_boolean
3248 is_opcode_valid_16 (const struct mips_opcode *mo)
3249 {
3250   return opcode_is_member (mo, mips_opts.isa, 0, mips_opts.arch);
3251 }
3252
3253 /* Return TRUE if the size of the microMIPS opcode MO matches one
3254    explicitly requested.  Always TRUE in the standard MIPS mode.  */
3255
3256 static bfd_boolean
3257 is_size_valid (const struct mips_opcode *mo)
3258 {
3259   if (!mips_opts.micromips)
3260     return TRUE;
3261
3262   if (mips_opts.insn32)
3263     {
3264       if (mo->pinfo != INSN_MACRO && micromips_insn_length (mo) != 4)
3265         return FALSE;
3266       if ((mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0)
3267         return FALSE;
3268     }
3269   if (!forced_insn_length)
3270     return TRUE;
3271   if (mo->pinfo == INSN_MACRO)
3272     return FALSE;
3273   return forced_insn_length == micromips_insn_length (mo);
3274 }
3275
3276 /* Return TRUE if the microMIPS opcode MO is valid for the delay slot
3277    of the preceding instruction.  Always TRUE in the standard MIPS mode.
3278
3279    We don't accept macros in 16-bit delay slots to avoid a case where
3280    a macro expansion fails because it relies on a preceding 32-bit real
3281    instruction to have matched and does not handle the operands correctly.
3282    The only macros that may expand to 16-bit instructions are JAL that
3283    cannot be placed in a delay slot anyway, and corner cases of BALIGN
3284    and BGT (that likewise cannot be placed in a delay slot) that decay to
3285    a NOP.  In all these cases the macros precede any corresponding real
3286    instruction definitions in the opcode table, so they will match in the
3287    second pass where the size of the delay slot is ignored and therefore
3288    produce correct code.  */
3289
3290 static bfd_boolean
3291 is_delay_slot_valid (const struct mips_opcode *mo)
3292 {
3293   if (!mips_opts.micromips)
3294     return TRUE;
3295
3296   if (mo->pinfo == INSN_MACRO)
3297     return (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) == 0;
3298   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
3299       && micromips_insn_length (mo) != 4)
3300     return FALSE;
3301   if ((history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
3302       && micromips_insn_length (mo) != 2)
3303     return FALSE;
3304
3305   return TRUE;
3306 }
3307
3308 /* For consistency checking, verify that all bits of OPCODE are specified
3309    either by the match/mask part of the instruction definition, or by the
3310    operand list.  Also build up a list of operands in OPERANDS.
3311
3312    INSN_BITS says which bits of the instruction are significant.
3313    If OPCODE is a standard or microMIPS instruction, DECODE_OPERAND
3314    provides the mips_operand description of each operand.  DECODE_OPERAND
3315    is null for MIPS16 instructions.  */
3316
3317 static int
3318 validate_mips_insn (const struct mips_opcode *opcode,
3319                     unsigned long insn_bits,
3320                     const struct mips_operand *(*decode_operand) (const char *),
3321                     struct mips_operand_array *operands)
3322 {
3323   const char *s;
3324   unsigned long used_bits, doubled, undefined, opno, mask;
3325   const struct mips_operand *operand;
3326
3327   mask = (opcode->pinfo == INSN_MACRO ? 0 : opcode->mask);
3328   if ((mask & opcode->match) != opcode->match)
3329     {
3330       as_bad (_("internal: bad mips opcode (mask error): %s %s"),
3331               opcode->name, opcode->args);
3332       return 0;
3333     }
3334   used_bits = 0;
3335   opno = 0;
3336   if (opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX)
3337     used_bits = mips_insert_operand (&mips_vu0_channel_mask, used_bits, -1);
3338   for (s = opcode->args; *s; ++s)
3339     switch (*s)
3340       {
3341       case ',':
3342       case '(':
3343       case ')':
3344         break;
3345
3346       case '#':
3347         s++;
3348         break;
3349
3350       default:
3351         if (!decode_operand)
3352           operand = decode_mips16_operand (*s, FALSE);
3353         else
3354           operand = decode_operand (s);
3355         if (!operand && opcode->pinfo != INSN_MACRO)
3356           {
3357             as_bad (_("internal: unknown operand type: %s %s"),
3358                     opcode->name, opcode->args);
3359             return 0;
3360           }
3361         gas_assert (opno < MAX_OPERANDS);
3362         operands->operand[opno] = operand;
3363         if (operand && operand->type != OP_VU0_MATCH_SUFFIX)
3364           {
3365             used_bits = mips_insert_operand (operand, used_bits, -1);
3366             if (operand->type == OP_MDMX_IMM_REG)
3367               /* Bit 5 is the format selector (OB vs QH).  The opcode table
3368                  has separate entries for each format.  */
3369               used_bits &= ~(1 << (operand->lsb + 5));
3370             if (operand->type == OP_ENTRY_EXIT_LIST)
3371               used_bits &= ~(mask & 0x700);
3372           }
3373         /* Skip prefix characters.  */
3374         if (decode_operand && (*s == '+' || *s == 'm' || *s == '-'))
3375           ++s;
3376         opno += 1;
3377         break;
3378       }
3379   doubled = used_bits & mask & insn_bits;
3380   if (doubled)
3381     {
3382       as_bad (_("internal: bad mips opcode (bits 0x%08lx doubly defined):"
3383                 " %s %s"), doubled, opcode->name, opcode->args);
3384       return 0;
3385     }
3386   used_bits |= mask;
3387   undefined = ~used_bits & insn_bits;
3388   if (opcode->pinfo != INSN_MACRO && undefined)
3389     {
3390       as_bad (_("internal: bad mips opcode (bits 0x%08lx undefined): %s %s"),
3391               undefined, opcode->name, opcode->args);
3392       return 0;
3393     }
3394   used_bits &= ~insn_bits;
3395   if (used_bits)
3396     {
3397       as_bad (_("internal: bad mips opcode (bits 0x%08lx defined): %s %s"),
3398               used_bits, opcode->name, opcode->args);
3399       return 0;
3400     }
3401   return 1;
3402 }
3403
3404 /* The MIPS16 version of validate_mips_insn.  */
3405
3406 static int
3407 validate_mips16_insn (const struct mips_opcode *opcode,
3408                       struct mips_operand_array *operands)
3409 {
3410   if (opcode->args[0] == 'a' || opcode->args[0] == 'i')
3411     {
3412       /* In this case OPCODE defines the first 16 bits in a 32-bit jump
3413          instruction.  Use TMP to describe the full instruction.  */
3414       struct mips_opcode tmp;
3415
3416       tmp = *opcode;
3417       tmp.match <<= 16;
3418       tmp.mask <<= 16;
3419       return validate_mips_insn (&tmp, 0xffffffff, 0, operands);
3420     }
3421   return validate_mips_insn (opcode, 0xffff, 0, operands);
3422 }
3423
3424 /* The microMIPS version of validate_mips_insn.  */
3425
3426 static int
3427 validate_micromips_insn (const struct mips_opcode *opc,
3428                          struct mips_operand_array *operands)
3429 {
3430   unsigned long insn_bits;
3431   unsigned long major;
3432   unsigned int length;
3433
3434   if (opc->pinfo == INSN_MACRO)
3435     return validate_mips_insn (opc, 0xffffffff, decode_micromips_operand,
3436                                operands);
3437
3438   length = micromips_insn_length (opc);
3439   if (length != 2 && length != 4)
3440     {
3441       as_bad (_("internal error: bad microMIPS opcode (incorrect length: %u): "
3442                 "%s %s"), length, opc->name, opc->args);
3443       return 0;
3444     }
3445   major = opc->match >> (10 + 8 * (length - 2));
3446   if ((length == 2 && (major & 7) != 1 && (major & 6) != 2)
3447       || (length == 4 && (major & 7) != 0 && (major & 4) != 4))
3448     {
3449       as_bad (_("internal error: bad microMIPS opcode "
3450                 "(opcode/length mismatch): %s %s"), opc->name, opc->args);
3451       return 0;
3452     }
3453
3454   /* Shift piecewise to avoid an overflow where unsigned long is 32-bit.  */
3455   insn_bits = 1 << 4 * length;
3456   insn_bits <<= 4 * length;
3457   insn_bits -= 1;
3458   return validate_mips_insn (opc, insn_bits, decode_micromips_operand,
3459                              operands);
3460 }
3461
3462 /* This function is called once, at assembler startup time.  It should set up
3463    all the tables, etc. that the MD part of the assembler will need.  */
3464
3465 void
3466 md_begin (void)
3467 {
3468   const char *retval = NULL;
3469   int i = 0;
3470   int broken = 0;
3471
3472   if (mips_pic != NO_PIC)
3473     {
3474       if (g_switch_seen && g_switch_value != 0)
3475         as_bad (_("-G may not be used in position-independent code"));
3476       g_switch_value = 0;
3477     }
3478   else if (mips_abicalls)
3479     {
3480       if (g_switch_seen && g_switch_value != 0)
3481         as_bad (_("-G may not be used with abicalls"));
3482       g_switch_value = 0;
3483     }
3484
3485   if (! bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3486     as_warn (_("could not set architecture and machine"));
3487
3488   op_hash = hash_new ();
3489
3490   mips_operands = XCNEWVEC (struct mips_operand_array, NUMOPCODES);
3491   for (i = 0; i < NUMOPCODES;)
3492     {
3493       const char *name = mips_opcodes[i].name;
3494
3495       retval = hash_insert (op_hash, name, (void *) &mips_opcodes[i]);
3496       if (retval != NULL)
3497         {
3498           fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
3499                    mips_opcodes[i].name, retval);
3500           /* Probably a memory allocation problem?  Give up now.  */
3501           as_fatal (_("broken assembler, no assembly attempted"));
3502         }
3503       do
3504         {
3505           if (!validate_mips_insn (&mips_opcodes[i], 0xffffffff,
3506                                    decode_mips_operand, &mips_operands[i]))
3507             broken = 1;
3508           if (nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3509             {
3510               create_insn (&nop_insn, mips_opcodes + i);
3511               if (mips_fix_loongson2f_nop)
3512                 nop_insn.insn_opcode = LOONGSON2F_NOP_INSN;
3513               nop_insn.fixed_p = 1;
3514             }
3515           ++i;
3516         }
3517       while ((i < NUMOPCODES) && !strcmp (mips_opcodes[i].name, name));
3518     }
3519
3520   mips16_op_hash = hash_new ();
3521   mips16_operands = XCNEWVEC (struct mips_operand_array,
3522                               bfd_mips16_num_opcodes);
3523
3524   i = 0;
3525   while (i < bfd_mips16_num_opcodes)
3526     {
3527       const char *name = mips16_opcodes[i].name;
3528
3529       retval = hash_insert (mips16_op_hash, name, (void *) &mips16_opcodes[i]);
3530       if (retval != NULL)
3531         as_fatal (_("internal: can't hash `%s': %s"),
3532                   mips16_opcodes[i].name, retval);
3533       do
3534         {
3535           if (!validate_mips16_insn (&mips16_opcodes[i], &mips16_operands[i]))
3536             broken = 1;
3537           if (mips16_nop_insn.insn_mo == NULL && strcmp (name, "nop") == 0)
3538             {
3539               create_insn (&mips16_nop_insn, mips16_opcodes + i);
3540               mips16_nop_insn.fixed_p = 1;
3541             }
3542           ++i;
3543         }
3544       while (i < bfd_mips16_num_opcodes
3545              && strcmp (mips16_opcodes[i].name, name) == 0);
3546     }
3547
3548   micromips_op_hash = hash_new ();
3549   micromips_operands = XCNEWVEC (struct mips_operand_array,
3550                                  bfd_micromips_num_opcodes);
3551
3552   i = 0;
3553   while (i < bfd_micromips_num_opcodes)
3554     {
3555       const char *name = micromips_opcodes[i].name;
3556
3557       retval = hash_insert (micromips_op_hash, name,
3558                             (void *) &micromips_opcodes[i]);
3559       if (retval != NULL)
3560         as_fatal (_("internal: can't hash `%s': %s"),
3561                   micromips_opcodes[i].name, retval);
3562       do
3563         {
3564           struct mips_cl_insn *micromips_nop_insn;
3565
3566           if (!validate_micromips_insn (&micromips_opcodes[i],
3567                                         &micromips_operands[i]))
3568             broken = 1;
3569
3570           if (micromips_opcodes[i].pinfo != INSN_MACRO)
3571             {
3572               if (micromips_insn_length (micromips_opcodes + i) == 2)
3573                 micromips_nop_insn = &micromips_nop16_insn;
3574               else if (micromips_insn_length (micromips_opcodes + i) == 4)
3575                 micromips_nop_insn = &micromips_nop32_insn;
3576               else
3577                 continue;
3578
3579               if (micromips_nop_insn->insn_mo == NULL
3580                   && strcmp (name, "nop") == 0)
3581                 {
3582                   create_insn (micromips_nop_insn, micromips_opcodes + i);
3583                   micromips_nop_insn->fixed_p = 1;
3584                 }
3585             }
3586         }
3587       while (++i < bfd_micromips_num_opcodes
3588              && strcmp (micromips_opcodes[i].name, name) == 0);
3589     }
3590
3591   if (broken)
3592     as_fatal (_("broken assembler, no assembly attempted"));
3593
3594   /* We add all the general register names to the symbol table.  This
3595      helps us detect invalid uses of them.  */
3596   for (i = 0; reg_names[i].name; i++)
3597     symbol_table_insert (symbol_new (reg_names[i].name, reg_section,
3598                                      reg_names[i].num, /* & RNUM_MASK, */
3599                                      &zero_address_frag));
3600   if (HAVE_NEWABI)
3601     for (i = 0; reg_names_n32n64[i].name; i++)
3602       symbol_table_insert (symbol_new (reg_names_n32n64[i].name, reg_section,
3603                                        reg_names_n32n64[i].num, /* & RNUM_MASK, */
3604                                        &zero_address_frag));
3605   else
3606     for (i = 0; reg_names_o32[i].name; i++)
3607       symbol_table_insert (symbol_new (reg_names_o32[i].name, reg_section,
3608                                        reg_names_o32[i].num, /* & RNUM_MASK, */
3609                                        &zero_address_frag));
3610
3611   for (i = 0; i < 32; i++)
3612     {
3613       char regname[6];
3614
3615       /* R5900 VU0 floating-point register.  */
3616       sprintf (regname, "$vf%d", i);
3617       symbol_table_insert (symbol_new (regname, reg_section,
3618                                        RTYPE_VF | i, &zero_address_frag));
3619
3620       /* R5900 VU0 integer register.  */
3621       sprintf (regname, "$vi%d", i);
3622       symbol_table_insert (symbol_new (regname, reg_section,
3623                                        RTYPE_VI | i, &zero_address_frag));
3624
3625       /* MSA register.  */
3626       sprintf (regname, "$w%d", i);
3627       symbol_table_insert (symbol_new (regname, reg_section,
3628                                        RTYPE_MSA | i, &zero_address_frag));
3629     }
3630
3631   obstack_init (&mips_operand_tokens);
3632
3633   mips_no_prev_insn ();
3634
3635   mips_gprmask = 0;
3636   mips_cprmask[0] = 0;
3637   mips_cprmask[1] = 0;
3638   mips_cprmask[2] = 0;
3639   mips_cprmask[3] = 0;
3640
3641   /* set the default alignment for the text section (2**2) */
3642   record_alignment (text_section, 2);
3643
3644   bfd_set_gp_size (stdoutput, g_switch_value);
3645
3646   /* On a native system other than VxWorks, sections must be aligned
3647      to 16 byte boundaries.  When configured for an embedded ELF
3648      target, we don't bother.  */
3649   if (strncmp (TARGET_OS, "elf", 3) != 0
3650       && strncmp (TARGET_OS, "vxworks", 7) != 0)
3651     {
3652       (void) bfd_set_section_alignment (stdoutput, text_section, 4);
3653       (void) bfd_set_section_alignment (stdoutput, data_section, 4);
3654       (void) bfd_set_section_alignment (stdoutput, bss_section, 4);
3655     }
3656
3657   /* Create a .reginfo section for register masks and a .mdebug
3658      section for debugging information.  */
3659   {
3660     segT seg;
3661     subsegT subseg;
3662     flagword flags;
3663     segT sec;
3664
3665     seg = now_seg;
3666     subseg = now_subseg;
3667
3668     /* The ABI says this section should be loaded so that the
3669        running program can access it.  However, we don't load it
3670        if we are configured for an embedded target */
3671     flags = SEC_READONLY | SEC_DATA;
3672     if (strncmp (TARGET_OS, "elf", 3) != 0)
3673       flags |= SEC_ALLOC | SEC_LOAD;
3674
3675     if (mips_abi != N64_ABI)
3676       {
3677         sec = subseg_new (".reginfo", (subsegT) 0);
3678
3679         bfd_set_section_flags (stdoutput, sec, flags);
3680         bfd_set_section_alignment (stdoutput, sec, HAVE_NEWABI ? 3 : 2);
3681
3682         mips_regmask_frag = frag_more (sizeof (Elf32_External_RegInfo));
3683       }
3684     else
3685       {
3686         /* The 64-bit ABI uses a .MIPS.options section rather than
3687            .reginfo section.  */
3688         sec = subseg_new (".MIPS.options", (subsegT) 0);
3689         bfd_set_section_flags (stdoutput, sec, flags);
3690         bfd_set_section_alignment (stdoutput, sec, 3);
3691
3692         /* Set up the option header.  */
3693         {
3694           Elf_Internal_Options opthdr;
3695           char *f;
3696
3697           opthdr.kind = ODK_REGINFO;
3698           opthdr.size = (sizeof (Elf_External_Options)
3699                          + sizeof (Elf64_External_RegInfo));
3700           opthdr.section = 0;
3701           opthdr.info = 0;
3702           f = frag_more (sizeof (Elf_External_Options));
3703           bfd_mips_elf_swap_options_out (stdoutput, &opthdr,
3704                                          (Elf_External_Options *) f);
3705
3706           mips_regmask_frag = frag_more (sizeof (Elf64_External_RegInfo));
3707         }
3708       }
3709
3710     sec = subseg_new (".MIPS.abiflags", (subsegT) 0);
3711     bfd_set_section_flags (stdoutput, sec,
3712                            SEC_READONLY | SEC_DATA | SEC_ALLOC | SEC_LOAD);
3713     bfd_set_section_alignment (stdoutput, sec, 3);
3714     mips_flags_frag = frag_more (sizeof (Elf_External_ABIFlags_v0));
3715
3716     if (ECOFF_DEBUGGING)
3717       {
3718         sec = subseg_new (".mdebug", (subsegT) 0);
3719         (void) bfd_set_section_flags (stdoutput, sec,
3720                                       SEC_HAS_CONTENTS | SEC_READONLY);
3721         (void) bfd_set_section_alignment (stdoutput, sec, 2);
3722       }
3723     else if (mips_flag_pdr)
3724       {
3725         pdr_seg = subseg_new (".pdr", (subsegT) 0);
3726         (void) bfd_set_section_flags (stdoutput, pdr_seg,
3727                                       SEC_READONLY | SEC_RELOC
3728                                       | SEC_DEBUGGING);
3729         (void) bfd_set_section_alignment (stdoutput, pdr_seg, 2);
3730       }
3731
3732     subseg_set (seg, subseg);
3733   }
3734
3735   if (mips_fix_vr4120)
3736     init_vr4120_conflicts ();
3737 }
3738
3739 static inline void
3740 fpabi_incompatible_with (int fpabi, const char *what)
3741 {
3742   as_warn (_(".gnu_attribute %d,%d is incompatible with `%s'"),
3743            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3744 }
3745
3746 static inline void
3747 fpabi_requires (int fpabi, const char *what)
3748 {
3749   as_warn (_(".gnu_attribute %d,%d requires `%s'"),
3750            Tag_GNU_MIPS_ABI_FP, fpabi, what);
3751 }
3752
3753 /* Check -mabi and register sizes against the specified FP ABI.  */
3754 static void
3755 check_fpabi (int fpabi)
3756 {
3757   switch (fpabi)
3758     {
3759     case Val_GNU_MIPS_ABI_FP_DOUBLE:
3760       if (file_mips_opts.soft_float)
3761         fpabi_incompatible_with (fpabi, "softfloat");
3762       else if (file_mips_opts.single_float)
3763         fpabi_incompatible_with (fpabi, "singlefloat");
3764       if (file_mips_opts.gp == 64 && file_mips_opts.fp == 32)
3765         fpabi_incompatible_with (fpabi, "gp=64 fp=32");
3766       else if (file_mips_opts.gp == 32 && file_mips_opts.fp == 64)
3767         fpabi_incompatible_with (fpabi, "gp=32 fp=64");
3768       break;
3769
3770     case Val_GNU_MIPS_ABI_FP_XX:
3771       if (mips_abi != O32_ABI)
3772         fpabi_requires (fpabi, "-mabi=32");
3773       else if (file_mips_opts.soft_float)
3774         fpabi_incompatible_with (fpabi, "softfloat");
3775       else if (file_mips_opts.single_float)
3776         fpabi_incompatible_with (fpabi, "singlefloat");
3777       else if (file_mips_opts.fp != 0)
3778         fpabi_requires (fpabi, "fp=xx");
3779       break;
3780
3781     case Val_GNU_MIPS_ABI_FP_64A:
3782     case Val_GNU_MIPS_ABI_FP_64:
3783       if (mips_abi != O32_ABI)
3784         fpabi_requires (fpabi, "-mabi=32");
3785       else if (file_mips_opts.soft_float)
3786         fpabi_incompatible_with (fpabi, "softfloat");
3787       else if (file_mips_opts.single_float)
3788         fpabi_incompatible_with (fpabi, "singlefloat");
3789       else if (file_mips_opts.fp != 64)
3790         fpabi_requires (fpabi, "fp=64");
3791       else if (fpabi == Val_GNU_MIPS_ABI_FP_64 && !file_mips_opts.oddspreg)
3792         fpabi_incompatible_with (fpabi, "nooddspreg");
3793       else if (fpabi == Val_GNU_MIPS_ABI_FP_64A && file_mips_opts.oddspreg)
3794         fpabi_requires (fpabi, "nooddspreg");
3795       break;
3796
3797     case Val_GNU_MIPS_ABI_FP_SINGLE:
3798       if (file_mips_opts.soft_float)
3799         fpabi_incompatible_with (fpabi, "softfloat");
3800       else if (!file_mips_opts.single_float)
3801         fpabi_requires (fpabi, "singlefloat");
3802       break;
3803
3804     case Val_GNU_MIPS_ABI_FP_SOFT:
3805       if (!file_mips_opts.soft_float)
3806         fpabi_requires (fpabi, "softfloat");
3807       break;
3808
3809     case Val_GNU_MIPS_ABI_FP_OLD_64:
3810       as_warn (_(".gnu_attribute %d,%d is no longer supported"),
3811                Tag_GNU_MIPS_ABI_FP, fpabi);
3812       break;
3813
3814     case Val_GNU_MIPS_ABI_FP_NAN2008:
3815       /* Silently ignore compatibility value.  */
3816       break;
3817
3818     default:
3819       as_warn (_(".gnu_attribute %d,%d is not a recognized"
3820                  " floating-point ABI"), Tag_GNU_MIPS_ABI_FP, fpabi);
3821       break;
3822     }
3823 }
3824
3825 /* Perform consistency checks on the current options.  */
3826
3827 static void
3828 mips_check_options (struct mips_set_options *opts, bfd_boolean abi_checks)
3829 {
3830   /* Check the size of integer registers agrees with the ABI and ISA.  */
3831   if (opts->gp == 64 && !ISA_HAS_64BIT_REGS (opts->isa))
3832     as_bad (_("`gp=64' used with a 32-bit processor"));
3833   else if (abi_checks
3834            && opts->gp == 32 && ABI_NEEDS_64BIT_REGS (mips_abi))
3835     as_bad (_("`gp=32' used with a 64-bit ABI"));
3836   else if (abi_checks
3837            && opts->gp == 64 && ABI_NEEDS_32BIT_REGS (mips_abi))
3838     as_bad (_("`gp=64' used with a 32-bit ABI"));
3839
3840   /* Check the size of the float registers agrees with the ABI and ISA.  */
3841   switch (opts->fp)
3842     {
3843     case 0:
3844       if (!CPU_HAS_LDC1_SDC1 (opts->arch))
3845         as_bad (_("`fp=xx' used with a cpu lacking ldc1/sdc1 instructions"));
3846       else if (opts->single_float == 1)
3847         as_bad (_("`fp=xx' cannot be used with `singlefloat'"));
3848       break;
3849     case 64:
3850       if (!ISA_HAS_64BIT_FPRS (opts->isa))
3851         as_bad (_("`fp=64' used with a 32-bit fpu"));
3852       else if (abi_checks
3853                && ABI_NEEDS_32BIT_REGS (mips_abi)
3854                && !ISA_HAS_MXHC1 (opts->isa))
3855         as_warn (_("`fp=64' used with a 32-bit ABI"));
3856       break;
3857     case 32:
3858       if (abi_checks
3859           && ABI_NEEDS_64BIT_REGS (mips_abi))
3860         as_warn (_("`fp=32' used with a 64-bit ABI"));
3861       if (ISA_IS_R6 (opts->isa) && opts->single_float == 0)
3862         as_bad (_("`fp=32' used with a MIPS R6 cpu"));
3863       break;
3864     default:
3865       as_bad (_("Unknown size of floating point registers"));
3866       break;
3867     }
3868
3869   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !opts->oddspreg)
3870     as_bad (_("`nooddspreg` cannot be used with a 64-bit ABI"));
3871
3872   if (opts->micromips == 1 && opts->mips16 == 1)
3873     as_bad (_("`%s' cannot be used with `%s'"), "mips16", "micromips");
3874   else if (ISA_IS_R6 (opts->isa)
3875            && (opts->micromips == 1
3876                || opts->mips16 == 1))
3877     as_fatal (_("`%s' cannot be used with `%s'"),
3878               opts->micromips ? "micromips" : "mips16",
3879               mips_cpu_info_from_isa (opts->isa)->name);
3880
3881   if (ISA_IS_R6 (opts->isa) && mips_relax_branch)
3882     as_fatal (_("branch relaxation is not supported in `%s'"),
3883               mips_cpu_info_from_isa (opts->isa)->name);
3884 }
3885
3886 /* Perform consistency checks on the module level options exactly once.
3887    This is a deferred check that happens:
3888      at the first .set directive
3889      or, at the first pseudo op that generates code (inc .dc.a)
3890      or, at the first instruction
3891      or, at the end.  */
3892
3893 static void
3894 file_mips_check_options (void)
3895 {
3896   const struct mips_cpu_info *arch_info = 0;
3897
3898   if (file_mips_opts_checked)
3899     return;
3900
3901   /* The following code determines the register size.
3902      Similar code was added to GCC 3.3 (see override_options() in
3903      config/mips/mips.c).  The GAS and GCC code should be kept in sync
3904      as much as possible.  */
3905
3906   if (file_mips_opts.gp < 0)
3907     {
3908       /* Infer the integer register size from the ABI and processor.
3909          Restrict ourselves to 32-bit registers if that's all the
3910          processor has, or if the ABI cannot handle 64-bit registers.  */
3911       file_mips_opts.gp = (ABI_NEEDS_32BIT_REGS (mips_abi)
3912                            || !ISA_HAS_64BIT_REGS (file_mips_opts.isa))
3913                           ? 32 : 64;
3914     }
3915
3916   if (file_mips_opts.fp < 0)
3917     {
3918       /* No user specified float register size.
3919          ??? GAS treats single-float processors as though they had 64-bit
3920          float registers (although it complains when double-precision
3921          instructions are used).  As things stand, saying they have 32-bit
3922          registers would lead to spurious "register must be even" messages.
3923          So here we assume float registers are never smaller than the
3924          integer ones.  */
3925       if (file_mips_opts.gp == 64)
3926         /* 64-bit integer registers implies 64-bit float registers.  */
3927         file_mips_opts.fp = 64;
3928       else if ((file_mips_opts.ase & FP64_ASES)
3929                && ISA_HAS_64BIT_FPRS (file_mips_opts.isa))
3930         /* Handle ASEs that require 64-bit float registers, if possible.  */
3931         file_mips_opts.fp = 64;
3932       else if (ISA_IS_R6 (mips_opts.isa))
3933         /* R6 implies 64-bit float registers.  */
3934         file_mips_opts.fp = 64;
3935       else
3936         /* 32-bit float registers.  */
3937         file_mips_opts.fp = 32;
3938     }
3939
3940   arch_info = mips_cpu_info_from_arch (file_mips_opts.arch);
3941
3942   /* Disable operations on odd-numbered floating-point registers by default
3943      when using the FPXX ABI.  */
3944   if (file_mips_opts.oddspreg < 0)
3945     {
3946       if (file_mips_opts.fp == 0)
3947         file_mips_opts.oddspreg = 0;
3948       else
3949         file_mips_opts.oddspreg = 1;
3950     }
3951
3952   /* End of GCC-shared inference code.  */
3953
3954   /* This flag is set when we have a 64-bit capable CPU but use only
3955      32-bit wide registers.  Note that EABI does not use it.  */
3956   if (ISA_HAS_64BIT_REGS (file_mips_opts.isa)
3957       && ((mips_abi == NO_ABI && file_mips_opts.gp == 32)
3958           || mips_abi == O32_ABI))
3959     mips_32bitmode = 1;
3960
3961   if (file_mips_opts.isa == ISA_MIPS1 && mips_trap)
3962     as_bad (_("trap exception not supported at ISA 1"));
3963
3964   /* If the selected architecture includes support for ASEs, enable
3965      generation of code for them.  */
3966   if (file_mips_opts.mips16 == -1)
3967     file_mips_opts.mips16 = (CPU_HAS_MIPS16 (file_mips_opts.arch)) ? 1 : 0;
3968   if (file_mips_opts.micromips == -1)
3969     file_mips_opts.micromips = (CPU_HAS_MICROMIPS (file_mips_opts.arch))
3970                                 ? 1 : 0;
3971
3972   if (mips_nan2008 == -1)
3973     mips_nan2008 = (ISA_HAS_LEGACY_NAN (file_mips_opts.isa)) ? 0 : 1;
3974   else if (!ISA_HAS_LEGACY_NAN (file_mips_opts.isa) && mips_nan2008 == 0)
3975     as_fatal (_("`%s' does not support legacy NaN"),
3976               mips_cpu_info_from_arch (file_mips_opts.arch)->name);
3977
3978   /* Some ASEs require 64-bit FPRs, so -mfp32 should stop those ASEs from
3979      being selected implicitly.  */
3980   if (file_mips_opts.fp != 64)
3981     file_ase_explicit |= ASE_MIPS3D | ASE_MDMX | ASE_MSA;
3982
3983   /* If the user didn't explicitly select or deselect a particular ASE,
3984      use the default setting for the CPU.  */
3985   file_mips_opts.ase |= (arch_info->ase & ~file_ase_explicit);
3986
3987   /* Set up the current options.  These may change throughout assembly.  */
3988   mips_opts = file_mips_opts;
3989
3990   mips_check_isa_supports_ases ();
3991   mips_check_options (&file_mips_opts, TRUE);
3992   file_mips_opts_checked = TRUE;
3993
3994   if (!bfd_set_arch_mach (stdoutput, bfd_arch_mips, file_mips_opts.arch))
3995     as_warn (_("could not set architecture and machine"));
3996 }
3997
3998 void
3999 md_assemble (char *str)
4000 {
4001   struct mips_cl_insn insn;
4002   bfd_reloc_code_real_type unused_reloc[3]
4003     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
4004
4005   file_mips_check_options ();
4006
4007   imm_expr.X_op = O_absent;
4008   offset_expr.X_op = O_absent;
4009   offset_reloc[0] = BFD_RELOC_UNUSED;
4010   offset_reloc[1] = BFD_RELOC_UNUSED;
4011   offset_reloc[2] = BFD_RELOC_UNUSED;
4012
4013   mips_mark_labels ();
4014   mips_assembling_insn = TRUE;
4015   clear_insn_error ();
4016
4017   if (mips_opts.mips16)
4018     mips16_ip (str, &insn);
4019   else
4020     {
4021       mips_ip (str, &insn);
4022       DBG ((_("returned from mips_ip(%s) insn_opcode = 0x%x\n"),
4023             str, insn.insn_opcode));
4024     }
4025
4026   if (insn_error.msg)
4027     report_insn_error (str);
4028   else if (insn.insn_mo->pinfo == INSN_MACRO)
4029     {
4030       macro_start ();
4031       if (mips_opts.mips16)
4032         mips16_macro (&insn);
4033       else
4034         macro (&insn, str);
4035       macro_end ();
4036     }
4037   else
4038     {
4039       if (offset_expr.X_op != O_absent)
4040         append_insn (&insn, &offset_expr, offset_reloc, FALSE);
4041       else
4042         append_insn (&insn, NULL, unused_reloc, FALSE);
4043     }
4044
4045   mips_assembling_insn = FALSE;
4046 }
4047
4048 /* Convenience functions for abstracting away the differences between
4049    MIPS16 and non-MIPS16 relocations.  */
4050
4051 static inline bfd_boolean
4052 mips16_reloc_p (bfd_reloc_code_real_type reloc)
4053 {
4054   switch (reloc)
4055     {
4056     case BFD_RELOC_MIPS16_JMP:
4057     case BFD_RELOC_MIPS16_GPREL:
4058     case BFD_RELOC_MIPS16_GOT16:
4059     case BFD_RELOC_MIPS16_CALL16:
4060     case BFD_RELOC_MIPS16_HI16_S:
4061     case BFD_RELOC_MIPS16_HI16:
4062     case BFD_RELOC_MIPS16_LO16:
4063     case BFD_RELOC_MIPS16_16_PCREL_S1:
4064       return TRUE;
4065
4066     default:
4067       return FALSE;
4068     }
4069 }
4070
4071 static inline bfd_boolean
4072 micromips_reloc_p (bfd_reloc_code_real_type reloc)
4073 {
4074   switch (reloc)
4075     {
4076     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4077     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4078     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4079     case BFD_RELOC_MICROMIPS_GPREL16:
4080     case BFD_RELOC_MICROMIPS_JMP:
4081     case BFD_RELOC_MICROMIPS_HI16:
4082     case BFD_RELOC_MICROMIPS_HI16_S:
4083     case BFD_RELOC_MICROMIPS_LO16:
4084     case BFD_RELOC_MICROMIPS_LITERAL:
4085     case BFD_RELOC_MICROMIPS_GOT16:
4086     case BFD_RELOC_MICROMIPS_CALL16:
4087     case BFD_RELOC_MICROMIPS_GOT_HI16:
4088     case BFD_RELOC_MICROMIPS_GOT_LO16:
4089     case BFD_RELOC_MICROMIPS_CALL_HI16:
4090     case BFD_RELOC_MICROMIPS_CALL_LO16:
4091     case BFD_RELOC_MICROMIPS_SUB:
4092     case BFD_RELOC_MICROMIPS_GOT_PAGE:
4093     case BFD_RELOC_MICROMIPS_GOT_OFST:
4094     case BFD_RELOC_MICROMIPS_GOT_DISP:
4095     case BFD_RELOC_MICROMIPS_HIGHEST:
4096     case BFD_RELOC_MICROMIPS_HIGHER:
4097     case BFD_RELOC_MICROMIPS_SCN_DISP:
4098     case BFD_RELOC_MICROMIPS_JALR:
4099       return TRUE;
4100
4101     default:
4102       return FALSE;
4103     }
4104 }
4105
4106 static inline bfd_boolean
4107 jmp_reloc_p (bfd_reloc_code_real_type reloc)
4108 {
4109   return reloc == BFD_RELOC_MIPS_JMP || reloc == BFD_RELOC_MICROMIPS_JMP;
4110 }
4111
4112 static inline bfd_boolean
4113 b_reloc_p (bfd_reloc_code_real_type reloc)
4114 {
4115   return (reloc == BFD_RELOC_MIPS_26_PCREL_S2
4116           || reloc == BFD_RELOC_MIPS_21_PCREL_S2
4117           || reloc == BFD_RELOC_16_PCREL_S2
4118           || reloc == BFD_RELOC_MIPS16_16_PCREL_S1
4119           || reloc == BFD_RELOC_MICROMIPS_16_PCREL_S1
4120           || reloc == BFD_RELOC_MICROMIPS_10_PCREL_S1
4121           || reloc == BFD_RELOC_MICROMIPS_7_PCREL_S1);
4122 }
4123
4124 static inline bfd_boolean
4125 got16_reloc_p (bfd_reloc_code_real_type reloc)
4126 {
4127   return (reloc == BFD_RELOC_MIPS_GOT16 || reloc == BFD_RELOC_MIPS16_GOT16
4128           || reloc == BFD_RELOC_MICROMIPS_GOT16);
4129 }
4130
4131 static inline bfd_boolean
4132 hi16_reloc_p (bfd_reloc_code_real_type reloc)
4133 {
4134   return (reloc == BFD_RELOC_HI16_S || reloc == BFD_RELOC_MIPS16_HI16_S
4135           || reloc == BFD_RELOC_MICROMIPS_HI16_S);
4136 }
4137
4138 static inline bfd_boolean
4139 lo16_reloc_p (bfd_reloc_code_real_type reloc)
4140 {
4141   return (reloc == BFD_RELOC_LO16 || reloc == BFD_RELOC_MIPS16_LO16
4142           || reloc == BFD_RELOC_MICROMIPS_LO16);
4143 }
4144
4145 static inline bfd_boolean
4146 jalr_reloc_p (bfd_reloc_code_real_type reloc)
4147 {
4148   return reloc == BFD_RELOC_MIPS_JALR || reloc == BFD_RELOC_MICROMIPS_JALR;
4149 }
4150
4151 static inline bfd_boolean
4152 gprel16_reloc_p (bfd_reloc_code_real_type reloc)
4153 {
4154   return (reloc == BFD_RELOC_GPREL16 || reloc == BFD_RELOC_MIPS16_GPREL
4155           || reloc == BFD_RELOC_MICROMIPS_GPREL16);
4156 }
4157
4158 /* Return true if RELOC is a PC-relative relocation that does not have
4159    full address range.  */
4160
4161 static inline bfd_boolean
4162 limited_pcrel_reloc_p (bfd_reloc_code_real_type reloc)
4163 {
4164   switch (reloc)
4165     {
4166     case BFD_RELOC_16_PCREL_S2:
4167     case BFD_RELOC_MIPS16_16_PCREL_S1:
4168     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
4169     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
4170     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
4171     case BFD_RELOC_MIPS_21_PCREL_S2:
4172     case BFD_RELOC_MIPS_26_PCREL_S2:
4173     case BFD_RELOC_MIPS_18_PCREL_S3:
4174     case BFD_RELOC_MIPS_19_PCREL_S2:
4175       return TRUE;
4176
4177     case BFD_RELOC_32_PCREL:
4178     case BFD_RELOC_HI16_S_PCREL:
4179     case BFD_RELOC_LO16_PCREL:
4180       return HAVE_64BIT_ADDRESSES;
4181
4182     default:
4183       return FALSE;
4184     }
4185 }
4186
4187 /* Return true if the given relocation might need a matching %lo().
4188    This is only "might" because SVR4 R_MIPS_GOT16 relocations only
4189    need a matching %lo() when applied to local symbols.  */
4190
4191 static inline bfd_boolean
4192 reloc_needs_lo_p (bfd_reloc_code_real_type reloc)
4193 {
4194   return (HAVE_IN_PLACE_ADDENDS
4195           && (hi16_reloc_p (reloc)
4196               /* VxWorks R_MIPS_GOT16 relocs never need a matching %lo();
4197                  all GOT16 relocations evaluate to "G".  */
4198               || (got16_reloc_p (reloc) && mips_pic != VXWORKS_PIC)));
4199 }
4200
4201 /* Return the type of %lo() reloc needed by RELOC, given that
4202    reloc_needs_lo_p.  */
4203
4204 static inline bfd_reloc_code_real_type
4205 matching_lo_reloc (bfd_reloc_code_real_type reloc)
4206 {
4207   return (mips16_reloc_p (reloc) ? BFD_RELOC_MIPS16_LO16
4208           : (micromips_reloc_p (reloc) ? BFD_RELOC_MICROMIPS_LO16
4209              : BFD_RELOC_LO16));
4210 }
4211
4212 /* Return true if the given fixup is followed by a matching R_MIPS_LO16
4213    relocation.  */
4214
4215 static inline bfd_boolean
4216 fixup_has_matching_lo_p (fixS *fixp)
4217 {
4218   return (fixp->fx_next != NULL
4219           && fixp->fx_next->fx_r_type == matching_lo_reloc (fixp->fx_r_type)
4220           && fixp->fx_addsy == fixp->fx_next->fx_addsy
4221           && fixp->fx_offset == fixp->fx_next->fx_offset);
4222 }
4223
4224 /* Move all labels in LABELS to the current insertion point.  TEXT_P
4225    says whether the labels refer to text or data.  */
4226
4227 static void
4228 mips_move_labels (struct insn_label_list *labels, bfd_boolean text_p)
4229 {
4230   struct insn_label_list *l;
4231   valueT val;
4232
4233   for (l = labels; l != NULL; l = l->next)
4234     {
4235       gas_assert (S_GET_SEGMENT (l->label) == now_seg);
4236       symbol_set_frag (l->label, frag_now);
4237       val = (valueT) frag_now_fix ();
4238       /* MIPS16/microMIPS text labels are stored as odd.  */
4239       if (text_p && HAVE_CODE_COMPRESSION)
4240         ++val;
4241       S_SET_VALUE (l->label, val);
4242     }
4243 }
4244
4245 /* Move all labels in insn_labels to the current insertion point
4246    and treat them as text labels.  */
4247
4248 static void
4249 mips_move_text_labels (void)
4250 {
4251   mips_move_labels (seg_info (now_seg)->label_list, TRUE);
4252 }
4253
4254 static bfd_boolean
4255 s_is_linkonce (symbolS *sym, segT from_seg)
4256 {
4257   bfd_boolean linkonce = FALSE;
4258   segT symseg = S_GET_SEGMENT (sym);
4259
4260   if (symseg != from_seg && !S_IS_LOCAL (sym))
4261     {
4262       if ((bfd_get_section_flags (stdoutput, symseg) & SEC_LINK_ONCE))
4263         linkonce = TRUE;
4264       /* The GNU toolchain uses an extension for ELF: a section
4265          beginning with the magic string .gnu.linkonce is a
4266          linkonce section.  */
4267       if (strncmp (segment_name (symseg), ".gnu.linkonce",
4268                    sizeof ".gnu.linkonce" - 1) == 0)
4269         linkonce = TRUE;
4270     }
4271   return linkonce;
4272 }
4273
4274 /* Mark MIPS16 or microMIPS instruction label LABEL.  This permits the
4275    linker to handle them specially, such as generating jalx instructions
4276    when needed.  We also make them odd for the duration of the assembly,
4277    in order to generate the right sort of code.  We will make them even
4278    in the adjust_symtab routine, while leaving them marked.  This is
4279    convenient for the debugger and the disassembler.  The linker knows
4280    to make them odd again.  */
4281
4282 static void
4283 mips_compressed_mark_label (symbolS *label)
4284 {
4285   gas_assert (HAVE_CODE_COMPRESSION);
4286
4287   if (mips_opts.mips16)
4288     S_SET_OTHER (label, ELF_ST_SET_MIPS16 (S_GET_OTHER (label)));
4289   else
4290     S_SET_OTHER (label, ELF_ST_SET_MICROMIPS (S_GET_OTHER (label)));
4291   if ((S_GET_VALUE (label) & 1) == 0
4292       /* Don't adjust the address if the label is global or weak, or
4293          in a link-once section, since we'll be emitting symbol reloc
4294          references to it which will be patched up by the linker, and
4295          the final value of the symbol may or may not be MIPS16/microMIPS.  */
4296       && !S_IS_WEAK (label)
4297       && !S_IS_EXTERNAL (label)
4298       && !s_is_linkonce (label, now_seg))
4299     S_SET_VALUE (label, S_GET_VALUE (label) | 1);
4300 }
4301
4302 /* Mark preceding MIPS16 or microMIPS instruction labels.  */
4303
4304 static void
4305 mips_compressed_mark_labels (void)
4306 {
4307   struct insn_label_list *l;
4308
4309   for (l = seg_info (now_seg)->label_list; l != NULL; l = l->next)
4310     mips_compressed_mark_label (l->label);
4311 }
4312
4313 /* End the current frag.  Make it a variant frag and record the
4314    relaxation info.  */
4315
4316 static void
4317 relax_close_frag (void)
4318 {
4319   mips_macro_warning.first_frag = frag_now;
4320   frag_var (rs_machine_dependent, 0, 0,
4321             RELAX_ENCODE (mips_relax.sizes[0], mips_relax.sizes[1]),
4322             mips_relax.symbol, 0, (char *) mips_relax.first_fixup);
4323
4324   memset (&mips_relax.sizes, 0, sizeof (mips_relax.sizes));
4325   mips_relax.first_fixup = 0;
4326 }
4327
4328 /* Start a new relaxation sequence whose expansion depends on SYMBOL.
4329    See the comment above RELAX_ENCODE for more details.  */
4330
4331 static void
4332 relax_start (symbolS *symbol)
4333 {
4334   gas_assert (mips_relax.sequence == 0);
4335   mips_relax.sequence = 1;
4336   mips_relax.symbol = symbol;
4337 }
4338
4339 /* Start generating the second version of a relaxable sequence.
4340    See the comment above RELAX_ENCODE for more details.  */
4341
4342 static void
4343 relax_switch (void)
4344 {
4345   gas_assert (mips_relax.sequence == 1);
4346   mips_relax.sequence = 2;
4347 }
4348
4349 /* End the current relaxable sequence.  */
4350
4351 static void
4352 relax_end (void)
4353 {
4354   gas_assert (mips_relax.sequence == 2);
4355   relax_close_frag ();
4356   mips_relax.sequence = 0;
4357 }
4358
4359 /* Return true if IP is a delayed branch or jump.  */
4360
4361 static inline bfd_boolean
4362 delayed_branch_p (const struct mips_cl_insn *ip)
4363 {
4364   return (ip->insn_mo->pinfo & (INSN_UNCOND_BRANCH_DELAY
4365                                 | INSN_COND_BRANCH_DELAY
4366                                 | INSN_COND_BRANCH_LIKELY)) != 0;
4367 }
4368
4369 /* Return true if IP is a compact branch or jump.  */
4370
4371 static inline bfd_boolean
4372 compact_branch_p (const struct mips_cl_insn *ip)
4373 {
4374   return (ip->insn_mo->pinfo2 & (INSN2_UNCOND_BRANCH
4375                                  | INSN2_COND_BRANCH)) != 0;
4376 }
4377
4378 /* Return true if IP is an unconditional branch or jump.  */
4379
4380 static inline bfd_boolean
4381 uncond_branch_p (const struct mips_cl_insn *ip)
4382 {
4383   return ((ip->insn_mo->pinfo & INSN_UNCOND_BRANCH_DELAY) != 0
4384           || (ip->insn_mo->pinfo2 & INSN2_UNCOND_BRANCH) != 0);
4385 }
4386
4387 /* Return true if IP is a branch-likely instruction.  */
4388
4389 static inline bfd_boolean
4390 branch_likely_p (const struct mips_cl_insn *ip)
4391 {
4392   return (ip->insn_mo->pinfo & INSN_COND_BRANCH_LIKELY) != 0;
4393 }
4394
4395 /* Return the type of nop that should be used to fill the delay slot
4396    of delayed branch IP.  */
4397
4398 static struct mips_cl_insn *
4399 get_delay_slot_nop (const struct mips_cl_insn *ip)
4400 {
4401   if (mips_opts.micromips
4402       && (ip->insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
4403     return &micromips_nop32_insn;
4404   return NOP_INSN;
4405 }
4406
4407 /* Return a mask that has bit N set if OPCODE reads the register(s)
4408    in operand N.  */
4409
4410 static unsigned int
4411 insn_read_mask (const struct mips_opcode *opcode)
4412 {
4413   return (opcode->pinfo & INSN_READ_ALL) >> INSN_READ_SHIFT;
4414 }
4415
4416 /* Return a mask that has bit N set if OPCODE writes to the register(s)
4417    in operand N.  */
4418
4419 static unsigned int
4420 insn_write_mask (const struct mips_opcode *opcode)
4421 {
4422   return (opcode->pinfo & INSN_WRITE_ALL) >> INSN_WRITE_SHIFT;
4423 }
4424
4425 /* Return a mask of the registers specified by operand OPERAND of INSN.
4426    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4427    is set.  */
4428
4429 static unsigned int
4430 operand_reg_mask (const struct mips_cl_insn *insn,
4431                   const struct mips_operand *operand,
4432                   unsigned int type_mask)
4433 {
4434   unsigned int uval, vsel;
4435
4436   switch (operand->type)
4437     {
4438     case OP_INT:
4439     case OP_MAPPED_INT:
4440     case OP_MSB:
4441     case OP_PCREL:
4442     case OP_PERF_REG:
4443     case OP_ADDIUSP_INT:
4444     case OP_ENTRY_EXIT_LIST:
4445     case OP_REPEAT_DEST_REG:
4446     case OP_REPEAT_PREV_REG:
4447     case OP_PC:
4448     case OP_VU0_SUFFIX:
4449     case OP_VU0_MATCH_SUFFIX:
4450     case OP_IMM_INDEX:
4451       abort ();
4452
4453     case OP_REG:
4454     case OP_OPTIONAL_REG:
4455       {
4456         const struct mips_reg_operand *reg_op;
4457
4458         reg_op = (const struct mips_reg_operand *) operand;
4459         if (!(type_mask & (1 << reg_op->reg_type)))
4460           return 0;
4461         uval = insn_extract_operand (insn, operand);
4462         return 1 << mips_decode_reg_operand (reg_op, uval);
4463       }
4464
4465     case OP_REG_PAIR:
4466       {
4467         const struct mips_reg_pair_operand *pair_op;
4468
4469         pair_op = (const struct mips_reg_pair_operand *) operand;
4470         if (!(type_mask & (1 << pair_op->reg_type)))
4471           return 0;
4472         uval = insn_extract_operand (insn, operand);
4473         return (1 << pair_op->reg1_map[uval]) | (1 << pair_op->reg2_map[uval]);
4474       }
4475
4476     case OP_CLO_CLZ_DEST:
4477       if (!(type_mask & (1 << OP_REG_GP)))
4478         return 0;
4479       uval = insn_extract_operand (insn, operand);
4480       return (1 << (uval & 31)) | (1 << (uval >> 5));
4481
4482     case OP_SAME_RS_RT:
4483       if (!(type_mask & (1 << OP_REG_GP)))
4484         return 0;
4485       uval = insn_extract_operand (insn, operand);
4486       gas_assert ((uval & 31) == (uval >> 5));
4487       return 1 << (uval & 31);
4488
4489     case OP_CHECK_PREV:
4490     case OP_NON_ZERO_REG:
4491       if (!(type_mask & (1 << OP_REG_GP)))
4492         return 0;
4493       uval = insn_extract_operand (insn, operand);
4494       return 1 << (uval & 31);
4495
4496     case OP_LWM_SWM_LIST:
4497       abort ();
4498
4499     case OP_SAVE_RESTORE_LIST:
4500       abort ();
4501
4502     case OP_MDMX_IMM_REG:
4503       if (!(type_mask & (1 << OP_REG_VEC)))
4504         return 0;
4505       uval = insn_extract_operand (insn, operand);
4506       vsel = uval >> 5;
4507       if ((vsel & 0x18) == 0x18)
4508         return 0;
4509       return 1 << (uval & 31);
4510
4511     case OP_REG_INDEX:
4512       if (!(type_mask & (1 << OP_REG_GP)))
4513         return 0;
4514       return 1 << insn_extract_operand (insn, operand);
4515     }
4516   abort ();
4517 }
4518
4519 /* Return a mask of the registers specified by operands OPNO_MASK of INSN,
4520    where bit N of OPNO_MASK is set if operand N should be included.
4521    Ignore registers of type OP_REG_<t> unless bit OP_REG_<t> of TYPE_MASK
4522    is set.  */
4523
4524 static unsigned int
4525 insn_reg_mask (const struct mips_cl_insn *insn,
4526                unsigned int type_mask, unsigned int opno_mask)
4527 {
4528   unsigned int opno, reg_mask;
4529
4530   opno = 0;
4531   reg_mask = 0;
4532   while (opno_mask != 0)
4533     {
4534       if (opno_mask & 1)
4535         reg_mask |= operand_reg_mask (insn, insn_opno (insn, opno), type_mask);
4536       opno_mask >>= 1;
4537       opno += 1;
4538     }
4539   return reg_mask;
4540 }
4541
4542 /* Return the mask of core registers that IP reads.  */
4543
4544 static unsigned int
4545 gpr_read_mask (const struct mips_cl_insn *ip)
4546 {
4547   unsigned long pinfo, pinfo2;
4548   unsigned int mask;
4549
4550   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_read_mask (ip->insn_mo));
4551   pinfo = ip->insn_mo->pinfo;
4552   pinfo2 = ip->insn_mo->pinfo2;
4553   if (pinfo & INSN_UDI)
4554     {
4555       /* UDI instructions have traditionally been assumed to read RS
4556          and RT.  */
4557       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RT, *ip);
4558       mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RS, *ip);
4559     }
4560   if (pinfo & INSN_READ_GPR_24)
4561     mask |= 1 << 24;
4562   if (pinfo2 & INSN2_READ_GPR_16)
4563     mask |= 1 << 16;
4564   if (pinfo2 & INSN2_READ_SP)
4565     mask |= 1 << SP;
4566   if (pinfo2 & INSN2_READ_GPR_31)
4567     mask |= 1 << 31;
4568   /* Don't include register 0.  */
4569   return mask & ~1;
4570 }
4571
4572 /* Return the mask of core registers that IP writes.  */
4573
4574 static unsigned int
4575 gpr_write_mask (const struct mips_cl_insn *ip)
4576 {
4577   unsigned long pinfo, pinfo2;
4578   unsigned int mask;
4579
4580   mask = insn_reg_mask (ip, 1 << OP_REG_GP, insn_write_mask (ip->insn_mo));
4581   pinfo = ip->insn_mo->pinfo;
4582   pinfo2 = ip->insn_mo->pinfo2;
4583   if (pinfo & INSN_WRITE_GPR_24)
4584     mask |= 1 << 24;
4585   if (pinfo & INSN_WRITE_GPR_31)
4586     mask |= 1 << 31;
4587   if (pinfo & INSN_UDI)
4588     /* UDI instructions have traditionally been assumed to write to RD.  */
4589     mask |= 1 << EXTRACT_OPERAND (mips_opts.micromips, RD, *ip);
4590   if (pinfo2 & INSN2_WRITE_SP)
4591     mask |= 1 << SP;
4592   /* Don't include register 0.  */
4593   return mask & ~1;
4594 }
4595
4596 /* Return the mask of floating-point registers that IP reads.  */
4597
4598 static unsigned int
4599 fpr_read_mask (const struct mips_cl_insn *ip)
4600 {
4601   unsigned long pinfo;
4602   unsigned int mask;
4603
4604   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4605                              | (1 << OP_REG_MSA)),
4606                         insn_read_mask (ip->insn_mo));
4607   pinfo = ip->insn_mo->pinfo;
4608   /* Conservatively treat all operands to an FP_D instruction are doubles.
4609      (This is overly pessimistic for things like cvt.d.s.)  */
4610   if (FPR_SIZE != 64 && (pinfo & FP_D))
4611     mask |= mask << 1;
4612   return mask;
4613 }
4614
4615 /* Return the mask of floating-point registers that IP writes.  */
4616
4617 static unsigned int
4618 fpr_write_mask (const struct mips_cl_insn *ip)
4619 {
4620   unsigned long pinfo;
4621   unsigned int mask;
4622
4623   mask = insn_reg_mask (ip, ((1 << OP_REG_FP) | (1 << OP_REG_VEC)
4624                              | (1 << OP_REG_MSA)),
4625                         insn_write_mask (ip->insn_mo));
4626   pinfo = ip->insn_mo->pinfo;
4627   /* Conservatively treat all operands to an FP_D instruction are doubles.
4628      (This is overly pessimistic for things like cvt.s.d.)  */
4629   if (FPR_SIZE != 64 && (pinfo & FP_D))
4630     mask |= mask << 1;
4631   return mask;
4632 }
4633
4634 /* Operand OPNUM of INSN is an odd-numbered floating-point register.
4635    Check whether that is allowed.  */
4636
4637 static bfd_boolean
4638 mips_oddfpreg_ok (const struct mips_opcode *insn, int opnum)
4639 {
4640   const char *s = insn->name;
4641   bfd_boolean oddspreg = (ISA_HAS_ODD_SINGLE_FPR (mips_opts.isa, mips_opts.arch)
4642                           || FPR_SIZE == 64)
4643                          && mips_opts.oddspreg;
4644
4645   if (insn->pinfo == INSN_MACRO)
4646     /* Let a macro pass, we'll catch it later when it is expanded.  */
4647     return TRUE;
4648
4649   /* Single-precision coprocessor loads and moves are OK for 32-bit registers,
4650      otherwise it depends on oddspreg.  */
4651   if ((insn->pinfo & FP_S)
4652       && (insn->pinfo & (INSN_LOAD_MEMORY | INSN_STORE_MEMORY
4653                          | INSN_LOAD_COPROC | INSN_COPROC_MOVE)))
4654     return FPR_SIZE == 32 || oddspreg;
4655
4656   /* Allow odd registers for single-precision ops and double-precision if the
4657      floating-point registers are 64-bit wide.  */
4658   switch (insn->pinfo & (FP_S | FP_D))
4659     {
4660     case FP_S:
4661     case 0:
4662       return oddspreg;
4663     case FP_D:
4664       return FPR_SIZE == 64;
4665     default:
4666       break;
4667     }
4668
4669   /* Cvt.w.x and cvt.x.w allow an odd register for a 'w' or 's' operand.  */
4670   s = strchr (insn->name, '.');
4671   if (s != NULL && opnum == 2)
4672     s = strchr (s + 1, '.');
4673   if (s != NULL && (s[1] == 'w' || s[1] == 's'))
4674     return oddspreg;
4675
4676   return FPR_SIZE == 64;
4677 }
4678
4679 /* Information about an instruction argument that we're trying to match.  */
4680 struct mips_arg_info
4681 {
4682   /* The instruction so far.  */
4683   struct mips_cl_insn *insn;
4684
4685   /* The first unconsumed operand token.  */
4686   struct mips_operand_token *token;
4687
4688   /* The 1-based operand number, in terms of insn->insn_mo->args.  */
4689   int opnum;
4690
4691   /* The 1-based argument number, for error reporting.  This does not
4692      count elided optional registers, etc..  */
4693   int argnum;
4694
4695   /* The last OP_REG operand seen, or ILLEGAL_REG if none.  */
4696   unsigned int last_regno;
4697
4698   /* If the first operand was an OP_REG, this is the register that it
4699      specified, otherwise it is ILLEGAL_REG.  */
4700   unsigned int dest_regno;
4701
4702   /* The value of the last OP_INT operand.  Only used for OP_MSB,
4703      where it gives the lsb position.  */
4704   unsigned int last_op_int;
4705
4706   /* If true, match routines should assume that no later instruction
4707      alternative matches and should therefore be as accomodating as
4708      possible.  Match routines should not report errors if something
4709      is only invalid for !LAX_MATCH.  */
4710   bfd_boolean lax_match;
4711
4712   /* True if a reference to the current AT register was seen.  */
4713   bfd_boolean seen_at;
4714 };
4715
4716 /* Record that the argument is out of range.  */
4717
4718 static void
4719 match_out_of_range (struct mips_arg_info *arg)
4720 {
4721   set_insn_error_i (arg->argnum, _("operand %d out of range"), arg->argnum);
4722 }
4723
4724 /* Record that the argument isn't constant but needs to be.  */
4725
4726 static void
4727 match_not_constant (struct mips_arg_info *arg)
4728 {
4729   set_insn_error_i (arg->argnum, _("operand %d must be constant"),
4730                     arg->argnum);
4731 }
4732
4733 /* Try to match an OT_CHAR token for character CH.  Consume the token
4734    and return true on success, otherwise return false.  */
4735
4736 static bfd_boolean
4737 match_char (struct mips_arg_info *arg, char ch)
4738 {
4739   if (arg->token->type == OT_CHAR && arg->token->u.ch == ch)
4740     {
4741       ++arg->token;
4742       if (ch == ',')
4743         arg->argnum += 1;
4744       return TRUE;
4745     }
4746   return FALSE;
4747 }
4748
4749 /* Try to get an expression from the next tokens in ARG.  Consume the
4750    tokens and return true on success, storing the expression value in
4751    VALUE and relocation types in R.  */
4752
4753 static bfd_boolean
4754 match_expression (struct mips_arg_info *arg, expressionS *value,
4755                   bfd_reloc_code_real_type *r)
4756 {
4757   /* If the next token is a '(' that was parsed as being part of a base
4758      expression, assume we have an elided offset.  The later match will fail
4759      if this turns out to be wrong.  */
4760   if (arg->token->type == OT_CHAR && arg->token->u.ch == '(')
4761     {
4762       value->X_op = O_constant;
4763       value->X_add_number = 0;
4764       r[0] = r[1] = r[2] = BFD_RELOC_UNUSED;
4765       return TRUE;
4766     }
4767
4768   /* Reject register-based expressions such as "0+$2" and "(($2))".
4769      For plain registers the default error seems more appropriate.  */
4770   if (arg->token->type == OT_INTEGER
4771       && arg->token->u.integer.value.X_op == O_register)
4772     {
4773       set_insn_error (arg->argnum, _("register value used as expression"));
4774       return FALSE;
4775     }
4776
4777   if (arg->token->type == OT_INTEGER)
4778     {
4779       *value = arg->token->u.integer.value;
4780       memcpy (r, arg->token->u.integer.relocs, 3 * sizeof (*r));
4781       ++arg->token;
4782       return TRUE;
4783     }
4784
4785   set_insn_error_i
4786     (arg->argnum, _("operand %d must be an immediate expression"),
4787      arg->argnum);
4788   return FALSE;
4789 }
4790
4791 /* Try to get a constant expression from the next tokens in ARG.  Consume
4792    the tokens and return return true on success, storing the constant value
4793    in *VALUE.  Use FALLBACK as the value if the match succeeded with an
4794    error.  */
4795
4796 static bfd_boolean
4797 match_const_int (struct mips_arg_info *arg, offsetT *value)
4798 {
4799   expressionS ex;
4800   bfd_reloc_code_real_type r[3];
4801
4802   if (!match_expression (arg, &ex, r))
4803     return FALSE;
4804
4805   if (r[0] == BFD_RELOC_UNUSED && ex.X_op == O_constant)
4806     *value = ex.X_add_number;
4807   else
4808     {
4809       match_not_constant (arg);
4810       return FALSE;
4811     }
4812   return TRUE;
4813 }
4814
4815 /* Return the RTYPE_* flags for a register operand of type TYPE that
4816    appears in instruction OPCODE.  */
4817
4818 static unsigned int
4819 convert_reg_type (const struct mips_opcode *opcode,
4820                   enum mips_reg_operand_type type)
4821 {
4822   switch (type)
4823     {
4824     case OP_REG_GP:
4825       return RTYPE_NUM | RTYPE_GP;
4826
4827     case OP_REG_FP:
4828       /* Allow vector register names for MDMX if the instruction is a 64-bit
4829          FPR load, store or move (including moves to and from GPRs).  */
4830       if ((mips_opts.ase & ASE_MDMX)
4831           && (opcode->pinfo & FP_D)
4832           && (opcode->pinfo & (INSN_COPROC_MOVE
4833                                | INSN_COPROC_MEMORY_DELAY
4834                                | INSN_LOAD_COPROC
4835                                | INSN_LOAD_MEMORY
4836                                | INSN_STORE_MEMORY)))
4837         return RTYPE_FPU | RTYPE_VEC;
4838       return RTYPE_FPU;
4839
4840     case OP_REG_CCC:
4841       if (opcode->pinfo & (FP_D | FP_S))
4842         return RTYPE_CCC | RTYPE_FCC;
4843       return RTYPE_CCC;
4844
4845     case OP_REG_VEC:
4846       if (opcode->membership & INSN_5400)
4847         return RTYPE_FPU;
4848       return RTYPE_FPU | RTYPE_VEC;
4849
4850     case OP_REG_ACC:
4851       return RTYPE_ACC;
4852
4853     case OP_REG_COPRO:
4854       if (opcode->name[strlen (opcode->name) - 1] == '0')
4855         return RTYPE_NUM | RTYPE_CP0;
4856       return RTYPE_NUM;
4857
4858     case OP_REG_HW:
4859       return RTYPE_NUM;
4860
4861     case OP_REG_VI:
4862       return RTYPE_NUM | RTYPE_VI;
4863
4864     case OP_REG_VF:
4865       return RTYPE_NUM | RTYPE_VF;
4866
4867     case OP_REG_R5900_I:
4868       return RTYPE_R5900_I;
4869
4870     case OP_REG_R5900_Q:
4871       return RTYPE_R5900_Q;
4872
4873     case OP_REG_R5900_R:
4874       return RTYPE_R5900_R;
4875
4876     case OP_REG_R5900_ACC:
4877       return RTYPE_R5900_ACC;
4878
4879     case OP_REG_MSA:
4880       return RTYPE_MSA;
4881
4882     case OP_REG_MSA_CTRL:
4883       return RTYPE_NUM;
4884     }
4885   abort ();
4886 }
4887
4888 /* ARG is register REGNO, of type TYPE.  Warn about any dubious registers.  */
4889
4890 static void
4891 check_regno (struct mips_arg_info *arg,
4892              enum mips_reg_operand_type type, unsigned int regno)
4893 {
4894   if (AT && type == OP_REG_GP && regno == AT)
4895     arg->seen_at = TRUE;
4896
4897   if (type == OP_REG_FP
4898       && (regno & 1) != 0
4899       && !mips_oddfpreg_ok (arg->insn->insn_mo, arg->opnum))
4900     {
4901       /* This was a warning prior to introducing O32 FPXX and FP64 support
4902          so maintain a warning for FP32 but raise an error for the new
4903          cases.  */
4904       if (FPR_SIZE == 32)
4905         as_warn (_("float register should be even, was %d"), regno);
4906       else
4907         as_bad (_("float register should be even, was %d"), regno);
4908     }
4909
4910   if (type == OP_REG_CCC)
4911     {
4912       const char *name;
4913       size_t length;
4914
4915       name = arg->insn->insn_mo->name;
4916       length = strlen (name);
4917       if ((regno & 1) != 0
4918           && ((length >= 3 && strcmp (name + length - 3, ".ps") == 0)
4919               || (length >= 5 && strncmp (name + length - 5, "any2", 4) == 0)))
4920         as_warn (_("condition code register should be even for %s, was %d"),
4921                  name, regno);
4922
4923       if ((regno & 3) != 0
4924           && (length >= 5 && strncmp (name + length - 5, "any4", 4) == 0))
4925         as_warn (_("condition code register should be 0 or 4 for %s, was %d"),
4926                  name, regno);
4927     }
4928 }
4929
4930 /* ARG is a register with symbol value SYMVAL.  Try to interpret it as
4931    a register of type TYPE.  Return true on success, storing the register
4932    number in *REGNO and warning about any dubious uses.  */
4933
4934 static bfd_boolean
4935 match_regno (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4936              unsigned int symval, unsigned int *regno)
4937 {
4938   if (type == OP_REG_VEC)
4939     symval = mips_prefer_vec_regno (symval);
4940   if (!(symval & convert_reg_type (arg->insn->insn_mo, type)))
4941     return FALSE;
4942
4943   *regno = symval & RNUM_MASK;
4944   check_regno (arg, type, *regno);
4945   return TRUE;
4946 }
4947
4948 /* Try to interpret the next token in ARG as a register of type TYPE.
4949    Consume the token and return true on success, storing the register
4950    number in *REGNO.  Return false on failure.  */
4951
4952 static bfd_boolean
4953 match_reg (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4954            unsigned int *regno)
4955 {
4956   if (arg->token->type == OT_REG
4957       && match_regno (arg, type, arg->token->u.regno, regno))
4958     {
4959       ++arg->token;
4960       return TRUE;
4961     }
4962   return FALSE;
4963 }
4964
4965 /* Try to interpret the next token in ARG as a range of registers of type TYPE.
4966    Consume the token and return true on success, storing the register numbers
4967    in *REGNO1 and *REGNO2.  Return false on failure.  */
4968
4969 static bfd_boolean
4970 match_reg_range (struct mips_arg_info *arg, enum mips_reg_operand_type type,
4971                  unsigned int *regno1, unsigned int *regno2)
4972 {
4973   if (match_reg (arg, type, regno1))
4974     {
4975       *regno2 = *regno1;
4976       return TRUE;
4977     }
4978   if (arg->token->type == OT_REG_RANGE
4979       && match_regno (arg, type, arg->token->u.reg_range.regno1, regno1)
4980       && match_regno (arg, type, arg->token->u.reg_range.regno2, regno2)
4981       && *regno1 <= *regno2)
4982     {
4983       ++arg->token;
4984       return TRUE;
4985     }
4986   return FALSE;
4987 }
4988
4989 /* OP_INT matcher.  */
4990
4991 static bfd_boolean
4992 match_int_operand (struct mips_arg_info *arg,
4993                    const struct mips_operand *operand_base)
4994 {
4995   const struct mips_int_operand *operand;
4996   unsigned int uval;
4997   int min_val, max_val, factor;
4998   offsetT sval;
4999
5000   operand = (const struct mips_int_operand *) operand_base;
5001   factor = 1 << operand->shift;
5002   min_val = mips_int_operand_min (operand);
5003   max_val = mips_int_operand_max (operand);
5004
5005   if (operand_base->lsb == 0
5006       && operand_base->size == 16
5007       && operand->shift == 0
5008       && operand->bias == 0
5009       && (operand->max_val == 32767 || operand->max_val == 65535))
5010     {
5011       /* The operand can be relocated.  */
5012       if (!match_expression (arg, &offset_expr, offset_reloc))
5013         return FALSE;
5014
5015       if (offset_reloc[0] != BFD_RELOC_UNUSED)
5016         /* Relocation operators were used.  Accept the arguent and
5017            leave the relocation value in offset_expr and offset_relocs
5018            for the caller to process.  */
5019         return TRUE;
5020
5021       if (offset_expr.X_op != O_constant)
5022         {
5023           /* Accept non-constant operands if no later alternative matches,
5024              leaving it for the caller to process.  */
5025           if (!arg->lax_match)
5026             return FALSE;
5027           offset_reloc[0] = BFD_RELOC_LO16;
5028           return TRUE;
5029         }
5030
5031       /* Clear the global state; we're going to install the operand
5032          ourselves.  */
5033       sval = offset_expr.X_add_number;
5034       offset_expr.X_op = O_absent;
5035
5036       /* For compatibility with older assemblers, we accept
5037          0x8000-0xffff as signed 16-bit numbers when only
5038          signed numbers are allowed.  */
5039       if (sval > max_val)
5040         {
5041           max_val = ((1 << operand_base->size) - 1) << operand->shift;
5042           if (!arg->lax_match && sval <= max_val)
5043             return FALSE;
5044         }
5045     }
5046   else
5047     {
5048       if (!match_const_int (arg, &sval))
5049         return FALSE;
5050     }
5051
5052   arg->last_op_int = sval;
5053
5054   if (sval < min_val || sval > max_val || sval % factor)
5055     {
5056       match_out_of_range (arg);
5057       return FALSE;
5058     }
5059
5060   uval = (unsigned int) sval >> operand->shift;
5061   uval -= operand->bias;
5062
5063   /* Handle -mfix-cn63xxp1.  */
5064   if (arg->opnum == 1
5065       && mips_fix_cn63xxp1
5066       && !mips_opts.micromips
5067       && strcmp ("pref", arg->insn->insn_mo->name) == 0)
5068     switch (uval)
5069       {
5070       case 5:
5071       case 25:
5072       case 26:
5073       case 27:
5074       case 28:
5075       case 29:
5076       case 30:
5077       case 31:
5078         /* These are ok.  */
5079         break;
5080
5081       default:
5082         /* The rest must be changed to 28.  */
5083         uval = 28;
5084         break;
5085       }
5086
5087   insn_insert_operand (arg->insn, operand_base, uval);
5088   return TRUE;
5089 }
5090
5091 /* OP_MAPPED_INT matcher.  */
5092
5093 static bfd_boolean
5094 match_mapped_int_operand (struct mips_arg_info *arg,
5095                           const struct mips_operand *operand_base)
5096 {
5097   const struct mips_mapped_int_operand *operand;
5098   unsigned int uval, num_vals;
5099   offsetT sval;
5100
5101   operand = (const struct mips_mapped_int_operand *) operand_base;
5102   if (!match_const_int (arg, &sval))
5103     return FALSE;
5104
5105   num_vals = 1 << operand_base->size;
5106   for (uval = 0; uval < num_vals; uval++)
5107     if (operand->int_map[uval] == sval)
5108       break;
5109   if (uval == num_vals)
5110     {
5111       match_out_of_range (arg);
5112       return FALSE;
5113     }
5114
5115   insn_insert_operand (arg->insn, operand_base, uval);
5116   return TRUE;
5117 }
5118
5119 /* OP_MSB matcher.  */
5120
5121 static bfd_boolean
5122 match_msb_operand (struct mips_arg_info *arg,
5123                    const struct mips_operand *operand_base)
5124 {
5125   const struct mips_msb_operand *operand;
5126   int min_val, max_val, max_high;
5127   offsetT size, sval, high;
5128
5129   operand = (const struct mips_msb_operand *) operand_base;
5130   min_val = operand->bias;
5131   max_val = min_val + (1 << operand_base->size) - 1;
5132   max_high = operand->opsize;
5133
5134   if (!match_const_int (arg, &size))
5135     return FALSE;
5136
5137   high = size + arg->last_op_int;
5138   sval = operand->add_lsb ? high : size;
5139
5140   if (size < 0 || high > max_high || sval < min_val || sval > max_val)
5141     {
5142       match_out_of_range (arg);
5143       return FALSE;
5144     }
5145   insn_insert_operand (arg->insn, operand_base, sval - min_val);
5146   return TRUE;
5147 }
5148
5149 /* OP_REG matcher.  */
5150
5151 static bfd_boolean
5152 match_reg_operand (struct mips_arg_info *arg,
5153                    const struct mips_operand *operand_base)
5154 {
5155   const struct mips_reg_operand *operand;
5156   unsigned int regno, uval, num_vals;
5157
5158   operand = (const struct mips_reg_operand *) operand_base;
5159   if (!match_reg (arg, operand->reg_type, &regno))
5160     return FALSE;
5161
5162   if (operand->reg_map)
5163     {
5164       num_vals = 1 << operand->root.size;
5165       for (uval = 0; uval < num_vals; uval++)
5166         if (operand->reg_map[uval] == regno)
5167           break;
5168       if (num_vals == uval)
5169         return FALSE;
5170     }
5171   else
5172     uval = regno;
5173
5174   arg->last_regno = regno;
5175   if (arg->opnum == 1)
5176     arg->dest_regno = regno;
5177   insn_insert_operand (arg->insn, operand_base, uval);
5178   return TRUE;
5179 }
5180
5181 /* OP_REG_PAIR matcher.  */
5182
5183 static bfd_boolean
5184 match_reg_pair_operand (struct mips_arg_info *arg,
5185                         const struct mips_operand *operand_base)
5186 {
5187   const struct mips_reg_pair_operand *operand;
5188   unsigned int regno1, regno2, uval, num_vals;
5189
5190   operand = (const struct mips_reg_pair_operand *) operand_base;
5191   if (!match_reg (arg, operand->reg_type, &regno1)
5192       || !match_char (arg, ',')
5193       || !match_reg (arg, operand->reg_type, &regno2))
5194     return FALSE;
5195
5196   num_vals = 1 << operand_base->size;
5197   for (uval = 0; uval < num_vals; uval++)
5198     if (operand->reg1_map[uval] == regno1 && operand->reg2_map[uval] == regno2)
5199       break;
5200   if (uval == num_vals)
5201     return FALSE;
5202
5203   insn_insert_operand (arg->insn, operand_base, uval);
5204   return TRUE;
5205 }
5206
5207 /* OP_PCREL matcher.  The caller chooses the relocation type.  */
5208
5209 static bfd_boolean
5210 match_pcrel_operand (struct mips_arg_info *arg)
5211 {
5212   bfd_reloc_code_real_type r[3];
5213
5214   return match_expression (arg, &offset_expr, r) && r[0] == BFD_RELOC_UNUSED;
5215 }
5216
5217 /* OP_PERF_REG matcher.  */
5218
5219 static bfd_boolean
5220 match_perf_reg_operand (struct mips_arg_info *arg,
5221                         const struct mips_operand *operand)
5222 {
5223   offsetT sval;
5224
5225   if (!match_const_int (arg, &sval))
5226     return FALSE;
5227
5228   if (sval != 0
5229       && (sval != 1
5230           || (mips_opts.arch == CPU_R5900
5231               && (strcmp (arg->insn->insn_mo->name, "mfps") == 0
5232                   || strcmp (arg->insn->insn_mo->name, "mtps") == 0))))
5233     {
5234       set_insn_error (arg->argnum, _("invalid performance register"));
5235       return FALSE;
5236     }
5237
5238   insn_insert_operand (arg->insn, operand, sval);
5239   return TRUE;
5240 }
5241
5242 /* OP_ADDIUSP matcher.  */
5243
5244 static bfd_boolean
5245 match_addiusp_operand (struct mips_arg_info *arg,
5246                        const struct mips_operand *operand)
5247 {
5248   offsetT sval;
5249   unsigned int uval;
5250
5251   if (!match_const_int (arg, &sval))
5252     return FALSE;
5253
5254   if (sval % 4)
5255     {
5256       match_out_of_range (arg);
5257       return FALSE;
5258     }
5259
5260   sval /= 4;
5261   if (!(sval >= -258 && sval <= 257) || (sval >= -2 && sval <= 1))
5262     {
5263       match_out_of_range (arg);
5264       return FALSE;
5265     }
5266
5267   uval = (unsigned int) sval;
5268   uval = ((uval >> 1) & ~0xff) | (uval & 0xff);
5269   insn_insert_operand (arg->insn, operand, uval);
5270   return TRUE;
5271 }
5272
5273 /* OP_CLO_CLZ_DEST matcher.  */
5274
5275 static bfd_boolean
5276 match_clo_clz_dest_operand (struct mips_arg_info *arg,
5277                             const struct mips_operand *operand)
5278 {
5279   unsigned int regno;
5280
5281   if (!match_reg (arg, OP_REG_GP, &regno))
5282     return FALSE;
5283
5284   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5285   return TRUE;
5286 }
5287
5288 /* OP_CHECK_PREV matcher.  */
5289
5290 static bfd_boolean
5291 match_check_prev_operand (struct mips_arg_info *arg,
5292                           const struct mips_operand *operand_base)
5293 {
5294   const struct mips_check_prev_operand *operand;
5295   unsigned int regno;
5296
5297   operand = (const struct mips_check_prev_operand *) operand_base;
5298
5299   if (!match_reg (arg, OP_REG_GP, &regno))
5300     return FALSE;
5301
5302   if (!operand->zero_ok && regno == 0)
5303     return FALSE;
5304
5305   if ((operand->less_than_ok && regno < arg->last_regno)
5306       || (operand->greater_than_ok && regno > arg->last_regno)
5307       || (operand->equal_ok && regno == arg->last_regno))
5308     {
5309       arg->last_regno = regno;
5310       insn_insert_operand (arg->insn, operand_base, regno);
5311       return TRUE;
5312     }
5313
5314   return FALSE;
5315 }
5316
5317 /* OP_SAME_RS_RT matcher.  */
5318
5319 static bfd_boolean
5320 match_same_rs_rt_operand (struct mips_arg_info *arg,
5321                           const struct mips_operand *operand)
5322 {
5323   unsigned int regno;
5324
5325   if (!match_reg (arg, OP_REG_GP, &regno))
5326     return FALSE;
5327
5328   if (regno == 0)
5329     {
5330       set_insn_error (arg->argnum, _("the source register must not be $0"));
5331       return FALSE;
5332     }
5333
5334   arg->last_regno = regno;
5335
5336   insn_insert_operand (arg->insn, operand, regno | (regno << 5));
5337   return TRUE;
5338 }
5339
5340 /* OP_LWM_SWM_LIST matcher.  */
5341
5342 static bfd_boolean
5343 match_lwm_swm_list_operand (struct mips_arg_info *arg,
5344                             const struct mips_operand *operand)
5345 {
5346   unsigned int reglist, sregs, ra, regno1, regno2;
5347   struct mips_arg_info reset;
5348
5349   reglist = 0;
5350   if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5351     return FALSE;
5352   do
5353     {
5354       if (regno2 == FP && regno1 >= S0 && regno1 <= S7)
5355         {
5356           reglist |= 1 << FP;
5357           regno2 = S7;
5358         }
5359       reglist |= ((1U << regno2 << 1) - 1) & -(1U << regno1);
5360       reset = *arg;
5361     }
5362   while (match_char (arg, ',')
5363          && match_reg_range (arg, OP_REG_GP, &regno1, &regno2));
5364   *arg = reset;
5365
5366   if (operand->size == 2)
5367     {
5368       /* The list must include both ra and s0-sN, for 0 <= N <= 3.  E.g.:
5369
5370          s0, ra
5371          s0, s1, ra, s2, s3
5372          s0-s2, ra
5373
5374          and any permutations of these.  */
5375       if ((reglist & 0xfff1ffff) != 0x80010000)
5376         return FALSE;
5377
5378       sregs = (reglist >> 17) & 7;
5379       ra = 0;
5380     }
5381   else
5382     {
5383       /* The list must include at least one of ra and s0-sN,
5384          for 0 <= N <= 8.  (Note that there is a gap between s7 and s8,
5385          which are $23 and $30 respectively.)  E.g.:
5386
5387          ra
5388          s0
5389          ra, s0, s1, s2
5390          s0-s8
5391          s0-s5, ra
5392
5393          and any permutations of these.  */
5394       if ((reglist & 0x3f00ffff) != 0)
5395         return FALSE;
5396
5397       ra = (reglist >> 27) & 0x10;
5398       sregs = ((reglist >> 22) & 0x100) | ((reglist >> 16) & 0xff);
5399     }
5400   sregs += 1;
5401   if ((sregs & -sregs) != sregs)
5402     return FALSE;
5403
5404   insn_insert_operand (arg->insn, operand, (ffs (sregs) - 1) | ra);
5405   return TRUE;
5406 }
5407
5408 /* OP_ENTRY_EXIT_LIST matcher.  */
5409
5410 static unsigned int
5411 match_entry_exit_operand (struct mips_arg_info *arg,
5412                           const struct mips_operand *operand)
5413 {
5414   unsigned int mask;
5415   bfd_boolean is_exit;
5416
5417   /* The format is the same for both ENTRY and EXIT, but the constraints
5418      are different.  */
5419   is_exit = strcmp (arg->insn->insn_mo->name, "exit") == 0;
5420   mask = (is_exit ? 7 << 3 : 0);
5421   do
5422     {
5423       unsigned int regno1, regno2;
5424       bfd_boolean is_freg;
5425
5426       if (match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5427         is_freg = FALSE;
5428       else if (match_reg_range (arg, OP_REG_FP, &regno1, &regno2))
5429         is_freg = TRUE;
5430       else
5431         return FALSE;
5432
5433       if (is_exit && is_freg && regno1 == 0 && regno2 < 2)
5434         {
5435           mask &= ~(7 << 3);
5436           mask |= (5 + regno2) << 3;
5437         }
5438       else if (!is_exit && regno1 == 4 && regno2 >= 4 && regno2 <= 7)
5439         mask |= (regno2 - 3) << 3;
5440       else if (regno1 == 16 && regno2 >= 16 && regno2 <= 17)
5441         mask |= (regno2 - 15) << 1;
5442       else if (regno1 == RA && regno2 == RA)
5443         mask |= 1;
5444       else
5445         return FALSE;
5446     }
5447   while (match_char (arg, ','));
5448
5449   insn_insert_operand (arg->insn, operand, mask);
5450   return TRUE;
5451 }
5452
5453 /* OP_SAVE_RESTORE_LIST matcher.  */
5454
5455 static bfd_boolean
5456 match_save_restore_list_operand (struct mips_arg_info *arg)
5457 {
5458   unsigned int opcode, args, statics, sregs;
5459   unsigned int num_frame_sizes, num_args, num_statics, num_sregs;
5460   offsetT frame_size;
5461
5462   opcode = arg->insn->insn_opcode;
5463   frame_size = 0;
5464   num_frame_sizes = 0;
5465   args = 0;
5466   statics = 0;
5467   sregs = 0;
5468   do
5469     {
5470       unsigned int regno1, regno2;
5471
5472       if (arg->token->type == OT_INTEGER)
5473         {
5474           /* Handle the frame size.  */
5475           if (!match_const_int (arg, &frame_size))
5476             return FALSE;
5477           num_frame_sizes += 1;
5478         }
5479       else
5480         {
5481           if (!match_reg_range (arg, OP_REG_GP, &regno1, &regno2))
5482             return FALSE;
5483
5484           while (regno1 <= regno2)
5485             {
5486               if (regno1 >= 4 && regno1 <= 7)
5487                 {
5488                   if (num_frame_sizes == 0)
5489                     /* args $a0-$a3 */
5490                     args |= 1 << (regno1 - 4);
5491                   else
5492                     /* statics $a0-$a3 */
5493                     statics |= 1 << (regno1 - 4);
5494                 }
5495               else if (regno1 >= 16 && regno1 <= 23)
5496                 /* $s0-$s7 */
5497                 sregs |= 1 << (regno1 - 16);
5498               else if (regno1 == 30)
5499                 /* $s8 */
5500                 sregs |= 1 << 8;
5501               else if (regno1 == 31)
5502                 /* Add $ra to insn.  */
5503                 opcode |= 0x40;
5504               else
5505                 return FALSE;
5506               regno1 += 1;
5507               if (regno1 == 24)
5508                 regno1 = 30;
5509             }
5510         }
5511     }
5512   while (match_char (arg, ','));
5513
5514   /* Encode args/statics combination.  */
5515   if (args & statics)
5516     return FALSE;
5517   else if (args == 0xf)
5518     /* All $a0-$a3 are args.  */
5519     opcode |= MIPS16_ALL_ARGS << 16;
5520   else if (statics == 0xf)
5521     /* All $a0-$a3 are statics.  */
5522     opcode |= MIPS16_ALL_STATICS << 16;
5523   else
5524     {
5525       /* Count arg registers.  */
5526       num_args = 0;
5527       while (args & 0x1)
5528         {
5529           args >>= 1;
5530           num_args += 1;
5531         }
5532       if (args != 0)
5533         return FALSE;
5534
5535       /* Count static registers.  */
5536       num_statics = 0;
5537       while (statics & 0x8)
5538         {
5539           statics = (statics << 1) & 0xf;
5540           num_statics += 1;
5541         }
5542       if (statics != 0)
5543         return FALSE;
5544
5545       /* Encode args/statics.  */
5546       opcode |= ((num_args << 2) | num_statics) << 16;
5547     }
5548
5549   /* Encode $s0/$s1.  */
5550   if (sregs & (1 << 0))         /* $s0 */
5551     opcode |= 0x20;
5552   if (sregs & (1 << 1))         /* $s1 */
5553     opcode |= 0x10;
5554   sregs >>= 2;
5555
5556   /* Encode $s2-$s8. */
5557   num_sregs = 0;
5558   while (sregs & 1)
5559     {
5560       sregs >>= 1;
5561       num_sregs += 1;
5562     }
5563   if (sregs != 0)
5564     return FALSE;
5565   opcode |= num_sregs << 24;
5566
5567   /* Encode frame size.  */
5568   if (num_frame_sizes == 0)
5569     {
5570       set_insn_error (arg->argnum, _("missing frame size"));
5571       return FALSE;
5572     }
5573   if (num_frame_sizes > 1)
5574     {
5575       set_insn_error (arg->argnum, _("frame size specified twice"));
5576       return FALSE;
5577     }
5578   if ((frame_size & 7) != 0 || frame_size < 0 || frame_size > 0xff * 8)
5579     {
5580       set_insn_error (arg->argnum, _("invalid frame size"));
5581       return FALSE;
5582     }
5583   if (frame_size != 128 || (opcode >> 16) != 0)
5584     {
5585       frame_size /= 8;
5586       opcode |= (((frame_size & 0xf0) << 16)
5587                  | (frame_size & 0x0f));
5588     }
5589
5590   /* Finally build the instruction.  */
5591   if ((opcode >> 16) != 0 || frame_size == 0)
5592     opcode |= MIPS16_EXTEND;
5593   arg->insn->insn_opcode = opcode;
5594   return TRUE;
5595 }
5596
5597 /* OP_MDMX_IMM_REG matcher.  */
5598
5599 static bfd_boolean
5600 match_mdmx_imm_reg_operand (struct mips_arg_info *arg,
5601                             const struct mips_operand *operand)
5602 {
5603   unsigned int regno, uval;
5604   bfd_boolean is_qh;
5605   const struct mips_opcode *opcode;
5606
5607   /* The mips_opcode records whether this is an octobyte or quadhalf
5608      instruction.  Start out with that bit in place.  */
5609   opcode = arg->insn->insn_mo;
5610   uval = mips_extract_operand (operand, opcode->match);
5611   is_qh = (uval != 0);
5612
5613   if (arg->token->type == OT_REG)
5614     {
5615       if ((opcode->membership & INSN_5400)
5616           && strcmp (opcode->name, "rzu.ob") == 0)
5617         {
5618           set_insn_error_i (arg->argnum, _("operand %d must be an immediate"),
5619                             arg->argnum);
5620           return FALSE;
5621         }
5622
5623       if (!match_regno (arg, OP_REG_VEC, arg->token->u.regno, &regno))
5624         return FALSE;
5625       ++arg->token;
5626
5627       /* Check whether this is a vector register or a broadcast of
5628          a single element.  */
5629       if (arg->token->type == OT_INTEGER_INDEX)
5630         {
5631           if (arg->token->u.index > (is_qh ? 3 : 7))
5632             {
5633               set_insn_error (arg->argnum, _("invalid element selector"));
5634               return FALSE;
5635             }
5636           uval |= arg->token->u.index << (is_qh ? 2 : 1) << 5;
5637           ++arg->token;
5638         }
5639       else
5640         {
5641           /* A full vector.  */
5642           if ((opcode->membership & INSN_5400)
5643               && (strcmp (opcode->name, "sll.ob") == 0
5644                   || strcmp (opcode->name, "srl.ob") == 0))
5645             {
5646               set_insn_error_i (arg->argnum, _("operand %d must be scalar"),
5647                                 arg->argnum);
5648               return FALSE;
5649             }
5650
5651           if (is_qh)
5652             uval |= MDMX_FMTSEL_VEC_QH << 5;
5653           else
5654             uval |= MDMX_FMTSEL_VEC_OB << 5;
5655         }
5656       uval |= regno;
5657     }
5658   else
5659     {
5660       offsetT sval;
5661
5662       if (!match_const_int (arg, &sval))
5663         return FALSE;
5664       if (sval < 0 || sval > 31)
5665         {
5666           match_out_of_range (arg);
5667           return FALSE;
5668         }
5669       uval |= (sval & 31);
5670       if (is_qh)
5671         uval |= MDMX_FMTSEL_IMM_QH << 5;
5672       else
5673         uval |= MDMX_FMTSEL_IMM_OB << 5;
5674     }
5675   insn_insert_operand (arg->insn, operand, uval);
5676   return TRUE;
5677 }
5678
5679 /* OP_IMM_INDEX matcher.  */
5680
5681 static bfd_boolean
5682 match_imm_index_operand (struct mips_arg_info *arg,
5683                          const struct mips_operand *operand)
5684 {
5685   unsigned int max_val;
5686
5687   if (arg->token->type != OT_INTEGER_INDEX)
5688     return FALSE;
5689
5690   max_val = (1 << operand->size) - 1;
5691   if (arg->token->u.index > max_val)
5692     {
5693       match_out_of_range (arg);
5694       return FALSE;
5695     }
5696   insn_insert_operand (arg->insn, operand, arg->token->u.index);
5697   ++arg->token;
5698   return TRUE;
5699 }
5700
5701 /* OP_REG_INDEX matcher.  */
5702
5703 static bfd_boolean
5704 match_reg_index_operand (struct mips_arg_info *arg,
5705                          const struct mips_operand *operand)
5706 {
5707   unsigned int regno;
5708
5709   if (arg->token->type != OT_REG_INDEX)
5710     return FALSE;
5711
5712   if (!match_regno (arg, OP_REG_GP, arg->token->u.regno, &regno))
5713     return FALSE;
5714
5715   insn_insert_operand (arg->insn, operand, regno);
5716   ++arg->token;
5717   return TRUE;
5718 }
5719
5720 /* OP_PC matcher.  */
5721
5722 static bfd_boolean
5723 match_pc_operand (struct mips_arg_info *arg)
5724 {
5725   if (arg->token->type == OT_REG && (arg->token->u.regno & RTYPE_PC))
5726     {
5727       ++arg->token;
5728       return TRUE;
5729     }
5730   return FALSE;
5731 }
5732
5733 /* OP_NON_ZERO_REG matcher.  */
5734
5735 static bfd_boolean
5736 match_non_zero_reg_operand (struct mips_arg_info *arg,
5737                             const struct mips_operand *operand)
5738 {
5739   unsigned int regno;
5740
5741   if (!match_reg (arg, OP_REG_GP, &regno))
5742     return FALSE;
5743
5744   if (regno == 0)
5745     return FALSE;
5746
5747   arg->last_regno = regno;
5748   insn_insert_operand (arg->insn, operand, regno);
5749   return TRUE;
5750 }
5751
5752 /* OP_REPEAT_DEST_REG and OP_REPEAT_PREV_REG matcher.  OTHER_REGNO is the
5753    register that we need to match.  */
5754
5755 static bfd_boolean
5756 match_tied_reg_operand (struct mips_arg_info *arg, unsigned int other_regno)
5757 {
5758   unsigned int regno;
5759
5760   return match_reg (arg, OP_REG_GP, &regno) && regno == other_regno;
5761 }
5762
5763 /* Read a floating-point constant from S for LI.S or LI.D.  LENGTH is
5764    the length of the value in bytes (4 for float, 8 for double) and
5765    USING_GPRS says whether the destination is a GPR rather than an FPR.
5766
5767    Return the constant in IMM and OFFSET as follows:
5768
5769    - If the constant should be loaded via memory, set IMM to O_absent and
5770      OFFSET to the memory address.
5771
5772    - Otherwise, if the constant should be loaded into two 32-bit registers,
5773      set IMM to the O_constant to load into the high register and OFFSET
5774      to the corresponding value for the low register.
5775
5776    - Otherwise, set IMM to the full O_constant and set OFFSET to O_absent.
5777
5778    These constants only appear as the last operand in an instruction,
5779    and every instruction that accepts them in any variant accepts them
5780    in all variants.  This means we don't have to worry about backing out
5781    any changes if the instruction does not match.  We just match
5782    unconditionally and report an error if the constant is invalid.  */
5783
5784 static bfd_boolean
5785 match_float_constant (struct mips_arg_info *arg, expressionS *imm,
5786                       expressionS *offset, int length, bfd_boolean using_gprs)
5787 {
5788   char *p;
5789   segT seg, new_seg;
5790   subsegT subseg;
5791   const char *newname;
5792   unsigned char *data;
5793
5794   /* Where the constant is placed is based on how the MIPS assembler
5795      does things:
5796
5797      length == 4 && using_gprs  -- immediate value only
5798      length == 8 && using_gprs  -- .rdata or immediate value
5799      length == 4 && !using_gprs -- .lit4 or immediate value
5800      length == 8 && !using_gprs -- .lit8 or immediate value
5801
5802      The .lit4 and .lit8 sections are only used if permitted by the
5803      -G argument.  */
5804   if (arg->token->type != OT_FLOAT)
5805     {
5806       set_insn_error (arg->argnum, _("floating-point expression required"));
5807       return FALSE;
5808     }
5809
5810   gas_assert (arg->token->u.flt.length == length);
5811   data = arg->token->u.flt.data;
5812   ++arg->token;
5813
5814   /* Handle 32-bit constants for which an immediate value is best.  */
5815   if (length == 4
5816       && (using_gprs
5817           || g_switch_value < 4
5818           || (data[0] == 0 && data[1] == 0)
5819           || (data[2] == 0 && data[3] == 0)))
5820     {
5821       imm->X_op = O_constant;
5822       if (!target_big_endian)
5823         imm->X_add_number = bfd_getl32 (data);
5824       else
5825         imm->X_add_number = bfd_getb32 (data);
5826       offset->X_op = O_absent;
5827       return TRUE;
5828     }
5829
5830   /* Handle 64-bit constants for which an immediate value is best.  */
5831   if (length == 8
5832       && !mips_disable_float_construction
5833       /* Constants can only be constructed in GPRs and copied to FPRs if the
5834          GPRs are at least as wide as the FPRs or MTHC1 is available.
5835          Unlike most tests for 32-bit floating-point registers this check
5836          specifically looks for GPR_SIZE == 32 as the FPXX ABI does not
5837          permit 64-bit moves without MXHC1.
5838          Force the constant into memory otherwise.  */
5839       && (using_gprs
5840           || GPR_SIZE == 64
5841           || ISA_HAS_MXHC1 (mips_opts.isa)
5842           || FPR_SIZE == 32)
5843       && ((data[0] == 0 && data[1] == 0)
5844           || (data[2] == 0 && data[3] == 0))
5845       && ((data[4] == 0 && data[5] == 0)
5846           || (data[6] == 0 && data[7] == 0)))
5847     {
5848       /* The value is simple enough to load with a couple of instructions.
5849          If using 32-bit registers, set IMM to the high order 32 bits and
5850          OFFSET to the low order 32 bits.  Otherwise, set IMM to the entire
5851          64 bit constant.  */
5852       if (GPR_SIZE == 32 || (!using_gprs && FPR_SIZE != 64))
5853         {
5854           imm->X_op = O_constant;
5855           offset->X_op = O_constant;
5856           if (!target_big_endian)
5857             {
5858               imm->X_add_number = bfd_getl32 (data + 4);
5859               offset->X_add_number = bfd_getl32 (data);
5860             }
5861           else
5862             {
5863               imm->X_add_number = bfd_getb32 (data);
5864               offset->X_add_number = bfd_getb32 (data + 4);
5865             }
5866           if (offset->X_add_number == 0)
5867             offset->X_op = O_absent;
5868         }
5869       else
5870         {
5871           imm->X_op = O_constant;
5872           if (!target_big_endian)
5873             imm->X_add_number = bfd_getl64 (data);
5874           else
5875             imm->X_add_number = bfd_getb64 (data);
5876           offset->X_op = O_absent;
5877         }
5878       return TRUE;
5879     }
5880
5881   /* Switch to the right section.  */
5882   seg = now_seg;
5883   subseg = now_subseg;
5884   if (length == 4)
5885     {
5886       gas_assert (!using_gprs && g_switch_value >= 4);
5887       newname = ".lit4";
5888     }
5889   else
5890     {
5891       if (using_gprs || g_switch_value < 8)
5892         newname = RDATA_SECTION_NAME;
5893       else
5894         newname = ".lit8";
5895     }
5896
5897   new_seg = subseg_new (newname, (subsegT) 0);
5898   bfd_set_section_flags (stdoutput, new_seg,
5899                          SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA);
5900   frag_align (length == 4 ? 2 : 3, 0, 0);
5901   if (strncmp (TARGET_OS, "elf", 3) != 0)
5902     record_alignment (new_seg, 4);
5903   else
5904     record_alignment (new_seg, length == 4 ? 2 : 3);
5905   if (seg == now_seg)
5906     as_bad (_("cannot use `%s' in this section"), arg->insn->insn_mo->name);
5907
5908   /* Set the argument to the current address in the section.  */
5909   imm->X_op = O_absent;
5910   offset->X_op = O_symbol;
5911   offset->X_add_symbol = symbol_temp_new_now ();
5912   offset->X_add_number = 0;
5913
5914   /* Put the floating point number into the section.  */
5915   p = frag_more (length);
5916   memcpy (p, data, length);
5917
5918   /* Switch back to the original section.  */
5919   subseg_set (seg, subseg);
5920   return TRUE;
5921 }
5922
5923 /* OP_VU0_SUFFIX and OP_VU0_MATCH_SUFFIX matcher; MATCH_P selects between
5924    them.  */
5925
5926 static bfd_boolean
5927 match_vu0_suffix_operand (struct mips_arg_info *arg,
5928                           const struct mips_operand *operand,
5929                           bfd_boolean match_p)
5930 {
5931   unsigned int uval;
5932
5933   /* The operand can be an XYZW mask or a single 2-bit channel index
5934      (with X being 0).  */
5935   gas_assert (operand->size == 2 || operand->size == 4);
5936
5937   /* The suffix can be omitted when it is already part of the opcode.  */
5938   if (arg->token->type != OT_CHANNELS)
5939     return match_p;
5940
5941   uval = arg->token->u.channels;
5942   if (operand->size == 2)
5943     {
5944       /* Check that a single bit is set and convert it into a 2-bit index.  */
5945       if ((uval & -uval) != uval)
5946         return FALSE;
5947       uval = 4 - ffs (uval);
5948     }
5949
5950   if (match_p && insn_extract_operand (arg->insn, operand) != uval)
5951     return FALSE;
5952
5953   ++arg->token;
5954   if (!match_p)
5955     insn_insert_operand (arg->insn, operand, uval);
5956   return TRUE;
5957 }
5958
5959 /* S is the text seen for ARG.  Match it against OPERAND.  Return the end
5960    of the argument text if the match is successful, otherwise return null.  */
5961
5962 static bfd_boolean
5963 match_operand (struct mips_arg_info *arg,
5964                const struct mips_operand *operand)
5965 {
5966   switch (operand->type)
5967     {
5968     case OP_INT:
5969       return match_int_operand (arg, operand);
5970
5971     case OP_MAPPED_INT:
5972       return match_mapped_int_operand (arg, operand);
5973
5974     case OP_MSB:
5975       return match_msb_operand (arg, operand);
5976
5977     case OP_REG:
5978     case OP_OPTIONAL_REG:
5979       return match_reg_operand (arg, operand);
5980
5981     case OP_REG_PAIR:
5982       return match_reg_pair_operand (arg, operand);
5983
5984     case OP_PCREL:
5985       return match_pcrel_operand (arg);
5986
5987     case OP_PERF_REG:
5988       return match_perf_reg_operand (arg, operand);
5989
5990     case OP_ADDIUSP_INT:
5991       return match_addiusp_operand (arg, operand);
5992
5993     case OP_CLO_CLZ_DEST:
5994       return match_clo_clz_dest_operand (arg, operand);
5995
5996     case OP_LWM_SWM_LIST:
5997       return match_lwm_swm_list_operand (arg, operand);
5998
5999     case OP_ENTRY_EXIT_LIST:
6000       return match_entry_exit_operand (arg, operand);
6001
6002     case OP_SAVE_RESTORE_LIST:
6003       return match_save_restore_list_operand (arg);
6004
6005     case OP_MDMX_IMM_REG:
6006       return match_mdmx_imm_reg_operand (arg, operand);
6007
6008     case OP_REPEAT_DEST_REG:
6009       return match_tied_reg_operand (arg, arg->dest_regno);
6010
6011     case OP_REPEAT_PREV_REG:
6012       return match_tied_reg_operand (arg, arg->last_regno);
6013
6014     case OP_PC:
6015       return match_pc_operand (arg);
6016
6017     case OP_VU0_SUFFIX:
6018       return match_vu0_suffix_operand (arg, operand, FALSE);
6019
6020     case OP_VU0_MATCH_SUFFIX:
6021       return match_vu0_suffix_operand (arg, operand, TRUE);
6022
6023     case OP_IMM_INDEX:
6024       return match_imm_index_operand (arg, operand);
6025
6026     case OP_REG_INDEX:
6027       return match_reg_index_operand (arg, operand);
6028
6029     case OP_SAME_RS_RT:
6030       return match_same_rs_rt_operand (arg, operand);
6031
6032     case OP_CHECK_PREV:
6033       return match_check_prev_operand (arg, operand);
6034
6035     case OP_NON_ZERO_REG:
6036       return match_non_zero_reg_operand (arg, operand);
6037     }
6038   abort ();
6039 }
6040
6041 /* ARG is the state after successfully matching an instruction.
6042    Issue any queued-up warnings.  */
6043
6044 static void
6045 check_completed_insn (struct mips_arg_info *arg)
6046 {
6047   if (arg->seen_at)
6048     {
6049       if (AT == ATREG)
6050         as_warn (_("used $at without \".set noat\""));
6051       else
6052         as_warn (_("used $%u with \".set at=$%u\""), AT, AT);
6053     }
6054 }
6055
6056 /* Return true if modifying general-purpose register REG needs a delay.  */
6057
6058 static bfd_boolean
6059 reg_needs_delay (unsigned int reg)
6060 {
6061   unsigned long prev_pinfo;
6062
6063   prev_pinfo = history[0].insn_mo->pinfo;
6064   if (!mips_opts.noreorder
6065       && (((prev_pinfo & INSN_LOAD_MEMORY) && !gpr_interlocks)
6066           || ((prev_pinfo & INSN_LOAD_COPROC) && !cop_interlocks))
6067       && (gpr_write_mask (&history[0]) & (1 << reg)))
6068     return TRUE;
6069
6070   return FALSE;
6071 }
6072
6073 /* Classify an instruction according to the FIX_VR4120_* enumeration.
6074    Return NUM_FIX_VR4120_CLASSES if the instruction isn't affected
6075    by VR4120 errata.  */
6076
6077 static unsigned int
6078 classify_vr4120_insn (const char *name)
6079 {
6080   if (strncmp (name, "macc", 4) == 0)
6081     return FIX_VR4120_MACC;
6082   if (strncmp (name, "dmacc", 5) == 0)
6083     return FIX_VR4120_DMACC;
6084   if (strncmp (name, "mult", 4) == 0)
6085     return FIX_VR4120_MULT;
6086   if (strncmp (name, "dmult", 5) == 0)
6087     return FIX_VR4120_DMULT;
6088   if (strstr (name, "div"))
6089     return FIX_VR4120_DIV;
6090   if (strcmp (name, "mtlo") == 0 || strcmp (name, "mthi") == 0)
6091     return FIX_VR4120_MTHILO;
6092   return NUM_FIX_VR4120_CLASSES;
6093 }
6094
6095 #define INSN_ERET       0x42000018
6096 #define INSN_DERET      0x4200001f
6097 #define INSN_DMULT      0x1c
6098 #define INSN_DMULTU     0x1d
6099
6100 /* Return the number of instructions that must separate INSN1 and INSN2,
6101    where INSN1 is the earlier instruction.  Return the worst-case value
6102    for any INSN2 if INSN2 is null.  */
6103
6104 static unsigned int
6105 insns_between (const struct mips_cl_insn *insn1,
6106                const struct mips_cl_insn *insn2)
6107 {
6108   unsigned long pinfo1, pinfo2;
6109   unsigned int mask;
6110
6111   /* If INFO2 is null, pessimistically assume that all flags are set for
6112      the second instruction.  */
6113   pinfo1 = insn1->insn_mo->pinfo;
6114   pinfo2 = insn2 ? insn2->insn_mo->pinfo : ~0U;
6115
6116   /* For most targets, write-after-read dependencies on the HI and LO
6117      registers must be separated by at least two instructions.  */
6118   if (!hilo_interlocks)
6119     {
6120       if ((pinfo1 & INSN_READ_LO) && (pinfo2 & INSN_WRITE_LO))
6121         return 2;
6122       if ((pinfo1 & INSN_READ_HI) && (pinfo2 & INSN_WRITE_HI))
6123         return 2;
6124     }
6125
6126   /* If we're working around r7000 errata, there must be two instructions
6127      between an mfhi or mflo and any instruction that uses the result.  */
6128   if (mips_7000_hilo_fix
6129       && !mips_opts.micromips
6130       && MF_HILO_INSN (pinfo1)
6131       && (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1))))
6132     return 2;
6133
6134   /* If we're working around 24K errata, one instruction is required
6135      if an ERET or DERET is followed by a branch instruction.  */
6136   if (mips_fix_24k && !mips_opts.micromips)
6137     {
6138       if (insn1->insn_opcode == INSN_ERET
6139           || insn1->insn_opcode == INSN_DERET)
6140         {
6141           if (insn2 == NULL
6142               || insn2->insn_opcode == INSN_ERET
6143               || insn2->insn_opcode == INSN_DERET
6144               || delayed_branch_p (insn2))
6145             return 1;
6146         }
6147     }
6148
6149   /* If we're working around PMC RM7000 errata, there must be three
6150      nops between a dmult and a load instruction.  */
6151   if (mips_fix_rm7000 && !mips_opts.micromips)
6152     {
6153       if ((insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULT
6154           || (insn1->insn_opcode & insn1->insn_mo->mask) == INSN_DMULTU)
6155         {
6156           if (pinfo2 & INSN_LOAD_MEMORY)
6157            return 3;
6158         }
6159     }
6160
6161   /* If working around VR4120 errata, check for combinations that need
6162      a single intervening instruction.  */
6163   if (mips_fix_vr4120 && !mips_opts.micromips)
6164     {
6165       unsigned int class1, class2;
6166
6167       class1 = classify_vr4120_insn (insn1->insn_mo->name);
6168       if (class1 != NUM_FIX_VR4120_CLASSES && vr4120_conflicts[class1] != 0)
6169         {
6170           if (insn2 == NULL)
6171             return 1;
6172           class2 = classify_vr4120_insn (insn2->insn_mo->name);
6173           if (vr4120_conflicts[class1] & (1 << class2))
6174             return 1;
6175         }
6176     }
6177
6178   if (!HAVE_CODE_COMPRESSION)
6179     {
6180       /* Check for GPR or coprocessor load delays.  All such delays
6181          are on the RT register.  */
6182       /* Itbl support may require additional care here.  */
6183       if ((!gpr_interlocks && (pinfo1 & INSN_LOAD_MEMORY))
6184           || (!cop_interlocks && (pinfo1 & INSN_LOAD_COPROC)))
6185         {
6186           if (insn2 == NULL || (gpr_read_mask (insn2) & gpr_write_mask (insn1)))
6187             return 1;
6188         }
6189
6190       /* Check for generic coprocessor hazards.
6191
6192          This case is not handled very well.  There is no special
6193          knowledge of CP0 handling, and the coprocessors other than
6194          the floating point unit are not distinguished at all.  */
6195       /* Itbl support may require additional care here. FIXME!
6196          Need to modify this to include knowledge about
6197          user specified delays!  */
6198       else if ((!cop_interlocks && (pinfo1 & INSN_COPROC_MOVE))
6199                || (!cop_mem_interlocks && (pinfo1 & INSN_COPROC_MEMORY_DELAY)))
6200         {
6201           /* Handle cases where INSN1 writes to a known general coprocessor
6202              register.  There must be a one instruction delay before INSN2
6203              if INSN2 reads that register, otherwise no delay is needed.  */
6204           mask = fpr_write_mask (insn1);
6205           if (mask != 0)
6206             {
6207               if (!insn2 || (mask & fpr_read_mask (insn2)) != 0)
6208                 return 1;
6209             }
6210           else
6211             {
6212               /* Read-after-write dependencies on the control registers
6213                  require a two-instruction gap.  */
6214               if ((pinfo1 & INSN_WRITE_COND_CODE)
6215                   && (pinfo2 & INSN_READ_COND_CODE))
6216                 return 2;
6217
6218               /* We don't know exactly what INSN1 does.  If INSN2 is
6219                  also a coprocessor instruction, assume there must be
6220                  a one instruction gap.  */
6221               if (pinfo2 & INSN_COP)
6222                 return 1;
6223             }
6224         }
6225
6226       /* Check for read-after-write dependencies on the coprocessor
6227          control registers in cases where INSN1 does not need a general
6228          coprocessor delay.  This means that INSN1 is a floating point
6229          comparison instruction.  */
6230       /* Itbl support may require additional care here.  */
6231       else if (!cop_interlocks
6232                && (pinfo1 & INSN_WRITE_COND_CODE)
6233                && (pinfo2 & INSN_READ_COND_CODE))
6234         return 1;
6235     }
6236
6237   /* Forbidden slots can not contain Control Transfer Instructions (CTIs)
6238      CTIs include all branches and jumps, nal, eret, eretnc, deret, wait
6239      and pause.  */
6240   if ((insn1->insn_mo->pinfo2 & INSN2_FORBIDDEN_SLOT)
6241       && ((pinfo2 & INSN_NO_DELAY_SLOT)
6242           || (insn2 && delayed_branch_p (insn2))))
6243     return 1;
6244
6245   return 0;
6246 }
6247
6248 /* Return the number of nops that would be needed to work around the
6249    VR4130 mflo/mfhi errata if instruction INSN immediately followed
6250    the MAX_VR4130_NOPS instructions described by HIST.  Ignore hazards
6251    that are contained within the first IGNORE instructions of HIST.  */
6252
6253 static int
6254 nops_for_vr4130 (int ignore, const struct mips_cl_insn *hist,
6255                  const struct mips_cl_insn *insn)
6256 {
6257   int i, j;
6258   unsigned int mask;
6259
6260   /* Check if the instruction writes to HI or LO.  MTHI and MTLO
6261      are not affected by the errata.  */
6262   if (insn != 0
6263       && ((insn->insn_mo->pinfo & (INSN_WRITE_HI | INSN_WRITE_LO)) == 0
6264           || strcmp (insn->insn_mo->name, "mtlo") == 0
6265           || strcmp (insn->insn_mo->name, "mthi") == 0))
6266     return 0;
6267
6268   /* Search for the first MFLO or MFHI.  */
6269   for (i = 0; i < MAX_VR4130_NOPS; i++)
6270     if (MF_HILO_INSN (hist[i].insn_mo->pinfo))
6271       {
6272         /* Extract the destination register.  */
6273         mask = gpr_write_mask (&hist[i]);
6274
6275         /* No nops are needed if INSN reads that register.  */
6276         if (insn != NULL && (gpr_read_mask (insn) & mask) != 0)
6277           return 0;
6278
6279         /* ...or if any of the intervening instructions do.  */
6280         for (j = 0; j < i; j++)
6281           if (gpr_read_mask (&hist[j]) & mask)
6282             return 0;
6283
6284         if (i >= ignore)
6285           return MAX_VR4130_NOPS - i;
6286       }
6287   return 0;
6288 }
6289
6290 #define BASE_REG_EQ(INSN1, INSN2)       \
6291   ((((INSN1) >> OP_SH_RS) & OP_MASK_RS) \
6292       == (((INSN2) >> OP_SH_RS) & OP_MASK_RS))
6293
6294 /* Return the minimum alignment for this store instruction.  */
6295
6296 static int
6297 fix_24k_align_to (const struct mips_opcode *mo)
6298 {
6299   if (strcmp (mo->name, "sh") == 0)
6300     return 2;
6301
6302   if (strcmp (mo->name, "swc1") == 0
6303       || strcmp (mo->name, "swc2") == 0
6304       || strcmp (mo->name, "sw") == 0
6305       || strcmp (mo->name, "sc") == 0
6306       || strcmp (mo->name, "s.s") == 0)
6307     return 4;
6308
6309   if (strcmp (mo->name, "sdc1") == 0
6310       || strcmp (mo->name, "sdc2") == 0
6311       || strcmp (mo->name, "s.d") == 0)
6312     return 8;
6313
6314   /* sb, swl, swr */
6315   return 1;
6316 }
6317
6318 struct fix_24k_store_info
6319   {
6320     /* Immediate offset, if any, for this store instruction.  */
6321     short off;
6322     /* Alignment required by this store instruction.  */
6323     int align_to;
6324     /* True for register offsets.  */
6325     int register_offset;
6326   };
6327
6328 /* Comparison function used by qsort.  */
6329
6330 static int
6331 fix_24k_sort (const void *a, const void *b)
6332 {
6333   const struct fix_24k_store_info *pos1 = a;
6334   const struct fix_24k_store_info *pos2 = b;
6335
6336   return (pos1->off - pos2->off);
6337 }
6338
6339 /* INSN is a store instruction.  Try to record the store information
6340    in STINFO.  Return false if the information isn't known.  */
6341
6342 static bfd_boolean
6343 fix_24k_record_store_info (struct fix_24k_store_info *stinfo,
6344                            const struct mips_cl_insn *insn)
6345 {
6346   /* The instruction must have a known offset.  */
6347   if (!insn->complete_p || !strstr (insn->insn_mo->args, "o("))
6348     return FALSE;
6349
6350   stinfo->off = (insn->insn_opcode >> OP_SH_IMMEDIATE) & OP_MASK_IMMEDIATE;
6351   stinfo->align_to = fix_24k_align_to (insn->insn_mo);
6352   return TRUE;
6353 }
6354
6355 /* Return the number of nops that would be needed to work around the 24k
6356    "lost data on stores during refill" errata if instruction INSN
6357    immediately followed the 2 instructions described by HIST.
6358    Ignore hazards that are contained within the first IGNORE
6359    instructions of HIST.
6360
6361    Problem: The FSB (fetch store buffer) acts as an intermediate buffer
6362    for the data cache refills and store data. The following describes
6363    the scenario where the store data could be lost.
6364
6365    * A data cache miss, due to either a load or a store, causing fill
6366      data to be supplied by the memory subsystem
6367    * The first three doublewords of fill data are returned and written
6368      into the cache
6369    * A sequence of four stores occurs in consecutive cycles around the
6370      final doubleword of the fill:
6371    * Store A
6372    * Store B
6373    * Store C
6374    * Zero, One or more instructions
6375    * Store D
6376
6377    The four stores A-D must be to different doublewords of the line that
6378    is being filled. The fourth instruction in the sequence above permits
6379    the fill of the final doubleword to be transferred from the FSB into
6380    the cache. In the sequence above, the stores may be either integer
6381    (sb, sh, sw, swr, swl, sc) or coprocessor (swc1/swc2, sdc1/sdc2,
6382    swxc1, sdxc1, suxc1) stores, as long as the four stores are to
6383    different doublewords on the line. If the floating point unit is
6384    running in 1:2 mode, it is not possible to create the sequence above
6385    using only floating point store instructions.
6386
6387    In this case, the cache line being filled is incorrectly marked
6388    invalid, thereby losing the data from any store to the line that
6389    occurs between the original miss and the completion of the five
6390    cycle sequence shown above.
6391
6392    The workarounds are:
6393
6394    * Run the data cache in write-through mode.
6395    * Insert a non-store instruction between
6396      Store A and Store B or Store B and Store C.  */
6397
6398 static int
6399 nops_for_24k (int ignore, const struct mips_cl_insn *hist,
6400               const struct mips_cl_insn *insn)
6401 {
6402   struct fix_24k_store_info pos[3];
6403   int align, i, base_offset;
6404
6405   if (ignore >= 2)
6406     return 0;
6407
6408   /* If the previous instruction wasn't a store, there's nothing to
6409      worry about.  */
6410   if ((hist[0].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6411     return 0;
6412
6413   /* If the instructions after the previous one are unknown, we have
6414      to assume the worst.  */
6415   if (!insn)
6416     return 1;
6417
6418   /* Check whether we are dealing with three consecutive stores.  */
6419   if ((insn->insn_mo->pinfo & INSN_STORE_MEMORY) == 0
6420       || (hist[1].insn_mo->pinfo & INSN_STORE_MEMORY) == 0)
6421     return 0;
6422
6423   /* If we don't know the relationship between the store addresses,
6424      assume the worst.  */
6425   if (!BASE_REG_EQ (insn->insn_opcode, hist[0].insn_opcode)
6426       || !BASE_REG_EQ (insn->insn_opcode, hist[1].insn_opcode))
6427     return 1;
6428
6429   if (!fix_24k_record_store_info (&pos[0], insn)
6430       || !fix_24k_record_store_info (&pos[1], &hist[0])
6431       || !fix_24k_record_store_info (&pos[2], &hist[1]))
6432     return 1;
6433
6434   qsort (&pos, 3, sizeof (struct fix_24k_store_info), fix_24k_sort);
6435
6436   /* Pick a value of ALIGN and X such that all offsets are adjusted by
6437      X bytes and such that the base register + X is known to be aligned
6438      to align bytes.  */
6439
6440   if (((insn->insn_opcode >> OP_SH_RS) & OP_MASK_RS) == SP)
6441     align = 8;
6442   else
6443     {
6444       align = pos[0].align_to;
6445       base_offset = pos[0].off;
6446       for (i = 1; i < 3; i++)
6447         if (align < pos[i].align_to)
6448           {
6449             align = pos[i].align_to;
6450             base_offset = pos[i].off;
6451           }
6452       for (i = 0; i < 3; i++)
6453         pos[i].off -= base_offset;
6454     }
6455
6456   pos[0].off &= ~align + 1;
6457   pos[1].off &= ~align + 1;
6458   pos[2].off &= ~align + 1;
6459
6460   /* If any two stores write to the same chunk, they also write to the
6461      same doubleword.  The offsets are still sorted at this point.  */
6462   if (pos[0].off == pos[1].off || pos[1].off == pos[2].off)
6463     return 0;
6464
6465   /* A range of at least 9 bytes is needed for the stores to be in
6466      non-overlapping doublewords.  */
6467   if (pos[2].off - pos[0].off <= 8)
6468     return 0;
6469
6470   if (pos[2].off - pos[1].off >= 24
6471       || pos[1].off - pos[0].off >= 24
6472       || pos[2].off - pos[0].off >= 32)
6473     return 0;
6474
6475   return 1;
6476 }
6477
6478 /* Return the number of nops that would be needed if instruction INSN
6479    immediately followed the MAX_NOPS instructions given by HIST,
6480    where HIST[0] is the most recent instruction.  Ignore hazards
6481    between INSN and the first IGNORE instructions in HIST.
6482
6483    If INSN is null, return the worse-case number of nops for any
6484    instruction.  */
6485
6486 static int
6487 nops_for_insn (int ignore, const struct mips_cl_insn *hist,
6488                const struct mips_cl_insn *insn)
6489 {
6490   int i, nops, tmp_nops;
6491
6492   nops = 0;
6493   for (i = ignore; i < MAX_DELAY_NOPS; i++)
6494     {
6495       tmp_nops = insns_between (hist + i, insn) - i;
6496       if (tmp_nops > nops)
6497         nops = tmp_nops;
6498     }
6499
6500   if (mips_fix_vr4130 && !mips_opts.micromips)
6501     {
6502       tmp_nops = nops_for_vr4130 (ignore, hist, insn);
6503       if (tmp_nops > nops)
6504         nops = tmp_nops;
6505     }
6506
6507   if (mips_fix_24k && !mips_opts.micromips)
6508     {
6509       tmp_nops = nops_for_24k (ignore, hist, insn);
6510       if (tmp_nops > nops)
6511         nops = tmp_nops;
6512     }
6513
6514   return nops;
6515 }
6516
6517 /* The variable arguments provide NUM_INSNS extra instructions that
6518    might be added to HIST.  Return the largest number of nops that
6519    would be needed after the extended sequence, ignoring hazards
6520    in the first IGNORE instructions.  */
6521
6522 static int
6523 nops_for_sequence (int num_insns, int ignore,
6524                    const struct mips_cl_insn *hist, ...)
6525 {
6526   va_list args;
6527   struct mips_cl_insn buffer[MAX_NOPS];
6528   struct mips_cl_insn *cursor;
6529   int nops;
6530
6531   va_start (args, hist);
6532   cursor = buffer + num_insns;
6533   memcpy (cursor, hist, (MAX_NOPS - num_insns) * sizeof (*cursor));
6534   while (cursor > buffer)
6535     *--cursor = *va_arg (args, const struct mips_cl_insn *);
6536
6537   nops = nops_for_insn (ignore, buffer, NULL);
6538   va_end (args);
6539   return nops;
6540 }
6541
6542 /* Like nops_for_insn, but if INSN is a branch, take into account the
6543    worst-case delay for the branch target.  */
6544
6545 static int
6546 nops_for_insn_or_target (int ignore, const struct mips_cl_insn *hist,
6547                          const struct mips_cl_insn *insn)
6548 {
6549   int nops, tmp_nops;
6550
6551   nops = nops_for_insn (ignore, hist, insn);
6552   if (delayed_branch_p (insn))
6553     {
6554       tmp_nops = nops_for_sequence (2, ignore ? ignore + 2 : 0,
6555                                     hist, insn, get_delay_slot_nop (insn));
6556       if (tmp_nops > nops)
6557         nops = tmp_nops;
6558     }
6559   else if (compact_branch_p (insn))
6560     {
6561       tmp_nops = nops_for_sequence (1, ignore ? ignore + 1 : 0, hist, insn);
6562       if (tmp_nops > nops)
6563         nops = tmp_nops;
6564     }
6565   return nops;
6566 }
6567
6568 /* Fix NOP issue: Replace nops by "or at,at,zero".  */
6569
6570 static void
6571 fix_loongson2f_nop (struct mips_cl_insn * ip)
6572 {
6573   gas_assert (!HAVE_CODE_COMPRESSION);
6574   if (strcmp (ip->insn_mo->name, "nop") == 0)
6575     ip->insn_opcode = LOONGSON2F_NOP_INSN;
6576 }
6577
6578 /* Fix Jump Issue: Eliminate instruction fetch from outside 256M region
6579                    jr target pc &= 'hffff_ffff_cfff_ffff.  */
6580
6581 static void
6582 fix_loongson2f_jump (struct mips_cl_insn * ip)
6583 {
6584   gas_assert (!HAVE_CODE_COMPRESSION);
6585   if (strcmp (ip->insn_mo->name, "j") == 0
6586       || strcmp (ip->insn_mo->name, "jr") == 0
6587       || strcmp (ip->insn_mo->name, "jalr") == 0)
6588     {
6589       int sreg;
6590       expressionS ep;
6591
6592       if (! mips_opts.at)
6593         return;
6594
6595       sreg = EXTRACT_OPERAND (0, RS, *ip);
6596       if (sreg == ZERO || sreg == KT0 || sreg == KT1 || sreg == ATREG)
6597         return;
6598
6599       ep.X_op = O_constant;
6600       ep.X_add_number = 0xcfff0000;
6601       macro_build (&ep, "lui", "t,u", ATREG, BFD_RELOC_HI16);
6602       ep.X_add_number = 0xffff;
6603       macro_build (&ep, "ori", "t,r,i", ATREG, ATREG, BFD_RELOC_LO16);
6604       macro_build (NULL, "and", "d,v,t", sreg, sreg, ATREG);
6605     }
6606 }
6607
6608 static void
6609 fix_loongson2f (struct mips_cl_insn * ip)
6610 {
6611   if (mips_fix_loongson2f_nop)
6612     fix_loongson2f_nop (ip);
6613
6614   if (mips_fix_loongson2f_jump)
6615     fix_loongson2f_jump (ip);
6616 }
6617
6618 /* IP is a branch that has a delay slot, and we need to fill it
6619    automatically.   Return true if we can do that by swapping IP
6620    with the previous instruction.
6621    ADDRESS_EXPR is an operand of the instruction to be used with
6622    RELOC_TYPE.  */
6623
6624 static bfd_boolean
6625 can_swap_branch_p (struct mips_cl_insn *ip, expressionS *address_expr,
6626                    bfd_reloc_code_real_type *reloc_type)
6627 {
6628   unsigned long pinfo, pinfo2, prev_pinfo, prev_pinfo2;
6629   unsigned int gpr_read, gpr_write, prev_gpr_read, prev_gpr_write;
6630   unsigned int fpr_read, prev_fpr_write;
6631
6632   /* -O2 and above is required for this optimization.  */
6633   if (mips_optimize < 2)
6634     return FALSE;
6635
6636   /* If we have seen .set volatile or .set nomove, don't optimize.  */
6637   if (mips_opts.nomove)
6638     return FALSE;
6639
6640   /* We can't swap if the previous instruction's position is fixed.  */
6641   if (history[0].fixed_p)
6642     return FALSE;
6643
6644   /* If the previous previous insn was in a .set noreorder, we can't
6645      swap.  Actually, the MIPS assembler will swap in this situation.
6646      However, gcc configured -with-gnu-as will generate code like
6647
6648         .set    noreorder
6649         lw      $4,XXX
6650         .set    reorder
6651         INSN
6652         bne     $4,$0,foo
6653
6654      in which we can not swap the bne and INSN.  If gcc is not configured
6655      -with-gnu-as, it does not output the .set pseudo-ops.  */
6656   if (history[1].noreorder_p)
6657     return FALSE;
6658
6659   /* If the previous instruction had a fixup in mips16 mode, we can not swap.
6660      This means that the previous instruction was a 4-byte one anyhow.  */
6661   if (mips_opts.mips16 && history[0].fixp[0])
6662     return FALSE;
6663
6664   /* If the branch is itself the target of a branch, we can not swap.
6665      We cheat on this; all we check for is whether there is a label on
6666      this instruction.  If there are any branches to anything other than
6667      a label, users must use .set noreorder.  */
6668   if (seg_info (now_seg)->label_list)
6669     return FALSE;
6670
6671   /* If the previous instruction is in a variant frag other than this
6672      branch's one, we cannot do the swap.  This does not apply to
6673      MIPS16 code, which uses variant frags for different purposes.  */
6674   if (!mips_opts.mips16
6675       && history[0].frag
6676       && history[0].frag->fr_type == rs_machine_dependent)
6677     return FALSE;
6678
6679   /* We do not swap with instructions that cannot architecturally
6680      be placed in a branch delay slot, such as SYNC or ERET.  We
6681      also refrain from swapping with a trap instruction, since it
6682      complicates trap handlers to have the trap instruction be in
6683      a delay slot.  */
6684   prev_pinfo = history[0].insn_mo->pinfo;
6685   if (prev_pinfo & INSN_NO_DELAY_SLOT)
6686     return FALSE;
6687
6688   /* Check for conflicts between the branch and the instructions
6689      before the candidate delay slot.  */
6690   if (nops_for_insn (0, history + 1, ip) > 0)
6691     return FALSE;
6692
6693   /* Check for conflicts between the swapped sequence and the
6694      target of the branch.  */
6695   if (nops_for_sequence (2, 0, history + 1, ip, history) > 0)
6696     return FALSE;
6697
6698   /* If the branch reads a register that the previous
6699      instruction sets, we can not swap.  */
6700   gpr_read = gpr_read_mask (ip);
6701   prev_gpr_write = gpr_write_mask (&history[0]);
6702   if (gpr_read & prev_gpr_write)
6703     return FALSE;
6704
6705   fpr_read = fpr_read_mask (ip);
6706   prev_fpr_write = fpr_write_mask (&history[0]);
6707   if (fpr_read & prev_fpr_write)
6708     return FALSE;
6709
6710   /* If the branch writes a register that the previous
6711      instruction sets, we can not swap.  */
6712   gpr_write = gpr_write_mask (ip);
6713   if (gpr_write & prev_gpr_write)
6714     return FALSE;
6715
6716   /* If the branch writes a register that the previous
6717      instruction reads, we can not swap.  */
6718   prev_gpr_read = gpr_read_mask (&history[0]);
6719   if (gpr_write & prev_gpr_read)
6720     return FALSE;
6721
6722   /* If one instruction sets a condition code and the
6723      other one uses a condition code, we can not swap.  */
6724   pinfo = ip->insn_mo->pinfo;
6725   if ((pinfo & INSN_READ_COND_CODE)
6726       && (prev_pinfo & INSN_WRITE_COND_CODE))
6727     return FALSE;
6728   if ((pinfo & INSN_WRITE_COND_CODE)
6729       && (prev_pinfo & INSN_READ_COND_CODE))
6730     return FALSE;
6731
6732   /* If the previous instruction uses the PC, we can not swap.  */
6733   prev_pinfo2 = history[0].insn_mo->pinfo2;
6734   if (prev_pinfo2 & INSN2_READ_PC)
6735     return FALSE;
6736
6737   /* If the previous instruction has an incorrect size for a fixed
6738      branch delay slot in microMIPS mode, we cannot swap.  */
6739   pinfo2 = ip->insn_mo->pinfo2;
6740   if (mips_opts.micromips
6741       && (pinfo2 & INSN2_BRANCH_DELAY_16BIT)
6742       && insn_length (history) != 2)
6743     return FALSE;
6744   if (mips_opts.micromips
6745       && (pinfo2 & INSN2_BRANCH_DELAY_32BIT)
6746       && insn_length (history) != 4)
6747     return FALSE;
6748
6749   /* On R5900 short loops need to be fixed by inserting a nop in
6750      the branch delay slots.
6751      A short loop can be terminated too early.  */
6752   if (mips_opts.arch == CPU_R5900
6753       /* Check if instruction has a parameter, ignore "j $31". */
6754       && (address_expr != NULL)
6755       /* Parameter must be 16 bit. */
6756       && (*reloc_type == BFD_RELOC_16_PCREL_S2)
6757       /* Branch to same segment. */
6758       && (S_GET_SEGMENT (address_expr->X_add_symbol) == now_seg)
6759       /* Branch to same code fragment. */
6760       && (symbol_get_frag (address_expr->X_add_symbol) == frag_now)
6761       /* Can only calculate branch offset if value is known. */
6762       && symbol_constant_p (address_expr->X_add_symbol)
6763       /* Check if branch is really conditional. */
6764       && !((ip->insn_opcode & 0xffff0000) == 0x10000000   /* beq $0,$0 */
6765         || (ip->insn_opcode & 0xffff0000) == 0x04010000   /* bgez $0 */
6766         || (ip->insn_opcode & 0xffff0000) == 0x04110000)) /* bgezal $0 */
6767     {
6768       int distance;
6769       /* Check if loop is shorter than 6 instructions including
6770          branch and delay slot.  */
6771       distance = frag_now_fix () - S_GET_VALUE (address_expr->X_add_symbol);
6772       if (distance <= 20)
6773         {
6774           int i;
6775           int rv;
6776
6777           rv = FALSE;
6778           /* When the loop includes branches or jumps,
6779              it is not a short loop. */
6780           for (i = 0; i < (distance / 4); i++)
6781             {
6782               if ((history[i].cleared_p)
6783                   || delayed_branch_p (&history[i]))
6784                 {
6785                   rv = TRUE;
6786                   break;
6787                 }
6788             }
6789           if (rv == FALSE)
6790             {
6791               /* Insert nop after branch to fix short loop. */
6792               return FALSE;
6793             }
6794         }
6795     }
6796
6797   return TRUE;
6798 }
6799
6800 /* Decide how we should add IP to the instruction stream.
6801    ADDRESS_EXPR is an operand of the instruction to be used with
6802    RELOC_TYPE.  */
6803
6804 static enum append_method
6805 get_append_method (struct mips_cl_insn *ip, expressionS *address_expr,
6806                    bfd_reloc_code_real_type *reloc_type)
6807 {
6808   /* The relaxed version of a macro sequence must be inherently
6809      hazard-free.  */
6810   if (mips_relax.sequence == 2)
6811     return APPEND_ADD;
6812
6813   /* We must not dabble with instructions in a ".set noreorder" block.  */
6814   if (mips_opts.noreorder)
6815     return APPEND_ADD;
6816
6817   /* Otherwise, it's our responsibility to fill branch delay slots.  */
6818   if (delayed_branch_p (ip))
6819     {
6820       if (!branch_likely_p (ip)
6821           && can_swap_branch_p (ip, address_expr, reloc_type))
6822         return APPEND_SWAP;
6823
6824       if (mips_opts.mips16
6825           && ISA_SUPPORTS_MIPS16E
6826           && gpr_read_mask (ip) != 0)
6827         return APPEND_ADD_COMPACT;
6828
6829       return APPEND_ADD_WITH_NOP;
6830     }
6831
6832   return APPEND_ADD;
6833 }
6834
6835 /* IP is a MIPS16 instruction whose opcode we have just changed.
6836    Point IP->insn_mo to the new opcode's definition.  */
6837
6838 static void
6839 find_altered_mips16_opcode (struct mips_cl_insn *ip)
6840 {
6841   const struct mips_opcode *mo, *end;
6842
6843   end = &mips16_opcodes[bfd_mips16_num_opcodes];
6844   for (mo = ip->insn_mo; mo < end; mo++)
6845     if ((ip->insn_opcode & mo->mask) == mo->match)
6846       {
6847         ip->insn_mo = mo;
6848         return;
6849       }
6850   abort ();
6851 }
6852
6853 /* For microMIPS macros, we need to generate a local number label
6854    as the target of branches.  */
6855 #define MICROMIPS_LABEL_CHAR            '\037'
6856 static unsigned long micromips_target_label;
6857 static char micromips_target_name[32];
6858
6859 static char *
6860 micromips_label_name (void)
6861 {
6862   char *p = micromips_target_name;
6863   char symbol_name_temporary[24];
6864   unsigned long l;
6865   int i;
6866
6867   if (*p)
6868     return p;
6869
6870   i = 0;
6871   l = micromips_target_label;
6872 #ifdef LOCAL_LABEL_PREFIX
6873   *p++ = LOCAL_LABEL_PREFIX;
6874 #endif
6875   *p++ = 'L';
6876   *p++ = MICROMIPS_LABEL_CHAR;
6877   do
6878     {
6879       symbol_name_temporary[i++] = l % 10 + '0';
6880       l /= 10;
6881     }
6882   while (l != 0);
6883   while (i > 0)
6884     *p++ = symbol_name_temporary[--i];
6885   *p = '\0';
6886
6887   return micromips_target_name;
6888 }
6889
6890 static void
6891 micromips_label_expr (expressionS *label_expr)
6892 {
6893   label_expr->X_op = O_symbol;
6894   label_expr->X_add_symbol = symbol_find_or_make (micromips_label_name ());
6895   label_expr->X_add_number = 0;
6896 }
6897
6898 static void
6899 micromips_label_inc (void)
6900 {
6901   micromips_target_label++;
6902   *micromips_target_name = '\0';
6903 }
6904
6905 static void
6906 micromips_add_label (void)
6907 {
6908   symbolS *s;
6909
6910   s = colon (micromips_label_name ());
6911   micromips_label_inc ();
6912   S_SET_OTHER (s, ELF_ST_SET_MICROMIPS (S_GET_OTHER (s)));
6913 }
6914
6915 /* If assembling microMIPS code, then return the microMIPS reloc
6916    corresponding to the requested one if any.  Otherwise return
6917    the reloc unchanged.  */
6918
6919 static bfd_reloc_code_real_type
6920 micromips_map_reloc (bfd_reloc_code_real_type reloc)
6921 {
6922   static const bfd_reloc_code_real_type relocs[][2] =
6923     {
6924       /* Keep sorted incrementally by the left-hand key.  */
6925       { BFD_RELOC_16_PCREL_S2, BFD_RELOC_MICROMIPS_16_PCREL_S1 },
6926       { BFD_RELOC_GPREL16, BFD_RELOC_MICROMIPS_GPREL16 },
6927       { BFD_RELOC_MIPS_JMP, BFD_RELOC_MICROMIPS_JMP },
6928       { BFD_RELOC_HI16, BFD_RELOC_MICROMIPS_HI16 },
6929       { BFD_RELOC_HI16_S, BFD_RELOC_MICROMIPS_HI16_S },
6930       { BFD_RELOC_LO16, BFD_RELOC_MICROMIPS_LO16 },
6931       { BFD_RELOC_MIPS_LITERAL, BFD_RELOC_MICROMIPS_LITERAL },
6932       { BFD_RELOC_MIPS_GOT16, BFD_RELOC_MICROMIPS_GOT16 },
6933       { BFD_RELOC_MIPS_CALL16, BFD_RELOC_MICROMIPS_CALL16 },
6934       { BFD_RELOC_MIPS_GOT_HI16, BFD_RELOC_MICROMIPS_GOT_HI16 },
6935       { BFD_RELOC_MIPS_GOT_LO16, BFD_RELOC_MICROMIPS_GOT_LO16 },
6936       { BFD_RELOC_MIPS_CALL_HI16, BFD_RELOC_MICROMIPS_CALL_HI16 },
6937       { BFD_RELOC_MIPS_CALL_LO16, BFD_RELOC_MICROMIPS_CALL_LO16 },
6938       { BFD_RELOC_MIPS_SUB, BFD_RELOC_MICROMIPS_SUB },
6939       { BFD_RELOC_MIPS_GOT_PAGE, BFD_RELOC_MICROMIPS_GOT_PAGE },
6940       { BFD_RELOC_MIPS_GOT_OFST, BFD_RELOC_MICROMIPS_GOT_OFST },
6941       { BFD_RELOC_MIPS_GOT_DISP, BFD_RELOC_MICROMIPS_GOT_DISP },
6942       { BFD_RELOC_MIPS_HIGHEST, BFD_RELOC_MICROMIPS_HIGHEST },
6943       { BFD_RELOC_MIPS_HIGHER, BFD_RELOC_MICROMIPS_HIGHER },
6944       { BFD_RELOC_MIPS_SCN_DISP, BFD_RELOC_MICROMIPS_SCN_DISP },
6945       { BFD_RELOC_MIPS_TLS_GD, BFD_RELOC_MICROMIPS_TLS_GD },
6946       { BFD_RELOC_MIPS_TLS_LDM, BFD_RELOC_MICROMIPS_TLS_LDM },
6947       { BFD_RELOC_MIPS_TLS_DTPREL_HI16, BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16 },
6948       { BFD_RELOC_MIPS_TLS_DTPREL_LO16, BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16 },
6949       { BFD_RELOC_MIPS_TLS_GOTTPREL, BFD_RELOC_MICROMIPS_TLS_GOTTPREL },
6950       { BFD_RELOC_MIPS_TLS_TPREL_HI16, BFD_RELOC_MICROMIPS_TLS_TPREL_HI16 },
6951       { BFD_RELOC_MIPS_TLS_TPREL_LO16, BFD_RELOC_MICROMIPS_TLS_TPREL_LO16 }
6952     };
6953   bfd_reloc_code_real_type r;
6954   size_t i;
6955
6956   if (!mips_opts.micromips)
6957     return reloc;
6958   for (i = 0; i < ARRAY_SIZE (relocs); i++)
6959     {
6960       r = relocs[i][0];
6961       if (r > reloc)
6962         return reloc;
6963       if (r == reloc)
6964         return relocs[i][1];
6965     }
6966   return reloc;
6967 }
6968
6969 /* Try to resolve relocation RELOC against constant OPERAND at assembly time.
6970    Return true on success, storing the resolved value in RESULT.  */
6971
6972 static bfd_boolean
6973 calculate_reloc (bfd_reloc_code_real_type reloc, offsetT operand,
6974                  offsetT *result)
6975 {
6976   switch (reloc)
6977     {
6978     case BFD_RELOC_MIPS_HIGHEST:
6979     case BFD_RELOC_MICROMIPS_HIGHEST:
6980       *result = ((operand + 0x800080008000ull) >> 48) & 0xffff;
6981       return TRUE;
6982
6983     case BFD_RELOC_MIPS_HIGHER:
6984     case BFD_RELOC_MICROMIPS_HIGHER:
6985       *result = ((operand + 0x80008000ull) >> 32) & 0xffff;
6986       return TRUE;
6987
6988     case BFD_RELOC_HI16_S:
6989     case BFD_RELOC_HI16_S_PCREL:
6990     case BFD_RELOC_MICROMIPS_HI16_S:
6991     case BFD_RELOC_MIPS16_HI16_S:
6992       *result = ((operand + 0x8000) >> 16) & 0xffff;
6993       return TRUE;
6994
6995     case BFD_RELOC_HI16:
6996     case BFD_RELOC_MICROMIPS_HI16:
6997     case BFD_RELOC_MIPS16_HI16:
6998       *result = (operand >> 16) & 0xffff;
6999       return TRUE;
7000
7001     case BFD_RELOC_LO16:
7002     case BFD_RELOC_LO16_PCREL:
7003     case BFD_RELOC_MICROMIPS_LO16:
7004     case BFD_RELOC_MIPS16_LO16:
7005       *result = operand & 0xffff;
7006       return TRUE;
7007
7008     case BFD_RELOC_UNUSED:
7009       *result = operand;
7010       return TRUE;
7011
7012     default:
7013       return FALSE;
7014     }
7015 }
7016
7017 /* Output an instruction.  IP is the instruction information.
7018    ADDRESS_EXPR is an operand of the instruction to be used with
7019    RELOC_TYPE.  EXPANSIONP is true if the instruction is part of
7020    a macro expansion.  */
7021
7022 static void
7023 append_insn (struct mips_cl_insn *ip, expressionS *address_expr,
7024              bfd_reloc_code_real_type *reloc_type, bfd_boolean expansionp)
7025 {
7026   unsigned long prev_pinfo2, pinfo;
7027   bfd_boolean relaxed_branch = FALSE;
7028   enum append_method method;
7029   bfd_boolean relax32;
7030   int branch_disp;
7031
7032   if (mips_fix_loongson2f && !HAVE_CODE_COMPRESSION)
7033     fix_loongson2f (ip);
7034
7035   file_ase_mips16 |= mips_opts.mips16;
7036   file_ase_micromips |= mips_opts.micromips;
7037
7038   prev_pinfo2 = history[0].insn_mo->pinfo2;
7039   pinfo = ip->insn_mo->pinfo;
7040
7041   if (mips_opts.micromips
7042       && !expansionp
7043       && (((prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0
7044            && micromips_insn_length (ip->insn_mo) != 2)
7045           || ((prev_pinfo2 & INSN2_BRANCH_DELAY_32BIT) != 0
7046               && micromips_insn_length (ip->insn_mo) != 4)))
7047     as_warn (_("wrong size instruction in a %u-bit branch delay slot"),
7048              (prev_pinfo2 & INSN2_BRANCH_DELAY_16BIT) != 0 ? 16 : 32);
7049
7050   if (address_expr == NULL)
7051     ip->complete_p = 1;
7052   else if (reloc_type[0] <= BFD_RELOC_UNUSED
7053            && reloc_type[1] == BFD_RELOC_UNUSED
7054            && reloc_type[2] == BFD_RELOC_UNUSED
7055            && address_expr->X_op == O_constant)
7056     {
7057       switch (*reloc_type)
7058         {
7059         case BFD_RELOC_MIPS_JMP:
7060           {
7061             int shift;
7062
7063             /* Shift is 2, unusually, for microMIPS JALX.  */
7064             shift = (mips_opts.micromips
7065                      && strcmp (ip->insn_mo->name, "jalx") != 0) ? 1 : 2;
7066             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7067               as_bad (_("jump to misaligned address (0x%lx)"),
7068                       (unsigned long) address_expr->X_add_number);
7069             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7070                                 & 0x3ffffff);
7071             ip->complete_p = 1;
7072           }
7073           break;
7074
7075         case BFD_RELOC_MIPS16_JMP:
7076           if ((address_expr->X_add_number & 3) != 0)
7077             as_bad (_("jump to misaligned address (0x%lx)"),
7078                     (unsigned long) address_expr->X_add_number);
7079           ip->insn_opcode |=
7080             (((address_expr->X_add_number & 0x7c0000) << 3)
7081                | ((address_expr->X_add_number & 0xf800000) >> 7)
7082                | ((address_expr->X_add_number & 0x3fffc) >> 2));
7083           ip->complete_p = 1;
7084           break;
7085
7086         case BFD_RELOC_16_PCREL_S2:
7087           {
7088             int shift;
7089
7090             shift = mips_opts.micromips ? 1 : 2;
7091             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7092               as_bad (_("branch to misaligned address (0x%lx)"),
7093                       (unsigned long) address_expr->X_add_number);
7094             if (!mips_relax_branch)
7095               {
7096                 if ((address_expr->X_add_number + (1 << (shift + 15)))
7097                     & ~((1 << (shift + 16)) - 1))
7098                   as_bad (_("branch address range overflow (0x%lx)"),
7099                           (unsigned long) address_expr->X_add_number);
7100                 ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7101                                     & 0xffff);
7102               }
7103           }
7104           break;
7105
7106         case BFD_RELOC_MIPS_21_PCREL_S2:
7107           {
7108             int shift;
7109
7110             shift = 2;
7111             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7112               as_bad (_("branch to misaligned address (0x%lx)"),
7113                       (unsigned long) address_expr->X_add_number);
7114             if ((address_expr->X_add_number + (1 << (shift + 20)))
7115                 & ~((1 << (shift + 21)) - 1))
7116               as_bad (_("branch address range overflow (0x%lx)"),
7117                       (unsigned long) address_expr->X_add_number);
7118             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7119                                 & 0x1fffff);
7120           }
7121           break;
7122
7123         case BFD_RELOC_MIPS_26_PCREL_S2:
7124           {
7125             int shift;
7126
7127             shift = 2;
7128             if ((address_expr->X_add_number & ((1 << shift) - 1)) != 0)
7129               as_bad (_("branch to misaligned address (0x%lx)"),
7130                       (unsigned long) address_expr->X_add_number);
7131             if ((address_expr->X_add_number + (1 << (shift + 25)))
7132                 & ~((1 << (shift + 26)) - 1))
7133               as_bad (_("branch address range overflow (0x%lx)"),
7134                       (unsigned long) address_expr->X_add_number);
7135             ip->insn_opcode |= ((address_expr->X_add_number >> shift)
7136                                 & 0x3ffffff);
7137           }
7138           break;
7139
7140         default:
7141           {
7142             offsetT value;
7143
7144             if (calculate_reloc (*reloc_type, address_expr->X_add_number,
7145                                  &value))
7146               {
7147                 ip->insn_opcode |= value & 0xffff;
7148                 ip->complete_p = 1;
7149               }
7150           }
7151           break;
7152         }
7153     }
7154
7155   if (mips_relax.sequence != 2 && !mips_opts.noreorder)
7156     {
7157       /* There are a lot of optimizations we could do that we don't.
7158          In particular, we do not, in general, reorder instructions.
7159          If you use gcc with optimization, it will reorder
7160          instructions and generally do much more optimization then we
7161          do here; repeating all that work in the assembler would only
7162          benefit hand written assembly code, and does not seem worth
7163          it.  */
7164       int nops = (mips_optimize == 0
7165                   ? nops_for_insn (0, history, NULL)
7166                   : nops_for_insn_or_target (0, history, ip));
7167       if (nops > 0)
7168         {
7169           fragS *old_frag;
7170           unsigned long old_frag_offset;
7171           int i;
7172
7173           old_frag = frag_now;
7174           old_frag_offset = frag_now_fix ();
7175
7176           for (i = 0; i < nops; i++)
7177             add_fixed_insn (NOP_INSN);
7178           insert_into_history (0, nops, NOP_INSN);
7179
7180           if (listing)
7181             {
7182               listing_prev_line ();
7183               /* We may be at the start of a variant frag.  In case we
7184                  are, make sure there is enough space for the frag
7185                  after the frags created by listing_prev_line.  The
7186                  argument to frag_grow here must be at least as large
7187                  as the argument to all other calls to frag_grow in
7188                  this file.  We don't have to worry about being in the
7189                  middle of a variant frag, because the variants insert
7190                  all needed nop instructions themselves.  */
7191               frag_grow (40);
7192             }
7193
7194           mips_move_text_labels ();
7195
7196 #ifndef NO_ECOFF_DEBUGGING
7197           if (ECOFF_DEBUGGING)
7198             ecoff_fix_loc (old_frag, old_frag_offset);
7199 #endif
7200         }
7201     }
7202   else if (mips_relax.sequence != 2 && prev_nop_frag != NULL)
7203     {
7204       int nops;
7205
7206       /* Work out how many nops in prev_nop_frag are needed by IP,
7207          ignoring hazards generated by the first prev_nop_frag_since
7208          instructions.  */
7209       nops = nops_for_insn_or_target (prev_nop_frag_since, history, ip);
7210       gas_assert (nops <= prev_nop_frag_holds);
7211
7212       /* Enforce NOPS as a minimum.  */
7213       if (nops > prev_nop_frag_required)
7214         prev_nop_frag_required = nops;
7215
7216       if (prev_nop_frag_holds == prev_nop_frag_required)
7217         {
7218           /* Settle for the current number of nops.  Update the history
7219              accordingly (for the benefit of any future .set reorder code).  */
7220           prev_nop_frag = NULL;
7221           insert_into_history (prev_nop_frag_since,
7222                                prev_nop_frag_holds, NOP_INSN);
7223         }
7224       else
7225         {
7226           /* Allow this instruction to replace one of the nops that was
7227              tentatively added to prev_nop_frag.  */
7228           prev_nop_frag->fr_fix -= NOP_INSN_SIZE;
7229           prev_nop_frag_holds--;
7230           prev_nop_frag_since++;
7231         }
7232     }
7233
7234   method = get_append_method (ip, address_expr, reloc_type);
7235   branch_disp = method == APPEND_SWAP ? insn_length (history) : 0;
7236
7237   dwarf2_emit_insn (0);
7238   /* We want MIPS16 and microMIPS debug info to use ISA-encoded addresses,
7239      so "move" the instruction address accordingly.
7240
7241      Also, it doesn't seem appropriate for the assembler to reorder .loc
7242      entries.  If this instruction is a branch that we are going to swap
7243      with the previous instruction, the two instructions should be
7244      treated as a unit, and the debug information for both instructions
7245      should refer to the start of the branch sequence.  Using the
7246      current position is certainly wrong when swapping a 32-bit branch
7247      and a 16-bit delay slot, since the current position would then be
7248      in the middle of a branch.  */
7249   dwarf2_move_insn ((HAVE_CODE_COMPRESSION ? 1 : 0) - branch_disp);
7250
7251   relax32 = (mips_relax_branch
7252              /* Don't try branch relaxation within .set nomacro, or within
7253                 .set noat if we use $at for PIC computations.  If it turns
7254                 out that the branch was out-of-range, we'll get an error.  */
7255              && !mips_opts.warn_about_macros
7256              && (mips_opts.at || mips_pic == NO_PIC)
7257              /* Don't relax BPOSGE32/64 or BC1ANY2T/F and BC1ANY4T/F
7258                 as they have no complementing branches.  */
7259              && !(ip->insn_mo->ase & (ASE_MIPS3D | ASE_DSP64 | ASE_DSP)));
7260
7261   if (!HAVE_CODE_COMPRESSION
7262       && address_expr
7263       && relax32
7264       && *reloc_type == BFD_RELOC_16_PCREL_S2
7265       && delayed_branch_p (ip))
7266     {
7267       relaxed_branch = TRUE;
7268       add_relaxed_insn (ip, (relaxed_branch_length
7269                              (NULL, NULL,
7270                               uncond_branch_p (ip) ? -1
7271                               : branch_likely_p (ip) ? 1
7272                               : 0)), 4,
7273                         RELAX_BRANCH_ENCODE
7274                         (AT,
7275                          uncond_branch_p (ip),
7276                          branch_likely_p (ip),
7277                          pinfo & INSN_WRITE_GPR_31,
7278                          0),
7279                         address_expr->X_add_symbol,
7280                         address_expr->X_add_number);
7281       *reloc_type = BFD_RELOC_UNUSED;
7282     }
7283   else if (mips_opts.micromips
7284            && address_expr
7285            && ((relax32 && *reloc_type == BFD_RELOC_16_PCREL_S2)
7286                || *reloc_type > BFD_RELOC_UNUSED)
7287            && (delayed_branch_p (ip) || compact_branch_p (ip))
7288            /* Don't try branch relaxation when users specify
7289               16-bit/32-bit instructions.  */
7290            && !forced_insn_length)
7291     {
7292       bfd_boolean relax16 = *reloc_type > BFD_RELOC_UNUSED;
7293       int type = relax16 ? *reloc_type - BFD_RELOC_UNUSED : 0;
7294       int uncond = uncond_branch_p (ip) ? -1 : 0;
7295       int compact = compact_branch_p (ip);
7296       int al = pinfo & INSN_WRITE_GPR_31;
7297       int length32;
7298
7299       gas_assert (address_expr != NULL);
7300       gas_assert (!mips_relax.sequence);
7301
7302       relaxed_branch = TRUE;
7303       length32 = relaxed_micromips_32bit_branch_length (NULL, NULL, uncond);
7304       add_relaxed_insn (ip, relax32 ? length32 : 4, relax16 ? 2 : 4,
7305                         RELAX_MICROMIPS_ENCODE (type, AT, uncond, compact, al,
7306                                                 relax32, 0, 0),
7307                         address_expr->X_add_symbol,
7308                         address_expr->X_add_number);
7309       *reloc_type = BFD_RELOC_UNUSED;
7310     }
7311   else if (mips_opts.mips16 && *reloc_type > BFD_RELOC_UNUSED)
7312     {
7313       symbolS *symbol;
7314       offsetT offset;
7315
7316       /* We need to set up a variant frag.  */
7317       gas_assert (address_expr != NULL);
7318       /* Pass any `O_symbol' expression unchanged as an `expr_section'
7319          symbol created by `make_expr_symbol' may not get a necessary
7320          external relocation produced.  */
7321       if (address_expr->X_op == O_symbol)
7322         {
7323           symbol = address_expr->X_add_symbol;
7324           offset = address_expr->X_add_number;
7325         }
7326       else
7327         {
7328           symbol = make_expr_symbol (address_expr);
7329           offset = 0;
7330         }
7331       add_relaxed_insn (ip, 4, 0,
7332                         RELAX_MIPS16_ENCODE
7333                         (*reloc_type - BFD_RELOC_UNUSED,
7334                          forced_insn_length == 2, forced_insn_length == 4,
7335                          delayed_branch_p (&history[0]),
7336                          history[0].mips16_absolute_jump_p),
7337                         symbol, offset);
7338     }
7339   else if (mips_opts.mips16 && insn_length (ip) == 2)
7340     {
7341       if (!delayed_branch_p (ip))
7342         /* Make sure there is enough room to swap this instruction with
7343            a following jump instruction.  */
7344         frag_grow (6);
7345       add_fixed_insn (ip);
7346     }
7347   else
7348     {
7349       if (mips_opts.mips16
7350           && mips_opts.noreorder
7351           && delayed_branch_p (&history[0]))
7352         as_warn (_("extended instruction in delay slot"));
7353
7354       if (mips_relax.sequence)
7355         {
7356           /* If we've reached the end of this frag, turn it into a variant
7357              frag and record the information for the instructions we've
7358              written so far.  */
7359           if (frag_room () < 4)
7360             relax_close_frag ();
7361           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (ip);
7362         }
7363
7364       if (mips_relax.sequence != 2)
7365         {
7366           if (mips_macro_warning.first_insn_sizes[0] == 0)
7367             mips_macro_warning.first_insn_sizes[0] = insn_length (ip);
7368           mips_macro_warning.sizes[0] += insn_length (ip);
7369           mips_macro_warning.insns[0]++;
7370         }
7371       if (mips_relax.sequence != 1)
7372         {
7373           if (mips_macro_warning.first_insn_sizes[1] == 0)
7374             mips_macro_warning.first_insn_sizes[1] = insn_length (ip);
7375           mips_macro_warning.sizes[1] += insn_length (ip);
7376           mips_macro_warning.insns[1]++;
7377         }
7378
7379       if (mips_opts.mips16)
7380         {
7381           ip->fixed_p = 1;
7382           ip->mips16_absolute_jump_p = (*reloc_type == BFD_RELOC_MIPS16_JMP);
7383         }
7384       add_fixed_insn (ip);
7385     }
7386
7387   if (!ip->complete_p && *reloc_type < BFD_RELOC_UNUSED)
7388     {
7389       bfd_reloc_code_real_type final_type[3];
7390       reloc_howto_type *howto0;
7391       reloc_howto_type *howto;
7392       int i;
7393
7394       /* Perform any necessary conversion to microMIPS relocations
7395          and find out how many relocations there actually are.  */
7396       for (i = 0; i < 3 && reloc_type[i] != BFD_RELOC_UNUSED; i++)
7397         final_type[i] = micromips_map_reloc (reloc_type[i]);
7398
7399       /* In a compound relocation, it is the final (outermost)
7400          operator that determines the relocated field.  */
7401       howto = howto0 = bfd_reloc_type_lookup (stdoutput, final_type[i - 1]);
7402       if (!howto)
7403         abort ();
7404
7405       if (i > 1)
7406         howto0 = bfd_reloc_type_lookup (stdoutput, final_type[0]);
7407       ip->fixp[0] = fix_new_exp (ip->frag, ip->where,
7408                                  bfd_get_reloc_size (howto),
7409                                  address_expr,
7410                                  howto0 && howto0->pc_relative,
7411                                  final_type[0]);
7412
7413       /* Tag symbols that have a R_MIPS16_26 relocation against them.  */
7414       if (final_type[0] == BFD_RELOC_MIPS16_JMP && ip->fixp[0]->fx_addsy)
7415         *symbol_get_tc (ip->fixp[0]->fx_addsy) = 1;
7416
7417       /* These relocations can have an addend that won't fit in
7418          4 octets for 64bit assembly.  */
7419       if (GPR_SIZE == 64
7420           && ! howto->partial_inplace
7421           && (reloc_type[0] == BFD_RELOC_16
7422               || reloc_type[0] == BFD_RELOC_32
7423               || reloc_type[0] == BFD_RELOC_MIPS_JMP
7424               || reloc_type[0] == BFD_RELOC_GPREL16
7425               || reloc_type[0] == BFD_RELOC_MIPS_LITERAL
7426               || reloc_type[0] == BFD_RELOC_GPREL32
7427               || reloc_type[0] == BFD_RELOC_64
7428               || reloc_type[0] == BFD_RELOC_CTOR
7429               || reloc_type[0] == BFD_RELOC_MIPS_SUB
7430               || reloc_type[0] == BFD_RELOC_MIPS_HIGHEST
7431               || reloc_type[0] == BFD_RELOC_MIPS_HIGHER
7432               || reloc_type[0] == BFD_RELOC_MIPS_SCN_DISP
7433               || reloc_type[0] == BFD_RELOC_MIPS_REL16
7434               || reloc_type[0] == BFD_RELOC_MIPS_RELGOT
7435               || reloc_type[0] == BFD_RELOC_MIPS16_GPREL
7436               || hi16_reloc_p (reloc_type[0])
7437               || lo16_reloc_p (reloc_type[0])))
7438         ip->fixp[0]->fx_no_overflow = 1;
7439
7440       /* These relocations can have an addend that won't fit in 2 octets.  */
7441       if (reloc_type[0] == BFD_RELOC_MICROMIPS_7_PCREL_S1
7442           || reloc_type[0] == BFD_RELOC_MICROMIPS_10_PCREL_S1)
7443         ip->fixp[0]->fx_no_overflow = 1;
7444
7445       if (mips_relax.sequence)
7446         {
7447           if (mips_relax.first_fixup == 0)
7448             mips_relax.first_fixup = ip->fixp[0];
7449         }
7450       else if (reloc_needs_lo_p (*reloc_type))
7451         {
7452           struct mips_hi_fixup *hi_fixup;
7453
7454           /* Reuse the last entry if it already has a matching %lo.  */
7455           hi_fixup = mips_hi_fixup_list;
7456           if (hi_fixup == 0
7457               || !fixup_has_matching_lo_p (hi_fixup->fixp))
7458             {
7459               hi_fixup = XNEW (struct mips_hi_fixup);
7460               hi_fixup->next = mips_hi_fixup_list;
7461               mips_hi_fixup_list = hi_fixup;
7462             }
7463           hi_fixup->fixp = ip->fixp[0];
7464           hi_fixup->seg = now_seg;
7465         }
7466
7467       /* Add fixups for the second and third relocations, if given.
7468          Note that the ABI allows the second relocation to be
7469          against RSS_UNDEF, RSS_GP, RSS_GP0 or RSS_LOC.  At the
7470          moment we only use RSS_UNDEF, but we could add support
7471          for the others if it ever becomes necessary.  */
7472       for (i = 1; i < 3; i++)
7473         if (reloc_type[i] != BFD_RELOC_UNUSED)
7474           {
7475             ip->fixp[i] = fix_new (ip->frag, ip->where,
7476                                    ip->fixp[0]->fx_size, NULL, 0,
7477                                    FALSE, final_type[i]);
7478
7479             /* Use fx_tcbit to mark compound relocs.  */
7480             ip->fixp[0]->fx_tcbit = 1;
7481             ip->fixp[i]->fx_tcbit = 1;
7482           }
7483     }
7484
7485   /* Update the register mask information.  */
7486   mips_gprmask |= gpr_read_mask (ip) | gpr_write_mask (ip);
7487   mips_cprmask[1] |= fpr_read_mask (ip) | fpr_write_mask (ip);
7488
7489   switch (method)
7490     {
7491     case APPEND_ADD:
7492       insert_into_history (0, 1, ip);
7493       break;
7494
7495     case APPEND_ADD_WITH_NOP:
7496       {
7497         struct mips_cl_insn *nop;
7498
7499         insert_into_history (0, 1, ip);
7500         nop = get_delay_slot_nop (ip);
7501         add_fixed_insn (nop);
7502         insert_into_history (0, 1, nop);
7503         if (mips_relax.sequence)
7504           mips_relax.sizes[mips_relax.sequence - 1] += insn_length (nop);
7505       }
7506       break;
7507
7508     case APPEND_ADD_COMPACT:
7509       /* Convert MIPS16 jr/jalr into a "compact" jump.  */
7510       gas_assert (mips_opts.mips16);
7511       ip->insn_opcode |= 0x0080;
7512       find_altered_mips16_opcode (ip);
7513       install_insn (ip);
7514       insert_into_history (0, 1, ip);
7515       break;
7516
7517     case APPEND_SWAP:
7518       {
7519         struct mips_cl_insn delay = history[0];
7520
7521         if (relaxed_branch || delay.frag != ip->frag)
7522           {
7523             /* Add the delay slot instruction to the end of the
7524                current frag and shrink the fixed part of the
7525                original frag.  If the branch occupies the tail of
7526                the latter, move it backwards to cover the gap.  */
7527             delay.frag->fr_fix -= branch_disp;
7528             if (delay.frag == ip->frag)
7529               move_insn (ip, ip->frag, ip->where - branch_disp);
7530             add_fixed_insn (&delay);
7531           }
7532         else
7533           {
7534             /* If this is not a relaxed branch and we are in the
7535                same frag, then just swap the instructions.  */
7536             move_insn (ip, delay.frag, delay.where);
7537             move_insn (&delay, ip->frag, ip->where + insn_length (ip));
7538           }
7539         history[0] = *ip;
7540         delay.fixed_p = 1;
7541         insert_into_history (0, 1, &delay);
7542       }
7543       break;
7544     }
7545
7546   /* If we have just completed an unconditional branch, clear the history.  */
7547   if ((delayed_branch_p (&history[1]) && uncond_branch_p (&history[1]))
7548       || (compact_branch_p (&history[0]) && uncond_branch_p (&history[0])))
7549     {
7550       unsigned int i;
7551
7552       mips_no_prev_insn ();
7553
7554       for (i = 0; i < ARRAY_SIZE (history); i++)
7555         history[i].cleared_p = 1;
7556     }
7557
7558   /* We need to emit a label at the end of branch-likely macros.  */
7559   if (emit_branch_likely_macro)
7560     {
7561       emit_branch_likely_macro = FALSE;
7562       micromips_add_label ();
7563     }
7564
7565   /* We just output an insn, so the next one doesn't have a label.  */
7566   mips_clear_insn_labels ();
7567 }
7568
7569 /* Forget that there was any previous instruction or label.
7570    When BRANCH is true, the branch history is also flushed.  */
7571
7572 static void
7573 mips_no_prev_insn (void)
7574 {
7575   prev_nop_frag = NULL;
7576   insert_into_history (0, ARRAY_SIZE (history), NOP_INSN);
7577   mips_clear_insn_labels ();
7578 }
7579
7580 /* This function must be called before we emit something other than
7581    instructions.  It is like mips_no_prev_insn except that it inserts
7582    any NOPS that might be needed by previous instructions.  */
7583
7584 void
7585 mips_emit_delays (void)
7586 {
7587   if (! mips_opts.noreorder)
7588     {
7589       int nops = nops_for_insn (0, history, NULL);
7590       if (nops > 0)
7591         {
7592           while (nops-- > 0)
7593             add_fixed_insn (NOP_INSN);
7594           mips_move_text_labels ();
7595         }
7596     }
7597   mips_no_prev_insn ();
7598 }
7599
7600 /* Start a (possibly nested) noreorder block.  */
7601
7602 static void
7603 start_noreorder (void)
7604 {
7605   if (mips_opts.noreorder == 0)
7606     {
7607       unsigned int i;
7608       int nops;
7609
7610       /* None of the instructions before the .set noreorder can be moved.  */
7611       for (i = 0; i < ARRAY_SIZE (history); i++)
7612         history[i].fixed_p = 1;
7613
7614       /* Insert any nops that might be needed between the .set noreorder
7615          block and the previous instructions.  We will later remove any
7616          nops that turn out not to be needed.  */
7617       nops = nops_for_insn (0, history, NULL);
7618       if (nops > 0)
7619         {
7620           if (mips_optimize != 0)
7621             {
7622               /* Record the frag which holds the nop instructions, so
7623                  that we can remove them if we don't need them.  */
7624               frag_grow (nops * NOP_INSN_SIZE);
7625               prev_nop_frag = frag_now;
7626               prev_nop_frag_holds = nops;
7627               prev_nop_frag_required = 0;
7628               prev_nop_frag_since = 0;
7629             }
7630
7631           for (; nops > 0; --nops)
7632             add_fixed_insn (NOP_INSN);
7633
7634           /* Move on to a new frag, so that it is safe to simply
7635              decrease the size of prev_nop_frag.  */
7636           frag_wane (frag_now);
7637           frag_new (0);
7638           mips_move_text_labels ();
7639         }
7640       mips_mark_labels ();
7641       mips_clear_insn_labels ();
7642     }
7643   mips_opts.noreorder++;
7644   mips_any_noreorder = 1;
7645 }
7646
7647 /* End a nested noreorder block.  */
7648
7649 static void
7650 end_noreorder (void)
7651 {
7652   mips_opts.noreorder--;
7653   if (mips_opts.noreorder == 0 && prev_nop_frag != NULL)
7654     {
7655       /* Commit to inserting prev_nop_frag_required nops and go back to
7656          handling nop insertion the .set reorder way.  */
7657       prev_nop_frag->fr_fix -= ((prev_nop_frag_holds - prev_nop_frag_required)
7658                                 * NOP_INSN_SIZE);
7659       insert_into_history (prev_nop_frag_since,
7660                            prev_nop_frag_required, NOP_INSN);
7661       prev_nop_frag = NULL;
7662     }
7663 }
7664
7665 /* Sign-extend 32-bit mode constants that have bit 31 set and all
7666    higher bits unset.  */
7667
7668 static void
7669 normalize_constant_expr (expressionS *ex)
7670 {
7671   if (ex->X_op == O_constant
7672       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7673     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7674                         - 0x80000000);
7675 }
7676
7677 /* Sign-extend 32-bit mode address offsets that have bit 31 set and
7678    all higher bits unset.  */
7679
7680 static void
7681 normalize_address_expr (expressionS *ex)
7682 {
7683   if (((ex->X_op == O_constant && HAVE_32BIT_ADDRESSES)
7684         || (ex->X_op == O_symbol && HAVE_32BIT_SYMBOLS))
7685       && IS_ZEXT_32BIT_NUM (ex->X_add_number))
7686     ex->X_add_number = (((ex->X_add_number & 0xffffffff) ^ 0x80000000)
7687                         - 0x80000000);
7688 }
7689
7690 /* Try to match TOKENS against OPCODE, storing the result in INSN.
7691    Return true if the match was successful.
7692
7693    OPCODE_EXTRA is a value that should be ORed into the opcode
7694    (used for VU0 channel suffixes, etc.).  MORE_ALTS is true if
7695    there are more alternatives after OPCODE and SOFT_MATCH is
7696    as for mips_arg_info.  */
7697
7698 static bfd_boolean
7699 match_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7700             struct mips_operand_token *tokens, unsigned int opcode_extra,
7701             bfd_boolean lax_match, bfd_boolean complete_p)
7702 {
7703   const char *args;
7704   struct mips_arg_info arg;
7705   const struct mips_operand *operand;
7706   char c;
7707
7708   imm_expr.X_op = O_absent;
7709   offset_expr.X_op = O_absent;
7710   offset_reloc[0] = BFD_RELOC_UNUSED;
7711   offset_reloc[1] = BFD_RELOC_UNUSED;
7712   offset_reloc[2] = BFD_RELOC_UNUSED;
7713
7714   create_insn (insn, opcode);
7715   /* When no opcode suffix is specified, assume ".xyzw". */
7716   if ((opcode->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0 && opcode_extra == 0)
7717     insn->insn_opcode |= 0xf << mips_vu0_channel_mask.lsb;
7718   else
7719     insn->insn_opcode |= opcode_extra;
7720   memset (&arg, 0, sizeof (arg));
7721   arg.insn = insn;
7722   arg.token = tokens;
7723   arg.argnum = 1;
7724   arg.last_regno = ILLEGAL_REG;
7725   arg.dest_regno = ILLEGAL_REG;
7726   arg.lax_match = lax_match;
7727   for (args = opcode->args;; ++args)
7728     {
7729       if (arg.token->type == OT_END)
7730         {
7731           /* Handle unary instructions in which only one operand is given.
7732              The source is then the same as the destination.  */
7733           if (arg.opnum == 1 && *args == ',')
7734             {
7735               operand = (mips_opts.micromips
7736                          ? decode_micromips_operand (args + 1)
7737                          : decode_mips_operand (args + 1));
7738               if (operand && mips_optional_operand_p (operand))
7739                 {
7740                   arg.token = tokens;
7741                   arg.argnum = 1;
7742                   continue;
7743                 }
7744             }
7745
7746           /* Treat elided base registers as $0.  */
7747           if (strcmp (args, "(b)") == 0)
7748             args += 3;
7749
7750           if (args[0] == '+')
7751             switch (args[1])
7752               {
7753               case 'K':
7754               case 'N':
7755                 /* The register suffix is optional. */
7756                 args += 2;
7757                 break;
7758               }
7759
7760           /* Fail the match if there were too few operands.  */
7761           if (*args)
7762             return FALSE;
7763
7764           /* Successful match.  */
7765           if (!complete_p)
7766             return TRUE;
7767           clear_insn_error ();
7768           if (arg.dest_regno == arg.last_regno
7769               && strncmp (insn->insn_mo->name, "jalr", 4) == 0)
7770             {
7771               if (arg.opnum == 2)
7772                 set_insn_error
7773                   (0, _("source and destination must be different"));
7774               else if (arg.last_regno == 31)
7775                 set_insn_error
7776                   (0, _("a destination register must be supplied"));
7777             }
7778           else if (arg.last_regno == 31
7779                    && (strncmp (insn->insn_mo->name, "bltzal", 6) == 0
7780                        || strncmp (insn->insn_mo->name, "bgezal", 6) == 0))
7781             set_insn_error (0, _("the source register must not be $31"));
7782           check_completed_insn (&arg);
7783           return TRUE;
7784         }
7785
7786       /* Fail the match if the line has too many operands.   */
7787       if (*args == 0)
7788         return FALSE;
7789
7790       /* Handle characters that need to match exactly.  */
7791       if (*args == '(' || *args == ')' || *args == ',')
7792         {
7793           if (match_char (&arg, *args))
7794             continue;
7795           return FALSE;
7796         }
7797       if (*args == '#')
7798         {
7799           ++args;
7800           if (arg.token->type == OT_DOUBLE_CHAR
7801               && arg.token->u.ch == *args)
7802             {
7803               ++arg.token;
7804               continue;
7805             }
7806           return FALSE;
7807         }
7808
7809       /* Handle special macro operands.  Work out the properties of
7810          other operands.  */
7811       arg.opnum += 1;
7812       switch (*args)
7813         {
7814         case '-':
7815           switch (args[1])
7816             {
7817             case 'A':
7818               *offset_reloc = BFD_RELOC_MIPS_19_PCREL_S2;
7819               break;
7820
7821             case 'B':
7822               *offset_reloc = BFD_RELOC_MIPS_18_PCREL_S3;
7823               break;
7824             }
7825           break;
7826
7827         case '+':
7828           switch (args[1])
7829             {
7830             case 'i':
7831               *offset_reloc = BFD_RELOC_MIPS_JMP;
7832               break;
7833
7834             case '\'':
7835               *offset_reloc = BFD_RELOC_MIPS_26_PCREL_S2;
7836               break;
7837
7838             case '\"':
7839               *offset_reloc = BFD_RELOC_MIPS_21_PCREL_S2;
7840               break;
7841             }
7842           break;
7843
7844         case 'I':
7845           if (!match_const_int (&arg, &imm_expr.X_add_number))
7846             return FALSE;
7847           imm_expr.X_op = O_constant;
7848           if (GPR_SIZE == 32)
7849             normalize_constant_expr (&imm_expr);
7850           continue;
7851
7852         case 'A':
7853           if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
7854             {
7855               /* Assume that the offset has been elided and that what
7856                  we saw was a base register.  The match will fail later
7857                  if that assumption turns out to be wrong.  */
7858               offset_expr.X_op = O_constant;
7859               offset_expr.X_add_number = 0;
7860             }
7861           else
7862             {
7863               if (!match_expression (&arg, &offset_expr, offset_reloc))
7864                 return FALSE;
7865               normalize_address_expr (&offset_expr);
7866             }
7867           continue;
7868
7869         case 'F':
7870           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7871                                      8, TRUE))
7872             return FALSE;
7873           continue;
7874
7875         case 'L':
7876           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7877                                      8, FALSE))
7878             return FALSE;
7879           continue;
7880
7881         case 'f':
7882           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7883                                      4, TRUE))
7884             return FALSE;
7885           continue;
7886
7887         case 'l':
7888           if (!match_float_constant (&arg, &imm_expr, &offset_expr,
7889                                      4, FALSE))
7890             return FALSE;
7891           continue;
7892
7893         case 'p':
7894           *offset_reloc = BFD_RELOC_16_PCREL_S2;
7895           break;
7896
7897         case 'a':
7898           *offset_reloc = BFD_RELOC_MIPS_JMP;
7899           break;
7900
7901         case 'm':
7902           gas_assert (mips_opts.micromips);
7903           c = args[1];
7904           switch (c)
7905             {
7906             case 'D':
7907             case 'E':
7908               if (!forced_insn_length)
7909                 *offset_reloc = (int) BFD_RELOC_UNUSED + c;
7910               else if (c == 'D')
7911                 *offset_reloc = BFD_RELOC_MICROMIPS_10_PCREL_S1;
7912               else
7913                 *offset_reloc = BFD_RELOC_MICROMIPS_7_PCREL_S1;
7914               break;
7915             }
7916           break;
7917         }
7918
7919       operand = (mips_opts.micromips
7920                  ? decode_micromips_operand (args)
7921                  : decode_mips_operand (args));
7922       if (!operand)
7923         abort ();
7924
7925       /* Skip prefixes.  */
7926       if (*args == '+' || *args == 'm' || *args == '-')
7927         args++;
7928
7929       if (mips_optional_operand_p (operand)
7930           && args[1] == ','
7931           && (arg.token[0].type != OT_REG
7932               || arg.token[1].type == OT_END))
7933         {
7934           /* Assume that the register has been elided and is the
7935              same as the first operand.  */
7936           arg.token = tokens;
7937           arg.argnum = 1;
7938         }
7939
7940       if (!match_operand (&arg, operand))
7941         return FALSE;
7942     }
7943 }
7944
7945 /* Like match_insn, but for MIPS16.  */
7946
7947 static bfd_boolean
7948 match_mips16_insn (struct mips_cl_insn *insn, const struct mips_opcode *opcode,
7949                    struct mips_operand_token *tokens)
7950 {
7951   const char *args;
7952   const struct mips_operand *operand;
7953   const struct mips_operand *ext_operand;
7954   struct mips_arg_info arg;
7955   int relax_char;
7956
7957   create_insn (insn, opcode);
7958   imm_expr.X_op = O_absent;
7959   offset_expr.X_op = O_absent;
7960   offset_reloc[0] = BFD_RELOC_UNUSED;
7961   offset_reloc[1] = BFD_RELOC_UNUSED;
7962   offset_reloc[2] = BFD_RELOC_UNUSED;
7963   relax_char = 0;
7964
7965   memset (&arg, 0, sizeof (arg));
7966   arg.insn = insn;
7967   arg.token = tokens;
7968   arg.argnum = 1;
7969   arg.last_regno = ILLEGAL_REG;
7970   arg.dest_regno = ILLEGAL_REG;
7971   relax_char = 0;
7972   for (args = opcode->args;; ++args)
7973     {
7974       int c;
7975
7976       if (arg.token->type == OT_END)
7977         {
7978           offsetT value;
7979
7980           /* Handle unary instructions in which only one operand is given.
7981              The source is then the same as the destination.  */
7982           if (arg.opnum == 1 && *args == ',')
7983             {
7984               operand = decode_mips16_operand (args[1], FALSE);
7985               if (operand && mips_optional_operand_p (operand))
7986                 {
7987                   arg.token = tokens;
7988                   arg.argnum = 1;
7989                   continue;
7990                 }
7991             }
7992
7993           /* Fail the match if there were too few operands.  */
7994           if (*args)
7995             return FALSE;
7996
7997           /* Successful match.  Stuff the immediate value in now, if
7998              we can.  */
7999           clear_insn_error ();
8000           if (opcode->pinfo == INSN_MACRO)
8001             {
8002               gas_assert (relax_char == 0 || relax_char == 'p');
8003               gas_assert (*offset_reloc == BFD_RELOC_UNUSED);
8004             }
8005           else if (relax_char
8006                    && offset_expr.X_op == O_constant
8007                    && calculate_reloc (*offset_reloc,
8008                                        offset_expr.X_add_number,
8009                                        &value))
8010             {
8011               mips16_immed (NULL, 0, relax_char, *offset_reloc, value,
8012                             forced_insn_length, &insn->insn_opcode);
8013               offset_expr.X_op = O_absent;
8014               *offset_reloc = BFD_RELOC_UNUSED;
8015             }
8016           else if (relax_char && *offset_reloc != BFD_RELOC_UNUSED)
8017             {
8018               if (forced_insn_length == 2)
8019                 set_insn_error (0, _("invalid unextended operand value"));
8020               forced_insn_length = 4;
8021               insn->insn_opcode |= MIPS16_EXTEND;
8022             }
8023           else if (relax_char)
8024             *offset_reloc = (int) BFD_RELOC_UNUSED + relax_char;
8025
8026           check_completed_insn (&arg);
8027           return TRUE;
8028         }
8029
8030       /* Fail the match if the line has too many operands.   */
8031       if (*args == 0)
8032         return FALSE;
8033
8034       /* Handle characters that need to match exactly.  */
8035       if (*args == '(' || *args == ')' || *args == ',')
8036         {
8037           if (match_char (&arg, *args))
8038             continue;
8039           return FALSE;
8040         }
8041
8042       arg.opnum += 1;
8043       c = *args;
8044       switch (c)
8045         {
8046         case 'p':
8047         case 'q':
8048         case 'A':
8049         case 'B':
8050         case 'E':
8051           relax_char = c;
8052           break;
8053
8054         case 'I':
8055           if (!match_const_int (&arg, &imm_expr.X_add_number))
8056             return FALSE;
8057           imm_expr.X_op = O_constant;
8058           if (GPR_SIZE == 32)
8059             normalize_constant_expr (&imm_expr);
8060           continue;
8061
8062         case 'a':
8063         case 'i':
8064           *offset_reloc = BFD_RELOC_MIPS16_JMP;
8065           insn->insn_opcode <<= 16;
8066           break;
8067         }
8068
8069       operand = decode_mips16_operand (c, FALSE);
8070       if (!operand)
8071         abort ();
8072
8073       /* '6' is a special case.  It is used for BREAK and SDBBP,
8074          whose operands are only meaningful to the software that decodes
8075          them.  This means that there is no architectural reason why
8076          they cannot be prefixed by EXTEND, but in practice,
8077          exception handlers will only look at the instruction
8078          itself.  We therefore allow '6' to be extended when
8079          disassembling but not when assembling.  */
8080       if (operand->type != OP_PCREL && c != '6')
8081         {
8082           ext_operand = decode_mips16_operand (c, TRUE);
8083           if (operand != ext_operand)
8084             {
8085               if (arg.token->type == OT_CHAR && arg.token->u.ch == '(')
8086                 {
8087                   offset_expr.X_op = O_constant;
8088                   offset_expr.X_add_number = 0;
8089                   relax_char = c;
8090                   continue;
8091                 }
8092
8093               /* We need the OT_INTEGER check because some MIPS16
8094                  immediate variants are listed before the register ones.  */
8095               if (arg.token->type != OT_INTEGER
8096                   || !match_expression (&arg, &offset_expr, offset_reloc))
8097                 return FALSE;
8098
8099               /* '8' is used for SLTI(U) and has traditionally not
8100                  been allowed to take relocation operators.  */
8101               if (offset_reloc[0] != BFD_RELOC_UNUSED
8102                   && (ext_operand->size != 16 || c == '8'))
8103                 return FALSE;
8104
8105               relax_char = c;
8106               continue;
8107             }
8108         }
8109
8110       if (mips_optional_operand_p (operand)
8111           && args[1] == ','
8112           && (arg.token[0].type != OT_REG
8113               || arg.token[1].type == OT_END))
8114         {
8115           /* Assume that the register has been elided and is the
8116              same as the first operand.  */
8117           arg.token = tokens;
8118           arg.argnum = 1;
8119         }
8120
8121       if (!match_operand (&arg, operand))
8122         return FALSE;
8123     }
8124 }
8125
8126 /* Record that the current instruction is invalid for the current ISA.  */
8127
8128 static void
8129 match_invalid_for_isa (void)
8130 {
8131   set_insn_error_ss
8132     (0, _("opcode not supported on this processor: %s (%s)"),
8133      mips_cpu_info_from_arch (mips_opts.arch)->name,
8134      mips_cpu_info_from_isa (mips_opts.isa)->name);
8135 }
8136
8137 /* Try to match TOKENS against a series of opcode entries, starting at FIRST.
8138    Return true if a definite match or failure was found, storing any match
8139    in INSN.  OPCODE_EXTRA is a value that should be ORed into the opcode
8140    (to handle things like VU0 suffixes).  LAX_MATCH is true if we have already
8141    tried and failed to match under normal conditions and now want to try a
8142    more relaxed match.  */
8143
8144 static bfd_boolean
8145 match_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8146              const struct mips_opcode *past, struct mips_operand_token *tokens,
8147              int opcode_extra, bfd_boolean lax_match)
8148 {
8149   const struct mips_opcode *opcode;
8150   const struct mips_opcode *invalid_delay_slot;
8151   bfd_boolean seen_valid_for_isa, seen_valid_for_size;
8152
8153   /* Search for a match, ignoring alternatives that don't satisfy the
8154      current ISA or forced_length.  */
8155   invalid_delay_slot = 0;
8156   seen_valid_for_isa = FALSE;
8157   seen_valid_for_size = FALSE;
8158   opcode = first;
8159   do
8160     {
8161       gas_assert (strcmp (opcode->name, first->name) == 0);
8162       if (is_opcode_valid (opcode))
8163         {
8164           seen_valid_for_isa = TRUE;
8165           if (is_size_valid (opcode))
8166             {
8167               bfd_boolean delay_slot_ok;
8168
8169               seen_valid_for_size = TRUE;
8170               delay_slot_ok = is_delay_slot_valid (opcode);
8171               if (match_insn (insn, opcode, tokens, opcode_extra,
8172                               lax_match, delay_slot_ok))
8173                 {
8174                   if (!delay_slot_ok)
8175                     {
8176                       if (!invalid_delay_slot)
8177                         invalid_delay_slot = opcode;
8178                     }
8179                   else
8180                     return TRUE;
8181                 }
8182             }
8183         }
8184       ++opcode;
8185     }
8186   while (opcode < past && strcmp (opcode->name, first->name) == 0);
8187
8188   /* If the only matches we found had the wrong length for the delay slot,
8189      pick the first such match.  We'll issue an appropriate warning later.  */
8190   if (invalid_delay_slot)
8191     {
8192       if (match_insn (insn, invalid_delay_slot, tokens, opcode_extra,
8193                       lax_match, TRUE))
8194         return TRUE;
8195       abort ();
8196     }
8197
8198   /* Handle the case where we didn't try to match an instruction because
8199      all the alternatives were incompatible with the current ISA.  */
8200   if (!seen_valid_for_isa)
8201     {
8202       match_invalid_for_isa ();
8203       return TRUE;
8204     }
8205
8206   /* Handle the case where we didn't try to match an instruction because
8207      all the alternatives were of the wrong size.  */
8208   if (!seen_valid_for_size)
8209     {
8210       if (mips_opts.insn32)
8211         set_insn_error (0, _("opcode not supported in the `insn32' mode"));
8212       else
8213         set_insn_error_i
8214           (0, _("unrecognized %d-bit version of microMIPS opcode"),
8215            8 * forced_insn_length);
8216       return TRUE;
8217     }
8218
8219   return FALSE;
8220 }
8221
8222 /* Like match_insns, but for MIPS16.  */
8223
8224 static bfd_boolean
8225 match_mips16_insns (struct mips_cl_insn *insn, const struct mips_opcode *first,
8226                     struct mips_operand_token *tokens)
8227 {
8228   const struct mips_opcode *opcode;
8229   bfd_boolean seen_valid_for_isa;
8230
8231   /* Search for a match, ignoring alternatives that don't satisfy the
8232      current ISA.  There are no separate entries for extended forms so
8233      we deal with forced_length later.  */
8234   seen_valid_for_isa = FALSE;
8235   opcode = first;
8236   do
8237     {
8238       gas_assert (strcmp (opcode->name, first->name) == 0);
8239       if (is_opcode_valid_16 (opcode))
8240         {
8241           seen_valid_for_isa = TRUE;
8242           if (match_mips16_insn (insn, opcode, tokens))
8243             return TRUE;
8244         }
8245       ++opcode;
8246     }
8247   while (opcode < &mips16_opcodes[bfd_mips16_num_opcodes]
8248          && strcmp (opcode->name, first->name) == 0);
8249
8250   /* Handle the case where we didn't try to match an instruction because
8251      all the alternatives were incompatible with the current ISA.  */
8252   if (!seen_valid_for_isa)
8253     {
8254       match_invalid_for_isa ();
8255       return TRUE;
8256     }
8257
8258   return FALSE;
8259 }
8260
8261 /* Set up global variables for the start of a new macro.  */
8262
8263 static void
8264 macro_start (void)
8265 {
8266   memset (&mips_macro_warning.sizes, 0, sizeof (mips_macro_warning.sizes));
8267   memset (&mips_macro_warning.first_insn_sizes, 0,
8268           sizeof (mips_macro_warning.first_insn_sizes));
8269   memset (&mips_macro_warning.insns, 0, sizeof (mips_macro_warning.insns));
8270   mips_macro_warning.delay_slot_p = (mips_opts.noreorder
8271                                      && delayed_branch_p (&history[0]));
8272   switch (history[0].insn_mo->pinfo2
8273           & (INSN2_BRANCH_DELAY_32BIT | INSN2_BRANCH_DELAY_16BIT))
8274     {
8275     case INSN2_BRANCH_DELAY_32BIT:
8276       mips_macro_warning.delay_slot_length = 4;
8277       break;
8278     case INSN2_BRANCH_DELAY_16BIT:
8279       mips_macro_warning.delay_slot_length = 2;
8280       break;
8281     default:
8282       mips_macro_warning.delay_slot_length = 0;
8283       break;
8284     }
8285   mips_macro_warning.first_frag = NULL;
8286 }
8287
8288 /* Given that a macro is longer than one instruction or of the wrong size,
8289    return the appropriate warning for it.  Return null if no warning is
8290    needed.  SUBTYPE is a bitmask of RELAX_DELAY_SLOT, RELAX_DELAY_SLOT_16BIT,
8291    RELAX_DELAY_SLOT_SIZE_FIRST, RELAX_DELAY_SLOT_SIZE_SECOND,
8292    and RELAX_NOMACRO.  */
8293
8294 static const char *
8295 macro_warning (relax_substateT subtype)
8296 {
8297   if (subtype & RELAX_DELAY_SLOT)
8298     return _("macro instruction expanded into multiple instructions"
8299              " in a branch delay slot");
8300   else if (subtype & RELAX_NOMACRO)
8301     return _("macro instruction expanded into multiple instructions");
8302   else if (subtype & (RELAX_DELAY_SLOT_SIZE_FIRST
8303                       | RELAX_DELAY_SLOT_SIZE_SECOND))
8304     return ((subtype & RELAX_DELAY_SLOT_16BIT)
8305             ? _("macro instruction expanded into a wrong size instruction"
8306                 " in a 16-bit branch delay slot")
8307             : _("macro instruction expanded into a wrong size instruction"
8308                 " in a 32-bit branch delay slot"));
8309   else
8310     return 0;
8311 }
8312
8313 /* Finish up a macro.  Emit warnings as appropriate.  */
8314
8315 static void
8316 macro_end (void)
8317 {
8318   /* Relaxation warning flags.  */
8319   relax_substateT subtype = 0;
8320
8321   /* Check delay slot size requirements.  */
8322   if (mips_macro_warning.delay_slot_length == 2)
8323     subtype |= RELAX_DELAY_SLOT_16BIT;
8324   if (mips_macro_warning.delay_slot_length != 0)
8325     {
8326       if (mips_macro_warning.delay_slot_length
8327           != mips_macro_warning.first_insn_sizes[0])
8328         subtype |= RELAX_DELAY_SLOT_SIZE_FIRST;
8329       if (mips_macro_warning.delay_slot_length
8330           != mips_macro_warning.first_insn_sizes[1])
8331         subtype |= RELAX_DELAY_SLOT_SIZE_SECOND;
8332     }
8333
8334   /* Check instruction count requirements.  */
8335   if (mips_macro_warning.insns[0] > 1 || mips_macro_warning.insns[1] > 1)
8336     {
8337       if (mips_macro_warning.insns[1] > mips_macro_warning.insns[0])
8338         subtype |= RELAX_SECOND_LONGER;
8339       if (mips_opts.warn_about_macros)
8340         subtype |= RELAX_NOMACRO;
8341       if (mips_macro_warning.delay_slot_p)
8342         subtype |= RELAX_DELAY_SLOT;
8343     }
8344
8345   /* If both alternatives fail to fill a delay slot correctly,
8346      emit the warning now.  */
8347   if ((subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0
8348       && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0)
8349     {
8350       relax_substateT s;
8351       const char *msg;
8352
8353       s = subtype & (RELAX_DELAY_SLOT_16BIT
8354                      | RELAX_DELAY_SLOT_SIZE_FIRST
8355                      | RELAX_DELAY_SLOT_SIZE_SECOND);
8356       msg = macro_warning (s);
8357       if (msg != NULL)
8358         as_warn ("%s", msg);
8359       subtype &= ~s;
8360     }
8361
8362   /* If both implementations are longer than 1 instruction, then emit the
8363      warning now.  */
8364   if (mips_macro_warning.insns[0] > 1 && mips_macro_warning.insns[1] > 1)
8365     {
8366       relax_substateT s;
8367       const char *msg;
8368
8369       s = subtype & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT);
8370       msg = macro_warning (s);
8371       if (msg != NULL)
8372         as_warn ("%s", msg);
8373       subtype &= ~s;
8374     }
8375
8376   /* If any flags still set, then one implementation might need a warning
8377      and the other either will need one of a different kind or none at all.
8378      Pass any remaining flags over to relaxation.  */
8379   if (mips_macro_warning.first_frag != NULL)
8380     mips_macro_warning.first_frag->fr_subtype |= subtype;
8381 }
8382
8383 /* Instruction operand formats used in macros that vary between
8384    standard MIPS and microMIPS code.  */
8385
8386 static const char * const brk_fmt[2][2] = { { "c", "c" }, { "mF", "c" } };
8387 static const char * const cop12_fmt[2] = { "E,o(b)", "E,~(b)" };
8388 static const char * const jalr_fmt[2] = { "d,s", "t,s" };
8389 static const char * const lui_fmt[2] = { "t,u", "s,u" };
8390 static const char * const mem12_fmt[2] = { "t,o(b)", "t,~(b)" };
8391 static const char * const mfhl_fmt[2][2] = { { "d", "d" }, { "mj", "s" } };
8392 static const char * const shft_fmt[2] = { "d,w,<", "t,r,<" };
8393 static const char * const trap_fmt[2] = { "s,t,q", "s,t,|" };
8394
8395 #define BRK_FMT (brk_fmt[mips_opts.micromips][mips_opts.insn32])
8396 #define COP12_FMT (ISA_IS_R6 (mips_opts.isa) ? "E,+:(d)" \
8397                                              : cop12_fmt[mips_opts.micromips])
8398 #define JALR_FMT (jalr_fmt[mips_opts.micromips])
8399 #define LUI_FMT (lui_fmt[mips_opts.micromips])
8400 #define MEM12_FMT (mem12_fmt[mips_opts.micromips])
8401 #define LL_SC_FMT (ISA_IS_R6 (mips_opts.isa) ? "t,+j(b)" \
8402                                              : mem12_fmt[mips_opts.micromips])
8403 #define MFHL_FMT (mfhl_fmt[mips_opts.micromips][mips_opts.insn32])
8404 #define SHFT_FMT (shft_fmt[mips_opts.micromips])
8405 #define TRAP_FMT (trap_fmt[mips_opts.micromips])
8406
8407 /* Read a macro's relocation codes from *ARGS and store them in *R.
8408    The first argument in *ARGS will be either the code for a single
8409    relocation or -1 followed by the three codes that make up a
8410    composite relocation.  */
8411
8412 static void
8413 macro_read_relocs (va_list *args, bfd_reloc_code_real_type *r)
8414 {
8415   int i, next;
8416
8417   next = va_arg (*args, int);
8418   if (next >= 0)
8419     r[0] = (bfd_reloc_code_real_type) next;
8420   else
8421     {
8422       for (i = 0; i < 3; i++)
8423         r[i] = (bfd_reloc_code_real_type) va_arg (*args, int);
8424       /* This function is only used for 16-bit relocation fields.
8425          To make the macro code simpler, treat an unrelocated value
8426          in the same way as BFD_RELOC_LO16.  */
8427       if (r[0] == BFD_RELOC_UNUSED)
8428         r[0] = BFD_RELOC_LO16;
8429     }
8430 }
8431
8432 /* Build an instruction created by a macro expansion.  This is passed
8433    a pointer to the count of instructions created so far, an
8434    expression, the name of the instruction to build, an operand format
8435    string, and corresponding arguments.  */
8436
8437 static void
8438 macro_build (expressionS *ep, const char *name, const char *fmt, ...)
8439 {
8440   const struct mips_opcode *mo = NULL;
8441   bfd_reloc_code_real_type r[3];
8442   const struct mips_opcode *amo;
8443   const struct mips_operand *operand;
8444   struct hash_control *hash;
8445   struct mips_cl_insn insn;
8446   va_list args;
8447   unsigned int uval;
8448
8449   va_start (args, fmt);
8450
8451   if (mips_opts.mips16)
8452     {
8453       mips16_macro_build (ep, name, fmt, &args);
8454       va_end (args);
8455       return;
8456     }
8457
8458   r[0] = BFD_RELOC_UNUSED;
8459   r[1] = BFD_RELOC_UNUSED;
8460   r[2] = BFD_RELOC_UNUSED;
8461   hash = mips_opts.micromips ? micromips_op_hash : op_hash;
8462   amo = (struct mips_opcode *) hash_find (hash, name);
8463   gas_assert (amo);
8464   gas_assert (strcmp (name, amo->name) == 0);
8465
8466   do
8467     {
8468       /* Search until we get a match for NAME.  It is assumed here that
8469          macros will never generate MDMX, MIPS-3D, or MT instructions.
8470          We try to match an instruction that fulfils the branch delay
8471          slot instruction length requirement (if any) of the previous
8472          instruction.  While doing this we record the first instruction
8473          seen that matches all the other conditions and use it anyway
8474          if the requirement cannot be met; we will issue an appropriate
8475          warning later on.  */
8476       if (strcmp (fmt, amo->args) == 0
8477           && amo->pinfo != INSN_MACRO
8478           && is_opcode_valid (amo)
8479           && is_size_valid (amo))
8480         {
8481           if (is_delay_slot_valid (amo))
8482             {
8483               mo = amo;
8484               break;
8485             }
8486           else if (!mo)
8487             mo = amo;
8488         }
8489
8490       ++amo;
8491       gas_assert (amo->name);
8492     }
8493   while (strcmp (name, amo->name) == 0);
8494
8495   gas_assert (mo);
8496   create_insn (&insn, mo);
8497   for (; *fmt; ++fmt)
8498     {
8499       switch (*fmt)
8500         {
8501         case ',':
8502         case '(':
8503         case ')':
8504         case 'z':
8505           break;
8506
8507         case 'i':
8508         case 'j':
8509           macro_read_relocs (&args, r);
8510           gas_assert (*r == BFD_RELOC_GPREL16
8511                       || *r == BFD_RELOC_MIPS_HIGHER
8512                       || *r == BFD_RELOC_HI16_S
8513                       || *r == BFD_RELOC_LO16
8514                       || *r == BFD_RELOC_MIPS_GOT_OFST);
8515           break;
8516
8517         case 'o':
8518           macro_read_relocs (&args, r);
8519           break;
8520
8521         case 'u':
8522           macro_read_relocs (&args, r);
8523           gas_assert (ep != NULL
8524                       && (ep->X_op == O_constant
8525                           || (ep->X_op == O_symbol
8526                               && (*r == BFD_RELOC_MIPS_HIGHEST
8527                                   || *r == BFD_RELOC_HI16_S
8528                                   || *r == BFD_RELOC_HI16
8529                                   || *r == BFD_RELOC_GPREL16
8530                                   || *r == BFD_RELOC_MIPS_GOT_HI16
8531                                   || *r == BFD_RELOC_MIPS_CALL_HI16))));
8532           break;
8533
8534         case 'p':
8535           gas_assert (ep != NULL);
8536
8537           /*
8538            * This allows macro() to pass an immediate expression for
8539            * creating short branches without creating a symbol.
8540            *
8541            * We don't allow branch relaxation for these branches, as
8542            * they should only appear in ".set nomacro" anyway.
8543            */
8544           if (ep->X_op == O_constant)
8545             {
8546               /* For microMIPS we always use relocations for branches.
8547                  So we should not resolve immediate values.  */
8548               gas_assert (!mips_opts.micromips);
8549
8550               if ((ep->X_add_number & 3) != 0)
8551                 as_bad (_("branch to misaligned address (0x%lx)"),
8552                         (unsigned long) ep->X_add_number);
8553               if ((ep->X_add_number + 0x20000) & ~0x3ffff)
8554                 as_bad (_("branch address range overflow (0x%lx)"),
8555                         (unsigned long) ep->X_add_number);
8556               insn.insn_opcode |= (ep->X_add_number >> 2) & 0xffff;
8557               ep = NULL;
8558             }
8559           else
8560             *r = BFD_RELOC_16_PCREL_S2;
8561           break;
8562
8563         case 'a':
8564           gas_assert (ep != NULL);
8565           *r = BFD_RELOC_MIPS_JMP;
8566           break;
8567
8568         default:
8569           operand = (mips_opts.micromips
8570                      ? decode_micromips_operand (fmt)
8571                      : decode_mips_operand (fmt));
8572           if (!operand)
8573             abort ();
8574
8575           uval = va_arg (args, int);
8576           if (operand->type == OP_CLO_CLZ_DEST)
8577             uval |= (uval << 5);
8578           insn_insert_operand (&insn, operand, uval);
8579
8580           if (*fmt == '+' || *fmt == 'm' || *fmt == '-')
8581             ++fmt;
8582           break;
8583         }
8584     }
8585   va_end (args);
8586   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8587
8588   append_insn (&insn, ep, r, TRUE);
8589 }
8590
8591 static void
8592 mips16_macro_build (expressionS *ep, const char *name, const char *fmt,
8593                     va_list *args)
8594 {
8595   struct mips_opcode *mo;
8596   struct mips_cl_insn insn;
8597   const struct mips_operand *operand;
8598   bfd_reloc_code_real_type r[3]
8599     = {BFD_RELOC_UNUSED, BFD_RELOC_UNUSED, BFD_RELOC_UNUSED};
8600
8601   mo = (struct mips_opcode *) hash_find (mips16_op_hash, name);
8602   gas_assert (mo);
8603   gas_assert (strcmp (name, mo->name) == 0);
8604
8605   while (strcmp (fmt, mo->args) != 0 || mo->pinfo == INSN_MACRO)
8606     {
8607       ++mo;
8608       gas_assert (mo->name);
8609       gas_assert (strcmp (name, mo->name) == 0);
8610     }
8611
8612   create_insn (&insn, mo);
8613   for (; *fmt; ++fmt)
8614     {
8615       int c;
8616
8617       c = *fmt;
8618       switch (c)
8619         {
8620         case ',':
8621         case '(':
8622         case ')':
8623           break;
8624
8625         case '0':
8626         case 'S':
8627         case 'P':
8628         case 'R':
8629           break;
8630
8631         case '<':
8632         case '>':
8633         case '4':
8634         case '5':
8635         case 'H':
8636         case 'W':
8637         case 'D':
8638         case 'j':
8639         case '8':
8640         case 'V':
8641         case 'C':
8642         case 'U':
8643         case 'k':
8644         case 'K':
8645         case 'p':
8646         case 'q':
8647           {
8648             offsetT value;
8649
8650             gas_assert (ep != NULL);
8651
8652             if (ep->X_op != O_constant)
8653               *r = (int) BFD_RELOC_UNUSED + c;
8654             else if (calculate_reloc (*r, ep->X_add_number, &value))
8655               {
8656                 mips16_immed (NULL, 0, c, *r, value, 0, &insn.insn_opcode);
8657                 ep = NULL;
8658                 *r = BFD_RELOC_UNUSED;
8659               }
8660           }
8661           break;
8662
8663         default:
8664           operand = decode_mips16_operand (c, FALSE);
8665           if (!operand)
8666             abort ();
8667
8668           insn_insert_operand (&insn, operand, va_arg (*args, int));
8669           break;
8670         }
8671     }
8672
8673   gas_assert (*r == BFD_RELOC_UNUSED ? ep == NULL : ep != NULL);
8674
8675   append_insn (&insn, ep, r, TRUE);
8676 }
8677
8678 /*
8679  * Generate a "jalr" instruction with a relocation hint to the called
8680  * function.  This occurs in NewABI PIC code.
8681  */
8682 static void
8683 macro_build_jalr (expressionS *ep, int cprestore)
8684 {
8685   static const bfd_reloc_code_real_type jalr_relocs[2]
8686     = { BFD_RELOC_MIPS_JALR, BFD_RELOC_MICROMIPS_JALR };
8687   bfd_reloc_code_real_type jalr_reloc = jalr_relocs[mips_opts.micromips];
8688   const char *jalr;
8689   char *f = NULL;
8690
8691   if (MIPS_JALR_HINT_P (ep))
8692     {
8693       frag_grow (8);
8694       f = frag_more (0);
8695     }
8696   if (mips_opts.micromips)
8697     {
8698       jalr = ((mips_opts.noreorder && !cprestore) || mips_opts.insn32
8699               ? "jalr" : "jalrs");
8700       if (MIPS_JALR_HINT_P (ep)
8701           || mips_opts.insn32
8702           || (history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
8703         macro_build (NULL, jalr, "t,s", RA, PIC_CALL_REG);
8704       else
8705         macro_build (NULL, jalr, "mj", PIC_CALL_REG);
8706     }
8707   else
8708     macro_build (NULL, "jalr", "d,s", RA, PIC_CALL_REG);
8709   if (MIPS_JALR_HINT_P (ep))
8710     fix_new_exp (frag_now, f - frag_now->fr_literal, 4, ep, FALSE, jalr_reloc);
8711 }
8712
8713 /*
8714  * Generate a "lui" instruction.
8715  */
8716 static void
8717 macro_build_lui (expressionS *ep, int regnum)
8718 {
8719   gas_assert (! mips_opts.mips16);
8720
8721   if (ep->X_op != O_constant)
8722     {
8723       gas_assert (ep->X_op == O_symbol);
8724       /* _gp_disp is a special case, used from s_cpload.
8725          __gnu_local_gp is used if mips_no_shared.  */
8726       gas_assert (mips_pic == NO_PIC
8727               || (! HAVE_NEWABI
8728                   && strcmp (S_GET_NAME (ep->X_add_symbol), "_gp_disp") == 0)
8729               || (! mips_in_shared
8730                   && strcmp (S_GET_NAME (ep->X_add_symbol),
8731                              "__gnu_local_gp") == 0));
8732     }
8733
8734   macro_build (ep, "lui", LUI_FMT, regnum, BFD_RELOC_HI16_S);
8735 }
8736
8737 /* Generate a sequence of instructions to do a load or store from a constant
8738    offset off of a base register (breg) into/from a target register (treg),
8739    using AT if necessary.  */
8740 static void
8741 macro_build_ldst_constoffset (expressionS *ep, const char *op,
8742                               int treg, int breg, int dbl)
8743 {
8744   gas_assert (ep->X_op == O_constant);
8745
8746   /* Sign-extending 32-bit constants makes their handling easier.  */
8747   if (!dbl)
8748     normalize_constant_expr (ep);
8749
8750   /* Right now, this routine can only handle signed 32-bit constants.  */
8751   if (! IS_SEXT_32BIT_NUM(ep->X_add_number + 0x8000))
8752     as_warn (_("operand overflow"));
8753
8754   if (IS_SEXT_16BIT_NUM(ep->X_add_number))
8755     {
8756       /* Signed 16-bit offset will fit in the op.  Easy!  */
8757       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, breg);
8758     }
8759   else
8760     {
8761       /* 32-bit offset, need multiple instructions and AT, like:
8762            lui      $tempreg,const_hi       (BFD_RELOC_HI16_S)
8763            addu     $tempreg,$tempreg,$breg
8764            <op>     $treg,const_lo($tempreg)   (BFD_RELOC_LO16)
8765          to handle the complete offset.  */
8766       macro_build_lui (ep, AT);
8767       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, AT, breg);
8768       macro_build (ep, op, "t,o(b)", treg, BFD_RELOC_LO16, AT);
8769
8770       if (!mips_opts.at)
8771         as_bad (_("macro used $at after \".set noat\""));
8772     }
8773 }
8774
8775 /*                      set_at()
8776  * Generates code to set the $at register to true (one)
8777  * if reg is less than the immediate expression.
8778  */
8779 static void
8780 set_at (int reg, int unsignedp)
8781 {
8782   if (imm_expr.X_add_number >= -0x8000
8783       && imm_expr.X_add_number < 0x8000)
8784     macro_build (&imm_expr, unsignedp ? "sltiu" : "slti", "t,r,j",
8785                  AT, reg, BFD_RELOC_LO16);
8786   else
8787     {
8788       load_register (AT, &imm_expr, GPR_SIZE == 64);
8789       macro_build (NULL, unsignedp ? "sltu" : "slt", "d,v,t", AT, reg, AT);
8790     }
8791 }
8792
8793 /* Count the leading zeroes by performing a binary chop. This is a
8794    bulky bit of source, but performance is a LOT better for the
8795    majority of values than a simple loop to count the bits:
8796        for (lcnt = 0; (lcnt < 32); lcnt++)
8797          if ((v) & (1 << (31 - lcnt)))
8798            break;
8799   However it is not code size friendly, and the gain will drop a bit
8800   on certain cached systems.
8801 */
8802 #define COUNT_TOP_ZEROES(v)             \
8803   (((v) & ~0xffff) == 0                 \
8804    ? ((v) & ~0xff) == 0                 \
8805      ? ((v) & ~0xf) == 0                \
8806        ? ((v) & ~0x3) == 0              \
8807          ? ((v) & ~0x1) == 0            \
8808            ? !(v)                       \
8809              ? 32                       \
8810              : 31                       \
8811            : 30                         \
8812          : ((v) & ~0x7) == 0            \
8813            ? 29                         \
8814            : 28                         \
8815        : ((v) & ~0x3f) == 0             \
8816          ? ((v) & ~0x1f) == 0           \
8817            ? 27                         \
8818            : 26                         \
8819          : ((v) & ~0x7f) == 0           \
8820            ? 25                         \
8821            : 24                         \
8822      : ((v) & ~0xfff) == 0              \
8823        ? ((v) & ~0x3ff) == 0            \
8824          ? ((v) & ~0x1ff) == 0          \
8825            ? 23                         \
8826            : 22                         \
8827          : ((v) & ~0x7ff) == 0          \
8828            ? 21                         \
8829            : 20                         \
8830        : ((v) & ~0x3fff) == 0           \
8831          ? ((v) & ~0x1fff) == 0         \
8832            ? 19                         \
8833            : 18                         \
8834          : ((v) & ~0x7fff) == 0         \
8835            ? 17                         \
8836            : 16                         \
8837    : ((v) & ~0xffffff) == 0             \
8838      ? ((v) & ~0xfffff) == 0            \
8839        ? ((v) & ~0x3ffff) == 0          \
8840          ? ((v) & ~0x1ffff) == 0        \
8841            ? 15                         \
8842            : 14                         \
8843          : ((v) & ~0x7ffff) == 0        \
8844            ? 13                         \
8845            : 12                         \
8846        : ((v) & ~0x3fffff) == 0         \
8847          ? ((v) & ~0x1fffff) == 0       \
8848            ? 11                         \
8849            : 10                         \
8850          : ((v) & ~0x7fffff) == 0       \
8851            ? 9                          \
8852            : 8                          \
8853      : ((v) & ~0xfffffff) == 0          \
8854        ? ((v) & ~0x3ffffff) == 0        \
8855          ? ((v) & ~0x1ffffff) == 0      \
8856            ? 7                          \
8857            : 6                          \
8858          : ((v) & ~0x7ffffff) == 0      \
8859            ? 5                          \
8860            : 4                          \
8861        : ((v) & ~0x3fffffff) == 0       \
8862          ? ((v) & ~0x1fffffff) == 0     \
8863            ? 3                          \
8864            : 2                          \
8865          : ((v) & ~0x7fffffff) == 0     \
8866            ? 1                          \
8867            : 0)
8868
8869 /*                      load_register()
8870  *  This routine generates the least number of instructions necessary to load
8871  *  an absolute expression value into a register.
8872  */
8873 static void
8874 load_register (int reg, expressionS *ep, int dbl)
8875 {
8876   int freg;
8877   expressionS hi32, lo32;
8878
8879   if (ep->X_op != O_big)
8880     {
8881       gas_assert (ep->X_op == O_constant);
8882
8883       /* Sign-extending 32-bit constants makes their handling easier.  */
8884       if (!dbl)
8885         normalize_constant_expr (ep);
8886
8887       if (IS_SEXT_16BIT_NUM (ep->X_add_number))
8888         {
8889           /* We can handle 16 bit signed values with an addiu to
8890              $zero.  No need to ever use daddiu here, since $zero and
8891              the result are always correct in 32 bit mode.  */
8892           macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8893           return;
8894         }
8895       else if (ep->X_add_number >= 0 && ep->X_add_number < 0x10000)
8896         {
8897           /* We can handle 16 bit unsigned values with an ori to
8898              $zero.  */
8899           macro_build (ep, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8900           return;
8901         }
8902       else if ((IS_SEXT_32BIT_NUM (ep->X_add_number)))
8903         {
8904           /* 32 bit values require an lui.  */
8905           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8906           if ((ep->X_add_number & 0xffff) != 0)
8907             macro_build (ep, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8908           return;
8909         }
8910     }
8911
8912   /* The value is larger than 32 bits.  */
8913
8914   if (!dbl || GPR_SIZE == 32)
8915     {
8916       char value[32];
8917
8918       sprintf_vma (value, ep->X_add_number);
8919       as_bad (_("number (0x%s) larger than 32 bits"), value);
8920       macro_build (ep, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8921       return;
8922     }
8923
8924   if (ep->X_op != O_big)
8925     {
8926       hi32 = *ep;
8927       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8928       hi32.X_add_number = (valueT) hi32.X_add_number >> 16;
8929       hi32.X_add_number &= 0xffffffff;
8930       lo32 = *ep;
8931       lo32.X_add_number &= 0xffffffff;
8932     }
8933   else
8934     {
8935       gas_assert (ep->X_add_number > 2);
8936       if (ep->X_add_number == 3)
8937         generic_bignum[3] = 0;
8938       else if (ep->X_add_number > 4)
8939         as_bad (_("number larger than 64 bits"));
8940       lo32.X_op = O_constant;
8941       lo32.X_add_number = generic_bignum[0] + (generic_bignum[1] << 16);
8942       hi32.X_op = O_constant;
8943       hi32.X_add_number = generic_bignum[2] + (generic_bignum[3] << 16);
8944     }
8945
8946   if (hi32.X_add_number == 0)
8947     freg = 0;
8948   else
8949     {
8950       int shift, bit;
8951       unsigned long hi, lo;
8952
8953       if (hi32.X_add_number == (offsetT) 0xffffffff)
8954         {
8955           if ((lo32.X_add_number & 0xffff8000) == 0xffff8000)
8956             {
8957               macro_build (&lo32, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
8958               return;
8959             }
8960           if (lo32.X_add_number & 0x80000000)
8961             {
8962               macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
8963               if (lo32.X_add_number & 0xffff)
8964                 macro_build (&lo32, "ori", "t,r,i", reg, reg, BFD_RELOC_LO16);
8965               return;
8966             }
8967         }
8968
8969       /* Check for 16bit shifted constant.  We know that hi32 is
8970          non-zero, so start the mask on the first bit of the hi32
8971          value.  */
8972       shift = 17;
8973       do
8974         {
8975           unsigned long himask, lomask;
8976
8977           if (shift < 32)
8978             {
8979               himask = 0xffff >> (32 - shift);
8980               lomask = (0xffff << shift) & 0xffffffff;
8981             }
8982           else
8983             {
8984               himask = 0xffff << (shift - 32);
8985               lomask = 0;
8986             }
8987           if ((hi32.X_add_number & ~(offsetT) himask) == 0
8988               && (lo32.X_add_number & ~(offsetT) lomask) == 0)
8989             {
8990               expressionS tmp;
8991
8992               tmp.X_op = O_constant;
8993               if (shift < 32)
8994                 tmp.X_add_number = ((hi32.X_add_number << (32 - shift))
8995                                     | (lo32.X_add_number >> shift));
8996               else
8997                 tmp.X_add_number = hi32.X_add_number >> (shift - 32);
8998               macro_build (&tmp, "ori", "t,r,i", reg, 0, BFD_RELOC_LO16);
8999               macro_build (NULL, (shift >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9000                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9001               return;
9002             }
9003           ++shift;
9004         }
9005       while (shift <= (64 - 16));
9006
9007       /* Find the bit number of the lowest one bit, and store the
9008          shifted value in hi/lo.  */
9009       hi = (unsigned long) (hi32.X_add_number & 0xffffffff);
9010       lo = (unsigned long) (lo32.X_add_number & 0xffffffff);
9011       if (lo != 0)
9012         {
9013           bit = 0;
9014           while ((lo & 1) == 0)
9015             {
9016               lo >>= 1;
9017               ++bit;
9018             }
9019           lo |= (hi & (((unsigned long) 1 << bit) - 1)) << (32 - bit);
9020           hi >>= bit;
9021         }
9022       else
9023         {
9024           bit = 32;
9025           while ((hi & 1) == 0)
9026             {
9027               hi >>= 1;
9028               ++bit;
9029             }
9030           lo = hi;
9031           hi = 0;
9032         }
9033
9034       /* Optimize if the shifted value is a (power of 2) - 1.  */
9035       if ((hi == 0 && ((lo + 1) & lo) == 0)
9036           || (lo == 0xffffffff && ((hi + 1) & hi) == 0))
9037         {
9038           shift = COUNT_TOP_ZEROES ((unsigned int) hi32.X_add_number);
9039           if (shift != 0)
9040             {
9041               expressionS tmp;
9042
9043               /* This instruction will set the register to be all
9044                  ones.  */
9045               tmp.X_op = O_constant;
9046               tmp.X_add_number = (offsetT) -1;
9047               macro_build (&tmp, "addiu", "t,r,j", reg, 0, BFD_RELOC_LO16);
9048               if (bit != 0)
9049                 {
9050                   bit += shift;
9051                   macro_build (NULL, (bit >= 32) ? "dsll32" : "dsll", SHFT_FMT,
9052                                reg, reg, (bit >= 32) ? bit - 32 : bit);
9053                 }
9054               macro_build (NULL, (shift >= 32) ? "dsrl32" : "dsrl", SHFT_FMT,
9055                            reg, reg, (shift >= 32) ? shift - 32 : shift);
9056               return;
9057             }
9058         }
9059
9060       /* Sign extend hi32 before calling load_register, because we can
9061          generally get better code when we load a sign extended value.  */
9062       if ((hi32.X_add_number & 0x80000000) != 0)
9063         hi32.X_add_number |= ~(offsetT) 0xffffffff;
9064       load_register (reg, &hi32, 0);
9065       freg = reg;
9066     }
9067   if ((lo32.X_add_number & 0xffff0000) == 0)
9068     {
9069       if (freg != 0)
9070         {
9071           macro_build (NULL, "dsll32", SHFT_FMT, reg, freg, 0);
9072           freg = reg;
9073         }
9074     }
9075   else
9076     {
9077       expressionS mid16;
9078
9079       if ((freg == 0) && (lo32.X_add_number == (offsetT) 0xffffffff))
9080         {
9081           macro_build (&lo32, "lui", LUI_FMT, reg, BFD_RELOC_HI16);
9082           macro_build (NULL, "dsrl32", SHFT_FMT, reg, reg, 0);
9083           return;
9084         }
9085
9086       if (freg != 0)
9087         {
9088           macro_build (NULL, "dsll", SHFT_FMT, reg, freg, 16);
9089           freg = reg;
9090         }
9091       mid16 = lo32;
9092       mid16.X_add_number >>= 16;
9093       macro_build (&mid16, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9094       macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9095       freg = reg;
9096     }
9097   if ((lo32.X_add_number & 0xffff) != 0)
9098     macro_build (&lo32, "ori", "t,r,i", reg, freg, BFD_RELOC_LO16);
9099 }
9100
9101 static inline void
9102 load_delay_nop (void)
9103 {
9104   if (!gpr_interlocks)
9105     macro_build (NULL, "nop", "");
9106 }
9107
9108 /* Load an address into a register.  */
9109
9110 static void
9111 load_address (int reg, expressionS *ep, int *used_at)
9112 {
9113   if (ep->X_op != O_constant
9114       && ep->X_op != O_symbol)
9115     {
9116       as_bad (_("expression too complex"));
9117       ep->X_op = O_constant;
9118     }
9119
9120   if (ep->X_op == O_constant)
9121     {
9122       load_register (reg, ep, HAVE_64BIT_ADDRESSES);
9123       return;
9124     }
9125
9126   if (mips_pic == NO_PIC)
9127     {
9128       /* If this is a reference to a GP relative symbol, we want
9129            addiu        $reg,$gp,<sym>          (BFD_RELOC_GPREL16)
9130          Otherwise we want
9131            lui          $reg,<sym>              (BFD_RELOC_HI16_S)
9132            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9133          If we have an addend, we always use the latter form.
9134
9135          With 64bit address space and a usable $at we want
9136            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9137            lui          $at,<sym>               (BFD_RELOC_HI16_S)
9138            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9139            daddiu       $at,<sym>               (BFD_RELOC_LO16)
9140            dsll32       $reg,0
9141            daddu        $reg,$reg,$at
9142
9143          If $at is already in use, we use a path which is suboptimal
9144          on superscalar processors.
9145            lui          $reg,<sym>              (BFD_RELOC_MIPS_HIGHEST)
9146            daddiu       $reg,<sym>              (BFD_RELOC_MIPS_HIGHER)
9147            dsll         $reg,16
9148            daddiu       $reg,<sym>              (BFD_RELOC_HI16_S)
9149            dsll         $reg,16
9150            daddiu       $reg,<sym>              (BFD_RELOC_LO16)
9151
9152          For GP relative symbols in 64bit address space we can use
9153          the same sequence as in 32bit address space.  */
9154       if (HAVE_64BIT_SYMBOLS)
9155         {
9156           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9157               && !nopic_need_relax (ep->X_add_symbol, 1))
9158             {
9159               relax_start (ep->X_add_symbol);
9160               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9161                            mips_gp_register, BFD_RELOC_GPREL16);
9162               relax_switch ();
9163             }
9164
9165           if (*used_at == 0 && mips_opts.at)
9166             {
9167               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9168               macro_build (ep, "lui", LUI_FMT, AT, BFD_RELOC_HI16_S);
9169               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9170                            BFD_RELOC_MIPS_HIGHER);
9171               macro_build (ep, "daddiu", "t,r,j", AT, AT, BFD_RELOC_LO16);
9172               macro_build (NULL, "dsll32", SHFT_FMT, reg, reg, 0);
9173               macro_build (NULL, "daddu", "d,v,t", reg, reg, AT);
9174               *used_at = 1;
9175             }
9176           else
9177             {
9178               macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_HIGHEST);
9179               macro_build (ep, "daddiu", "t,r,j", reg, reg,
9180                            BFD_RELOC_MIPS_HIGHER);
9181               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9182               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_HI16_S);
9183               macro_build (NULL, "dsll", SHFT_FMT, reg, reg, 16);
9184               macro_build (ep, "daddiu", "t,r,j", reg, reg, BFD_RELOC_LO16);
9185             }
9186
9187           if (mips_relax.sequence)
9188             relax_end ();
9189         }
9190       else
9191         {
9192           if ((valueT) ep->X_add_number <= MAX_GPREL_OFFSET
9193               && !nopic_need_relax (ep->X_add_symbol, 1))
9194             {
9195               relax_start (ep->X_add_symbol);
9196               macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg,
9197                            mips_gp_register, BFD_RELOC_GPREL16);
9198               relax_switch ();
9199             }
9200           macro_build_lui (ep, reg);
9201           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j",
9202                        reg, reg, BFD_RELOC_LO16);
9203           if (mips_relax.sequence)
9204             relax_end ();
9205         }
9206     }
9207   else if (!mips_big_got)
9208     {
9209       expressionS ex;
9210
9211       /* If this is a reference to an external symbol, we want
9212            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9213          Otherwise we want
9214            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9215            nop
9216            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9217          If there is a constant, it must be added in after.
9218
9219          If we have NewABI, we want
9220            lw           $reg,<sym+cst>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
9221          unless we're referencing a global symbol with a non-zero
9222          offset, in which case cst must be added separately.  */
9223       if (HAVE_NEWABI)
9224         {
9225           if (ep->X_add_number)
9226             {
9227               ex.X_add_number = ep->X_add_number;
9228               ep->X_add_number = 0;
9229               relax_start (ep->X_add_symbol);
9230               macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9231                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9232               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9233                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9234               ex.X_op = O_constant;
9235               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9236                            reg, reg, BFD_RELOC_LO16);
9237               ep->X_add_number = ex.X_add_number;
9238               relax_switch ();
9239             }
9240           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9241                        BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
9242           if (mips_relax.sequence)
9243             relax_end ();
9244         }
9245       else
9246         {
9247           ex.X_add_number = ep->X_add_number;
9248           ep->X_add_number = 0;
9249           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9250                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9251           load_delay_nop ();
9252           relax_start (ep->X_add_symbol);
9253           relax_switch ();
9254           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9255                        BFD_RELOC_LO16);
9256           relax_end ();
9257
9258           if (ex.X_add_number != 0)
9259             {
9260               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9261                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9262               ex.X_op = O_constant;
9263               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j",
9264                            reg, reg, BFD_RELOC_LO16);
9265             }
9266         }
9267     }
9268   else if (mips_big_got)
9269     {
9270       expressionS ex;
9271
9272       /* This is the large GOT case.  If this is a reference to an
9273          external symbol, we want
9274            lui          $reg,<sym>              (BFD_RELOC_MIPS_GOT_HI16)
9275            addu         $reg,$reg,$gp
9276            lw           $reg,<sym>($reg)        (BFD_RELOC_MIPS_GOT_LO16)
9277
9278          Otherwise, for a reference to a local symbol in old ABI, we want
9279            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT16)
9280            nop
9281            addiu        $reg,$reg,<sym>         (BFD_RELOC_LO16)
9282          If there is a constant, it must be added in after.
9283
9284          In the NewABI, for local symbols, with or without offsets, we want:
9285            lw           $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
9286            addiu        $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
9287       */
9288       if (HAVE_NEWABI)
9289         {
9290           ex.X_add_number = ep->X_add_number;
9291           ep->X_add_number = 0;
9292           relax_start (ep->X_add_symbol);
9293           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9294           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9295                        reg, reg, mips_gp_register);
9296           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9297                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9298           if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9299             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9300           else if (ex.X_add_number)
9301             {
9302               ex.X_op = O_constant;
9303               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9304                            BFD_RELOC_LO16);
9305             }
9306
9307           ep->X_add_number = ex.X_add_number;
9308           relax_switch ();
9309           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9310                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
9311           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9312                        BFD_RELOC_MIPS_GOT_OFST);
9313           relax_end ();
9314         }
9315       else
9316         {
9317           ex.X_add_number = ep->X_add_number;
9318           ep->X_add_number = 0;
9319           relax_start (ep->X_add_symbol);
9320           macro_build (ep, "lui", LUI_FMT, reg, BFD_RELOC_MIPS_GOT_HI16);
9321           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
9322                        reg, reg, mips_gp_register);
9323           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)",
9324                        reg, BFD_RELOC_MIPS_GOT_LO16, reg);
9325           relax_switch ();
9326           if (reg_needs_delay (mips_gp_register))
9327             {
9328               /* We need a nop before loading from $gp.  This special
9329                  check is required because the lui which starts the main
9330                  instruction stream does not refer to $gp, and so will not
9331                  insert the nop which may be required.  */
9332               macro_build (NULL, "nop", "");
9333             }
9334           macro_build (ep, ADDRESS_LOAD_INSN, "t,o(b)", reg,
9335                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
9336           load_delay_nop ();
9337           macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9338                        BFD_RELOC_LO16);
9339           relax_end ();
9340
9341           if (ex.X_add_number != 0)
9342             {
9343               if (ex.X_add_number < -0x8000 || ex.X_add_number >= 0x8000)
9344                 as_bad (_("PIC code offset overflow (max 16 signed bits)"));
9345               ex.X_op = O_constant;
9346               macro_build (&ex, ADDRESS_ADDI_INSN, "t,r,j", reg, reg,
9347                            BFD_RELOC_LO16);
9348             }
9349         }
9350     }
9351   else
9352     abort ();
9353
9354   if (!mips_opts.at && *used_at == 1)
9355     as_bad (_("macro used $at after \".set noat\""));
9356 }
9357
9358 /* Move the contents of register SOURCE into register DEST.  */
9359
9360 static void
9361 move_register (int dest, int source)
9362 {
9363   /* Prefer to use a 16-bit microMIPS instruction unless the previous
9364      instruction specifically requires a 32-bit one.  */
9365   if (mips_opts.micromips
9366       && !mips_opts.insn32
9367       && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
9368     macro_build (NULL, "move", "mp,mj", dest, source);
9369   else
9370     macro_build (NULL, "or", "d,v,t", dest, source, 0);
9371 }
9372
9373 /* Emit an SVR4 PIC sequence to load address LOCAL into DEST, where
9374    LOCAL is the sum of a symbol and a 16-bit or 32-bit displacement.
9375    The two alternatives are:
9376
9377    Global symbol                Local sybmol
9378    -------------                ------------
9379    lw DEST,%got(SYMBOL)         lw DEST,%got(SYMBOL + OFFSET)
9380    ...                          ...
9381    addiu DEST,DEST,OFFSET       addiu DEST,DEST,%lo(SYMBOL + OFFSET)
9382
9383    load_got_offset emits the first instruction and add_got_offset
9384    emits the second for a 16-bit offset or add_got_offset_hilo emits
9385    a sequence to add a 32-bit offset using a scratch register.  */
9386
9387 static void
9388 load_got_offset (int dest, expressionS *local)
9389 {
9390   expressionS global;
9391
9392   global = *local;
9393   global.X_add_number = 0;
9394
9395   relax_start (local->X_add_symbol);
9396   macro_build (&global, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9397                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9398   relax_switch ();
9399   macro_build (local, ADDRESS_LOAD_INSN, "t,o(b)", dest,
9400                BFD_RELOC_MIPS_GOT16, mips_gp_register);
9401   relax_end ();
9402 }
9403
9404 static void
9405 add_got_offset (int dest, expressionS *local)
9406 {
9407   expressionS global;
9408
9409   global.X_op = O_constant;
9410   global.X_op_symbol = NULL;
9411   global.X_add_symbol = NULL;
9412   global.X_add_number = local->X_add_number;
9413
9414   relax_start (local->X_add_symbol);
9415   macro_build (&global, ADDRESS_ADDI_INSN, "t,r,j",
9416                dest, dest, BFD_RELOC_LO16);
9417   relax_switch ();
9418   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", dest, dest, BFD_RELOC_LO16);
9419   relax_end ();
9420 }
9421
9422 static void
9423 add_got_offset_hilo (int dest, expressionS *local, int tmp)
9424 {
9425   expressionS global;
9426   int hold_mips_optimize;
9427
9428   global.X_op = O_constant;
9429   global.X_op_symbol = NULL;
9430   global.X_add_symbol = NULL;
9431   global.X_add_number = local->X_add_number;
9432
9433   relax_start (local->X_add_symbol);
9434   load_register (tmp, &global, HAVE_64BIT_ADDRESSES);
9435   relax_switch ();
9436   /* Set mips_optimize around the lui instruction to avoid
9437      inserting an unnecessary nop after the lw.  */
9438   hold_mips_optimize = mips_optimize;
9439   mips_optimize = 2;
9440   macro_build_lui (&global, tmp);
9441   mips_optimize = hold_mips_optimize;
9442   macro_build (local, ADDRESS_ADDI_INSN, "t,r,j", tmp, tmp, BFD_RELOC_LO16);
9443   relax_end ();
9444
9445   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dest, dest, tmp);
9446 }
9447
9448 /* Emit a sequence of instructions to emulate a branch likely operation.
9449    BR is an ordinary branch corresponding to one to be emulated.  BRNEG
9450    is its complementing branch with the original condition negated.
9451    CALL is set if the original branch specified the link operation.
9452    EP, FMT, SREG and TREG specify the usual macro_build() parameters.
9453
9454    Code like this is produced in the noreorder mode:
9455
9456         BRNEG   <args>, 1f
9457          nop
9458         b       <sym>
9459          delay slot (executed only if branch taken)
9460     1:
9461
9462    or, if CALL is set:
9463
9464         BRNEG   <args>, 1f
9465          nop
9466         bal     <sym>
9467          delay slot (executed only if branch taken)
9468     1:
9469
9470    In the reorder mode the delay slot would be filled with a nop anyway,
9471    so code produced is simply:
9472
9473         BR      <args>, <sym>
9474          nop
9475
9476    This function is used when producing code for the microMIPS ASE that
9477    does not implement branch likely instructions in hardware.  */
9478
9479 static void
9480 macro_build_branch_likely (const char *br, const char *brneg,
9481                            int call, expressionS *ep, const char *fmt,
9482                            unsigned int sreg, unsigned int treg)
9483 {
9484   int noreorder = mips_opts.noreorder;
9485   expressionS expr1;
9486
9487   gas_assert (mips_opts.micromips);
9488   start_noreorder ();
9489   if (noreorder)
9490     {
9491       micromips_label_expr (&expr1);
9492       macro_build (&expr1, brneg, fmt, sreg, treg);
9493       macro_build (NULL, "nop", "");
9494       macro_build (ep, call ? "bal" : "b", "p");
9495
9496       /* Set to true so that append_insn adds a label.  */
9497       emit_branch_likely_macro = TRUE;
9498     }
9499   else
9500     {
9501       macro_build (ep, br, fmt, sreg, treg);
9502       macro_build (NULL, "nop", "");
9503     }
9504   end_noreorder ();
9505 }
9506
9507 /* Emit a coprocessor branch-likely macro specified by TYPE, using CC as
9508    the condition code tested.  EP specifies the branch target.  */
9509
9510 static void
9511 macro_build_branch_ccl (int type, expressionS *ep, unsigned int cc)
9512 {
9513   const int call = 0;
9514   const char *brneg;
9515   const char *br;
9516
9517   switch (type)
9518     {
9519     case M_BC1FL:
9520       br = "bc1f";
9521       brneg = "bc1t";
9522       break;
9523     case M_BC1TL:
9524       br = "bc1t";
9525       brneg = "bc1f";
9526       break;
9527     case M_BC2FL:
9528       br = "bc2f";
9529       brneg = "bc2t";
9530       break;
9531     case M_BC2TL:
9532       br = "bc2t";
9533       brneg = "bc2f";
9534       break;
9535     default:
9536       abort ();
9537     }
9538   macro_build_branch_likely (br, brneg, call, ep, "N,p", cc, ZERO);
9539 }
9540
9541 /* Emit a two-argument branch macro specified by TYPE, using SREG as
9542    the register tested.  EP specifies the branch target.  */
9543
9544 static void
9545 macro_build_branch_rs (int type, expressionS *ep, unsigned int sreg)
9546 {
9547   const char *brneg = NULL;
9548   const char *br;
9549   int call = 0;
9550
9551   switch (type)
9552     {
9553     case M_BGEZ:
9554       br = "bgez";
9555       break;
9556     case M_BGEZL:
9557       br = mips_opts.micromips ? "bgez" : "bgezl";
9558       brneg = "bltz";
9559       break;
9560     case M_BGEZALL:
9561       gas_assert (mips_opts.micromips);
9562       br = mips_opts.insn32 ? "bgezal" : "bgezals";
9563       brneg = "bltz";
9564       call = 1;
9565       break;
9566     case M_BGTZ:
9567       br = "bgtz";
9568       break;
9569     case M_BGTZL:
9570       br = mips_opts.micromips ? "bgtz" : "bgtzl";
9571       brneg = "blez";
9572       break;
9573     case M_BLEZ:
9574       br = "blez";
9575       break;
9576     case M_BLEZL:
9577       br = mips_opts.micromips ? "blez" : "blezl";
9578       brneg = "bgtz";
9579       break;
9580     case M_BLTZ:
9581       br = "bltz";
9582       break;
9583     case M_BLTZL:
9584       br = mips_opts.micromips ? "bltz" : "bltzl";
9585       brneg = "bgez";
9586       break;
9587     case M_BLTZALL:
9588       gas_assert (mips_opts.micromips);
9589       br = mips_opts.insn32 ? "bltzal" : "bltzals";
9590       brneg = "bgez";
9591       call = 1;
9592       break;
9593     default:
9594       abort ();
9595     }
9596   if (mips_opts.micromips && brneg)
9597     macro_build_branch_likely (br, brneg, call, ep, "s,p", sreg, ZERO);
9598   else
9599     macro_build (ep, br, "s,p", sreg);
9600 }
9601
9602 /* Emit a three-argument branch macro specified by TYPE, using SREG and
9603    TREG as the registers tested.  EP specifies the branch target.  */
9604
9605 static void
9606 macro_build_branch_rsrt (int type, expressionS *ep,
9607                          unsigned int sreg, unsigned int treg)
9608 {
9609   const char *brneg = NULL;
9610   const int call = 0;
9611   const char *br;
9612
9613   switch (type)
9614     {
9615     case M_BEQ:
9616     case M_BEQ_I:
9617       br = "beq";
9618       break;
9619     case M_BEQL:
9620     case M_BEQL_I:
9621       br = mips_opts.micromips ? "beq" : "beql";
9622       brneg = "bne";
9623       break;
9624     case M_BNE:
9625     case M_BNE_I:
9626       br = "bne";
9627       break;
9628     case M_BNEL:
9629     case M_BNEL_I:
9630       br = mips_opts.micromips ? "bne" : "bnel";
9631       brneg = "beq";
9632       break;
9633     default:
9634       abort ();
9635     }
9636   if (mips_opts.micromips && brneg)
9637     macro_build_branch_likely (br, brneg, call, ep, "s,t,p", sreg, treg);
9638   else
9639     macro_build (ep, br, "s,t,p", sreg, treg);
9640 }
9641
9642 /* Return the high part that should be loaded in order to make the low
9643    part of VALUE accessible using an offset of OFFBITS bits.  */
9644
9645 static offsetT
9646 offset_high_part (offsetT value, unsigned int offbits)
9647 {
9648   offsetT bias;
9649   addressT low_mask;
9650
9651   if (offbits == 0)
9652     return value;
9653   bias = 1 << (offbits - 1);
9654   low_mask = bias * 2 - 1;
9655   return (value + bias) & ~low_mask;
9656 }
9657
9658 /* Return true if the value stored in offset_expr and offset_reloc
9659    fits into a signed offset of OFFBITS bits.  RANGE is the maximum
9660    amount that the caller wants to add without inducing overflow
9661    and ALIGN is the known alignment of the value in bytes.  */
9662
9663 static bfd_boolean
9664 small_offset_p (unsigned int range, unsigned int align, unsigned int offbits)
9665 {
9666   if (offbits == 16)
9667     {
9668       /* Accept any relocation operator if overflow isn't a concern.  */
9669       if (range < align && *offset_reloc != BFD_RELOC_UNUSED)
9670         return TRUE;
9671
9672       /* These relocations are guaranteed not to overflow in correct links.  */
9673       if (*offset_reloc == BFD_RELOC_MIPS_LITERAL
9674           || gprel16_reloc_p (*offset_reloc))
9675         return TRUE;
9676     }
9677   if (offset_expr.X_op == O_constant
9678       && offset_high_part (offset_expr.X_add_number, offbits) == 0
9679       && offset_high_part (offset_expr.X_add_number + range, offbits) == 0)
9680     return TRUE;
9681   return FALSE;
9682 }
9683
9684 /*
9685  *                      Build macros
9686  *   This routine implements the seemingly endless macro or synthesized
9687  * instructions and addressing modes in the mips assembly language. Many
9688  * of these macros are simple and are similar to each other. These could
9689  * probably be handled by some kind of table or grammar approach instead of
9690  * this verbose method. Others are not simple macros but are more like
9691  * optimizing code generation.
9692  *   One interesting optimization is when several store macros appear
9693  * consecutively that would load AT with the upper half of the same address.
9694  * The ensuing load upper instructions are ommited. This implies some kind
9695  * of global optimization. We currently only optimize within a single macro.
9696  *   For many of the load and store macros if the address is specified as a
9697  * constant expression in the first 64k of memory (ie ld $2,0x4000c) we
9698  * first load register 'at' with zero and use it as the base register. The
9699  * mips assembler simply uses register $zero. Just one tiny optimization
9700  * we're missing.
9701  */
9702 static void
9703 macro (struct mips_cl_insn *ip, char *str)
9704 {
9705   const struct mips_operand_array *operands;
9706   unsigned int breg, i;
9707   unsigned int tempreg;
9708   int mask;
9709   int used_at = 0;
9710   expressionS label_expr;
9711   expressionS expr1;
9712   expressionS *ep;
9713   const char *s;
9714   const char *s2;
9715   const char *fmt;
9716   int likely = 0;
9717   int coproc = 0;
9718   int offbits = 16;
9719   int call = 0;
9720   int jals = 0;
9721   int dbl = 0;
9722   int imm = 0;
9723   int ust = 0;
9724   int lp = 0;
9725   bfd_boolean large_offset;
9726   int off;
9727   int hold_mips_optimize;
9728   unsigned int align;
9729   unsigned int op[MAX_OPERANDS];
9730
9731   gas_assert (! mips_opts.mips16);
9732
9733   operands = insn_operands (ip);
9734   for (i = 0; i < MAX_OPERANDS; i++)
9735     if (operands->operand[i])
9736       op[i] = insn_extract_operand (ip, operands->operand[i]);
9737     else
9738       op[i] = -1;
9739
9740   mask = ip->insn_mo->mask;
9741
9742   label_expr.X_op = O_constant;
9743   label_expr.X_op_symbol = NULL;
9744   label_expr.X_add_symbol = NULL;
9745   label_expr.X_add_number = 0;
9746
9747   expr1.X_op = O_constant;
9748   expr1.X_op_symbol = NULL;
9749   expr1.X_add_symbol = NULL;
9750   expr1.X_add_number = 1;
9751   align = 1;
9752
9753   switch (mask)
9754     {
9755     case M_DABS:
9756       dbl = 1;
9757     case M_ABS:
9758       /*    bgez    $a0,1f
9759             move    v0,$a0
9760             sub     v0,$zero,$a0
9761          1:
9762        */
9763
9764       start_noreorder ();
9765
9766       if (mips_opts.micromips)
9767         micromips_label_expr (&label_expr);
9768       else
9769         label_expr.X_add_number = 8;
9770       macro_build (&label_expr, "bgez", "s,p", op[1]);
9771       if (op[0] == op[1])
9772         macro_build (NULL, "nop", "");
9773       else
9774         move_register (op[0], op[1]);
9775       macro_build (NULL, dbl ? "dsub" : "sub", "d,v,t", op[0], 0, op[1]);
9776       if (mips_opts.micromips)
9777         micromips_add_label ();
9778
9779       end_noreorder ();
9780       break;
9781
9782     case M_ADD_I:
9783       s = "addi";
9784       s2 = "add";
9785       goto do_addi;
9786     case M_ADDU_I:
9787       s = "addiu";
9788       s2 = "addu";
9789       goto do_addi;
9790     case M_DADD_I:
9791       dbl = 1;
9792       s = "daddi";
9793       s2 = "dadd";
9794       if (!mips_opts.micromips)
9795         goto do_addi;
9796       if (imm_expr.X_add_number >= -0x200
9797           && imm_expr.X_add_number < 0x200)
9798         {
9799           macro_build (NULL, s, "t,r,.", op[0], op[1],
9800                        (int) imm_expr.X_add_number);
9801           break;
9802         }
9803       goto do_addi_i;
9804     case M_DADDU_I:
9805       dbl = 1;
9806       s = "daddiu";
9807       s2 = "daddu";
9808     do_addi:
9809       if (imm_expr.X_add_number >= -0x8000
9810           && imm_expr.X_add_number < 0x8000)
9811         {
9812           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
9813           break;
9814         }
9815     do_addi_i:
9816       used_at = 1;
9817       load_register (AT, &imm_expr, dbl);
9818       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9819       break;
9820
9821     case M_AND_I:
9822       s = "andi";
9823       s2 = "and";
9824       goto do_bit;
9825     case M_OR_I:
9826       s = "ori";
9827       s2 = "or";
9828       goto do_bit;
9829     case M_NOR_I:
9830       s = "";
9831       s2 = "nor";
9832       goto do_bit;
9833     case M_XOR_I:
9834       s = "xori";
9835       s2 = "xor";
9836     do_bit:
9837       if (imm_expr.X_add_number >= 0
9838           && imm_expr.X_add_number < 0x10000)
9839         {
9840           if (mask != M_NOR_I)
9841             macro_build (&imm_expr, s, "t,r,i", op[0], op[1], BFD_RELOC_LO16);
9842           else
9843             {
9844               macro_build (&imm_expr, "ori", "t,r,i",
9845                            op[0], op[1], BFD_RELOC_LO16);
9846               macro_build (NULL, "nor", "d,v,t", op[0], op[0], 0);
9847             }
9848           break;
9849         }
9850
9851       used_at = 1;
9852       load_register (AT, &imm_expr, GPR_SIZE == 64);
9853       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
9854       break;
9855
9856     case M_BALIGN:
9857       switch (imm_expr.X_add_number)
9858         {
9859         case 0:
9860           macro_build (NULL, "nop", "");
9861           break;
9862         case 2:
9863           macro_build (NULL, "packrl.ph", "d,s,t", op[0], op[0], op[1]);
9864           break;
9865         case 1:
9866         case 3:
9867           macro_build (NULL, "balign", "t,s,2", op[0], op[1],
9868                        (int) imm_expr.X_add_number);
9869           break;
9870         default:
9871           as_bad (_("BALIGN immediate not 0, 1, 2 or 3 (%lu)"),
9872                   (unsigned long) imm_expr.X_add_number);
9873           break;
9874         }
9875       break;
9876
9877     case M_BC1FL:
9878     case M_BC1TL:
9879     case M_BC2FL:
9880     case M_BC2TL:
9881       gas_assert (mips_opts.micromips);
9882       macro_build_branch_ccl (mask, &offset_expr,
9883                               EXTRACT_OPERAND (1, BCC, *ip));
9884       break;
9885
9886     case M_BEQ_I:
9887     case M_BEQL_I:
9888     case M_BNE_I:
9889     case M_BNEL_I:
9890       if (imm_expr.X_add_number == 0)
9891         op[1] = 0;
9892       else
9893         {
9894           op[1] = AT;
9895           used_at = 1;
9896           load_register (op[1], &imm_expr, GPR_SIZE == 64);
9897         }
9898       /* Fall through.  */
9899     case M_BEQL:
9900     case M_BNEL:
9901       macro_build_branch_rsrt (mask, &offset_expr, op[0], op[1]);
9902       break;
9903
9904     case M_BGEL:
9905       likely = 1;
9906     case M_BGE:
9907       if (op[1] == 0)
9908         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[0]);
9909       else if (op[0] == 0)
9910         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[1]);
9911       else
9912         {
9913           used_at = 1;
9914           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
9915           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9916                                    &offset_expr, AT, ZERO);
9917         }
9918       break;
9919
9920     case M_BGEZL:
9921     case M_BGEZALL:
9922     case M_BGTZL:
9923     case M_BLEZL:
9924     case M_BLTZL:
9925     case M_BLTZALL:
9926       macro_build_branch_rs (mask, &offset_expr, op[0]);
9927       break;
9928
9929     case M_BGTL_I:
9930       likely = 1;
9931     case M_BGT_I:
9932       /* Check for > max integer.  */
9933       if (imm_expr.X_add_number >= GPR_SMAX)
9934         {
9935         do_false:
9936           /* Result is always false.  */
9937           if (! likely)
9938             macro_build (NULL, "nop", "");
9939           else
9940             macro_build_branch_rsrt (M_BNEL, &offset_expr, ZERO, ZERO);
9941           break;
9942         }
9943       ++imm_expr.X_add_number;
9944       /* FALLTHROUGH */
9945     case M_BGE_I:
9946     case M_BGEL_I:
9947       if (mask == M_BGEL_I)
9948         likely = 1;
9949       if (imm_expr.X_add_number == 0)
9950         {
9951           macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ,
9952                                  &offset_expr, op[0]);
9953           break;
9954         }
9955       if (imm_expr.X_add_number == 1)
9956         {
9957           macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ,
9958                                  &offset_expr, op[0]);
9959           break;
9960         }
9961       if (imm_expr.X_add_number <= GPR_SMIN)
9962         {
9963         do_true:
9964           /* result is always true */
9965           as_warn (_("branch %s is always true"), ip->insn_mo->name);
9966           macro_build (&offset_expr, "b", "p");
9967           break;
9968         }
9969       used_at = 1;
9970       set_at (op[0], 0);
9971       macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9972                                &offset_expr, AT, ZERO);
9973       break;
9974
9975     case M_BGEUL:
9976       likely = 1;
9977     case M_BGEU:
9978       if (op[1] == 0)
9979         goto do_true;
9980       else if (op[0] == 0)
9981         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9982                                  &offset_expr, ZERO, op[1]);
9983       else
9984         {
9985           used_at = 1;
9986           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
9987           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
9988                                    &offset_expr, AT, ZERO);
9989         }
9990       break;
9991
9992     case M_BGTUL_I:
9993       likely = 1;
9994     case M_BGTU_I:
9995       if (op[0] == 0
9996           || (GPR_SIZE == 32
9997               && imm_expr.X_add_number == -1))
9998         goto do_false;
9999       ++imm_expr.X_add_number;
10000       /* FALLTHROUGH */
10001     case M_BGEU_I:
10002     case M_BGEUL_I:
10003       if (mask == M_BGEUL_I)
10004         likely = 1;
10005       if (imm_expr.X_add_number == 0)
10006         goto do_true;
10007       else if (imm_expr.X_add_number == 1)
10008         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10009                                  &offset_expr, op[0], ZERO);
10010       else
10011         {
10012           used_at = 1;
10013           set_at (op[0], 1);
10014           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10015                                    &offset_expr, AT, ZERO);
10016         }
10017       break;
10018
10019     case M_BGTL:
10020       likely = 1;
10021     case M_BGT:
10022       if (op[1] == 0)
10023         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[0]);
10024       else if (op[0] == 0)
10025         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[1]);
10026       else
10027         {
10028           used_at = 1;
10029           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10030           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10031                                    &offset_expr, AT, ZERO);
10032         }
10033       break;
10034
10035     case M_BGTUL:
10036       likely = 1;
10037     case M_BGTU:
10038       if (op[1] == 0)
10039         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10040                                  &offset_expr, op[0], ZERO);
10041       else if (op[0] == 0)
10042         goto do_false;
10043       else
10044         {
10045           used_at = 1;
10046           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10047           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10048                                    &offset_expr, AT, ZERO);
10049         }
10050       break;
10051
10052     case M_BLEL:
10053       likely = 1;
10054     case M_BLE:
10055       if (op[1] == 0)
10056         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10057       else if (op[0] == 0)
10058         macro_build_branch_rs (likely ? M_BGEZL : M_BGEZ, &offset_expr, op[1]);
10059       else
10060         {
10061           used_at = 1;
10062           macro_build (NULL, "slt", "d,v,t", AT, op[1], op[0]);
10063           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10064                                    &offset_expr, AT, ZERO);
10065         }
10066       break;
10067
10068     case M_BLEL_I:
10069       likely = 1;
10070     case M_BLE_I:
10071       if (imm_expr.X_add_number >= GPR_SMAX)
10072         goto do_true;
10073       ++imm_expr.X_add_number;
10074       /* FALLTHROUGH */
10075     case M_BLT_I:
10076     case M_BLTL_I:
10077       if (mask == M_BLTL_I)
10078         likely = 1;
10079       if (imm_expr.X_add_number == 0)
10080         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10081       else if (imm_expr.X_add_number == 1)
10082         macro_build_branch_rs (likely ? M_BLEZL : M_BLEZ, &offset_expr, op[0]);
10083       else
10084         {
10085           used_at = 1;
10086           set_at (op[0], 0);
10087           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10088                                    &offset_expr, AT, ZERO);
10089         }
10090       break;
10091
10092     case M_BLEUL:
10093       likely = 1;
10094     case M_BLEU:
10095       if (op[1] == 0)
10096         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10097                                  &offset_expr, op[0], ZERO);
10098       else if (op[0] == 0)
10099         goto do_true;
10100       else
10101         {
10102           used_at = 1;
10103           macro_build (NULL, "sltu", "d,v,t", AT, op[1], op[0]);
10104           macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10105                                    &offset_expr, AT, ZERO);
10106         }
10107       break;
10108
10109     case M_BLEUL_I:
10110       likely = 1;
10111     case M_BLEU_I:
10112       if (op[0] == 0
10113           || (GPR_SIZE == 32
10114               && imm_expr.X_add_number == -1))
10115         goto do_true;
10116       ++imm_expr.X_add_number;
10117       /* FALLTHROUGH */
10118     case M_BLTU_I:
10119     case M_BLTUL_I:
10120       if (mask == M_BLTUL_I)
10121         likely = 1;
10122       if (imm_expr.X_add_number == 0)
10123         goto do_false;
10124       else if (imm_expr.X_add_number == 1)
10125         macro_build_branch_rsrt (likely ? M_BEQL : M_BEQ,
10126                                  &offset_expr, op[0], ZERO);
10127       else
10128         {
10129           used_at = 1;
10130           set_at (op[0], 1);
10131           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10132                                    &offset_expr, AT, ZERO);
10133         }
10134       break;
10135
10136     case M_BLTL:
10137       likely = 1;
10138     case M_BLT:
10139       if (op[1] == 0)
10140         macro_build_branch_rs (likely ? M_BLTZL : M_BLTZ, &offset_expr, op[0]);
10141       else if (op[0] == 0)
10142         macro_build_branch_rs (likely ? M_BGTZL : M_BGTZ, &offset_expr, op[1]);
10143       else
10144         {
10145           used_at = 1;
10146           macro_build (NULL, "slt", "d,v,t", AT, op[0], op[1]);
10147           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10148                                    &offset_expr, AT, ZERO);
10149         }
10150       break;
10151
10152     case M_BLTUL:
10153       likely = 1;
10154     case M_BLTU:
10155       if (op[1] == 0)
10156         goto do_false;
10157       else if (op[0] == 0)
10158         macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10159                                  &offset_expr, ZERO, op[1]);
10160       else
10161         {
10162           used_at = 1;
10163           macro_build (NULL, "sltu", "d,v,t", AT, op[0], op[1]);
10164           macro_build_branch_rsrt (likely ? M_BNEL : M_BNE,
10165                                    &offset_expr, AT, ZERO);
10166         }
10167       break;
10168
10169     case M_DDIV_3:
10170       dbl = 1;
10171     case M_DIV_3:
10172       s = "mflo";
10173       goto do_div3;
10174     case M_DREM_3:
10175       dbl = 1;
10176     case M_REM_3:
10177       s = "mfhi";
10178     do_div3:
10179       if (op[2] == 0)
10180         {
10181           as_warn (_("divide by zero"));
10182           if (mips_trap)
10183             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10184           else
10185             macro_build (NULL, "break", BRK_FMT, 7);
10186           break;
10187         }
10188
10189       start_noreorder ();
10190       if (mips_trap)
10191         {
10192           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10193           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10194         }
10195       else
10196         {
10197           if (mips_opts.micromips)
10198             micromips_label_expr (&label_expr);
10199           else
10200             label_expr.X_add_number = 8;
10201           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10202           macro_build (NULL, dbl ? "ddiv" : "div", "z,s,t", op[1], op[2]);
10203           macro_build (NULL, "break", BRK_FMT, 7);
10204           if (mips_opts.micromips)
10205             micromips_add_label ();
10206         }
10207       expr1.X_add_number = -1;
10208       used_at = 1;
10209       load_register (AT, &expr1, dbl);
10210       if (mips_opts.micromips)
10211         micromips_label_expr (&label_expr);
10212       else
10213         label_expr.X_add_number = mips_trap ? (dbl ? 12 : 8) : (dbl ? 20 : 16);
10214       macro_build (&label_expr, "bne", "s,t,p", op[2], AT);
10215       if (dbl)
10216         {
10217           expr1.X_add_number = 1;
10218           load_register (AT, &expr1, dbl);
10219           macro_build (NULL, "dsll32", SHFT_FMT, AT, AT, 31);
10220         }
10221       else
10222         {
10223           expr1.X_add_number = 0x80000000;
10224           macro_build (&expr1, "lui", LUI_FMT, AT, BFD_RELOC_HI16);
10225         }
10226       if (mips_trap)
10227         {
10228           macro_build (NULL, "teq", TRAP_FMT, op[1], AT, 6);
10229           /* We want to close the noreorder block as soon as possible, so
10230              that later insns are available for delay slot filling.  */
10231           end_noreorder ();
10232         }
10233       else
10234         {
10235           if (mips_opts.micromips)
10236             micromips_label_expr (&label_expr);
10237           else
10238             label_expr.X_add_number = 8;
10239           macro_build (&label_expr, "bne", "s,t,p", op[1], AT);
10240           macro_build (NULL, "nop", "");
10241
10242           /* We want to close the noreorder block as soon as possible, so
10243              that later insns are available for delay slot filling.  */
10244           end_noreorder ();
10245
10246           macro_build (NULL, "break", BRK_FMT, 6);
10247         }
10248       if (mips_opts.micromips)
10249         micromips_add_label ();
10250       macro_build (NULL, s, MFHL_FMT, op[0]);
10251       break;
10252
10253     case M_DIV_3I:
10254       s = "div";
10255       s2 = "mflo";
10256       goto do_divi;
10257     case M_DIVU_3I:
10258       s = "divu";
10259       s2 = "mflo";
10260       goto do_divi;
10261     case M_REM_3I:
10262       s = "div";
10263       s2 = "mfhi";
10264       goto do_divi;
10265     case M_REMU_3I:
10266       s = "divu";
10267       s2 = "mfhi";
10268       goto do_divi;
10269     case M_DDIV_3I:
10270       dbl = 1;
10271       s = "ddiv";
10272       s2 = "mflo";
10273       goto do_divi;
10274     case M_DDIVU_3I:
10275       dbl = 1;
10276       s = "ddivu";
10277       s2 = "mflo";
10278       goto do_divi;
10279     case M_DREM_3I:
10280       dbl = 1;
10281       s = "ddiv";
10282       s2 = "mfhi";
10283       goto do_divi;
10284     case M_DREMU_3I:
10285       dbl = 1;
10286       s = "ddivu";
10287       s2 = "mfhi";
10288     do_divi:
10289       if (imm_expr.X_add_number == 0)
10290         {
10291           as_warn (_("divide by zero"));
10292           if (mips_trap)
10293             macro_build (NULL, "teq", TRAP_FMT, ZERO, ZERO, 7);
10294           else
10295             macro_build (NULL, "break", BRK_FMT, 7);
10296           break;
10297         }
10298       if (imm_expr.X_add_number == 1)
10299         {
10300           if (strcmp (s2, "mflo") == 0)
10301             move_register (op[0], op[1]);
10302           else
10303             move_register (op[0], ZERO);
10304           break;
10305         }
10306       if (imm_expr.X_add_number == -1 && s[strlen (s) - 1] != 'u')
10307         {
10308           if (strcmp (s2, "mflo") == 0)
10309             macro_build (NULL, dbl ? "dneg" : "neg", "d,w", op[0], op[1]);
10310           else
10311             move_register (op[0], ZERO);
10312           break;
10313         }
10314
10315       used_at = 1;
10316       load_register (AT, &imm_expr, dbl);
10317       macro_build (NULL, s, "z,s,t", op[1], AT);
10318       macro_build (NULL, s2, MFHL_FMT, op[0]);
10319       break;
10320
10321     case M_DIVU_3:
10322       s = "divu";
10323       s2 = "mflo";
10324       goto do_divu3;
10325     case M_REMU_3:
10326       s = "divu";
10327       s2 = "mfhi";
10328       goto do_divu3;
10329     case M_DDIVU_3:
10330       s = "ddivu";
10331       s2 = "mflo";
10332       goto do_divu3;
10333     case M_DREMU_3:
10334       s = "ddivu";
10335       s2 = "mfhi";
10336     do_divu3:
10337       start_noreorder ();
10338       if (mips_trap)
10339         {
10340           macro_build (NULL, "teq", TRAP_FMT, op[2], ZERO, 7);
10341           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10342           /* We want to close the noreorder block as soon as possible, so
10343              that later insns are available for delay slot filling.  */
10344           end_noreorder ();
10345         }
10346       else
10347         {
10348           if (mips_opts.micromips)
10349             micromips_label_expr (&label_expr);
10350           else
10351             label_expr.X_add_number = 8;
10352           macro_build (&label_expr, "bne", "s,t,p", op[2], ZERO);
10353           macro_build (NULL, s, "z,s,t", op[1], op[2]);
10354
10355           /* We want to close the noreorder block as soon as possible, so
10356              that later insns are available for delay slot filling.  */
10357           end_noreorder ();
10358           macro_build (NULL, "break", BRK_FMT, 7);
10359           if (mips_opts.micromips)
10360             micromips_add_label ();
10361         }
10362       macro_build (NULL, s2, MFHL_FMT, op[0]);
10363       break;
10364
10365     case M_DLCA_AB:
10366       dbl = 1;
10367     case M_LCA_AB:
10368       call = 1;
10369       goto do_la;
10370     case M_DLA_AB:
10371       dbl = 1;
10372     case M_LA_AB:
10373     do_la:
10374       /* Load the address of a symbol into a register.  If breg is not
10375          zero, we then add a base register to it.  */
10376
10377       breg = op[2];
10378       if (dbl && GPR_SIZE == 32)
10379         as_warn (_("dla used to load 32-bit register; recommend using la "
10380                    "instead"));
10381
10382       if (!dbl && HAVE_64BIT_OBJECTS)
10383         as_warn (_("la used to load 64-bit address; recommend using dla "
10384                    "instead"));
10385
10386       if (small_offset_p (0, align, 16))
10387         {
10388           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", op[0], breg,
10389                        -1, offset_reloc[0], offset_reloc[1], offset_reloc[2]);
10390           break;
10391         }
10392
10393       if (mips_opts.at && (op[0] == breg))
10394         {
10395           tempreg = AT;
10396           used_at = 1;
10397         }
10398       else
10399         tempreg = op[0];
10400
10401       if (offset_expr.X_op != O_symbol
10402           && offset_expr.X_op != O_constant)
10403         {
10404           as_bad (_("expression too complex"));
10405           offset_expr.X_op = O_constant;
10406         }
10407
10408       if (offset_expr.X_op == O_constant)
10409         load_register (tempreg, &offset_expr, HAVE_64BIT_ADDRESSES);
10410       else if (mips_pic == NO_PIC)
10411         {
10412           /* If this is a reference to a GP relative symbol, we want
10413                addiu    $tempreg,$gp,<sym>      (BFD_RELOC_GPREL16)
10414              Otherwise we want
10415                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
10416                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10417              If we have a constant, we need two instructions anyhow,
10418              so we may as well always use the latter form.
10419
10420              With 64bit address space and a usable $at we want
10421                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10422                lui      $at,<sym>               (BFD_RELOC_HI16_S)
10423                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10424                daddiu   $at,<sym>               (BFD_RELOC_LO16)
10425                dsll32   $tempreg,0
10426                daddu    $tempreg,$tempreg,$at
10427
10428              If $at is already in use, we use a path which is suboptimal
10429              on superscalar processors.
10430                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
10431                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
10432                dsll     $tempreg,16
10433                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
10434                dsll     $tempreg,16
10435                daddiu   $tempreg,<sym>          (BFD_RELOC_LO16)
10436
10437              For GP relative symbols in 64bit address space we can use
10438              the same sequence as in 32bit address space.  */
10439           if (HAVE_64BIT_SYMBOLS)
10440             {
10441               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10442                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10443                 {
10444                   relax_start (offset_expr.X_add_symbol);
10445                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10446                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10447                   relax_switch ();
10448                 }
10449
10450               if (used_at == 0 && mips_opts.at)
10451                 {
10452                   macro_build (&offset_expr, "lui", LUI_FMT,
10453                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10454                   macro_build (&offset_expr, "lui", LUI_FMT,
10455                                AT, BFD_RELOC_HI16_S);
10456                   macro_build (&offset_expr, "daddiu", "t,r,j",
10457                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10458                   macro_build (&offset_expr, "daddiu", "t,r,j",
10459                                AT, AT, BFD_RELOC_LO16);
10460                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
10461                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
10462                   used_at = 1;
10463                 }
10464               else
10465                 {
10466                   macro_build (&offset_expr, "lui", LUI_FMT,
10467                                tempreg, BFD_RELOC_MIPS_HIGHEST);
10468                   macro_build (&offset_expr, "daddiu", "t,r,j",
10469                                tempreg, tempreg, BFD_RELOC_MIPS_HIGHER);
10470                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10471                   macro_build (&offset_expr, "daddiu", "t,r,j",
10472                                tempreg, tempreg, BFD_RELOC_HI16_S);
10473                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
10474                   macro_build (&offset_expr, "daddiu", "t,r,j",
10475                                tempreg, tempreg, BFD_RELOC_LO16);
10476                 }
10477
10478               if (mips_relax.sequence)
10479                 relax_end ();
10480             }
10481           else
10482             {
10483               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
10484                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
10485                 {
10486                   relax_start (offset_expr.X_add_symbol);
10487                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10488                                tempreg, mips_gp_register, BFD_RELOC_GPREL16);
10489                   relax_switch ();
10490                 }
10491               if (!IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
10492                 as_bad (_("offset too large"));
10493               macro_build_lui (&offset_expr, tempreg);
10494               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10495                            tempreg, tempreg, BFD_RELOC_LO16);
10496               if (mips_relax.sequence)
10497                 relax_end ();
10498             }
10499         }
10500       else if (!mips_big_got && !HAVE_NEWABI)
10501         {
10502           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10503
10504           /* If this is a reference to an external symbol, and there
10505              is no constant, we want
10506                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10507              or for lca or if tempreg is PIC_CALL_REG
10508                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10509              For a local symbol, we want
10510                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10511                nop
10512                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10513
10514              If we have a small constant, and this is a reference to
10515              an external symbol, we want
10516                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10517                nop
10518                addiu    $tempreg,$tempreg,<constant>
10519              For a local symbol, we want the same instruction
10520              sequence, but we output a BFD_RELOC_LO16 reloc on the
10521              addiu instruction.
10522
10523              If we have a large constant, and this is a reference to
10524              an external symbol, we want
10525                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10526                lui      $at,<hiconstant>
10527                addiu    $at,$at,<loconstant>
10528                addu     $tempreg,$tempreg,$at
10529              For a local symbol, we want the same instruction
10530              sequence, but we output a BFD_RELOC_LO16 reloc on the
10531              addiu instruction.
10532            */
10533
10534           if (offset_expr.X_add_number == 0)
10535             {
10536               if (mips_pic == SVR4_PIC
10537                   && breg == 0
10538                   && (call || tempreg == PIC_CALL_REG))
10539                 lw_reloc_type = (int) BFD_RELOC_MIPS_CALL16;
10540
10541               relax_start (offset_expr.X_add_symbol);
10542               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10543                            lw_reloc_type, mips_gp_register);
10544               if (breg != 0)
10545                 {
10546                   /* We're going to put in an addu instruction using
10547                      tempreg, so we may as well insert the nop right
10548                      now.  */
10549                   load_delay_nop ();
10550                 }
10551               relax_switch ();
10552               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10553                            tempreg, BFD_RELOC_MIPS_GOT16, mips_gp_register);
10554               load_delay_nop ();
10555               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10556                            tempreg, tempreg, BFD_RELOC_LO16);
10557               relax_end ();
10558               /* FIXME: If breg == 0, and the next instruction uses
10559                  $tempreg, then if this variant case is used an extra
10560                  nop will be generated.  */
10561             }
10562           else if (offset_expr.X_add_number >= -0x8000
10563                    && offset_expr.X_add_number < 0x8000)
10564             {
10565               load_got_offset (tempreg, &offset_expr);
10566               load_delay_nop ();
10567               add_got_offset (tempreg, &offset_expr);
10568             }
10569           else
10570             {
10571               expr1.X_add_number = offset_expr.X_add_number;
10572               offset_expr.X_add_number =
10573                 SEXT_16BIT (offset_expr.X_add_number);
10574               load_got_offset (tempreg, &offset_expr);
10575               offset_expr.X_add_number = expr1.X_add_number;
10576               /* If we are going to add in a base register, and the
10577                  target register and the base register are the same,
10578                  then we are using AT as a temporary register.  Since
10579                  we want to load the constant into AT, we add our
10580                  current AT (from the global offset table) and the
10581                  register into the register now, and pretend we were
10582                  not using a base register.  */
10583               if (breg == op[0])
10584                 {
10585                   load_delay_nop ();
10586                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10587                                op[0], AT, breg);
10588                   breg = 0;
10589                   tempreg = op[0];
10590                 }
10591               add_got_offset_hilo (tempreg, &offset_expr, AT);
10592               used_at = 1;
10593             }
10594         }
10595       else if (!mips_big_got && HAVE_NEWABI)
10596         {
10597           int add_breg_early = 0;
10598
10599           /* If this is a reference to an external, and there is no
10600              constant, or local symbol (*), with or without a
10601              constant, we want
10602                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10603              or for lca or if tempreg is PIC_CALL_REG
10604                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_CALL16)
10605
10606              If we have a small constant, and this is a reference to
10607              an external symbol, we want
10608                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10609                addiu    $tempreg,$tempreg,<constant>
10610
10611              If we have a large constant, and this is a reference to
10612              an external symbol, we want
10613                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_DISP)
10614                lui      $at,<hiconstant>
10615                addiu    $at,$at,<loconstant>
10616                addu     $tempreg,$tempreg,$at
10617
10618              (*) Other assemblers seem to prefer GOT_PAGE/GOT_OFST for
10619              local symbols, even though it introduces an additional
10620              instruction.  */
10621
10622           if (offset_expr.X_add_number)
10623             {
10624               expr1.X_add_number = offset_expr.X_add_number;
10625               offset_expr.X_add_number = 0;
10626
10627               relax_start (offset_expr.X_add_symbol);
10628               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10629                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10630
10631               if (expr1.X_add_number >= -0x8000
10632                   && expr1.X_add_number < 0x8000)
10633                 {
10634                   macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10635                                tempreg, tempreg, BFD_RELOC_LO16);
10636                 }
10637               else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10638                 {
10639                   unsigned int dreg;
10640
10641                   /* If we are going to add in a base register, and the
10642                      target register and the base register are the same,
10643                      then we are using AT as a temporary register.  Since
10644                      we want to load the constant into AT, we add our
10645                      current AT (from the global offset table) and the
10646                      register into the register now, and pretend we were
10647                      not using a base register.  */
10648                   if (breg != op[0])
10649                     dreg = tempreg;
10650                   else
10651                     {
10652                       gas_assert (tempreg == AT);
10653                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10654                                    op[0], AT, breg);
10655                       dreg = op[0];
10656                       add_breg_early = 1;
10657                     }
10658
10659                   load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10660                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10661                                dreg, dreg, AT);
10662
10663                   used_at = 1;
10664                 }
10665               else
10666                 as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10667
10668               relax_switch ();
10669               offset_expr.X_add_number = expr1.X_add_number;
10670
10671               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10672                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10673               if (add_breg_early)
10674                 {
10675                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10676                                op[0], tempreg, breg);
10677                   breg = 0;
10678                   tempreg = op[0];
10679                 }
10680               relax_end ();
10681             }
10682           else if (breg == 0 && (call || tempreg == PIC_CALL_REG))
10683             {
10684               relax_start (offset_expr.X_add_symbol);
10685               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10686                            BFD_RELOC_MIPS_CALL16, mips_gp_register);
10687               relax_switch ();
10688               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10689                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10690               relax_end ();
10691             }
10692           else
10693             {
10694               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10695                            BFD_RELOC_MIPS_GOT_DISP, mips_gp_register);
10696             }
10697         }
10698       else if (mips_big_got && !HAVE_NEWABI)
10699         {
10700           int gpdelay;
10701           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10702           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10703           int local_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
10704
10705           /* This is the large GOT case.  If this is a reference to an
10706              external symbol, and there is no constant, we want
10707                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10708                addu     $tempreg,$tempreg,$gp
10709                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10710              or for lca or if tempreg is PIC_CALL_REG
10711                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10712                addu     $tempreg,$tempreg,$gp
10713                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10714              For a local symbol, we want
10715                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10716                nop
10717                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
10718
10719              If we have a small constant, and this is a reference to
10720              an external symbol, we want
10721                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10722                addu     $tempreg,$tempreg,$gp
10723                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10724                nop
10725                addiu    $tempreg,$tempreg,<constant>
10726              For a local symbol, we want
10727                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10728                nop
10729                addiu    $tempreg,$tempreg,<constant> (BFD_RELOC_LO16)
10730
10731              If we have a large constant, and this is a reference to
10732              an external symbol, we want
10733                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10734                addu     $tempreg,$tempreg,$gp
10735                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10736                lui      $at,<hiconstant>
10737                addiu    $at,$at,<loconstant>
10738                addu     $tempreg,$tempreg,$at
10739              For a local symbol, we want
10740                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
10741                lui      $at,<hiconstant>
10742                addiu    $at,$at,<loconstant>    (BFD_RELOC_LO16)
10743                addu     $tempreg,$tempreg,$at
10744           */
10745
10746           expr1.X_add_number = offset_expr.X_add_number;
10747           offset_expr.X_add_number = 0;
10748           relax_start (offset_expr.X_add_symbol);
10749           gpdelay = reg_needs_delay (mips_gp_register);
10750           if (expr1.X_add_number == 0 && breg == 0
10751               && (call || tempreg == PIC_CALL_REG))
10752             {
10753               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10754               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10755             }
10756           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10757           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10758                        tempreg, tempreg, mips_gp_register);
10759           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10760                        tempreg, lw_reloc_type, tempreg);
10761           if (expr1.X_add_number == 0)
10762             {
10763               if (breg != 0)
10764                 {
10765                   /* We're going to put in an addu instruction using
10766                      tempreg, so we may as well insert the nop right
10767                      now.  */
10768                   load_delay_nop ();
10769                 }
10770             }
10771           else if (expr1.X_add_number >= -0x8000
10772                    && expr1.X_add_number < 0x8000)
10773             {
10774               load_delay_nop ();
10775               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10776                            tempreg, tempreg, BFD_RELOC_LO16);
10777             }
10778           else
10779             {
10780               unsigned int dreg;
10781
10782               /* If we are going to add in a base register, and the
10783                  target register and the base register are the same,
10784                  then we are using AT as a temporary register.  Since
10785                  we want to load the constant into AT, we add our
10786                  current AT (from the global offset table) and the
10787                  register into the register now, and pretend we were
10788                  not using a base register.  */
10789               if (breg != op[0])
10790                 dreg = tempreg;
10791               else
10792                 {
10793                   gas_assert (tempreg == AT);
10794                   load_delay_nop ();
10795                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10796                                op[0], AT, breg);
10797                   dreg = op[0];
10798                 }
10799
10800               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10801               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10802
10803               used_at = 1;
10804             }
10805           offset_expr.X_add_number = SEXT_16BIT (expr1.X_add_number);
10806           relax_switch ();
10807
10808           if (gpdelay)
10809             {
10810               /* This is needed because this instruction uses $gp, but
10811                  the first instruction on the main stream does not.  */
10812               macro_build (NULL, "nop", "");
10813             }
10814
10815           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10816                        local_reloc_type, mips_gp_register);
10817           if (expr1.X_add_number >= -0x8000
10818               && expr1.X_add_number < 0x8000)
10819             {
10820               load_delay_nop ();
10821               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10822                            tempreg, tempreg, BFD_RELOC_LO16);
10823               /* FIXME: If add_number is 0, and there was no base
10824                  register, the external symbol case ended with a load,
10825                  so if the symbol turns out to not be external, and
10826                  the next instruction uses tempreg, an unnecessary nop
10827                  will be inserted.  */
10828             }
10829           else
10830             {
10831               if (breg == op[0])
10832                 {
10833                   /* We must add in the base register now, as in the
10834                      external symbol case.  */
10835                   gas_assert (tempreg == AT);
10836                   load_delay_nop ();
10837                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10838                                op[0], AT, breg);
10839                   tempreg = op[0];
10840                   /* We set breg to 0 because we have arranged to add
10841                      it in in both cases.  */
10842                   breg = 0;
10843                 }
10844
10845               macro_build_lui (&expr1, AT);
10846               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
10847                            AT, AT, BFD_RELOC_LO16);
10848               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10849                            tempreg, tempreg, AT);
10850               used_at = 1;
10851             }
10852           relax_end ();
10853         }
10854       else if (mips_big_got && HAVE_NEWABI)
10855         {
10856           int lui_reloc_type = (int) BFD_RELOC_MIPS_GOT_HI16;
10857           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT_LO16;
10858           int add_breg_early = 0;
10859
10860           /* This is the large GOT case.  If this is a reference to an
10861              external symbol, and there is no constant, we want
10862                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10863                add      $tempreg,$tempreg,$gp
10864                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10865              or for lca or if tempreg is PIC_CALL_REG
10866                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_CALL_HI16)
10867                add      $tempreg,$tempreg,$gp
10868                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_CALL_LO16)
10869
10870              If we have a small constant, and this is a reference to
10871              an external symbol, we want
10872                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10873                add      $tempreg,$tempreg,$gp
10874                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10875                addi     $tempreg,$tempreg,<constant>
10876
10877              If we have a large constant, and this is a reference to
10878              an external symbol, we want
10879                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
10880                addu     $tempreg,$tempreg,$gp
10881                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
10882                lui      $at,<hiconstant>
10883                addi     $at,$at,<loconstant>
10884                add      $tempreg,$tempreg,$at
10885
10886              If we have NewABI, and we know it's a local symbol, we want
10887                lw       $reg,<sym>($gp)         (BFD_RELOC_MIPS_GOT_PAGE)
10888                addiu    $reg,$reg,<sym>         (BFD_RELOC_MIPS_GOT_OFST)
10889              otherwise we have to resort to GOT_HI16/GOT_LO16.  */
10890
10891           relax_start (offset_expr.X_add_symbol);
10892
10893           expr1.X_add_number = offset_expr.X_add_number;
10894           offset_expr.X_add_number = 0;
10895
10896           if (expr1.X_add_number == 0 && breg == 0
10897               && (call || tempreg == PIC_CALL_REG))
10898             {
10899               lui_reloc_type = (int) BFD_RELOC_MIPS_CALL_HI16;
10900               lw_reloc_type = (int) BFD_RELOC_MIPS_CALL_LO16;
10901             }
10902           macro_build (&offset_expr, "lui", LUI_FMT, tempreg, lui_reloc_type);
10903           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10904                        tempreg, tempreg, mips_gp_register);
10905           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
10906                        tempreg, lw_reloc_type, tempreg);
10907
10908           if (expr1.X_add_number == 0)
10909             ;
10910           else if (expr1.X_add_number >= -0x8000
10911                    && expr1.X_add_number < 0x8000)
10912             {
10913               macro_build (&expr1, ADDRESS_ADDI_INSN, "t,r,j",
10914                            tempreg, tempreg, BFD_RELOC_LO16);
10915             }
10916           else if (IS_SEXT_32BIT_NUM (expr1.X_add_number + 0x8000))
10917             {
10918               unsigned int dreg;
10919
10920               /* If we are going to add in a base register, and the
10921                  target register and the base register are the same,
10922                  then we are using AT as a temporary register.  Since
10923                  we want to load the constant into AT, we add our
10924                  current AT (from the global offset table) and the
10925                  register into the register now, and pretend we were
10926                  not using a base register.  */
10927               if (breg != op[0])
10928                 dreg = tempreg;
10929               else
10930                 {
10931                   gas_assert (tempreg == AT);
10932                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10933                                op[0], AT, breg);
10934                   dreg = op[0];
10935                   add_breg_early = 1;
10936                 }
10937
10938               load_register (AT, &expr1, HAVE_64BIT_ADDRESSES);
10939               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", dreg, dreg, AT);
10940
10941               used_at = 1;
10942             }
10943           else
10944             as_bad (_("PIC code offset overflow (max 32 signed bits)"));
10945
10946           relax_switch ();
10947           offset_expr.X_add_number = expr1.X_add_number;
10948           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
10949                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
10950           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
10951                        tempreg, BFD_RELOC_MIPS_GOT_OFST);
10952           if (add_breg_early)
10953             {
10954               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
10955                            op[0], tempreg, breg);
10956               breg = 0;
10957               tempreg = op[0];
10958             }
10959           relax_end ();
10960         }
10961       else
10962         abort ();
10963
10964       if (breg != 0)
10965         macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", op[0], tempreg, breg);
10966       break;
10967
10968     case M_MSGSND:
10969       gas_assert (!mips_opts.micromips);
10970       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x01);
10971       break;
10972
10973     case M_MSGLD:
10974       gas_assert (!mips_opts.micromips);
10975       macro_build (NULL, "c2", "C", 0x02);
10976       break;
10977
10978     case M_MSGLD_T:
10979       gas_assert (!mips_opts.micromips);
10980       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x02);
10981       break;
10982
10983     case M_MSGWAIT:
10984       gas_assert (!mips_opts.micromips);
10985       macro_build (NULL, "c2", "C", 3);
10986       break;
10987
10988     case M_MSGWAIT_T:
10989       gas_assert (!mips_opts.micromips);
10990       macro_build (NULL, "c2", "C", (op[0] << 16) | 0x03);
10991       break;
10992
10993     case M_J_A:
10994       /* The j instruction may not be used in PIC code, since it
10995          requires an absolute address.  We convert it to a b
10996          instruction.  */
10997       if (mips_pic == NO_PIC)
10998         macro_build (&offset_expr, "j", "a");
10999       else
11000         macro_build (&offset_expr, "b", "p");
11001       break;
11002
11003       /* The jal instructions must be handled as macros because when
11004          generating PIC code they expand to multi-instruction
11005          sequences.  Normally they are simple instructions.  */
11006     case M_JALS_1:
11007       op[1] = op[0];
11008       op[0] = RA;
11009       /* Fall through.  */
11010     case M_JALS_2:
11011       gas_assert (mips_opts.micromips);
11012       if (mips_opts.insn32)
11013         {
11014           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11015           break;
11016         }
11017       jals = 1;
11018       goto jal;
11019     case M_JAL_1:
11020       op[1] = op[0];
11021       op[0] = RA;
11022       /* Fall through.  */
11023     case M_JAL_2:
11024     jal:
11025       if (mips_pic == NO_PIC)
11026         {
11027           s = jals ? "jalrs" : "jalr";
11028           if (mips_opts.micromips
11029               && !mips_opts.insn32
11030               && op[0] == RA
11031               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11032             macro_build (NULL, s, "mj", op[1]);
11033           else
11034             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11035         }
11036       else
11037         {
11038           int cprestore = (mips_pic == SVR4_PIC && !HAVE_NEWABI
11039                            && mips_cprestore_offset >= 0);
11040
11041           if (op[1] != PIC_CALL_REG)
11042             as_warn (_("MIPS PIC call to register other than $25"));
11043
11044           s = ((mips_opts.micromips
11045                 && !mips_opts.insn32
11046                 && (!mips_opts.noreorder || cprestore))
11047                ? "jalrs" : "jalr");
11048           if (mips_opts.micromips
11049               && !mips_opts.insn32
11050               && op[0] == RA
11051               && !(history[0].insn_mo->pinfo2 & INSN2_BRANCH_DELAY_32BIT))
11052             macro_build (NULL, s, "mj", op[1]);
11053           else
11054             macro_build (NULL, s, JALR_FMT, op[0], op[1]);
11055           if (mips_pic == SVR4_PIC && !HAVE_NEWABI)
11056             {
11057               if (mips_cprestore_offset < 0)
11058                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11059               else
11060                 {
11061                   if (!mips_frame_reg_valid)
11062                     {
11063                       as_warn (_("no .frame pseudo-op used in PIC code"));
11064                       /* Quiet this warning.  */
11065                       mips_frame_reg_valid = 1;
11066                     }
11067                   if (!mips_cprestore_valid)
11068                     {
11069                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11070                       /* Quiet this warning.  */
11071                       mips_cprestore_valid = 1;
11072                     }
11073                   if (mips_opts.noreorder)
11074                     macro_build (NULL, "nop", "");
11075                   expr1.X_add_number = mips_cprestore_offset;
11076                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11077                                                 mips_gp_register,
11078                                                 mips_frame_reg,
11079                                                 HAVE_64BIT_ADDRESSES);
11080                 }
11081             }
11082         }
11083
11084       break;
11085
11086     case M_JALS_A:
11087       gas_assert (mips_opts.micromips);
11088       if (mips_opts.insn32)
11089         {
11090           as_bad (_("opcode not supported in the `insn32' mode `%s'"), str);
11091           break;
11092         }
11093       jals = 1;
11094       /* Fall through.  */
11095     case M_JAL_A:
11096       if (mips_pic == NO_PIC)
11097         macro_build (&offset_expr, jals ? "jals" : "jal", "a");
11098       else if (mips_pic == SVR4_PIC)
11099         {
11100           /* If this is a reference to an external symbol, and we are
11101              using a small GOT, we want
11102                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_CALL16)
11103                nop
11104                jalr     $ra,$25
11105                nop
11106                lw       $gp,cprestore($sp)
11107              The cprestore value is set using the .cprestore
11108              pseudo-op.  If we are using a big GOT, we want
11109                lui      $25,<sym>               (BFD_RELOC_MIPS_CALL_HI16)
11110                addu     $25,$25,$gp
11111                lw       $25,<sym>($25)          (BFD_RELOC_MIPS_CALL_LO16)
11112                nop
11113                jalr     $ra,$25
11114                nop
11115                lw       $gp,cprestore($sp)
11116              If the symbol is not external, we want
11117                lw       $25,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
11118                nop
11119                addiu    $25,$25,<sym>           (BFD_RELOC_LO16)
11120                jalr     $ra,$25
11121                nop
11122                lw $gp,cprestore($sp)
11123
11124              For NewABI, we use the same CALL16 or CALL_HI16/CALL_LO16
11125              sequences above, minus nops, unless the symbol is local,
11126              which enables us to use GOT_PAGE/GOT_OFST (big got) or
11127              GOT_DISP.  */
11128           if (HAVE_NEWABI)
11129             {
11130               if (!mips_big_got)
11131                 {
11132                   relax_start (offset_expr.X_add_symbol);
11133                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11134                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11135                                mips_gp_register);
11136                   relax_switch ();
11137                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11138                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_DISP,
11139                                mips_gp_register);
11140                   relax_end ();
11141                 }
11142               else
11143                 {
11144                   relax_start (offset_expr.X_add_symbol);
11145                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11146                                BFD_RELOC_MIPS_CALL_HI16);
11147                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11148                                PIC_CALL_REG, mips_gp_register);
11149                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11150                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11151                                PIC_CALL_REG);
11152                   relax_switch ();
11153                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11154                                PIC_CALL_REG, BFD_RELOC_MIPS_GOT_PAGE,
11155                                mips_gp_register);
11156                   macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11157                                PIC_CALL_REG, PIC_CALL_REG,
11158                                BFD_RELOC_MIPS_GOT_OFST);
11159                   relax_end ();
11160                 }
11161
11162               macro_build_jalr (&offset_expr, 0);
11163             }
11164           else
11165             {
11166               relax_start (offset_expr.X_add_symbol);
11167               if (!mips_big_got)
11168                 {
11169                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11170                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL16,
11171                                mips_gp_register);
11172                   load_delay_nop ();
11173                   relax_switch ();
11174                 }
11175               else
11176                 {
11177                   int gpdelay;
11178
11179                   gpdelay = reg_needs_delay (mips_gp_register);
11180                   macro_build (&offset_expr, "lui", LUI_FMT, PIC_CALL_REG,
11181                                BFD_RELOC_MIPS_CALL_HI16);
11182                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", PIC_CALL_REG,
11183                                PIC_CALL_REG, mips_gp_register);
11184                   macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11185                                PIC_CALL_REG, BFD_RELOC_MIPS_CALL_LO16,
11186                                PIC_CALL_REG);
11187                   load_delay_nop ();
11188                   relax_switch ();
11189                   if (gpdelay)
11190                     macro_build (NULL, "nop", "");
11191                 }
11192               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
11193                            PIC_CALL_REG, BFD_RELOC_MIPS_GOT16,
11194                            mips_gp_register);
11195               load_delay_nop ();
11196               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11197                            PIC_CALL_REG, PIC_CALL_REG, BFD_RELOC_LO16);
11198               relax_end ();
11199               macro_build_jalr (&offset_expr, mips_cprestore_offset >= 0);
11200
11201               if (mips_cprestore_offset < 0)
11202                 as_warn (_("no .cprestore pseudo-op used in PIC code"));
11203               else
11204                 {
11205                   if (!mips_frame_reg_valid)
11206                     {
11207                       as_warn (_("no .frame pseudo-op used in PIC code"));
11208                       /* Quiet this warning.  */
11209                       mips_frame_reg_valid = 1;
11210                     }
11211                   if (!mips_cprestore_valid)
11212                     {
11213                       as_warn (_("no .cprestore pseudo-op used in PIC code"));
11214                       /* Quiet this warning.  */
11215                       mips_cprestore_valid = 1;
11216                     }
11217                   if (mips_opts.noreorder)
11218                     macro_build (NULL, "nop", "");
11219                   expr1.X_add_number = mips_cprestore_offset;
11220                   macro_build_ldst_constoffset (&expr1, ADDRESS_LOAD_INSN,
11221                                                 mips_gp_register,
11222                                                 mips_frame_reg,
11223                                                 HAVE_64BIT_ADDRESSES);
11224                 }
11225             }
11226         }
11227       else if (mips_pic == VXWORKS_PIC)
11228         as_bad (_("non-PIC jump used in PIC library"));
11229       else
11230         abort ();
11231
11232       break;
11233
11234     case M_LBUE_AB:
11235       s = "lbue";
11236       fmt = "t,+j(b)";
11237       offbits = 9;
11238       goto ld_st;
11239     case M_LHUE_AB:
11240       s = "lhue";
11241       fmt = "t,+j(b)";
11242       offbits = 9;
11243       goto ld_st;
11244     case M_LBE_AB:
11245       s = "lbe";
11246       fmt = "t,+j(b)";
11247       offbits = 9;
11248       goto ld_st;
11249     case M_LHE_AB:
11250       s = "lhe";
11251       fmt = "t,+j(b)";
11252       offbits = 9;
11253       goto ld_st;
11254     case M_LLE_AB:
11255       s = "lle";
11256       fmt = "t,+j(b)";
11257       offbits = 9;
11258       goto ld_st;
11259     case M_LWE_AB:
11260       s = "lwe";
11261       fmt = "t,+j(b)";
11262       offbits = 9;
11263       goto ld_st;
11264     case M_LWLE_AB:
11265       s = "lwle";
11266       fmt = "t,+j(b)";
11267       offbits = 9;
11268       goto ld_st;
11269     case M_LWRE_AB:
11270       s = "lwre";
11271       fmt = "t,+j(b)";
11272       offbits = 9;
11273       goto ld_st;
11274     case M_SBE_AB:
11275       s = "sbe";
11276       fmt = "t,+j(b)";
11277       offbits = 9;
11278       goto ld_st;
11279     case M_SCE_AB:
11280       s = "sce";
11281       fmt = "t,+j(b)";
11282       offbits = 9;
11283       goto ld_st;
11284     case M_SHE_AB:
11285       s = "she";
11286       fmt = "t,+j(b)";
11287       offbits = 9;
11288       goto ld_st;
11289     case M_SWE_AB:
11290       s = "swe";
11291       fmt = "t,+j(b)";
11292       offbits = 9;
11293       goto ld_st;
11294     case M_SWLE_AB:
11295       s = "swle";
11296       fmt = "t,+j(b)";
11297       offbits = 9;
11298       goto ld_st;
11299     case M_SWRE_AB:
11300       s = "swre";
11301       fmt = "t,+j(b)";
11302       offbits = 9;
11303       goto ld_st;
11304     case M_ACLR_AB:
11305       s = "aclr";
11306       fmt = "\\,~(b)";
11307       offbits = 12;
11308       goto ld_st;
11309     case M_ASET_AB:
11310       s = "aset";
11311       fmt = "\\,~(b)";
11312       offbits = 12;
11313       goto ld_st;
11314     case M_LB_AB:
11315       s = "lb";
11316       fmt = "t,o(b)";
11317       goto ld;
11318     case M_LBU_AB:
11319       s = "lbu";
11320       fmt = "t,o(b)";
11321       goto ld;
11322     case M_LH_AB:
11323       s = "lh";
11324       fmt = "t,o(b)";
11325       goto ld;
11326     case M_LHU_AB:
11327       s = "lhu";
11328       fmt = "t,o(b)";
11329       goto ld;
11330     case M_LW_AB:
11331       s = "lw";
11332       fmt = "t,o(b)";
11333       goto ld;
11334     case M_LWC0_AB:
11335       gas_assert (!mips_opts.micromips);
11336       s = "lwc0";
11337       fmt = "E,o(b)";
11338       /* Itbl support may require additional care here.  */
11339       coproc = 1;
11340       goto ld_st;
11341     case M_LWC1_AB:
11342       s = "lwc1";
11343       fmt = "T,o(b)";
11344       /* Itbl support may require additional care here.  */
11345       coproc = 1;
11346       goto ld_st;
11347     case M_LWC2_AB:
11348       s = "lwc2";
11349       fmt = COP12_FMT;
11350       offbits = (mips_opts.micromips ? 12
11351                  : ISA_IS_R6 (mips_opts.isa) ? 11
11352                  : 16);
11353       /* Itbl support may require additional care here.  */
11354       coproc = 1;
11355       goto ld_st;
11356     case M_LWC3_AB:
11357       gas_assert (!mips_opts.micromips);
11358       s = "lwc3";
11359       fmt = "E,o(b)";
11360       /* Itbl support may require additional care here.  */
11361       coproc = 1;
11362       goto ld_st;
11363     case M_LWL_AB:
11364       s = "lwl";
11365       fmt = MEM12_FMT;
11366       offbits = (mips_opts.micromips ? 12 : 16);
11367       goto ld_st;
11368     case M_LWR_AB:
11369       s = "lwr";
11370       fmt = MEM12_FMT;
11371       offbits = (mips_opts.micromips ? 12 : 16);
11372       goto ld_st;
11373     case M_LDC1_AB:
11374       s = "ldc1";
11375       fmt = "T,o(b)";
11376       /* Itbl support may require additional care here.  */
11377       coproc = 1;
11378       goto ld_st;
11379     case M_LDC2_AB:
11380       s = "ldc2";
11381       fmt = COP12_FMT;
11382       offbits = (mips_opts.micromips ? 12
11383                  : ISA_IS_R6 (mips_opts.isa) ? 11
11384                  : 16);
11385       /* Itbl support may require additional care here.  */
11386       coproc = 1;
11387       goto ld_st;
11388     case M_LQC2_AB:
11389       s = "lqc2";
11390       fmt = "+7,o(b)";
11391       /* Itbl support may require additional care here.  */
11392       coproc = 1;
11393       goto ld_st;
11394     case M_LDC3_AB:
11395       s = "ldc3";
11396       fmt = "E,o(b)";
11397       /* Itbl support may require additional care here.  */
11398       coproc = 1;
11399       goto ld_st;
11400     case M_LDL_AB:
11401       s = "ldl";
11402       fmt = MEM12_FMT;
11403       offbits = (mips_opts.micromips ? 12 : 16);
11404       goto ld_st;
11405     case M_LDR_AB:
11406       s = "ldr";
11407       fmt = MEM12_FMT;
11408       offbits = (mips_opts.micromips ? 12 : 16);
11409       goto ld_st;
11410     case M_LL_AB:
11411       s = "ll";
11412       fmt = LL_SC_FMT;
11413       offbits = (mips_opts.micromips ? 12
11414                  : ISA_IS_R6 (mips_opts.isa) ? 9
11415                  : 16);
11416       goto ld;
11417     case M_LLD_AB:
11418       s = "lld";
11419       fmt = LL_SC_FMT;
11420       offbits = (mips_opts.micromips ? 12
11421                  : ISA_IS_R6 (mips_opts.isa) ? 9
11422                  : 16);
11423       goto ld;
11424     case M_LWU_AB:
11425       s = "lwu";
11426       fmt = MEM12_FMT;
11427       offbits = (mips_opts.micromips ? 12 : 16);
11428       goto ld;
11429     case M_LWP_AB:
11430       gas_assert (mips_opts.micromips);
11431       s = "lwp";
11432       fmt = "t,~(b)";
11433       offbits = 12;
11434       lp = 1;
11435       goto ld;
11436     case M_LDP_AB:
11437       gas_assert (mips_opts.micromips);
11438       s = "ldp";
11439       fmt = "t,~(b)";
11440       offbits = 12;
11441       lp = 1;
11442       goto ld;
11443     case M_LWM_AB:
11444       gas_assert (mips_opts.micromips);
11445       s = "lwm";
11446       fmt = "n,~(b)";
11447       offbits = 12;
11448       goto ld_st;
11449     case M_LDM_AB:
11450       gas_assert (mips_opts.micromips);
11451       s = "ldm";
11452       fmt = "n,~(b)";
11453       offbits = 12;
11454       goto ld_st;
11455
11456     ld:
11457       /* We don't want to use $0 as tempreg.  */
11458       if (op[2] == op[0] + lp || op[0] + lp == ZERO)
11459         goto ld_st;
11460       else
11461         tempreg = op[0] + lp;
11462       goto ld_noat;
11463
11464     case M_SB_AB:
11465       s = "sb";
11466       fmt = "t,o(b)";
11467       goto ld_st;
11468     case M_SH_AB:
11469       s = "sh";
11470       fmt = "t,o(b)";
11471       goto ld_st;
11472     case M_SW_AB:
11473       s = "sw";
11474       fmt = "t,o(b)";
11475       goto ld_st;
11476     case M_SWC0_AB:
11477       gas_assert (!mips_opts.micromips);
11478       s = "swc0";
11479       fmt = "E,o(b)";
11480       /* Itbl support may require additional care here.  */
11481       coproc = 1;
11482       goto ld_st;
11483     case M_SWC1_AB:
11484       s = "swc1";
11485       fmt = "T,o(b)";
11486       /* Itbl support may require additional care here.  */
11487       coproc = 1;
11488       goto ld_st;
11489     case M_SWC2_AB:
11490       s = "swc2";
11491       fmt = COP12_FMT;
11492       offbits = (mips_opts.micromips ? 12
11493                  : ISA_IS_R6 (mips_opts.isa) ? 11
11494                  : 16);
11495       /* Itbl support may require additional care here.  */
11496       coproc = 1;
11497       goto ld_st;
11498     case M_SWC3_AB:
11499       gas_assert (!mips_opts.micromips);
11500       s = "swc3";
11501       fmt = "E,o(b)";
11502       /* Itbl support may require additional care here.  */
11503       coproc = 1;
11504       goto ld_st;
11505     case M_SWL_AB:
11506       s = "swl";
11507       fmt = MEM12_FMT;
11508       offbits = (mips_opts.micromips ? 12 : 16);
11509       goto ld_st;
11510     case M_SWR_AB:
11511       s = "swr";
11512       fmt = MEM12_FMT;
11513       offbits = (mips_opts.micromips ? 12 : 16);
11514       goto ld_st;
11515     case M_SC_AB:
11516       s = "sc";
11517       fmt = LL_SC_FMT;
11518       offbits = (mips_opts.micromips ? 12
11519                  : ISA_IS_R6 (mips_opts.isa) ? 9
11520                  : 16);
11521       goto ld_st;
11522     case M_SCD_AB:
11523       s = "scd";
11524       fmt = LL_SC_FMT;
11525       offbits = (mips_opts.micromips ? 12
11526                  : ISA_IS_R6 (mips_opts.isa) ? 9
11527                  : 16);
11528       goto ld_st;
11529     case M_CACHE_AB:
11530       s = "cache";
11531       fmt = (mips_opts.micromips ? "k,~(b)"
11532              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11533              : "k,o(b)");
11534       offbits = (mips_opts.micromips ? 12
11535                  : ISA_IS_R6 (mips_opts.isa) ? 9
11536                  : 16);
11537       goto ld_st;
11538     case M_CACHEE_AB:
11539       s = "cachee";
11540       fmt = "k,+j(b)";
11541       offbits = 9;
11542       goto ld_st;
11543     case M_PREF_AB:
11544       s = "pref";
11545       fmt = (mips_opts.micromips ? "k,~(b)"
11546              : ISA_IS_R6 (mips_opts.isa) ? "k,+j(b)"
11547              : "k,o(b)");
11548       offbits = (mips_opts.micromips ? 12
11549                  : ISA_IS_R6 (mips_opts.isa) ? 9
11550                  : 16);
11551       goto ld_st;
11552     case M_PREFE_AB:
11553       s = "prefe";
11554       fmt = "k,+j(b)";
11555       offbits = 9;
11556       goto ld_st;
11557     case M_SDC1_AB:
11558       s = "sdc1";
11559       fmt = "T,o(b)";
11560       coproc = 1;
11561       /* Itbl support may require additional care here.  */
11562       goto ld_st;
11563     case M_SDC2_AB:
11564       s = "sdc2";
11565       fmt = COP12_FMT;
11566       offbits = (mips_opts.micromips ? 12
11567                  : ISA_IS_R6 (mips_opts.isa) ? 11
11568                  : 16);
11569       /* Itbl support may require additional care here.  */
11570       coproc = 1;
11571       goto ld_st;
11572     case M_SQC2_AB:
11573       s = "sqc2";
11574       fmt = "+7,o(b)";
11575       /* Itbl support may require additional care here.  */
11576       coproc = 1;
11577       goto ld_st;
11578     case M_SDC3_AB:
11579       gas_assert (!mips_opts.micromips);
11580       s = "sdc3";
11581       fmt = "E,o(b)";
11582       /* Itbl support may require additional care here.  */
11583       coproc = 1;
11584       goto ld_st;
11585     case M_SDL_AB:
11586       s = "sdl";
11587       fmt = MEM12_FMT;
11588       offbits = (mips_opts.micromips ? 12 : 16);
11589       goto ld_st;
11590     case M_SDR_AB:
11591       s = "sdr";
11592       fmt = MEM12_FMT;
11593       offbits = (mips_opts.micromips ? 12 : 16);
11594       goto ld_st;
11595     case M_SWP_AB:
11596       gas_assert (mips_opts.micromips);
11597       s = "swp";
11598       fmt = "t,~(b)";
11599       offbits = 12;
11600       goto ld_st;
11601     case M_SDP_AB:
11602       gas_assert (mips_opts.micromips);
11603       s = "sdp";
11604       fmt = "t,~(b)";
11605       offbits = 12;
11606       goto ld_st;
11607     case M_SWM_AB:
11608       gas_assert (mips_opts.micromips);
11609       s = "swm";
11610       fmt = "n,~(b)";
11611       offbits = 12;
11612       goto ld_st;
11613     case M_SDM_AB:
11614       gas_assert (mips_opts.micromips);
11615       s = "sdm";
11616       fmt = "n,~(b)";
11617       offbits = 12;
11618
11619     ld_st:
11620       tempreg = AT;
11621     ld_noat:
11622       breg = op[2];
11623       if (small_offset_p (0, align, 16))
11624         {
11625           /* The first case exists for M_LD_AB and M_SD_AB, which are
11626              macros for o32 but which should act like normal instructions
11627              otherwise.  */
11628           if (offbits == 16)
11629             macro_build (&offset_expr, s, fmt, op[0], -1, offset_reloc[0],
11630                          offset_reloc[1], offset_reloc[2], breg);
11631           else if (small_offset_p (0, align, offbits))
11632             {
11633               if (offbits == 0)
11634                 macro_build (NULL, s, fmt, op[0], breg);
11635               else
11636                 macro_build (NULL, s, fmt, op[0],
11637                              (int) offset_expr.X_add_number, breg);
11638             }
11639           else
11640             {
11641               if (tempreg == AT)
11642                 used_at = 1;
11643               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j",
11644                            tempreg, breg, -1, offset_reloc[0],
11645                            offset_reloc[1], offset_reloc[2]);
11646               if (offbits == 0)
11647                 macro_build (NULL, s, fmt, op[0], tempreg);
11648               else
11649                 macro_build (NULL, s, fmt, op[0], 0, tempreg);
11650             }
11651           break;
11652         }
11653
11654       if (tempreg == AT)
11655         used_at = 1;
11656
11657       if (offset_expr.X_op != O_constant
11658           && offset_expr.X_op != O_symbol)
11659         {
11660           as_bad (_("expression too complex"));
11661           offset_expr.X_op = O_constant;
11662         }
11663
11664       if (HAVE_32BIT_ADDRESSES
11665           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
11666         {
11667           char value [32];
11668
11669           sprintf_vma (value, offset_expr.X_add_number);
11670           as_bad (_("number (0x%s) larger than 32 bits"), value);
11671         }
11672
11673       /* A constant expression in PIC code can be handled just as it
11674          is in non PIC code.  */
11675       if (offset_expr.X_op == O_constant)
11676         {
11677           expr1.X_add_number = offset_high_part (offset_expr.X_add_number,
11678                                                  offbits == 0 ? 16 : offbits);
11679           offset_expr.X_add_number -= expr1.X_add_number;
11680
11681           load_register (tempreg, &expr1, HAVE_64BIT_ADDRESSES);
11682           if (breg != 0)
11683             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11684                          tempreg, tempreg, breg);
11685           if (offbits == 0)
11686             {
11687               if (offset_expr.X_add_number != 0)
11688                 macro_build (&offset_expr, ADDRESS_ADDI_INSN,
11689                              "t,r,j", tempreg, tempreg, BFD_RELOC_LO16);
11690               macro_build (NULL, s, fmt, op[0], tempreg);
11691             }
11692           else if (offbits == 16)
11693             macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11694           else
11695             macro_build (NULL, s, fmt, op[0],
11696                          (int) offset_expr.X_add_number, tempreg);
11697         }
11698       else if (offbits != 16)
11699         {
11700           /* The offset field is too narrow to be used for a low-part
11701              relocation, so load the whole address into the auxillary
11702              register.  */
11703           load_address (tempreg, &offset_expr, &used_at);
11704           if (breg != 0)
11705             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11706                          tempreg, tempreg, breg);
11707           if (offbits == 0)
11708             macro_build (NULL, s, fmt, op[0], tempreg);
11709           else
11710             macro_build (NULL, s, fmt, op[0], 0, tempreg);
11711         }
11712       else if (mips_pic == NO_PIC)
11713         {
11714           /* If this is a reference to a GP relative symbol, and there
11715              is no base register, we want
11716                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
11717              Otherwise, if there is no base register, we want
11718                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11719                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11720              If we have a constant, we need two instructions anyhow,
11721              so we always use the latter form.
11722
11723              If we have a base register, and this is a reference to a
11724              GP relative symbol, we want
11725                addu     $tempreg,$breg,$gp
11726                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_GPREL16)
11727              Otherwise we want
11728                lui      $tempreg,<sym>          (BFD_RELOC_HI16_S)
11729                addu     $tempreg,$tempreg,$breg
11730                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11731              With a constant we always use the latter case.
11732
11733              With 64bit address space and no base register and $at usable,
11734              we want
11735                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11736                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11737                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11738                dsll32   $tempreg,0
11739                daddu    $tempreg,$at
11740                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11741              If we have a base register, we want
11742                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11743                lui      $at,<sym>               (BFD_RELOC_HI16_S)
11744                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11745                daddu    $at,$breg
11746                dsll32   $tempreg,0
11747                daddu    $tempreg,$at
11748                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11749
11750              Without $at we can't generate the optimal path for superscalar
11751              processors here since this would require two temporary registers.
11752                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11753                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11754                dsll     $tempreg,16
11755                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11756                dsll     $tempreg,16
11757                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11758              If we have a base register, we want
11759                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHEST)
11760                daddiu   $tempreg,<sym>          (BFD_RELOC_MIPS_HIGHER)
11761                dsll     $tempreg,16
11762                daddiu   $tempreg,<sym>          (BFD_RELOC_HI16_S)
11763                dsll     $tempreg,16
11764                daddu    $tempreg,$tempreg,$breg
11765                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_LO16)
11766
11767              For GP relative symbols in 64bit address space we can use
11768              the same sequence as in 32bit address space.  */
11769           if (HAVE_64BIT_SYMBOLS)
11770             {
11771               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11772                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11773                 {
11774                   relax_start (offset_expr.X_add_symbol);
11775                   if (breg == 0)
11776                     {
11777                       macro_build (&offset_expr, s, fmt, op[0],
11778                                    BFD_RELOC_GPREL16, mips_gp_register);
11779                     }
11780                   else
11781                     {
11782                       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11783                                    tempreg, breg, mips_gp_register);
11784                       macro_build (&offset_expr, s, fmt, op[0],
11785                                    BFD_RELOC_GPREL16, tempreg);
11786                     }
11787                   relax_switch ();
11788                 }
11789
11790               if (used_at == 0 && mips_opts.at)
11791                 {
11792                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11793                                BFD_RELOC_MIPS_HIGHEST);
11794                   macro_build (&offset_expr, "lui", LUI_FMT, AT,
11795                                BFD_RELOC_HI16_S);
11796                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11797                                tempreg, BFD_RELOC_MIPS_HIGHER);
11798                   if (breg != 0)
11799                     macro_build (NULL, "daddu", "d,v,t", AT, AT, breg);
11800                   macro_build (NULL, "dsll32", SHFT_FMT, tempreg, tempreg, 0);
11801                   macro_build (NULL, "daddu", "d,v,t", tempreg, tempreg, AT);
11802                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_LO16,
11803                                tempreg);
11804                   used_at = 1;
11805                 }
11806               else
11807                 {
11808                   macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11809                                BFD_RELOC_MIPS_HIGHEST);
11810                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11811                                tempreg, BFD_RELOC_MIPS_HIGHER);
11812                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11813                   macro_build (&offset_expr, "daddiu", "t,r,j", tempreg,
11814                                tempreg, BFD_RELOC_HI16_S);
11815                   macro_build (NULL, "dsll", SHFT_FMT, tempreg, tempreg, 16);
11816                   if (breg != 0)
11817                     macro_build (NULL, "daddu", "d,v,t",
11818                                  tempreg, tempreg, breg);
11819                   macro_build (&offset_expr, s, fmt, op[0],
11820                                BFD_RELOC_LO16, tempreg);
11821                 }
11822
11823               if (mips_relax.sequence)
11824                 relax_end ();
11825               break;
11826             }
11827
11828           if (breg == 0)
11829             {
11830               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11831                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11832                 {
11833                   relax_start (offset_expr.X_add_symbol);
11834                   macro_build (&offset_expr, s, fmt, op[0], BFD_RELOC_GPREL16,
11835                                mips_gp_register);
11836                   relax_switch ();
11837                 }
11838               macro_build_lui (&offset_expr, tempreg);
11839               macro_build (&offset_expr, s, fmt, op[0],
11840                            BFD_RELOC_LO16, tempreg);
11841               if (mips_relax.sequence)
11842                 relax_end ();
11843             }
11844           else
11845             {
11846               if ((valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
11847                   && !nopic_need_relax (offset_expr.X_add_symbol, 1))
11848                 {
11849                   relax_start (offset_expr.X_add_symbol);
11850                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11851                                tempreg, breg, mips_gp_register);
11852                   macro_build (&offset_expr, s, fmt, op[0],
11853                                BFD_RELOC_GPREL16, tempreg);
11854                   relax_switch ();
11855                 }
11856               macro_build_lui (&offset_expr, tempreg);
11857               macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11858                            tempreg, tempreg, breg);
11859               macro_build (&offset_expr, s, fmt, op[0],
11860                            BFD_RELOC_LO16, tempreg);
11861               if (mips_relax.sequence)
11862                 relax_end ();
11863             }
11864         }
11865       else if (!mips_big_got)
11866         {
11867           int lw_reloc_type = (int) BFD_RELOC_MIPS_GOT16;
11868
11869           /* If this is a reference to an external symbol, we want
11870                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11871                nop
11872                <op>     op[0],0($tempreg)
11873              Otherwise we want
11874                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11875                nop
11876                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11877                <op>     op[0],0($tempreg)
11878
11879              For NewABI, we want
11880                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11881                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)
11882
11883              If there is a base register, we add it to $tempreg before
11884              the <op>.  If there is a constant, we stick it in the
11885              <op> instruction.  We don't handle constants larger than
11886              16 bits, because we have no way to load the upper 16 bits
11887              (actually, we could handle them for the subset of cases
11888              in which we are not using $at).  */
11889           gas_assert (offset_expr.X_op == O_symbol);
11890           if (HAVE_NEWABI)
11891             {
11892               macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11893                            BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
11894               if (breg != 0)
11895                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11896                              tempreg, tempreg, breg);
11897               macro_build (&offset_expr, s, fmt, op[0],
11898                            BFD_RELOC_MIPS_GOT_OFST, tempreg);
11899               break;
11900             }
11901           expr1.X_add_number = offset_expr.X_add_number;
11902           offset_expr.X_add_number = 0;
11903           if (expr1.X_add_number < -0x8000
11904               || expr1.X_add_number >= 0x8000)
11905             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11906           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11907                        lw_reloc_type, mips_gp_register);
11908           load_delay_nop ();
11909           relax_start (offset_expr.X_add_symbol);
11910           relax_switch ();
11911           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11912                        tempreg, BFD_RELOC_LO16);
11913           relax_end ();
11914           if (breg != 0)
11915             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11916                          tempreg, tempreg, breg);
11917           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11918         }
11919       else if (mips_big_got && !HAVE_NEWABI)
11920         {
11921           int gpdelay;
11922
11923           /* If this is a reference to an external symbol, we want
11924                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11925                addu     $tempreg,$tempreg,$gp
11926                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11927                <op>     op[0],0($tempreg)
11928              Otherwise we want
11929                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT16)
11930                nop
11931                addiu    $tempreg,$tempreg,<sym> (BFD_RELOC_LO16)
11932                <op>     op[0],0($tempreg)
11933              If there is a base register, we add it to $tempreg before
11934              the <op>.  If there is a constant, we stick it in the
11935              <op> instruction.  We don't handle constants larger than
11936              16 bits, because we have no way to load the upper 16 bits
11937              (actually, we could handle them for the subset of cases
11938              in which we are not using $at).  */
11939           gas_assert (offset_expr.X_op == O_symbol);
11940           expr1.X_add_number = offset_expr.X_add_number;
11941           offset_expr.X_add_number = 0;
11942           if (expr1.X_add_number < -0x8000
11943               || expr1.X_add_number >= 0x8000)
11944             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11945           gpdelay = reg_needs_delay (mips_gp_register);
11946           relax_start (offset_expr.X_add_symbol);
11947           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11948                        BFD_RELOC_MIPS_GOT_HI16);
11949           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11950                        mips_gp_register);
11951           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11952                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11953           relax_switch ();
11954           if (gpdelay)
11955             macro_build (NULL, "nop", "");
11956           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11957                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
11958           load_delay_nop ();
11959           macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", tempreg,
11960                        tempreg, BFD_RELOC_LO16);
11961           relax_end ();
11962
11963           if (breg != 0)
11964             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11965                          tempreg, tempreg, breg);
11966           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11967         }
11968       else if (mips_big_got && HAVE_NEWABI)
11969         {
11970           /* If this is a reference to an external symbol, we want
11971                lui      $tempreg,<sym>          (BFD_RELOC_MIPS_GOT_HI16)
11972                add      $tempreg,$tempreg,$gp
11973                lw       $tempreg,<sym>($tempreg) (BFD_RELOC_MIPS_GOT_LO16)
11974                <op>     op[0],<ofst>($tempreg)
11975              Otherwise, for local symbols, we want:
11976                lw       $tempreg,<sym>($gp)     (BFD_RELOC_MIPS_GOT_PAGE)
11977                <op>     op[0],<sym>($tempreg)   (BFD_RELOC_MIPS_GOT_OFST)  */
11978           gas_assert (offset_expr.X_op == O_symbol);
11979           expr1.X_add_number = offset_expr.X_add_number;
11980           offset_expr.X_add_number = 0;
11981           if (expr1.X_add_number < -0x8000
11982               || expr1.X_add_number >= 0x8000)
11983             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
11984           relax_start (offset_expr.X_add_symbol);
11985           macro_build (&offset_expr, "lui", LUI_FMT, tempreg,
11986                        BFD_RELOC_MIPS_GOT_HI16);
11987           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", tempreg, tempreg,
11988                        mips_gp_register);
11989           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11990                        BFD_RELOC_MIPS_GOT_LO16, tempreg);
11991           if (breg != 0)
11992             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
11993                          tempreg, tempreg, breg);
11994           macro_build (&expr1, s, fmt, op[0], BFD_RELOC_LO16, tempreg);
11995
11996           relax_switch ();
11997           offset_expr.X_add_number = expr1.X_add_number;
11998           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", tempreg,
11999                        BFD_RELOC_MIPS_GOT_PAGE, mips_gp_register);
12000           if (breg != 0)
12001             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12002                          tempreg, tempreg, breg);
12003           macro_build (&offset_expr, s, fmt, op[0],
12004                        BFD_RELOC_MIPS_GOT_OFST, tempreg);
12005           relax_end ();
12006         }
12007       else
12008         abort ();
12009
12010       break;
12011
12012     case M_JRADDIUSP:
12013       gas_assert (mips_opts.micromips);
12014       gas_assert (mips_opts.insn32);
12015       start_noreorder ();
12016       macro_build (NULL, "jr", "s", RA);
12017       expr1.X_add_number = op[0] << 2;
12018       macro_build (&expr1, "addiu", "t,r,j", SP, SP, BFD_RELOC_LO16);
12019       end_noreorder ();
12020       break;
12021
12022     case M_JRC:
12023       gas_assert (mips_opts.micromips);
12024       gas_assert (mips_opts.insn32);
12025       macro_build (NULL, "jr", "s", op[0]);
12026       if (mips_opts.noreorder)
12027         macro_build (NULL, "nop", "");
12028       break;
12029
12030     case M_LI:
12031     case M_LI_S:
12032       load_register (op[0], &imm_expr, 0);
12033       break;
12034
12035     case M_DLI:
12036       load_register (op[0], &imm_expr, 1);
12037       break;
12038
12039     case M_LI_SS:
12040       if (imm_expr.X_op == O_constant)
12041         {
12042           used_at = 1;
12043           load_register (AT, &imm_expr, 0);
12044           macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12045           break;
12046         }
12047       else
12048         {
12049           gas_assert (imm_expr.X_op == O_absent
12050                       && offset_expr.X_op == O_symbol
12051                       && strcmp (segment_name (S_GET_SEGMENT
12052                                                (offset_expr.X_add_symbol)),
12053                                  ".lit4") == 0
12054                       && offset_expr.X_add_number == 0);
12055           macro_build (&offset_expr, "lwc1", "T,o(b)", op[0],
12056                        BFD_RELOC_MIPS_LITERAL, mips_gp_register);
12057           break;
12058         }
12059
12060     case M_LI_D:
12061       /* Check if we have a constant in IMM_EXPR.  If the GPRs are 64 bits
12062          wide, IMM_EXPR is the entire value.  Otherwise IMM_EXPR is the high
12063          order 32 bits of the value and the low order 32 bits are either
12064          zero or in OFFSET_EXPR.  */
12065       if (imm_expr.X_op == O_constant)
12066         {
12067           if (GPR_SIZE == 64)
12068             load_register (op[0], &imm_expr, 1);
12069           else
12070             {
12071               int hreg, lreg;
12072
12073               if (target_big_endian)
12074                 {
12075                   hreg = op[0];
12076                   lreg = op[0] + 1;
12077                 }
12078               else
12079                 {
12080                   hreg = op[0] + 1;
12081                   lreg = op[0];
12082                 }
12083
12084               if (hreg <= 31)
12085                 load_register (hreg, &imm_expr, 0);
12086               if (lreg <= 31)
12087                 {
12088                   if (offset_expr.X_op == O_absent)
12089                     move_register (lreg, 0);
12090                   else
12091                     {
12092                       gas_assert (offset_expr.X_op == O_constant);
12093                       load_register (lreg, &offset_expr, 0);
12094                     }
12095                 }
12096             }
12097           break;
12098         }
12099       gas_assert (imm_expr.X_op == O_absent);
12100
12101       /* We know that sym is in the .rdata section.  First we get the
12102          upper 16 bits of the address.  */
12103       if (mips_pic == NO_PIC)
12104         {
12105           macro_build_lui (&offset_expr, AT);
12106           used_at = 1;
12107         }
12108       else
12109         {
12110           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12111                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12112           used_at = 1;
12113         }
12114
12115       /* Now we load the register(s).  */
12116       if (GPR_SIZE == 64)
12117         {
12118           used_at = 1;
12119           macro_build (&offset_expr, "ld", "t,o(b)", op[0],
12120                        BFD_RELOC_LO16, AT);
12121         }
12122       else
12123         {
12124           used_at = 1;
12125           macro_build (&offset_expr, "lw", "t,o(b)", op[0],
12126                        BFD_RELOC_LO16, AT);
12127           if (op[0] != RA)
12128             {
12129               /* FIXME: How in the world do we deal with the possible
12130                  overflow here?  */
12131               offset_expr.X_add_number += 4;
12132               macro_build (&offset_expr, "lw", "t,o(b)",
12133                            op[0] + 1, BFD_RELOC_LO16, AT);
12134             }
12135         }
12136       break;
12137
12138     case M_LI_DD:
12139       /* Check if we have a constant in IMM_EXPR.  If the FPRs are 64 bits
12140          wide, IMM_EXPR is the entire value and the GPRs are known to be 64
12141          bits wide as well.  Otherwise IMM_EXPR is the high order 32 bits of
12142          the value and the low order 32 bits are either zero or in
12143          OFFSET_EXPR.  */
12144       if (imm_expr.X_op == O_constant)
12145         {
12146           used_at = 1;
12147           load_register (AT, &imm_expr, FPR_SIZE == 64);
12148           if (FPR_SIZE == 64 && GPR_SIZE == 64)
12149             macro_build (NULL, "dmtc1", "t,S", AT, op[0]);
12150           else
12151             {
12152               if (ISA_HAS_MXHC1 (mips_opts.isa))
12153                 macro_build (NULL, "mthc1", "t,G", AT, op[0]);
12154               else if (FPR_SIZE != 32)
12155                 as_bad (_("Unable to generate `%s' compliant code "
12156                           "without mthc1"),
12157                         (FPR_SIZE == 64) ? "fp64" : "fpxx");
12158               else
12159                 macro_build (NULL, "mtc1", "t,G", AT, op[0] + 1);
12160               if (offset_expr.X_op == O_absent)
12161                 macro_build (NULL, "mtc1", "t,G", 0, op[0]);
12162               else
12163                 {
12164                   gas_assert (offset_expr.X_op == O_constant);
12165                   load_register (AT, &offset_expr, 0);
12166                   macro_build (NULL, "mtc1", "t,G", AT, op[0]);
12167                 }
12168             }
12169           break;
12170         }
12171
12172       gas_assert (imm_expr.X_op == O_absent
12173                   && offset_expr.X_op == O_symbol
12174                   && offset_expr.X_add_number == 0);
12175       s = segment_name (S_GET_SEGMENT (offset_expr.X_add_symbol));
12176       if (strcmp (s, ".lit8") == 0)
12177         {
12178           op[2] = mips_gp_register;
12179           offset_reloc[0] = BFD_RELOC_MIPS_LITERAL;
12180           offset_reloc[1] = BFD_RELOC_UNUSED;
12181           offset_reloc[2] = BFD_RELOC_UNUSED;
12182         }
12183       else
12184         {
12185           gas_assert (strcmp (s, RDATA_SECTION_NAME) == 0);
12186           used_at = 1;
12187           if (mips_pic != NO_PIC)
12188             macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12189                          BFD_RELOC_MIPS_GOT16, mips_gp_register);
12190           else
12191             {
12192               /* FIXME: This won't work for a 64 bit address.  */
12193               macro_build_lui (&offset_expr, AT);
12194             }
12195
12196           op[2] = AT;
12197           offset_reloc[0] = BFD_RELOC_LO16;
12198           offset_reloc[1] = BFD_RELOC_UNUSED;
12199           offset_reloc[2] = BFD_RELOC_UNUSED;
12200         }
12201       align = 8;
12202       /* Fall through */
12203
12204     case M_L_DAB:
12205       /*
12206        * The MIPS assembler seems to check for X_add_number not
12207        * being double aligned and generating:
12208        *        lui     at,%hi(foo+1)
12209        *        addu    at,at,v1
12210        *        addiu   at,at,%lo(foo+1)
12211        *        lwc1    f2,0(at)
12212        *        lwc1    f3,4(at)
12213        * But, the resulting address is the same after relocation so why
12214        * generate the extra instruction?
12215        */
12216       /* Itbl support may require additional care here.  */
12217       coproc = 1;
12218       fmt = "T,o(b)";
12219       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12220         {
12221           s = "ldc1";
12222           goto ld_st;
12223         }
12224       s = "lwc1";
12225       goto ldd_std;
12226
12227     case M_S_DAB:
12228       gas_assert (!mips_opts.micromips);
12229       /* Itbl support may require additional care here.  */
12230       coproc = 1;
12231       fmt = "T,o(b)";
12232       if (CPU_HAS_LDC1_SDC1 (mips_opts.arch))
12233         {
12234           s = "sdc1";
12235           goto ld_st;
12236         }
12237       s = "swc1";
12238       goto ldd_std;
12239
12240     case M_LQ_AB:
12241       fmt = "t,o(b)";
12242       s = "lq";
12243       goto ld;
12244
12245     case M_SQ_AB:
12246       fmt = "t,o(b)";
12247       s = "sq";
12248       goto ld_st;
12249
12250     case M_LD_AB:
12251       fmt = "t,o(b)";
12252       if (GPR_SIZE == 64)
12253         {
12254           s = "ld";
12255           goto ld;
12256         }
12257       s = "lw";
12258       goto ldd_std;
12259
12260     case M_SD_AB:
12261       fmt = "t,o(b)";
12262       if (GPR_SIZE == 64)
12263         {
12264           s = "sd";
12265           goto ld_st;
12266         }
12267       s = "sw";
12268
12269     ldd_std:
12270       /* Even on a big endian machine $fn comes before $fn+1.  We have
12271          to adjust when loading from memory.  We set coproc if we must
12272          load $fn+1 first.  */
12273       /* Itbl support may require additional care here.  */
12274       if (!target_big_endian)
12275         coproc = 0;
12276
12277       breg = op[2];
12278       if (small_offset_p (0, align, 16))
12279         {
12280           ep = &offset_expr;
12281           if (!small_offset_p (4, align, 16))
12282             {
12283               macro_build (&offset_expr, ADDRESS_ADDI_INSN, "t,r,j", AT, breg,
12284                            -1, offset_reloc[0], offset_reloc[1],
12285                            offset_reloc[2]);
12286               expr1.X_add_number = 0;
12287               ep = &expr1;
12288               breg = AT;
12289               used_at = 1;
12290               offset_reloc[0] = BFD_RELOC_LO16;
12291               offset_reloc[1] = BFD_RELOC_UNUSED;
12292               offset_reloc[2] = BFD_RELOC_UNUSED;
12293             }
12294           if (strcmp (s, "lw") == 0 && op[0] == breg)
12295             {
12296               ep->X_add_number += 4;
12297               macro_build (ep, s, fmt, op[0] + 1, -1, offset_reloc[0],
12298                            offset_reloc[1], offset_reloc[2], breg);
12299               ep->X_add_number -= 4;
12300               macro_build (ep, s, fmt, op[0], -1, offset_reloc[0],
12301                            offset_reloc[1], offset_reloc[2], breg);
12302             }
12303           else
12304             {
12305               macro_build (ep, s, fmt, coproc ? op[0] + 1 : op[0], -1,
12306                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12307                            breg);
12308               ep->X_add_number += 4;
12309               macro_build (ep, s, fmt, coproc ? op[0] : op[0] + 1, -1,
12310                            offset_reloc[0], offset_reloc[1], offset_reloc[2],
12311                            breg);
12312             }
12313           break;
12314         }
12315
12316       if (offset_expr.X_op != O_symbol
12317           && offset_expr.X_op != O_constant)
12318         {
12319           as_bad (_("expression too complex"));
12320           offset_expr.X_op = O_constant;
12321         }
12322
12323       if (HAVE_32BIT_ADDRESSES
12324           && !IS_SEXT_32BIT_NUM (offset_expr.X_add_number))
12325         {
12326           char value [32];
12327
12328           sprintf_vma (value, offset_expr.X_add_number);
12329           as_bad (_("number (0x%s) larger than 32 bits"), value);
12330         }
12331
12332       if (mips_pic == NO_PIC || offset_expr.X_op == O_constant)
12333         {
12334           /* If this is a reference to a GP relative symbol, we want
12335                <op>     op[0],<sym>($gp)        (BFD_RELOC_GPREL16)
12336                <op>     op[0]+1,<sym>+4($gp)    (BFD_RELOC_GPREL16)
12337              If we have a base register, we use this
12338                addu     $at,$breg,$gp
12339                <op>     op[0],<sym>($at)        (BFD_RELOC_GPREL16)
12340                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_GPREL16)
12341              If this is not a GP relative symbol, we want
12342                lui      $at,<sym>               (BFD_RELOC_HI16_S)
12343                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12344                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12345              If there is a base register, we add it to $at after the
12346              lui instruction.  If there is a constant, we always use
12347              the last case.  */
12348           if (offset_expr.X_op == O_symbol
12349               && (valueT) offset_expr.X_add_number <= MAX_GPREL_OFFSET
12350               && !nopic_need_relax (offset_expr.X_add_symbol, 1))
12351             {
12352               relax_start (offset_expr.X_add_symbol);
12353               if (breg == 0)
12354                 {
12355                   tempreg = mips_gp_register;
12356                 }
12357               else
12358                 {
12359                   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12360                                AT, breg, mips_gp_register);
12361                   tempreg = AT;
12362                   used_at = 1;
12363                 }
12364
12365               /* Itbl support may require additional care here.  */
12366               macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12367                            BFD_RELOC_GPREL16, tempreg);
12368               offset_expr.X_add_number += 4;
12369
12370               /* Set mips_optimize to 2 to avoid inserting an
12371                  undesired nop.  */
12372               hold_mips_optimize = mips_optimize;
12373               mips_optimize = 2;
12374               /* Itbl support may require additional care here.  */
12375               macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12376                            BFD_RELOC_GPREL16, tempreg);
12377               mips_optimize = hold_mips_optimize;
12378
12379               relax_switch ();
12380
12381               offset_expr.X_add_number -= 4;
12382             }
12383           used_at = 1;
12384           if (offset_high_part (offset_expr.X_add_number, 16)
12385               != offset_high_part (offset_expr.X_add_number + 4, 16))
12386             {
12387               load_address (AT, &offset_expr, &used_at);
12388               offset_expr.X_op = O_constant;
12389               offset_expr.X_add_number = 0;
12390             }
12391           else
12392             macro_build_lui (&offset_expr, AT);
12393           if (breg != 0)
12394             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12395           /* Itbl support may require additional care here.  */
12396           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12397                        BFD_RELOC_LO16, AT);
12398           /* FIXME: How do we handle overflow here?  */
12399           offset_expr.X_add_number += 4;
12400           /* Itbl support may require additional care here.  */
12401           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12402                        BFD_RELOC_LO16, AT);
12403           if (mips_relax.sequence)
12404             relax_end ();
12405         }
12406       else if (!mips_big_got)
12407         {
12408           /* If this is a reference to an external symbol, we want
12409                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12410                nop
12411                <op>     op[0],0($at)
12412                <op>     op[0]+1,4($at)
12413              Otherwise we want
12414                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12415                nop
12416                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12417                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12418              If there is a base register we add it to $at before the
12419              lwc1 instructions.  If there is a constant we include it
12420              in the lwc1 instructions.  */
12421           used_at = 1;
12422           expr1.X_add_number = offset_expr.X_add_number;
12423           if (expr1.X_add_number < -0x8000
12424               || expr1.X_add_number >= 0x8000 - 4)
12425             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12426           load_got_offset (AT, &offset_expr);
12427           load_delay_nop ();
12428           if (breg != 0)
12429             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12430
12431           /* Set mips_optimize to 2 to avoid inserting an undesired
12432              nop.  */
12433           hold_mips_optimize = mips_optimize;
12434           mips_optimize = 2;
12435
12436           /* Itbl support may require additional care here.  */
12437           relax_start (offset_expr.X_add_symbol);
12438           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12439                        BFD_RELOC_LO16, AT);
12440           expr1.X_add_number += 4;
12441           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12442                        BFD_RELOC_LO16, AT);
12443           relax_switch ();
12444           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12445                        BFD_RELOC_LO16, AT);
12446           offset_expr.X_add_number += 4;
12447           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12448                        BFD_RELOC_LO16, AT);
12449           relax_end ();
12450
12451           mips_optimize = hold_mips_optimize;
12452         }
12453       else if (mips_big_got)
12454         {
12455           int gpdelay;
12456
12457           /* If this is a reference to an external symbol, we want
12458                lui      $at,<sym>               (BFD_RELOC_MIPS_GOT_HI16)
12459                addu     $at,$at,$gp
12460                lw       $at,<sym>($at)          (BFD_RELOC_MIPS_GOT_LO16)
12461                nop
12462                <op>     op[0],0($at)
12463                <op>     op[0]+1,4($at)
12464              Otherwise we want
12465                lw       $at,<sym>($gp)          (BFD_RELOC_MIPS_GOT16)
12466                nop
12467                <op>     op[0],<sym>($at)        (BFD_RELOC_LO16)
12468                <op>     op[0]+1,<sym>+4($at)    (BFD_RELOC_LO16)
12469              If there is a base register we add it to $at before the
12470              lwc1 instructions.  If there is a constant we include it
12471              in the lwc1 instructions.  */
12472           used_at = 1;
12473           expr1.X_add_number = offset_expr.X_add_number;
12474           offset_expr.X_add_number = 0;
12475           if (expr1.X_add_number < -0x8000
12476               || expr1.X_add_number >= 0x8000 - 4)
12477             as_bad (_("PIC code offset overflow (max 16 signed bits)"));
12478           gpdelay = reg_needs_delay (mips_gp_register);
12479           relax_start (offset_expr.X_add_symbol);
12480           macro_build (&offset_expr, "lui", LUI_FMT,
12481                        AT, BFD_RELOC_MIPS_GOT_HI16);
12482           macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
12483                        AT, AT, mips_gp_register);
12484           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)",
12485                        AT, BFD_RELOC_MIPS_GOT_LO16, AT);
12486           load_delay_nop ();
12487           if (breg != 0)
12488             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12489           /* Itbl support may require additional care here.  */
12490           macro_build (&expr1, s, fmt, coproc ? op[0] + 1 : op[0],
12491                        BFD_RELOC_LO16, AT);
12492           expr1.X_add_number += 4;
12493
12494           /* Set mips_optimize to 2 to avoid inserting an undesired
12495              nop.  */
12496           hold_mips_optimize = mips_optimize;
12497           mips_optimize = 2;
12498           /* Itbl support may require additional care here.  */
12499           macro_build (&expr1, s, fmt, coproc ? op[0] : op[0] + 1,
12500                        BFD_RELOC_LO16, AT);
12501           mips_optimize = hold_mips_optimize;
12502           expr1.X_add_number -= 4;
12503
12504           relax_switch ();
12505           offset_expr.X_add_number = expr1.X_add_number;
12506           if (gpdelay)
12507             macro_build (NULL, "nop", "");
12508           macro_build (&offset_expr, ADDRESS_LOAD_INSN, "t,o(b)", AT,
12509                        BFD_RELOC_MIPS_GOT16, mips_gp_register);
12510           load_delay_nop ();
12511           if (breg != 0)
12512             macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", AT, breg, AT);
12513           /* Itbl support may require additional care here.  */
12514           macro_build (&offset_expr, s, fmt, coproc ? op[0] + 1 : op[0],
12515                        BFD_RELOC_LO16, AT);
12516           offset_expr.X_add_number += 4;
12517
12518           /* Set mips_optimize to 2 to avoid inserting an undesired
12519              nop.  */
12520           hold_mips_optimize = mips_optimize;
12521           mips_optimize = 2;
12522           /* Itbl support may require additional care here.  */
12523           macro_build (&offset_expr, s, fmt, coproc ? op[0] : op[0] + 1,
12524                        BFD_RELOC_LO16, AT);
12525           mips_optimize = hold_mips_optimize;
12526           relax_end ();
12527         }
12528       else
12529         abort ();
12530
12531       break;
12532
12533     case M_SAA_AB:
12534       s = "saa";
12535       goto saa_saad;
12536     case M_SAAD_AB:
12537       s = "saad";
12538     saa_saad:
12539       gas_assert (!mips_opts.micromips);
12540       offbits = 0;
12541       fmt = "t,(b)";
12542       goto ld_st;
12543
12544    /* New code added to support COPZ instructions.
12545       This code builds table entries out of the macros in mip_opcodes.
12546       R4000 uses interlocks to handle coproc delays.
12547       Other chips (like the R3000) require nops to be inserted for delays.
12548
12549       FIXME: Currently, we require that the user handle delays.
12550       In order to fill delay slots for non-interlocked chips,
12551       we must have a way to specify delays based on the coprocessor.
12552       Eg. 4 cycles if load coproc reg from memory, 1 if in cache, etc.
12553       What are the side-effects of the cop instruction?
12554       What cache support might we have and what are its effects?
12555       Both coprocessor & memory require delays. how long???
12556       What registers are read/set/modified?
12557
12558       If an itbl is provided to interpret cop instructions,
12559       this knowledge can be encoded in the itbl spec.  */
12560
12561     case M_COP0:
12562       s = "c0";
12563       goto copz;
12564     case M_COP1:
12565       s = "c1";
12566       goto copz;
12567     case M_COP2:
12568       s = "c2";
12569       goto copz;
12570     case M_COP3:
12571       s = "c3";
12572     copz:
12573       gas_assert (!mips_opts.micromips);
12574       /* For now we just do C (same as Cz).  The parameter will be
12575          stored in insn_opcode by mips_ip.  */
12576       macro_build (NULL, s, "C", (int) ip->insn_opcode);
12577       break;
12578
12579     case M_MOVE:
12580       move_register (op[0], op[1]);
12581       break;
12582
12583     case M_MOVEP:
12584       gas_assert (mips_opts.micromips);
12585       gas_assert (mips_opts.insn32);
12586       move_register (micromips_to_32_reg_h_map1[op[0]],
12587                      micromips_to_32_reg_m_map[op[1]]);
12588       move_register (micromips_to_32_reg_h_map2[op[0]],
12589                      micromips_to_32_reg_n_map[op[2]]);
12590       break;
12591
12592     case M_DMUL:
12593       dbl = 1;
12594     case M_MUL:
12595       if (mips_opts.arch == CPU_R5900)
12596         macro_build (NULL, dbl ? "dmultu" : "multu", "d,s,t", op[0], op[1],
12597                      op[2]);
12598       else
12599         {
12600           macro_build (NULL, dbl ? "dmultu" : "multu", "s,t", op[1], op[2]);
12601           macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12602         }
12603       break;
12604
12605     case M_DMUL_I:
12606       dbl = 1;
12607     case M_MUL_I:
12608       /* The MIPS assembler some times generates shifts and adds.  I'm
12609          not trying to be that fancy. GCC should do this for us
12610          anyway.  */
12611       used_at = 1;
12612       load_register (AT, &imm_expr, dbl);
12613       macro_build (NULL, dbl ? "dmult" : "mult", "s,t", op[1], AT);
12614       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12615       break;
12616
12617     case M_DMULO_I:
12618       dbl = 1;
12619     case M_MULO_I:
12620       imm = 1;
12621       goto do_mulo;
12622
12623     case M_DMULO:
12624       dbl = 1;
12625     case M_MULO:
12626     do_mulo:
12627       start_noreorder ();
12628       used_at = 1;
12629       if (imm)
12630         load_register (AT, &imm_expr, dbl);
12631       macro_build (NULL, dbl ? "dmult" : "mult", "s,t",
12632                    op[1], imm ? AT : op[2]);
12633       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12634       macro_build (NULL, dbl ? "dsra32" : "sra", SHFT_FMT, op[0], op[0], 31);
12635       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12636       if (mips_trap)
12637         macro_build (NULL, "tne", TRAP_FMT, op[0], AT, 6);
12638       else
12639         {
12640           if (mips_opts.micromips)
12641             micromips_label_expr (&label_expr);
12642           else
12643             label_expr.X_add_number = 8;
12644           macro_build (&label_expr, "beq", "s,t,p", op[0], AT);
12645           macro_build (NULL, "nop", "");
12646           macro_build (NULL, "break", BRK_FMT, 6);
12647           if (mips_opts.micromips)
12648             micromips_add_label ();
12649         }
12650       end_noreorder ();
12651       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12652       break;
12653
12654     case M_DMULOU_I:
12655       dbl = 1;
12656     case M_MULOU_I:
12657       imm = 1;
12658       goto do_mulou;
12659
12660     case M_DMULOU:
12661       dbl = 1;
12662     case M_MULOU:
12663     do_mulou:
12664       start_noreorder ();
12665       used_at = 1;
12666       if (imm)
12667         load_register (AT, &imm_expr, dbl);
12668       macro_build (NULL, dbl ? "dmultu" : "multu", "s,t",
12669                    op[1], imm ? AT : op[2]);
12670       macro_build (NULL, "mfhi", MFHL_FMT, AT);
12671       macro_build (NULL, "mflo", MFHL_FMT, op[0]);
12672       if (mips_trap)
12673         macro_build (NULL, "tne", TRAP_FMT, AT, ZERO, 6);
12674       else
12675         {
12676           if (mips_opts.micromips)
12677             micromips_label_expr (&label_expr);
12678           else
12679             label_expr.X_add_number = 8;
12680           macro_build (&label_expr, "beq", "s,t,p", AT, ZERO);
12681           macro_build (NULL, "nop", "");
12682           macro_build (NULL, "break", BRK_FMT, 6);
12683           if (mips_opts.micromips)
12684             micromips_add_label ();
12685         }
12686       end_noreorder ();
12687       break;
12688
12689     case M_DROL:
12690       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12691         {
12692           if (op[0] == op[1])
12693             {
12694               tempreg = AT;
12695               used_at = 1;
12696             }
12697           else
12698             tempreg = op[0];
12699           macro_build (NULL, "dnegu", "d,w", tempreg, op[2]);
12700           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], tempreg);
12701           break;
12702         }
12703       used_at = 1;
12704       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12705       macro_build (NULL, "dsrlv", "d,t,s", AT, op[1], AT);
12706       macro_build (NULL, "dsllv", "d,t,s", op[0], op[1], op[2]);
12707       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12708       break;
12709
12710     case M_ROL:
12711       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12712         {
12713           if (op[0] == op[1])
12714             {
12715               tempreg = AT;
12716               used_at = 1;
12717             }
12718           else
12719             tempreg = op[0];
12720           macro_build (NULL, "negu", "d,w", tempreg, op[2]);
12721           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], tempreg);
12722           break;
12723         }
12724       used_at = 1;
12725       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12726       macro_build (NULL, "srlv", "d,t,s", AT, op[1], AT);
12727       macro_build (NULL, "sllv", "d,t,s", op[0], op[1], op[2]);
12728       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12729       break;
12730
12731     case M_DROL_I:
12732       {
12733         unsigned int rot;
12734         const char *l;
12735         const char *rr;
12736
12737         rot = imm_expr.X_add_number & 0x3f;
12738         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12739           {
12740             rot = (64 - rot) & 0x3f;
12741             if (rot >= 32)
12742               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12743             else
12744               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12745             break;
12746           }
12747         if (rot == 0)
12748           {
12749             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12750             break;
12751           }
12752         l = (rot < 0x20) ? "dsll" : "dsll32";
12753         rr = ((0x40 - rot) < 0x20) ? "dsrl" : "dsrl32";
12754         rot &= 0x1f;
12755         used_at = 1;
12756         macro_build (NULL, l, SHFT_FMT, AT, op[1], rot);
12757         macro_build (NULL, rr, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12758         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12759       }
12760       break;
12761
12762     case M_ROL_I:
12763       {
12764         unsigned int rot;
12765
12766         rot = imm_expr.X_add_number & 0x1f;
12767         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12768           {
12769             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1],
12770                          (32 - rot) & 0x1f);
12771             break;
12772           }
12773         if (rot == 0)
12774           {
12775             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12776             break;
12777           }
12778         used_at = 1;
12779         macro_build (NULL, "sll", SHFT_FMT, AT, op[1], rot);
12780         macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12781         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12782       }
12783       break;
12784
12785     case M_DROR:
12786       if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12787         {
12788           macro_build (NULL, "drorv", "d,t,s", op[0], op[1], op[2]);
12789           break;
12790         }
12791       used_at = 1;
12792       macro_build (NULL, "dsubu", "d,v,t", AT, ZERO, op[2]);
12793       macro_build (NULL, "dsllv", "d,t,s", AT, op[1], AT);
12794       macro_build (NULL, "dsrlv", "d,t,s", op[0], op[1], op[2]);
12795       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12796       break;
12797
12798     case M_ROR:
12799       if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12800         {
12801           macro_build (NULL, "rorv", "d,t,s", op[0], op[1], op[2]);
12802           break;
12803         }
12804       used_at = 1;
12805       macro_build (NULL, "subu", "d,v,t", AT, ZERO, op[2]);
12806       macro_build (NULL, "sllv", "d,t,s", AT, op[1], AT);
12807       macro_build (NULL, "srlv", "d,t,s", op[0], op[1], op[2]);
12808       macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12809       break;
12810
12811     case M_DROR_I:
12812       {
12813         unsigned int rot;
12814         const char *l;
12815         const char *rr;
12816
12817         rot = imm_expr.X_add_number & 0x3f;
12818         if (ISA_HAS_DROR (mips_opts.isa) || CPU_HAS_DROR (mips_opts.arch))
12819           {
12820             if (rot >= 32)
12821               macro_build (NULL, "dror32", SHFT_FMT, op[0], op[1], rot - 32);
12822             else
12823               macro_build (NULL, "dror", SHFT_FMT, op[0], op[1], rot);
12824             break;
12825           }
12826         if (rot == 0)
12827           {
12828             macro_build (NULL, "dsrl", SHFT_FMT, op[0], op[1], 0);
12829             break;
12830           }
12831         rr = (rot < 0x20) ? "dsrl" : "dsrl32";
12832         l = ((0x40 - rot) < 0x20) ? "dsll" : "dsll32";
12833         rot &= 0x1f;
12834         used_at = 1;
12835         macro_build (NULL, rr, SHFT_FMT, AT, op[1], rot);
12836         macro_build (NULL, l, SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12837         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12838       }
12839       break;
12840
12841     case M_ROR_I:
12842       {
12843         unsigned int rot;
12844
12845         rot = imm_expr.X_add_number & 0x1f;
12846         if (ISA_HAS_ROR (mips_opts.isa) || CPU_HAS_ROR (mips_opts.arch))
12847           {
12848             macro_build (NULL, "ror", SHFT_FMT, op[0], op[1], rot);
12849             break;
12850           }
12851         if (rot == 0)
12852           {
12853             macro_build (NULL, "srl", SHFT_FMT, op[0], op[1], 0);
12854             break;
12855           }
12856         used_at = 1;
12857         macro_build (NULL, "srl", SHFT_FMT, AT, op[1], rot);
12858         macro_build (NULL, "sll", SHFT_FMT, op[0], op[1], (0x20 - rot) & 0x1f);
12859         macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
12860       }
12861       break;
12862
12863     case M_SEQ:
12864       if (op[1] == 0)
12865         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[2], BFD_RELOC_LO16);
12866       else if (op[2] == 0)
12867         macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12868       else
12869         {
12870           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
12871           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12872         }
12873       break;
12874
12875     case M_SEQ_I:
12876       if (imm_expr.X_add_number == 0)
12877         {
12878           macro_build (&expr1, "sltiu", "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12879           break;
12880         }
12881       if (op[1] == 0)
12882         {
12883           as_warn (_("instruction %s: result is always false"),
12884                    ip->insn_mo->name);
12885           move_register (op[0], 0);
12886           break;
12887         }
12888       if (CPU_HAS_SEQ (mips_opts.arch)
12889           && -512 <= imm_expr.X_add_number
12890           && imm_expr.X_add_number < 512)
12891         {
12892           macro_build (NULL, "seqi", "t,r,+Q", op[0], op[1],
12893                        (int) imm_expr.X_add_number);
12894           break;
12895         }
12896       if (imm_expr.X_add_number >= 0
12897           && imm_expr.X_add_number < 0x10000)
12898         macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1], BFD_RELOC_LO16);
12899       else if (imm_expr.X_add_number > -0x8000
12900                && imm_expr.X_add_number < 0)
12901         {
12902           imm_expr.X_add_number = -imm_expr.X_add_number;
12903           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
12904                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
12905         }
12906       else if (CPU_HAS_SEQ (mips_opts.arch))
12907         {
12908           used_at = 1;
12909           load_register (AT, &imm_expr, GPR_SIZE == 64);
12910           macro_build (NULL, "seq", "d,v,t", op[0], op[1], AT);
12911           break;
12912         }
12913       else
12914         {
12915           load_register (AT, &imm_expr, GPR_SIZE == 64);
12916           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
12917           used_at = 1;
12918         }
12919       macro_build (&expr1, "sltiu", "t,r,j", op[0], op[0], BFD_RELOC_LO16);
12920       break;
12921
12922     case M_SGE:         /* X >= Y  <==>  not (X < Y) */
12923       s = "slt";
12924       goto sge;
12925     case M_SGEU:
12926       s = "sltu";
12927     sge:
12928       macro_build (NULL, s, "d,v,t", op[0], op[1], op[2]);
12929       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12930       break;
12931
12932     case M_SGE_I:       /* X >= I  <==>  not (X < I) */
12933     case M_SGEU_I:
12934       if (imm_expr.X_add_number >= -0x8000
12935           && imm_expr.X_add_number < 0x8000)
12936         macro_build (&imm_expr, mask == M_SGE_I ? "slti" : "sltiu", "t,r,j",
12937                      op[0], op[1], BFD_RELOC_LO16);
12938       else
12939         {
12940           load_register (AT, &imm_expr, GPR_SIZE == 64);
12941           macro_build (NULL, mask == M_SGE_I ? "slt" : "sltu", "d,v,t",
12942                        op[0], op[1], AT);
12943           used_at = 1;
12944         }
12945       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12946       break;
12947
12948     case M_SGT:         /* X > Y  <==>  Y < X */
12949       s = "slt";
12950       goto sgt;
12951     case M_SGTU:
12952       s = "sltu";
12953     sgt:
12954       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12955       break;
12956
12957     case M_SGT_I:       /* X > I  <==>  I < X */
12958       s = "slt";
12959       goto sgti;
12960     case M_SGTU_I:
12961       s = "sltu";
12962     sgti:
12963       used_at = 1;
12964       load_register (AT, &imm_expr, GPR_SIZE == 64);
12965       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12966       break;
12967
12968     case M_SLE:         /* X <= Y  <==>  Y >= X  <==>  not (Y < X) */
12969       s = "slt";
12970       goto sle;
12971     case M_SLEU:
12972       s = "sltu";
12973     sle:
12974       macro_build (NULL, s, "d,v,t", op[0], op[2], op[1]);
12975       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12976       break;
12977
12978     case M_SLE_I:       /* X <= I  <==>  I >= X  <==>  not (I < X) */
12979       s = "slt";
12980       goto slei;
12981     case M_SLEU_I:
12982       s = "sltu";
12983     slei:
12984       used_at = 1;
12985       load_register (AT, &imm_expr, GPR_SIZE == 64);
12986       macro_build (NULL, s, "d,v,t", op[0], AT, op[1]);
12987       macro_build (&expr1, "xori", "t,r,i", op[0], op[0], BFD_RELOC_LO16);
12988       break;
12989
12990     case M_SLT_I:
12991       if (imm_expr.X_add_number >= -0x8000
12992           && imm_expr.X_add_number < 0x8000)
12993         {
12994           macro_build (&imm_expr, "slti", "t,r,j", op[0], op[1],
12995                        BFD_RELOC_LO16);
12996           break;
12997         }
12998       used_at = 1;
12999       load_register (AT, &imm_expr, GPR_SIZE == 64);
13000       macro_build (NULL, "slt", "d,v,t", op[0], op[1], AT);
13001       break;
13002
13003     case M_SLTU_I:
13004       if (imm_expr.X_add_number >= -0x8000
13005           && imm_expr.X_add_number < 0x8000)
13006         {
13007           macro_build (&imm_expr, "sltiu", "t,r,j", op[0], op[1],
13008                        BFD_RELOC_LO16);
13009           break;
13010         }
13011       used_at = 1;
13012       load_register (AT, &imm_expr, GPR_SIZE == 64);
13013       macro_build (NULL, "sltu", "d,v,t", op[0], op[1], AT);
13014       break;
13015
13016     case M_SNE:
13017       if (op[1] == 0)
13018         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[2]);
13019       else if (op[2] == 0)
13020         macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13021       else
13022         {
13023           macro_build (NULL, "xor", "d,v,t", op[0], op[1], op[2]);
13024           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13025         }
13026       break;
13027
13028     case M_SNE_I:
13029       if (imm_expr.X_add_number == 0)
13030         {
13031           macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[1]);
13032           break;
13033         }
13034       if (op[1] == 0)
13035         {
13036           as_warn (_("instruction %s: result is always true"),
13037                    ip->insn_mo->name);
13038           macro_build (&expr1, GPR_SIZE == 32 ? "addiu" : "daddiu", "t,r,j",
13039                        op[0], 0, BFD_RELOC_LO16);
13040           break;
13041         }
13042       if (CPU_HAS_SEQ (mips_opts.arch)
13043           && -512 <= imm_expr.X_add_number
13044           && imm_expr.X_add_number < 512)
13045         {
13046           macro_build (NULL, "snei", "t,r,+Q", op[0], op[1],
13047                        (int) imm_expr.X_add_number);
13048           break;
13049         }
13050       if (imm_expr.X_add_number >= 0
13051           && imm_expr.X_add_number < 0x10000)
13052         {
13053           macro_build (&imm_expr, "xori", "t,r,i", op[0], op[1],
13054                        BFD_RELOC_LO16);
13055         }
13056       else if (imm_expr.X_add_number > -0x8000
13057                && imm_expr.X_add_number < 0)
13058         {
13059           imm_expr.X_add_number = -imm_expr.X_add_number;
13060           macro_build (&imm_expr, GPR_SIZE == 32 ? "addiu" : "daddiu",
13061                        "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13062         }
13063       else if (CPU_HAS_SEQ (mips_opts.arch))
13064         {
13065           used_at = 1;
13066           load_register (AT, &imm_expr, GPR_SIZE == 64);
13067           macro_build (NULL, "sne", "d,v,t", op[0], op[1], AT);
13068           break;
13069         }
13070       else
13071         {
13072           load_register (AT, &imm_expr, GPR_SIZE == 64);
13073           macro_build (NULL, "xor", "d,v,t", op[0], op[1], AT);
13074           used_at = 1;
13075         }
13076       macro_build (NULL, "sltu", "d,v,t", op[0], 0, op[0]);
13077       break;
13078
13079     case M_SUB_I:
13080       s = "addi";
13081       s2 = "sub";
13082       goto do_subi;
13083     case M_SUBU_I:
13084       s = "addiu";
13085       s2 = "subu";
13086       goto do_subi;
13087     case M_DSUB_I:
13088       dbl = 1;
13089       s = "daddi";
13090       s2 = "dsub";
13091       if (!mips_opts.micromips)
13092         goto do_subi;
13093       if (imm_expr.X_add_number > -0x200
13094           && imm_expr.X_add_number <= 0x200)
13095         {
13096           macro_build (NULL, s, "t,r,.", op[0], op[1],
13097                        (int) -imm_expr.X_add_number);
13098           break;
13099         }
13100       goto do_subi_i;
13101     case M_DSUBU_I:
13102       dbl = 1;
13103       s = "daddiu";
13104       s2 = "dsubu";
13105     do_subi:
13106       if (imm_expr.X_add_number > -0x8000
13107           && imm_expr.X_add_number <= 0x8000)
13108         {
13109           imm_expr.X_add_number = -imm_expr.X_add_number;
13110           macro_build (&imm_expr, s, "t,r,j", op[0], op[1], BFD_RELOC_LO16);
13111           break;
13112         }
13113     do_subi_i:
13114       used_at = 1;
13115       load_register (AT, &imm_expr, dbl);
13116       macro_build (NULL, s2, "d,v,t", op[0], op[1], AT);
13117       break;
13118
13119     case M_TEQ_I:
13120       s = "teq";
13121       goto trap;
13122     case M_TGE_I:
13123       s = "tge";
13124       goto trap;
13125     case M_TGEU_I:
13126       s = "tgeu";
13127       goto trap;
13128     case M_TLT_I:
13129       s = "tlt";
13130       goto trap;
13131     case M_TLTU_I:
13132       s = "tltu";
13133       goto trap;
13134     case M_TNE_I:
13135       s = "tne";
13136     trap:
13137       used_at = 1;
13138       load_register (AT, &imm_expr, GPR_SIZE == 64);
13139       macro_build (NULL, s, "s,t", op[0], AT);
13140       break;
13141
13142     case M_TRUNCWS:
13143     case M_TRUNCWD:
13144       gas_assert (!mips_opts.micromips);
13145       gas_assert (mips_opts.isa == ISA_MIPS1);
13146       used_at = 1;
13147
13148       /*
13149        * Is the double cfc1 instruction a bug in the mips assembler;
13150        * or is there a reason for it?
13151        */
13152       start_noreorder ();
13153       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13154       macro_build (NULL, "cfc1", "t,G", op[2], RA);
13155       macro_build (NULL, "nop", "");
13156       expr1.X_add_number = 3;
13157       macro_build (&expr1, "ori", "t,r,i", AT, op[2], BFD_RELOC_LO16);
13158       expr1.X_add_number = 2;
13159       macro_build (&expr1, "xori", "t,r,i", AT, AT, BFD_RELOC_LO16);
13160       macro_build (NULL, "ctc1", "t,G", AT, RA);
13161       macro_build (NULL, "nop", "");
13162       macro_build (NULL, mask == M_TRUNCWD ? "cvt.w.d" : "cvt.w.s", "D,S",
13163                    op[0], op[1]);
13164       macro_build (NULL, "ctc1", "t,G", op[2], RA);
13165       macro_build (NULL, "nop", "");
13166       end_noreorder ();
13167       break;
13168
13169     case M_ULH_AB:
13170       s = "lb";
13171       s2 = "lbu";
13172       off = 1;
13173       goto uld_st;
13174     case M_ULHU_AB:
13175       s = "lbu";
13176       s2 = "lbu";
13177       off = 1;
13178       goto uld_st;
13179     case M_ULW_AB:
13180       s = "lwl";
13181       s2 = "lwr";
13182       offbits = (mips_opts.micromips ? 12 : 16);
13183       off = 3;
13184       goto uld_st;
13185     case M_ULD_AB:
13186       s = "ldl";
13187       s2 = "ldr";
13188       offbits = (mips_opts.micromips ? 12 : 16);
13189       off = 7;
13190       goto uld_st;
13191     case M_USH_AB:
13192       s = "sb";
13193       s2 = "sb";
13194       off = 1;
13195       ust = 1;
13196       goto uld_st;
13197     case M_USW_AB:
13198       s = "swl";
13199       s2 = "swr";
13200       offbits = (mips_opts.micromips ? 12 : 16);
13201       off = 3;
13202       ust = 1;
13203       goto uld_st;
13204     case M_USD_AB:
13205       s = "sdl";
13206       s2 = "sdr";
13207       offbits = (mips_opts.micromips ? 12 : 16);
13208       off = 7;
13209       ust = 1;
13210
13211     uld_st:
13212       breg = op[2];
13213       large_offset = !small_offset_p (off, align, offbits);
13214       ep = &offset_expr;
13215       expr1.X_add_number = 0;
13216       if (large_offset)
13217         {
13218           used_at = 1;
13219           tempreg = AT;
13220           if (small_offset_p (0, align, 16))
13221             macro_build (ep, ADDRESS_ADDI_INSN, "t,r,j", tempreg, breg, -1,
13222                          offset_reloc[0], offset_reloc[1], offset_reloc[2]);
13223           else
13224             {
13225               load_address (tempreg, ep, &used_at);
13226               if (breg != 0)
13227                 macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t",
13228                              tempreg, tempreg, breg);
13229             }
13230           offset_reloc[0] = BFD_RELOC_LO16;
13231           offset_reloc[1] = BFD_RELOC_UNUSED;
13232           offset_reloc[2] = BFD_RELOC_UNUSED;
13233           breg = tempreg;
13234           tempreg = op[0];
13235           ep = &expr1;
13236         }
13237       else if (!ust && op[0] == breg)
13238         {
13239           used_at = 1;
13240           tempreg = AT;
13241         }
13242       else
13243         tempreg = op[0];
13244
13245       if (off == 1)
13246         goto ulh_sh;
13247
13248       if (!target_big_endian)
13249         ep->X_add_number += off;
13250       if (offbits == 12)
13251         macro_build (NULL, s, "t,~(b)", tempreg, (int) ep->X_add_number, breg);
13252       else
13253         macro_build (ep, s, "t,o(b)", tempreg, -1,
13254                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13255
13256       if (!target_big_endian)
13257         ep->X_add_number -= off;
13258       else
13259         ep->X_add_number += off;
13260       if (offbits == 12)
13261         macro_build (NULL, s2, "t,~(b)",
13262                      tempreg, (int) ep->X_add_number, breg);
13263       else
13264         macro_build (ep, s2, "t,o(b)", tempreg, -1,
13265                      offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13266
13267       /* If necessary, move the result in tempreg to the final destination.  */
13268       if (!ust && op[0] != tempreg)
13269         {
13270           /* Protect second load's delay slot.  */
13271           load_delay_nop ();
13272           move_register (op[0], tempreg);
13273         }
13274       break;
13275
13276     ulh_sh:
13277       used_at = 1;
13278       if (target_big_endian == ust)
13279         ep->X_add_number += off;
13280       tempreg = ust || large_offset ? op[0] : AT;
13281       macro_build (ep, s, "t,o(b)", tempreg, -1,
13282                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13283
13284       /* For halfword transfers we need a temporary register to shuffle
13285          bytes.  Unfortunately for M_USH_A we have none available before
13286          the next store as AT holds the base address.  We deal with this
13287          case by clobbering TREG and then restoring it as with ULH.  */
13288       tempreg = ust == large_offset ? op[0] : AT;
13289       if (ust)
13290         macro_build (NULL, "srl", SHFT_FMT, tempreg, op[0], 8);
13291
13292       if (target_big_endian == ust)
13293         ep->X_add_number -= off;
13294       else
13295         ep->X_add_number += off;
13296       macro_build (ep, s2, "t,o(b)", tempreg, -1,
13297                    offset_reloc[0], offset_reloc[1], offset_reloc[2], breg);
13298
13299       /* For M_USH_A re-retrieve the LSB.  */
13300       if (ust && large_offset)
13301         {
13302           if (target_big_endian)
13303             ep->X_add_number += off;
13304           else
13305             ep->X_add_number -= off;
13306           macro_build (&expr1, "lbu", "t,o(b)", AT, -1,
13307                        offset_reloc[0], offset_reloc[1], offset_reloc[2], AT);
13308         }
13309       /* For ULH and M_USH_A OR the LSB in.  */
13310       if (!ust || large_offset)
13311         {
13312           tempreg = !large_offset ? AT : op[0];
13313           macro_build (NULL, "sll", SHFT_FMT, tempreg, tempreg, 8);
13314           macro_build (NULL, "or", "d,v,t", op[0], op[0], AT);
13315         }
13316       break;
13317
13318     default:
13319       /* FIXME: Check if this is one of the itbl macros, since they
13320          are added dynamically.  */
13321       as_bad (_("macro %s not implemented yet"), ip->insn_mo->name);
13322       break;
13323     }
13324   if (!mips_opts.at && used_at)
13325     as_bad (_("macro used $at after \".set noat\""));
13326 }
13327
13328 /* Implement macros in mips16 mode.  */
13329
13330 static void
13331 mips16_macro (struct mips_cl_insn *ip)
13332 {
13333   const struct mips_operand_array *operands;
13334   int mask;
13335   int tmp;
13336   expressionS expr1;
13337   int dbl;
13338   const char *s, *s2, *s3;
13339   unsigned int op[MAX_OPERANDS];
13340   unsigned int i;
13341
13342   mask = ip->insn_mo->mask;
13343
13344   operands = insn_operands (ip);
13345   for (i = 0; i < MAX_OPERANDS; i++)
13346     if (operands->operand[i])
13347       op[i] = insn_extract_operand (ip, operands->operand[i]);
13348     else
13349       op[i] = -1;
13350
13351   expr1.X_op = O_constant;
13352   expr1.X_op_symbol = NULL;
13353   expr1.X_add_symbol = NULL;
13354   expr1.X_add_number = 1;
13355
13356   dbl = 0;
13357
13358   switch (mask)
13359     {
13360     default:
13361       abort ();
13362
13363     case M_DDIV_3:
13364       dbl = 1;
13365     case M_DIV_3:
13366       s = "mflo";
13367       goto do_div3;
13368     case M_DREM_3:
13369       dbl = 1;
13370     case M_REM_3:
13371       s = "mfhi";
13372     do_div3:
13373       start_noreorder ();
13374       macro_build (NULL, dbl ? "ddiv" : "div", "0,x,y", op[1], op[2]);
13375       expr1.X_add_number = 2;
13376       macro_build (&expr1, "bnez", "x,p", op[2]);
13377       macro_build (NULL, "break", "6", 7);
13378
13379       /* FIXME: The normal code checks for of -1 / -0x80000000 here,
13380          since that causes an overflow.  We should do that as well,
13381          but I don't see how to do the comparisons without a temporary
13382          register.  */
13383       end_noreorder ();
13384       macro_build (NULL, s, "x", op[0]);
13385       break;
13386
13387     case M_DIVU_3:
13388       s = "divu";
13389       s2 = "mflo";
13390       goto do_divu3;
13391     case M_REMU_3:
13392       s = "divu";
13393       s2 = "mfhi";
13394       goto do_divu3;
13395     case M_DDIVU_3:
13396       s = "ddivu";
13397       s2 = "mflo";
13398       goto do_divu3;
13399     case M_DREMU_3:
13400       s = "ddivu";
13401       s2 = "mfhi";
13402     do_divu3:
13403       start_noreorder ();
13404       macro_build (NULL, s, "0,x,y", op[1], op[2]);
13405       expr1.X_add_number = 2;
13406       macro_build (&expr1, "bnez", "x,p", op[2]);
13407       macro_build (NULL, "break", "6", 7);
13408       end_noreorder ();
13409       macro_build (NULL, s2, "x", op[0]);
13410       break;
13411
13412     case M_DMUL:
13413       dbl = 1;
13414     case M_MUL:
13415       macro_build (NULL, dbl ? "dmultu" : "multu", "x,y", op[1], op[2]);
13416       macro_build (NULL, "mflo", "x", op[0]);
13417       break;
13418
13419     case M_DSUBU_I:
13420       dbl = 1;
13421       goto do_subu;
13422     case M_SUBU_I:
13423     do_subu:
13424       imm_expr.X_add_number = -imm_expr.X_add_number;
13425       macro_build (&imm_expr, dbl ? "daddiu" : "addiu", "y,x,4", op[0], op[1]);
13426       break;
13427
13428     case M_SUBU_I_2:
13429       imm_expr.X_add_number = -imm_expr.X_add_number;
13430       macro_build (&imm_expr, "addiu", "x,k", op[0]);
13431       break;
13432
13433     case M_DSUBU_I_2:
13434       imm_expr.X_add_number = -imm_expr.X_add_number;
13435       macro_build (&imm_expr, "daddiu", "y,j", op[0]);
13436       break;
13437
13438     case M_BEQ:
13439       s = "cmp";
13440       s2 = "bteqz";
13441       goto do_branch;
13442     case M_BNE:
13443       s = "cmp";
13444       s2 = "btnez";
13445       goto do_branch;
13446     case M_BLT:
13447       s = "slt";
13448       s2 = "btnez";
13449       goto do_branch;
13450     case M_BLTU:
13451       s = "sltu";
13452       s2 = "btnez";
13453       goto do_branch;
13454     case M_BLE:
13455       s = "slt";
13456       s2 = "bteqz";
13457       goto do_reverse_branch;
13458     case M_BLEU:
13459       s = "sltu";
13460       s2 = "bteqz";
13461       goto do_reverse_branch;
13462     case M_BGE:
13463       s = "slt";
13464       s2 = "bteqz";
13465       goto do_branch;
13466     case M_BGEU:
13467       s = "sltu";
13468       s2 = "bteqz";
13469       goto do_branch;
13470     case M_BGT:
13471       s = "slt";
13472       s2 = "btnez";
13473       goto do_reverse_branch;
13474     case M_BGTU:
13475       s = "sltu";
13476       s2 = "btnez";
13477
13478     do_reverse_branch:
13479       tmp = op[1];
13480       op[1] = op[0];
13481       op[0] = tmp;
13482
13483     do_branch:
13484       macro_build (NULL, s, "x,y", op[0], op[1]);
13485       macro_build (&offset_expr, s2, "p");
13486       break;
13487
13488     case M_BEQ_I:
13489       s = "cmpi";
13490       s2 = "bteqz";
13491       s3 = "x,U";
13492       goto do_branch_i;
13493     case M_BNE_I:
13494       s = "cmpi";
13495       s2 = "btnez";
13496       s3 = "x,U";
13497       goto do_branch_i;
13498     case M_BLT_I:
13499       s = "slti";
13500       s2 = "btnez";
13501       s3 = "x,8";
13502       goto do_branch_i;
13503     case M_BLTU_I:
13504       s = "sltiu";
13505       s2 = "btnez";
13506       s3 = "x,8";
13507       goto do_branch_i;
13508     case M_BLE_I:
13509       s = "slti";
13510       s2 = "btnez";
13511       s3 = "x,8";
13512       goto do_addone_branch_i;
13513     case M_BLEU_I:
13514       s = "sltiu";
13515       s2 = "btnez";
13516       s3 = "x,8";
13517       goto do_addone_branch_i;
13518     case M_BGE_I:
13519       s = "slti";
13520       s2 = "bteqz";
13521       s3 = "x,8";
13522       goto do_branch_i;
13523     case M_BGEU_I:
13524       s = "sltiu";
13525       s2 = "bteqz";
13526       s3 = "x,8";
13527       goto do_branch_i;
13528     case M_BGT_I:
13529       s = "slti";
13530       s2 = "bteqz";
13531       s3 = "x,8";
13532       goto do_addone_branch_i;
13533     case M_BGTU_I:
13534       s = "sltiu";
13535       s2 = "bteqz";
13536       s3 = "x,8";
13537
13538     do_addone_branch_i:
13539       ++imm_expr.X_add_number;
13540
13541     do_branch_i:
13542       macro_build (&imm_expr, s, s3, op[0]);
13543       macro_build (&offset_expr, s2, "p");
13544       break;
13545
13546     case M_ABS:
13547       expr1.X_add_number = 0;
13548       macro_build (&expr1, "slti", "x,8", op[1]);
13549       if (op[0] != op[1])
13550         macro_build (NULL, "move", "y,X", op[0], mips16_to_32_reg_map[op[1]]);
13551       expr1.X_add_number = 2;
13552       macro_build (&expr1, "bteqz", "p");
13553       macro_build (NULL, "neg", "x,w", op[0], op[0]);
13554       break;
13555     }
13556 }
13557
13558 /* Look up instruction [START, START + LENGTH) in HASH.  Record any extra
13559    opcode bits in *OPCODE_EXTRA.  */
13560
13561 static struct mips_opcode *
13562 mips_lookup_insn (struct hash_control *hash, const char *start,
13563                   ssize_t length, unsigned int *opcode_extra)
13564 {
13565   char *name, *dot, *p;
13566   unsigned int mask, suffix;
13567   ssize_t opend;
13568   struct mips_opcode *insn;
13569
13570   /* Make a copy of the instruction so that we can fiddle with it.  */
13571   name = xstrndup (start, length);
13572
13573   /* Look up the instruction as-is.  */
13574   insn = (struct mips_opcode *) hash_find (hash, name);
13575   if (insn)
13576     goto end;
13577
13578   dot = strchr (name, '.');
13579   if (dot && dot[1])
13580     {
13581       /* Try to interpret the text after the dot as a VU0 channel suffix.  */
13582       p = mips_parse_vu0_channels (dot + 1, &mask);
13583       if (*p == 0 && mask != 0)
13584         {
13585           *dot = 0;
13586           insn = (struct mips_opcode *) hash_find (hash, name);
13587           *dot = '.';
13588           if (insn && (insn->pinfo2 & INSN2_VU0_CHANNEL_SUFFIX) != 0)
13589             {
13590               *opcode_extra |= mask << mips_vu0_channel_mask.lsb;
13591               goto end;
13592             }
13593         }
13594     }
13595
13596   if (mips_opts.micromips)
13597     {
13598       /* See if there's an instruction size override suffix,
13599          either `16' or `32', at the end of the mnemonic proper,
13600          that defines the operation, i.e. before the first `.'
13601          character if any.  Strip it and retry.  */
13602       opend = dot != NULL ? dot - name : length;
13603       if (opend >= 3 && name[opend - 2] == '1' && name[opend - 1] == '6')
13604         suffix = 2;
13605       else if (name[opend - 2] == '3' && name[opend - 1] == '2')
13606         suffix = 4;
13607       else
13608         suffix = 0;
13609       if (suffix)
13610         {
13611           memcpy (name + opend - 2, name + opend, length - opend + 1);
13612           insn = (struct mips_opcode *) hash_find (hash, name);
13613           if (insn)
13614             {
13615               forced_insn_length = suffix;
13616               goto end;
13617             }
13618         }
13619     }
13620
13621   insn = NULL;
13622  end:
13623   free (name);
13624   return insn;
13625 }
13626
13627 /* Assemble an instruction into its binary format.  If the instruction
13628    is a macro, set imm_expr and offset_expr to the values associated
13629    with "I" and "A" operands respectively.  Otherwise store the value
13630    of the relocatable field (if any) in offset_expr.  In both cases
13631    set offset_reloc to the relocation operators applied to offset_expr.  */
13632
13633 static void
13634 mips_ip (char *str, struct mips_cl_insn *insn)
13635 {
13636   const struct mips_opcode *first, *past;
13637   struct hash_control *hash;
13638   char format;
13639   size_t end;
13640   struct mips_operand_token *tokens;
13641   unsigned int opcode_extra;
13642
13643   if (mips_opts.micromips)
13644     {
13645       hash = micromips_op_hash;
13646       past = &micromips_opcodes[bfd_micromips_num_opcodes];
13647     }
13648   else
13649     {
13650       hash = op_hash;
13651       past = &mips_opcodes[NUMOPCODES];
13652     }
13653   forced_insn_length = 0;
13654   opcode_extra = 0;
13655
13656   /* We first try to match an instruction up to a space or to the end.  */
13657   for (end = 0; str[end] != '\0' && !ISSPACE (str[end]); end++)
13658     continue;
13659
13660   first = mips_lookup_insn (hash, str, end, &opcode_extra);
13661   if (first == NULL)
13662     {
13663       set_insn_error (0, _("unrecognized opcode"));
13664       return;
13665     }
13666
13667   if (strcmp (first->name, "li.s") == 0)
13668     format = 'f';
13669   else if (strcmp (first->name, "li.d") == 0)
13670     format = 'd';
13671   else
13672     format = 0;
13673   tokens = mips_parse_arguments (str + end, format);
13674   if (!tokens)
13675     return;
13676
13677   if (!match_insns (insn, first, past, tokens, opcode_extra, FALSE)
13678       && !match_insns (insn, first, past, tokens, opcode_extra, TRUE))
13679     set_insn_error (0, _("invalid operands"));
13680
13681   obstack_free (&mips_operand_tokens, tokens);
13682 }
13683
13684 /* As for mips_ip, but used when assembling MIPS16 code.
13685    Also set forced_insn_length to the resulting instruction size in
13686    bytes if the user explicitly requested a small or extended instruction.  */
13687
13688 static void
13689 mips16_ip (char *str, struct mips_cl_insn *insn)
13690 {
13691   char *end, *s, c;
13692   struct mips_opcode *first;
13693   struct mips_operand_token *tokens;
13694
13695   forced_insn_length = 0;
13696
13697   for (s = str; ISLOWER (*s); ++s)
13698     ;
13699   end = s;
13700   c = *end;
13701   switch (c)
13702     {
13703     case '\0':
13704       break;
13705
13706     case ' ':
13707       s++;
13708       break;
13709
13710     case '.':
13711       if (s[1] == 't' && s[2] == ' ')
13712         {
13713           forced_insn_length = 2;
13714           s += 3;
13715           break;
13716         }
13717       else if (s[1] == 'e' && s[2] == ' ')
13718         {
13719           forced_insn_length = 4;
13720           s += 3;
13721           break;
13722         }
13723       /* Fall through.  */
13724     default:
13725       set_insn_error (0, _("unrecognized opcode"));
13726       return;
13727     }
13728
13729   if (mips_opts.noautoextend && !forced_insn_length)
13730     forced_insn_length = 2;
13731
13732   *end = 0;
13733   first = (struct mips_opcode *) hash_find (mips16_op_hash, str);
13734   *end = c;
13735
13736   if (!first)
13737     {
13738       set_insn_error (0, _("unrecognized opcode"));
13739       return;
13740     }
13741
13742   tokens = mips_parse_arguments (s, 0);
13743   if (!tokens)
13744     return;
13745
13746   if (!match_mips16_insns (insn, first, tokens))
13747     set_insn_error (0, _("invalid operands"));
13748
13749   obstack_free (&mips_operand_tokens, tokens);
13750 }
13751
13752 /* Marshal immediate value VAL for an extended MIPS16 instruction.
13753    NBITS is the number of significant bits in VAL.  */
13754
13755 static unsigned long
13756 mips16_immed_extend (offsetT val, unsigned int nbits)
13757 {
13758   int extval;
13759   if (nbits == 16)
13760     {
13761       extval = ((val >> 11) & 0x1f) | (val & 0x7e0);
13762       val &= 0x1f;
13763     }
13764   else if (nbits == 15)
13765     {
13766       extval = ((val >> 11) & 0xf) | (val & 0x7f0);
13767       val &= 0xf;
13768     }
13769   else
13770     {
13771       extval = ((val & 0x1f) << 6) | (val & 0x20);
13772       val = 0;
13773     }
13774   return (extval << 16) | val;
13775 }
13776
13777 /* Like decode_mips16_operand, but require the operand to be defined and
13778    require it to be an integer.  */
13779
13780 static const struct mips_int_operand *
13781 mips16_immed_operand (int type, bfd_boolean extended_p)
13782 {
13783   const struct mips_operand *operand;
13784
13785   operand = decode_mips16_operand (type, extended_p);
13786   if (!operand || (operand->type != OP_INT && operand->type != OP_PCREL))
13787     abort ();
13788   return (const struct mips_int_operand *) operand;
13789 }
13790
13791 /* Return true if SVAL fits OPERAND.  RELOC is as for mips16_immed.  */
13792
13793 static bfd_boolean
13794 mips16_immed_in_range_p (const struct mips_int_operand *operand,
13795                          bfd_reloc_code_real_type reloc, offsetT sval)
13796 {
13797   int min_val, max_val;
13798
13799   min_val = mips_int_operand_min (operand);
13800   max_val = mips_int_operand_max (operand);
13801   if (reloc != BFD_RELOC_UNUSED)
13802     {
13803       if (min_val < 0)
13804         sval = SEXT_16BIT (sval);
13805       else
13806         sval &= 0xffff;
13807     }
13808
13809   return (sval >= min_val
13810           && sval <= max_val
13811           && (sval & ((1 << operand->shift) - 1)) == 0);
13812 }
13813
13814 /* Install immediate value VAL into MIPS16 instruction *INSN,
13815    extending it if necessary.  The instruction in *INSN may
13816    already be extended.
13817
13818    RELOC is the relocation that produced VAL, or BFD_RELOC_UNUSED
13819    if none.  In the former case, VAL is a 16-bit number with no
13820    defined signedness.
13821
13822    TYPE is the type of the immediate field.  USER_INSN_LENGTH
13823    is the length that the user requested, or 0 if none.  */
13824
13825 static void
13826 mips16_immed (const char *file, unsigned int line, int type,
13827               bfd_reloc_code_real_type reloc, offsetT val,
13828               unsigned int user_insn_length, unsigned long *insn)
13829 {
13830   const struct mips_int_operand *operand;
13831   unsigned int uval, length;
13832
13833   operand = mips16_immed_operand (type, FALSE);
13834   if (!mips16_immed_in_range_p (operand, reloc, val))
13835     {
13836       /* We need an extended instruction.  */
13837       if (user_insn_length == 2)
13838         as_bad_where (file, line, _("invalid unextended operand value"));
13839       else
13840         *insn |= MIPS16_EXTEND;
13841     }
13842   else if (user_insn_length == 4)
13843     {
13844       /* The operand doesn't force an unextended instruction to be extended.
13845          Warn if the user wanted an extended instruction anyway.  */
13846       *insn |= MIPS16_EXTEND;
13847       as_warn_where (file, line,
13848                      _("extended operand requested but not required"));
13849     }
13850
13851   length = mips16_opcode_length (*insn);
13852   if (length == 4)
13853     {
13854       operand = mips16_immed_operand (type, TRUE);
13855       if (!mips16_immed_in_range_p (operand, reloc, val))
13856         as_bad_where (file, line,
13857                       _("operand value out of range for instruction"));
13858     }
13859   uval = ((unsigned int) val >> operand->shift) - operand->bias;
13860   if (length == 2)
13861     *insn = mips_insert_operand (&operand->root, *insn, uval);
13862   else
13863     *insn |= mips16_immed_extend (uval, operand->root.size);
13864 }
13865 \f
13866 struct percent_op_match
13867 {
13868   const char *str;
13869   bfd_reloc_code_real_type reloc;
13870 };
13871
13872 static const struct percent_op_match mips_percent_op[] =
13873 {
13874   {"%lo", BFD_RELOC_LO16},
13875   {"%call_hi", BFD_RELOC_MIPS_CALL_HI16},
13876   {"%call_lo", BFD_RELOC_MIPS_CALL_LO16},
13877   {"%call16", BFD_RELOC_MIPS_CALL16},
13878   {"%got_disp", BFD_RELOC_MIPS_GOT_DISP},
13879   {"%got_page", BFD_RELOC_MIPS_GOT_PAGE},
13880   {"%got_ofst", BFD_RELOC_MIPS_GOT_OFST},
13881   {"%got_hi", BFD_RELOC_MIPS_GOT_HI16},
13882   {"%got_lo", BFD_RELOC_MIPS_GOT_LO16},
13883   {"%got", BFD_RELOC_MIPS_GOT16},
13884   {"%gp_rel", BFD_RELOC_GPREL16},
13885   {"%half", BFD_RELOC_16},
13886   {"%highest", BFD_RELOC_MIPS_HIGHEST},
13887   {"%higher", BFD_RELOC_MIPS_HIGHER},
13888   {"%neg", BFD_RELOC_MIPS_SUB},
13889   {"%tlsgd", BFD_RELOC_MIPS_TLS_GD},
13890   {"%tlsldm", BFD_RELOC_MIPS_TLS_LDM},
13891   {"%dtprel_hi", BFD_RELOC_MIPS_TLS_DTPREL_HI16},
13892   {"%dtprel_lo", BFD_RELOC_MIPS_TLS_DTPREL_LO16},
13893   {"%tprel_hi", BFD_RELOC_MIPS_TLS_TPREL_HI16},
13894   {"%tprel_lo", BFD_RELOC_MIPS_TLS_TPREL_LO16},
13895   {"%gottprel", BFD_RELOC_MIPS_TLS_GOTTPREL},
13896   {"%hi", BFD_RELOC_HI16_S},
13897   {"%pcrel_hi", BFD_RELOC_HI16_S_PCREL},
13898   {"%pcrel_lo", BFD_RELOC_LO16_PCREL}
13899 };
13900
13901 static const struct percent_op_match mips16_percent_op[] =
13902 {
13903   {"%lo", BFD_RELOC_MIPS16_LO16},
13904   {"%gprel", BFD_RELOC_MIPS16_GPREL},
13905   {"%got", BFD_RELOC_MIPS16_GOT16},
13906   {"%call16", BFD_RELOC_MIPS16_CALL16},
13907   {"%hi", BFD_RELOC_MIPS16_HI16_S},
13908   {"%tlsgd", BFD_RELOC_MIPS16_TLS_GD},
13909   {"%tlsldm", BFD_RELOC_MIPS16_TLS_LDM},
13910   {"%dtprel_hi", BFD_RELOC_MIPS16_TLS_DTPREL_HI16},
13911   {"%dtprel_lo", BFD_RELOC_MIPS16_TLS_DTPREL_LO16},
13912   {"%tprel_hi", BFD_RELOC_MIPS16_TLS_TPREL_HI16},
13913   {"%tprel_lo", BFD_RELOC_MIPS16_TLS_TPREL_LO16},
13914   {"%gottprel", BFD_RELOC_MIPS16_TLS_GOTTPREL}
13915 };
13916
13917
13918 /* Return true if *STR points to a relocation operator.  When returning true,
13919    move *STR over the operator and store its relocation code in *RELOC.
13920    Leave both *STR and *RELOC alone when returning false.  */
13921
13922 static bfd_boolean
13923 parse_relocation (char **str, bfd_reloc_code_real_type *reloc)
13924 {
13925   const struct percent_op_match *percent_op;
13926   size_t limit, i;
13927
13928   if (mips_opts.mips16)
13929     {
13930       percent_op = mips16_percent_op;
13931       limit = ARRAY_SIZE (mips16_percent_op);
13932     }
13933   else
13934     {
13935       percent_op = mips_percent_op;
13936       limit = ARRAY_SIZE (mips_percent_op);
13937     }
13938
13939   for (i = 0; i < limit; i++)
13940     if (strncasecmp (*str, percent_op[i].str, strlen (percent_op[i].str)) == 0)
13941       {
13942         int len = strlen (percent_op[i].str);
13943
13944         if (!ISSPACE ((*str)[len]) && (*str)[len] != '(')
13945           continue;
13946
13947         *str += strlen (percent_op[i].str);
13948         *reloc = percent_op[i].reloc;
13949
13950         /* Check whether the output BFD supports this relocation.
13951            If not, issue an error and fall back on something safe.  */
13952         if (!bfd_reloc_type_lookup (stdoutput, percent_op[i].reloc))
13953           {
13954             as_bad (_("relocation %s isn't supported by the current ABI"),
13955                     percent_op[i].str);
13956             *reloc = BFD_RELOC_UNUSED;
13957           }
13958         return TRUE;
13959       }
13960   return FALSE;
13961 }
13962
13963
13964 /* Parse string STR as a 16-bit relocatable operand.  Store the
13965    expression in *EP and the relocations in the array starting
13966    at RELOC.  Return the number of relocation operators used.
13967
13968    On exit, EXPR_END points to the first character after the expression.  */
13969
13970 static size_t
13971 my_getSmallExpression (expressionS *ep, bfd_reloc_code_real_type *reloc,
13972                        char *str)
13973 {
13974   bfd_reloc_code_real_type reversed_reloc[3];
13975   size_t reloc_index, i;
13976   int crux_depth, str_depth;
13977   char *crux;
13978
13979   /* Search for the start of the main expression, recoding relocations
13980      in REVERSED_RELOC.  End the loop with CRUX pointing to the start
13981      of the main expression and with CRUX_DEPTH containing the number
13982      of open brackets at that point.  */
13983   reloc_index = -1;
13984   str_depth = 0;
13985   do
13986     {
13987       reloc_index++;
13988       crux = str;
13989       crux_depth = str_depth;
13990
13991       /* Skip over whitespace and brackets, keeping count of the number
13992          of brackets.  */
13993       while (*str == ' ' || *str == '\t' || *str == '(')
13994         if (*str++ == '(')
13995           str_depth++;
13996     }
13997   while (*str == '%'
13998          && reloc_index < (HAVE_NEWABI ? 3 : 1)
13999          && parse_relocation (&str, &reversed_reloc[reloc_index]));
14000
14001   my_getExpression (ep, crux);
14002   str = expr_end;
14003
14004   /* Match every open bracket.  */
14005   while (crux_depth > 0 && (*str == ')' || *str == ' ' || *str == '\t'))
14006     if (*str++ == ')')
14007       crux_depth--;
14008
14009   if (crux_depth > 0)
14010     as_bad (_("unclosed '('"));
14011
14012   expr_end = str;
14013
14014   if (reloc_index != 0)
14015     {
14016       prev_reloc_op_frag = frag_now;
14017       for (i = 0; i < reloc_index; i++)
14018         reloc[i] = reversed_reloc[reloc_index - 1 - i];
14019     }
14020
14021   return reloc_index;
14022 }
14023
14024 static void
14025 my_getExpression (expressionS *ep, char *str)
14026 {
14027   char *save_in;
14028
14029   save_in = input_line_pointer;
14030   input_line_pointer = str;
14031   expression (ep);
14032   expr_end = input_line_pointer;
14033   input_line_pointer = save_in;
14034 }
14035
14036 const char *
14037 md_atof (int type, char *litP, int *sizeP)
14038 {
14039   return ieee_md_atof (type, litP, sizeP, target_big_endian);
14040 }
14041
14042 void
14043 md_number_to_chars (char *buf, valueT val, int n)
14044 {
14045   if (target_big_endian)
14046     number_to_chars_bigendian (buf, val, n);
14047   else
14048     number_to_chars_littleendian (buf, val, n);
14049 }
14050 \f
14051 static int support_64bit_objects(void)
14052 {
14053   const char **list, **l;
14054   int yes;
14055
14056   list = bfd_target_list ();
14057   for (l = list; *l != NULL; l++)
14058     if (strcmp (*l, ELF_TARGET ("elf64-", "big")) == 0
14059         || strcmp (*l, ELF_TARGET ("elf64-", "little")) == 0)
14060       break;
14061   yes = (*l != NULL);
14062   free (list);
14063   return yes;
14064 }
14065
14066 /* Set STRING_PTR (either &mips_arch_string or &mips_tune_string) to
14067    NEW_VALUE.  Warn if another value was already specified.  Note:
14068    we have to defer parsing the -march and -mtune arguments in order
14069    to handle 'from-abi' correctly, since the ABI might be specified
14070    in a later argument.  */
14071
14072 static void
14073 mips_set_option_string (const char **string_ptr, const char *new_value)
14074 {
14075   if (*string_ptr != 0 && strcasecmp (*string_ptr, new_value) != 0)
14076     as_warn (_("a different %s was already specified, is now %s"),
14077              string_ptr == &mips_arch_string ? "-march" : "-mtune",
14078              new_value);
14079
14080   *string_ptr = new_value;
14081 }
14082
14083 int
14084 md_parse_option (int c, const char *arg)
14085 {
14086   unsigned int i;
14087
14088   for (i = 0; i < ARRAY_SIZE (mips_ases); i++)
14089     if (c == mips_ases[i].option_on || c == mips_ases[i].option_off)
14090       {
14091         file_ase_explicit |= mips_set_ase (&mips_ases[i], &file_mips_opts,
14092                                            c == mips_ases[i].option_on);
14093         return 1;
14094       }
14095
14096   switch (c)
14097     {
14098     case OPTION_CONSTRUCT_FLOATS:
14099       mips_disable_float_construction = 0;
14100       break;
14101
14102     case OPTION_NO_CONSTRUCT_FLOATS:
14103       mips_disable_float_construction = 1;
14104       break;
14105
14106     case OPTION_TRAP:
14107       mips_trap = 1;
14108       break;
14109
14110     case OPTION_BREAK:
14111       mips_trap = 0;
14112       break;
14113
14114     case OPTION_EB:
14115       target_big_endian = 1;
14116       break;
14117
14118     case OPTION_EL:
14119       target_big_endian = 0;
14120       break;
14121
14122     case 'O':
14123       if (arg == NULL)
14124         mips_optimize = 1;
14125       else if (arg[0] == '0')
14126         mips_optimize = 0;
14127       else if (arg[0] == '1')
14128         mips_optimize = 1;
14129       else
14130         mips_optimize = 2;
14131       break;
14132
14133     case 'g':
14134       if (arg == NULL)
14135         mips_debug = 2;
14136       else
14137         mips_debug = atoi (arg);
14138       break;
14139
14140     case OPTION_MIPS1:
14141       file_mips_opts.isa = ISA_MIPS1;
14142       break;
14143
14144     case OPTION_MIPS2:
14145       file_mips_opts.isa = ISA_MIPS2;
14146       break;
14147
14148     case OPTION_MIPS3:
14149       file_mips_opts.isa = ISA_MIPS3;
14150       break;
14151
14152     case OPTION_MIPS4:
14153       file_mips_opts.isa = ISA_MIPS4;
14154       break;
14155
14156     case OPTION_MIPS5:
14157       file_mips_opts.isa = ISA_MIPS5;
14158       break;
14159
14160     case OPTION_MIPS32:
14161       file_mips_opts.isa = ISA_MIPS32;
14162       break;
14163
14164     case OPTION_MIPS32R2:
14165       file_mips_opts.isa = ISA_MIPS32R2;
14166       break;
14167
14168     case OPTION_MIPS32R3:
14169       file_mips_opts.isa = ISA_MIPS32R3;
14170       break;
14171
14172     case OPTION_MIPS32R5:
14173       file_mips_opts.isa = ISA_MIPS32R5;
14174       break;
14175
14176     case OPTION_MIPS32R6:
14177       file_mips_opts.isa = ISA_MIPS32R6;
14178       break;
14179
14180     case OPTION_MIPS64R2:
14181       file_mips_opts.isa = ISA_MIPS64R2;
14182       break;
14183
14184     case OPTION_MIPS64R3:
14185       file_mips_opts.isa = ISA_MIPS64R3;
14186       break;
14187
14188     case OPTION_MIPS64R5:
14189       file_mips_opts.isa = ISA_MIPS64R5;
14190       break;
14191
14192     case OPTION_MIPS64R6:
14193       file_mips_opts.isa = ISA_MIPS64R6;
14194       break;
14195
14196     case OPTION_MIPS64:
14197       file_mips_opts.isa = ISA_MIPS64;
14198       break;
14199
14200     case OPTION_MTUNE:
14201       mips_set_option_string (&mips_tune_string, arg);
14202       break;
14203
14204     case OPTION_MARCH:
14205       mips_set_option_string (&mips_arch_string, arg);
14206       break;
14207
14208     case OPTION_M4650:
14209       mips_set_option_string (&mips_arch_string, "4650");
14210       mips_set_option_string (&mips_tune_string, "4650");
14211       break;
14212
14213     case OPTION_NO_M4650:
14214       break;
14215
14216     case OPTION_M4010:
14217       mips_set_option_string (&mips_arch_string, "4010");
14218       mips_set_option_string (&mips_tune_string, "4010");
14219       break;
14220
14221     case OPTION_NO_M4010:
14222       break;
14223
14224     case OPTION_M4100:
14225       mips_set_option_string (&mips_arch_string, "4100");
14226       mips_set_option_string (&mips_tune_string, "4100");
14227       break;
14228
14229     case OPTION_NO_M4100:
14230       break;
14231
14232     case OPTION_M3900:
14233       mips_set_option_string (&mips_arch_string, "3900");
14234       mips_set_option_string (&mips_tune_string, "3900");
14235       break;
14236
14237     case OPTION_NO_M3900:
14238       break;
14239
14240     case OPTION_MICROMIPS:
14241       if (file_mips_opts.mips16 == 1)
14242         {
14243           as_bad (_("-mmicromips cannot be used with -mips16"));
14244           return 0;
14245         }
14246       file_mips_opts.micromips = 1;
14247       mips_no_prev_insn ();
14248       break;
14249
14250     case OPTION_NO_MICROMIPS:
14251       file_mips_opts.micromips = 0;
14252       mips_no_prev_insn ();
14253       break;
14254
14255     case OPTION_MIPS16:
14256       if (file_mips_opts.micromips == 1)
14257         {
14258           as_bad (_("-mips16 cannot be used with -micromips"));
14259           return 0;
14260         }
14261       file_mips_opts.mips16 = 1;
14262       mips_no_prev_insn ();
14263       break;
14264
14265     case OPTION_NO_MIPS16:
14266       file_mips_opts.mips16 = 0;
14267       mips_no_prev_insn ();
14268       break;
14269
14270     case OPTION_FIX_24K:
14271       mips_fix_24k = 1;
14272       break;
14273
14274     case OPTION_NO_FIX_24K:
14275       mips_fix_24k = 0;
14276       break;
14277
14278     case OPTION_FIX_RM7000:
14279       mips_fix_rm7000 = 1;
14280       break;
14281
14282     case OPTION_NO_FIX_RM7000:
14283       mips_fix_rm7000 = 0;
14284       break;
14285
14286     case OPTION_FIX_LOONGSON2F_JUMP:
14287       mips_fix_loongson2f_jump = TRUE;
14288       break;
14289
14290     case OPTION_NO_FIX_LOONGSON2F_JUMP:
14291       mips_fix_loongson2f_jump = FALSE;
14292       break;
14293
14294     case OPTION_FIX_LOONGSON2F_NOP:
14295       mips_fix_loongson2f_nop = TRUE;
14296       break;
14297
14298     case OPTION_NO_FIX_LOONGSON2F_NOP:
14299       mips_fix_loongson2f_nop = FALSE;
14300       break;
14301
14302     case OPTION_FIX_VR4120:
14303       mips_fix_vr4120 = 1;
14304       break;
14305
14306     case OPTION_NO_FIX_VR4120:
14307       mips_fix_vr4120 = 0;
14308       break;
14309
14310     case OPTION_FIX_VR4130:
14311       mips_fix_vr4130 = 1;
14312       break;
14313
14314     case OPTION_NO_FIX_VR4130:
14315       mips_fix_vr4130 = 0;
14316       break;
14317
14318     case OPTION_FIX_CN63XXP1:
14319       mips_fix_cn63xxp1 = TRUE;
14320       break;
14321
14322     case OPTION_NO_FIX_CN63XXP1:
14323       mips_fix_cn63xxp1 = FALSE;
14324       break;
14325
14326     case OPTION_RELAX_BRANCH:
14327       mips_relax_branch = 1;
14328       break;
14329
14330     case OPTION_NO_RELAX_BRANCH:
14331       mips_relax_branch = 0;
14332       break;
14333
14334     case OPTION_INSN32:
14335       file_mips_opts.insn32 = TRUE;
14336       break;
14337
14338     case OPTION_NO_INSN32:
14339       file_mips_opts.insn32 = FALSE;
14340       break;
14341
14342     case OPTION_MSHARED:
14343       mips_in_shared = TRUE;
14344       break;
14345
14346     case OPTION_MNO_SHARED:
14347       mips_in_shared = FALSE;
14348       break;
14349
14350     case OPTION_MSYM32:
14351       file_mips_opts.sym32 = TRUE;
14352       break;
14353
14354     case OPTION_MNO_SYM32:
14355       file_mips_opts.sym32 = FALSE;
14356       break;
14357
14358       /* When generating ELF code, we permit -KPIC and -call_shared to
14359          select SVR4_PIC, and -non_shared to select no PIC.  This is
14360          intended to be compatible with Irix 5.  */
14361     case OPTION_CALL_SHARED:
14362       mips_pic = SVR4_PIC;
14363       mips_abicalls = TRUE;
14364       break;
14365
14366     case OPTION_CALL_NONPIC:
14367       mips_pic = NO_PIC;
14368       mips_abicalls = TRUE;
14369       break;
14370
14371     case OPTION_NON_SHARED:
14372       mips_pic = NO_PIC;
14373       mips_abicalls = FALSE;
14374       break;
14375
14376       /* The -xgot option tells the assembler to use 32 bit offsets
14377          when accessing the got in SVR4_PIC mode.  It is for Irix
14378          compatibility.  */
14379     case OPTION_XGOT:
14380       mips_big_got = 1;
14381       break;
14382
14383     case 'G':
14384       g_switch_value = atoi (arg);
14385       g_switch_seen = 1;
14386       break;
14387
14388       /* The -32, -n32 and -64 options are shortcuts for -mabi=32, -mabi=n32
14389          and -mabi=64.  */
14390     case OPTION_32:
14391       mips_abi = O32_ABI;
14392       break;
14393
14394     case OPTION_N32:
14395       mips_abi = N32_ABI;
14396       break;
14397
14398     case OPTION_64:
14399       mips_abi = N64_ABI;
14400       if (!support_64bit_objects())
14401         as_fatal (_("no compiled in support for 64 bit object file format"));
14402       break;
14403
14404     case OPTION_GP32:
14405       file_mips_opts.gp = 32;
14406       break;
14407
14408     case OPTION_GP64:
14409       file_mips_opts.gp = 64;
14410       break;
14411
14412     case OPTION_FP32:
14413       file_mips_opts.fp = 32;
14414       break;
14415
14416     case OPTION_FPXX:
14417       file_mips_opts.fp = 0;
14418       break;
14419
14420     case OPTION_FP64:
14421       file_mips_opts.fp = 64;
14422       break;
14423
14424     case OPTION_ODD_SPREG:
14425       file_mips_opts.oddspreg = 1;
14426       break;
14427
14428     case OPTION_NO_ODD_SPREG:
14429       file_mips_opts.oddspreg = 0;
14430       break;
14431
14432     case OPTION_SINGLE_FLOAT:
14433       file_mips_opts.single_float = 1;
14434       break;
14435
14436     case OPTION_DOUBLE_FLOAT:
14437       file_mips_opts.single_float = 0;
14438       break;
14439
14440     case OPTION_SOFT_FLOAT:
14441       file_mips_opts.soft_float = 1;
14442       break;
14443
14444     case OPTION_HARD_FLOAT:
14445       file_mips_opts.soft_float = 0;
14446       break;
14447
14448     case OPTION_MABI:
14449       if (strcmp (arg, "32") == 0)
14450         mips_abi = O32_ABI;
14451       else if (strcmp (arg, "o64") == 0)
14452         mips_abi = O64_ABI;
14453       else if (strcmp (arg, "n32") == 0)
14454         mips_abi = N32_ABI;
14455       else if (strcmp (arg, "64") == 0)
14456         {
14457           mips_abi = N64_ABI;
14458           if (! support_64bit_objects())
14459             as_fatal (_("no compiled in support for 64 bit object file "
14460                         "format"));
14461         }
14462       else if (strcmp (arg, "eabi") == 0)
14463         mips_abi = EABI_ABI;
14464       else
14465         {
14466           as_fatal (_("invalid abi -mabi=%s"), arg);
14467           return 0;
14468         }
14469       break;
14470
14471     case OPTION_M7000_HILO_FIX:
14472       mips_7000_hilo_fix = TRUE;
14473       break;
14474
14475     case OPTION_MNO_7000_HILO_FIX:
14476       mips_7000_hilo_fix = FALSE;
14477       break;
14478
14479     case OPTION_MDEBUG:
14480       mips_flag_mdebug = TRUE;
14481       break;
14482
14483     case OPTION_NO_MDEBUG:
14484       mips_flag_mdebug = FALSE;
14485       break;
14486
14487     case OPTION_PDR:
14488       mips_flag_pdr = TRUE;
14489       break;
14490
14491     case OPTION_NO_PDR:
14492       mips_flag_pdr = FALSE;
14493       break;
14494
14495     case OPTION_MVXWORKS_PIC:
14496       mips_pic = VXWORKS_PIC;
14497       break;
14498
14499     case OPTION_NAN:
14500       if (strcmp (arg, "2008") == 0)
14501         mips_nan2008 = 1;
14502       else if (strcmp (arg, "legacy") == 0)
14503         mips_nan2008 = 0;
14504       else
14505         {
14506           as_fatal (_("invalid NaN setting -mnan=%s"), arg);
14507           return 0;
14508         }
14509       break;
14510
14511     default:
14512       return 0;
14513     }
14514
14515     mips_fix_loongson2f = mips_fix_loongson2f_nop || mips_fix_loongson2f_jump;
14516
14517   return 1;
14518 }
14519 \f
14520 /* Set up globals to tune for the ISA or processor described by INFO.  */
14521
14522 static void
14523 mips_set_tune (const struct mips_cpu_info *info)
14524 {
14525   if (info != 0)
14526     mips_tune = info->cpu;
14527 }
14528
14529
14530 void
14531 mips_after_parse_args (void)
14532 {
14533   const struct mips_cpu_info *arch_info = 0;
14534   const struct mips_cpu_info *tune_info = 0;
14535
14536   /* GP relative stuff not working for PE */
14537   if (strncmp (TARGET_OS, "pe", 2) == 0)
14538     {
14539       if (g_switch_seen && g_switch_value != 0)
14540         as_bad (_("-G not supported in this configuration"));
14541       g_switch_value = 0;
14542     }
14543
14544   if (mips_abi == NO_ABI)
14545     mips_abi = MIPS_DEFAULT_ABI;
14546
14547   /* The following code determines the architecture.
14548      Similar code was added to GCC 3.3 (see override_options() in
14549      config/mips/mips.c).  The GAS and GCC code should be kept in sync
14550      as much as possible.  */
14551
14552   if (mips_arch_string != 0)
14553     arch_info = mips_parse_cpu ("-march", mips_arch_string);
14554
14555   if (file_mips_opts.isa != ISA_UNKNOWN)
14556     {
14557       /* Handle -mipsN.  At this point, file_mips_opts.isa contains the
14558          ISA level specified by -mipsN, while arch_info->isa contains
14559          the -march selection (if any).  */
14560       if (arch_info != 0)
14561         {
14562           /* -march takes precedence over -mipsN, since it is more descriptive.
14563              There's no harm in specifying both as long as the ISA levels
14564              are the same.  */
14565           if (file_mips_opts.isa != arch_info->isa)
14566             as_bad (_("-%s conflicts with the other architecture options,"
14567                       " which imply -%s"),
14568                     mips_cpu_info_from_isa (file_mips_opts.isa)->name,
14569                     mips_cpu_info_from_isa (arch_info->isa)->name);
14570         }
14571       else
14572         arch_info = mips_cpu_info_from_isa (file_mips_opts.isa);
14573     }
14574
14575   if (arch_info == 0)
14576     {
14577       arch_info = mips_parse_cpu ("default CPU", MIPS_CPU_STRING_DEFAULT);
14578       gas_assert (arch_info);
14579     }
14580
14581   if (ABI_NEEDS_64BIT_REGS (mips_abi) && !ISA_HAS_64BIT_REGS (arch_info->isa))
14582     as_bad (_("-march=%s is not compatible with the selected ABI"),
14583             arch_info->name);
14584
14585   file_mips_opts.arch = arch_info->cpu;
14586   file_mips_opts.isa = arch_info->isa;
14587
14588   /* Set up initial mips_opts state.  */
14589   mips_opts = file_mips_opts;
14590
14591   /* The register size inference code is now placed in
14592      file_mips_check_options.  */
14593
14594   /* Optimize for file_mips_opts.arch, unless -mtune selects a different
14595      processor.  */
14596   if (mips_tune_string != 0)
14597     tune_info = mips_parse_cpu ("-mtune", mips_tune_string);
14598
14599   if (tune_info == 0)
14600     mips_set_tune (arch_info);
14601   else
14602     mips_set_tune (tune_info);
14603
14604   if (mips_flag_mdebug < 0)
14605     mips_flag_mdebug = 0;
14606 }
14607 \f
14608 void
14609 mips_init_after_args (void)
14610 {
14611   /* initialize opcodes */
14612   bfd_mips_num_opcodes = bfd_mips_num_builtin_opcodes;
14613   mips_opcodes = (struct mips_opcode *) mips_builtin_opcodes;
14614 }
14615
14616 long
14617 md_pcrel_from (fixS *fixP)
14618 {
14619   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
14620   switch (fixP->fx_r_type)
14621     {
14622     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14623     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14624       /* Return the address of the delay slot.  */
14625       return addr + 2;
14626
14627     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14628     case BFD_RELOC_MICROMIPS_JMP:
14629     case BFD_RELOC_MIPS16_16_PCREL_S1:
14630     case BFD_RELOC_16_PCREL_S2:
14631     case BFD_RELOC_MIPS_21_PCREL_S2:
14632     case BFD_RELOC_MIPS_26_PCREL_S2:
14633     case BFD_RELOC_MIPS_JMP:
14634       /* Return the address of the delay slot.  */
14635       return addr + 4;
14636
14637     case BFD_RELOC_MIPS_18_PCREL_S3:
14638       /* Return the aligned address of the doubleword containing
14639          the instruction.  */
14640       return addr & ~7;
14641
14642     default:
14643       return addr;
14644     }
14645 }
14646
14647 /* This is called before the symbol table is processed.  In order to
14648    work with gcc when using mips-tfile, we must keep all local labels.
14649    However, in other cases, we want to discard them.  If we were
14650    called with -g, but we didn't see any debugging information, it may
14651    mean that gcc is smuggling debugging information through to
14652    mips-tfile, in which case we must generate all local labels.  */
14653
14654 void
14655 mips_frob_file_before_adjust (void)
14656 {
14657 #ifndef NO_ECOFF_DEBUGGING
14658   if (ECOFF_DEBUGGING
14659       && mips_debug != 0
14660       && ! ecoff_debugging_seen)
14661     flag_keep_locals = 1;
14662 #endif
14663 }
14664
14665 /* Sort any unmatched HI16 and GOT16 relocs so that they immediately precede
14666    the corresponding LO16 reloc.  This is called before md_apply_fix and
14667    tc_gen_reloc.  Unmatched relocs can only be generated by use of explicit
14668    relocation operators.
14669
14670    For our purposes, a %lo() expression matches a %got() or %hi()
14671    expression if:
14672
14673       (a) it refers to the same symbol; and
14674       (b) the offset applied in the %lo() expression is no lower than
14675           the offset applied in the %got() or %hi().
14676
14677    (b) allows us to cope with code like:
14678
14679         lui     $4,%hi(foo)
14680         lh      $4,%lo(foo+2)($4)
14681
14682    ...which is legal on RELA targets, and has a well-defined behaviour
14683    if the user knows that adding 2 to "foo" will not induce a carry to
14684    the high 16 bits.
14685
14686    When several %lo()s match a particular %got() or %hi(), we use the
14687    following rules to distinguish them:
14688
14689      (1) %lo()s with smaller offsets are a better match than %lo()s with
14690          higher offsets.
14691
14692      (2) %lo()s with no matching %got() or %hi() are better than those
14693          that already have a matching %got() or %hi().
14694
14695      (3) later %lo()s are better than earlier %lo()s.
14696
14697    These rules are applied in order.
14698
14699    (1) means, among other things, that %lo()s with identical offsets are
14700    chosen if they exist.
14701
14702    (2) means that we won't associate several high-part relocations with
14703    the same low-part relocation unless there's no alternative.  Having
14704    several high parts for the same low part is a GNU extension; this rule
14705    allows careful users to avoid it.
14706
14707    (3) is purely cosmetic.  mips_hi_fixup_list is is in reverse order,
14708    with the last high-part relocation being at the front of the list.
14709    It therefore makes sense to choose the last matching low-part
14710    relocation, all other things being equal.  It's also easier
14711    to code that way.  */
14712
14713 void
14714 mips_frob_file (void)
14715 {
14716   struct mips_hi_fixup *l;
14717   bfd_reloc_code_real_type looking_for_rtype = BFD_RELOC_UNUSED;
14718
14719   for (l = mips_hi_fixup_list; l != NULL; l = l->next)
14720     {
14721       segment_info_type *seginfo;
14722       bfd_boolean matched_lo_p;
14723       fixS **hi_pos, **lo_pos, **pos;
14724
14725       gas_assert (reloc_needs_lo_p (l->fixp->fx_r_type));
14726
14727       /* If a GOT16 relocation turns out to be against a global symbol,
14728          there isn't supposed to be a matching LO.  Ignore %gots against
14729          constants; we'll report an error for those later.  */
14730       if (got16_reloc_p (l->fixp->fx_r_type)
14731           && !(l->fixp->fx_addsy
14732                && pic_need_relax (l->fixp->fx_addsy, l->seg)))
14733         continue;
14734
14735       /* Check quickly whether the next fixup happens to be a matching %lo.  */
14736       if (fixup_has_matching_lo_p (l->fixp))
14737         continue;
14738
14739       seginfo = seg_info (l->seg);
14740
14741       /* Set HI_POS to the position of this relocation in the chain.
14742          Set LO_POS to the position of the chosen low-part relocation.
14743          MATCHED_LO_P is true on entry to the loop if *POS is a low-part
14744          relocation that matches an immediately-preceding high-part
14745          relocation.  */
14746       hi_pos = NULL;
14747       lo_pos = NULL;
14748       matched_lo_p = FALSE;
14749       looking_for_rtype = matching_lo_reloc (l->fixp->fx_r_type);
14750
14751       for (pos = &seginfo->fix_root; *pos != NULL; pos = &(*pos)->fx_next)
14752         {
14753           if (*pos == l->fixp)
14754             hi_pos = pos;
14755
14756           if ((*pos)->fx_r_type == looking_for_rtype
14757               && symbol_same_p ((*pos)->fx_addsy, l->fixp->fx_addsy)
14758               && (*pos)->fx_offset >= l->fixp->fx_offset
14759               && (lo_pos == NULL
14760                   || (*pos)->fx_offset < (*lo_pos)->fx_offset
14761                   || (!matched_lo_p
14762                       && (*pos)->fx_offset == (*lo_pos)->fx_offset)))
14763             lo_pos = pos;
14764
14765           matched_lo_p = (reloc_needs_lo_p ((*pos)->fx_r_type)
14766                           && fixup_has_matching_lo_p (*pos));
14767         }
14768
14769       /* If we found a match, remove the high-part relocation from its
14770          current position and insert it before the low-part relocation.
14771          Make the offsets match so that fixup_has_matching_lo_p()
14772          will return true.
14773
14774          We don't warn about unmatched high-part relocations since some
14775          versions of gcc have been known to emit dead "lui ...%hi(...)"
14776          instructions.  */
14777       if (lo_pos != NULL)
14778         {
14779           l->fixp->fx_offset = (*lo_pos)->fx_offset;
14780           if (l->fixp->fx_next != *lo_pos)
14781             {
14782               *hi_pos = l->fixp->fx_next;
14783               l->fixp->fx_next = *lo_pos;
14784               *lo_pos = l->fixp;
14785             }
14786         }
14787     }
14788 }
14789
14790 int
14791 mips_force_relocation (fixS *fixp)
14792 {
14793   if (generic_force_reloc (fixp))
14794     return 1;
14795
14796   /* We want to keep BFD_RELOC_MICROMIPS_*_PCREL_S1 relocation,
14797      so that the linker relaxation can update targets.  */
14798   if (fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
14799       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
14800       || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1)
14801     return 1;
14802
14803   /* We want to keep R_MIPS_PC26_S2, R_MIPS_PC21_S2, BFD_RELOC_16_PCREL_S2
14804      BFD_RELOC_MIPS_21_PCREL_S2 and BFD_RELOC_MIPS_26_PCREL_S2 relocations
14805      against MIPS16 and microMIPS symbols so that we do cross-mode branch
14806      diagnostics.  */
14807   if ((fixp->fx_r_type == R_MIPS_PC26_S2
14808        || fixp->fx_r_type == R_MIPS_PC21_S2
14809        || fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
14810        || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
14811        || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2)
14812       && fixp->fx_addsy
14813       && ELF_ST_IS_COMPRESSED (S_GET_OTHER (fixp->fx_addsy)))
14814     return 1;
14815
14816   /* We want all PC-relative relocations to be kept for R6 relaxation.  */
14817   if (ISA_IS_R6 (file_mips_opts.isa)
14818       && (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
14819           || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
14820           || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
14821           || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
14822           || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
14823           || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
14824           || fixp->fx_r_type == BFD_RELOC_LO16_PCREL))
14825     return 1;
14826
14827   return 0;
14828 }
14829
14830 /* Implement TC_FORCE_RELOCATION_ABS.  */
14831
14832 bfd_boolean
14833 mips_force_relocation_abs (fixS *fixp)
14834 {
14835   if (generic_force_reloc (fixp))
14836     return TRUE;
14837
14838   /* These relocations do not have enough bits in the in-place addend
14839      to hold an arbitrary absolute section's offset.  */
14840   if (HAVE_IN_PLACE_ADDENDS && limited_pcrel_reloc_p (fixp->fx_r_type))
14841     return TRUE;
14842
14843   return FALSE;
14844 }
14845
14846 /* Read the instruction associated with RELOC from BUF.  */
14847
14848 static unsigned int
14849 read_reloc_insn (char *buf, bfd_reloc_code_real_type reloc)
14850 {
14851   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14852     return read_compressed_insn (buf, 4);
14853   else
14854     return read_insn (buf);
14855 }
14856
14857 /* Write instruction INSN to BUF, given that it has been relocated
14858    by RELOC.  */
14859
14860 static void
14861 write_reloc_insn (char *buf, bfd_reloc_code_real_type reloc,
14862                   unsigned long insn)
14863 {
14864   if (mips16_reloc_p (reloc) || micromips_reloc_p (reloc))
14865     write_compressed_insn (buf, insn, 4);
14866   else
14867     write_insn (buf, insn);
14868 }
14869
14870 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
14871    to a symbol in another ISA mode, which cannot be converted to JALX.  */
14872
14873 static bfd_boolean
14874 fix_bad_cross_mode_jump_p (fixS *fixP)
14875 {
14876   unsigned long opcode;
14877   int other;
14878   char *buf;
14879
14880   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
14881     return FALSE;
14882
14883   other = S_GET_OTHER (fixP->fx_addsy);
14884   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14885   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
14886   switch (fixP->fx_r_type)
14887     {
14888     case BFD_RELOC_MIPS_JMP:
14889       return opcode != 0x1d && opcode != 0x03 && ELF_ST_IS_COMPRESSED (other);
14890     case BFD_RELOC_MICROMIPS_JMP:
14891       return opcode != 0x3c && opcode != 0x3d && !ELF_ST_IS_MICROMIPS (other);
14892     default:
14893       return FALSE;
14894     }
14895 }
14896
14897 /* Return TRUE if the instruction pointed to by FIXP is an invalid JALX
14898    jump to a symbol in the same ISA mode.  */
14899
14900 static bfd_boolean
14901 fix_bad_same_mode_jalx_p (fixS *fixP)
14902 {
14903   unsigned long opcode;
14904   int other;
14905   char *buf;
14906
14907   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
14908     return FALSE;
14909
14910   other = S_GET_OTHER (fixP->fx_addsy);
14911   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14912   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 26;
14913   switch (fixP->fx_r_type)
14914     {
14915     case BFD_RELOC_MIPS_JMP:
14916       return opcode == 0x1d && !ELF_ST_IS_COMPRESSED (other);
14917     case BFD_RELOC_MIPS16_JMP:
14918       return opcode == 0x07 && ELF_ST_IS_COMPRESSED (other);
14919     case BFD_RELOC_MICROMIPS_JMP:
14920       return opcode == 0x3c && ELF_ST_IS_COMPRESSED (other);
14921     default:
14922       return FALSE;
14923     }
14924 }
14925
14926 /* Return TRUE if the instruction pointed to by FIXP is an invalid jump
14927    to a symbol whose value plus addend is not aligned according to the
14928    ultimate (after linker relaxation) jump instruction's immediate field
14929    requirement, either to (1 << SHIFT), or, for jumps from microMIPS to
14930    regular MIPS code, to (1 << 2).  */
14931
14932 static bfd_boolean
14933 fix_bad_misaligned_jump_p (fixS *fixP, int shift)
14934 {
14935   bfd_boolean micro_to_mips_p;
14936   valueT val;
14937   int other;
14938
14939   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
14940     return FALSE;
14941
14942   other = S_GET_OTHER (fixP->fx_addsy);
14943   val = S_GET_VALUE (fixP->fx_addsy) | ELF_ST_IS_COMPRESSED (other);
14944   val += fixP->fx_offset;
14945   micro_to_mips_p = (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
14946                      && !ELF_ST_IS_MICROMIPS (other));
14947   return ((val & ((1 << (micro_to_mips_p ? 2 : shift)) - 1))
14948           != ELF_ST_IS_COMPRESSED (other));
14949 }
14950
14951 /* Return TRUE if the instruction pointed to by FIXP is an invalid branch
14952    to a symbol whose annotation indicates another ISA mode.  For absolute
14953    symbols check the ISA bit instead.  */
14954
14955 static bfd_boolean
14956 fix_bad_cross_mode_branch_p (fixS *fixP)
14957 {
14958   bfd_boolean absolute_p;
14959   unsigned long opcode;
14960   asection *symsec;
14961   valueT val;
14962   int other;
14963   char *buf;
14964
14965   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
14966     return FALSE;
14967
14968   symsec = S_GET_SEGMENT (fixP->fx_addsy);
14969   absolute_p = bfd_is_abs_section (symsec);
14970
14971   val = S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset;
14972   other = S_GET_OTHER (fixP->fx_addsy);
14973
14974   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
14975   opcode = read_reloc_insn (buf, fixP->fx_r_type) >> 16;
14976   switch (fixP->fx_r_type)
14977     {
14978     case BFD_RELOC_16_PCREL_S2:
14979     case BFD_RELOC_MIPS_21_PCREL_S2:
14980     case BFD_RELOC_MIPS_26_PCREL_S2:
14981       return absolute_p ? val & 1 : ELF_ST_IS_COMPRESSED (other);
14982     case BFD_RELOC_MIPS16_16_PCREL_S1:
14983       return absolute_p ? !(val & 1) : !ELF_ST_IS_MIPS16 (other);
14984     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
14985     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
14986     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
14987       return absolute_p ? !(val & 1) : !ELF_ST_IS_MICROMIPS (other);
14988     default:
14989       abort ();
14990     }
14991 }
14992
14993 /* Return TRUE if the symbol plus addend associated with a regular MIPS
14994    branch instruction pointed to by FIXP is not aligned according to the
14995    branch instruction's immediate field requirement.  We need the addend
14996    to preserve the ISA bit and also the sum must not have bit 2 set.  We
14997    must explicitly OR in the ISA bit from symbol annotation as the bit
14998    won't be set in the symbol's value then.  */
14999
15000 static bfd_boolean
15001 fix_bad_misaligned_branch_p (fixS *fixP)
15002 {
15003   bfd_boolean absolute_p;
15004   asection *symsec;
15005   valueT isa_bit;
15006   valueT val;
15007   valueT off;
15008   int other;
15009
15010   if (!fixP->fx_addsy || S_FORCE_RELOC (fixP->fx_addsy, TRUE))
15011     return FALSE;
15012
15013   symsec = S_GET_SEGMENT (fixP->fx_addsy);
15014   absolute_p = bfd_is_abs_section (symsec);
15015
15016   val = S_GET_VALUE (fixP->fx_addsy);
15017   other = S_GET_OTHER (fixP->fx_addsy);
15018   off = fixP->fx_offset;
15019
15020   isa_bit = absolute_p ? (val + off) & 1 : ELF_ST_IS_COMPRESSED (other);
15021   val |= ELF_ST_IS_COMPRESSED (other);
15022   val += off;
15023   return (val & 0x3) != isa_bit;
15024 }
15025
15026 /* Make the necessary checks on a regular MIPS branch pointed to by FIXP
15027    and its calculated value VAL.  */
15028
15029 static void
15030 fix_validate_branch (fixS *fixP, valueT val)
15031 {
15032   if (fixP->fx_done && (val & 0x3) != 0)
15033     as_bad_where (fixP->fx_file, fixP->fx_line,
15034                   _("branch to misaligned address (0x%lx)"),
15035                   (long) (val + md_pcrel_from (fixP)));
15036   else if (fix_bad_cross_mode_branch_p (fixP))
15037     as_bad_where (fixP->fx_file, fixP->fx_line,
15038                   _("branch to a symbol in another ISA mode"));
15039   else if (fix_bad_misaligned_branch_p (fixP))
15040     as_bad_where (fixP->fx_file, fixP->fx_line,
15041                   _("branch to misaligned address (0x%lx)"),
15042                   (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15043   else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x3) != 0)
15044     as_bad_where (fixP->fx_file, fixP->fx_line,
15045                   _("cannot encode misaligned addend "
15046                     "in the relocatable field (0x%lx)"),
15047                   (long) fixP->fx_offset);
15048 }
15049
15050 /* Apply a fixup to the object file.  */
15051
15052 void
15053 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
15054 {
15055   char *buf;
15056   unsigned long insn;
15057   reloc_howto_type *howto;
15058
15059   if (fixP->fx_pcrel)
15060     switch (fixP->fx_r_type)
15061       {
15062       case BFD_RELOC_16_PCREL_S2:
15063       case BFD_RELOC_MIPS16_16_PCREL_S1:
15064       case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15065       case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15066       case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15067       case BFD_RELOC_32_PCREL:
15068       case BFD_RELOC_MIPS_21_PCREL_S2:
15069       case BFD_RELOC_MIPS_26_PCREL_S2:
15070       case BFD_RELOC_MIPS_18_PCREL_S3:
15071       case BFD_RELOC_MIPS_19_PCREL_S2:
15072       case BFD_RELOC_HI16_S_PCREL:
15073       case BFD_RELOC_LO16_PCREL:
15074         break;
15075
15076       case BFD_RELOC_32:
15077         fixP->fx_r_type = BFD_RELOC_32_PCREL;
15078         break;
15079
15080       default:
15081         as_bad_where (fixP->fx_file, fixP->fx_line,
15082                       _("PC-relative reference to a different section"));
15083         break;
15084       }
15085
15086   /* Handle BFD_RELOC_8, since it's easy.  Punt on other bfd relocations
15087      that have no MIPS ELF equivalent.  */
15088   if (fixP->fx_r_type != BFD_RELOC_8)
15089     {
15090       howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
15091       if (!howto)
15092         return;
15093     }
15094
15095   gas_assert (fixP->fx_size == 2
15096               || fixP->fx_size == 4
15097               || fixP->fx_r_type == BFD_RELOC_8
15098               || fixP->fx_r_type == BFD_RELOC_16
15099               || fixP->fx_r_type == BFD_RELOC_64
15100               || fixP->fx_r_type == BFD_RELOC_CTOR
15101               || fixP->fx_r_type == BFD_RELOC_MIPS_SUB
15102               || fixP->fx_r_type == BFD_RELOC_MICROMIPS_SUB
15103               || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
15104               || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
15105               || fixP->fx_r_type == BFD_RELOC_MIPS_TLS_DTPREL64
15106               || fixP->fx_r_type == BFD_RELOC_NONE);
15107
15108   buf = fixP->fx_frag->fr_literal + fixP->fx_where;
15109
15110   /* Don't treat parts of a composite relocation as done.  There are two
15111      reasons for this:
15112
15113      (1) The second and third parts will be against 0 (RSS_UNDEF) but
15114          should nevertheless be emitted if the first part is.
15115
15116      (2) In normal usage, composite relocations are never assembly-time
15117          constants.  The easiest way of dealing with the pathological
15118          exceptions is to generate a relocation against STN_UNDEF and
15119          leave everything up to the linker.  */
15120   if (fixP->fx_addsy == NULL && !fixP->fx_pcrel && fixP->fx_tcbit == 0)
15121     fixP->fx_done = 1;
15122
15123   switch (fixP->fx_r_type)
15124     {
15125     case BFD_RELOC_MIPS_TLS_GD:
15126     case BFD_RELOC_MIPS_TLS_LDM:
15127     case BFD_RELOC_MIPS_TLS_DTPREL32:
15128     case BFD_RELOC_MIPS_TLS_DTPREL64:
15129     case BFD_RELOC_MIPS_TLS_DTPREL_HI16:
15130     case BFD_RELOC_MIPS_TLS_DTPREL_LO16:
15131     case BFD_RELOC_MIPS_TLS_GOTTPREL:
15132     case BFD_RELOC_MIPS_TLS_TPREL32:
15133     case BFD_RELOC_MIPS_TLS_TPREL64:
15134     case BFD_RELOC_MIPS_TLS_TPREL_HI16:
15135     case BFD_RELOC_MIPS_TLS_TPREL_LO16:
15136     case BFD_RELOC_MICROMIPS_TLS_GD:
15137     case BFD_RELOC_MICROMIPS_TLS_LDM:
15138     case BFD_RELOC_MICROMIPS_TLS_DTPREL_HI16:
15139     case BFD_RELOC_MICROMIPS_TLS_DTPREL_LO16:
15140     case BFD_RELOC_MICROMIPS_TLS_GOTTPREL:
15141     case BFD_RELOC_MICROMIPS_TLS_TPREL_HI16:
15142     case BFD_RELOC_MICROMIPS_TLS_TPREL_LO16:
15143     case BFD_RELOC_MIPS16_TLS_GD:
15144     case BFD_RELOC_MIPS16_TLS_LDM:
15145     case BFD_RELOC_MIPS16_TLS_DTPREL_HI16:
15146     case BFD_RELOC_MIPS16_TLS_DTPREL_LO16:
15147     case BFD_RELOC_MIPS16_TLS_GOTTPREL:
15148     case BFD_RELOC_MIPS16_TLS_TPREL_HI16:
15149     case BFD_RELOC_MIPS16_TLS_TPREL_LO16:
15150       if (fixP->fx_addsy)
15151         S_SET_THREAD_LOCAL (fixP->fx_addsy);
15152       else
15153         as_bad_where (fixP->fx_file, fixP->fx_line,
15154                       _("TLS relocation against a constant"));
15155       break;
15156
15157     case BFD_RELOC_MIPS_JMP:
15158     case BFD_RELOC_MIPS16_JMP:
15159     case BFD_RELOC_MICROMIPS_JMP:
15160       {
15161         int shift;
15162
15163         gas_assert (!fixP->fx_done);
15164
15165         /* Shift is 2, unusually, for microMIPS JALX.  */
15166         if (fixP->fx_r_type == BFD_RELOC_MICROMIPS_JMP
15167             && (read_compressed_insn (buf, 4) >> 26) != 0x3c)
15168           shift = 1;
15169         else
15170           shift = 2;
15171
15172         if (fix_bad_cross_mode_jump_p (fixP))
15173           as_bad_where (fixP->fx_file, fixP->fx_line,
15174                         _("jump to a symbol in another ISA mode"));
15175         else if (fix_bad_same_mode_jalx_p (fixP))
15176           as_bad_where (fixP->fx_file, fixP->fx_line,
15177                         _("JALX to a symbol in the same ISA mode"));
15178         else if (fix_bad_misaligned_jump_p (fixP, shift))
15179           as_bad_where (fixP->fx_file, fixP->fx_line,
15180                         _("jump to misaligned address (0x%lx)"),
15181                         (long) (S_GET_VALUE (fixP->fx_addsy)
15182                                 + fixP->fx_offset));
15183         else if (HAVE_IN_PLACE_ADDENDS
15184                  && (fixP->fx_offset & ((1 << shift) - 1)) != 0)
15185           as_bad_where (fixP->fx_file, fixP->fx_line,
15186                         _("cannot encode misaligned addend "
15187                           "in the relocatable field (0x%lx)"),
15188                         (long) fixP->fx_offset);
15189       }
15190       /* Fall through.  */
15191
15192     case BFD_RELOC_MIPS_SHIFT5:
15193     case BFD_RELOC_MIPS_SHIFT6:
15194     case BFD_RELOC_MIPS_GOT_DISP:
15195     case BFD_RELOC_MIPS_GOT_PAGE:
15196     case BFD_RELOC_MIPS_GOT_OFST:
15197     case BFD_RELOC_MIPS_SUB:
15198     case BFD_RELOC_MIPS_INSERT_A:
15199     case BFD_RELOC_MIPS_INSERT_B:
15200     case BFD_RELOC_MIPS_DELETE:
15201     case BFD_RELOC_MIPS_HIGHEST:
15202     case BFD_RELOC_MIPS_HIGHER:
15203     case BFD_RELOC_MIPS_SCN_DISP:
15204     case BFD_RELOC_MIPS_REL16:
15205     case BFD_RELOC_MIPS_RELGOT:
15206     case BFD_RELOC_MIPS_JALR:
15207     case BFD_RELOC_HI16:
15208     case BFD_RELOC_HI16_S:
15209     case BFD_RELOC_LO16:
15210     case BFD_RELOC_GPREL16:
15211     case BFD_RELOC_MIPS_LITERAL:
15212     case BFD_RELOC_MIPS_CALL16:
15213     case BFD_RELOC_MIPS_GOT16:
15214     case BFD_RELOC_GPREL32:
15215     case BFD_RELOC_MIPS_GOT_HI16:
15216     case BFD_RELOC_MIPS_GOT_LO16:
15217     case BFD_RELOC_MIPS_CALL_HI16:
15218     case BFD_RELOC_MIPS_CALL_LO16:
15219     case BFD_RELOC_HI16_S_PCREL:
15220     case BFD_RELOC_LO16_PCREL:
15221     case BFD_RELOC_MIPS16_GPREL:
15222     case BFD_RELOC_MIPS16_GOT16:
15223     case BFD_RELOC_MIPS16_CALL16:
15224     case BFD_RELOC_MIPS16_HI16:
15225     case BFD_RELOC_MIPS16_HI16_S:
15226     case BFD_RELOC_MIPS16_LO16:
15227     case BFD_RELOC_MICROMIPS_GOT_DISP:
15228     case BFD_RELOC_MICROMIPS_GOT_PAGE:
15229     case BFD_RELOC_MICROMIPS_GOT_OFST:
15230     case BFD_RELOC_MICROMIPS_SUB:
15231     case BFD_RELOC_MICROMIPS_HIGHEST:
15232     case BFD_RELOC_MICROMIPS_HIGHER:
15233     case BFD_RELOC_MICROMIPS_SCN_DISP:
15234     case BFD_RELOC_MICROMIPS_JALR:
15235     case BFD_RELOC_MICROMIPS_HI16:
15236     case BFD_RELOC_MICROMIPS_HI16_S:
15237     case BFD_RELOC_MICROMIPS_LO16:
15238     case BFD_RELOC_MICROMIPS_GPREL16:
15239     case BFD_RELOC_MICROMIPS_LITERAL:
15240     case BFD_RELOC_MICROMIPS_CALL16:
15241     case BFD_RELOC_MICROMIPS_GOT16:
15242     case BFD_RELOC_MICROMIPS_GOT_HI16:
15243     case BFD_RELOC_MICROMIPS_GOT_LO16:
15244     case BFD_RELOC_MICROMIPS_CALL_HI16:
15245     case BFD_RELOC_MICROMIPS_CALL_LO16:
15246     case BFD_RELOC_MIPS_EH:
15247       if (fixP->fx_done)
15248         {
15249           offsetT value;
15250
15251           if (calculate_reloc (fixP->fx_r_type, *valP, &value))
15252             {
15253               insn = read_reloc_insn (buf, fixP->fx_r_type);
15254               if (mips16_reloc_p (fixP->fx_r_type))
15255                 insn |= mips16_immed_extend (value, 16);
15256               else
15257                 insn |= (value & 0xffff);
15258               write_reloc_insn (buf, fixP->fx_r_type, insn);
15259             }
15260           else
15261             as_bad_where (fixP->fx_file, fixP->fx_line,
15262                           _("unsupported constant in relocation"));
15263         }
15264       break;
15265
15266     case BFD_RELOC_64:
15267       /* This is handled like BFD_RELOC_32, but we output a sign
15268          extended value if we are only 32 bits.  */
15269       if (fixP->fx_done)
15270         {
15271           if (8 <= sizeof (valueT))
15272             md_number_to_chars (buf, *valP, 8);
15273           else
15274             {
15275               valueT hiv;
15276
15277               if ((*valP & 0x80000000) != 0)
15278                 hiv = 0xffffffff;
15279               else
15280                 hiv = 0;
15281               md_number_to_chars (buf + (target_big_endian ? 4 : 0), *valP, 4);
15282               md_number_to_chars (buf + (target_big_endian ? 0 : 4), hiv, 4);
15283             }
15284         }
15285       break;
15286
15287     case BFD_RELOC_RVA:
15288     case BFD_RELOC_32:
15289     case BFD_RELOC_32_PCREL:
15290     case BFD_RELOC_16:
15291     case BFD_RELOC_8:
15292       /* If we are deleting this reloc entry, we must fill in the
15293          value now.  This can happen if we have a .word which is not
15294          resolved when it appears but is later defined.  */
15295       if (fixP->fx_done)
15296         md_number_to_chars (buf, *valP, fixP->fx_size);
15297       break;
15298
15299     case BFD_RELOC_MIPS_21_PCREL_S2:
15300       fix_validate_branch (fixP, *valP);
15301       if (!fixP->fx_done)
15302         break;
15303
15304       if (*valP + 0x400000 <= 0x7fffff)
15305         {
15306           insn = read_insn (buf);
15307           insn |= (*valP >> 2) & 0x1fffff;
15308           write_insn (buf, insn);
15309         }
15310       else
15311         as_bad_where (fixP->fx_file, fixP->fx_line,
15312                       _("branch out of range"));
15313       break;
15314
15315     case BFD_RELOC_MIPS_26_PCREL_S2:
15316       fix_validate_branch (fixP, *valP);
15317       if (!fixP->fx_done)
15318         break;
15319
15320       if (*valP + 0x8000000 <= 0xfffffff)
15321         {
15322           insn = read_insn (buf);
15323           insn |= (*valP >> 2) & 0x3ffffff;
15324           write_insn (buf, insn);
15325         }
15326       else
15327         as_bad_where (fixP->fx_file, fixP->fx_line,
15328                       _("branch out of range"));
15329       break;
15330
15331     case BFD_RELOC_MIPS_18_PCREL_S3:
15332       if (fixP->fx_addsy && (S_GET_VALUE (fixP->fx_addsy) & 0x7) != 0)
15333         as_bad_where (fixP->fx_file, fixP->fx_line,
15334                       _("PC-relative access using misaligned symbol (%lx)"),
15335                       (long) S_GET_VALUE (fixP->fx_addsy));
15336       if ((fixP->fx_offset & 0x7) != 0)
15337         as_bad_where (fixP->fx_file, fixP->fx_line,
15338                       _("PC-relative access using misaligned offset (%lx)"),
15339                       (long) fixP->fx_offset);
15340       if (!fixP->fx_done)
15341         break;
15342
15343       if (*valP + 0x100000 <= 0x1fffff)
15344         {
15345           insn = read_insn (buf);
15346           insn |= (*valP >> 3) & 0x3ffff;
15347           write_insn (buf, insn);
15348         }
15349       else
15350         as_bad_where (fixP->fx_file, fixP->fx_line,
15351                       _("PC-relative access out of range"));
15352       break;
15353
15354     case BFD_RELOC_MIPS_19_PCREL_S2:
15355       if ((*valP & 0x3) != 0)
15356         as_bad_where (fixP->fx_file, fixP->fx_line,
15357                       _("PC-relative access to misaligned address (%lx)"),
15358                       (long) *valP);
15359       if (!fixP->fx_done)
15360         break;
15361
15362       if (*valP + 0x100000 <= 0x1fffff)
15363         {
15364           insn = read_insn (buf);
15365           insn |= (*valP >> 2) & 0x7ffff;
15366           write_insn (buf, insn);
15367         }
15368       else
15369         as_bad_where (fixP->fx_file, fixP->fx_line,
15370                       _("PC-relative access out of range"));
15371       break;
15372
15373     case BFD_RELOC_16_PCREL_S2:
15374       fix_validate_branch (fixP, *valP);
15375
15376       /* We need to save the bits in the instruction since fixup_segment()
15377          might be deleting the relocation entry (i.e., a branch within
15378          the current segment).  */
15379       if (! fixP->fx_done)
15380         break;
15381
15382       /* Update old instruction data.  */
15383       insn = read_insn (buf);
15384
15385       if (*valP + 0x20000 <= 0x3ffff)
15386         {
15387           insn |= (*valP >> 2) & 0xffff;
15388           write_insn (buf, insn);
15389         }
15390       else if (mips_pic == NO_PIC
15391                && fixP->fx_done
15392                && fixP->fx_frag->fr_address >= text_section->vma
15393                && (fixP->fx_frag->fr_address
15394                    < text_section->vma + bfd_get_section_size (text_section))
15395                && ((insn & 0xffff0000) == 0x10000000     /* beq $0,$0 */
15396                    || (insn & 0xffff0000) == 0x04010000  /* bgez $0 */
15397                    || (insn & 0xffff0000) == 0x04110000)) /* bgezal $0 */
15398         {
15399           /* The branch offset is too large.  If this is an
15400              unconditional branch, and we are not generating PIC code,
15401              we can convert it to an absolute jump instruction.  */
15402           if ((insn & 0xffff0000) == 0x04110000)         /* bgezal $0 */
15403             insn = 0x0c000000;  /* jal */
15404           else
15405             insn = 0x08000000;  /* j */
15406           fixP->fx_r_type = BFD_RELOC_MIPS_JMP;
15407           fixP->fx_done = 0;
15408           fixP->fx_addsy = section_symbol (text_section);
15409           *valP += md_pcrel_from (fixP);
15410           write_insn (buf, insn);
15411         }
15412       else
15413         {
15414           /* If we got here, we have branch-relaxation disabled,
15415              and there's nothing we can do to fix this instruction
15416              without turning it into a longer sequence.  */
15417           as_bad_where (fixP->fx_file, fixP->fx_line,
15418                         _("branch out of range"));
15419         }
15420       break;
15421
15422     case BFD_RELOC_MIPS16_16_PCREL_S1:
15423     case BFD_RELOC_MICROMIPS_7_PCREL_S1:
15424     case BFD_RELOC_MICROMIPS_10_PCREL_S1:
15425     case BFD_RELOC_MICROMIPS_16_PCREL_S1:
15426       gas_assert (!fixP->fx_done);
15427       if (fix_bad_cross_mode_branch_p (fixP))
15428         as_bad_where (fixP->fx_file, fixP->fx_line,
15429                       _("branch to a symbol in another ISA mode"));
15430       else if (fixP->fx_addsy
15431                && !S_FORCE_RELOC (fixP->fx_addsy, TRUE)
15432                && !bfd_is_abs_section (S_GET_SEGMENT (fixP->fx_addsy))
15433                && (fixP->fx_offset & 0x1) != 0)
15434         as_bad_where (fixP->fx_file, fixP->fx_line,
15435                       _("branch to misaligned address (0x%lx)"),
15436                       (long) (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset));
15437       else if (HAVE_IN_PLACE_ADDENDS && (fixP->fx_offset & 0x1) != 0)
15438         as_bad_where (fixP->fx_file, fixP->fx_line,
15439                       _("cannot encode misaligned addend "
15440                         "in the relocatable field (0x%lx)"),
15441                       (long) fixP->fx_offset);
15442       break;
15443
15444     case BFD_RELOC_VTABLE_INHERIT:
15445       fixP->fx_done = 0;
15446       if (fixP->fx_addsy
15447           && !S_IS_DEFINED (fixP->fx_addsy)
15448           && !S_IS_WEAK (fixP->fx_addsy))
15449         S_SET_WEAK (fixP->fx_addsy);
15450       break;
15451
15452     case BFD_RELOC_NONE:
15453     case BFD_RELOC_VTABLE_ENTRY:
15454       fixP->fx_done = 0;
15455       break;
15456
15457     default:
15458       abort ();
15459     }
15460
15461   /* Remember value for tc_gen_reloc.  */
15462   fixP->fx_addnumber = *valP;
15463 }
15464
15465 static symbolS *
15466 get_symbol (void)
15467 {
15468   int c;
15469   char *name;
15470   symbolS *p;
15471
15472   c = get_symbol_name (&name);
15473   p = (symbolS *) symbol_find_or_make (name);
15474   (void) restore_line_pointer (c);
15475   return p;
15476 }
15477
15478 /* Align the current frag to a given power of two.  If a particular
15479    fill byte should be used, FILL points to an integer that contains
15480    that byte, otherwise FILL is null.
15481
15482    This function used to have the comment:
15483
15484       The MIPS assembler also automatically adjusts any preceding label.
15485
15486    The implementation therefore applied the adjustment to a maximum of
15487    one label.  However, other label adjustments are applied to batches
15488    of labels, and adjusting just one caused problems when new labels
15489    were added for the sake of debugging or unwind information.
15490    We therefore adjust all preceding labels (given as LABELS) instead.  */
15491
15492 static void
15493 mips_align (int to, int *fill, struct insn_label_list *labels)
15494 {
15495   mips_emit_delays ();
15496   mips_record_compressed_mode ();
15497   if (fill == NULL && subseg_text_p (now_seg))
15498     frag_align_code (to, 0);
15499   else
15500     frag_align (to, fill ? *fill : 0, 0);
15501   record_alignment (now_seg, to);
15502   mips_move_labels (labels, FALSE);
15503 }
15504
15505 /* Align to a given power of two.  .align 0 turns off the automatic
15506    alignment used by the data creating pseudo-ops.  */
15507
15508 static void
15509 s_align (int x ATTRIBUTE_UNUSED)
15510 {
15511   int temp, fill_value, *fill_ptr;
15512   long max_alignment = 28;
15513
15514   /* o Note that the assembler pulls down any immediately preceding label
15515        to the aligned address.
15516      o It's not documented but auto alignment is reinstated by
15517        a .align pseudo instruction.
15518      o Note also that after auto alignment is turned off the mips assembler
15519        issues an error on attempt to assemble an improperly aligned data item.
15520        We don't.  */
15521
15522   temp = get_absolute_expression ();
15523   if (temp > max_alignment)
15524     as_bad (_("alignment too large, %d assumed"), temp = max_alignment);
15525   else if (temp < 0)
15526     {
15527       as_warn (_("alignment negative, 0 assumed"));
15528       temp = 0;
15529     }
15530   if (*input_line_pointer == ',')
15531     {
15532       ++input_line_pointer;
15533       fill_value = get_absolute_expression ();
15534       fill_ptr = &fill_value;
15535     }
15536   else
15537     fill_ptr = 0;
15538   if (temp)
15539     {
15540       segment_info_type *si = seg_info (now_seg);
15541       struct insn_label_list *l = si->label_list;
15542       /* Auto alignment should be switched on by next section change.  */
15543       auto_align = 1;
15544       mips_align (temp, fill_ptr, l);
15545     }
15546   else
15547     {
15548       auto_align = 0;
15549     }
15550
15551   demand_empty_rest_of_line ();
15552 }
15553
15554 static void
15555 s_change_sec (int sec)
15556 {
15557   segT seg;
15558
15559   /* The ELF backend needs to know that we are changing sections, so
15560      that .previous works correctly.  We could do something like check
15561      for an obj_section_change_hook macro, but that might be confusing
15562      as it would not be appropriate to use it in the section changing
15563      functions in read.c, since obj-elf.c intercepts those.  FIXME:
15564      This should be cleaner, somehow.  */
15565   obj_elf_section_change_hook ();
15566
15567   mips_emit_delays ();
15568
15569   switch (sec)
15570     {
15571     case 't':
15572       s_text (0);
15573       break;
15574     case 'd':
15575       s_data (0);
15576       break;
15577     case 'b':
15578       subseg_set (bss_section, (subsegT) get_absolute_expression ());
15579       demand_empty_rest_of_line ();
15580       break;
15581
15582     case 'r':
15583       seg = subseg_new (RDATA_SECTION_NAME,
15584                         (subsegT) get_absolute_expression ());
15585       bfd_set_section_flags (stdoutput, seg, (SEC_ALLOC | SEC_LOAD
15586                                               | SEC_READONLY | SEC_RELOC
15587                                               | SEC_DATA));
15588       if (strncmp (TARGET_OS, "elf", 3) != 0)
15589         record_alignment (seg, 4);
15590       demand_empty_rest_of_line ();
15591       break;
15592
15593     case 's':
15594       seg = subseg_new (".sdata", (subsegT) get_absolute_expression ());
15595       bfd_set_section_flags (stdoutput, seg,
15596                              SEC_ALLOC | SEC_LOAD | SEC_RELOC | SEC_DATA);
15597       if (strncmp (TARGET_OS, "elf", 3) != 0)
15598         record_alignment (seg, 4);
15599       demand_empty_rest_of_line ();
15600       break;
15601
15602     case 'B':
15603       seg = subseg_new (".sbss", (subsegT) get_absolute_expression ());
15604       bfd_set_section_flags (stdoutput, seg, SEC_ALLOC);
15605       if (strncmp (TARGET_OS, "elf", 3) != 0)
15606         record_alignment (seg, 4);
15607       demand_empty_rest_of_line ();
15608       break;
15609     }
15610
15611   auto_align = 1;
15612 }
15613
15614 void
15615 s_change_section (int ignore ATTRIBUTE_UNUSED)
15616 {
15617   char *saved_ilp;
15618   char *section_name;
15619   char c, endc;
15620   char next_c = 0;
15621   int section_type;
15622   int section_flag;
15623   int section_entry_size;
15624   int section_alignment;
15625
15626   saved_ilp = input_line_pointer;
15627   endc = get_symbol_name (&section_name);
15628   c = (endc == '"' ? input_line_pointer[1] : endc);
15629   if (c)
15630     next_c = input_line_pointer [(endc == '"' ? 2 : 1)];
15631
15632   /* Do we have .section Name<,"flags">?  */
15633   if (c != ',' || (c == ',' && next_c == '"'))
15634     {
15635       /* Just after name is now '\0'.  */
15636       (void) restore_line_pointer (endc);
15637       input_line_pointer = saved_ilp;
15638       obj_elf_section (ignore);
15639       return;
15640     }
15641
15642   section_name = xstrdup (section_name);
15643   c = restore_line_pointer (endc);
15644
15645   input_line_pointer++;
15646
15647   /* Do we have .section Name<,type><,flag><,entry_size><,alignment>  */
15648   if (c == ',')
15649     section_type = get_absolute_expression ();
15650   else
15651     section_type = 0;
15652
15653   if (*input_line_pointer++ == ',')
15654     section_flag = get_absolute_expression ();
15655   else
15656     section_flag = 0;
15657
15658   if (*input_line_pointer++ == ',')
15659     section_entry_size = get_absolute_expression ();
15660   else
15661     section_entry_size = 0;
15662
15663   if (*input_line_pointer++ == ',')
15664     section_alignment = get_absolute_expression ();
15665   else
15666     section_alignment = 0;
15667
15668   /* FIXME: really ignore?  */
15669   (void) section_alignment;
15670
15671   /* When using the generic form of .section (as implemented by obj-elf.c),
15672      there's no way to set the section type to SHT_MIPS_DWARF.  Users have
15673      traditionally had to fall back on the more common @progbits instead.
15674
15675      There's nothing really harmful in this, since bfd will correct
15676      SHT_PROGBITS to SHT_MIPS_DWARF before writing out the file.  But it
15677      means that, for backwards compatibility, the special_section entries
15678      for dwarf sections must use SHT_PROGBITS rather than SHT_MIPS_DWARF.
15679
15680      Even so, we shouldn't force users of the MIPS .section syntax to
15681      incorrectly label the sections as SHT_PROGBITS.  The best compromise
15682      seems to be to map SHT_MIPS_DWARF to SHT_PROGBITS before calling the
15683      generic type-checking code.  */
15684   if (section_type == SHT_MIPS_DWARF)
15685     section_type = SHT_PROGBITS;
15686
15687   obj_elf_change_section (section_name, section_type, section_flag,
15688                           section_entry_size, 0, 0, 0);
15689
15690   if (now_seg->name != section_name)
15691     free (section_name);
15692 }
15693
15694 void
15695 mips_enable_auto_align (void)
15696 {
15697   auto_align = 1;
15698 }
15699
15700 static void
15701 s_cons (int log_size)
15702 {
15703   segment_info_type *si = seg_info (now_seg);
15704   struct insn_label_list *l = si->label_list;
15705
15706   mips_emit_delays ();
15707   if (log_size > 0 && auto_align)
15708     mips_align (log_size, 0, l);
15709   cons (1 << log_size);
15710   mips_clear_insn_labels ();
15711 }
15712
15713 static void
15714 s_float_cons (int type)
15715 {
15716   segment_info_type *si = seg_info (now_seg);
15717   struct insn_label_list *l = si->label_list;
15718
15719   mips_emit_delays ();
15720
15721   if (auto_align)
15722     {
15723       if (type == 'd')
15724         mips_align (3, 0, l);
15725       else
15726         mips_align (2, 0, l);
15727     }
15728
15729   float_cons (type);
15730   mips_clear_insn_labels ();
15731 }
15732
15733 /* Handle .globl.  We need to override it because on Irix 5 you are
15734    permitted to say
15735        .globl foo .text
15736    where foo is an undefined symbol, to mean that foo should be
15737    considered to be the address of a function.  */
15738
15739 static void
15740 s_mips_globl (int x ATTRIBUTE_UNUSED)
15741 {
15742   char *name;
15743   int c;
15744   symbolS *symbolP;
15745   flagword flag;
15746
15747   do
15748     {
15749       c = get_symbol_name (&name);
15750       symbolP = symbol_find_or_make (name);
15751       S_SET_EXTERNAL (symbolP);
15752
15753       *input_line_pointer = c;
15754       SKIP_WHITESPACE_AFTER_NAME ();
15755
15756       /* On Irix 5, every global symbol that is not explicitly labelled as
15757          being a function is apparently labelled as being an object.  */
15758       flag = BSF_OBJECT;
15759
15760       if (!is_end_of_line[(unsigned char) *input_line_pointer]
15761           && (*input_line_pointer != ','))
15762         {
15763           char *secname;
15764           asection *sec;
15765
15766           c = get_symbol_name (&secname);
15767           sec = bfd_get_section_by_name (stdoutput, secname);
15768           if (sec == NULL)
15769             as_bad (_("%s: no such section"), secname);
15770           (void) restore_line_pointer (c);
15771
15772           if (sec != NULL && (sec->flags & SEC_CODE) != 0)
15773             flag = BSF_FUNCTION;
15774         }
15775
15776       symbol_get_bfdsym (symbolP)->flags |= flag;
15777
15778       c = *input_line_pointer;
15779       if (c == ',')
15780         {
15781           input_line_pointer++;
15782           SKIP_WHITESPACE ();
15783           if (is_end_of_line[(unsigned char) *input_line_pointer])
15784             c = '\n';
15785         }
15786     }
15787   while (c == ',');
15788
15789   demand_empty_rest_of_line ();
15790 }
15791
15792 static void
15793 s_option (int x ATTRIBUTE_UNUSED)
15794 {
15795   char *opt;
15796   char c;
15797
15798   c = get_symbol_name (&opt);
15799
15800   if (*opt == 'O')
15801     {
15802       /* FIXME: What does this mean?  */
15803     }
15804   else if (strncmp (opt, "pic", 3) == 0 && ISDIGIT (opt[3]) && opt[4] == '\0')
15805     {
15806       int i;
15807
15808       i = atoi (opt + 3);
15809       if (i != 0 && i != 2)
15810         as_bad (_(".option pic%d not supported"), i);
15811       else if (mips_pic == VXWORKS_PIC)
15812         as_bad (_(".option pic%d not supported in VxWorks PIC mode"), i);
15813       else if (i == 0)
15814         mips_pic = NO_PIC;
15815       else if (i == 2)
15816         {
15817           mips_pic = SVR4_PIC;
15818           mips_abicalls = TRUE;
15819         }
15820
15821       if (mips_pic == SVR4_PIC)
15822         {
15823           if (g_switch_seen && g_switch_value != 0)
15824             as_warn (_("-G may not be used with SVR4 PIC code"));
15825           g_switch_value = 0;
15826           bfd_set_gp_size (stdoutput, 0);
15827         }
15828     }
15829   else
15830     as_warn (_("unrecognized option \"%s\""), opt);
15831
15832   (void) restore_line_pointer (c);
15833   demand_empty_rest_of_line ();
15834 }
15835
15836 /* This structure is used to hold a stack of .set values.  */
15837
15838 struct mips_option_stack
15839 {
15840   struct mips_option_stack *next;
15841   struct mips_set_options options;
15842 };
15843
15844 static struct mips_option_stack *mips_opts_stack;
15845
15846 /* Return status for .set/.module option handling.  */
15847
15848 enum code_option_type
15849 {
15850   /* Unrecognized option.  */
15851   OPTION_TYPE_BAD = -1,
15852
15853   /* Ordinary option.  */
15854   OPTION_TYPE_NORMAL,
15855
15856   /* ISA changing option.  */
15857   OPTION_TYPE_ISA
15858 };
15859
15860 /* Handle common .set/.module options.  Return status indicating option
15861    type.  */
15862
15863 static enum code_option_type
15864 parse_code_option (char * name)
15865 {
15866   bfd_boolean isa_set = FALSE;
15867   const struct mips_ase *ase;
15868
15869   if (strncmp (name, "at=", 3) == 0)
15870     {
15871       char *s = name + 3;
15872
15873       if (!reg_lookup (&s, RTYPE_NUM | RTYPE_GP, &mips_opts.at))
15874         as_bad (_("unrecognized register name `%s'"), s);
15875     }
15876   else if (strcmp (name, "at") == 0)
15877     mips_opts.at = ATREG;
15878   else if (strcmp (name, "noat") == 0)
15879     mips_opts.at = ZERO;
15880   else if (strcmp (name, "move") == 0 || strcmp (name, "novolatile") == 0)
15881     mips_opts.nomove = 0;
15882   else if (strcmp (name, "nomove") == 0 || strcmp (name, "volatile") == 0)
15883     mips_opts.nomove = 1;
15884   else if (strcmp (name, "bopt") == 0)
15885     mips_opts.nobopt = 0;
15886   else if (strcmp (name, "nobopt") == 0)
15887     mips_opts.nobopt = 1;
15888   else if (strcmp (name, "gp=32") == 0)
15889     mips_opts.gp = 32;
15890   else if (strcmp (name, "gp=64") == 0)
15891     mips_opts.gp = 64;
15892   else if (strcmp (name, "fp=32") == 0)
15893     mips_opts.fp = 32;
15894   else if (strcmp (name, "fp=xx") == 0)
15895     mips_opts.fp = 0;
15896   else if (strcmp (name, "fp=64") == 0)
15897     mips_opts.fp = 64;
15898   else if (strcmp (name, "softfloat") == 0)
15899     mips_opts.soft_float = 1;
15900   else if (strcmp (name, "hardfloat") == 0)
15901     mips_opts.soft_float = 0;
15902   else if (strcmp (name, "singlefloat") == 0)
15903     mips_opts.single_float = 1;
15904   else if (strcmp (name, "doublefloat") == 0)
15905     mips_opts.single_float = 0;
15906   else if (strcmp (name, "nooddspreg") == 0)
15907     mips_opts.oddspreg = 0;
15908   else if (strcmp (name, "oddspreg") == 0)
15909     mips_opts.oddspreg = 1;
15910   else if (strcmp (name, "mips16") == 0
15911            || strcmp (name, "MIPS-16") == 0)
15912     mips_opts.mips16 = 1;
15913   else if (strcmp (name, "nomips16") == 0
15914            || strcmp (name, "noMIPS-16") == 0)
15915     mips_opts.mips16 = 0;
15916   else if (strcmp (name, "micromips") == 0)
15917     mips_opts.micromips = 1;
15918   else if (strcmp (name, "nomicromips") == 0)
15919     mips_opts.micromips = 0;
15920   else if (name[0] == 'n'
15921            && name[1] == 'o'
15922            && (ase = mips_lookup_ase (name + 2)))
15923     mips_set_ase (ase, &mips_opts, FALSE);
15924   else if ((ase = mips_lookup_ase (name)))
15925     mips_set_ase (ase, &mips_opts, TRUE);
15926   else if (strncmp (name, "mips", 4) == 0 || strncmp (name, "arch=", 5) == 0)
15927     {
15928       /* Permit the user to change the ISA and architecture on the fly.
15929          Needless to say, misuse can cause serious problems.  */
15930       if (strncmp (name, "arch=", 5) == 0)
15931         {
15932           const struct mips_cpu_info *p;
15933
15934           p = mips_parse_cpu ("internal use", name + 5);
15935           if (!p)
15936             as_bad (_("unknown architecture %s"), name + 5);
15937           else
15938             {
15939               mips_opts.arch = p->cpu;
15940               mips_opts.isa = p->isa;
15941               isa_set = TRUE;
15942             }
15943         }
15944       else if (strncmp (name, "mips", 4) == 0)
15945         {
15946           const struct mips_cpu_info *p;
15947
15948           p = mips_parse_cpu ("internal use", name);
15949           if (!p)
15950             as_bad (_("unknown ISA level %s"), name + 4);
15951           else
15952             {
15953               mips_opts.arch = p->cpu;
15954               mips_opts.isa = p->isa;
15955               isa_set = TRUE;
15956             }
15957         }
15958       else
15959         as_bad (_("unknown ISA or architecture %s"), name);
15960     }
15961   else if (strcmp (name, "autoextend") == 0)
15962     mips_opts.noautoextend = 0;
15963   else if (strcmp (name, "noautoextend") == 0)
15964     mips_opts.noautoextend = 1;
15965   else if (strcmp (name, "insn32") == 0)
15966     mips_opts.insn32 = TRUE;
15967   else if (strcmp (name, "noinsn32") == 0)
15968     mips_opts.insn32 = FALSE;
15969   else if (strcmp (name, "sym32") == 0)
15970     mips_opts.sym32 = TRUE;
15971   else if (strcmp (name, "nosym32") == 0)
15972     mips_opts.sym32 = FALSE;
15973   else
15974     return OPTION_TYPE_BAD;
15975
15976   return isa_set ? OPTION_TYPE_ISA : OPTION_TYPE_NORMAL;
15977 }
15978
15979 /* Handle the .set pseudo-op.  */
15980
15981 static void
15982 s_mipsset (int x ATTRIBUTE_UNUSED)
15983 {
15984   enum code_option_type type = OPTION_TYPE_NORMAL;
15985   char *name = input_line_pointer, ch;
15986
15987   file_mips_check_options ();
15988
15989   while (!is_end_of_line[(unsigned char) *input_line_pointer])
15990     ++input_line_pointer;
15991   ch = *input_line_pointer;
15992   *input_line_pointer = '\0';
15993
15994   if (strchr (name, ','))
15995     {
15996       /* Generic ".set" directive; use the generic handler.  */
15997       *input_line_pointer = ch;
15998       input_line_pointer = name;
15999       s_set (0);
16000       return;
16001     }
16002
16003   if (strcmp (name, "reorder") == 0)
16004     {
16005       if (mips_opts.noreorder)
16006         end_noreorder ();
16007     }
16008   else if (strcmp (name, "noreorder") == 0)
16009     {
16010       if (!mips_opts.noreorder)
16011         start_noreorder ();
16012     }
16013   else if (strcmp (name, "macro") == 0)
16014     mips_opts.warn_about_macros = 0;
16015   else if (strcmp (name, "nomacro") == 0)
16016     {
16017       if (mips_opts.noreorder == 0)
16018         as_bad (_("`noreorder' must be set before `nomacro'"));
16019       mips_opts.warn_about_macros = 1;
16020     }
16021   else if (strcmp (name, "gp=default") == 0)
16022     mips_opts.gp = file_mips_opts.gp;
16023   else if (strcmp (name, "fp=default") == 0)
16024     mips_opts.fp = file_mips_opts.fp;
16025   else if (strcmp (name, "mips0") == 0 || strcmp (name, "arch=default") == 0)
16026     {
16027       mips_opts.isa = file_mips_opts.isa;
16028       mips_opts.arch = file_mips_opts.arch;
16029       mips_opts.gp = file_mips_opts.gp;
16030       mips_opts.fp = file_mips_opts.fp;
16031     }
16032   else if (strcmp (name, "push") == 0)
16033     {
16034       struct mips_option_stack *s;
16035
16036       s = XNEW (struct mips_option_stack);
16037       s->next = mips_opts_stack;
16038       s->options = mips_opts;
16039       mips_opts_stack = s;
16040     }
16041   else if (strcmp (name, "pop") == 0)
16042     {
16043       struct mips_option_stack *s;
16044
16045       s = mips_opts_stack;
16046       if (s == NULL)
16047         as_bad (_(".set pop with no .set push"));
16048       else
16049         {
16050           /* If we're changing the reorder mode we need to handle
16051              delay slots correctly.  */
16052           if (s->options.noreorder && ! mips_opts.noreorder)
16053             start_noreorder ();
16054           else if (! s->options.noreorder && mips_opts.noreorder)
16055             end_noreorder ();
16056
16057           mips_opts = s->options;
16058           mips_opts_stack = s->next;
16059           free (s);
16060         }
16061     }
16062   else
16063     {
16064       type = parse_code_option (name);
16065       if (type == OPTION_TYPE_BAD)
16066         as_warn (_("tried to set unrecognized symbol: %s\n"), name);
16067     }
16068
16069   /* The use of .set [arch|cpu]= historically 'fixes' the width of gp and fp
16070      registers based on what is supported by the arch/cpu.  */
16071   if (type == OPTION_TYPE_ISA)
16072     {
16073       switch (mips_opts.isa)
16074         {
16075         case 0:
16076           break;
16077         case ISA_MIPS1:
16078           /* MIPS I cannot support FPXX.  */
16079           mips_opts.fp = 32;
16080           /* fall-through.  */
16081         case ISA_MIPS2:
16082         case ISA_MIPS32:
16083         case ISA_MIPS32R2:
16084         case ISA_MIPS32R3:
16085         case ISA_MIPS32R5:
16086           mips_opts.gp = 32;
16087           if (mips_opts.fp != 0)
16088             mips_opts.fp = 32;
16089           break;
16090         case ISA_MIPS32R6:
16091           mips_opts.gp = 32;
16092           mips_opts.fp = 64;
16093           break;
16094         case ISA_MIPS3:
16095         case ISA_MIPS4:
16096         case ISA_MIPS5:
16097         case ISA_MIPS64:
16098         case ISA_MIPS64R2:
16099         case ISA_MIPS64R3:
16100         case ISA_MIPS64R5:
16101         case ISA_MIPS64R6:
16102           mips_opts.gp = 64;
16103           if (mips_opts.fp != 0)
16104             {
16105               if (mips_opts.arch == CPU_R5900)
16106                 mips_opts.fp = 32;
16107               else
16108                 mips_opts.fp = 64;
16109             }
16110           break;
16111         default:
16112           as_bad (_("unknown ISA level %s"), name + 4);
16113           break;
16114         }
16115     }
16116
16117   mips_check_options (&mips_opts, FALSE);
16118
16119   mips_check_isa_supports_ases ();
16120   *input_line_pointer = ch;
16121   demand_empty_rest_of_line ();
16122 }
16123
16124 /* Handle the .module pseudo-op.  */
16125
16126 static void
16127 s_module (int ignore ATTRIBUTE_UNUSED)
16128 {
16129   char *name = input_line_pointer, ch;
16130
16131   while (!is_end_of_line[(unsigned char) *input_line_pointer])
16132     ++input_line_pointer;
16133   ch = *input_line_pointer;
16134   *input_line_pointer = '\0';
16135
16136   if (!file_mips_opts_checked)
16137     {
16138       if (parse_code_option (name) == OPTION_TYPE_BAD)
16139         as_bad (_(".module used with unrecognized symbol: %s\n"), name);
16140
16141       /* Update module level settings from mips_opts.  */
16142       file_mips_opts = mips_opts;
16143     }
16144   else
16145     as_bad (_(".module is not permitted after generating code"));
16146
16147   *input_line_pointer = ch;
16148   demand_empty_rest_of_line ();
16149 }
16150
16151 /* Handle the .abicalls pseudo-op.  I believe this is equivalent to
16152    .option pic2.  It means to generate SVR4 PIC calls.  */
16153
16154 static void
16155 s_abicalls (int ignore ATTRIBUTE_UNUSED)
16156 {
16157   mips_pic = SVR4_PIC;
16158   mips_abicalls = TRUE;
16159
16160   if (g_switch_seen && g_switch_value != 0)
16161     as_warn (_("-G may not be used with SVR4 PIC code"));
16162   g_switch_value = 0;
16163
16164   bfd_set_gp_size (stdoutput, 0);
16165   demand_empty_rest_of_line ();
16166 }
16167
16168 /* Handle the .cpload pseudo-op.  This is used when generating SVR4
16169    PIC code.  It sets the $gp register for the function based on the
16170    function address, which is in the register named in the argument.
16171    This uses a relocation against _gp_disp, which is handled specially
16172    by the linker.  The result is:
16173         lui     $gp,%hi(_gp_disp)
16174         addiu   $gp,$gp,%lo(_gp_disp)
16175         addu    $gp,$gp,.cpload argument
16176    The .cpload argument is normally $25 == $t9.
16177
16178    The -mno-shared option changes this to:
16179         lui     $gp,%hi(__gnu_local_gp)
16180         addiu   $gp,$gp,%lo(__gnu_local_gp)
16181    and the argument is ignored.  This saves an instruction, but the
16182    resulting code is not position independent; it uses an absolute
16183    address for __gnu_local_gp.  Thus code assembled with -mno-shared
16184    can go into an ordinary executable, but not into a shared library.  */
16185
16186 static void
16187 s_cpload (int ignore ATTRIBUTE_UNUSED)
16188 {
16189   expressionS ex;
16190   int reg;
16191   int in_shared;
16192
16193   file_mips_check_options ();
16194
16195   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16196      .cpload is ignored.  */
16197   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16198     {
16199       s_ignore (0);
16200       return;
16201     }
16202
16203   if (mips_opts.mips16)
16204     {
16205       as_bad (_("%s not supported in MIPS16 mode"), ".cpload");
16206       ignore_rest_of_line ();
16207       return;
16208     }
16209
16210   /* .cpload should be in a .set noreorder section.  */
16211   if (mips_opts.noreorder == 0)
16212     as_warn (_(".cpload not in noreorder section"));
16213
16214   reg = tc_get_register (0);
16215
16216   /* If we need to produce a 64-bit address, we are better off using
16217      the default instruction sequence.  */
16218   in_shared = mips_in_shared || HAVE_64BIT_SYMBOLS;
16219
16220   ex.X_op = O_symbol;
16221   ex.X_add_symbol = symbol_find_or_make (in_shared ? "_gp_disp" :
16222                                          "__gnu_local_gp");
16223   ex.X_op_symbol = NULL;
16224   ex.X_add_number = 0;
16225
16226   /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16227   symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16228
16229   mips_mark_labels ();
16230   mips_assembling_insn = TRUE;
16231
16232   macro_start ();
16233   macro_build_lui (&ex, mips_gp_register);
16234   macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16235                mips_gp_register, BFD_RELOC_LO16);
16236   if (in_shared)
16237     macro_build (NULL, "addu", "d,v,t", mips_gp_register,
16238                  mips_gp_register, reg);
16239   macro_end ();
16240
16241   mips_assembling_insn = FALSE;
16242   demand_empty_rest_of_line ();
16243 }
16244
16245 /* Handle the .cpsetup pseudo-op defined for NewABI PIC code.  The syntax is:
16246      .cpsetup $reg1, offset|$reg2, label
16247
16248    If offset is given, this results in:
16249      sd         $gp, offset($sp)
16250      lui        $gp, %hi(%neg(%gp_rel(label)))
16251      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16252      daddu      $gp, $gp, $reg1
16253
16254    If $reg2 is given, this results in:
16255      or         $reg2, $gp, $0
16256      lui        $gp, %hi(%neg(%gp_rel(label)))
16257      addiu      $gp, $gp, %lo(%neg(%gp_rel(label)))
16258      daddu      $gp, $gp, $reg1
16259    $reg1 is normally $25 == $t9.
16260
16261    The -mno-shared option replaces the last three instructions with
16262         lui     $gp,%hi(_gp)
16263         addiu   $gp,$gp,%lo(_gp)  */
16264
16265 static void
16266 s_cpsetup (int ignore ATTRIBUTE_UNUSED)
16267 {
16268   expressionS ex_off;
16269   expressionS ex_sym;
16270   int reg1;
16271
16272   file_mips_check_options ();
16273
16274   /* If we are not generating SVR4 PIC code, .cpsetup is ignored.
16275      We also need NewABI support.  */
16276   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16277     {
16278       s_ignore (0);
16279       return;
16280     }
16281
16282   if (mips_opts.mips16)
16283     {
16284       as_bad (_("%s not supported in MIPS16 mode"), ".cpsetup");
16285       ignore_rest_of_line ();
16286       return;
16287     }
16288
16289   reg1 = tc_get_register (0);
16290   SKIP_WHITESPACE ();
16291   if (*input_line_pointer != ',')
16292     {
16293       as_bad (_("missing argument separator ',' for .cpsetup"));
16294       return;
16295     }
16296   else
16297     ++input_line_pointer;
16298   SKIP_WHITESPACE ();
16299   if (*input_line_pointer == '$')
16300     {
16301       mips_cpreturn_register = tc_get_register (0);
16302       mips_cpreturn_offset = -1;
16303     }
16304   else
16305     {
16306       mips_cpreturn_offset = get_absolute_expression ();
16307       mips_cpreturn_register = -1;
16308     }
16309   SKIP_WHITESPACE ();
16310   if (*input_line_pointer != ',')
16311     {
16312       as_bad (_("missing argument separator ',' for .cpsetup"));
16313       return;
16314     }
16315   else
16316     ++input_line_pointer;
16317   SKIP_WHITESPACE ();
16318   expression (&ex_sym);
16319
16320   mips_mark_labels ();
16321   mips_assembling_insn = TRUE;
16322
16323   macro_start ();
16324   if (mips_cpreturn_register == -1)
16325     {
16326       ex_off.X_op = O_constant;
16327       ex_off.X_add_symbol = NULL;
16328       ex_off.X_op_symbol = NULL;
16329       ex_off.X_add_number = mips_cpreturn_offset;
16330
16331       macro_build (&ex_off, "sd", "t,o(b)", mips_gp_register,
16332                    BFD_RELOC_LO16, SP);
16333     }
16334   else
16335     move_register (mips_cpreturn_register, mips_gp_register);
16336
16337   if (mips_in_shared || HAVE_64BIT_SYMBOLS)
16338     {
16339       macro_build (&ex_sym, "lui", LUI_FMT, mips_gp_register,
16340                    -1, BFD_RELOC_GPREL16, BFD_RELOC_MIPS_SUB,
16341                    BFD_RELOC_HI16_S);
16342
16343       macro_build (&ex_sym, "addiu", "t,r,j", mips_gp_register,
16344                    mips_gp_register, -1, BFD_RELOC_GPREL16,
16345                    BFD_RELOC_MIPS_SUB, BFD_RELOC_LO16);
16346
16347       macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", mips_gp_register,
16348                    mips_gp_register, reg1);
16349     }
16350   else
16351     {
16352       expressionS ex;
16353
16354       ex.X_op = O_symbol;
16355       ex.X_add_symbol = symbol_find_or_make ("__gnu_local_gp");
16356       ex.X_op_symbol = NULL;
16357       ex.X_add_number = 0;
16358
16359       /* In ELF, this symbol is implicitly an STT_OBJECT symbol.  */
16360       symbol_get_bfdsym (ex.X_add_symbol)->flags |= BSF_OBJECT;
16361
16362       macro_build_lui (&ex, mips_gp_register);
16363       macro_build (&ex, "addiu", "t,r,j", mips_gp_register,
16364                    mips_gp_register, BFD_RELOC_LO16);
16365     }
16366
16367   macro_end ();
16368
16369   mips_assembling_insn = FALSE;
16370   demand_empty_rest_of_line ();
16371 }
16372
16373 static void
16374 s_cplocal (int ignore ATTRIBUTE_UNUSED)
16375 {
16376   file_mips_check_options ();
16377
16378   /* If we are not generating SVR4 PIC code, or if this is not NewABI code,
16379      .cplocal is ignored.  */
16380   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16381     {
16382       s_ignore (0);
16383       return;
16384     }
16385
16386   if (mips_opts.mips16)
16387     {
16388       as_bad (_("%s not supported in MIPS16 mode"), ".cplocal");
16389       ignore_rest_of_line ();
16390       return;
16391     }
16392
16393   mips_gp_register = tc_get_register (0);
16394   demand_empty_rest_of_line ();
16395 }
16396
16397 /* Handle the .cprestore pseudo-op.  This stores $gp into a given
16398    offset from $sp.  The offset is remembered, and after making a PIC
16399    call $gp is restored from that location.  */
16400
16401 static void
16402 s_cprestore (int ignore ATTRIBUTE_UNUSED)
16403 {
16404   expressionS ex;
16405
16406   file_mips_check_options ();
16407
16408   /* If we are not generating SVR4 PIC code, or if this is NewABI code,
16409      .cprestore is ignored.  */
16410   if (mips_pic != SVR4_PIC || HAVE_NEWABI)
16411     {
16412       s_ignore (0);
16413       return;
16414     }
16415
16416   if (mips_opts.mips16)
16417     {
16418       as_bad (_("%s not supported in MIPS16 mode"), ".cprestore");
16419       ignore_rest_of_line ();
16420       return;
16421     }
16422
16423   mips_cprestore_offset = get_absolute_expression ();
16424   mips_cprestore_valid = 1;
16425
16426   ex.X_op = O_constant;
16427   ex.X_add_symbol = NULL;
16428   ex.X_op_symbol = NULL;
16429   ex.X_add_number = mips_cprestore_offset;
16430
16431   mips_mark_labels ();
16432   mips_assembling_insn = TRUE;
16433
16434   macro_start ();
16435   macro_build_ldst_constoffset (&ex, ADDRESS_STORE_INSN, mips_gp_register,
16436                                 SP, HAVE_64BIT_ADDRESSES);
16437   macro_end ();
16438
16439   mips_assembling_insn = FALSE;
16440   demand_empty_rest_of_line ();
16441 }
16442
16443 /* Handle the .cpreturn pseudo-op defined for NewABI PIC code. If an offset
16444    was given in the preceding .cpsetup, it results in:
16445      ld         $gp, offset($sp)
16446
16447    If a register $reg2 was given there, it results in:
16448      or         $gp, $reg2, $0  */
16449
16450 static void
16451 s_cpreturn (int ignore ATTRIBUTE_UNUSED)
16452 {
16453   expressionS ex;
16454
16455   file_mips_check_options ();
16456
16457   /* If we are not generating SVR4 PIC code, .cpreturn is ignored.
16458      We also need NewABI support.  */
16459   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16460     {
16461       s_ignore (0);
16462       return;
16463     }
16464
16465   if (mips_opts.mips16)
16466     {
16467       as_bad (_("%s not supported in MIPS16 mode"), ".cpreturn");
16468       ignore_rest_of_line ();
16469       return;
16470     }
16471
16472   mips_mark_labels ();
16473   mips_assembling_insn = TRUE;
16474
16475   macro_start ();
16476   if (mips_cpreturn_register == -1)
16477     {
16478       ex.X_op = O_constant;
16479       ex.X_add_symbol = NULL;
16480       ex.X_op_symbol = NULL;
16481       ex.X_add_number = mips_cpreturn_offset;
16482
16483       macro_build (&ex, "ld", "t,o(b)", mips_gp_register, BFD_RELOC_LO16, SP);
16484     }
16485   else
16486     move_register (mips_gp_register, mips_cpreturn_register);
16487
16488   macro_end ();
16489
16490   mips_assembling_insn = FALSE;
16491   demand_empty_rest_of_line ();
16492 }
16493
16494 /* Handle a .dtprelword, .dtpreldword, .tprelword, or .tpreldword
16495    pseudo-op; DIRSTR says which. The pseudo-op generates a BYTES-size
16496    DTP- or TP-relative relocation of type RTYPE, for use in either DWARF
16497    debug information or MIPS16 TLS.  */
16498
16499 static void
16500 s_tls_rel_directive (const size_t bytes, const char *dirstr,
16501                      bfd_reloc_code_real_type rtype)
16502 {
16503   expressionS ex;
16504   char *p;
16505
16506   expression (&ex);
16507
16508   if (ex.X_op != O_symbol)
16509     {
16510       as_bad (_("unsupported use of %s"), dirstr);
16511       ignore_rest_of_line ();
16512     }
16513
16514   p = frag_more (bytes);
16515   md_number_to_chars (p, 0, bytes);
16516   fix_new_exp (frag_now, p - frag_now->fr_literal, bytes, &ex, FALSE, rtype);
16517   demand_empty_rest_of_line ();
16518   mips_clear_insn_labels ();
16519 }
16520
16521 /* Handle .dtprelword.  */
16522
16523 static void
16524 s_dtprelword (int ignore ATTRIBUTE_UNUSED)
16525 {
16526   s_tls_rel_directive (4, ".dtprelword", BFD_RELOC_MIPS_TLS_DTPREL32);
16527 }
16528
16529 /* Handle .dtpreldword.  */
16530
16531 static void
16532 s_dtpreldword (int ignore ATTRIBUTE_UNUSED)
16533 {
16534   s_tls_rel_directive (8, ".dtpreldword", BFD_RELOC_MIPS_TLS_DTPREL64);
16535 }
16536
16537 /* Handle .tprelword.  */
16538
16539 static void
16540 s_tprelword (int ignore ATTRIBUTE_UNUSED)
16541 {
16542   s_tls_rel_directive (4, ".tprelword", BFD_RELOC_MIPS_TLS_TPREL32);
16543 }
16544
16545 /* Handle .tpreldword.  */
16546
16547 static void
16548 s_tpreldword (int ignore ATTRIBUTE_UNUSED)
16549 {
16550   s_tls_rel_directive (8, ".tpreldword", BFD_RELOC_MIPS_TLS_TPREL64);
16551 }
16552
16553 /* Handle the .gpvalue pseudo-op.  This is used when generating NewABI PIC
16554    code.  It sets the offset to use in gp_rel relocations.  */
16555
16556 static void
16557 s_gpvalue (int ignore ATTRIBUTE_UNUSED)
16558 {
16559   /* If we are not generating SVR4 PIC code, .gpvalue is ignored.
16560      We also need NewABI support.  */
16561   if (mips_pic != SVR4_PIC || ! HAVE_NEWABI)
16562     {
16563       s_ignore (0);
16564       return;
16565     }
16566
16567   mips_gprel_offset = get_absolute_expression ();
16568
16569   demand_empty_rest_of_line ();
16570 }
16571
16572 /* Handle the .gpword pseudo-op.  This is used when generating PIC
16573    code.  It generates a 32 bit GP relative reloc.  */
16574
16575 static void
16576 s_gpword (int ignore ATTRIBUTE_UNUSED)
16577 {
16578   segment_info_type *si;
16579   struct insn_label_list *l;
16580   expressionS ex;
16581   char *p;
16582
16583   /* When not generating PIC code, this is treated as .word.  */
16584   if (mips_pic != SVR4_PIC)
16585     {
16586       s_cons (2);
16587       return;
16588     }
16589
16590   si = seg_info (now_seg);
16591   l = si->label_list;
16592   mips_emit_delays ();
16593   if (auto_align)
16594     mips_align (2, 0, l);
16595
16596   expression (&ex);
16597   mips_clear_insn_labels ();
16598
16599   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16600     {
16601       as_bad (_("unsupported use of .gpword"));
16602       ignore_rest_of_line ();
16603     }
16604
16605   p = frag_more (4);
16606   md_number_to_chars (p, 0, 4);
16607   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16608                BFD_RELOC_GPREL32);
16609
16610   demand_empty_rest_of_line ();
16611 }
16612
16613 static void
16614 s_gpdword (int ignore ATTRIBUTE_UNUSED)
16615 {
16616   segment_info_type *si;
16617   struct insn_label_list *l;
16618   expressionS ex;
16619   char *p;
16620
16621   /* When not generating PIC code, this is treated as .dword.  */
16622   if (mips_pic != SVR4_PIC)
16623     {
16624       s_cons (3);
16625       return;
16626     }
16627
16628   si = seg_info (now_seg);
16629   l = si->label_list;
16630   mips_emit_delays ();
16631   if (auto_align)
16632     mips_align (3, 0, l);
16633
16634   expression (&ex);
16635   mips_clear_insn_labels ();
16636
16637   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16638     {
16639       as_bad (_("unsupported use of .gpdword"));
16640       ignore_rest_of_line ();
16641     }
16642
16643   p = frag_more (8);
16644   md_number_to_chars (p, 0, 8);
16645   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16646                BFD_RELOC_GPREL32)->fx_tcbit = 1;
16647
16648   /* GPREL32 composed with 64 gives a 64-bit GP offset.  */
16649   fix_new (frag_now, p - frag_now->fr_literal, 8, NULL, 0,
16650            FALSE, BFD_RELOC_64)->fx_tcbit = 1;
16651
16652   demand_empty_rest_of_line ();
16653 }
16654
16655 /* Handle the .ehword pseudo-op.  This is used when generating unwinding
16656    tables.  It generates a R_MIPS_EH reloc.  */
16657
16658 static void
16659 s_ehword (int ignore ATTRIBUTE_UNUSED)
16660 {
16661   expressionS ex;
16662   char *p;
16663
16664   mips_emit_delays ();
16665
16666   expression (&ex);
16667   mips_clear_insn_labels ();
16668
16669   if (ex.X_op != O_symbol || ex.X_add_number != 0)
16670     {
16671       as_bad (_("unsupported use of .ehword"));
16672       ignore_rest_of_line ();
16673     }
16674
16675   p = frag_more (4);
16676   md_number_to_chars (p, 0, 4);
16677   fix_new_exp (frag_now, p - frag_now->fr_literal, 4, &ex, FALSE,
16678                BFD_RELOC_32_PCREL);
16679
16680   demand_empty_rest_of_line ();
16681 }
16682
16683 /* Handle the .cpadd pseudo-op.  This is used when dealing with switch
16684    tables in SVR4 PIC code.  */
16685
16686 static void
16687 s_cpadd (int ignore ATTRIBUTE_UNUSED)
16688 {
16689   int reg;
16690
16691   file_mips_check_options ();
16692
16693   /* This is ignored when not generating SVR4 PIC code.  */
16694   if (mips_pic != SVR4_PIC)
16695     {
16696       s_ignore (0);
16697       return;
16698     }
16699
16700   mips_mark_labels ();
16701   mips_assembling_insn = TRUE;
16702
16703   /* Add $gp to the register named as an argument.  */
16704   macro_start ();
16705   reg = tc_get_register (0);
16706   macro_build (NULL, ADDRESS_ADD_INSN, "d,v,t", reg, reg, mips_gp_register);
16707   macro_end ();
16708
16709   mips_assembling_insn = FALSE;
16710   demand_empty_rest_of_line ();
16711 }
16712
16713 /* Handle the .insn pseudo-op.  This marks instruction labels in
16714    mips16/micromips mode.  This permits the linker to handle them specially,
16715    such as generating jalx instructions when needed.  We also make
16716    them odd for the duration of the assembly, in order to generate the
16717    right sort of code.  We will make them even in the adjust_symtab
16718    routine, while leaving them marked.  This is convenient for the
16719    debugger and the disassembler.  The linker knows to make them odd
16720    again.  */
16721
16722 static void
16723 s_insn (int ignore ATTRIBUTE_UNUSED)
16724 {
16725   file_mips_check_options ();
16726   file_ase_mips16 |= mips_opts.mips16;
16727   file_ase_micromips |= mips_opts.micromips;
16728
16729   mips_mark_labels ();
16730
16731   demand_empty_rest_of_line ();
16732 }
16733
16734 /* Handle the .nan pseudo-op.  */
16735
16736 static void
16737 s_nan (int ignore ATTRIBUTE_UNUSED)
16738 {
16739   static const char str_legacy[] = "legacy";
16740   static const char str_2008[] = "2008";
16741   size_t i;
16742
16743   for (i = 0; !is_end_of_line[(unsigned char) input_line_pointer[i]]; i++);
16744
16745   if (i == sizeof (str_2008) - 1
16746       && memcmp (input_line_pointer, str_2008, i) == 0)
16747     mips_nan2008 = 1;
16748   else if (i == sizeof (str_legacy) - 1
16749            && memcmp (input_line_pointer, str_legacy, i) == 0)
16750     {
16751       if (ISA_HAS_LEGACY_NAN (file_mips_opts.isa))
16752         mips_nan2008 = 0;
16753       else
16754         as_bad (_("`%s' does not support legacy NaN"),
16755                   mips_cpu_info_from_isa (file_mips_opts.isa)->name);
16756     }
16757   else
16758     as_bad (_("bad .nan directive"));
16759
16760   input_line_pointer += i;
16761   demand_empty_rest_of_line ();
16762 }
16763
16764 /* Handle a .stab[snd] directive.  Ideally these directives would be
16765    implemented in a transparent way, so that removing them would not
16766    have any effect on the generated instructions.  However, s_stab
16767    internally changes the section, so in practice we need to decide
16768    now whether the preceding label marks compressed code.  We do not
16769    support changing the compression mode of a label after a .stab*
16770    directive, such as in:
16771
16772    foo:
16773         .stabs ...
16774         .set mips16
16775
16776    so the current mode wins.  */
16777
16778 static void
16779 s_mips_stab (int type)
16780 {
16781   mips_mark_labels ();
16782   s_stab (type);
16783 }
16784
16785 /* Handle the .weakext pseudo-op as defined in Kane and Heinrich.  */
16786
16787 static void
16788 s_mips_weakext (int ignore ATTRIBUTE_UNUSED)
16789 {
16790   char *name;
16791   int c;
16792   symbolS *symbolP;
16793   expressionS exp;
16794
16795   c = get_symbol_name (&name);
16796   symbolP = symbol_find_or_make (name);
16797   S_SET_WEAK (symbolP);
16798   *input_line_pointer = c;
16799
16800   SKIP_WHITESPACE_AFTER_NAME ();
16801
16802   if (! is_end_of_line[(unsigned char) *input_line_pointer])
16803     {
16804       if (S_IS_DEFINED (symbolP))
16805         {
16806           as_bad (_("ignoring attempt to redefine symbol %s"),
16807                   S_GET_NAME (symbolP));
16808           ignore_rest_of_line ();
16809           return;
16810         }
16811
16812       if (*input_line_pointer == ',')
16813         {
16814           ++input_line_pointer;
16815           SKIP_WHITESPACE ();
16816         }
16817
16818       expression (&exp);
16819       if (exp.X_op != O_symbol)
16820         {
16821           as_bad (_("bad .weakext directive"));
16822           ignore_rest_of_line ();
16823           return;
16824         }
16825       symbol_set_value_expression (symbolP, &exp);
16826     }
16827
16828   demand_empty_rest_of_line ();
16829 }
16830
16831 /* Parse a register string into a number.  Called from the ECOFF code
16832    to parse .frame.  The argument is non-zero if this is the frame
16833    register, so that we can record it in mips_frame_reg.  */
16834
16835 int
16836 tc_get_register (int frame)
16837 {
16838   unsigned int reg;
16839
16840   SKIP_WHITESPACE ();
16841   if (! reg_lookup (&input_line_pointer, RWARN | RTYPE_NUM | RTYPE_GP, &reg))
16842     reg = 0;
16843   if (frame)
16844     {
16845       mips_frame_reg = reg != 0 ? reg : SP;
16846       mips_frame_reg_valid = 1;
16847       mips_cprestore_valid = 0;
16848     }
16849   return reg;
16850 }
16851
16852 valueT
16853 md_section_align (asection *seg, valueT addr)
16854 {
16855   int align = bfd_get_section_alignment (stdoutput, seg);
16856
16857   /* We don't need to align ELF sections to the full alignment.
16858      However, Irix 5 may prefer that we align them at least to a 16
16859      byte boundary.  We don't bother to align the sections if we
16860      are targeted for an embedded system.  */
16861   if (strncmp (TARGET_OS, "elf", 3) == 0)
16862     return addr;
16863   if (align > 4)
16864     align = 4;
16865
16866   return ((addr + (1 << align) - 1) & -(1 << align));
16867 }
16868
16869 /* Utility routine, called from above as well.  If called while the
16870    input file is still being read, it's only an approximation.  (For
16871    example, a symbol may later become defined which appeared to be
16872    undefined earlier.)  */
16873
16874 static int
16875 nopic_need_relax (symbolS *sym, int before_relaxing)
16876 {
16877   if (sym == 0)
16878     return 0;
16879
16880   if (g_switch_value > 0)
16881     {
16882       const char *symname;
16883       int change;
16884
16885       /* Find out whether this symbol can be referenced off the $gp
16886          register.  It can be if it is smaller than the -G size or if
16887          it is in the .sdata or .sbss section.  Certain symbols can
16888          not be referenced off the $gp, although it appears as though
16889          they can.  */
16890       symname = S_GET_NAME (sym);
16891       if (symname != (const char *) NULL
16892           && (strcmp (symname, "eprol") == 0
16893               || strcmp (symname, "etext") == 0
16894               || strcmp (symname, "_gp") == 0
16895               || strcmp (symname, "edata") == 0
16896               || strcmp (symname, "_fbss") == 0
16897               || strcmp (symname, "_fdata") == 0
16898               || strcmp (symname, "_ftext") == 0
16899               || strcmp (symname, "end") == 0
16900               || strcmp (symname, "_gp_disp") == 0))
16901         change = 1;
16902       else if ((! S_IS_DEFINED (sym) || S_IS_COMMON (sym))
16903                && (0
16904 #ifndef NO_ECOFF_DEBUGGING
16905                    || (symbol_get_obj (sym)->ecoff_extern_size != 0
16906                        && (symbol_get_obj (sym)->ecoff_extern_size
16907                            <= g_switch_value))
16908 #endif
16909                    /* We must defer this decision until after the whole
16910                       file has been read, since there might be a .extern
16911                       after the first use of this symbol.  */
16912                    || (before_relaxing
16913 #ifndef NO_ECOFF_DEBUGGING
16914                        && symbol_get_obj (sym)->ecoff_extern_size == 0
16915 #endif
16916                        && S_GET_VALUE (sym) == 0)
16917                    || (S_GET_VALUE (sym) != 0
16918                        && S_GET_VALUE (sym) <= g_switch_value)))
16919         change = 0;
16920       else
16921         {
16922           const char *segname;
16923
16924           segname = segment_name (S_GET_SEGMENT (sym));
16925           gas_assert (strcmp (segname, ".lit8") != 0
16926                   && strcmp (segname, ".lit4") != 0);
16927           change = (strcmp (segname, ".sdata") != 0
16928                     && strcmp (segname, ".sbss") != 0
16929                     && strncmp (segname, ".sdata.", 7) != 0
16930                     && strncmp (segname, ".sbss.", 6) != 0
16931                     && strncmp (segname, ".gnu.linkonce.sb.", 17) != 0
16932                     && strncmp (segname, ".gnu.linkonce.s.", 16) != 0);
16933         }
16934       return change;
16935     }
16936   else
16937     /* We are not optimizing for the $gp register.  */
16938     return 1;
16939 }
16940
16941
16942 /* Return true if the given symbol should be considered local for SVR4 PIC.  */
16943
16944 static bfd_boolean
16945 pic_need_relax (symbolS *sym, asection *segtype)
16946 {
16947   asection *symsec;
16948
16949   /* Handle the case of a symbol equated to another symbol.  */
16950   while (symbol_equated_reloc_p (sym))
16951     {
16952       symbolS *n;
16953
16954       /* It's possible to get a loop here in a badly written program.  */
16955       n = symbol_get_value_expression (sym)->X_add_symbol;
16956       if (n == sym)
16957         break;
16958       sym = n;
16959     }
16960
16961   if (symbol_section_p (sym))
16962     return TRUE;
16963
16964   symsec = S_GET_SEGMENT (sym);
16965
16966   /* This must duplicate the test in adjust_reloc_syms.  */
16967   return (!bfd_is_und_section (symsec)
16968           && !bfd_is_abs_section (symsec)
16969           && !bfd_is_com_section (symsec)
16970           && !s_is_linkonce (sym, segtype)
16971           /* A global or weak symbol is treated as external.  */
16972           && (!S_IS_WEAK (sym) && !S_IS_EXTERNAL (sym)));
16973 }
16974
16975
16976 /* Given a mips16 variant frag FRAGP, return non-zero if it needs an
16977    extended opcode.  SEC is the section the frag is in.  */
16978
16979 static int
16980 mips16_extended_frag (fragS *fragp, asection *sec, long stretch)
16981 {
16982   int type;
16983   const struct mips_int_operand *operand;
16984   offsetT val;
16985   segT symsec;
16986   fragS *sym_frag;
16987
16988   if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
16989     return 0;
16990   if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
16991     return 1;
16992
16993   symsec = S_GET_SEGMENT (fragp->fr_symbol);
16994   type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
16995   operand = mips16_immed_operand (type, FALSE);
16996   if (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
16997       || (operand->root.type == OP_PCREL
16998           ? sec != symsec
16999           : !bfd_is_abs_section (symsec)))
17000     return 1;
17001
17002   sym_frag = symbol_get_frag (fragp->fr_symbol);
17003   val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17004
17005   if (operand->root.type == OP_PCREL)
17006     {
17007       const struct mips_pcrel_operand *pcrel_op;
17008       addressT addr;
17009       offsetT maxtiny;
17010
17011       if (RELAX_MIPS16_LONG_BRANCH (fragp->fr_subtype))
17012         return 1;
17013
17014       pcrel_op = (const struct mips_pcrel_operand *) operand;
17015
17016       /* If the relax_marker of the symbol fragment differs from the
17017          relax_marker of this fragment, we have not yet adjusted the
17018          symbol fragment fr_address.  We want to add in STRETCH in
17019          order to get a better estimate of the address.  This
17020          particularly matters because of the shift bits.  */
17021       if (stretch != 0
17022           && sym_frag->relax_marker != fragp->relax_marker)
17023         {
17024           fragS *f;
17025
17026           /* Adjust stretch for any alignment frag.  Note that if have
17027              been expanding the earlier code, the symbol may be
17028              defined in what appears to be an earlier frag.  FIXME:
17029              This doesn't handle the fr_subtype field, which specifies
17030              a maximum number of bytes to skip when doing an
17031              alignment.  */
17032           for (f = fragp; f != NULL && f != sym_frag; f = f->fr_next)
17033             {
17034               if (f->fr_type == rs_align || f->fr_type == rs_align_code)
17035                 {
17036                   if (stretch < 0)
17037                     stretch = - ((- stretch)
17038                                  & ~ ((1 << (int) f->fr_offset) - 1));
17039                   else
17040                     stretch &= ~ ((1 << (int) f->fr_offset) - 1);
17041                   if (stretch == 0)
17042                     break;
17043                 }
17044             }
17045           if (f != NULL)
17046             val += stretch;
17047         }
17048
17049       addr = fragp->fr_address + fragp->fr_fix;
17050
17051       /* The base address rules are complicated.  The base address of
17052          a branch is the following instruction.  The base address of a
17053          PC relative load or add is the instruction itself, but if it
17054          is in a delay slot (in which case it can not be extended) use
17055          the address of the instruction whose delay slot it is in.  */
17056       if (pcrel_op->include_isa_bit)
17057         {
17058           addr += 2;
17059
17060           /* If we are currently assuming that this frag should be
17061              extended, then, the current address is two bytes
17062              higher.  */
17063           if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17064             addr += 2;
17065
17066           /* Ignore the low bit in the target, since it will be set
17067              for a text label.  */
17068           val &= -2;
17069         }
17070       else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
17071         addr -= 4;
17072       else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
17073         addr -= 2;
17074
17075       val -= addr & -(1 << pcrel_op->align_log2);
17076
17077       /* If any of the shifted bits are set, we must use an extended
17078          opcode.  If the address depends on the size of this
17079          instruction, this can lead to a loop, so we arrange to always
17080          use an extended opcode.  */
17081       if ((val & ((1 << operand->shift) - 1)) != 0)
17082         {
17083           fragp->fr_subtype =
17084             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17085           return 1;
17086         }
17087
17088       /* If we are about to mark a frag as extended because the value
17089          is precisely the next value above maxtiny, then there is a
17090          chance of an infinite loop as in the following code:
17091              la $4,foo
17092              .skip      1020
17093              .align     2
17094            foo:
17095          In this case when the la is extended, foo is 0x3fc bytes
17096          away, so the la can be shrunk, but then foo is 0x400 away, so
17097          the la must be extended.  To avoid this loop, we mark the
17098          frag as extended if it was small, and is about to become
17099          extended with the next value above maxtiny.  */
17100       maxtiny = mips_int_operand_max (operand);
17101       if (val == maxtiny + (1 << operand->shift)
17102           && ! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17103         {
17104           fragp->fr_subtype =
17105             RELAX_MIPS16_MARK_LONG_BRANCH (fragp->fr_subtype);
17106           return 1;
17107         }
17108     }
17109
17110   return !mips16_immed_in_range_p (operand, BFD_RELOC_UNUSED, val);
17111 }
17112
17113 /* Compute the length of a branch sequence, and adjust the
17114    RELAX_BRANCH_TOOFAR bit accordingly.  If FRAGP is NULL, the
17115    worst-case length is computed, with UPDATE being used to indicate
17116    whether an unconditional (-1), branch-likely (+1) or regular (0)
17117    branch is to be computed.  */
17118 static int
17119 relaxed_branch_length (fragS *fragp, asection *sec, int update)
17120 {
17121   bfd_boolean toofar;
17122   int length;
17123
17124   if (fragp
17125       && S_IS_DEFINED (fragp->fr_symbol)
17126       && !S_IS_WEAK (fragp->fr_symbol)
17127       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17128     {
17129       addressT addr;
17130       offsetT val;
17131
17132       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17133
17134       addr = fragp->fr_address + fragp->fr_fix + 4;
17135
17136       val -= addr;
17137
17138       toofar = val < - (0x8000 << 2) || val >= (0x8000 << 2);
17139     }
17140   else
17141     /* If the symbol is not defined or it's in a different segment,
17142        we emit the long sequence.  */
17143     toofar = TRUE;
17144
17145   if (fragp && update && toofar != RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17146     fragp->fr_subtype
17147       = RELAX_BRANCH_ENCODE (RELAX_BRANCH_AT (fragp->fr_subtype),
17148                              RELAX_BRANCH_UNCOND (fragp->fr_subtype),
17149                              RELAX_BRANCH_LIKELY (fragp->fr_subtype),
17150                              RELAX_BRANCH_LINK (fragp->fr_subtype),
17151                              toofar);
17152
17153   length = 4;
17154   if (toofar)
17155     {
17156       if (fragp ? RELAX_BRANCH_LIKELY (fragp->fr_subtype) : (update > 0))
17157         length += 8;
17158
17159       if (mips_pic != NO_PIC)
17160         {
17161           /* Additional space for PIC loading of target address.  */
17162           length += 8;
17163           if (mips_opts.isa == ISA_MIPS1)
17164             /* Additional space for $at-stabilizing nop.  */
17165             length += 4;
17166         }
17167
17168       /* If branch is conditional.  */
17169       if (fragp ? !RELAX_BRANCH_UNCOND (fragp->fr_subtype) : (update >= 0))
17170         length += 8;
17171     }
17172
17173   return length;
17174 }
17175
17176 /* Compute the length of a branch sequence, and adjust the
17177    RELAX_MICROMIPS_TOOFAR32 bit accordingly.  If FRAGP is NULL, the
17178    worst-case length is computed, with UPDATE being used to indicate
17179    whether an unconditional (-1), or regular (0) branch is to be
17180    computed.  */
17181
17182 static int
17183 relaxed_micromips_32bit_branch_length (fragS *fragp, asection *sec, int update)
17184 {
17185   bfd_boolean toofar;
17186   int length;
17187
17188   if (fragp
17189       && S_IS_DEFINED (fragp->fr_symbol)
17190       && !S_IS_WEAK (fragp->fr_symbol)
17191       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17192     {
17193       addressT addr;
17194       offsetT val;
17195
17196       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17197       /* Ignore the low bit in the target, since it will be set
17198          for a text label.  */
17199       if ((val & 1) != 0)
17200         --val;
17201
17202       addr = fragp->fr_address + fragp->fr_fix + 4;
17203
17204       val -= addr;
17205
17206       toofar = val < - (0x8000 << 1) || val >= (0x8000 << 1);
17207     }
17208   else
17209     /* If the symbol is not defined or it's in a different segment,
17210        we emit the long sequence.  */
17211     toofar = TRUE;
17212
17213   if (fragp && update
17214       && toofar != RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17215     fragp->fr_subtype = (toofar
17216                          ? RELAX_MICROMIPS_MARK_TOOFAR32 (fragp->fr_subtype)
17217                          : RELAX_MICROMIPS_CLEAR_TOOFAR32 (fragp->fr_subtype));
17218
17219   length = 4;
17220   if (toofar)
17221     {
17222       bfd_boolean compact_known = fragp != NULL;
17223       bfd_boolean compact = FALSE;
17224       bfd_boolean uncond;
17225
17226       if (compact_known)
17227         compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17228       if (fragp)
17229         uncond = RELAX_MICROMIPS_UNCOND (fragp->fr_subtype);
17230       else
17231         uncond = update < 0;
17232
17233       /* If label is out of range, we turn branch <br>:
17234
17235                 <br>    label                   # 4 bytes
17236             0:
17237
17238          into:
17239
17240                 j       label                   # 4 bytes
17241                 nop                             # 2 bytes if compact && !PIC
17242             0:
17243        */
17244       if (mips_pic == NO_PIC && (!compact_known || compact))
17245         length += 2;
17246
17247       /* If assembling PIC code, we further turn:
17248
17249                         j       label                   # 4 bytes
17250
17251          into:
17252
17253                         lw/ld   at, %got(label)(gp)     # 4 bytes
17254                         d/addiu at, %lo(label)          # 4 bytes
17255                         jr/c    at                      # 2 bytes
17256        */
17257       if (mips_pic != NO_PIC)
17258         length += 6;
17259
17260       /* If branch <br> is conditional, we prepend negated branch <brneg>:
17261
17262                         <brneg> 0f                      # 4 bytes
17263                         nop                             # 2 bytes if !compact
17264        */
17265       if (!uncond)
17266         length += (compact_known && compact) ? 4 : 6;
17267     }
17268
17269   return length;
17270 }
17271
17272 /* Compute the length of a branch, and adjust the RELAX_MICROMIPS_TOOFAR16
17273    bit accordingly.  */
17274
17275 static int
17276 relaxed_micromips_16bit_branch_length (fragS *fragp, asection *sec, int update)
17277 {
17278   bfd_boolean toofar;
17279
17280   if (fragp
17281       && S_IS_DEFINED (fragp->fr_symbol)
17282       && !S_IS_WEAK (fragp->fr_symbol)
17283       && sec == S_GET_SEGMENT (fragp->fr_symbol))
17284     {
17285       addressT addr;
17286       offsetT val;
17287       int type;
17288
17289       val = S_GET_VALUE (fragp->fr_symbol) + fragp->fr_offset;
17290       /* Ignore the low bit in the target, since it will be set
17291          for a text label.  */
17292       if ((val & 1) != 0)
17293         --val;
17294
17295       /* Assume this is a 2-byte branch.  */
17296       addr = fragp->fr_address + fragp->fr_fix + 2;
17297
17298       /* We try to avoid the infinite loop by not adding 2 more bytes for
17299          long branches.  */
17300
17301       val -= addr;
17302
17303       type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17304       if (type == 'D')
17305         toofar = val < - (0x200 << 1) || val >= (0x200 << 1);
17306       else if (type == 'E')
17307         toofar = val < - (0x40 << 1) || val >= (0x40 << 1);
17308       else
17309         abort ();
17310     }
17311   else
17312     /* If the symbol is not defined or it's in a different segment,
17313        we emit a normal 32-bit branch.  */
17314     toofar = TRUE;
17315
17316   if (fragp && update
17317       && toofar != RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17318     fragp->fr_subtype
17319       = toofar ? RELAX_MICROMIPS_MARK_TOOFAR16 (fragp->fr_subtype)
17320                : RELAX_MICROMIPS_CLEAR_TOOFAR16 (fragp->fr_subtype);
17321
17322   if (toofar)
17323     return 4;
17324
17325   return 2;
17326 }
17327
17328 /* Estimate the size of a frag before relaxing.  Unless this is the
17329    mips16, we are not really relaxing here, and the final size is
17330    encoded in the subtype information.  For the mips16, we have to
17331    decide whether we are using an extended opcode or not.  */
17332
17333 int
17334 md_estimate_size_before_relax (fragS *fragp, asection *segtype)
17335 {
17336   int change;
17337
17338   if (RELAX_BRANCH_P (fragp->fr_subtype))
17339     {
17340
17341       fragp->fr_var = relaxed_branch_length (fragp, segtype, FALSE);
17342
17343       return fragp->fr_var;
17344     }
17345
17346   if (RELAX_MIPS16_P (fragp->fr_subtype))
17347     /* We don't want to modify the EXTENDED bit here; it might get us
17348        into infinite loops.  We change it only in mips_relax_frag().  */
17349     return (RELAX_MIPS16_EXTENDED (fragp->fr_subtype) ? 4 : 2);
17350
17351   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17352     {
17353       int length = 4;
17354
17355       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17356         length = relaxed_micromips_16bit_branch_length (fragp, segtype, FALSE);
17357       if (length == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17358         length = relaxed_micromips_32bit_branch_length (fragp, segtype, FALSE);
17359       fragp->fr_var = length;
17360
17361       return length;
17362     }
17363
17364   if (mips_pic == NO_PIC)
17365     change = nopic_need_relax (fragp->fr_symbol, 0);
17366   else if (mips_pic == SVR4_PIC)
17367     change = pic_need_relax (fragp->fr_symbol, segtype);
17368   else if (mips_pic == VXWORKS_PIC)
17369     /* For vxworks, GOT16 relocations never have a corresponding LO16.  */
17370     change = 0;
17371   else
17372     abort ();
17373
17374   if (change)
17375     {
17376       fragp->fr_subtype |= RELAX_USE_SECOND;
17377       return -RELAX_FIRST (fragp->fr_subtype);
17378     }
17379   else
17380     return -RELAX_SECOND (fragp->fr_subtype);
17381 }
17382
17383 /* This is called to see whether a reloc against a defined symbol
17384    should be converted into a reloc against a section.  */
17385
17386 int
17387 mips_fix_adjustable (fixS *fixp)
17388 {
17389   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
17390       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17391     return 0;
17392
17393   if (fixp->fx_addsy == NULL)
17394     return 1;
17395
17396   /* Allow relocs used for EH tables.  */
17397   if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
17398     return 1;
17399
17400   /* If symbol SYM is in a mergeable section, relocations of the form
17401      SYM + 0 can usually be made section-relative.  The mergeable data
17402      is then identified by the section offset rather than by the symbol.
17403
17404      However, if we're generating REL LO16 relocations, the offset is split
17405      between the LO16 and parterning high part relocation.  The linker will
17406      need to recalculate the complete offset in order to correctly identify
17407      the merge data.
17408
17409      The linker has traditionally not looked for the parterning high part
17410      relocation, and has thus allowed orphaned R_MIPS_LO16 relocations to be
17411      placed anywhere.  Rather than break backwards compatibility by changing
17412      this, it seems better not to force the issue, and instead keep the
17413      original symbol.  This will work with either linker behavior.  */
17414   if ((lo16_reloc_p (fixp->fx_r_type)
17415        || reloc_needs_lo_p (fixp->fx_r_type))
17416       && HAVE_IN_PLACE_ADDENDS
17417       && (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE) != 0)
17418     return 0;
17419
17420   /* There is no place to store an in-place offset for JALR relocations.  */
17421   if (jalr_reloc_p (fixp->fx_r_type) && HAVE_IN_PLACE_ADDENDS)
17422     return 0;
17423
17424   /* Likewise an in-range offset of limited PC-relative relocations may
17425      overflow the in-place relocatable field if recalculated against the
17426      start address of the symbol's containing section.
17427
17428      Also, PC relative relocations for MIPS R6 need to be symbol rather than
17429      section relative to allow linker relaxations to be performed later on.  */
17430   if (limited_pcrel_reloc_p (fixp->fx_r_type)
17431       && (HAVE_IN_PLACE_ADDENDS || ISA_IS_R6 (file_mips_opts.isa)))
17432     return 0;
17433
17434   /* R_MIPS16_26 relocations against non-MIPS16 functions might resolve
17435      to a floating-point stub.  The same is true for non-R_MIPS16_26
17436      relocations against MIPS16 functions; in this case, the stub becomes
17437      the function's canonical address.
17438
17439      Floating-point stubs are stored in unique .mips16.call.* or
17440      .mips16.fn.* sections.  If a stub T for function F is in section S,
17441      the first relocation in section S must be against F; this is how the
17442      linker determines the target function.  All relocations that might
17443      resolve to T must also be against F.  We therefore have the following
17444      restrictions, which are given in an intentionally-redundant way:
17445
17446        1. We cannot reduce R_MIPS16_26 relocations against non-MIPS16
17447           symbols.
17448
17449        2. We cannot reduce a stub's relocations against non-MIPS16 symbols
17450           if that stub might be used.
17451
17452        3. We cannot reduce non-R_MIPS16_26 relocations against MIPS16
17453           symbols.
17454
17455        4. We cannot reduce a stub's relocations against MIPS16 symbols if
17456           that stub might be used.
17457
17458      There is a further restriction:
17459
17460        5. We cannot reduce jump relocations (R_MIPS_26, R_MIPS16_26 or
17461           R_MICROMIPS_26_S1) or branch relocations (R_MIPS_PC26_S2,
17462           R_MIPS_PC21_S2, R_MIPS_PC16, R_MIPS16_PC16_S1,
17463           R_MICROMIPS_PC16_S1, R_MICROMIPS_PC10_S1 or R_MICROMIPS_PC7_S1)
17464           against MIPS16 or microMIPS symbols because we need to keep the
17465           MIPS16 or microMIPS symbol for the purpose of mode mismatch
17466           detection and JAL to JALX instruction conversion in the linker.
17467
17468      For simplicity, we deal with (3)-(4) by not reducing _any_ relocation
17469      against a MIPS16 symbol.  We deal with (5) by additionally leaving
17470      alone any jump and branch relocations against a microMIPS symbol.
17471
17472      We deal with (1)-(2) by saying that, if there's a R_MIPS16_26
17473      relocation against some symbol R, no relocation against R may be
17474      reduced.  (Note that this deals with (2) as well as (1) because
17475      relocations against global symbols will never be reduced on ELF
17476      targets.)  This approach is a little simpler than trying to detect
17477      stub sections, and gives the "all or nothing" per-symbol consistency
17478      that we have for MIPS16 symbols.  */
17479   if (fixp->fx_subsy == NULL
17480       && (ELF_ST_IS_MIPS16 (S_GET_OTHER (fixp->fx_addsy))
17481           || (ELF_ST_IS_MICROMIPS (S_GET_OTHER (fixp->fx_addsy))
17482               && (jmp_reloc_p (fixp->fx_r_type)
17483                   || b_reloc_p (fixp->fx_r_type)))
17484           || *symbol_get_tc (fixp->fx_addsy)))
17485     return 0;
17486
17487   return 1;
17488 }
17489
17490 /* Translate internal representation of relocation info to BFD target
17491    format.  */
17492
17493 arelent **
17494 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
17495 {
17496   static arelent *retval[4];
17497   arelent *reloc;
17498   bfd_reloc_code_real_type code;
17499
17500   memset (retval, 0, sizeof(retval));
17501   reloc = retval[0] = XCNEW (arelent);
17502   reloc->sym_ptr_ptr = XNEW (asymbol *);
17503   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
17504   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
17505
17506   if (fixp->fx_pcrel)
17507     {
17508       gas_assert (fixp->fx_r_type == BFD_RELOC_16_PCREL_S2
17509                   || fixp->fx_r_type == BFD_RELOC_MIPS16_16_PCREL_S1
17510                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_7_PCREL_S1
17511                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_10_PCREL_S1
17512                   || fixp->fx_r_type == BFD_RELOC_MICROMIPS_16_PCREL_S1
17513                   || fixp->fx_r_type == BFD_RELOC_32_PCREL
17514                   || fixp->fx_r_type == BFD_RELOC_MIPS_21_PCREL_S2
17515                   || fixp->fx_r_type == BFD_RELOC_MIPS_26_PCREL_S2
17516                   || fixp->fx_r_type == BFD_RELOC_MIPS_18_PCREL_S3
17517                   || fixp->fx_r_type == BFD_RELOC_MIPS_19_PCREL_S2
17518                   || fixp->fx_r_type == BFD_RELOC_HI16_S_PCREL
17519                   || fixp->fx_r_type == BFD_RELOC_LO16_PCREL);
17520
17521       /* At this point, fx_addnumber is "symbol offset - pcrel address".
17522          Relocations want only the symbol offset.  */
17523       switch (fixp->fx_r_type)
17524         {
17525         case BFD_RELOC_MIPS_18_PCREL_S3:
17526           reloc->addend = fixp->fx_addnumber + (reloc->address & ~7);
17527           break;
17528         default:
17529           reloc->addend = fixp->fx_addnumber + reloc->address;
17530           break;
17531         }
17532     }
17533   else if (HAVE_IN_PLACE_ADDENDS
17534            && fixp->fx_r_type == BFD_RELOC_MICROMIPS_JMP
17535            && (read_compressed_insn (fixp->fx_frag->fr_literal
17536                                      + fixp->fx_where, 4) >> 26) == 0x3c)
17537     {
17538       /* Shift is 2, unusually, for microMIPS JALX.  Adjust the in-place
17539          addend accordingly.  */
17540       reloc->addend = fixp->fx_addnumber >> 1;
17541     }
17542   else
17543     reloc->addend = fixp->fx_addnumber;
17544
17545   /* Since the old MIPS ELF ABI uses Rel instead of Rela, encode the vtable
17546      entry to be used in the relocation's section offset.  */
17547   if (! HAVE_NEWABI && fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
17548     {
17549       reloc->address = reloc->addend;
17550       reloc->addend = 0;
17551     }
17552
17553   code = fixp->fx_r_type;
17554
17555   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
17556   if (reloc->howto == NULL)
17557     {
17558       as_bad_where (fixp->fx_file, fixp->fx_line,
17559                     _("cannot represent %s relocation in this object file"
17560                       " format"),
17561                     bfd_get_reloc_code_name (code));
17562       retval[0] = NULL;
17563     }
17564
17565   return retval;
17566 }
17567
17568 /* Relax a machine dependent frag.  This returns the amount by which
17569    the current size of the frag should change.  */
17570
17571 int
17572 mips_relax_frag (asection *sec, fragS *fragp, long stretch)
17573 {
17574   if (RELAX_BRANCH_P (fragp->fr_subtype))
17575     {
17576       offsetT old_var = fragp->fr_var;
17577
17578       fragp->fr_var = relaxed_branch_length (fragp, sec, TRUE);
17579
17580       return fragp->fr_var - old_var;
17581     }
17582
17583   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17584     {
17585       offsetT old_var = fragp->fr_var;
17586       offsetT new_var = 4;
17587
17588       if (RELAX_MICROMIPS_TYPE (fragp->fr_subtype) != 0)
17589         new_var = relaxed_micromips_16bit_branch_length (fragp, sec, TRUE);
17590       if (new_var == 4 && RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype))
17591         new_var = relaxed_micromips_32bit_branch_length (fragp, sec, TRUE);
17592       fragp->fr_var = new_var;
17593
17594       return new_var - old_var;
17595     }
17596
17597   if (! RELAX_MIPS16_P (fragp->fr_subtype))
17598     return 0;
17599
17600   if (mips16_extended_frag (fragp, sec, stretch))
17601     {
17602       if (RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17603         return 0;
17604       fragp->fr_subtype = RELAX_MIPS16_MARK_EXTENDED (fragp->fr_subtype);
17605       return 2;
17606     }
17607   else
17608     {
17609       if (! RELAX_MIPS16_EXTENDED (fragp->fr_subtype))
17610         return 0;
17611       fragp->fr_subtype = RELAX_MIPS16_CLEAR_EXTENDED (fragp->fr_subtype);
17612       return -2;
17613     }
17614
17615   return 0;
17616 }
17617
17618 /* Convert a machine dependent frag.  */
17619
17620 void
17621 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec, fragS *fragp)
17622 {
17623   if (RELAX_BRANCH_P (fragp->fr_subtype))
17624     {
17625       char *buf;
17626       unsigned long insn;
17627       expressionS exp;
17628       fixS *fixp;
17629
17630       buf = fragp->fr_literal + fragp->fr_fix;
17631       insn = read_insn (buf);
17632
17633       if (!RELAX_BRANCH_TOOFAR (fragp->fr_subtype))
17634         {
17635           /* We generate a fixup instead of applying it right now
17636              because, if there are linker relaxations, we're going to
17637              need the relocations.  */
17638           exp.X_op = O_symbol;
17639           exp.X_add_symbol = fragp->fr_symbol;
17640           exp.X_add_number = fragp->fr_offset;
17641
17642           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17643                               BFD_RELOC_16_PCREL_S2);
17644           fixp->fx_file = fragp->fr_file;
17645           fixp->fx_line = fragp->fr_line;
17646
17647           buf = write_insn (buf, insn);
17648         }
17649       else
17650         {
17651           int i;
17652
17653           as_warn_where (fragp->fr_file, fragp->fr_line,
17654                          _("relaxed out-of-range branch into a jump"));
17655
17656           if (RELAX_BRANCH_UNCOND (fragp->fr_subtype))
17657             goto uncond;
17658
17659           if (!RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17660             {
17661               /* Reverse the branch.  */
17662               switch ((insn >> 28) & 0xf)
17663                 {
17664                 case 4:
17665                   if ((insn & 0xff000000) == 0x47000000
17666                       || (insn & 0xff600000) == 0x45600000)
17667                     {
17668                       /* BZ.df/BNZ.df, BZ.V/BNZ.V can have the condition
17669                          reversed by tweaking bit 23.  */
17670                       insn ^= 0x00800000;
17671                     }
17672                   else
17673                     {
17674                       /* bc[0-3][tf]l? instructions can have the condition
17675                          reversed by tweaking a single TF bit, and their
17676                          opcodes all have 0x4???????.  */
17677                       gas_assert ((insn & 0xf3e00000) == 0x41000000);
17678                       insn ^= 0x00010000;
17679                     }
17680                   break;
17681
17682                 case 0:
17683                   /* bltz       0x04000000      bgez    0x04010000
17684                      bltzal     0x04100000      bgezal  0x04110000  */
17685                   gas_assert ((insn & 0xfc0e0000) == 0x04000000);
17686                   insn ^= 0x00010000;
17687                   break;
17688
17689                 case 1:
17690                   /* beq        0x10000000      bne     0x14000000
17691                      blez       0x18000000      bgtz    0x1c000000  */
17692                   insn ^= 0x04000000;
17693                   break;
17694
17695                 default:
17696                   abort ();
17697                 }
17698             }
17699
17700           if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17701             {
17702               /* Clear the and-link bit.  */
17703               gas_assert ((insn & 0xfc1c0000) == 0x04100000);
17704
17705               /* bltzal         0x04100000      bgezal  0x04110000
17706                  bltzall        0x04120000      bgezall 0x04130000  */
17707               insn &= ~0x00100000;
17708             }
17709
17710           /* Branch over the branch (if the branch was likely) or the
17711              full jump (not likely case).  Compute the offset from the
17712              current instruction to branch to.  */
17713           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17714             i = 16;
17715           else
17716             {
17717               /* How many bytes in instructions we've already emitted?  */
17718               i = buf - fragp->fr_literal - fragp->fr_fix;
17719               /* How many bytes in instructions from here to the end?  */
17720               i = fragp->fr_var - i;
17721             }
17722           /* Convert to instruction count.  */
17723           i >>= 2;
17724           /* Branch counts from the next instruction.  */
17725           i--;
17726           insn |= i;
17727           /* Branch over the jump.  */
17728           buf = write_insn (buf, insn);
17729
17730           /* nop */
17731           buf = write_insn (buf, 0);
17732
17733           if (RELAX_BRANCH_LIKELY (fragp->fr_subtype))
17734             {
17735               /* beql $0, $0, 2f */
17736               insn = 0x50000000;
17737               /* Compute the PC offset from the current instruction to
17738                  the end of the variable frag.  */
17739               /* How many bytes in instructions we've already emitted?  */
17740               i = buf - fragp->fr_literal - fragp->fr_fix;
17741               /* How many bytes in instructions from here to the end?  */
17742               i = fragp->fr_var - i;
17743               /* Convert to instruction count.  */
17744               i >>= 2;
17745               /* Don't decrement i, because we want to branch over the
17746                  delay slot.  */
17747               insn |= i;
17748
17749               buf = write_insn (buf, insn);
17750               buf = write_insn (buf, 0);
17751             }
17752
17753         uncond:
17754           if (mips_pic == NO_PIC)
17755             {
17756               /* j or jal.  */
17757               insn = (RELAX_BRANCH_LINK (fragp->fr_subtype)
17758                       ? 0x0c000000 : 0x08000000);
17759               exp.X_op = O_symbol;
17760               exp.X_add_symbol = fragp->fr_symbol;
17761               exp.X_add_number = fragp->fr_offset;
17762
17763               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17764                                   FALSE, BFD_RELOC_MIPS_JMP);
17765               fixp->fx_file = fragp->fr_file;
17766               fixp->fx_line = fragp->fr_line;
17767
17768               buf = write_insn (buf, insn);
17769             }
17770           else
17771             {
17772               unsigned long at = RELAX_BRANCH_AT (fragp->fr_subtype);
17773
17774               /* lw/ld $at, <sym>($gp)  R_MIPS_GOT16 */
17775               insn = HAVE_64BIT_ADDRESSES ? 0xdf800000 : 0x8f800000;
17776               insn |= at << OP_SH_RT;
17777               exp.X_op = O_symbol;
17778               exp.X_add_symbol = fragp->fr_symbol;
17779               exp.X_add_number = fragp->fr_offset;
17780
17781               if (fragp->fr_offset)
17782                 {
17783                   exp.X_add_symbol = make_expr_symbol (&exp);
17784                   exp.X_add_number = 0;
17785                 }
17786
17787               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17788                                   FALSE, BFD_RELOC_MIPS_GOT16);
17789               fixp->fx_file = fragp->fr_file;
17790               fixp->fx_line = fragp->fr_line;
17791
17792               buf = write_insn (buf, insn);
17793
17794               if (mips_opts.isa == ISA_MIPS1)
17795                 /* nop */
17796                 buf = write_insn (buf, 0);
17797
17798               /* d/addiu $at, $at, <sym>  R_MIPS_LO16 */
17799               insn = HAVE_64BIT_ADDRESSES ? 0x64000000 : 0x24000000;
17800               insn |= at << OP_SH_RS | at << OP_SH_RT;
17801
17802               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp,
17803                                   FALSE, BFD_RELOC_LO16);
17804               fixp->fx_file = fragp->fr_file;
17805               fixp->fx_line = fragp->fr_line;
17806
17807               buf = write_insn (buf, insn);
17808
17809               /* j(al)r $at.  */
17810               if (RELAX_BRANCH_LINK (fragp->fr_subtype))
17811                 insn = 0x0000f809;
17812               else
17813                 insn = 0x00000008;
17814               insn |= at << OP_SH_RS;
17815
17816               buf = write_insn (buf, insn);
17817             }
17818         }
17819
17820       fragp->fr_fix += fragp->fr_var;
17821       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17822       return;
17823     }
17824
17825   /* Relax microMIPS branches.  */
17826   if (RELAX_MICROMIPS_P (fragp->fr_subtype))
17827     {
17828       char *buf = fragp->fr_literal + fragp->fr_fix;
17829       bfd_boolean compact = RELAX_MICROMIPS_COMPACT (fragp->fr_subtype);
17830       bfd_boolean al = RELAX_MICROMIPS_LINK (fragp->fr_subtype);
17831       int type = RELAX_MICROMIPS_TYPE (fragp->fr_subtype);
17832       bfd_boolean short_ds;
17833       unsigned long insn;
17834       expressionS exp;
17835       fixS *fixp;
17836
17837       exp.X_op = O_symbol;
17838       exp.X_add_symbol = fragp->fr_symbol;
17839       exp.X_add_number = fragp->fr_offset;
17840
17841       fragp->fr_fix += fragp->fr_var;
17842
17843       /* Handle 16-bit branches that fit or are forced to fit.  */
17844       if (type != 0 && !RELAX_MICROMIPS_TOOFAR16 (fragp->fr_subtype))
17845         {
17846           /* We generate a fixup instead of applying it right now,
17847              because if there is linker relaxation, we're going to
17848              need the relocations.  */
17849           if (type == 'D')
17850             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17851                                 BFD_RELOC_MICROMIPS_10_PCREL_S1);
17852           else if (type == 'E')
17853             fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp, TRUE,
17854                                 BFD_RELOC_MICROMIPS_7_PCREL_S1);
17855           else
17856             abort ();
17857
17858           fixp->fx_file = fragp->fr_file;
17859           fixp->fx_line = fragp->fr_line;
17860
17861           /* These relocations can have an addend that won't fit in
17862              2 octets.  */
17863           fixp->fx_no_overflow = 1;
17864
17865           return;
17866         }
17867
17868       /* Handle 32-bit branches that fit or are forced to fit.  */
17869       if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17870           || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17871         {
17872           /* We generate a fixup instead of applying it right now,
17873              because if there is linker relaxation, we're going to
17874              need the relocations.  */
17875           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, TRUE,
17876                               BFD_RELOC_MICROMIPS_16_PCREL_S1);
17877           fixp->fx_file = fragp->fr_file;
17878           fixp->fx_line = fragp->fr_line;
17879
17880           if (type == 0)
17881             return;
17882         }
17883
17884       /* Relax 16-bit branches to 32-bit branches.  */
17885       if (type != 0)
17886         {
17887           insn = read_compressed_insn (buf, 2);
17888
17889           if ((insn & 0xfc00) == 0xcc00)                /* b16  */
17890             insn = 0x94000000;                          /* beq  */
17891           else if ((insn & 0xdc00) == 0x8c00)           /* beqz16/bnez16  */
17892             {
17893               unsigned long regno;
17894
17895               regno = (insn >> MICROMIPSOP_SH_MD) & MICROMIPSOP_MASK_MD;
17896               regno = micromips_to_32_reg_d_map [regno];
17897               insn = ((insn & 0x2000) << 16) | 0x94000000;      /* beq/bne  */
17898               insn |= regno << MICROMIPSOP_SH_RS;
17899             }
17900           else
17901             abort ();
17902
17903           /* Nothing else to do, just write it out.  */
17904           if (!RELAX_MICROMIPS_RELAX32 (fragp->fr_subtype)
17905               || !RELAX_MICROMIPS_TOOFAR32 (fragp->fr_subtype))
17906             {
17907               buf = write_compressed_insn (buf, insn, 4);
17908               gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
17909               return;
17910             }
17911         }
17912       else
17913         insn = read_compressed_insn (buf, 4);
17914
17915       /* Relax 32-bit branches to a sequence of instructions.  */
17916       as_warn_where (fragp->fr_file, fragp->fr_line,
17917                      _("relaxed out-of-range branch into a jump"));
17918
17919       /* Set the short-delay-slot bit.  */
17920       short_ds = al && (insn & 0x02000000) != 0;
17921
17922       if (!RELAX_MICROMIPS_UNCOND (fragp->fr_subtype))
17923         {
17924           symbolS *l;
17925
17926           /* Reverse the branch.  */
17927           if ((insn & 0xfc000000) == 0x94000000                 /* beq  */
17928               || (insn & 0xfc000000) == 0xb4000000)             /* bne  */
17929             insn ^= 0x20000000;
17930           else if ((insn & 0xffe00000) == 0x40000000            /* bltz  */
17931                    || (insn & 0xffe00000) == 0x40400000         /* bgez  */
17932                    || (insn & 0xffe00000) == 0x40800000         /* blez  */
17933                    || (insn & 0xffe00000) == 0x40c00000         /* bgtz  */
17934                    || (insn & 0xffe00000) == 0x40a00000         /* bnezc  */
17935                    || (insn & 0xffe00000) == 0x40e00000         /* beqzc  */
17936                    || (insn & 0xffe00000) == 0x40200000         /* bltzal  */
17937                    || (insn & 0xffe00000) == 0x40600000         /* bgezal  */
17938                    || (insn & 0xffe00000) == 0x42200000         /* bltzals  */
17939                    || (insn & 0xffe00000) == 0x42600000)        /* bgezals  */
17940             insn ^= 0x00400000;
17941           else if ((insn & 0xffe30000) == 0x43800000            /* bc1f  */
17942                    || (insn & 0xffe30000) == 0x43a00000         /* bc1t  */
17943                    || (insn & 0xffe30000) == 0x42800000         /* bc2f  */
17944                    || (insn & 0xffe30000) == 0x42a00000)        /* bc2t  */
17945             insn ^= 0x00200000;
17946           else if ((insn & 0xff000000) == 0x83000000            /* BZ.df
17947                                                                    BNZ.df  */
17948                     || (insn & 0xff600000) == 0x81600000)       /* BZ.V
17949                                                                    BNZ.V */
17950             insn ^= 0x00800000;
17951           else
17952             abort ();
17953
17954           if (al)
17955             {
17956               /* Clear the and-link and short-delay-slot bits.  */
17957               gas_assert ((insn & 0xfda00000) == 0x40200000);
17958
17959               /* bltzal  0x40200000     bgezal  0x40600000  */
17960               /* bltzals 0x42200000     bgezals 0x42600000  */
17961               insn &= ~0x02200000;
17962             }
17963
17964           /* Make a label at the end for use with the branch.  */
17965           l = symbol_new (micromips_label_name (), asec, fragp->fr_fix, fragp);
17966           micromips_label_inc ();
17967           S_SET_OTHER (l, ELF_ST_SET_MICROMIPS (S_GET_OTHER (l)));
17968
17969           /* Refer to it.  */
17970           fixp = fix_new (fragp, buf - fragp->fr_literal, 4, l, 0, TRUE,
17971                           BFD_RELOC_MICROMIPS_16_PCREL_S1);
17972           fixp->fx_file = fragp->fr_file;
17973           fixp->fx_line = fragp->fr_line;
17974
17975           /* Branch over the jump.  */
17976           buf = write_compressed_insn (buf, insn, 4);
17977           if (!compact)
17978             /* nop */
17979             buf = write_compressed_insn (buf, 0x0c00, 2);
17980         }
17981
17982       if (mips_pic == NO_PIC)
17983         {
17984           unsigned long jal = short_ds ? 0x74000000 : 0xf4000000; /* jal/s  */
17985
17986           /* j/jal/jals <sym>  R_MICROMIPS_26_S1  */
17987           insn = al ? jal : 0xd4000000;
17988
17989           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
17990                               BFD_RELOC_MICROMIPS_JMP);
17991           fixp->fx_file = fragp->fr_file;
17992           fixp->fx_line = fragp->fr_line;
17993
17994           buf = write_compressed_insn (buf, insn, 4);
17995           if (compact)
17996             /* nop */
17997             buf = write_compressed_insn (buf, 0x0c00, 2);
17998         }
17999       else
18000         {
18001           unsigned long at = RELAX_MICROMIPS_AT (fragp->fr_subtype);
18002           unsigned long jalr = short_ds ? 0x45e0 : 0x45c0;      /* jalr/s  */
18003           unsigned long jr = compact ? 0x45a0 : 0x4580;         /* jr/c  */
18004
18005           /* lw/ld $at, <sym>($gp)  R_MICROMIPS_GOT16  */
18006           insn = HAVE_64BIT_ADDRESSES ? 0xdc1c0000 : 0xfc1c0000;
18007           insn |= at << MICROMIPSOP_SH_RT;
18008
18009           if (exp.X_add_number)
18010             {
18011               exp.X_add_symbol = make_expr_symbol (&exp);
18012               exp.X_add_number = 0;
18013             }
18014
18015           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18016                               BFD_RELOC_MICROMIPS_GOT16);
18017           fixp->fx_file = fragp->fr_file;
18018           fixp->fx_line = fragp->fr_line;
18019
18020           buf = write_compressed_insn (buf, insn, 4);
18021
18022           /* d/addiu $at, $at, <sym>  R_MICROMIPS_LO16  */
18023           insn = HAVE_64BIT_ADDRESSES ? 0x5c000000 : 0x30000000;
18024           insn |= at << MICROMIPSOP_SH_RT | at << MICROMIPSOP_SH_RS;
18025
18026           fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 4, &exp, FALSE,
18027                               BFD_RELOC_MICROMIPS_LO16);
18028           fixp->fx_file = fragp->fr_file;
18029           fixp->fx_line = fragp->fr_line;
18030
18031           buf = write_compressed_insn (buf, insn, 4);
18032
18033           /* jr/jrc/jalr/jalrs $at  */
18034           insn = al ? jalr : jr;
18035           insn |= at << MICROMIPSOP_SH_MJ;
18036
18037           buf = write_compressed_insn (buf, insn, 2);
18038         }
18039
18040       gas_assert (buf == fragp->fr_literal + fragp->fr_fix);
18041       return;
18042     }
18043
18044   if (RELAX_MIPS16_P (fragp->fr_subtype))
18045     {
18046       int type;
18047       const struct mips_int_operand *operand;
18048       offsetT val;
18049       char *buf;
18050       unsigned int user_length, length;
18051       bfd_boolean need_reloc;
18052       unsigned long insn;
18053       bfd_boolean ext;
18054       segT symsec;
18055
18056       type = RELAX_MIPS16_TYPE (fragp->fr_subtype);
18057       operand = mips16_immed_operand (type, FALSE);
18058
18059       ext = RELAX_MIPS16_EXTENDED (fragp->fr_subtype);
18060       val = resolve_symbol_value (fragp->fr_symbol) + fragp->fr_offset;
18061
18062       symsec = S_GET_SEGMENT (fragp->fr_symbol);
18063       need_reloc = (S_FORCE_RELOC (fragp->fr_symbol, TRUE)
18064                     || (operand->root.type == OP_PCREL
18065                         ? asec != symsec
18066                         : !bfd_is_abs_section (symsec)));
18067
18068       if (operand->root.type == OP_PCREL)
18069         {
18070           const struct mips_pcrel_operand *pcrel_op;
18071           addressT addr;
18072
18073           pcrel_op = (const struct mips_pcrel_operand *) operand;
18074           addr = fragp->fr_address + fragp->fr_fix;
18075
18076           /* The rules for the base address of a PC relative reloc are
18077              complicated; see mips16_extended_frag.  */
18078           if (pcrel_op->include_isa_bit)
18079             {
18080               if (!need_reloc)
18081                 {
18082                   if (!ELF_ST_IS_MIPS16 (S_GET_OTHER (fragp->fr_symbol)))
18083                     as_bad_where (fragp->fr_file, fragp->fr_line,
18084                                   _("branch to a symbol in another ISA mode"));
18085                   else if ((fragp->fr_offset & 0x1) != 0)
18086                     as_bad_where (fragp->fr_file, fragp->fr_line,
18087                                   _("branch to misaligned address (0x%lx)"),
18088                                   (long) val);
18089                 }
18090               addr += 2;
18091               if (ext)
18092                 addr += 2;
18093               /* Ignore the low bit in the target, since it will be
18094                  set for a text label.  */
18095               val &= -2;
18096             }
18097           else if (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype))
18098             addr -= 4;
18099           else if (RELAX_MIPS16_DSLOT (fragp->fr_subtype))
18100             addr -= 2;
18101
18102           addr &= -(1 << pcrel_op->align_log2);
18103           val -= addr;
18104
18105           /* Make sure the section winds up with the alignment we have
18106              assumed.  */
18107           if (operand->shift > 0)
18108             record_alignment (asec, operand->shift);
18109         }
18110
18111       if (ext
18112           && (RELAX_MIPS16_JAL_DSLOT (fragp->fr_subtype)
18113               || RELAX_MIPS16_DSLOT (fragp->fr_subtype)))
18114         as_warn_where (fragp->fr_file, fragp->fr_line,
18115                        _("extended instruction in delay slot"));
18116
18117       buf = fragp->fr_literal + fragp->fr_fix;
18118
18119       insn = read_compressed_insn (buf, 2);
18120       if (ext)
18121         insn |= MIPS16_EXTEND;
18122
18123       if (RELAX_MIPS16_USER_EXT (fragp->fr_subtype))
18124         user_length = 4;
18125       else if (RELAX_MIPS16_USER_SMALL (fragp->fr_subtype))
18126         user_length = 2;
18127       else
18128         user_length = 0;
18129
18130       if (need_reloc)
18131         {
18132           bfd_reloc_code_real_type reloc = BFD_RELOC_NONE;
18133           expressionS exp;
18134           fixS *fixp;
18135
18136           switch (type)
18137             {
18138             case 'p':
18139             case 'q':
18140               reloc = BFD_RELOC_MIPS16_16_PCREL_S1;
18141               break;
18142             default:
18143               as_bad_where (fragp->fr_file, fragp->fr_line,
18144                             _("unsupported relocation"));
18145               break;
18146             }
18147           if (reloc != BFD_RELOC_NONE)
18148             {
18149               gas_assert (ext);
18150
18151               exp.X_op = O_symbol;
18152               exp.X_add_symbol = fragp->fr_symbol;
18153               exp.X_add_number = fragp->fr_offset;
18154
18155               fixp = fix_new_exp (fragp, buf - fragp->fr_literal, 2, &exp,
18156                                   TRUE, reloc);
18157
18158               fixp->fx_file = fragp->fr_file;
18159               fixp->fx_line = fragp->fr_line;
18160
18161               /* These relocations can have an addend that won't fit
18162                  in 2 octets.  */
18163               fixp->fx_no_overflow = 1;
18164             }
18165         }
18166       else
18167         mips16_immed (fragp->fr_file, fragp->fr_line, type,
18168                       BFD_RELOC_UNUSED, val, user_length, &insn);
18169
18170       length = (ext ? 4 : 2);
18171       gas_assert (mips16_opcode_length (insn) == length);
18172       write_compressed_insn (buf, insn, length);
18173       fragp->fr_fix += length;
18174     }
18175   else
18176     {
18177       relax_substateT subtype = fragp->fr_subtype;
18178       bfd_boolean second_longer = (subtype & RELAX_SECOND_LONGER) != 0;
18179       bfd_boolean use_second = (subtype & RELAX_USE_SECOND) != 0;
18180       int first, second;
18181       fixS *fixp;
18182
18183       first = RELAX_FIRST (subtype);
18184       second = RELAX_SECOND (subtype);
18185       fixp = (fixS *) fragp->fr_opcode;
18186
18187       /* If the delay slot chosen does not match the size of the instruction,
18188          then emit a warning.  */
18189       if ((!use_second && (subtype & RELAX_DELAY_SLOT_SIZE_FIRST) != 0)
18190            || (use_second && (subtype & RELAX_DELAY_SLOT_SIZE_SECOND) != 0))
18191         {
18192           relax_substateT s;
18193           const char *msg;
18194
18195           s = subtype & (RELAX_DELAY_SLOT_16BIT
18196                          | RELAX_DELAY_SLOT_SIZE_FIRST
18197                          | RELAX_DELAY_SLOT_SIZE_SECOND);
18198           msg = macro_warning (s);
18199           if (msg != NULL)
18200             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18201           subtype &= ~s;
18202         }
18203
18204       /* Possibly emit a warning if we've chosen the longer option.  */
18205       if (use_second == second_longer)
18206         {
18207           relax_substateT s;
18208           const char *msg;
18209
18210           s = (subtype
18211                & (RELAX_SECOND_LONGER | RELAX_NOMACRO | RELAX_DELAY_SLOT));
18212           msg = macro_warning (s);
18213           if (msg != NULL)
18214             as_warn_where (fragp->fr_file, fragp->fr_line, "%s", msg);
18215           subtype &= ~s;
18216         }
18217
18218       /* Go through all the fixups for the first sequence.  Disable them
18219          (by marking them as done) if we're going to use the second
18220          sequence instead.  */
18221       while (fixp
18222              && fixp->fx_frag == fragp
18223              && fixp->fx_where < fragp->fr_fix - second)
18224         {
18225           if (subtype & RELAX_USE_SECOND)
18226             fixp->fx_done = 1;
18227           fixp = fixp->fx_next;
18228         }
18229
18230       /* Go through the fixups for the second sequence.  Disable them if
18231          we're going to use the first sequence, otherwise adjust their
18232          addresses to account for the relaxation.  */
18233       while (fixp && fixp->fx_frag == fragp)
18234         {
18235           if (subtype & RELAX_USE_SECOND)
18236             fixp->fx_where -= first;
18237           else
18238             fixp->fx_done = 1;
18239           fixp = fixp->fx_next;
18240         }
18241
18242       /* Now modify the frag contents.  */
18243       if (subtype & RELAX_USE_SECOND)
18244         {
18245           char *start;
18246
18247           start = fragp->fr_literal + fragp->fr_fix - first - second;
18248           memmove (start, start + first, second);
18249           fragp->fr_fix -= first;
18250         }
18251       else
18252         fragp->fr_fix -= second;
18253     }
18254 }
18255
18256 /* This function is called after the relocs have been generated.
18257    We've been storing mips16 text labels as odd.  Here we convert them
18258    back to even for the convenience of the debugger.  */
18259
18260 void
18261 mips_frob_file_after_relocs (void)
18262 {
18263   asymbol **syms;
18264   unsigned int count, i;
18265
18266   syms = bfd_get_outsymbols (stdoutput);
18267   count = bfd_get_symcount (stdoutput);
18268   for (i = 0; i < count; i++, syms++)
18269     if (ELF_ST_IS_COMPRESSED (elf_symbol (*syms)->internal_elf_sym.st_other)
18270         && ((*syms)->value & 1) != 0)
18271       {
18272         (*syms)->value &= ~1;
18273         /* If the symbol has an odd size, it was probably computed
18274            incorrectly, so adjust that as well.  */
18275         if ((elf_symbol (*syms)->internal_elf_sym.st_size & 1) != 0)
18276           ++elf_symbol (*syms)->internal_elf_sym.st_size;
18277       }
18278 }
18279
18280 /* This function is called whenever a label is defined, including fake
18281    labels instantiated off the dot special symbol.  It is used when
18282    handling branch delays; if a branch has a label, we assume we cannot
18283    move it.  This also bumps the value of the symbol by 1 in compressed
18284    code.  */
18285
18286 static void
18287 mips_record_label (symbolS *sym)
18288 {
18289   segment_info_type *si = seg_info (now_seg);
18290   struct insn_label_list *l;
18291
18292   if (free_insn_labels == NULL)
18293     l = XNEW (struct insn_label_list);
18294   else
18295     {
18296       l = free_insn_labels;
18297       free_insn_labels = l->next;
18298     }
18299
18300   l->label = sym;
18301   l->next = si->label_list;
18302   si->label_list = l;
18303 }
18304
18305 /* This function is called as tc_frob_label() whenever a label is defined
18306    and adds a DWARF-2 record we only want for true labels.  */
18307
18308 void
18309 mips_define_label (symbolS *sym)
18310 {
18311   mips_record_label (sym);
18312   dwarf2_emit_label (sym);
18313 }
18314
18315 /* This function is called by tc_new_dot_label whenever a new dot symbol
18316    is defined.  */
18317
18318 void
18319 mips_add_dot_label (symbolS *sym)
18320 {
18321   mips_record_label (sym);
18322   if (mips_assembling_insn && HAVE_CODE_COMPRESSION)
18323     mips_compressed_mark_label (sym);
18324 }
18325 \f
18326 /* Converting ASE flags from internal to .MIPS.abiflags values.  */
18327 static unsigned int
18328 mips_convert_ase_flags (int ase)
18329 {
18330   unsigned int ext_ases = 0;
18331
18332   if (ase & ASE_DSP)
18333     ext_ases |= AFL_ASE_DSP;
18334   if (ase & ASE_DSPR2)
18335     ext_ases |= AFL_ASE_DSPR2;
18336   if (ase & ASE_DSPR3)
18337     ext_ases |= AFL_ASE_DSPR3;
18338   if (ase & ASE_EVA)
18339     ext_ases |= AFL_ASE_EVA;
18340   if (ase & ASE_MCU)
18341     ext_ases |= AFL_ASE_MCU;
18342   if (ase & ASE_MDMX)
18343     ext_ases |= AFL_ASE_MDMX;
18344   if (ase & ASE_MIPS3D)
18345     ext_ases |= AFL_ASE_MIPS3D;
18346   if (ase & ASE_MT)
18347     ext_ases |= AFL_ASE_MT;
18348   if (ase & ASE_SMARTMIPS)
18349     ext_ases |= AFL_ASE_SMARTMIPS;
18350   if (ase & ASE_VIRT)
18351     ext_ases |= AFL_ASE_VIRT;
18352   if (ase & ASE_MSA)
18353     ext_ases |= AFL_ASE_MSA;
18354   if (ase & ASE_XPA)
18355     ext_ases |= AFL_ASE_XPA;
18356
18357   return ext_ases;
18358 }
18359 /* Some special processing for a MIPS ELF file.  */
18360
18361 void
18362 mips_elf_final_processing (void)
18363 {
18364   int fpabi;
18365   Elf_Internal_ABIFlags_v0 flags;
18366
18367   flags.version = 0;
18368   flags.isa_rev = 0;
18369   switch (file_mips_opts.isa)
18370     {
18371     case INSN_ISA1:
18372       flags.isa_level = 1;
18373       break;
18374     case INSN_ISA2:
18375       flags.isa_level = 2;
18376       break;
18377     case INSN_ISA3:
18378       flags.isa_level = 3;
18379       break;
18380     case INSN_ISA4:
18381       flags.isa_level = 4;
18382       break;
18383     case INSN_ISA5:
18384       flags.isa_level = 5;
18385       break;
18386     case INSN_ISA32:
18387       flags.isa_level = 32;
18388       flags.isa_rev = 1;
18389       break;
18390     case INSN_ISA32R2:
18391       flags.isa_level = 32;
18392       flags.isa_rev = 2;
18393       break;
18394     case INSN_ISA32R3:
18395       flags.isa_level = 32;
18396       flags.isa_rev = 3;
18397       break;
18398     case INSN_ISA32R5:
18399       flags.isa_level = 32;
18400       flags.isa_rev = 5;
18401       break;
18402     case INSN_ISA32R6:
18403       flags.isa_level = 32;
18404       flags.isa_rev = 6;
18405       break;
18406     case INSN_ISA64:
18407       flags.isa_level = 64;
18408       flags.isa_rev = 1;
18409       break;
18410     case INSN_ISA64R2:
18411       flags.isa_level = 64;
18412       flags.isa_rev = 2;
18413       break;
18414     case INSN_ISA64R3:
18415       flags.isa_level = 64;
18416       flags.isa_rev = 3;
18417       break;
18418     case INSN_ISA64R5:
18419       flags.isa_level = 64;
18420       flags.isa_rev = 5;
18421       break;
18422     case INSN_ISA64R6:
18423       flags.isa_level = 64;
18424       flags.isa_rev = 6;
18425       break;
18426     }
18427
18428   flags.gpr_size = file_mips_opts.gp == 32 ? AFL_REG_32 : AFL_REG_64;
18429   flags.cpr1_size = file_mips_opts.soft_float ? AFL_REG_NONE
18430                     : (file_mips_opts.ase & ASE_MSA) ? AFL_REG_128
18431                     : (file_mips_opts.fp == 64) ? AFL_REG_64
18432                     : AFL_REG_32;
18433   flags.cpr2_size = AFL_REG_NONE;
18434   flags.fp_abi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18435                                            Tag_GNU_MIPS_ABI_FP);
18436   flags.isa_ext = bfd_mips_isa_ext (stdoutput);
18437   flags.ases = mips_convert_ase_flags (file_mips_opts.ase);
18438   if (file_ase_mips16)
18439     flags.ases |= AFL_ASE_MIPS16;
18440   if (file_ase_micromips)
18441     flags.ases |= AFL_ASE_MICROMIPS;
18442   flags.flags1 = 0;
18443   if ((ISA_HAS_ODD_SINGLE_FPR (file_mips_opts.isa, file_mips_opts.arch)
18444        || file_mips_opts.fp == 64)
18445       && file_mips_opts.oddspreg)
18446     flags.flags1 |= AFL_FLAGS1_ODDSPREG;
18447   flags.flags2 = 0;
18448
18449   bfd_mips_elf_swap_abiflags_v0_out (stdoutput, &flags,
18450                                      ((Elf_External_ABIFlags_v0 *)
18451                                      mips_flags_frag));
18452
18453   /* Write out the register information.  */
18454   if (mips_abi != N64_ABI)
18455     {
18456       Elf32_RegInfo s;
18457
18458       s.ri_gprmask = mips_gprmask;
18459       s.ri_cprmask[0] = mips_cprmask[0];
18460       s.ri_cprmask[1] = mips_cprmask[1];
18461       s.ri_cprmask[2] = mips_cprmask[2];
18462       s.ri_cprmask[3] = mips_cprmask[3];
18463       /* The gp_value field is set by the MIPS ELF backend.  */
18464
18465       bfd_mips_elf32_swap_reginfo_out (stdoutput, &s,
18466                                        ((Elf32_External_RegInfo *)
18467                                         mips_regmask_frag));
18468     }
18469   else
18470     {
18471       Elf64_Internal_RegInfo s;
18472
18473       s.ri_gprmask = mips_gprmask;
18474       s.ri_pad = 0;
18475       s.ri_cprmask[0] = mips_cprmask[0];
18476       s.ri_cprmask[1] = mips_cprmask[1];
18477       s.ri_cprmask[2] = mips_cprmask[2];
18478       s.ri_cprmask[3] = mips_cprmask[3];
18479       /* The gp_value field is set by the MIPS ELF backend.  */
18480
18481       bfd_mips_elf64_swap_reginfo_out (stdoutput, &s,
18482                                        ((Elf64_External_RegInfo *)
18483                                         mips_regmask_frag));
18484     }
18485
18486   /* Set the MIPS ELF flag bits.  FIXME: There should probably be some
18487      sort of BFD interface for this.  */
18488   if (mips_any_noreorder)
18489     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NOREORDER;
18490   if (mips_pic != NO_PIC)
18491     {
18492       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_PIC;
18493       elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18494     }
18495   if (mips_abicalls)
18496     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_CPIC;
18497
18498   /* Set MIPS ELF flags for ASEs.  Note that not all ASEs have flags
18499      defined at present; this might need to change in future.  */
18500   if (file_ase_mips16)
18501     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_M16;
18502   if (file_ase_micromips)
18503     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MICROMIPS;
18504   if (file_mips_opts.ase & ASE_MDMX)
18505     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ARCH_ASE_MDMX;
18506
18507   /* Set the MIPS ELF ABI flags.  */
18508   if (mips_abi == O32_ABI && USE_E_MIPS_ABI_O32)
18509     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O32;
18510   else if (mips_abi == O64_ABI)
18511     elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_O64;
18512   else if (mips_abi == EABI_ABI)
18513     {
18514       if (file_mips_opts.gp == 64)
18515         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI64;
18516       else
18517         elf_elfheader (stdoutput)->e_flags |= E_MIPS_ABI_EABI32;
18518     }
18519   else if (mips_abi == N32_ABI)
18520     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_ABI2;
18521
18522   /* Nothing to do for N64_ABI.  */
18523
18524   if (mips_32bitmode)
18525     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_32BITMODE;
18526
18527   if (mips_nan2008 == 1)
18528     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_NAN2008;
18529
18530   /* 32 bit code with 64 bit FP registers.  */
18531   fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
18532                                     Tag_GNU_MIPS_ABI_FP);
18533   if (fpabi == Val_GNU_MIPS_ABI_FP_OLD_64)
18534     elf_elfheader (stdoutput)->e_flags |= EF_MIPS_FP64;
18535 }
18536 \f
18537 typedef struct proc {
18538   symbolS *func_sym;
18539   symbolS *func_end_sym;
18540   unsigned long reg_mask;
18541   unsigned long reg_offset;
18542   unsigned long fpreg_mask;
18543   unsigned long fpreg_offset;
18544   unsigned long frame_offset;
18545   unsigned long frame_reg;
18546   unsigned long pc_reg;
18547 } procS;
18548
18549 static procS cur_proc;
18550 static procS *cur_proc_ptr;
18551 static int numprocs;
18552
18553 /* Implement NOP_OPCODE.  We encode a MIPS16 nop as "1", a microMIPS nop
18554    as "2", and a normal nop as "0".  */
18555
18556 #define NOP_OPCODE_MIPS         0
18557 #define NOP_OPCODE_MIPS16       1
18558 #define NOP_OPCODE_MICROMIPS    2
18559
18560 char
18561 mips_nop_opcode (void)
18562 {
18563   if (seg_info (now_seg)->tc_segment_info_data.micromips)
18564     return NOP_OPCODE_MICROMIPS;
18565   else if (seg_info (now_seg)->tc_segment_info_data.mips16)
18566     return NOP_OPCODE_MIPS16;
18567   else
18568     return NOP_OPCODE_MIPS;
18569 }
18570
18571 /* Fill in an rs_align_code fragment.  Unlike elsewhere we want to use
18572    32-bit microMIPS NOPs here (if applicable).  */
18573
18574 void
18575 mips_handle_align (fragS *fragp)
18576 {
18577   char nop_opcode;
18578   char *p;
18579   int bytes, size, excess;
18580   valueT opcode;
18581
18582   if (fragp->fr_type != rs_align_code)
18583     return;
18584
18585   p = fragp->fr_literal + fragp->fr_fix;
18586   nop_opcode = *p;
18587   switch (nop_opcode)
18588     {
18589     case NOP_OPCODE_MICROMIPS:
18590       opcode = micromips_nop32_insn.insn_opcode;
18591       size = 4;
18592       break;
18593     case NOP_OPCODE_MIPS16:
18594       opcode = mips16_nop_insn.insn_opcode;
18595       size = 2;
18596       break;
18597     case NOP_OPCODE_MIPS:
18598     default:
18599       opcode = nop_insn.insn_opcode;
18600       size = 4;
18601       break;
18602     }
18603
18604   bytes = fragp->fr_next->fr_address - fragp->fr_address - fragp->fr_fix;
18605   excess = bytes % size;
18606
18607   /* Handle the leading part if we're not inserting a whole number of
18608      instructions, and make it the end of the fixed part of the frag.
18609      Try to fit in a short microMIPS NOP if applicable and possible,
18610      and use zeroes otherwise.  */
18611   gas_assert (excess < 4);
18612   fragp->fr_fix += excess;
18613   switch (excess)
18614     {
18615     case 3:
18616       *p++ = '\0';
18617       /* Fall through.  */
18618     case 2:
18619       if (nop_opcode == NOP_OPCODE_MICROMIPS && !mips_opts.insn32)
18620         {
18621           p = write_compressed_insn (p, micromips_nop16_insn.insn_opcode, 2);
18622           break;
18623         }
18624       *p++ = '\0';
18625       /* Fall through.  */
18626     case 1:
18627       *p++ = '\0';
18628       /* Fall through.  */
18629     case 0:
18630       break;
18631     }
18632
18633   md_number_to_chars (p, opcode, size);
18634   fragp->fr_var = size;
18635 }
18636
18637 static long
18638 get_number (void)
18639 {
18640   int negative = 0;
18641   long val = 0;
18642
18643   if (*input_line_pointer == '-')
18644     {
18645       ++input_line_pointer;
18646       negative = 1;
18647     }
18648   if (!ISDIGIT (*input_line_pointer))
18649     as_bad (_("expected simple number"));
18650   if (input_line_pointer[0] == '0')
18651     {
18652       if (input_line_pointer[1] == 'x')
18653         {
18654           input_line_pointer += 2;
18655           while (ISXDIGIT (*input_line_pointer))
18656             {
18657               val <<= 4;
18658               val |= hex_value (*input_line_pointer++);
18659             }
18660           return negative ? -val : val;
18661         }
18662       else
18663         {
18664           ++input_line_pointer;
18665           while (ISDIGIT (*input_line_pointer))
18666             {
18667               val <<= 3;
18668               val |= *input_line_pointer++ - '0';
18669             }
18670           return negative ? -val : val;
18671         }
18672     }
18673   if (!ISDIGIT (*input_line_pointer))
18674     {
18675       printf (_(" *input_line_pointer == '%c' 0x%02x\n"),
18676               *input_line_pointer, *input_line_pointer);
18677       as_warn (_("invalid number"));
18678       return -1;
18679     }
18680   while (ISDIGIT (*input_line_pointer))
18681     {
18682       val *= 10;
18683       val += *input_line_pointer++ - '0';
18684     }
18685   return negative ? -val : val;
18686 }
18687
18688 /* The .file directive; just like the usual .file directive, but there
18689    is an initial number which is the ECOFF file index.  In the non-ECOFF
18690    case .file implies DWARF-2.  */
18691
18692 static void
18693 s_mips_file (int x ATTRIBUTE_UNUSED)
18694 {
18695   static int first_file_directive = 0;
18696
18697   if (ECOFF_DEBUGGING)
18698     {
18699       get_number ();
18700       s_app_file (0);
18701     }
18702   else
18703     {
18704       char *filename;
18705
18706       filename = dwarf2_directive_file (0);
18707
18708       /* Versions of GCC up to 3.1 start files with a ".file"
18709          directive even for stabs output.  Make sure that this
18710          ".file" is handled.  Note that you need a version of GCC
18711          after 3.1 in order to support DWARF-2 on MIPS.  */
18712       if (filename != NULL && ! first_file_directive)
18713         {
18714           (void) new_logical_line (filename, -1);
18715           s_app_file_string (filename, 0);
18716         }
18717       first_file_directive = 1;
18718     }
18719 }
18720
18721 /* The .loc directive, implying DWARF-2.  */
18722
18723 static void
18724 s_mips_loc (int x ATTRIBUTE_UNUSED)
18725 {
18726   if (!ECOFF_DEBUGGING)
18727     dwarf2_directive_loc (0);
18728 }
18729
18730 /* The .end directive.  */
18731
18732 static void
18733 s_mips_end (int x ATTRIBUTE_UNUSED)
18734 {
18735   symbolS *p;
18736
18737   /* Following functions need their own .frame and .cprestore directives.  */
18738   mips_frame_reg_valid = 0;
18739   mips_cprestore_valid = 0;
18740
18741   if (!is_end_of_line[(unsigned char) *input_line_pointer])
18742     {
18743       p = get_symbol ();
18744       demand_empty_rest_of_line ();
18745     }
18746   else
18747     p = NULL;
18748
18749   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18750     as_warn (_(".end not in text section"));
18751
18752   if (!cur_proc_ptr)
18753     {
18754       as_warn (_(".end directive without a preceding .ent directive"));
18755       demand_empty_rest_of_line ();
18756       return;
18757     }
18758
18759   if (p != NULL)
18760     {
18761       gas_assert (S_GET_NAME (p));
18762       if (strcmp (S_GET_NAME (p), S_GET_NAME (cur_proc_ptr->func_sym)))
18763         as_warn (_(".end symbol does not match .ent symbol"));
18764
18765       if (debug_type == DEBUG_STABS)
18766         stabs_generate_asm_endfunc (S_GET_NAME (p),
18767                                     S_GET_NAME (p));
18768     }
18769   else
18770     as_warn (_(".end directive missing or unknown symbol"));
18771
18772   /* Create an expression to calculate the size of the function.  */
18773   if (p && cur_proc_ptr)
18774     {
18775       OBJ_SYMFIELD_TYPE *obj = symbol_get_obj (p);
18776       expressionS *exp = XNEW (expressionS);
18777
18778       obj->size = exp;
18779       exp->X_op = O_subtract;
18780       exp->X_add_symbol = symbol_temp_new_now ();
18781       exp->X_op_symbol = p;
18782       exp->X_add_number = 0;
18783
18784       cur_proc_ptr->func_end_sym = exp->X_add_symbol;
18785     }
18786
18787   /* Generate a .pdr section.  */
18788   if (!ECOFF_DEBUGGING && mips_flag_pdr)
18789     {
18790       segT saved_seg = now_seg;
18791       subsegT saved_subseg = now_subseg;
18792       expressionS exp;
18793       char *fragp;
18794
18795 #ifdef md_flush_pending_output
18796       md_flush_pending_output ();
18797 #endif
18798
18799       gas_assert (pdr_seg);
18800       subseg_set (pdr_seg, 0);
18801
18802       /* Write the symbol.  */
18803       exp.X_op = O_symbol;
18804       exp.X_add_symbol = p;
18805       exp.X_add_number = 0;
18806       emit_expr (&exp, 4);
18807
18808       fragp = frag_more (7 * 4);
18809
18810       md_number_to_chars (fragp, cur_proc_ptr->reg_mask, 4);
18811       md_number_to_chars (fragp + 4, cur_proc_ptr->reg_offset, 4);
18812       md_number_to_chars (fragp + 8, cur_proc_ptr->fpreg_mask, 4);
18813       md_number_to_chars (fragp + 12, cur_proc_ptr->fpreg_offset, 4);
18814       md_number_to_chars (fragp + 16, cur_proc_ptr->frame_offset, 4);
18815       md_number_to_chars (fragp + 20, cur_proc_ptr->frame_reg, 4);
18816       md_number_to_chars (fragp + 24, cur_proc_ptr->pc_reg, 4);
18817
18818       subseg_set (saved_seg, saved_subseg);
18819     }
18820
18821   cur_proc_ptr = NULL;
18822 }
18823
18824 /* The .aent and .ent directives.  */
18825
18826 static void
18827 s_mips_ent (int aent)
18828 {
18829   symbolS *symbolP;
18830
18831   symbolP = get_symbol ();
18832   if (*input_line_pointer == ',')
18833     ++input_line_pointer;
18834   SKIP_WHITESPACE ();
18835   if (ISDIGIT (*input_line_pointer)
18836       || *input_line_pointer == '-')
18837     get_number ();
18838
18839   if ((bfd_get_section_flags (stdoutput, now_seg) & SEC_CODE) == 0)
18840     as_warn (_(".ent or .aent not in text section"));
18841
18842   if (!aent && cur_proc_ptr)
18843     as_warn (_("missing .end"));
18844
18845   if (!aent)
18846     {
18847       /* This function needs its own .frame and .cprestore directives.  */
18848       mips_frame_reg_valid = 0;
18849       mips_cprestore_valid = 0;
18850
18851       cur_proc_ptr = &cur_proc;
18852       memset (cur_proc_ptr, '\0', sizeof (procS));
18853
18854       cur_proc_ptr->func_sym = symbolP;
18855
18856       ++numprocs;
18857
18858       if (debug_type == DEBUG_STABS)
18859         stabs_generate_asm_func (S_GET_NAME (symbolP),
18860                                  S_GET_NAME (symbolP));
18861     }
18862
18863   symbol_get_bfdsym (symbolP)->flags |= BSF_FUNCTION;
18864
18865   demand_empty_rest_of_line ();
18866 }
18867
18868 /* The .frame directive. If the mdebug section is present (IRIX 5 native)
18869    then ecoff.c (ecoff_directive_frame) is used. For embedded targets,
18870    s_mips_frame is used so that we can set the PDR information correctly.
18871    We can't use the ecoff routines because they make reference to the ecoff
18872    symbol table (in the mdebug section).  */
18873
18874 static void
18875 s_mips_frame (int ignore ATTRIBUTE_UNUSED)
18876 {
18877   if (ECOFF_DEBUGGING)
18878     s_ignore (ignore);
18879   else
18880     {
18881       long val;
18882
18883       if (cur_proc_ptr == (procS *) NULL)
18884         {
18885           as_warn (_(".frame outside of .ent"));
18886           demand_empty_rest_of_line ();
18887           return;
18888         }
18889
18890       cur_proc_ptr->frame_reg = tc_get_register (1);
18891
18892       SKIP_WHITESPACE ();
18893       if (*input_line_pointer++ != ','
18894           || get_absolute_expression_and_terminator (&val) != ',')
18895         {
18896           as_warn (_("bad .frame directive"));
18897           --input_line_pointer;
18898           demand_empty_rest_of_line ();
18899           return;
18900         }
18901
18902       cur_proc_ptr->frame_offset = val;
18903       cur_proc_ptr->pc_reg = tc_get_register (0);
18904
18905       demand_empty_rest_of_line ();
18906     }
18907 }
18908
18909 /* The .fmask and .mask directives. If the mdebug section is present
18910    (IRIX 5 native) then ecoff.c (ecoff_directive_mask) is used. For
18911    embedded targets, s_mips_mask is used so that we can set the PDR
18912    information correctly. We can't use the ecoff routines because they
18913    make reference to the ecoff symbol table (in the mdebug section).  */
18914
18915 static void
18916 s_mips_mask (int reg_type)
18917 {
18918   if (ECOFF_DEBUGGING)
18919     s_ignore (reg_type);
18920   else
18921     {
18922       long mask, off;
18923
18924       if (cur_proc_ptr == (procS *) NULL)
18925         {
18926           as_warn (_(".mask/.fmask outside of .ent"));
18927           demand_empty_rest_of_line ();
18928           return;
18929         }
18930
18931       if (get_absolute_expression_and_terminator (&mask) != ',')
18932         {
18933           as_warn (_("bad .mask/.fmask directive"));
18934           --input_line_pointer;
18935           demand_empty_rest_of_line ();
18936           return;
18937         }
18938
18939       off = get_absolute_expression ();
18940
18941       if (reg_type == 'F')
18942         {
18943           cur_proc_ptr->fpreg_mask = mask;
18944           cur_proc_ptr->fpreg_offset = off;
18945         }
18946       else
18947         {
18948           cur_proc_ptr->reg_mask = mask;
18949           cur_proc_ptr->reg_offset = off;
18950         }
18951
18952       demand_empty_rest_of_line ();
18953     }
18954 }
18955
18956 /* A table describing all the processors gas knows about.  Names are
18957    matched in the order listed.
18958
18959    To ease comparison, please keep this table in the same order as
18960    gcc's mips_cpu_info_table[].  */
18961 static const struct mips_cpu_info mips_cpu_info_table[] =
18962 {
18963   /* Entries for generic ISAs */
18964   { "mips1",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS1,    CPU_R3000 },
18965   { "mips2",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS2,    CPU_R6000 },
18966   { "mips3",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS3,    CPU_R4000 },
18967   { "mips4",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS4,    CPU_R8000 },
18968   { "mips5",          MIPS_CPU_IS_ISA, 0,       ISA_MIPS5,    CPU_MIPS5 },
18969   { "mips32",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS32,   CPU_MIPS32 },
18970   { "mips32r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R2, CPU_MIPS32R2 },
18971   { "mips32r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R3, CPU_MIPS32R3 },
18972   { "mips32r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R5, CPU_MIPS32R5 },
18973   { "mips32r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS32R6, CPU_MIPS32R6 },
18974   { "mips64",         MIPS_CPU_IS_ISA, 0,       ISA_MIPS64,   CPU_MIPS64 },
18975   { "mips64r2",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R2, CPU_MIPS64R2 },
18976   { "mips64r3",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R3, CPU_MIPS64R3 },
18977   { "mips64r5",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R5, CPU_MIPS64R5 },
18978   { "mips64r6",       MIPS_CPU_IS_ISA, 0,       ISA_MIPS64R6, CPU_MIPS64R6 },
18979
18980   /* MIPS I */
18981   { "r3000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18982   { "r2000",          0, 0,                     ISA_MIPS1,    CPU_R3000 },
18983   { "r3900",          0, 0,                     ISA_MIPS1,    CPU_R3900 },
18984
18985   /* MIPS II */
18986   { "r6000",          0, 0,                     ISA_MIPS2,    CPU_R6000 },
18987
18988   /* MIPS III */
18989   { "r4000",          0, 0,                     ISA_MIPS3,    CPU_R4000 },
18990   { "r4010",          0, 0,                     ISA_MIPS2,    CPU_R4010 },
18991   { "vr4100",         0, 0,                     ISA_MIPS3,    CPU_VR4100 },
18992   { "vr4111",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18993   { "vr4120",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18994   { "vr4130",         0, 0,                     ISA_MIPS3,    CPU_VR4120 },
18995   { "vr4181",         0, 0,                     ISA_MIPS3,    CPU_R4111 },
18996   { "vr4300",         0, 0,                     ISA_MIPS3,    CPU_R4300 },
18997   { "r4400",          0, 0,                     ISA_MIPS3,    CPU_R4400 },
18998   { "r4600",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
18999   { "orion",          0, 0,                     ISA_MIPS3,    CPU_R4600 },
19000   { "r4650",          0, 0,                     ISA_MIPS3,    CPU_R4650 },
19001   { "r5900",          0, 0,                     ISA_MIPS3,    CPU_R5900 },
19002   /* ST Microelectronics Loongson 2E and 2F cores */
19003   { "loongson2e",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2E },
19004   { "loongson2f",     0, 0,                     ISA_MIPS3,    CPU_LOONGSON_2F },
19005
19006   /* MIPS IV */
19007   { "r8000",          0, 0,                     ISA_MIPS4,    CPU_R8000 },
19008   { "r10000",         0, 0,                     ISA_MIPS4,    CPU_R10000 },
19009   { "r12000",         0, 0,                     ISA_MIPS4,    CPU_R12000 },
19010   { "r14000",         0, 0,                     ISA_MIPS4,    CPU_R14000 },
19011   { "r16000",         0, 0,                     ISA_MIPS4,    CPU_R16000 },
19012   { "vr5000",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19013   { "vr5400",         0, 0,                     ISA_MIPS4,    CPU_VR5400 },
19014   { "vr5500",         0, 0,                     ISA_MIPS4,    CPU_VR5500 },
19015   { "rm5200",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19016   { "rm5230",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19017   { "rm5231",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19018   { "rm5261",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19019   { "rm5721",         0, 0,                     ISA_MIPS4,    CPU_R5000 },
19020   { "rm7000",         0, 0,                     ISA_MIPS4,    CPU_RM7000 },
19021   { "rm9000",         0, 0,                     ISA_MIPS4,    CPU_RM9000 },
19022
19023   /* MIPS 32 */
19024   { "4kc",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19025   { "4km",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19026   { "4kp",            0, 0,                     ISA_MIPS32,   CPU_MIPS32 },
19027   { "4ksc",           0, ASE_SMARTMIPS,         ISA_MIPS32,   CPU_MIPS32 },
19028
19029   /* MIPS 32 Release 2 */
19030   { "4kec",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19031   { "4kem",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19032   { "4kep",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19033   { "4ksd",           0, ASE_SMARTMIPS,         ISA_MIPS32R2, CPU_MIPS32R2 },
19034   { "m4k",            0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19035   { "m4kp",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19036   { "m14k",           0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19037   { "m14kc",          0, ASE_MCU,               ISA_MIPS32R2, CPU_MIPS32R2 },
19038   { "m14ke",          0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19039                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19040   { "m14kec",         0, ASE_DSP | ASE_DSPR2 | ASE_MCU,
19041                                                 ISA_MIPS32R2, CPU_MIPS32R2 },
19042   { "24kc",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19043   { "24kf2_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19044   { "24kf",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19045   { "24kf1_1",        0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19046   /* Deprecated forms of the above.  */
19047   { "24kfx",          0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19048   { "24kx",           0, 0,                     ISA_MIPS32R2, CPU_MIPS32R2 },
19049   /* 24KE is a 24K with DSP ASE, other ASEs are optional.  */
19050   { "24kec",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19051   { "24kef2_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19052   { "24kef",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19053   { "24kef1_1",       0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19054   /* Deprecated forms of the above.  */
19055   { "24kefx",         0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19056   { "24kex",          0, ASE_DSP,               ISA_MIPS32R2, CPU_MIPS32R2 },
19057   /* 34K is a 24K with DSP and MT ASE, other ASEs are optional.  */
19058   { "34kc",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19059   { "34kf2_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19060   { "34kf",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19061   { "34kf1_1",        0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19062   /* Deprecated forms of the above.  */
19063   { "34kfx",          0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19064   { "34kx",           0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19065   /* 34Kn is a 34kc without DSP.  */
19066   { "34kn",           0, ASE_MT,                ISA_MIPS32R2, CPU_MIPS32R2 },
19067   /* 74K with DSP and DSPR2 ASE, other ASEs are optional.  */
19068   { "74kc",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19069   { "74kf2_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19070   { "74kf",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19071   { "74kf1_1",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19072   { "74kf3_2",        0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19073   /* Deprecated forms of the above.  */
19074   { "74kfx",          0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19075   { "74kx",           0, ASE_DSP | ASE_DSPR2,   ISA_MIPS32R2, CPU_MIPS32R2 },
19076   /* 1004K cores are multiprocessor versions of the 34K.  */
19077   { "1004kc",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19078   { "1004kf2_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19079   { "1004kf",         0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19080   { "1004kf1_1",      0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19081   /* interaptiv is the new name for 1004kf */
19082   { "interaptiv",     0, ASE_DSP | ASE_MT,      ISA_MIPS32R2, CPU_MIPS32R2 },
19083   /* M5100 family */
19084   { "m5100",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19085   { "m5101",          0, ASE_MCU,               ISA_MIPS32R5, CPU_MIPS32R5 },
19086   /* P5600 with EVA and Virtualization ASEs, other ASEs are optional.  */
19087   { "p5600",          0, ASE_VIRT | ASE_EVA | ASE_XPA,  ISA_MIPS32R5, CPU_MIPS32R5 },
19088
19089   /* MIPS 64 */
19090   { "5kc",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19091   { "5kf",            0, 0,                     ISA_MIPS64,   CPU_MIPS64 },
19092   { "20kc",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19093   { "25kf",           0, ASE_MIPS3D,            ISA_MIPS64,   CPU_MIPS64 },
19094
19095   /* Broadcom SB-1 CPU core */
19096   { "sb1",            0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19097   /* Broadcom SB-1A CPU core */
19098   { "sb1a",           0, ASE_MIPS3D | ASE_MDMX, ISA_MIPS64,   CPU_SB1 },
19099
19100   { "loongson3a",     0, 0,                     ISA_MIPS64R2, CPU_LOONGSON_3A },
19101
19102   /* MIPS 64 Release 2 */
19103
19104   /* Cavium Networks Octeon CPU core */
19105   { "octeon",         0, 0,                     ISA_MIPS64R2, CPU_OCTEON },
19106   { "octeon+",        0, 0,                     ISA_MIPS64R2, CPU_OCTEONP },
19107   { "octeon2",        0, 0,                     ISA_MIPS64R2, CPU_OCTEON2 },
19108   { "octeon3",        0, ASE_VIRT | ASE_VIRT64, ISA_MIPS64R5, CPU_OCTEON3 },
19109
19110   /* RMI Xlr */
19111   { "xlr",            0, 0,                     ISA_MIPS64,   CPU_XLR },
19112
19113   /* Broadcom XLP.
19114      XLP is mostly like XLR, with the prominent exception that it is
19115      MIPS64R2 rather than MIPS64.  */
19116   { "xlp",            0, 0,                     ISA_MIPS64R2, CPU_XLR },
19117
19118   /* MIPS 64 Release 6 */
19119   { "i6400",          0, ASE_MSA,               ISA_MIPS64R6, CPU_MIPS64R6},
19120   { "p6600",          0, ASE_VIRT | ASE_MSA,    ISA_MIPS64R6, CPU_MIPS64R6},
19121
19122   /* End marker */
19123   { NULL, 0, 0, 0, 0 }
19124 };
19125
19126
19127 /* Return true if GIVEN is the same as CANONICAL, or if it is CANONICAL
19128    with a final "000" replaced by "k".  Ignore case.
19129
19130    Note: this function is shared between GCC and GAS.  */
19131
19132 static bfd_boolean
19133 mips_strict_matching_cpu_name_p (const char *canonical, const char *given)
19134 {
19135   while (*given != 0 && TOLOWER (*given) == TOLOWER (*canonical))
19136     given++, canonical++;
19137
19138   return ((*given == 0 && *canonical == 0)
19139           || (strcmp (canonical, "000") == 0 && strcasecmp (given, "k") == 0));
19140 }
19141
19142
19143 /* Return true if GIVEN matches CANONICAL, where GIVEN is a user-supplied
19144    CPU name.  We've traditionally allowed a lot of variation here.
19145
19146    Note: this function is shared between GCC and GAS.  */
19147
19148 static bfd_boolean
19149 mips_matching_cpu_name_p (const char *canonical, const char *given)
19150 {
19151   /* First see if the name matches exactly, or with a final "000"
19152      turned into "k".  */
19153   if (mips_strict_matching_cpu_name_p (canonical, given))
19154     return TRUE;
19155
19156   /* If not, try comparing based on numerical designation alone.
19157      See if GIVEN is an unadorned number, or 'r' followed by a number.  */
19158   if (TOLOWER (*given) == 'r')
19159     given++;
19160   if (!ISDIGIT (*given))
19161     return FALSE;
19162
19163   /* Skip over some well-known prefixes in the canonical name,
19164      hoping to find a number there too.  */
19165   if (TOLOWER (canonical[0]) == 'v' && TOLOWER (canonical[1]) == 'r')
19166     canonical += 2;
19167   else if (TOLOWER (canonical[0]) == 'r' && TOLOWER (canonical[1]) == 'm')
19168     canonical += 2;
19169   else if (TOLOWER (canonical[0]) == 'r')
19170     canonical += 1;
19171
19172   return mips_strict_matching_cpu_name_p (canonical, given);
19173 }
19174
19175
19176 /* Parse an option that takes the name of a processor as its argument.
19177    OPTION is the name of the option and CPU_STRING is the argument.
19178    Return the corresponding processor enumeration if the CPU_STRING is
19179    recognized, otherwise report an error and return null.
19180
19181    A similar function exists in GCC.  */
19182
19183 static const struct mips_cpu_info *
19184 mips_parse_cpu (const char *option, const char *cpu_string)
19185 {
19186   const struct mips_cpu_info *p;
19187
19188   /* 'from-abi' selects the most compatible architecture for the given
19189      ABI: MIPS I for 32-bit ABIs and MIPS III for 64-bit ABIs.  For the
19190      EABIs, we have to decide whether we're using the 32-bit or 64-bit
19191      version.  Look first at the -mgp options, if given, otherwise base
19192      the choice on MIPS_DEFAULT_64BIT.
19193
19194      Treat NO_ABI like the EABIs.  One reason to do this is that the
19195      plain 'mips' and 'mips64' configs have 'from-abi' as their default
19196      architecture.  This code picks MIPS I for 'mips' and MIPS III for
19197      'mips64', just as we did in the days before 'from-abi'.  */
19198   if (strcasecmp (cpu_string, "from-abi") == 0)
19199     {
19200       if (ABI_NEEDS_32BIT_REGS (mips_abi))
19201         return mips_cpu_info_from_isa (ISA_MIPS1);
19202
19203       if (ABI_NEEDS_64BIT_REGS (mips_abi))
19204         return mips_cpu_info_from_isa (ISA_MIPS3);
19205
19206       if (file_mips_opts.gp >= 0)
19207         return mips_cpu_info_from_isa (file_mips_opts.gp == 32
19208                                        ? ISA_MIPS1 : ISA_MIPS3);
19209
19210       return mips_cpu_info_from_isa (MIPS_DEFAULT_64BIT
19211                                      ? ISA_MIPS3
19212                                      : ISA_MIPS1);
19213     }
19214
19215   /* 'default' has traditionally been a no-op.  Probably not very useful.  */
19216   if (strcasecmp (cpu_string, "default") == 0)
19217     return 0;
19218
19219   for (p = mips_cpu_info_table; p->name != 0; p++)
19220     if (mips_matching_cpu_name_p (p->name, cpu_string))
19221       return p;
19222
19223   as_bad (_("bad value (%s) for %s"), cpu_string, option);
19224   return 0;
19225 }
19226
19227 /* Return the canonical processor information for ISA (a member of the
19228    ISA_MIPS* enumeration).  */
19229
19230 static const struct mips_cpu_info *
19231 mips_cpu_info_from_isa (int isa)
19232 {
19233   int i;
19234
19235   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19236     if ((mips_cpu_info_table[i].flags & MIPS_CPU_IS_ISA)
19237         && isa == mips_cpu_info_table[i].isa)
19238       return (&mips_cpu_info_table[i]);
19239
19240   return NULL;
19241 }
19242
19243 static const struct mips_cpu_info *
19244 mips_cpu_info_from_arch (int arch)
19245 {
19246   int i;
19247
19248   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19249     if (arch == mips_cpu_info_table[i].cpu)
19250       return (&mips_cpu_info_table[i]);
19251
19252   return NULL;
19253 }
19254 \f
19255 static void
19256 show (FILE *stream, const char *string, int *col_p, int *first_p)
19257 {
19258   if (*first_p)
19259     {
19260       fprintf (stream, "%24s", "");
19261       *col_p = 24;
19262     }
19263   else
19264     {
19265       fprintf (stream, ", ");
19266       *col_p += 2;
19267     }
19268
19269   if (*col_p + strlen (string) > 72)
19270     {
19271       fprintf (stream, "\n%24s", "");
19272       *col_p = 24;
19273     }
19274
19275   fprintf (stream, "%s", string);
19276   *col_p += strlen (string);
19277
19278   *first_p = 0;
19279 }
19280
19281 void
19282 md_show_usage (FILE *stream)
19283 {
19284   int column, first;
19285   size_t i;
19286
19287   fprintf (stream, _("\
19288 MIPS options:\n\
19289 -EB                     generate big endian output\n\
19290 -EL                     generate little endian output\n\
19291 -g, -g2                 do not remove unneeded NOPs or swap branches\n\
19292 -G NUM                  allow referencing objects up to NUM bytes\n\
19293                         implicitly with the gp register [default 8]\n"));
19294   fprintf (stream, _("\
19295 -mips1                  generate MIPS ISA I instructions\n\
19296 -mips2                  generate MIPS ISA II instructions\n\
19297 -mips3                  generate MIPS ISA III instructions\n\
19298 -mips4                  generate MIPS ISA IV instructions\n\
19299 -mips5                  generate MIPS ISA V instructions\n\
19300 -mips32                 generate MIPS32 ISA instructions\n\
19301 -mips32r2               generate MIPS32 release 2 ISA instructions\n\
19302 -mips32r3               generate MIPS32 release 3 ISA instructions\n\
19303 -mips32r5               generate MIPS32 release 5 ISA instructions\n\
19304 -mips32r6               generate MIPS32 release 6 ISA instructions\n\
19305 -mips64                 generate MIPS64 ISA instructions\n\
19306 -mips64r2               generate MIPS64 release 2 ISA instructions\n\
19307 -mips64r3               generate MIPS64 release 3 ISA instructions\n\
19308 -mips64r5               generate MIPS64 release 5 ISA instructions\n\
19309 -mips64r6               generate MIPS64 release 6 ISA instructions\n\
19310 -march=CPU/-mtune=CPU   generate code/schedule for CPU, where CPU is one of:\n"));
19311
19312   first = 1;
19313
19314   for (i = 0; mips_cpu_info_table[i].name != NULL; i++)
19315     show (stream, mips_cpu_info_table[i].name, &column, &first);
19316   show (stream, "from-abi", &column, &first);
19317   fputc ('\n', stream);
19318
19319   fprintf (stream, _("\
19320 -mCPU                   equivalent to -march=CPU -mtune=CPU. Deprecated.\n\
19321 -no-mCPU                don't generate code specific to CPU.\n\
19322                         For -mCPU and -no-mCPU, CPU must be one of:\n"));
19323
19324   first = 1;
19325
19326   show (stream, "3900", &column, &first);
19327   show (stream, "4010", &column, &first);
19328   show (stream, "4100", &column, &first);
19329   show (stream, "4650", &column, &first);
19330   fputc ('\n', stream);
19331
19332   fprintf (stream, _("\
19333 -mips16                 generate mips16 instructions\n\
19334 -no-mips16              do not generate mips16 instructions\n"));
19335   fprintf (stream, _("\
19336 -mmicromips             generate microMIPS instructions\n\
19337 -mno-micromips          do not generate microMIPS instructions\n"));
19338   fprintf (stream, _("\
19339 -msmartmips             generate smartmips instructions\n\
19340 -mno-smartmips          do not generate smartmips instructions\n"));
19341   fprintf (stream, _("\
19342 -mdsp                   generate DSP instructions\n\
19343 -mno-dsp                do not generate DSP instructions\n"));
19344   fprintf (stream, _("\
19345 -mdspr2                 generate DSP R2 instructions\n\
19346 -mno-dspr2              do not generate DSP R2 instructions\n"));
19347   fprintf (stream, _("\
19348 -mdspr3                 generate DSP R3 instructions\n\
19349 -mno-dspr3              do not generate DSP R3 instructions\n"));
19350   fprintf (stream, _("\
19351 -mmt                    generate MT instructions\n\
19352 -mno-mt                 do not generate MT instructions\n"));
19353   fprintf (stream, _("\
19354 -mmcu                   generate MCU instructions\n\
19355 -mno-mcu                do not generate MCU instructions\n"));
19356   fprintf (stream, _("\
19357 -mmsa                   generate MSA instructions\n\
19358 -mno-msa                do not generate MSA instructions\n"));
19359   fprintf (stream, _("\
19360 -mxpa                   generate eXtended Physical Address (XPA) instructions\n\
19361 -mno-xpa                do not generate eXtended Physical Address (XPA) instructions\n"));
19362   fprintf (stream, _("\
19363 -mvirt                  generate Virtualization instructions\n\
19364 -mno-virt               do not generate Virtualization instructions\n"));
19365   fprintf (stream, _("\
19366 -minsn32                only generate 32-bit microMIPS instructions\n\
19367 -mno-insn32             generate all microMIPS instructions\n"));
19368   fprintf (stream, _("\
19369 -mfix-loongson2f-jump   work around Loongson2F JUMP instructions\n\
19370 -mfix-loongson2f-nop    work around Loongson2F NOP errata\n\
19371 -mfix-vr4120            work around certain VR4120 errata\n\
19372 -mfix-vr4130            work around VR4130 mflo/mfhi errata\n\
19373 -mfix-24k               insert a nop after ERET and DERET instructions\n\
19374 -mfix-cn63xxp1          work around CN63XXP1 PREF errata\n\
19375 -mgp32                  use 32-bit GPRs, regardless of the chosen ISA\n\
19376 -mfp32                  use 32-bit FPRs, regardless of the chosen ISA\n\
19377 -msym32                 assume all symbols have 32-bit values\n\
19378 -O0                     remove unneeded NOPs, do not swap branches\n\
19379 -O                      remove unneeded NOPs and swap branches\n\
19380 --trap, --no-break      trap exception on div by 0 and mult overflow\n\
19381 --break, --no-trap      break exception on div by 0 and mult overflow\n"));
19382   fprintf (stream, _("\
19383 -mhard-float            allow floating-point instructions\n\
19384 -msoft-float            do not allow floating-point instructions\n\
19385 -msingle-float          only allow 32-bit floating-point operations\n\
19386 -mdouble-float          allow 32-bit and 64-bit floating-point operations\n\
19387 --[no-]construct-floats [dis]allow floating point values to be constructed\n\
19388 --[no-]relax-branch     [dis]allow out-of-range branches to be relaxed\n\
19389 -mnan=ENCODING          select an IEEE 754 NaN encoding convention, either of:\n"));
19390
19391   first = 1;
19392
19393   show (stream, "legacy", &column, &first);
19394   show (stream, "2008", &column, &first);
19395
19396   fputc ('\n', stream);
19397
19398   fprintf (stream, _("\
19399 -KPIC, -call_shared     generate SVR4 position independent code\n\
19400 -call_nonpic            generate non-PIC code that can operate with DSOs\n\
19401 -mvxworks-pic           generate VxWorks position independent code\n\
19402 -non_shared             do not generate code that can operate with DSOs\n\
19403 -xgot                   assume a 32 bit GOT\n\
19404 -mpdr, -mno-pdr         enable/disable creation of .pdr sections\n\
19405 -mshared, -mno-shared   disable/enable .cpload optimization for\n\
19406                         position dependent (non shared) code\n\
19407 -mabi=ABI               create ABI conformant object file for:\n"));
19408
19409   first = 1;
19410
19411   show (stream, "32", &column, &first);
19412   show (stream, "o64", &column, &first);
19413   show (stream, "n32", &column, &first);
19414   show (stream, "64", &column, &first);
19415   show (stream, "eabi", &column, &first);
19416
19417   fputc ('\n', stream);
19418
19419   fprintf (stream, _("\
19420 -32                     create o32 ABI object file (default)\n\
19421 -n32                    create n32 ABI object file\n\
19422 -64                     create 64 ABI object file\n"));
19423 }
19424
19425 #ifdef TE_IRIX
19426 enum dwarf2_format
19427 mips_dwarf2_format (asection *sec ATTRIBUTE_UNUSED)
19428 {
19429   if (HAVE_64BIT_SYMBOLS)
19430     return dwarf2_format_64bit_irix;
19431   else
19432     return dwarf2_format_32bit;
19433 }
19434 #endif
19435
19436 int
19437 mips_dwarf2_addr_size (void)
19438 {
19439   if (HAVE_64BIT_OBJECTS)
19440     return 8;
19441   else
19442     return 4;
19443 }
19444
19445 /* Standard calling conventions leave the CFA at SP on entry.  */
19446 void
19447 mips_cfi_frame_initial_instructions (void)
19448 {
19449   cfi_add_CFA_def_cfa_register (SP);
19450 }
19451
19452 int
19453 tc_mips_regname_to_dw2regnum (char *regname)
19454 {
19455   unsigned int regnum = -1;
19456   unsigned int reg;
19457
19458   if (reg_lookup (&regname, RTYPE_GP | RTYPE_NUM, &reg))
19459     regnum = reg;
19460
19461   return regnum;
19462 }
19463
19464 /* Implement CONVERT_SYMBOLIC_ATTRIBUTE.
19465    Given a symbolic attribute NAME, return the proper integer value.
19466    Returns -1 if the attribute is not known.  */
19467
19468 int
19469 mips_convert_symbolic_attribute (const char *name)
19470 {
19471   static const struct
19472   {
19473     const char * name;
19474     const int    tag;
19475   }
19476   attribute_table[] =
19477     {
19478 #define T(tag) {#tag, tag}
19479       T (Tag_GNU_MIPS_ABI_FP),
19480       T (Tag_GNU_MIPS_ABI_MSA),
19481 #undef T
19482     };
19483   unsigned int i;
19484
19485   if (name == NULL)
19486     return -1;
19487
19488   for (i = 0; i < ARRAY_SIZE (attribute_table); i++)
19489     if (streq (name, attribute_table[i].name))
19490       return attribute_table[i].tag;
19491
19492   return -1;
19493 }
19494
19495 void
19496 md_mips_end (void)
19497 {
19498   int fpabi = Val_GNU_MIPS_ABI_FP_ANY;
19499
19500   mips_emit_delays ();
19501   if (cur_proc_ptr)
19502     as_warn (_("missing .end at end of assembly"));
19503
19504   /* Just in case no code was emitted, do the consistency check.  */
19505   file_mips_check_options ();
19506
19507   /* Set a floating-point ABI if the user did not.  */
19508   if (obj_elf_seen_attribute (OBJ_ATTR_GNU, Tag_GNU_MIPS_ABI_FP))
19509     {
19510       /* Perform consistency checks on the floating-point ABI.  */
19511       fpabi = bfd_elf_get_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19512                                         Tag_GNU_MIPS_ABI_FP);
19513       if (fpabi != Val_GNU_MIPS_ABI_FP_ANY)
19514         check_fpabi (fpabi);
19515     }
19516   else
19517     {
19518       /* Soft-float gets precedence over single-float, the two options should
19519          not be used together so this should not matter.  */
19520       if (file_mips_opts.soft_float == 1)
19521         fpabi = Val_GNU_MIPS_ABI_FP_SOFT;
19522       /* Single-float gets precedence over all double_float cases.  */
19523       else if (file_mips_opts.single_float == 1)
19524         fpabi = Val_GNU_MIPS_ABI_FP_SINGLE;
19525       else
19526         {
19527           switch (file_mips_opts.fp)
19528             {
19529             case 32:
19530               if (file_mips_opts.gp == 32)
19531                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
19532               break;
19533             case 0:
19534               fpabi = Val_GNU_MIPS_ABI_FP_XX;
19535               break;
19536             case 64:
19537               if (file_mips_opts.gp == 32 && !file_mips_opts.oddspreg)
19538                 fpabi = Val_GNU_MIPS_ABI_FP_64A;
19539               else if (file_mips_opts.gp == 32)
19540                 fpabi = Val_GNU_MIPS_ABI_FP_64;
19541               else
19542                 fpabi = Val_GNU_MIPS_ABI_FP_DOUBLE;
19543               break;
19544             }
19545         }
19546
19547       bfd_elf_add_obj_attr_int (stdoutput, OBJ_ATTR_GNU,
19548                                 Tag_GNU_MIPS_ABI_FP, fpabi);
19549     }
19550 }
19551
19552 /*  Returns the relocation type required for a particular CFI encoding.  */
19553
19554 bfd_reloc_code_real_type
19555 mips_cfi_reloc_for_encoding (int encoding)
19556 {
19557   if (encoding == (DW_EH_PE_sdata4 | DW_EH_PE_pcrel))
19558     return BFD_RELOC_32_PCREL;
19559   else return BFD_RELOC_NONE;
19560 }